diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2e87a963..4a2dfd43 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -19,6 +19,10 @@ updates: update-types: - "minor" - "patch" + ignore: + # The typed-path source generator ships inside the builder package and must load in the oldest supported compiler + # (Roslyn 5.0, .NET 10 SDK); a newer Microsoft.CodeAnalysis.CSharp would break it for those consumers (CS9057). + - dependency-name: "Microsoft.CodeAnalysis.CSharp" - package-ecosystem: "github-actions" directory: "/" diff --git a/.github/scripts/check-builder-package.sh b/.github/scripts/check-builder-package.sh new file mode 100755 index 00000000..a37368aa --- /dev/null +++ b/.github/scripts/check-builder-package.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# The packed builder package must depend on the core version in TriasDev.Templify.csproj (a global -p:Version would +# also version the referenced core project). Usage: check-builder-package.sh +set -euo pipefail +dir=$1 +version=$2 +core=$(sed -n 's:.*\(.*\).*:\1:p' src/TriasDev.Templify/TriasDev.Templify.csproj | head -1) +nuspec=$(unzip -p "$dir/TriasDev.Templify.Builder.$version.nupkg" '*.nuspec') +echo "$nuspec" | grep -q "id=\"TriasDev.Templify\" version=\"$core\"" \ + || { echo "::error::TriasDev.Templify.Builder $version does not depend on TriasDev.Templify $core"; echo "$nuspec" | grep -i dependency; exit 1; } +testing=$(unzip -p "$dir/TriasDev.Templify.Builder.Testing.$version.nupkg" '*.nuspec') +echo "$testing" | grep -q "id=\"TriasDev.Templify.Builder\" version=\"$version\"" \ + || { echo "::error::TriasDev.Templify.Builder.Testing $version does not depend on TriasDev.Templify.Builder $version"; exit 1; } +echo "Builder $version depends on core $core; the test kit on builder $version." diff --git a/.github/scripts/check-core-released.sh b/.github/scripts/check-core-released.sh new file mode 100755 index 00000000..2f9b828b --- /dev/null +++ b/.github/scripts/check-core-released.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# The builder package depends on the core version in TriasDev.Templify.csproj. That version must be on nuget.org, and +# the core source must not have changed since its tag: otherwise the builder would rely on core features no published +# core has (release core first). Runs on the builder release PR (ci.yml) and before publishing (release-please.yml). +set -euo pipefail +core=$(sed -n 's:.*\(.*\).*:\1:p' src/TriasDev.Templify/TriasDev.Templify.csproj | head -1) +echo "Core version: $core" +if ! curl -fsS https://api.nuget.org/v3-flatcontainer/triasdev.templify/index.json | grep -q "\"$core\""; then + echo "::error::TriasDev.Templify $core is not on nuget.org. Release core first." + exit 1 +fi +if ! git diff --quiet "v$core" HEAD -- 'src/TriasDev.Templify/*.cs'; then + echo "::error::The core source changed since v$core. Release core first, then the builder." + git diff --stat "v$core" HEAD -- 'src/TriasDev.Templify/*.cs' + exit 1 +fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d2212de1..175426d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -164,6 +164,22 @@ jobs: - name: Pack run: dotnet pack src/TriasDev.Templify/TriasDev.Templify.csproj --no-build --configuration Release --output ./artifacts + # The builder packages, as the release packs them: a packaging error shows on the PR, not in the release. + - name: Pack the builder packages + run: | + for project in src/TriasDev.Templify.Builder src/TriasDev.Templify.Builder.Testing; do + dotnet pack "$project" --no-build --configuration Release --output ./artifacts + done + ./.github/scripts/check-builder-package.sh ./artifacts "$(tr -d '[:space:]' < src/TriasDev.Templify.Builder/version.txt)" + + # On the builder's release PR: the core it depends on must be released first (the publish job checks it again, + # but only after the tag exists). + - name: Check that the core is released (builder release PR) + if: startsWith(github.head_ref, 'release-please--branches--main--components--builder') + run: | + git fetch --tags --unshallow --quiet || git fetch --tags --quiet + ./.github/scripts/check-core-released.sh + - name: Upload NuGet package artifact uses: actions/upload-artifact@v7 with: diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 2f1ca676..46e292b9 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -22,6 +22,11 @@ jobs: release_created: ${{ steps.release.outputs.release_created }} version: ${{ steps.release.outputs.version }} tag_name: ${{ steps.release.outputs.tag_name }} + # The builder is a second release-please package: path src (minus src/TriasDev.Templify), component "builder", + # tags builder-v0.x.y. + builder_release_created: ${{ steps.release.outputs['src--release_created'] }} + builder_version: ${{ steps.release.outputs['src--version'] }} + builder_tag_name: ${{ steps.release.outputs['src--tag_name'] }} steps: - id: release @@ -132,3 +137,108 @@ jobs: echo "| **Package** | \`TriasDev.Templify\` |" >> $GITHUB_STEP_SUMMARY echo "| **Version** | \`${{ env.VERSION }}\` |" >> $GITHUB_STEP_SUMMARY echo "| **Tag** | \`${{ needs.release-please.outputs.tag_name }}\` |" >> $GITHUB_STEP_SUMMARY + + # TriasDev.Templify.Builder and TriasDev.Templify.Builder.Testing: own version line (0.x), released by their own + # release-please PR. Core and builder releases never share a job, so one cannot publish the other by accident. + publish-builder: + if: needs.release-please.outputs.builder_release_created == 'true' + needs: release-please + runs-on: ubuntu-latest + environment: nuget + permissions: + contents: read + id-token: write + + env: + VERSION: ${{ needs.release-please.outputs.builder_version }} + + steps: + - uses: actions/checkout@v7 + with: + # The core guard below compares the core source with its release tag. + fetch-depth: 0 + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: | + 10.0.x + global-json-file: global.json + + # The same check runs on the builder release PR (ci.yml), so it fails there, before a tag exists. + - name: Check that the core it depends on is released + run: ./.github/scripts/check-core-released.sh + + - name: Check that version.txt is the released version + run: | + file=$(tr -d '[:space:]' < src/TriasDev.Templify.Builder/version.txt) + [ "$file" = "$VERSION" ] || { echo "::error::version.txt ($file) is not the released version ($VERSION)"; exit 1; } + + # No -p:Version: a global property would also version the referenced core project, and the builder package would + # depend on TriasDev.Templify >= its own version. version.txt is the version source. + - name: Build + run: | + for project in src/TriasDev.Templify.Builder src/TriasDev.Templify.Builder.Testing tests/TriasDev.Templify.Builder.Tests; do + dotnet build "$project" --configuration Release -p:RestoreLockedMode=true + done + + - name: Run tests + run: | + dotnet test tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj \ + --configuration Release \ + --no-build \ + --verbosity normal \ + --logger trx \ + --results-directory ./test-results + + - name: Verify tests ran + run: | + shopt -s nullglob + files=(./test-results/*.trx) + if [ "${#files[@]}" -lt 1 ]; then + echo "::error::No test result file" + exit 1 + fi + for f in "${files[@]}"; do ./.github/scripts/verify-test-results.sh "$f"; done + + - name: Pack + run: | + for project in src/TriasDev.Templify.Builder src/TriasDev.Templify.Builder.Testing; do + dotnet pack "$project" --configuration Release --no-build --output ./artifacts + done + + - name: Check the packed dependencies + run: ./.github/scripts/check-builder-package.sh ./artifacts "$VERSION" + + - name: NuGet login (Trusted Publishing) + id: login + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ secrets.NUGET_USER }} + + - name: Push to NuGet + env: + NUGET_API_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} + run: | + dotnet nuget push ./artifacts/*.nupkg \ + --source https://api.nuget.org/v3/index.json \ + --api-key "$NUGET_API_KEY" \ + --skip-duplicate + + - name: Upload artifacts + uses: actions/upload-artifact@v7 + with: + name: nuget-packages-builder + path: | + ./artifacts/*.nupkg + ./artifacts/*.snupkg + + - name: Summary + run: | + echo "## NuGet Release (builder)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "| Key | Value |" >> $GITHUB_STEP_SUMMARY + echo "|-----|-------|" >> $GITHUB_STEP_SUMMARY + echo "| **Packages** | \`TriasDev.Templify.Builder\`, \`TriasDev.Templify.Builder.Testing\` |" >> $GITHUB_STEP_SUMMARY + echo "| **Version** | \`${{ env.VERSION }}\` |" >> $GITHUB_STEP_SUMMARY + echo "| **Tag** | \`${{ needs.release-please.outputs.builder_tag_name }}\` |" >> $GITHUB_STEP_SUMMARY diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cf198b9b..7b32cc58 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,4 @@ { - ".": "1.11.0" + ".": "1.11.0", + "src": "0.0.0" } diff --git a/CLAUDE.md b/CLAUDE.md index f3646d45..41ed73f8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,18 +12,23 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Solution Structure -`templify.slnx` holds 9 projects in solution folders that mirror the directories (same layout as TriasDev/tabular): +`templify.slnx` holds 14 projects in solution folders that mirror the directories (same layout as TriasDev/tabular): - `src/` (only what ships to NuGet) - **TriasDev.Templify** - Core library with template processing logic + - **TriasDev.Templify.Builder** - Code-first template builder (0.x preview, own version line): generates .docx/.odt templates from C#; uses the core's public API only. Design: `docs/superpowers/specs/2026-11-25-template-builder-design.md`, epic #261 + - **TriasDev.Templify.Builder.Testing** - Consumer test kit for the builder (same version line): `TemplateVerifier` (`VerifyAll` over languages × formats: build, ValidateTemplate, witness and sample fills, DOCX schema / ODT package, determinism, contract parity), `TemplateSnapshot` (canonical text dump), `LibreOfficeConverter` + - **TriasDev.Templify.Builder.Generators** - Roslyn source generator for typed data paths (`order.Number`); not a package of its own, it ships inside the builder package (`analyzers/dotnet/cs`). Must load in Roslyn 5.0 (.NET 10 SDK) - `tests/` - **TriasDev.Templify.Tests** - xUnit test suite (~2,360 tests, ~91% line / ~85% branch coverage) - **TriasDev.Templify.Tools.Tests** - xUnit tests for the tools/apps (GUI ViewModel/services headless, DocumentGenerator smoke tests) - **TriasDev.Templify.Converter.Tests** - xUnit tests for the Converter CLI (round trips through the core, file safety, CLI parsing) + - **TriasDev.Templify.Builder.Tests** - xUnit tests for the builder (every test: ValidateTemplate, fill through the engine, DOCX schema / ODT package checks, byte determinism; LibreOffice round trips with `Category=LibreOffice`). Its invariants are the test kit's checks (dogfooding); links `OdtDocumentVerifier`, `OdtDocumentBuilder` and `LibreOfficeRunner` from the core tests - `benchmarks/` - **TriasDev.Templify.Benchmarks** - BenchmarkDotNet performance tests - `samples/` - **TriasDev.Templify.Demo** - Demo console application + - **TriasDev.Templify.Builder.Sample** - Builder sample (order confirmation, DE/EN, DOCX/ODT, every construct; verified with the test kit, run by `SampleTests`) - `tools/` (applications that are not packages) - **TriasDev.Templify.Converter** - CLI tool for converting Word documents - **TriasDev.Templify.Gui** - Avalonia-based GUI application @@ -104,6 +109,9 @@ Instead these tests are a **required local step**: ```bash dotnet test tests/TriasDev.Templify.Tests/TriasDev.Templify.Tests.csproj -c Release -f net11.0 --filter "Category=LibreOffice" +# builder changes, and before every builder release PR (also needs poppler: pdftotext, pdftoppm, pdffonts, pdfimages +# in /opt/homebrew/bin, /usr/local/bin or /usr/bin) +dotnet test tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj -c Release --filter "Category=LibreOffice" ``` - all tests must **pass with 0 skipped** (a skip means `soffice` was not found — that is not a pass). Mention the result @@ -588,6 +596,7 @@ When adding new features: ### Public API Compatibility (hard rule) The library has external consumers. **Do not change, remove or rename public API** (types, members, signatures, namespaces) as a side effect of a fix or refactoring. +This rule is for the core library (`TriasDev.Templify`). The builder packages (`TriasDev.Templify.Builder`, `TriasDev.Templify.Builder.Testing`) are experimental (`[assembly: Experimental("TPLB001")]`, `0.x`): their API may change when a change needs it, without compatibility shims; record every change in their `PublicAPI.*.txt` files (entries carry the `[TPLB001]` prefix) and in the commit message. - Public API is tracked in `src/TriasDev.Templify/PublicAPI.Shipped.txt` / `PublicAPI.Unshipped.txt`; the build fails on undeclared additions (RS0016) or removals/changes (RS0017). `dotnet pack` validates against the last released package (`PackageValidationBaselineVersion`). - New public API → add it to `PublicAPI.Unshipped.txt` deliberately. Prefer `internal` unless the symbol is meant for consumers. - Retire API with `[Obsolete]`; remove only in a major version. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11fcae50..8e1ffd60 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -256,15 +256,20 @@ dotnet format --no-restore ``` templify/ ├── src/ -│ └── TriasDev.Templify/ # Core library (NuGet package) +│ ├── TriasDev.Templify/ # Core library (NuGet package) +│ ├── TriasDev.Templify.Builder/ # Template builder (NuGet package, experimental 0.x) +│ ├── TriasDev.Templify.Builder.Testing/ # Builder test kit (NuGet package, experimental 0.x) +│ └── TriasDev.Templify.Builder.Generators/ # Typed-path source generator (ships inside the builder package) ├── tests/ │ ├── TriasDev.Templify.Tests/ # Core library tests +│ ├── TriasDev.Templify.Builder.Tests/ # Builder tests (incl. LibreOffice round trips) │ ├── TriasDev.Templify.Converter.Tests/ # Converter tests │ └── TriasDev.Templify.Tools.Tests/ # Tests for GUI view models and DocumentGenerator ├── benchmarks/ │ └── TriasDev.Templify.Benchmarks/ # BenchmarkDotNet performance benchmarks ├── samples/ -│ └── TriasDev.Templify.Demo/ # Demo console application +│ ├── TriasDev.Templify.Demo/ # Demo console application +│ └── TriasDev.Templify.Builder.Sample/ # Builder sample (order confirmation) ├── tools/ │ ├── TriasDev.Templify.Converter/ # CLI converter (OpenXMLTemplates → Templify) │ ├── TriasDev.Templify.Gui/ # Avalonia GUI application @@ -359,9 +364,12 @@ every change to OpenDocument code or the shared engine, and before every release ```bash dotnet test tests/TriasDev.Templify.Tests/TriasDev.Templify.Tests.csproj -c Release -f net11.0 --filter "Category=LibreOffice" +dotnet test tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj -c Release --filter "Category=LibreOffice" ``` -They need LibreOffice installed (macOS default path is detected; otherwise set `TEMPLIFY_SOFFICE` to the `soffice` +The second line is for builder changes and before every builder release PR; the builder's round trips also need +poppler (`pdftotext`, `pdftoppm`, `pdffonts`, `pdfimages`, looked up in `/opt/homebrew/bin`, `/usr/local/bin` and +`/usr/bin`). They need LibreOffice installed (macOS default path is detected; otherwise set `TEMPLIFY_SOFFICE` to the `soffice` executable). The run must show **0 skipped** — a skipped run means LibreOffice was not found. Put the result in the PR description. @@ -569,6 +577,38 @@ mkdocs build --strict - Write PR titles for users: they become changelog lines. Put behavior changes and migration notes in the PR description so maintainers can carry them into the release notes. +### Builder releases (preview, 0.x) + +`TriasDev.Templify.Builder` and `TriasDev.Templify.Builder.Testing` have their own version line and their own +release-please package (`src/TriasDev.Templify.Builder`, component `builder`, tags `builder-v0.x.y`, changelog +`src/TriasDev.Templify.Builder/CHANGELOG.md`): + +- Core and builder get separate release PRs (`separate-pull-requests`), each with its own changelog. +- The builder's release-please package is `src` without `src/TriasDev.Templify` (`exclude-paths`), so commits to any + of the three shipped builder projects (`src/TriasDev.Templify.Builder`, `.Builder.Testing`, `.Builder.Generators`) + count for the builder; `version-file` and `changelog-path` keep `version.txt` and `CHANGELOG.md` in + `src/TriasDev.Templify.Builder`. The core package excludes those projects, the builder tests and sample, and `docs/`, + so builder commits do not reach the core release notes. Root files (solution, `Directory.*.props`, `CLAUDE.md`, + `CONTRIBUTING.md`, CI) count for core: change them in their own `build`/`chore`/`docs`/`ci` commits. +- The PR that merges builder work into `main` gets a `chore(builder): …` title and a merge commit (no + `BEGIN_COMMIT_OVERRIDE`, no `BREAKING CHANGE`): GitHub puts the title into the merge commit body, and + release-please would read a `feat:` title as a core change. +- `src/TriasDev.Templify.Builder/version.txt` is the single version source of both packages; release-please updates + it in the builder's release PR. During `0.x`, a breaking change bumps the minor version (`bump-minor-pre-major`). +- The builder package depends on the core version in `TriasDev.Templify.csproj`. **Release core first** when the + builder needs unreleased core changes: the `publish-builder` job refuses to publish when that core version is not + on nuget.org or when the core source changed since its tag. +- Merging the builder's release PR runs `publish-builder` (builder tests, pack, Trusted Publishing with the `nuget` + environment, as for core). The core release job is not involved. +- The builder packages are experimental (`[assembly: Experimental("TPLB001")]`, docs "Preview status"): their API may + change in any `0.x` release, and the compatibility rules for core do not apply. There is no + `PackageValidationBaselineVersion` for them. Their `PublicAPI.*.txt` files are still kept (entries carry the + `[TPLB001]` prefix), so every change of the API is visible in review. After a builder release, move the + `PublicAPI.Unshipped.txt` entries to `PublicAPI.Shipped.txt` in the builder, the test kit and the generator, and the + generator's `AnalyzerReleases.Unshipped.md` entries to `AnalyzerReleases.Shipped.md`. +- The first release is 0.1.0 (`"initial-version"` in `release-please-config.json`; it no longer applies once a builder + release exists). + --- ## Additional Resources diff --git a/Directory.Packages.props b/Directory.Packages.props index 2764b16c..3ff7dd51 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,6 +8,8 @@ + + diff --git a/benchmarks/TriasDev.Templify.Benchmarks/packages.lock.json b/benchmarks/TriasDev.Templify.Benchmarks/packages.lock.json index ee209375..5f913fd7 100644 --- a/benchmarks/TriasDev.Templify.Benchmarks/packages.lock.json +++ b/benchmarks/TriasDev.Templify.Benchmarks/packages.lock.json @@ -61,15 +61,6 @@ "Microsoft.CodeAnalysis.Analyzers": "3.11.0" } }, - "Microsoft.CodeAnalysis.CSharp": { - "type": "Transitive", - "resolved": "4.14.0", - "contentHash": "568a6wcTivauIhbeWcCwfWwIn7UV7MeHEBvFB2uzGIpM2OhJ4eM/FZ8KS0yhPoNxnSpjGzz7x7CIjTxhslojQA==", - "dependencies": { - "Microsoft.CodeAnalysis.Analyzers": "3.11.0", - "Microsoft.CodeAnalysis.Common": "[4.14.0]" - } - }, "Microsoft.Diagnostics.NETCore.Client": { "type": "Transitive", "resolved": "0.2.510501", @@ -186,6 +177,16 @@ "DocumentFormat.OpenXml.Framework": "3.5.1" } }, + "Microsoft.CodeAnalysis.CSharp": { + "type": "CentralTransitive", + "requested": "[5.0.0, )", + "resolved": "4.14.0", + "contentHash": "568a6wcTivauIhbeWcCwfWwIn7UV7MeHEBvFB2uzGIpM2OhJ4eM/FZ8KS0yhPoNxnSpjGzz7x7CIjTxhslojQA==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.11.0", + "Microsoft.CodeAnalysis.Common": "[4.14.0]" + } + }, "Microsoft.Extensions.DependencyInjection": { "type": "CentralTransitive", "requested": "[11.0.0, )", diff --git a/docs/for-developers/template-builder.md b/docs/for-developers/template-builder.md new file mode 100644 index 00000000..c03c0050 --- /dev/null +++ b/docs/for-developers/template-builder.md @@ -0,0 +1,641 @@ +# Template Builder (preview) + +`TriasDev.Templify.Builder` describes Templify templates in C# and generates them at runtime as Word (`.docx`) or +OpenDocument Text (`.odt`) files. Templify fills the generated templates like any other template. Users can download +one, change it in Word or LibreOffice and upload it again, and the builder checks the uploaded copy against the data +the template is allowed to read. + +!!! warning "Preview" + The builder is experimental: its API may change in any release until the first stable one. See + [Preview status](#preview-status). + +```bash +dotnet add package TriasDev.Templify.Builder +dotnet add package TriasDev.Templify.Builder.Testing # in your test project +``` + +The packages are not on nuget.org yet: until the first preview release, reference the projects from source. The builder +needs TriasDev.Templify 1.11.0 or later. + +The complete example on this page is the sample `samples/TriasDev.Templify.Builder.Sample`. It builds an order +confirmation in German and English, as DOCX and ODT, verifies it, fills it and writes the files: + +```bash +dotnet run --project samples/TriasDev.Templify.Builder.Sample -- output +``` + +## Preview status + +`TriasDev.Templify.Builder` and `TriasDev.Templify.Builder.Testing` are a preview on their own `0.x` version line. They +are marked `[Experimental("TPLB001")]`: code that uses them gets diagnostic **TPLB001** (an error by default) until it +opts in, and their API may change in any release, without the compatibility rules of the core library (`TriasDev.Templify` +itself is unaffected). Opt in for the whole project: + +```xml + + $(NoWarn);TPLB001 + +``` + +Stored JSON definitions are versioned separately (`"templifyDefinition": 1`); a change of the format is announced with +the release that makes it. + +## Concepts + +### Definition + +A template is a class that implements `ITemplateDefinition`. `Identity` names it and carries its version, and +`Compose` describes it. `TemplateBuilder.Build` runs `Compose` for one format and one language: + +```csharp +public sealed class OrderConfirmation(BrandTheme theme) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = new("order-confirmation", 1); + + public void Compose(TemplateComposer template) + { + TemplateTexts t = template.Texts; + TemplatePath order = template.Data["order"]; + + template.Styles(Styles.Create(theme)); + template.Content(c => + { + c.Paragraph(Styles.Title, t["title"]); + c.Paragraph(Styles.Subtitle, x => + { + x.Text(t["orderNo"] + " "); + x.Value(Styles.Strong, order["number"]); + }); + }); + } +} + +GeneratedTemplate template = TemplateBuilder.Build( + new OrderConfirmation(theme), + new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = CultureInfo.GetCultureInfo("de-DE"), Texts = texts }); +``` + +`GeneratedTemplate` holds the file (`Content`, `OpenRead()`, `WriteTo`), the `FileExtension` and `MediaType` for a +download, the data `Contract`, the identity `Stamp` and build `Warnings`. Building is deterministic. The same +definition and options give the same bytes on the same runtime and operating system family, so `ContentHash` can serve +as a cache key. + +`Compose` does not see the format: one definition produces both. Mistakes in a definition (an undefined style, a +loop variable used outside its loop, a missing text) fail the build with a `TemplateBuildException`. It lists every +problem with a code (`TB…`). + +### Styles + +Styles are named, and the names are stable: a user who edits the template sees "Section Heading", not direct +formatting. Text formatting, alignment and indents come only from styles. One paragraph may set four layout options of +its own (space before and after, keep with next, keep lines together); see "Content blocks". A `StyleSheet` defines +paragraph, character, table, box and list styles. It is usually built from a theme +record, so one theme restyles every template of a product: + +```csharp +public static StyleSheet Create(BrandTheme t) => StyleSheet.Create(s => +{ + s.Defaults(d => d.Font(t.Body).Size(10.Pt()).Color(t.Ink).ParagraphStyle(Body)); + s.Paragraph(Body, p => p.SpaceAfter(6.Pt()).LineSpacing(1.15)); + s.Paragraph(Heading, p => p.BasedOn(Body).Size(13.Pt()).Bold().Color(t.Accent).KeepWithNext().OutlineLevel(1)); + s.Paragraph(RunHead, p => p.BasedOn(Body).Size(8.Pt()).BorderBottom(0.75.Pt(), t.Line, 3.Pt())); + s.Character(Strong, c => c.Bold()); + s.Table(Grid, g => g.HeaderRule(1.Pt(), t.Accent).RowRule(0.5.Pt(), t.Line).CellPadding(3.Pt(), 5.Pt()) + .ParagraphStyle(TableText).HeaderParagraphStyle(TableHeader)); + s.Table(Marked, g => g.OuterBorder(Sides.Top, 0.75.Pt(), t.Line).RowRule(0.5.Pt(), t.Line).CellPadding(8.Pt(), 6.Pt(), 9.Pt(), 6.Pt())); + s.Box(Success, b => b.Border(0.75.Pt(), t.SuccessBorder).Background(t.SuccessBackground).Padding(6.Pt(), 8.Pt())); + s.List(Bullets, l => l.ItemStyle(ListItem).Level(0, "•", 6.Mm(), 4.Mm())); +}); +``` + +Padding takes one value, two (vertical, horizontal) or four (top, right, bottom, left). `OuterBorder(sides, …)` sets +the table's outer lines on some sides only, for example a rule above a list table; `BorderBottom` on a paragraph style +draws a line under its paragraphs (a running head). + +A paragraph without a style of its own inherits one, so most paragraphs need none: + +1. in a table cell, the row's `ParagraphStyle` (for example a totals row: `r.ParagraphStyle(TableHeader)`), then the table + style's `HeaderParagraphStyle` (header rows) or `ParagraphStyle` (other rows); +2. the style sheet's default paragraph style, `Defaults(d => d.ParagraphStyle(Body))`; +3. otherwise none (the application's "Normal" / "Standard"). + +List items take their list style's `ItemStyle`; a list style without one lets its items inherit like any paragraph. The inherited style is written into the document explicitly, so Word +and LibreOffice show it by name. Without a default and without table text styles nothing is inherited. + +The marker paragraphs (`{{#if …}}`, `{{#foreach …}}`) use the style "Template Marker": small and grey, visible but +quiet. + +#### Fonts + +`new FontFace("Source Sans 3")` refers to an installed font by name. `FontFace.Embedded(File.ReadAllBytes("Brand.ttf"))` +embeds the file in the document, so a server-side PDF conversion and recipients without the font installed see it: + +- TrueType files (`.ttf`) only; the family name is read from the file; +- the font's licence must allow installable or editable embedding (`fsType`); other fonts are refused; +- one file per family and weight: embed the bold weight as its own family ("Brand Bold"), because Word for Mac + ignores embedded bold faces; +- the builder does not subset, so pass a subset file to keep documents small. + +### Paths + +`template.Data` is the root of the data. An indexer appends segments: `order["customer.address"]["city"]` is +`order.customer.address.city`. Values are written with `Value(path)`, with an optional `ValueFormat` (`Currency`, +`Date("d MMMM yyyy")`, `Number("N2")`, `YesNo`, `Checkmark`, `Join(separator: ", ")`, `Raw`, …) and a character +style. + +A segment may read one item of a list by its index (0 to 999): `order["items[0].name"]`, typed +`order.Path(o => o.Items[0].Name)`, in JSON `{{order.items[0].name}}`. The data contract keeps the index, and its +witness holds enough items for the highest index used. A loop cannot run over an indexed path (`groups[1].lines`): +Templify's loop marker does not accept an index. + +### Conditions + +Conditions are built from paths and are written in Templify's syntax, with the correct quoting and precedence: + +```csharp +c.If(order["isExpress"] & order["total"].Gt(1000), b => b.Paragraph(Body, t["expressFree"])) + .ElseIf(order["isExpress"], b => b.Paragraph(Body, t["express"])) + .Else(b => b.Paragraph(Body, t["standard"])); + +c.Switch(order["status"], s => +{ + s.Case("paid", b => b.Box(Styles.Success, x => x.Paragraph(Body, t["statusPaid"]))); + s.Case(new[] { "overdue", "reminded" }, b => b.Paragraph(Body, t["statusOverdue"])); + s.Default(b => b.Paragraph(Body, t["statusOpen"])); +}); +``` + +A path alone tests truthiness. `!`, `&` and `|` combine conditions. Comparisons are `Eq`, `NotEq`, `Gt`, `Ge`, `Lt`, +`Le`, `In`, `Contains`, `StartsWith` and `EndsWith`, and the existence tests are `Exists`, `IsEmpty` and +`IsNotEmpty`. The comparisons and the three text operators also take another path, so two values from the data +compare directly: `entry["ownerId"].Eq(owner["id"])` is written `entry.ownerId = owner.id`, and both paths go into the +data contract. Templify reads an operand that does not resolve as its own text, so the contract is what keeps such a +comparison meaningful. Inside a paragraph, `x.If(…)` writes an inline conditional, and `x.Expression(condition, format)` an +inline expression such as `{{(order.isExpress and order.total > 1000):yesno}}`. + +### Loops + +Loops always have a named item, so nested loops can reach outer items: + +```csharp +c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(Body, x => +{ + x.Value(line.Loop.Number); // {{@number}} + x.Text(". "); + x.Value(line["description"]); // {{line.description}} +})); +``` + +The loop's metadata is under `Loop`: `line.Loop.Index` (`{{@index}}`), `Number`, `Count`, `IsFirst` and `IsLast`. It +is a member of its own, so a data property named `Number` or `Count` is always the data. + +Tables loop over rows (`table.ForEachRow`, `RowsIf`), and lists loop over items (`list.ForEach`). A `LoopItem` that +escapes its loop, or loop metadata of an outer loop used in an inner one, is a build error. + +### Components + +An `ITemplateComponent` is a reusable block, for example an address, a signature block or a status box. Templates +share it through `c.Component(new AddressBlock(order["customer.address"]))`. A component receives paths, so the same +block can print the customer's address and the delivery address. + +A standard block whose changes stored copies should pick up (terms, legal notes) gets a version: +`[ComponentVersion(2)]` on the class. The stamp records the versioned components a template was built from, and the +check reports copies built from an older version (TB9306). A JSON export must name a versioned component through its +registration (`ComponentCatalog`), so builds from the JSON always use the current version; exporting it unregistered is +an error (TB9204), because inlining it as a section would freeze its content. + +### Data contract + +Every build lists the data the template reads in `template.Contract`: each path with its use (value, collection, +condition). Loop items are written as `[]` (`order.lines[].description`). The contract has a `Hash`, serialises to +JSON (`ToJson`, `FromJson`) and creates a *witness*, a minimal data object that touches every path. The contract does +not depend on the language or the format. Different contracts for German and English mean the definition branches on +something it should not. + +### Stamp and checking stored templates + +The build writes an identity stamp into the document properties: template id, version, contract hash, language, +builder version and the versioned components (`Templify.*` custom properties). The stamp stays in filled documents; +`TemplateStampRemover.Remove(stream)` removes it before a document leaves the organisation. + +Templates the host builds from code are rebuilt and always match the current data. Stored templates are different: a +copy a user downloaded, edited in Word and uploaded, or a stored JSON definition. When the data changes, the host checks +them against the current data catalogue: + +```csharp +TemplateCheckOptions options = new TemplateCheckOptions +{ + Data = DataCatalog.From(), // every path the data has today + Expected = new TemplateIdentity("order-confirmation", 3), // optional: the current definition + Components = components, // optional: the current versioned components +}; + +TemplateCheckResult copy = TemplateInspector.Check(upload, options); // DOCX or ODT +TemplateCheckResult json = TemplateInspector.CheckDefinition(text, importOptions, buildOptions); // JSON definition +// copy.Status: Ok, Warning (works, but outdated or of unknown origin) or Broken (will not fill correctly) +// copy.Problems: code, severity, message, DataPath, Location +``` + +A copy is checked against the **catalogue**, not against the contract of the standard template: it may read any field +the data has, also one the standard template does not use. `Check` validates the syntax, every path the copy reads +(loop variables are resolved; any path below an open shape such as a dictionary is accepted) and fills the copy once +with data of the catalogue's shape. `CheckDefinition` imports the JSON with the catalogue and, given build options, +builds it; its problems carry the JSON pointer. See the known limits for what the check of a copy cannot see. + +| Code | Severity | Meaning | +|---|---|---| +| TB9300 | error | The syntax is broken (unclosed loop, …) or the file is not a DOCX/ODT template. | +| TB9301 | error | The copy reads a path the data does not have (`DataPath` names it as the copy writes it). | +| TB9302 | error | Filling with the data's shape fails, for example a loop over a value. | +| TB9303 | warning | No stamp: edited in an application that dropped it, or not built by the builder. | +| TB9304 | warning | The stamp (or the definition's identity) names another template than `Expected`. | +| TB9305 | warning | Built from an older version of the definition than `Expected`. | +| TB9306 | warning | Built from an older version of a component, or from one no longer registered in `Components`. | +| TB92xx, others | error | `CheckDefinition`: the import's and the build's own codes (TB9203: unknown data path). | + +**Changing the data.** Adding a field is safe. Renaming or removing one is a breaking change: stored templates that read +it break. Check every stored template after such a change (for example on deploy) and show the result to the users +(yellow for warnings, red for broken). The library only checks; storing templates, keeping a changelog of data +changes, and fixing templates (by hand, or by an agent that reads the changelog) are the host's work. +`DataCatalog.ToJson()` writes the catalogue (path, kind, C# type) for agents; a host that commits it sees removed +fields in its diff. + +### Localisation + +Texts come from an `ITextCatalog`: `TextCatalog.FromResourceManager(Resources.ResourceManager)` for `.resx` files, +`TextCatalog.FromDictionary(...)` for tests and small products, and `TextCatalog.Combine(product, customer)` for +overrides (a later catalog wins). `template.Texts["key"]` returns the text in the build's language (with the usual culture fallback). A +missing key is a build error (TB5001). Values (dates, numbers, currency) are formatted by Templify with the culture +of the fill (`PlaceholderReplacementOptions.Culture`), not by the builder. + +### Page, headers and footers + +```csharp +template.Page(page => page + .Size(PageSize.A4) + .Margins(25.Mm(), 20.Mm(), 22.Mm(), 20.Mm()) + .Header(h => h.Paragraph(Styles.Small, x => + { + x.Value(order["number"]); + x.TabRight(); + x.PageNumber(); + x.Text(" / "); + x.PageCount(); + })) + .Footer(f => f.Paragraph(Styles.Small, t["footer"])) + .FirstPage(first => first.Header(h => h.Paragraph(x => x.Image(theme.Logo, "Logo", ImageFit.Height(12.Mm())))))); +``` + +### Content blocks + +| Block | API | +|---|---| +| Paragraph | `Paragraph(style, text \| path \| x => …)`, with `Text`, `Value`, `Tab`, `TabRight`, `LineBreak`, `Image`, `PageNumber`, `PageCount`, inline `If`, `Expression`; layout options as a last argument: `Paragraph(style, text, p => p.SpaceBefore(7.Pt()).KeepWithNext())` (also `SpaceAfter`, `KeepLinesTogether`; `null` as the style keeps the inherited one) | +| Spacer | `Spacer(height)`: vertical space without a style, an empty paragraph exactly that high (at most 72 pt) | +| Page break | `PageBreak()` | +| Table | `Table(t => …)`: `Style`, `Columns` (`Fixed`, `Relative`), `Indent`, `SpaceBefore`, `SpaceAfter`, `HeaderRow`, `Row`, `ForEachRow`, `RowsIf`; cells with `ColumnSpan`, `Background`, `VerticalAlignment`, `Padding(top, right, bottom, left)`, `Border(sides, width, color)` and any blocks | +| Box | `Box(boxStyle, b => …)`: a framed, shaded block (a one-cell table) | +| Rule | `Rule(thickness, color[, above, below[, width]])`; with a width the rule is that long from the start of its container | +| List | `List(listStyle, l => …)`: `Item(text \| path \| x => …)`, `Item(level, …)`, `ForEach`, `If` | +| Image | `Image(ImageSource.Png(bytes), altText, ImageFit.Within(w, h))`, PNG and JPEG | +| Table of contents | `TableOfContents(maxLevel)` over the styles with an outline level; entry styles per level: `TableOfContents(3, toc => toc.Level(1, Styles.TocPart).Level(2, Styles.TocSection))` | +| Component | `Component(component)` | +| Raw XML | `Raw(new RawBlock { Docx = ctx => …, Odt = ctx => …, Uses = [...] })` (see below) | + +Templify removes the marker paragraphs (`{{#if}}`, `{{/foreach}}`, …) when it fills a template. So that a table cell +still ends with a paragraph and a table never touches the next one afterwards, the builder adds an invisible 1 pt +paragraph in the style "Template Spacer" where that could happen: after a table that a marker follows, and at the end of +a cell that ends with a table or that filling may empty. There is one per position, so a box ending with a conditional +does not grow. A style display name must not contain a comma (TB2006). + +The four paragraph layout options are written as the paragraph's own properties on top of its named style (in Word a +visible override in the paragraph dialog; in LibreOffice an automatic style whose parent is the named style). +A cell's own `Border` replaces the table style's line on those sides of that cell; on an edge shared with a neighbour +both formats draw the wider line. A cell's own `Padding` replaces the table style's for that cell. A table's `Indent` +steps it in from the start of its frame and narrows its columns; an indent not smaller than the frame, a rule wider than +its container and cell padding that leaves no width are build errors (TB7002). + +A style always comes first (`Paragraph(style, text)`, `Text(style, text)`, `Value(style, path[, format])`), like the +options before the content in JSON. The methods that add content return their composer, so short parts chain: +`x.Text("Dear ").Value(Styles.Strong, order["name"]).Text("!")`, `r.Cell("A").Cell("B")`. + +### Raw blocks + +For a construct the builder does not have, `Raw` writes format XML. Both formats are required, and the paths the XML +reads must be declared in `Uses`. `RawContext.Placeholder(path)` returns the placeholder text only for a declared +path, so the data contract stays complete: + +```csharp +TemplatePath name = order["customer.name"]; +c.Raw(new RawBlock +{ + Uses = [name], + Docx = ctx => new XElement(w + "p", + new XElement(w + "r", new XElement(w + "t", ctx.Placeholder(name))), + new XElement(w + "fldSimple", new XAttribute(w + "instr", " DATE "), new XElement(w + "r", new XElement(w + "t", "date")))), + Odt = ctx => new XElement(text + "p", ctx.Placeholder(name), " ", new XElement(text + "date", "date")), +}); +``` + +The root must be a paragraph or a table (`w:p`, `w:tbl`; `text:p`, `text:h`, `text:list`, `table:table`). The XML +cannot add styles, numbering or relationships. + +## Typed data paths + +Instead of string paths (`order["customer.name"]`), a definition can take its paths from the C# classes of its data. +The package's source generator writes C# 14 extension properties for every type used in `template.DataAs()` and every +type reachable from it, so the paths read like the data: + +```csharp +TemplatePath order = template.DataAs().Order; +c.Paragraph(x => x.Value(order.Customer.Name)); +table.ForEachRow(order.Lines, "line", (line, rows) => rows.Row(r => +{ + r.Cell(line.Description); + r.Cell(line.Quantity); +})); +c.If(order.Total.Gt(1000) & order.IsExpress, b => b.Paragraph("Free express shipping")); +``` + +The data classes need nothing (no attribute, no `partial`); they may live in another assembly. Names follow the JSON +rules of the data: `[JsonPropertyName]` wins, otherwise the naming policy given to `DataAs(policy)` (camelCase by +default); `[JsonIgnore]` hides a property. A collection property gives a `TemplateCollection` for loops, and the loop +item has the item type's properties. Every generated property is shorthand for the lambda form, which always works too: +`order.Path(o => o.Customer.Name)`. + +- A property whose name the path or loop item type already uses (`Self`, `Item`, `Loop`, `Path`, `Items` on a loop + item; `Path`, `Items`, `Exists`, `IsEmpty`, `IsNotEmpty`, the comparison methods on a path) is not generated, and the + build warns (TBG001): `order.Exists` would mean the condition "order exists", not the property. Use the lambda there. +- Types of .NET itself (`Uri`, `Version`, …) get a path but are not walked into, like the lambda API. Private, + protected and `file` types, ref structs (`Span`) and ref-returning properties are skipped. An `[Obsolete]` data + property gives an `[Obsolete]` path property. +- Types not reached from `DataAs` are added with `[assembly: TemplateData(typeof(Address))]` (for example in a component + library). A project that sees another assembly's internals (a test project) uses that assembly's generated paths. +- C# 14 or later is required (.NET 10 SDK); below, the generator reports TBG002 and generates nothing. + +## JSON definitions + +A definition can also be a JSON file: something an editor or an agent changes without a build, and that a host stores +per customer. `TemplateJson.Export` writes a C# definition as JSON; `TemplateJson.Import` reads JSON as a definition that +builds the same bytes. Every builder test checks that round trip, both ways. + +```csharp +TemplateJsonDocument exported = TemplateJson.Export(new OrderConfirmation(theme), options, new TemplateJsonExportOptions +{ + Components = catalog, // registered components are written as references + TextLanguages = [de, en], // translations go into the file's texts section + Indented = true, // false: one line without whitespace, for storage +}); +ITemplateDefinition definition = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions +{ + Assets = exported.Assets, // the images and fonts the file names + Components = catalog, // the components it may refer to + Shared = [theme], // what template.Share(…) gives components in C# + Data = DataCatalog.From(), // optional: every data path must exist (TB9203) + Theme = customerColours, // optional: token → value, replaces the file's theme + ValueFormats = ["janein"], // formats the host registered with Templify + AllowRawXml = false, // default: raw XML is refused (TB9202) +}); +``` + +### Layout + +An object or array whose one-line form fits in 100 characters (counting its key, not its indentation) is written on +one line, otherwise one member per line. Options come before the content key (`{"style": …, "paragraph": …}`), so a +reader sees what a block is before what it holds. A paragraph in the inherited style is a plain string, values sit in +the text as Templify placeholders, and conditions are strings in Templify's condition syntax: + +```json +{"style": "LineGrid", "columns": ["10mm", 4, "16mm", "30mm"], "table": [ + {"header": true, "row": ["#", "[[description]]", "[[quantity]]", "[[amount]]"]}, + {"forEachRow": "order.lines", "as": "line", "rows": [ + {"row": ["{{@number}}", "{{line.description}}", "{{line.quantity}}", "{{line.amount:currency}}"]} + ]}, + {"rowsIf": "order.discount > 0", "then": [{"row": [{"span": 3, "content": "[[discount]]"}, "{{order.discount:currency}}"]}]}, + {"paragraphStyle": "TableHeader", "row": [{"span": 3, "content": "[[total]]"}, "{{order.total:currency}}"]} +]} +``` + +(Hand-wrapped here; the writer applies the width rule.) + +### Root + +| Key | Holds | +|---|---| +| `templifyDefinition` | the format version, `1` (required) | +| `identity` | `{"id", "version"}` (required) | +| `texts` | translations, key first: `"title": {"de": "…", "en": "…"}` | +| `assets` | images and fonts by name: `"logo": "sha256:…"`; the content comes from `TemplateJsonImportOptions.Assets` | +| `theme` | `{"colors": {"accent": "#1F4E79"}, "fonts": {"heading": "Source Serif 4"}}` | +| `properties` | document properties: `title`, `author`, `subject` | +| `styles` | `defaults`, `paragraph`, `character`, `table`, `box`, `list`, each a map from style id to its settings | +| `page` | `size` (`"A4"`, `"Letter"`, … or `{"width", "height"}`), `margins`, `headerFooterDistance`, `header`, `footer`, `firstPage` (`header`, `footer`; `"none"` for an empty one) | +| `content` | the body: a list of blocks | + +`$schema` is allowed and ignored; `components` is reserved. Any other key is an error. + +### Content + +| Where | Form | +|---|---| +| Text | a string with `{{path}}`, `{{path:format}}`, `{{(condition):format}}`, `[[key]]`, a tab `\t` and a line break `\n`; styled: `{"text": "{{order.number}}", "style": "StrongText"}`; a list mixes strings, styled text, `{"if": …}`, `{"tabRight": true}`, `{"pageNumber": true}`, `{"pageCount": true}`, `{"image": …}` | +| Block | a string (a paragraph in the inherited style), `{"style", "paragraph", "spaceBefore", "spaceAfter", "keepWithNext", "keepLinesTogether"}`, `{"spacer": "14pt"}`, `{"style", "box": [blocks]}`, `{"style", "list": [items]}`, `{"style", "columns", "indent", "spaceBefore", "spaceAfter", "table": [rows]}`, `if`, `forEach`, `{"section": "name", "blocks": [blocks]}`, `component`, `pageBreak`, `{"rule": {"line", "spaceAbove", "spaceBelow", "width"}}`, `{"toc": {"maxLevel": 3, "levels": {"1": "TocPart"}}}`, `raw` | +| Row | `{"header", "allowSplit", "paragraphStyle", "row": [cells]}`, `forEachRow`, `rowsIf` | +| Cell | a string (one paragraph), `{"style": "Label", "content": "…"}` (one paragraph in its own style), or `{"span", "background", "verticalAlign", "border", "padding", "content": [blocks]}` | +| List item | a string, `{"level", "item"}`, `forEach`, `if` | +| Image | `{"image": "logo", "alt": "…", "width": "40mm"}`; one size is enough, the other follows from the image's proportions | +| Component | `{"component": "address", "params": {"address": "order.customer.address"}}`; a component without parameters is `{"component": "terms"}` | + +Every conditional has `then`, `elseIf` (a list of `{"if": …, "then": …}`) and `else`, in blocks, rows, list items and +inline. In a condition, a literal is quoted (`status = "paid"`); a path on the right of an operator has a dot or an +index (`entry.ownerId = owner.id`) or is loop metadata (`@index`), and a top-level value is written in brackets (`total > [limit]`). A plain word there +(`status = paid`) is an error, since it is almost always a missing quote. A loop is `{"forEach": "order.checks", "as": "check", "body": […]}` (rows: `"rows"`, list items: `"items"`). There +is no `{{#if}}` inside strings. An expression whose condition is raw has no text form and is written as +`{"expression": {"raw": …, "uses": […]}, "format": …}`. + +### Values + +- **Lengths** carry a unit: `"10mm"`, `"6pt"`, `"2cm"`, `"0.5in"`. A table column is a length (fixed) or a number + (relative weight). +- **Colours** are `"#1F4E79"` or a theme token `"$accent"`. A **line** is a thickness and a colour: `"0.5pt $line"`. +- **Padding** (`padding`, `cellPadding`) is one to four lengths in CSS order: one for all sides, two (vertical, + horizontal) `"6pt 8pt"`, three (top, horizontal, bottom) or four (top, right, bottom, left) `"8pt 6pt 9pt 6pt"`. +- **Lines per side** (`outerBorder` of a table style, `border` of a cell) are one line for all four sides, or an object + with the sides that have one: `{"top": "0.75pt $line"}`. A paragraph style's `borderBottom` is a line, with + `borderBottomSpace` the space between the text and the line. +- **Value formats** are Templify's: `date:…`, `number:…`, `currency`, `uppercase`, `lowercase`, `raw`, `join`, and the + boolean formats (`yesno`, `checkmark`, …). A format the host registered with Templify (`ValueFormat.Custom("janein")`) + is exported as written and listed in `TemplateJsonImportOptions.ValueFormats` on import; any other name is an error. + +### Strictness + +The import accepts only what it understands, so a mistake fails where it is made instead of building a different +template: an unknown key or block kind, an unknown format, padding with three values, a loop variable that shadows its +own collection's root (`{"forEach": "line.parts", "as": "line"}`), a text in `texts` without a language the others +have (a regional `de-CH` is covered by `de`), a duplicate section name. `==` is read as `=`. The import reports every problem at once, each with the JSON pointer of the +element (`/content/7/table/1/row/3`): TB9200 (structure), TB9201 (a value the builder rejects), TB9202 (raw XML not +allowed), TB9203 (a data path outside `Data`). + +### Texts + +**One JSON for every language.** Texts from `template.Texts["key"]` are exported as `[[key]]` references, wherever the +code put them (in text, in a date format such as `{{order.date:date:[[dateFormat]]}}`, in raw XML, in document +properties), so the exported JSON does not depend on the language. With `TextLanguages` the translations are written +into the `texts` section and the file is self-contained, including the texts a registered component reads. Every text +must then have every requested language; a missing one is TB9204 at `/texts/`. + +At build time a key is translated from the JSON's `texts` for the build language (`de-DE` finds `de`), else from +`TemplateBuildOptions.Texts`; a key neither has is TB5001. Components of an imported definition look their texts up the +same way. A key is letters, digits, `_`, `.` or `-`; a literal `[[` cannot be exported (TB9204). Texts are opaque to the +export: code that changes a text (`string.Format(Texts["pages"], n)`, `Texts["x"].ToUpper()`) changes the key, not the +translation. The export therefore checks itself: it imports the JSON it wrote, builds it for the options' language and +every `TextLanguages` entry, and fails with TB9204 (naming the first paragraph that differs) when the bytes differ from +the C# definition's. Re-exporting an imported definition without `TextLanguages` writes its `texts` section exactly as +it was read. + +### Sections, components, assets, theme + +A **section** (`c.Section("items", b => …)` in C#) names a part of the document without adding output: in JSON +`{"section": "items", "blocks": […]}`, the unit to read, replace or compare. Names are unique in a definition; a +component the export's catalog does not know is written as a section named after it (`AddressBlock`, `AddressBlock-2`). + +**Components** see the build's texts (`c.Texts["title"]`) and objects the definition shares (`template.Share(theme)`, +`c.Shared()`; for JSON imports `TemplateJsonImportOptions.Shared`). A component then needs only data paths +as parameters, so it can be registered in a `ComponentCatalog` and written as a reference; the import builds it from the +current component code. A colour parameter that is a theme token is written as `"$accent"` and follows the host's theme. + +Images and embedded fonts are **named assets**. In C# an image gets its name with `ImageSource.Png(bytes).WithName("logo")`; +unnamed images are exported as `image-1`, `image-2`, fonts as `font-`. + +**Theme tokens.** A colour or font that comes from the theme is a token: in C# `Color.Token("accent", +Color.FromHex("1F4E79"))` or `FontFace.Token("heading", new FontFace("Source Serif 4"))`, in JSON `"$accent"` wherever a +colour or font goes, with the values in the `theme` section: + +```json +"theme": {"colors": {"accent": "#1F4E79", "line": "#D4D4D4"}, "fonts": {"heading": "Source Serif 4"}}, +"styles": {"paragraph": {"SectionHeading": {"font": "$heading", "color": "$accent"}}} +``` + +A host replaces values on import (`TemplateJsonImportOptions.Theme`, for example a customer's accent colour), so a +customer's JSON keeps working when the brand changes. A colour token takes a colour (anything else is TB9200); a token the +definition does not have is not used, and the build warns (TB9205), so one palette can serve many definitions. + +### Agent API + +A host lets an agent (its own chat, or a customer's agent through the host's MCP server) change a customer's +definition. Templify provides the functions behind such tools; storage, authentication, chat, the MCP server and PDF +conversion stay with the host. + +| Host tool | Function | What it gives | +|---|---|---| +| describe | `TemplateJson.Describe(new TemplateJsonDescribeOptions { Components = …, Data = … })` | every JSON construct with where it is written, its keys and an example; the value forms; the host's components with their parameters; the data paths | +| schema | `TemplateJson.Schema(components)` | JSON Schema (draft 2020-12) of the format, for editors and agents that validate on their side | +| outline | `TemplateJson.Outline(json)` | every block, row, cell, list item and elseIf branch with its JSON pointer, kind, a short label and depth | +| read | `TemplateJson.Read(json, "/content/3/blocks/1")` | one part by JSON pointer | +| patch | `TemplateJson.Patch(json, patch, importOptions, buildOptions)` | applies a JSON Patch (RFC 6902) all or nothing and checks the result like `TemplateInspector.CheckDefinition`; save `Json` when `Check.Status` is Ok | +| preview | `TemplateJson.Preview(json, importOptions, buildOptions, dataJson)` | the filled DOCX/ODT and its text; convert the document to PDF on the host | + +```csharp +TemplatePatchResult result = TemplateJson.Patch(stored, patchFromAgent, new TemplateJsonImportOptions +{ + Data = DataCatalog.From(), + Components = components, + Assets = assets, +}, buildOptions); +if (result.Applied && result.Check.Status == TemplateCheckStatus.Ok) +{ + Save(customer, result.Json); +} +else +{ + return result.Check.Problems; // codes, messages and JSON pointers for the agent's next attempt +} +``` + +Export the definitions a host stores with `TemplateJsonExportOptions.TextLanguages`, so their `[[key]]` texts are in +the JSON and an agent can read and change them; without, the texts come from the host's catalogue and the agent only +sees the keys. + +A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` into its own child) +changes nothing and reports TB9207 at the operation (`/1` is the second). The description and the schema are generated +from one vocabulary that a test compares with the reader, so they always describe what the import accepts. + +## Testing your definitions + +The builder generates templates at runtime, so a definition is verified in your CI. Use the test kit +`TriasDev.Templify.Builder.Testing`, which works with any test framework: + +```csharp +[Fact] +public void OrderConfirmation_IsValid() => TemplateVerifier.VerifyAll( + () => new OrderConfirmation(theme), + new TemplateVerificationOptions + { + Languages = [CultureInfo.GetCultureInfo("de-DE"), CultureInfo.GetCultureInfo("en-GB")], + Texts = _ => SampleTexts.Catalog, + SampleData = [File.ReadAllText("sample-data.json")], + }); +``` + +`VerifyAll` builds every language and format. It fails, listing every problem, when the build fails, +`ValidateTemplate` reports errors, the contract's witness does not fill cleanly, a sample does not fill without +missing variables and warnings, a DOCX fails the schema validation or an ODT the package checks, a second build +(also under the tr-TR and ar-SA cultures) gives different bytes, or the languages and formats have different +contracts. + +`TemplateSnapshot.Create(template)` returns a text dump for golden tests. It shows paragraphs with their styles, +markers, tables, lists, headers and footers, in the same notation for DOCX and ODT. `LibreOfficeConverter` converts +templates and filled documents with a local LibreOffice. + +## Support matrix + +| Target | Supported | +|---|---| +| DOCX in Microsoft Word (Windows, Mac) | yes | +| DOCX in LibreOffice (including conversion to PDF) | yes | +| ODT in LibreOffice | yes | +| ODT in Word | best effort, not tested | + +Known behaviour of the applications: + +- **Table of contents.** Word builds a DOCX table of contents when it opens the document (fill with + `UpdateFieldsOnOpen = UpdateFieldsOnOpenMode.Auto`). Converters that refresh indexes on load (for example + Stirling-PDF) build it from DOCX and ODT; a plain `soffice --convert-to pdf` does not. The build reports warning + TB9001. Entry styles (`toc.Level(level, style)`) become Word's "toc 1" … "toc 9" in DOCX, based on the chosen style + (LibreOffice reads them as "Contents N"), and the entry templates' styles in ODT; both lay out alike. DOCX has one entry + style per level for the whole document: two tables of contents must agree (TB8003), a table of contents that sets + none uses the others' in both formats, and a user style must not take the id `TOCn` or the name "toc n" of a styled + level (TB2001, TB2002). An entry style must not be a heading (TB8002). +- **Word's built-in style names.** LibreOffice maps a DOCX style named like a Word built-in (`Body Text`, + `Heading 1`) to its own style when it opens the file. Choose your own display names ("Body Copy"). +- **Embedded fonts.** LibreOffice uses embedded fonts from DOCX and ODT, also when converting to PDF. Word uses + them from DOCX too (not tested automatically). +- **Cell padding.** With a 1 pt border, cell text in DOCX and ODT can be up to 2 pt apart in LibreOffice. +- **Space at the top of a page after a page break.** LibreOffice drops the space before of the paragraph that follows + a page break when it opens a DOCX, but not in an ODT. The ODT therefore says it: the first paragraph, table or rule + after a break, and the first one of every branch of a conditional there, has no space before. Not inside a loop + (every copy would lose it) and not in a table cell (LibreOffice ignores a break there). Content that only becomes + first because filling removed what came before it keeps its space in ODT. +- **Table indent in DOCX.** The builder writes no Word compatibility mode, so Word and LibreOffice use the legacy + table layout, in which `tblInd` places the first cell's text; the builder adds the left cell margin so the table's + edge sits at the indent. Word in a newer compatibility mode would place the table one cell margin further right. + +## Known limits + +- **Comparison operands in uploaded copies.** A path that an edited copy uses only as a comparison operand + (`{{#if order.priority = "high"}}`) is not reported as unknown by `TemplateInspector.Check`. The engine treats an unresolved + operand as a string literal ([#271](https://github.com/TriasDev/templify/issues/271)). +- **Condition variables are read from a message.** The check of stored templates reads the variable of a missing-condition-variable + warning from its message text until the engine exposes it + ([#275](https://github.com/TriasDev/templify/issues/275)). +- **What the check of stored templates cannot see.** The engine's validation checks every branch and, since Templify + #299, the whole path of a loop item (`{{line.product.name}}`), in values and conditions. Only a loop over a value + instead of a collection is found by the trial fill alone, so only in the branches data of the catalogue's shape takes + (its values are the text `x`, so `{{#if order.status = "paid"}}` is false). +- **No location for unknown value paths.** `Check` names the path of a TB9301 problem but not its place in the + document; the engine does not report locations of missing variables yet. +- **Implicit names inside loops.** Inside a loop the engine also resolves names on the current item, so a root path + such as `order.number` resolves to the item's `order` property if the item has one. The builder cannot see the data. + The guards are the data contract and the item names a definition chooses. A root path whose first segment is the + name of an enclosing loop's item is a build error (TB4003). +- **Raw blocks** are not checked beyond their root element. The DOCX schema validation in the test kit covers them. diff --git a/docs/superpowers/plans/2026-10-03-project-structure.md b/docs/superpowers/plans/2026-10-03-project-structure.md index db6c68f4..2575deaf 100644 --- a/docs/superpowers/plans/2026-10-03-project-structure.md +++ b/docs/superpowers/plans/2026-10-03-project-structure.md @@ -25,9 +25,9 @@ xUnit v3 through VSTest, GitHub Actions, release-please, MkDocs. frameworks, package ID, namespaces. - `Version` and `PackageValidationBaselineVersion` stay in `src/TriasDev.Templify/TriasDev.Templify.csproj`. - `docs/archive/**` and `docs/superpowers/**` (other than this plan and its spec) are not edited. -- Run all commands from the repository root `/Users/vaceslavustinov/Documents/work/triasdev/templify`. +- Run all commands from the repository root ``. - Scratch files (baseline packages, test logs) go to - `/private/tmp/claude-501/-Users-vaceslavustinov-Documents-work-triasdev-templify/10f81cd0-4b6d-459a-b6a1-298912a1a9f2/scratchpad` + `` (written below as `$SCRATCH`; set `SCRATCH=` in each shell). ## Review Focus @@ -56,7 +56,7 @@ xUnit v3 through VSTest, GitHub Actions, release-please, MkDocs. - [ ] **Step 1: Pack the current layout** ```bash -SCRATCH=/private/tmp/claude-501/-Users-vaceslavustinov-Documents-work-triasdev-templify/10f81cd0-4b6d-459a-b6a1-298912a1a9f2/scratchpad +SCRATCH= mkdir -p $SCRATCH/baseline dotnet pack TriasDev.Templify/TriasDev.Templify.csproj -c Release -p:ContinuousIntegrationBuild=true -o $SCRATCH/baseline unzip -l $SCRATCH/baseline/TriasDev.Templify.1.9.0.nupkg | awk 'NR>3 {print $4}' | grep -v '^$' | sort > $SCRATCH/baseline/files.txt @@ -520,7 +520,7 @@ project reference; `tests/TriasDev.Templify.Tools.Tests` keeps `TargetFramework` - [ ] **Step 5: Verify restore, build, tests and package equivalence** ```bash -SCRATCH=/private/tmp/claude-501/-Users-vaceslavustinov-Documents-work-triasdev-templify/10f81cd0-4b6d-459a-b6a1-298912a1a9f2/scratchpad +SCRATCH= dotnet restore --locked-mode dotnet build -c Release -p:ContinuousIntegrationBuild=true 2>&1 | tail -3 dotnet test -c Release --no-build 2>&1 | grep -E "^(Passed|Failed)!" @@ -641,7 +641,7 @@ Expected: no `BROKEN` lines. ```bash git grep -nP '(? mkdocs build --strict -d $SCRATCH/site 2>&1 | grep -iE "warn|error|built" ``` @@ -676,7 +676,7 @@ Expected: 0 warnings / 0 errors; `format-exit=0`. - [ ] **Step 2: All tests, compared with the baseline** ```bash -SCRATCH=/private/tmp/claude-501/-Users-vaceslavustinov-Documents-work-triasdev-templify/10f81cd0-4b6d-459a-b6a1-298912a1a9f2/scratchpad +SCRATCH= dotnet test -c Release --no-build 2>&1 | grep -E "^(Passed|Failed)!" | sed -E 's/Duration: [^-]+- //' | sort > $SCRATCH/after/tests.txt diff $SCRATCH/baseline/tests.txt $SCRATCH/after/tests.txt && echo TESTS-SAME ``` @@ -694,12 +694,12 @@ Expected: all passed, `Skipped: 0`. Note the count for the PR description. - [ ] **Step 4: Converter scripts** ```bash -SCRATCH=/private/tmp/claude-501/-Users-vaceslavustinov-Documents-work-triasdev-templify/10f81cd0-4b6d-459a-b6a1-298912a1a9f2/scratchpad +SCRATCH= sample=$(git ls-files 'examples/templates/*.docx' | head -1); cp "$sample" $SCRATCH/sample.docx -(cd $SCRATCH && /Users/vaceslavustinov/Documents/work/triasdev/templify/scripts/validate.sh sample.docx; echo exit=$?) -(cd $SCRATCH && /Users/vaceslavustinov/Documents/work/triasdev/templify/scripts/analyze.sh sample.docx --output report.md; echo exit=$?) -(cd $SCRATCH && /Users/vaceslavustinov/Documents/work/triasdev/templify/scripts/clean.sh sample.docx --output cleaned.docx; echo exit=$?) -(cd $SCRATCH && /Users/vaceslavustinov/Documents/work/triasdev/templify/scripts/convert.sh sample.docx --output converted.docx; echo exit=$?) +(cd $SCRATCH && /scripts/validate.sh sample.docx; echo exit=$?) +(cd $SCRATCH && /scripts/analyze.sh sample.docx --output report.md; echo exit=$?) +(cd $SCRATCH && /scripts/clean.sh sample.docx --output cleaned.docx; echo exit=$?) +(cd $SCRATCH && /scripts/convert.sh sample.docx --output converted.docx; echo exit=$?) ``` Expected: each script starts the converter (no "project file does not exist"); `exit=0` for each. diff --git a/docs/superpowers/plans/2026-11-25-builder-phase3-json-and-typed-data.md b/docs/superpowers/plans/2026-11-25-builder-phase3-json-and-typed-data.md new file mode 100644 index 00000000..78473ffc --- /dev/null +++ b/docs/superpowers/plans/2026-11-25-builder-phase3-json-and-typed-data.md @@ -0,0 +1,299 @@ +# Builder phase 3: JSON definitions and typed data paths — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Export fluent C# template definitions to JSON and import them back into the builder's model with byte-identical DOCX/ODT output, and let definitions take data paths from C# types (`d.Path(o => o.Order.Number)`). + +**Architecture:** A JSON writer walks the builder's semantic model (`DocumentModel` before writing) and emits a stable, readable JSON document; an importer is an `ITemplateDefinition` whose `Compose` replays the JSON through the existing composers, so every rule is checked once. Typed paths are a generic wrapper `TemplatePath` built from expression trees that converts to the existing `TemplatePath`, so everything downstream is unchanged. + +**Tech Stack:** C# / .NET 11+10, `System.Text.Json` (`Utf8JsonWriter`, `JsonDocument`), `System.Linq.Expressions`, xUnit v3. + +**Spec:** `docs/superpowers/specs/2026-11-25-builder-phase3-json-and-typed-data-design.md` (approved 2026-11-25). Parent: `docs/superpowers/specs/2026-11-25-template-builder-design.md`. + +## Global Constraints + +- Work on `feature/builder` only; one worktree per task (`git worktree add -b feat/p3-- ../templify-p3- feature/builder`, then `dotnet restore templify.slnx`). Another agent uses the main checkout. +- Gate every merge with `$S/check.sh ` (format, locked restore, CI-mode build, all tests). `$S` = the session scratchpad. Merge with `git -C ../templify-builder merge --ff-only ` and `git push origin feature/builder`. Do **not** use `finish.sh` (it would tick #274 in the epic early). No PRs, no NuGet. +- Commits reference `#274`, Conventional Commits with scope `builder`; changes to shared files (solution, CLAUDE.md, CI) go in separate `build`/`docs` commits. +- No new package dependency. JSON only (no YAML). +- Public API changes are additive and declared in `src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt` (extract RS0016 symbols, as in phase 2). +- Existing behaviour is unchanged: every existing builder test and the sample's bytes stay as they are. +- Determinism: export of the same definition and options gives the same JSON text; numbers and lengths formatted with `CultureInfo.InvariantCulture`. +- Every new builder construct delivers DOCX **and** ODT and keeps the test kit's invariants (`BuilderHarness.AssertInvariants`). +- Respond to the maintainer in Russian; code, docs and commits in English. + +## Review Focus + +1. **A path in JSON that names an enclosing loop item vs. the data root** (`line.x` inside `forEach … as line`, `line.x` outside it) — import must resolve exactly like the fluent API (LoopItem vs root, TB4001/TB4003), not silently treat it as a root path. Test in Task 5. +2. **Hand-written JSON with legal-but-unusual forms** (shorthand string paragraph vs. object, lengths in `mm` vs `pt`, lower-case colour hex) — the reader accepts every form the writer could emit and the documented shorthands; re-export normalises them. Test in Task 4. +3. **Many errors in one file** (three bad blocks, one unknown component) — one exception listing all of them with distinct JSON pointers, not the first only. Test in Task 6. +4. **Typed expressions the walker cannot map** (`o => o.Lines.First().X`, `o => o.Name.ToUpper()`, a captured variable index `o.Lines[i]`) — `ArgumentException` naming the expression, never a wrong path. Test in Task 7. +5. **A data type whose JSON names differ from C#** (`[JsonPropertyName("cust")]`, snake_case policy) — typed paths and the data catalogue use the data's names, so the filled document is correct. Test in Tasks 7 and 9. + +--- + +## File structure + +New (library, namespace in brackets): + +- `src/TriasDev.Templify.Builder/Json/TemplateJson.cs` — public entry: `Export`, `Import` (`…Builder.Json`). +- `src/TriasDev.Templify.Builder/Json/TemplateJsonDocument.cs`, `TemplateJsonImportOptions.cs` — public results/options. +- `src/TriasDev.Templify.Builder/Json/JsonValues.cs` — internal: lengths, colours, page sizes, formats, paths ↔ text. +- `src/TriasDev.Templify.Builder/Json/ConditionParser.cs` — internal: Templify condition text → `Condition`. +- `src/TriasDev.Templify.Builder/Json/ModelJsonWriter.cs` — internal: `DocumentModel` → JSON. +- `src/TriasDev.Templify.Builder/Json/JsonDefinition.cs` — internal `ITemplateDefinition` that composes from JSON. +- `src/TriasDev.Templify.Builder/Json/JsonDiagnostics.cs` — internal: pointer tracking, collected import errors. +- `src/TriasDev.Templify.Builder/Components/ComponentCatalog.cs` — public registry (`…Builder`). +- `src/TriasDev.Templify.Builder/Typed/TemplatePathOfT.cs`, `TemplateCollection.cs`, `LoopItemOfT.cs`, `PathExpression.cs` — typed paths (`…Builder`). +- `src/TriasDev.Templify.Builder/Typed/DataCatalog.cs` — public data catalogue (`…Builder`). + +Modified: `Model/DocumentModel.cs` (ListBlock), `Lists.cs`, `BlockComposer.cs`, `Images.cs` (`ImageFit.Exact`), `BuildDiagnostic.cs` (Location), `BuildContext.cs`, `TemplateBuilder.cs`, `TemplateComposer.cs`, `Tables.cs`, `Lists.cs`, `DataContract.cs`. + +Tests (flat, namespace `TriasDev.Templify.Builder.Tests`): `JsonValuesTests.cs`, `ConditionParserTests.cs`, `JsonExportTests.cs`, `JsonImportTests.cs`, `JsonDiagnosticsTests.cs`, `ComponentCatalogTests.cs`, `TypedPathTests.cs`, `DataCatalogTests.cs`; `BuilderHarness.cs` gains the round-trip invariant; `SampleTests.cs` extended. + +Sample: `samples/TriasDev.Templify.Builder.Sample/` gains `OrderData.cs`, `TypedOrderConfirmation.cs`, and a `phase3` mode in `Program.cs`/`SampleRunner.cs`. + +--- + +### Task 1: Model and API groundwork (no output change) + +**Files:** +- Modify: `src/TriasDev.Templify.Builder/Model/DocumentModel.cs`, `Lists.cs`, `BlockComposer.cs` (List), `Images.cs`, `BuildDiagnostic.cs`, `BuildContext.cs` +- Test: `tests/TriasDev.Templify.Builder.Tests/ListTests.cs`, `ImageTests.cs`, `DefinitionErrorTests.cs` + +**Interfaces:** +- Produces: `internal sealed record ListBlock(ListStyleKey Style, List Items) : Block` — the list's items (paragraphs with `ListItemInfo`, and `LoopBlock`/`ConditionalBlock` over items). `BlockTree.All`/`Children` and `BlockFlattener.Flatten` expand it to its items, so writers and the contract see exactly what they see today. +- Produces: `public static ImageFit ImageFit.Exact(Length width, Length height)` (both positive; the image is drawn at exactly that size). +- Produces: `public string? BuildDiagnostic.Location { get; init; }` (JSON pointer or null). Keep the positional record constructor `(Code, Message)`. +- Produces: `internal void BuildContext.Error(string code, string message, string? location)` overload; existing overload passes `null`. + +- [ ] **Step 1: Write failing tests** + - `ListTests.List_IsOneBlockInTheModel`: compose `c.List(bullets, l => { l.Item("a"); l.ForEach(path, "x", …); })` through an internal helper that returns the composed body (`BlockComposer` internal ctor); assert body is `[ListBlock]` with 2 items. + - `ImageTests.Exact_DrawsAtThatSize` (both formats): `Image(png, "a", ImageFit.Exact(30.Pt(), 10.Pt()))` → DOCX `wp:extent cx=381000 cy=127000`, ODT `svg:width="30pt" svg:height="10pt"`; `ImageFit.Exact(0.Pt(), 1.Pt())` throws `ArgumentOutOfRangeException`. + - `DefinitionErrorTests.Diagnostic_LocationIsNullForCSharp`: every error of an existing failing C# definition has `Location == null`. +- [ ] **Step 2: Run; expect compile failures / FAIL.** `dotnet test tests/TriasDev.Templify.Builder.Tests --filter "FullyQualifiedName~ListTests|FullyQualifiedName~ImageTests|FullyQualifiedName~DefinitionErrorTests"` +- [ ] **Step 3: Implement** `ListBlock` (ListComposer writes into it; `BlockComposer.List` adds one `ListBlock`), the flatten/tree expansion, `ImageFit.Exact`, `Location`. +- [ ] **Step 4: Run the whole builder suite; all pass, and `SampleTests` (byte expectations via snapshots) unchanged.** `dotnet test tests/TriasDev.Templify.Builder.Tests` +- [ ] **Step 5: Declare API, `check.sh`, commit** `refactor(builder): list container in the model, ImageFit.Exact, diagnostic locations (#274)`, merge, push. + +### Task 2: JSON value encodings + +**Files:** +- Create: `src/TriasDev.Templify.Builder/Json/JsonValues.cs` +- Test: `tests/TriasDev.Templify.Builder.Tests/JsonValuesTests.cs` + +**Interfaces:** +- Produces (internal static class `JsonValues`): + - `string Length(Length value)`; `bool TryLength(string text, out Length value)` — writer rule: whole or half points → `"10pt"`/`"10.5pt"`; else if a value with ≤ 2 decimals in mm round-trips to the same millipoints → `"25mm"`; else points with 3 decimals. Reader accepts `pt`, `mm`, `cm`, `in`. + - `string Color(Color value)` → `"#1F4E79"`; `bool TryColor(string, out Color)` accepts upper/lower case. + - `string? PageSizeName(PageSize)` (`A4`, `A5`, `Letter`, `Legal`) / `bool TryPageSize(string, out PageSize)`; non-named sizes are written as `{ "width": …, "height": … }`. + - `string Border(BorderLine)` → `"0.5pt #D4D4D4"`; `bool TryBorder(string, out BorderLine)`. + - `string Box(Length top, Length right, Length bottom, Length left)` → 1, 2 or 4 values CSS-style (`"3pt 5pt"`); `bool TryBox(...)`. + +- [ ] **Step 1: Failing tests** (`[Theory]` tables): `10.Pt()`→`"10pt"`, `10.5.Pt()`→`"10.5pt"`, `25.Mm()`→`"25mm"`, `12.5.Mm()`→`"12.5mm"`, `Length.FromPoints(10.123)`→`"10.123pt"`; every written value parses back to the same `Length`; `"1in"`→72pt; `"#abcdef"` parses; `"12"`/`"pt"`/`"#12345"` fail; `PageSize.A4`→`"A4"`; box forms `"3pt"`, `"3pt 5pt"`, `"1pt 2pt 3pt 4pt"`. Run under tr-TR and ar-SA current culture (`[Fact]` that sets `CultureInfo.CurrentCulture`) — same strings. +- [ ] **Step 2: Run; FAIL.** `--filter FullyQualifiedName~JsonValuesTests` +- [ ] **Step 3: Implement `JsonValues`.** +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: `check.sh`, commit** `feat(builder): JSON value encodings (#274)`, merge, push. + +### Task 3: Condition parser + +**Files:** +- Create: `src/TriasDev.Templify.Builder/Json/ConditionParser.cs` +- Test: `tests/TriasDev.Templify.Builder.Tests/ConditionParserTests.cs` + +**Interfaces:** +- Consumes: `Condition` AST types in `Condition.cs` (`TruthCondition`, `ComparisonCondition`, `InCondition`, `PostfixCondition`, `NotCondition`, `LogicalCondition`), `ConditionText` emitter. +- Produces: `internal static Condition ConditionParser.Parse(string text, Func resolvePath)` — throws `FormatException` with the 0-based column on error. `resolvePath` maps a path's text (as written, including `[keyword]` escapes and `@index`) to a `TemplatePath` with the right loop scope (Task 5 supplies it). +- Grammar = what the emitter writes: `or` < `and` < `not` < comparison (`= != > >= < <=`, `in (…)`, `contains`, `startswith`, `endswith`) < postfix (`exists`, `is empty`, `is not empty`); parentheses; literals are double-quoted strings (with `\"`/`\\`) or invariant numbers. A bare word on the right of a comparison is an error: "quote the literal". + +- [ ] **Step 1: Failing tests.** + - Round trip: for a `[Theory]` of conditions built with the C# API (truth, each comparison, `In`, `Contains`, each postfix, `!`, nested `&`/`|` with parentheses, keyword-escaped segments, a decimal literal `0.5`, a string with `"` and `\`), `Parse(c.ToString(), Root).ToString() == c.ToString()`. + - Errors: `"a >"` (column 3), `"a = b"` (message contains `quote`), `"(a"`, `"a and"`, `""` → `FormatException`. + - `Condition.Raw` is **not** parsed: covered in Task 4 as its own JSON form. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement** a small recursive-descent / precedence-climbing parser over a tokenizer. +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: `check.sh`, commit** `feat(builder): condition parser for JSON definitions (#274)`, merge, push. + +### Task 4: Export (model → JSON) and the public entry points + +**Files:** +- Create: `Json/ModelJsonWriter.cs`, `Json/TemplateJson.cs`, `Json/TemplateJsonDocument.cs` +- Modify: `TemplateBuilder.cs` (expose an internal `Compose(definition, options) → (DocumentModel, BuildContext)` used by both `Build` and `Export`) +- Test: `JsonExportTests.cs` + +**Interfaces:** +- Produces (public, namespace `TriasDev.Templify.Builder.Json`): + - `static class TemplateJson { static TemplateJsonDocument Export(ITemplateDefinition definition, TemplateBuildOptions options, ComponentCatalog? components = null); static ITemplateDefinition Import(string json, TemplateJsonImportOptions? options = null); }` (`Import` lands in Task 5; `components` is honoured from Task 8; until then it may be ignored). + - `sealed class TemplateJsonDocument { string Json { get; } IReadOnlyDictionary Assets { get; } }` — asset keys `"sha256:"`. +- Export runs `Compose` (same checks as `Build`; a definition that does not build throws `TemplateBuildException`), then writes. `options.Format` does not influence the JSON. +- JSON shape (spec §4.1), fixed key order, 2-space indented, `\n` line ends: + - top: `templifyDefinition` (1), `identity` {id, version}, `language`, `properties`, `styles`, `page`, `content`. + - `styles`: `defaults`, `paragraph`, `character`, `table`, `box`, `list` — each keyed by style id, values only for properties that are set; `name` = display name. + - blocks: `paragraph` (string shorthand when it has no style, no list info and one plain `TextInline`), `pageBreak: true`, `if`/`then`/`elseIf[{when,then}]`/`else`, `forEach`/`as`/`body`, `table` {style, columns, spaceAfter, rows}, `box` {style, content}, `rule` {line, spaceAbove, spaceBelow}, `list` {style, items}, `image` (block form), `toc` {maxLevel}, `raw` {docx, odt, uses}, `component` (Task 8; until then expanded as `{ "group": [...] }` with `"from": ""`). + - rows: `{ "row": { "header": true?, "allowSplit": true?, "cells": [...] } }`, `{ "forEachRow": path, "as": name, "rows": [...] }`, `{ "rowsIf": cond, "then": [...], "elseIf": [...], "else": [...] }`; cells: `{ "span"?, "background"?, "align"?, "content": [blocks] }`. + - list items: `{ "item": { "level"?: n, "content": … } }`, `forEach`/`if` with item bodies. + - inlines (`content` string shorthand for one plain text): `{ "text", "style"? }`, `{ "value": path, "format"?, "style"? }`, `{ "tab": true }`, `{ "tabRight": true }`, `{ "lineBreak": true }`, `{ "pageNumber": true, "style"? }`, `{ "pageCount": true, "style"? }`, `{ "image": "sha256:…", "alt", "width", "height" }`, `{ "if": cond, "then": [inlines], "elseIf", "else" }`, `{ "expression": cond, "format"? }`. + - conditions: the condition text; `Condition.Raw` → `{ "raw": expr, "uses": [paths] }`. + - raw blocks: `{ "raw": { "docx": "", "odt": "", "uses": [...] } }` — the XML snapshot is taken by calling the factories with `RawContext` whose `Frame` is the page frame width (documented limit: an imported raw block does not see its real container width). + - embedded fonts: `"font": { "family": "...", "embedded": "sha256:…" }`; plain fonts as the family string. +- [ ] **Step 1: Failing tests.** + - `Export_WalkingSkeleton_IsThisJson`: a one-paragraph definition with a value → assert the exact JSON text (golden string in the test). + - `Export_IsDeterministic` (both formats' options, tr-TR current culture): two exports → equal text; `Format` = DOCX vs ODT → equal text. + - `Export_CoversEveryBlock`: one definition using every block and inline kind (reuse the sample's `OrderConfirmation`) → parse the JSON with `JsonDocument` and assert each kind's key occurs (`paragraph`, `if`, `forEach`, `table`, `forEachRow`, `rowsIf`, `box`, `rule`, `list`, `image`, `toc`, `raw`, `expression`, `tabRight`, `pageNumber`), and `Assets` holds the logo under `sha256:`. + - `Export_FailingDefinition_Throws`: undefined style → `TemplateBuildException` with TB2010. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement** `ModelJsonWriter` with `Utf8JsonWriter` (`Indented = true`, `Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping` so umlauts and `€` stay readable) and `TemplateJson.Export`. +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): export definitions to JSON (#274)`, merge, push. + +### Task 5: Import (JSON → definition) with the round-trip invariant + +**Files:** +- Create: `Json/JsonDefinition.cs`, `Json/TemplateJsonImportOptions.cs` +- Modify: `Json/TemplateJson.cs` (Import), `tests/.../BuilderHarness.cs` +- Test: `JsonImportTests.cs` + +**Interfaces:** +- Consumes: `ConditionParser.Parse` (Task 3), `JsonValues` (Task 2), the JSON shape (Task 4), all composers. +- Produces (public): `sealed class TemplateJsonImportOptions { IReadOnlyDictionary? Assets { get; init; } ComponentCatalog? Components { get; init; } DataCatalog? Data { get; init; } bool AllowRawXml { get; init; } }` (`Components` used from Task 8, `Data` from Task 9). +- Produces: `TemplateJson.Import` returns an `ITemplateDefinition` (`JsonDefinition`) whose `Identity` comes from the JSON and whose `Compose` replays the JSON through the composers: `template.Styles(StyleSheet.Create(...))`, `Properties`, `Page`, `Content`. The reader accepts the writer's forms and the shorthands; re-export of an import is the original text. +- Path resolution while composing: a stack of `(itemName, LoopItem)` from enclosing `forEach`/`forEachRow`/list `forEach`; a path whose first segment equals an enclosing item name → `loopItem[rest]` (or `loopItem.Self` for the bare name); `@index`/`@number`/`@count`/`@first`/`@last` → the innermost loop item's metadata; else `template.Data[path]`. Feed the same resolver to `ConditionParser`. +- Values: `ValueFormat.Custom(specifier)`; images via `ImageSource.FromBytes(assets[key])` + `ImageFit.Exact(width, height)`; embedded fonts via `FontFace.Embedded(family, assets[key])`. +- Raw blocks: refused unless `AllowRawXml` (Task 6 makes this a diagnostic; here: `NotSupportedException` is acceptable as a placeholder only if Task 6 replaces it — prefer to emit the Task 6 diagnostic code `TB9202` directly). +- Harness: `BuilderHarness.AssertInvariants` additionally exports the definition, imports it (`AllowRawXml = true`, the export's assets), builds with the same options and asserts `ContentHash` equality and that re-export gives the same JSON text. + +- [ ] **Step 1: Failing tests.** + - `Import_RoundTripsTheSample` (DOCX, ODT × de-DE, en-GB): `Build(Import(Export(OrderConfirmation))).ContentHash == Build(OrderConfirmation).ContentHash`; `Export(Import(...)).Json == first.Json`. + - `Import_AcceptsShorthandsAndAlternativeForms`: hand-written JSON with `"paragraph": "Hi"`, `{ "paragraph": { "content": "Hi" } }`, `"25mm"`, `"70.866pt"`, `"#1f4e79"` builds; re-export normalises (Review Focus 2). + - `Import_ResolvesLoopItemsLikeTheFluentApi`: JSON `forEach order.lines as line` with `value: line.description` and `@number` fills `{"order":{"lines":[{"description":"A"}]}}` to `"1 A"`; the same `line.description` outside the loop is a **root** path `line.description` (contract entry `line.description`), matching what `template.Data["line"]["description"]` would do (Review Focus 1). + - Harness change: the whole builder suite passes with the round-trip invariant on. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement `JsonDefinition` and `Import`; extend the harness.** +- [ ] **Step 4: Run the full builder suite; PASS.** Any test whose definition cannot round-trip is a bug in Task 4/5, not a reason to skip the invariant. +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): import JSON definitions; every builder test round-trips (#274)`, merge, push. + +### Task 6: Import diagnostics + +**Files:** +- Create: `Json/JsonDiagnostics.cs` +- Modify: `Json/JsonDefinition.cs`, `Json/TemplateJson.cs`, `TemplateBuilder.cs` (post-compose checks look up block → pointer), `BuildContext.cs` +- Test: `JsonDiagnosticsTests.cs` + +**Interfaces:** +- Produces codes (in `DiagnosticCodes`): `TB9200` malformed or unexpected JSON (structure, unknown key or kind, wrong value type, unknown asset, unsupported `templifyDefinition` version), `TB9201` invalid value (a composer threw `ArgumentException`), `TB9202` raw XML not allowed. +- `Import` parses the whole document first and throws one `TemplateBuildException` with every `TB9200`/`TB9202` (each with `Location` = JSON pointer, e.g. `/content/3/table/rows/1/row/cells/0`). +- During `Compose`, `JsonDefinition` keeps the current pointer in `BuildContext` (internal `string? CurrentLocation`); `BuildContext.Error` without an explicit location uses it. Per element: `try { compose } catch (ArgumentException e) { context.Error(TB9201, e.Message, pointer); }` and continue with the next sibling. +- Post-compose checks: `JsonDefinition` records `model block → pointer` in an internal `ConditionalWeakTable` on the context; `CheckStylesAreDefined` and `TableLayout.Check` pass the looked-up pointer as location. + +- [ ] **Step 1: Failing tests.** + - `Import_ReportsEveryStructuralProblemAtOnce`: JSON with an unknown block kind at `/content/1`, a wrong type at `/content/2/paragraph/style`, an unknown asset at `/content/4/image` and an unknown component → one `TemplateBuildException`, 4 errors, those pointers, codes TB9200 (Review Focus 3). + - `Import_ComposerArgumentErrors_BecomeTB9201`: list item `level: 12` and `rule.line: "0pt #000000"` → at `Build`, two TB9201 errors with their pointers; the rest of the document still composed (assert a later undefined-style error TB2010 also reported, with pointer). + - `Import_RawXml_RefusedByDefault`: TB9202 at the raw block's pointer; with `AllowRawXml = true` builds. + - `Import_InvalidJsonText`: `"{"` → TB9200, `Location = ""`, message includes line/position. + - `Import_UnknownVersion`: `templifyDefinition: 2` → TB9200. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run; PASS** (and the full suite). +- [ ] **Step 5: `check.sh`, commit** `feat(builder): import diagnostics with JSON pointers (#274)`, merge, push. + +### Task 7: Typed data paths + +**Files:** +- Create: `Typed/TemplatePathOfT.cs`, `Typed/TemplateCollection.cs`, `Typed/LoopItemOfT.cs`, `Typed/PathExpression.cs` +- Modify: `TemplateComposer.cs`, `BlockComposer.cs`, `Tables.cs` (`TableComposer`/`RowsComposer.ForEachRow`), `Lists.cs` (`ListComposer.ForEach`) +- Test: `TypedPathTests.cs` + +**Interfaces:** +- Produces (public, namespace `TriasDev.Templify.Builder`): + - `TemplateComposer.Data(JsonNamingPolicy? naming = null) → TemplatePath` (root; default naming camelCase; `[JsonPropertyName]` wins). + - `readonly struct TemplatePath`: `TemplatePath Path(Expression> member)`; `TemplateCollection Items(Expression>> member)`; implicit conversions to `TemplatePath` and `Condition`; operators `!`, `&`, `|` (with `TemplatePath`, `TemplatePath`, `Condition`); the condition helpers of `TemplatePath` forwarded (`Eq`, `NotEq`, `Gt`, `Ge`, `Lt`, `Le`, `In`, `Contains`, `StartsWith`, `EndsWith`, `Exists`, `IsEmpty`, `IsNotEmpty`); `ToString()` = the path text. + - `readonly struct TemplateCollection` (implicit to `TemplatePath`). + - `sealed class LoopItem`: `LoopItem Item { get; }`, `TemplatePath Self`, `Path(…)`, `Items(…)`, `Index`, `Number`, `Count`, `IsFirst`, `IsLast` (forwarded). + - Overloads: `BlockComposer.ForEach(TemplateCollection collection, string itemName, Action, BlockComposer> body)`; same for `TableComposer.ForEachRow`, `RowsComposer.ForEachRow`, `ListComposer.ForEach`. +- `PathExpression.Segments(LambdaExpression, JsonNamingPolicy)` (internal): member chains, `Convert` nodes, constant `int` indexers (`List` indexer / array index → `[n]`), constant `string` dictionary keys → a plain segment with the key text, exactly as `path["Theme"]` gives in the string API (Templify reads `settings.Theme` as a dictionary key); anything else → `ArgumentException("The expression 'o => …' cannot be turned into a data path: …")`. +- Typed paths produce the **same** `TemplatePath` values (same scope) as the string API, so the contract and output are identical. + +- [ ] **Step 1: Failing tests.** + - `Path_MapsMembersWithCamelCase`: `d.Path(o => o.Order.Customer.Name).ToString() == "order.customer.name"`. + - `Path_HonoursJsonPropertyNameAndPolicy`: `[JsonPropertyName("cust")]` → `order.cust.name`; `JsonNamingPolicy.SnakeCaseLower` on `IsExpress` → `order.is_express`; filling with matching JSON renders the value (Review Focus 5). + - `Path_ConstantIndexAndKey`: `o.Order.Lines[0].Description` → `order.lines[0].description`; dictionary `o.Settings["Theme"]` → `settings.Theme`, equal to `d["settings"]["Theme"]` in the string API. + - `Path_UnsupportedExpressions_Throw` (Theory): `o => o.Order.Lines.First().Description`, `o => o.Order.Number.ToUpper()`, `o => o.Order.Lines[i].Description` with captured `i` → `ArgumentException` whose message contains the expression text (Review Focus 4). + - `TypedLoop_ProducesTheSameBytesAsTheStringApi` (both formats): a definition with `ForEach(d.Items(o => o.Order.Lines), "line", (line, b) => b.Paragraph(x => { x.Value(line.Number); x.Value(line.Path(l => l.Description)); }))` vs. the string version → equal `ContentHash`. + - `TypedComponentParameter`: a component taking `TemplatePath
` composes `Address.Path(a => a.City)` → contract entry `order.customer.address.city`. + - `TypedConditions`: `d.Path(o => o.Order.IsExpress) & d.Path(o => o.Order.Total).Gt(1000)` emits `order.isExpress and order.total > 1000`. + - `TypedPaths_ScopeErrorsStillApply`: a captured `LoopItem` used after its loop → TB4001. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run; PASS** (full suite). +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): typed data paths from C# types (#274)`, merge, push. + +### Task 8: Component catalog (hybrid export) + +**Files:** +- Create: `Components/ComponentCatalog.cs` +- Modify: `Json/ModelJsonWriter.cs`, `Json/JsonDefinition.cs` +- Test: `ComponentCatalogTests.cs` + +**Interfaces:** +- Consumes: `TemplatePath` (Task 7), export/import (Tasks 4–6). +- Produces (public): `sealed class ComponentCatalog { ComponentCatalog Register(string name) where TComponent : ITemplateComponent; IReadOnlyCollection Names { get; } }`. +- A registrable component type has one public constructor; every parameter has a same-named readable property (records satisfy this) of an allowed type: `TemplatePath`, `TemplatePath`, `string`, `bool`, `int`, `long`, `double`, `decimal`, enums, `ParagraphStyleKey`/`CharacterStyleKey`/`BoxStyleKey`/`TableStyleKey`/`ListStyleKey` (written as id), `Length`, `Color`, nullable forms, and `IReadOnlyList<>` of those. `Register` throws `ArgumentException` naming the first offending parameter. Names: `[a-z][a-zA-Z0-9]*`, unique. +- Export: a `ComponentBlock` whose component's runtime type is registered → `{ "component": name, "params": { camelCaseParam: value } }`; otherwise `{ "group": [...], "from": "" }`. Paths in params are written relative to the component's call site exactly as the JSON paths elsewhere (loop item names apply). +- Import: `"component"` → `options.Components` must contain the name (else TB9200 at Import); construct via the constructor with parameters converted from JSON (paths through the loop-scope resolver; style keys looked up by id in the definition's own style sheet; else TB9200); then `c.Component(instance)`. `"group"` composes its blocks in place. + +- [ ] **Step 1: Failing tests.** + - `Register_RejectsUnserializableParameters`: a component with a `BrandTheme` parameter → `ArgumentException` naming it; a component without public ctor → `ArgumentException`. + - `Export_RegisteredComponent_IsAReference`: sample `AddressBlock` (made registrable in Task 10; use a test component here) → `{ "component": "address", "params": { "address": "order.customer.address" } }`; unregistered → `group` with `from`. + - `Import_ComponentReference_UsesCurrentComponentCode`: export with catalog, then import with a catalog whose `address` maps to a **changed** component type → the built document has the changed output (the hybrid's point). + - `RoundTrip_WithCatalog_IsByteIdentical` (both formats) for a definition using registered components inside a loop (params with loop-item paths). + - `Import_UnknownComponent`: TB9200 with pointer. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): component catalog; registered components export as references (#274)`, merge, push. + +### Task 9: Data catalogue and import check + +**Files:** +- Create: `Typed/DataCatalog.cs` +- Modify: `Json/JsonDefinition.cs` (Import-time path check) +- Test: `DataCatalogTests.cs` + +**Interfaces:** +- Produces (public): `sealed class DataCatalog { static DataCatalog From(JsonNamingPolicy? naming = null); static DataCatalog From(Type type, JsonNamingPolicy? naming = null); IReadOnlyList Entries { get; } bool Contains(string canonicalPath); }`; `sealed record DataCatalogEntry(string Path, DataKind Kind, Type ClrType)`; `enum DataKind { Value, Object, Collection, Open }`. +- Canonical paths as in `DataContract` (`order.lines[].description`). Values: primitives, `string`, `decimal`, `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, `Guid`, enums and their nullables. Collections: `IEnumerable` except `string`. `Open`: dictionaries, `object`, `JsonElement`, `JsonNode` — `Contains` accepts any path below. Recursion: a type already on the current branch is not expanded again (entry kept as `Object`), and depth is capped at 16. +- Import check (only when `options.Data` is set): every path the JSON uses (values, collections, conditions, component params, raw `uses`), canonicalised with the loop-scope stack, must be in the catalogue → else TB9203 "unknown data path" with pointer, at `Import` (with the other structural errors). Metadata paths (`@index` …) are exempt. + +- [ ] **Step 1: Failing tests.** + - `From_SampleData_ListsPaths`: `DataCatalog.From()` (test-local records mirroring the sample) contains `order.number` (Value), `order.lines` (Collection), `order.lines[].description` (Value), `order.customer.address.city`. + - `From_HonoursNaming`: `[JsonPropertyName]` and snake_case (Review Focus 5). + - `From_RecursiveType_Terminates`: `record Node(string Name, IReadOnlyList Children)` → contains `children[].name`, finishes. + - `From_OpenShapes`: a `Dictionary` property `extra` → `Contains("extra.anything.deep")`. + - `Import_PathOutsideCatalog_IsTB9203`: JSON with `value: order.nummer` and a condition `order.totl > 1` → two TB9203 with pointers; with the correct names → builds. + - `Contract_IsSubsetOfCatalog`: for the sample, every contract entry's path is in `DataCatalog.From()`. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): data catalogue from C# types; import checks paths against it (#274)`, merge, push. + +### Task 10: Sample, artefacts and evaluation + +**Files:** +- Create: `samples/TriasDev.Templify.Builder.Sample/OrderData.cs` (records matching `sample-data.json`), `TypedOrderConfirmation.cs` (same document via `template.Data()`, typed `TypedAddressBlock(TemplatePath
Address)`) +- Modify: `OrderConfirmation.cs` (`AddressBlock` becomes a registrable record `AddressBlock(TemplatePath Address)`), `SampleRunner.cs` (`RunPhase3(string outputDirectory, TextWriter log)`), `Program.cs` (`phase3 ` argument), `tests/.../SampleTests.cs`, design spec (evaluation section) + +**Interfaces:** +- Consumes: everything above. `SampleRunner.Components` = `new ComponentCatalog().Register("address")`. +- `RunPhase3` writes: `order-confirmation..json`, `assets/.png`, `order-confirmation..from-json.{docx,odt}` (template built from the imported JSON) and `.filled.{docx,odt}`, for de-DE and en-GB; logs sizes (bytes, lines, approximate tokens = bytes / 4) and asserts by exception that from-JSON bytes equal the C# bytes. + +- [ ] **Step 1: Failing tests** (`SampleTests`): + - `Phase3_JsonRoundTripIsByteIdentical`: for both languages and formats, `RunPhase3` succeeds and the from-JSON templates equal the C# templates (hash). + - `Typed_SampleProducesTheSameBytes`: `TypedOrderConfirmation` vs `OrderConfirmation`, both formats and languages → equal `ContentHash`; and `TemplateVerifier.VerifyAll` passes for the typed version with the sample data. + - `Phase3_Catalogue`: importing the exported JSON with `Data = DataCatalog.From()` builds. +- [ ] **Step 2: Run; FAIL.** +- [ ] **Step 3: Implement the sample changes.** +- [ ] **Step 4: Run; PASS; run** `dotnet run --project samples/TriasDev.Templify.Builder.Sample -- phase3 ~/Desktop/templify-builder-phase3` **and copy `OrderConfirmation.cs`, `TypedOrderConfirmation.cs`, `OrderData.cs` next to the output.** +- [ ] **Step 5: Evaluation.** Add a section "Phase 3 evaluation" to the phase 3 design spec: JSON sizes per language (bytes, lines, approximate tokens), the share taken by styles vs. content, three things that read well and three that are awkward in the JSON; the typed vs. string definition (line count, character count, what the lambdas cost in readability), and proposals for the next step. LibreOffice round trip of the from-JSON documents: `dotnet test tests/TriasDev.Templify.Builder.Tests -c Release --filter "Category=LibreOffice"` passes with 0 skipped. +- [ ] **Step 6: `check.sh`, commit** `feat(builder): phase 3 sample — JSON round trip and typed definition (#274)` and `docs(builder): phase 3 evaluation (#274)`, merge, push. Report to the maintainer (Russian) with the Desktop folder and the evaluation's key numbers. diff --git a/docs/superpowers/plans/2026-11-26-builder-compact-json.md b/docs/superpowers/plans/2026-11-26-builder-compact-json.md new file mode 100644 index 00000000..37d40768 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-compact-json.md @@ -0,0 +1,164 @@ +# Builder: compact JSON definitions — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make exported/imported JSON definitions compact and readable — placeholders inside strings, inherited paragraph styles (document default, table text styles), short forms for blocks/rows/cells/items, and a width-based layout — while C# → JSON → build stays byte-identical. + +**Architecture:** Style inheritance is a model feature: a post-compose pass in `TemplateBuilder.Compose` gives every unstyled paragraph its inherited style, so writers are untouched and the JSON writer can omit styles equal to the inherited one. The JSON reader/writer change shape in two steps (inline text, then blocks), each keeping the harness-wide round trip green; a final layout pass reformats the writer's compact output. + +**Tech Stack:** C# / .NET 11+10, `System.Text.Json`, xUnit v3. + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-compact-json-design.md` (approved 2026-11-26), amending section 4.1 of `docs/superpowers/specs/2026-11-25-builder-phase3-json-and-typed-data-design.md`. + +## Global Constraints + +- Work on `feature/builder` only; one worktree per task: `git worktree add -b feat/cj-- ../templify-cj- feature/builder`, then `dotnet restore templify.slnx`. Another agent uses the main checkout. +- Gate every merge with `$S/check.sh ` (`$S` = session scratchpad). Merge with `git -C ../templify-builder merge --ff-only `, `git push origin feature/builder`, remove the worktree and branch. Not `finish.sh`. No PRs, no NuGet. +- Conventional Commits, scope `builder`, reference `#274`; shared files (solution, CLAUDE.md, CI) in separate `build`/`docs` commits. +- Public API additions declared in `src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt`. +- `templifyDefinition` stays `1`; the reader accepts only the new shape (no phase 3 compatibility). +- Definitions without a default paragraph style and without table text styles build byte-identically to today. +- `BuilderHarness.AssertJsonRoundTrip` stays on for every builder test; it must pass after every task. +- Writer line width **100**; two-space indent; `", "` and `": "` separators on single lines; strings never wrapped. +- No `{{#if}}` / `{{#foreach}}` inside strings. `value` and `expression` inline objects are removed. +- Respond to the maintainer in Russian; code, docs, commits in English. + +## Review Focus + +1. **Hand-written placeholder strings at the edges** — `"{{"` unterminated, `"{{}}"`, `"{{a}}}"`, a lone `"}}"`, a format with colons (`{{order.date:date:HH:mm}}`): exactly one reading each (error with pointer, or the documented split at the first `:`). Tests in Task 2. +2. **Expressions whose condition contains `)`, `:` or `}` inside quoted strings** (`{{(order.status = "a):b"):yesno}}`) — paren matching honours quotes and escapes. Tests in Task 2. +3. **Nested scopes** — a table inside a table cell uses its own table style's text styles, a box inside a cell gets the document default, a paragraph explicitly styled with the inherited style round-trips and is exported without a style. Tests in Tasks 1 and 4. +4. **Undefined inherited styles with no paragraph using them** — the default paragraph style or a table text style that the sheet does not define is still TB2010. Test in Task 1. +5. **Inline sequences that must not merge** — adjacent text inlines, an empty text, a styled value with a format inside an inline `if`, an expression next to styled text: export never writes a string that import splits differently; import rejects an expression with a style / inside an inline `if` with a pointer. Tests in Task 3. + +--- + +## File structure + +New: +- `src/TriasDev.Templify.Builder/StyleInheritance.cs` — internal: the inheritance pass and `InheritedFor(...)` lookups shared by the pass and the JSON writer. +- `src/TriasDev.Templify.Builder/Json/TextTemplate.cs` — internal: string ↔ pieces (`{{path}}`, `{{path:format}}`, `{{(condition):format}}`). +- `src/TriasDev.Templify.Builder/Json/JsonLayout.cs` — internal: width-based reformatting. +- Tests: `StyleInheritanceTests.cs`, `TextTemplateTests.cs`, `JsonLayoutTests.cs`, `JsonShortFormTests.cs`. + +Modified: `Styles/StyleSheet.cs`, `Styles/StyleSheetComposer.cs`, `Model/DocumentModel.cs` (`TableStyleDefinition`, `TableRowModel`), `Tables.cs`, `TemplateBuilder.cs`, `Json/ModelJsonWriter.cs`, `Json/JsonDefinition.cs`, existing JSON tests, the sample, `docs/for-developers/template-builder.md`, phase 3 spec section 9. + +--- + +### Task 1: Inherited paragraph styles (model, C# API, JSON style properties) + +**Files:** +- Create: `src/TriasDev.Templify.Builder/StyleInheritance.cs`, `tests/TriasDev.Templify.Builder.Tests/StyleInheritanceTests.cs` +- Modify: `Styles/StyleSheet.cs`, `Styles/StyleSheetComposer.cs`, `Model/DocumentModel.cs`, `Tables.cs`, `TemplateBuilder.cs`, `Json/ModelJsonWriter.cs` (styles section, row), `Json/JsonDefinition.cs` (styles section, row), `PublicAPI.Unshipped.txt` + +**Interfaces:** +- Produces (public): `DefaultStyleComposer DefaultStyleComposer.Paragraph(ParagraphStyleKey style)`; `TableStyleComposer TableStyleComposer.TextStyle(ParagraphStyleKey style)`; `TableStyleComposer TableStyleComposer.HeaderTextStyle(ParagraphStyleKey style)`; `void RowComposer.TextStyle(ParagraphStyleKey style)`. +- Produces (internal): `ParagraphStyleKey? StyleSheet.DefaultParagraphStyle`; `TableStyleDefinition.TextStyle` / `.HeaderTextStyle` (`ParagraphStyleKey?`); `TableRowModel.TextStyle` (`ParagraphStyleKey?`). +- Produces (internal): `static class StyleInheritance` with `void Apply(List blocks, ParagraphStyleKey? inherited, StyleSheet styles, BuildContext context)` and `ParagraphStyleKey? ForCell(StyleSheet styles, TableBlock table, TableRowModel row)` = `row.TextStyle ?? (row.IsHeader ? def?.HeaderTextStyle : def?.TextStyle) ?? styles.DefaultParagraphStyle`, where `def = styles.Resolve(table)` (a box's `AsTableStyle()` has no text styles). +- JSON keys: `styles.defaults.paragraph`, table style `textStyle` / `headerTextStyle`, row `textStyle` (phase 3 shape otherwise; the writer keeps writing every paragraph's style explicitly in this task). + +- [ ] **Step 1: Write failing tests** in `StyleInheritanceTests` (each builds DOCX and ODT through `BuilderHarness`, so the JSON round trip runs too): + - `UnstyledParagraph_GetsTheDefault`: defaults `.Paragraph(Body)`; `c.Paragraph("x")` → snapshot line `Body | x`. + - `ExplicitStyle_Wins`: `c.Paragraph(Heading, "x")` with default Body → `Heading | x`. + - `NoDefault_StaysUnstyled`: no default → same `ContentHash` as before the change for an existing definition (use `WalkingSkeletonTests`' definition) — i.e. assert the paragraph has no `pStyle`. + - `TableCells_UseTextStyles`: style `.TextStyle(Cell).HeaderTextStyle(Head)`; header row cell → `Head`, body row cell → `Cell`, row with `r.TextStyle(Total)` → `Total`, cell paragraph with explicit `Other` → `Other`. + - `NestedTable_UsesItsOwnStyle` and `BoxInCell_GetsTheDocumentDefault`. + - `ListItems_KeepTheirItemStyle`: default Body, list style with `ItemStyle(Item)` → items `Item`. + - `HeaderAndFooter_GetTheDefault`. + - `UndefinedDefault_IsTB2010` and `UndefinedTableTextStyle_IsTB2010` — with **no** unstyled paragraph in the definition. + - `UndefinedDefault_ErrorHasJsonLocation`: imported JSON with `"defaults": {"paragraph": "Nope"}` → TB2010 (location may be the styles pointer or null; assert the code only). +- [ ] **Step 2: Run, expect compile failures.** `dotnet test tests/TriasDev.Templify.Builder.Tests --filter "FullyQualifiedName~StyleInheritanceTests"` +- [ ] **Step 3: Implement.** API setters; `StyleSheet` validation reports TB2010 for an undefined default paragraph style or table text style (message names the style and where it is used); `StyleInheritance.Apply` runs in `TemplateBuilder.Compose` right after `composer.Close()` over the body (inherited = default) and each header/footer part, recursing through conditionals, loops, components, list items (paragraphs with `List != null` are skipped), and table cells (inherited = `ForCell`). It replaces an unstyled `ParagraphBlock` in its list with `p with { Style = inherited }` and copies its `BuildContext.Locations` entry to the replacement. JSON writer/reader handle the three new keys. +- [ ] **Step 4: Run the whole builder suite.** `dotnet test tests/TriasDev.Templify.Builder.Tests` → all pass (existing ones unchanged). +- [ ] **Step 5: Declare API, `check.sh`, commit** `feat(builder): inherited paragraph styles — default, table text styles, row text style (#274)`, merge, push. + +### Task 2: Placeholder text parser + +**Files:** +- Create: `src/TriasDev.Templify.Builder/Json/TextTemplate.cs`, `tests/TriasDev.Templify.Builder.Tests/TextTemplateTests.cs` + +**Interfaces:** +- Produces: `internal abstract record TextPiece`; `TextPiece.Literal(string Text)`, `TextPiece.Value(string Path, string? Format)`, `TextPiece.Expression(string Condition, string? Format)`. +- Produces: `internal static IReadOnlyList TextTemplate.Parse(string text)` — throws `FormatException` (message quotes the offending placeholder); a string without `{{` is one `Literal` (also `""`); empty literals between placeholders are dropped. +- Produces: `internal static string TextTemplate.Write(IEnumerable pieces)` — the inverse for pieces that came from `Parse`. +- Rules: `{{` starts a placeholder; `{{(` starts an expression: the condition runs to the matching `)` (nested parens counted; `"…"` and `'…'` with `\` escapes skipped), then optional `:format`, then `}}`. Otherwise path and format run to the first `}}`, split at the first `:`. Path/format/condition text is not validated here (the reader does that with its existing parsers). + +- [ ] **Step 1: Write failing tests** (`[Theory]` tables): + - `"Auftrag {{order.number}} · {{order.date:date:d. MMMM yyyy}}"` → Literal `"Auftrag "`, Value(`order.number`, null), Literal `" · "`, Value(`order.date`, `date:d. MMMM yyyy`). + - `"{{a}}{{b}}"` → Value, Value. `"plain"` → Literal. `""` → Literal `""`. `"a }} b"` → Literal. + - `"{{order.date:date:HH:mm}}"` → Value(`order.date`, `date:HH:mm`). `"{{line.tags:join:\" · \"}}"` → Value(`line.tags`, `join:" · "`). + - `"{{(order.isExpress and order.total > 1000):yesno}}"` → Expression(`order.isExpress and order.total > 1000`, `yesno`); `"{{(a = \"x):y\"):yesno}}"` → Expression(`a = "x):y"`, `yesno`); `"{{((a or b) and c)}}"` → Expression(`(a or b) and c`, null). + - Errors (`FormatException`): `"{{"`, `"x {{a"`, `"{{}}"`, `"{{(a}}"`, `"{{(a) junk}}"`. + - `Write(Parse(s)) == s` for every valid row. +- [ ] **Step 2: Run, expect FAIL.** `dotnet test tests/TriasDev.Templify.Builder.Tests --filter "FullyQualifiedName~TextTemplateTests"` +- [ ] **Step 3: Implement** as a single left-to-right scanner. +- [ ] **Step 4: Run; PASS.** +- [ ] **Step 5: `check.sh`, commit** `feat(builder): placeholder text parser for JSON strings (#274)`, merge, push. + +### Task 3: Inline text as strings with placeholders (reader + writer) + +**Files:** +- Modify: `Json/JsonDefinition.cs` (`Inline`, `Inlines`, `TextInline(s)`, paragraph/item content strings), `Json/ModelJsonWriter.cs` (`Content`, `Inlines`, `IsPlainText`), JSON tests that use `text`/`value`/`expression` objects +- Test: `tests/TriasDev.Templify.Builder.Tests/JsonShortFormTests.cs` + +**Interfaces:** +- Consumes: `TextTemplate.Parse/Write` (Task 2); existing `Resolve(text, at, kind)`, `Condition`, `ValueFormat.Custom`. +- Inline content = string or array; array pieces = string, `{"text": s, "style": c}`, `if`, `tab`, `tabRight`, `lineBreak`, `pageNumber`, `pageCount`, `image`. A string becomes `Text`/`Value`/`Expression` calls in order; styled text applies the style to each piece. `:join`/`join:` formats read a collection (as today). +- Errors (TB9200 at the string's pointer, message quoting the placeholder): malformed placeholder; an expression without a format (the C# API requires one); an expression in styled text; an expression inside an inline `if` branch; a value with both format and style inside an inline `if` (no such overload). Unknown paths stay TB9203 per placeholder. The removed `value`/`expression` objects give the existing "Unknown inline" error, its list updated. +- Writer: a maximal run of `TextInline`/`ValueInline`/`ExpressionInline` (expression only unstyled) with the same character style becomes one string, except that two `TextInline`s are never joined and an empty `TextInline` is written as its own `""`; a run of one unstyled piece in a paragraph is written as the bare string instead of an array. + +- [ ] **Step 1: Write failing tests** in `JsonShortFormTests`: + - `Import_StringWithPlaceholders`: `{"paragraph": {"content": "Order {{order.number}} of {{order.date:date:yyyy}}"}}` (phase 3 block shape, still current) → filled DOCX text `Order 42 of 2026`. + - `Import_StyledTextWithValue`: `{"text": "{{order.number}}", "style": "Strong"}` → value run has the character style. + - `Import_Expression`: `"Free: {{(a and b):yesno}}"` fills `Free: Yes`/`No` (culture-invariant). + - `Import_Errors` (Theory): each error above → `TemplateBuildException` with code and `Location` ending `/content` or `/content/`. + - `Import_UnknownPathInString_IsTB9203` with `Data` catalogue. + - `Export_MergesValuesIntoText`: C# `x.Text("Order "); x.Value(p); x.Text(" of "); x.Value(d, ValueFormat.Date("yyyy"))` → JSON contains `"Order {{order.number}} of {{order.date:date:yyyy}}"`. + - `Export_KeepsAdjacentTextsApart`: `x.Text("a"); x.Text("b")` → `["a", "b"]`; empty text kept; same-hash round trip (harness). + - `Export_StyledRun`: `Text("x", s); Value(p, s)` → `{"text": "x{{p}}", "style": "S"}`. +- [ ] **Step 2: Run, expect FAIL.** `dotnet test tests/TriasDev.Templify.Builder.Tests --filter "FullyQualifiedName~JsonShortFormTests"` +- [ ] **Step 3: Implement reader and writer; migrate the existing JSON tests' inline objects to strings.** +- [ ] **Step 4: Run the whole builder suite; all pass (the harness round trip covers every inline test).** +- [ ] **Step 5: `check.sh`, commit** `feat(builder): JSON inline content as strings with placeholders (#274)`, merge, push. + +### Task 4: Block short forms and inherited-style omission (reader + writer) + +**Files:** +- Modify: `Json/JsonDefinition.cs` (`Block`, `Paragraph`, `ListItem(s)`, `Table`, `RowItem`, `Row`, box/list), `Json/ModelJsonWriter.cs` (`Block`, `ListItems`, `Table`, `Rows`), JSON tests with block literals +- Test: `JsonShortFormTests.cs` + +**Interfaces:** +- Consumes: `StyleInheritance.ForCell` and `StyleSheet.DefaultParagraphStyle` (Task 1) for the inherited style while writing. +- Shapes (spec 4.4): block string; `{"style"?, "paragraph": content}`; `{"style", "box": [blocks]}`; `{"style", "list": [items]}` with item = string | `{"level"?, "item": content}` | `forEach`/`if` (`items`); `{"style"?, "columns"?, "spaceAfter"?, "table": [rows]}`; row `{"header"?, "textStyle"?, "allowSplit"?, "row": [cells]}`; cell = string | [blocks] | `{"span"?, "background"?, "align"?, "content": string | [blocks]}`. Keep every existing option key under its current name; only the nesting changes. +- Writer key order: options first, payload key last; `if`/`forEach`/`component`/`group`/`forEachRow`/`rowsIf` unchanged. A paragraph's `style` is omitted when it equals the inherited style of its scope. Bare-string forms: block/cell/item whose single paragraph has the inherited style (items: level 0) and whose content is one unstyled string. An unstyled paragraph in a scope with no inherited style writes no `style`. + +- [ ] **Step 1: Write failing tests:** + - `Import_ShortForms`: one definition using every form above → snapshot equals the same definition in C#. + - `Export_ShortForms`: the C# definition exports to JSON containing `{"style": "SuccessBox", "box": ["Paid"]}`, `{"header": true, "row": ["#", "Item"]}`, `"Plain block"`, `{"textStyle": "Total", "row": [{"span": 2, "content": "Total"}, "{{total}}"]}` (substring checks after Task 5's layout are fragile — assert by parsing the JSON with `JsonDocument` and comparing elements). + - `Export_OmitsInheritedStyle_KeepsOthers`: default Body; paragraphs `Body` and `Heading` → first has no `style`, second has. + - `Export_ExplicitInheritedStyleInNestedCell_RoundTrips` (Review Focus 3). + - `Import_OldShape_IsRejected`: `{"paragraph": {"style": "Body", "content": "x"}}` → TB9200 at `/content/0/paragraph` ("expected a string or an array"). + - `Import_CellOptionsWithoutContent_IsTB9200`. +- [ ] **Step 2: Run, expect FAIL.** +- [ ] **Step 3: Implement reader and writer; migrate the existing JSON tests and the `Phase3ReviewTests`/`ComponentCatalogTests`/`DataCatalogTests` literals.** +- [ ] **Step 4: Run the whole builder suite; all pass.** +- [ ] **Step 5: `check.sh`, commit** `feat(builder): JSON block short forms, inherited styles omitted (#274)`, merge, push. + +### Task 5: Compact layout, sample, docs, evaluation + +**Files:** +- Create: `src/TriasDev.Templify.Builder/Json/JsonLayout.cs`, `tests/TriasDev.Templify.Builder.Tests/JsonLayoutTests.cs` +- Modify: `Json/ModelJsonWriter.cs` (write unindented, then `JsonLayout.Format`), `samples/TriasDev.Templify.Builder.Sample/OrderConfirmation.cs`, `TypedOrderConfirmation.cs`, `docs/for-developers/template-builder.md` (JSON section), phase 3 spec section 9 (new numbers), `SampleTests.cs` if its asserted strings change + +**Interfaces:** +- Produces: `internal static string JsonLayout.Format(string json, int width = 100)` — input: valid JSON; primitives copied with `GetRawText()` (keeps the writer's escaping); object/array on one line when `indent + key + single-line form <= width`, else one member per line, recursively; empty `{}`/`[]` always inline; output ends with `\n`. + +- [ ] **Step 1: Write failing tests** in `JsonLayoutTests`: + - fits at exactly 100 (incl. indent and key) → one line; 101 → broken; + - nested: outer breaks, inner fits → inner on one line; + - long string never wrapped; escaping preserved (`"\""`, `"ü"` unescaped as the writer emits); + - `Format(Format(x)) == Format(x)`; same input → same output. +- [ ] **Step 2: Run, expect FAIL.** +- [ ] **Step 3: Implement; switch the writer; update the sample:** style sheet gets `.Paragraph(Styles.BodyCopy)` in defaults and `LineGrid` gets `.TextStyle(TableText).HeaderTextStyle(TableHeader)`; drop now-redundant explicit styles in both sample definitions (typed and untyped must keep producing the same bytes as each other); the totals row uses `r.TextStyle(Styles.TableHeader)`. If the first-page logo paragraph's new `BodyCopy` spacing visibly moves the header (compare the PDF via `LibreOfficeConverter`), give it its own style in the sample. +- [ ] **Step 4: Run the whole builder suite and the sample** (`dotnet run --project samples/TriasDev.Templify.Builder.Sample -- phase3 ~/Desktop/templify-builder-phase3`), refresh `~/Desktop/templify-builder-phase3/` (JSON, assets, docx/odt, the sample's C#), record lines/characters/tokens for both languages in spec section 9 and in the developer docs' JSON example. +- [ ] **Step 5: `check.sh`, commit** `feat(builder): compact JSON layout; sample uses inherited styles (#274)` and `docs(builder): compact JSON format and evaluation (#274)`, merge, push. diff --git a/docs/superpowers/plans/2026-11-26-builder-evolution-policy.md b/docs/superpowers/plans/2026-11-26-builder-evolution-policy.md new file mode 100644 index 00000000..a063cd56 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-evolution-policy.md @@ -0,0 +1,78 @@ +# Builder: checking stored templates (#294) — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** One check that tells a host whether a stored template (DOCX/ODT copy or JSON definition) still works with the current data, with a status and located problems. + +**Architecture:** A catalogue witness (data in which every catalogue path exists) drives the engine's validation and a trial fill for document copies; JSON definitions are imported with the catalogue and built. The stamp gains component versions; a result type collects problems into `Ok`/`Warning`/`Broken`. + +**Tech Stack:** .NET 10/11, xUnit v3, TriasDev.Templify core (`TemplateProcessor.ValidateTemplate`, `ProcessTemplate`). + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-evolution-policy-design.md` + +## Global Constraints + +- Worktree `templify-evo-294`, branch `feat/evo-294-design`, `$S/check.sh`, ff-merge to `feature/builder`, push; commits reference #294. +- Nothing is released: `CheckUpload`, `UploadCheckResult` and `TemplateOrigin` are replaced, not obsoleted. Public API in `PublicAPI.Unshipped.txt`. +- Public repository: no customer or product names in code, docs, commits or the issue. +- Codes: TB9300 template syntax, TB9301 unknown data path, TB9302 wrong kind (loop over a non-collection), TB9303 no stamp, TB9304 other template, TB9305 older definition version, TB9306 older or unknown component. JSON definitions keep their own codes (TB92xx, build codes). + +## Review Focus + +1. A copy reading a field the catalogue has but the standard template does not use → `Ok` (the reason for checking against the catalogue). +2. Paths under an open catalogue shape (a dictionary property) → accepted, also in loops and conditions. +3. Loop variables: `{{line.description}}` inside `{{#foreach line in order.lines}}` resolves through the loop → no false unknown path. +4. A damaged or non-template file → `Broken` with TB9300, never an exception. +5. A stamp written before this change (no component property) still reads; components are then simply not compared. + +--- + +### Task 1: Catalogue witness and JSON + +**Files:** Modify `src/TriasDev.Templify.Builder/Typed/DataCatalog.cs`; Test `tests/TriasDev.Templify.Builder.Tests/DataCatalogEvolutionTests.cs` (folder as the existing catalogue tests). + +**Produces:** `public string DataCatalog.ToJson()` — `{"version":1,"paths":[{"path":…,"kind":"value|object|collection|open","type":""}]}`, indented, in `Entries` order; `internal IReadOnlyDictionary DataCatalog.CreateWitness()` — values `"x"`, collections with one item, open shapes an accept-everything node (an `IReadOnlyDictionary` whose `TryGetValue` always succeeds with another such node, and which enumerates as one item). + +- [ ] Tests: `ToJson_ListsEveryPath_WithKindAndType`; `Witness_ValidatesTemplateReadingAnyCataloguePath` (a docx built with the core test helpers that reads `order.customer.name`, loops `order.lines` with `line.description`, has a condition on `order.isExpress` → `ValidateTemplate(witness)` has no missing variables); `Witness_AcceptsAnyPathBelowAnOpenShape` (`order.extra.anything.deep` with `extra` a `Dictionary`); watch them fail, implement, pass. +- [ ] Commit `feat(builder): data catalogue as JSON and witness (#294)`. + +### Task 2: Component versions in the stamp + +**Files:** Create `src/TriasDev.Templify.Builder/Components/ComponentVersionAttribute.cs`; modify `TemplateStamp.cs`, `TemplateBuilder.cs` (collect `ComponentBlock`s of the model, skipping the builder's own `SectionComponent`), `Json/ModelJsonWriter.cs` only if it reads the stamp; tests `ComponentVersionTests.cs`. + +**Produces:** `[AttributeUsage(Class)] public sealed class ComponentVersionAttribute(int version)`, `int Version` (≥ 1, else `ArgumentOutOfRangeException`); `TemplateStamp.Components : IReadOnlyDictionary` (name = type name without generic suffix, as `ComponentSectionName`); document property `Templify.Components` = `Name=version` pairs joined by `;`, sorted ordinal, omitted when empty; `FromProperties` reads it when present (absent → empty), a malformed value → empty. `internal static string ComponentName(Type)` and `internal static int ComponentVersionOf(Type)` shared with Task 3. + +- [ ] Tests: `Stamp_RecordsComponentsAndVersions` (`[ComponentVersion(2)] Terms` + unversioned `Card` → `Card=1;Terms=2`, read back by `TemplateInspector.Inspect`, DOCX and ODT); `Stamp_WithoutComponentProperty_StillReads`; `Stamp_SectionsAreNotComponents`; byte-identical JSON round trip unchanged (the existing invariant tests). +- [ ] Commit `feat(builder): component versions in the template stamp (#294)`. + +### Task 3: `TemplateInspector.Check` for document copies + +**Files:** Create `src/TriasDev.Templify.Builder/TemplateCheck.cs` (result types); modify `TemplateInspector.cs` (replace `CheckUpload`); update the tests of `CheckUpload` to the new API; tests `TemplateCheckTests.cs`. + +**Produces:** +- `public enum TemplateCheckStatus { Ok, Warning, Broken }`, `public enum TemplateCheckSeverity { Warning, Error }`. +- `public sealed record TemplateCheckProblem(string Code, TemplateCheckSeverity Severity, string Message) { string? DataPath; string? Location; }` (init). +- `public sealed class TemplateCheckResult { TemplateCheckStatus Status; IReadOnlyList Problems; TemplateFormat Format; TemplateStamp? Stamp; }` — status `Broken` if any error, `Warning` if any warning, else `Ok`. +- `public sealed record TemplateCheckOptions { required DataCatalog Data; TemplateIdentity? Expected; ComponentCatalog? Components; PlaceholderReplacementOptions? Fill }`. +- `public static TemplateCheckResult TemplateInspector.Check(Stream template, TemplateCheckOptions options)`. + +Approach: syntax errors of `ValidateTemplate(stream)` → TB9300 (location from the engine); missing variables of `ValidateTemplate(stream, witness)` (and missing condition variables, as `CheckUpload` reads them) → TB9301 with `DataPath`; then a trial `ProcessTemplate` with the witness: a failure → TB9302 with the engine's message (a loop over a value). Stamp: none → TB9303; `Expected` given and another id → TB9304; same id and lower version → TB9305; with `Components`, each stamped component whose registered type has a higher `ComponentVersion` or that no registered type has → TB9306 (registered types matched by `ComponentName`). + +- [ ] Tests: `Check_CopyReadingAnotherCatalogueField_IsOk`; `Check_RemovedField_IsBroken_WithPath` (catalogue of a type without the field); `Check_LoopOverValue_IsBroken`; `Check_SyntaxError_IsBroken_WithLocation`; `Check_NotATemplate_IsBroken` (random bytes); `Check_NoStamp_IsWarning`; `Check_OtherTemplate_IsWarning`; `Check_OlderVersion_IsWarning`; `Check_OlderComponent_IsWarning`; `Check_LoopVariables_ResolveThroughTheLoop`; `Check_OpenShape_AcceptsAnyPath`. ODT for the Ok and Broken cases. +- [ ] Commit `feat(builder): check stored template copies against the data catalogue (#294)`. + +### Task 4: `TemplateInspector.CheckDefinition` for JSON definitions + +**Files:** modify `TemplateInspector.cs` (or `TemplateCheck.cs`); tests in `TemplateCheckTests.cs`. + +**Produces:** `public static TemplateCheckResult TemplateInspector.CheckDefinition(string json, TemplateJsonImportOptions import, TemplateBuildOptions? build = null, TemplateIdentity? expected = null)`. `import.Data` is required (`ArgumentException` without it). Import errors → `Error` problems with their own code and the JSON pointer as `Location`, `DataPath` for TB9203 when known; with `build`, the definition is built and build errors/warnings become problems; `expected` → TB9304/TB9305 from the identity. `Stamp` is null, `Format` `Unknown`. + +- [ ] Tests: `CheckDefinition_Current_IsOk` (sample definition exported with `TemplateJson.Export`); `CheckDefinition_RemovedField_IsBroken_AtPointer`; `CheckDefinition_NotJson_IsBroken`; `CheckDefinition_BuildError_IsBroken` (a rule only the build checks); `CheckDefinition_OlderVersion_IsWarning`. +- [ ] Commit `feat(builder): check stored JSON definitions (#294)`. + +### Task 5: Docs, sample, issue + +- [ ] `docs/for-developers/template-builder.md`: "Stamp and upload check" becomes "Checking stored templates" (both calls, statuses, codes table, `ComponentVersion`, `DataCatalog.ToJson`) and a short "Changing the data" policy: adding is safe; renaming or removing is breaking, re-check stored templates; the host keeps the changelog and decides. +- [ ] Sample: `[ComponentVersion(1)]` on `Terms`; `SampleRunner` runs `Check` on the built DOCX and prints the status. +- [ ] Desktop artefacts refreshed; #294 body updated to the reduced scope (sanitised); commit `docs(builder): checking stored templates (#294)`. +- [ ] Final review (fresh reviewer, most capable model), one fix pass, ff-merge, push, tick #294 in #261. diff --git a/docs/superpowers/plans/2026-11-26-builder-json-format-round.md b/docs/superpowers/plans/2026-11-26-builder-json-format-round.md new file mode 100644 index 00000000..fd4a20a7 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-json-format-round.md @@ -0,0 +1,40 @@ +# Builder: JSON format round (#293) — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Settle the JSON format before any customer definition is stored, following the style review (decisions A1–A9 and the "change now" list, accepted by the maintainer 2026-11-26). + +**Architecture:** Reader/writer changes in `Json/`, small model and API additions (theme tokens on `Color`/`FontFace`, `SectionBlock`, named assets), renames in C# and JSON together. The byte-identical round trip stays the invariant of every test. + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-direction-review.md` (findings), the style review A1–A9 (summarised below), issue #293 and its comment (port findings F4, F5, F12). + +## Decisions (style review, accepted) + +- **A1 strict reader:** value formats checked against the known list (host can add names); `padding`/`cellPadding` take one or two values; `as` equal to the first segment of its own collection path is an error; a text key missing in one language of `texts` is an import error. +- **A2:** every conditional's branch is `then` (also in lists); `elseIf` branches are `{"if": …, "then": …}`. +- **A3:** `paragraphStyle` / `headerParagraphStyle` (table style, row), `defaults.paragraphStyle`, cell `verticalAlign`; C#: `ParagraphStyle(…)`, `HeaderParagraphStyle(…)`, `Defaults(d => d.ParagraphStyle(…))`, `RowComposer.ParagraphStyle(…)`. +- **A4:** a cell is a string or an object; no bare array (`{"content": [blocks]}`); a cell `style` option for the one-paragraph case (`{"style": "Label", "content": "…"}`). +- **A5:** theme tokens: root `theme` with `colors` and `fonts`; values `"$accent"` wherever a colour or font family goes (also inside borders, `"1pt $line"`); `TemplateJsonImportOptions.Theme` overrides values; C# `Color.Token(name, value)` / `FontFace.Token(name, family)` keep the reference through export. +- **A6:** root `assets` map (`"logo": "sha256:…"`); images reference the name; an image may give only `width` or only `height` (the other from the image's proportions). +- **A7:** `{"section": "name", "blocks": […]}` and `c.Section("name", b => …)` replace `group`/`from`; names unique in a file; unregistered components export as sections named after the component. +- **A8:** `texts` key-first: `"title": {"de": …, "en": …}`. +- **A9:** layout width counted without the indentation. +- **Small:** `\n`/`\t` in strings are the official line break and tab (the `lineBreak`/`tab` objects go); `==` is accepted as `=`; root keys `components`, `$schema` reserved (`$schema` ignored). +- **Port findings:** components reach the build's texts and theme (`BlockComposer.Texts`, `BlockComposer.Theme`) so they can be registered (F5); export option without indentation (F12); TB9204 names the first difference (F4 message; per-language values stay out of scope). +- **C# consistency:** the style parameter comes first everywhere (inline `Text(style, text)`, `Value(path, …)` keeps the path first and the style after the format — see Task 6); content-adding methods return their composer. + +## Global Constraints + +- Worktree per task (`feat/fmt--`), `$S/check.sh`, ff-merge to `feature/builder`, push; commits reference #293. +- Every builder test keeps its JSON round trip; public API changes in `PublicAPI.Unshipped.txt` (renames are free: nothing is released). +- The sample, its exported JSON and the developer docs follow every change; the Desktop artefacts are refreshed at the end. + +## Tasks + +1. **Strict reader and small decisions** — A1, `==`, reserved root keys, TB9204 names the first difference. Tests: each silent mistake of the style review's probes becomes an error with a pointer. +2. **Names** — A2, A3 in JSON and C#. +3. **Structure** — A8 texts key-first, A7 sections (C# `Section`), A4 cells, `\n`/`\t` strings. +4. **Assets and images** — A6. +5. **Theme tokens and component context** — A5, F5. +6. **Layout and C# consistency** — A9, export without indentation, style-first parameters, chaining. +7. **Docs, sample, artefacts** — developer docs (JSON reference section rewritten), sample definitions and JSON, Desktop refresh, a short re-run of the Haiku edit trials on the new format. diff --git a/docs/superpowers/plans/2026-11-26-builder-json-text-keys.md b/docs/superpowers/plans/2026-11-26-builder-json-text-keys.md new file mode 100644 index 00000000..d6fa4605 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-json-text-keys.md @@ -0,0 +1,54 @@ +# Builder: text keys in JSON definitions — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** One JSON definition for every language: texts are `[[key]]`, translated at build from the JSON's `texts` section or the host catalog. + +**Architecture:** Export composes with key markers (`TemplateTexts` in export mode returns `key`); the writer turns markers into `[[key]]`. Import resolves `[[key]]` in every string before the existing reader runs (JSON texts first, then `TemplateTexts`; markers again in export mode). + +**Tech Stack:** C# / .NET 11+10, System.Text.Json, xUnit v3. + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-json-text-keys-design.md` + +## Global Constraints + +- Same workflow as the compact-JSON plan: worktree per task (`feat/tk--`, `../templify-tk-`), `$S/check.sh`, ff-merge into `feature/builder`, push; Conventional Commits `(builder)`, `#274`; public API in `PublicAPI.Unshipped.txt`. +- C# API unchanged except the additive export options. +- Byte-identical round trip for every builder test; the `language` member is removed from the JSON format (no compatibility). +- Key syntax `[A-Za-z0-9_.-]+`; markers U+E000 / U+E001; new code TB9204 (export: text not representable). + +## Review Focus + +1. A text inside a format argument or raw XML (`date:[[dateFormat]]`, `Gedruckt am` in raw) round-trips. +2. A key whose translation is missing in the JSON `texts` but present in the catalog (and vice versa) — JSON wins, catalog fills gaps. +3. A literal `[[` written in C#, or a key with characters outside the key syntax — export error, never a silently different template. +4. A translation containing `{{` (would become a placeholder) — rejected at build with a pointer. +5. Re-export of an imported JSON with `texts` and without `TextLanguages` keeps the section unchanged. + +--- + +### Task 1: Keys in the JSON (markers out, `[[key]]` in) + +**Files:** `TextCatalog.cs` (`TemplateTexts` export mode + `Resolve`), `TemplateBuilder.cs` (internal compose with key markers), `Json/TemplateJson.cs`, `Json/ModelJsonWriter.cs` (drop `language`; markers → `[[key]]`; TB9204), `Json/JsonDefinition.cs` (drop `language`; resolve `[[key]]`), `Json/TextKeys.cs` (new: marker/key helpers), `BuildContext.cs` (TB9204); tests `JsonTextKeyTests.cs`; migrate JSON literals (remove `"language"`). + +**Interfaces:** +- `internal static class TextKeys`: `string Marker(string key)`; `bool IsKey(string key)`; `string MarkersToKeys(string text)`; `string ResolveKeys(string text, Func lookup)` (throws `FormatException` for malformed `[[`). +- `internal bool TemplateTexts.WritesKeys`; `internal string TemplateTexts.Resolve(string key, ITextCatalog? preferred)`. +- `TemplateBuilder.Compose(definition, options, keyMarkers: bool)`. + +- [ ] Tests (RED): export of `x.Text(t["hello"] + " "); x.Value(p, ValueFormat.Date(t["fmt"]))` → `"[[hello]] {{p:date:[[fmt]]}}"`; properties title and image alt and raw XML carry `[[key]]`; import + build with a catalog gives the C# bytes (de and en); missing key → TB5001; `"[[bad key]]"`/`"[[x"` → TB9200 with pointer; `x.Text("a [[b")` → export TB9204; translation `"{{x}}"` → build TB9201 at the string. +- [ ] Implement; migrate tests; whole suite green; `check.sh`; commit `feat(builder): text keys in JSON definitions (#274)`. + +### Task 2: Embedded `texts` section and export options + +**Files:** `Json/TemplateJsonExportOptions.cs` (new, public), `Json/TemplateJson.cs` (overload), `Json/ModelJsonWriter.cs` (`texts`), `Json/JsonDefinition.cs` (read `texts`, lookup order), tests in `JsonTextKeyTests.cs`. + +**Interfaces:** `TemplateJsonExportOptions { Components, TextLanguages }`; `TemplateJson.Export(definition, options, TemplateJsonExportOptions export)`; `JsonDefinition.Texts` (internal: languages and texts, for re-export). + +- [ ] Tests (RED): export with `TextLanguages = [de, en]` writes `texts` in first-use key order; import **without** catalog builds the C# bytes for de-DE and en-GB; JSON text wins over catalog; catalog fills a key the JSON lacks; `de-DE` build reads `"de"`; re-export without `TextLanguages` keeps `texts`; malformed `texts` → TB9200 pointers. +- [ ] Implement; declare API; suite green; `check.sh`; commit `feat(builder): translations embedded in JSON definitions (#274)`. + +### Task 3: Sample, docs, evaluation + +- [ ] Sample `phase3` mode writes one `order-confirmation.json` (texts de + en), imports it without a catalog and checks same bytes for both languages; `SampleTests` updated; developer docs JSON section (`[[key]]`, `texts`, lookup order); phase 3 spec section 9 numbers; refresh `~/Desktop/templify-builder-phase3/`. +- [ ] `check.sh`; commits `feat(builder): sample exports one JSON for all languages (#274)` and `docs(builder): text keys (#274)`. diff --git a/docs/superpowers/plans/2026-11-26-builder-phase4-step1.md b/docs/superpowers/plans/2026-11-26-builder-phase4-step1.md new file mode 100644 index 00000000..03aeceb2 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-phase4-step1.md @@ -0,0 +1,41 @@ +# Builder phase 4 step 1 — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Indexed data paths (#290) and render-safe containers (#291). + +**Architecture:** Paths gain an optional `[n]` per segment through `TemplatePath`, `PathExpression` and the contract/witness; the writers add a spacer paragraph where Templify's marker removal would leave a cell ending with a table or two tables touching. + +**Tech Stack:** C# / .NET 11+10, OpenXML SDK, System.Xml.Linq, xUnit v3. + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-phase4-step1-design.md` + +## Global Constraints + +- Same workflow: worktree per task (`feat/p4--`), `$S/check.sh`, ff-merge into `feature/builder`, push; commits reference the issue (`#290`, `#291`). +- Every builder test keeps its JSON round trip; public API changes declared in `PublicAPI.Unshipped.txt`. +- Index range 0..999; spacer style id `TemplateSpacer`, display name "Template Spacer". + +## Review Focus + +1. An index after a loop item (`line.parts[1].name`) and in a nested loop — canonical path and witness. +2. The same collection used by a loop and by an index — the witness satisfies both. +3. A cell that ends with a nested box whose own content ends with a conditional — both cells get spacers. +4. Headers/footers with tables followed by markers. +5. A typed index on a dictionary vs a list (`get_Item(string)` stays a key, `get_Item(int)` becomes an index). + +--- + +### Task 1: Indexed path segments (#290) + +**Files:** `TemplatePath.cs`, `Typed/PathExpression.cs`, `DataContract.cs`, `Loops.cs` (hidden-root check), `Typed/DataCatalog.cs` (`KindOf` normalisation); tests `IndexedPathTests.cs`. + +- [ ] Tests (RED): `order["items[0].textValue"]` builds `{{order.items[0].textValue}}` and fills the first item's value (DOCX, ODT); `line["parts[1].name"]` inside a loop; typed `o => o.Items[0].Name` and array index; captured index and `[1000]`, `[x]`, `items[0][1]` are errors; condition `order.items[0].ok` in C# and JSON; JSON text `{{order.items[1].name}}`; contract entry `order.items[0].textValue`; witness validation of a template with a loop over `order.items` and `order.items[2].name` reports no missing variables; catalogue check accepts `order.items[0].name` for a typed catalogue. +- [ ] Implement; suite green; `check.sh`; commit `feat(builder): indexed path segments (#290)`. + +### Task 2: Render-safe containers (#291) + +**Files:** `Writers/DocxWriter.cs`, `Writers/OdtWriter.cs`, `Model/DocumentModel.cs` (`BlockFlattener` helpers), `Styles/BuilderStyles.cs` (spacer definition), `TemplateBuilder.cs` (inject the spacer style when used), `Styles/StyleSheet.cs` (comma check); tests `RenderSafetyTests.cs`. + +- [ ] Tests (RED): cell ending with `If` → filled with the condition false, the cell's last child is a paragraph (DOCX and ODT); box ending with `ForEach` over an empty list → same; table, `If` (false), table → a paragraph between the two tables after filling; a cell ending with a paragraph gets no spacer; the spacer style appears only when used; comma in a style display name → TB2006. +- [ ] Implement; suite green; `check.sh`; commit `fix(builder): cells end with a paragraph, tables stay apart, style name check (#291)`. diff --git a/docs/superpowers/plans/2026-11-26-builder-typed-path-generator.md b/docs/superpowers/plans/2026-11-26-builder-typed-path-generator.md new file mode 100644 index 00000000..b9a87a35 --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-builder-typed-path-generator.md @@ -0,0 +1,40 @@ +# Builder: typed path source generator — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `order.Number`, `line.Quantity` instead of `order.Path(o => o.Number)` through generated C# 14 extension properties. + +**Architecture:** An incremental Roslyn generator (netstandard2.0) finds `TemplateComposer.DataAs()` calls and `[assembly: TemplateData(typeof(X))]`, walks the reachable data types with the `DataCatalog` type rules, and emits extension blocks on `TemplatePath` and `LoopItem` that call the existing lambda API. + +**Tech Stack:** C# 14, Microsoft.CodeAnalysis.CSharp 5.0.0 (generator), xUnit v3. + +**Spec:** `docs/superpowers/specs/2026-11-26-builder-typed-path-generator-design.md` + +## Global Constraints + +- Same workflow as before: worktree per task (`feat/gen--`), `$S/check.sh`, ff-merge into `feature/builder`, push; Conventional Commits `(builder)`, `#274`; shared files (solution, `Directory.Packages.props`, lock files) in a separate `build` commit. +- New dependency only for the generator and tests: `Microsoft.CodeAnalysis.CSharp` 5.0.0 (central version), `PrivateAssets=all`. +- Diagnostics: TBG001 warning (name collision), TBG002 error (LangVersion < 14). Release tracking files for RS2008. +- Generated file `TemplifyDataPaths.g.cs`, namespace `TriasDev.Templify.Builder`, `internal static class TemplifyDataPaths`, `#nullable disable`, deterministic order (types by fully qualified name, properties in declaration order, base properties after derived). + +## Review Focus + +1. A client data type in another assembly (metadata symbols, inherited properties) — generated like a source type. +2. Private/protected nested data types (common in tests) — skipped, the client still compiles. +3. A property named like a C# keyword (`@class`) or colliding with a receiver member — escaped / TBG001, never a compile error. +4. A strict client (nullable enabled, warnings as errors) — the generated code produces no warnings. +5. Recursive and mutually referencing types, and the same type reached from two roots — generated once. + +--- + +### Task 1: Generator project, attribute, packaging, generator tests + +**Files:** `src/TriasDev.Templify.Builder.Generators/` (csproj, `TypedPathGenerator.cs`, `DataTypeModel.cs`, `EquatableArray.cs`, `PublicAPI.*.txt`, `AnalyzerReleases.*.md`), `src/TriasDev.Templify.Builder/TemplateDataAttribute.cs`, builder csproj (pack the generator), `templify.slnx`, `Directory.Packages.props`; tests `tests/TriasDev.Templify.Builder.Tests/GeneratorTests.cs` (driver). + +- [ ] Tests (RED): driver over a source compilation referencing the builder: generated text for value/object/collection/open properties on both receivers; inheritance; `[JsonIgnore]`; keyword property; TBG001 on `Line.Number` for `LoopItem` only; TBG002 with LangVersion 13; private nested type skipped and output compiles; `[assembly: TemplateData(typeof(X))]` root; two runs give identical text; no compile diagnostics in the output compilation (warnings as errors, nullable enabled). +- [ ] Implement; `check.sh`; commits `build(builder): source generator project` and `feat(builder): typed path source generator (#274)`. + +### Task 2: End-to-end, sample, docs + +- [ ] The builder test project and the sample run the generator (`OutputItemType="Analyzer"`). Tests (RED): generated properties equal lambda paths (`[JsonPropertyName]`, snake_case policy, loop items, nested collections). +- [ ] Rewrite `TypedOrderConfirmation`/`OrderAddressBlock` with generated properties; `SampleTests` byte equality stays; `dotnet pack` contains `analyzers/dotnet/cs/TriasDev.Templify.Builder.Generators.dll`; developer docs "Typed data paths" section; Desktop refresh; `check.sh`; commits. diff --git a/docs/superpowers/plans/2026-12-01-builder-agent-api.md b/docs/superpowers/plans/2026-12-01-builder-agent-api.md new file mode 100644 index 00000000..c3d48e79 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-builder-agent-api.md @@ -0,0 +1,87 @@ +# Builder agent API (#274) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Describe, Schema, Outline, Read, Patch and Preview for JSON definitions, as library functions a host's agent tools call. + +**Architecture:** An internal vocabulary table (`Json/JsonVocabulary.cs`) describes every JSON construct; Describe and Schema render it, and a test cross-checks it against the reader's "allowed here" lists. Outline/Read/Patch work on `System.Text.Json.Nodes`; Patch and Preview reuse `TemplateJson.Import`, `TemplateInspector.CheckDefinition` and `TemplateProcessor`. + +**Tech Stack:** .NET 11, System.Text.Json(.Nodes), xUnit v3; test-only JsonSchema.Net to validate the schema. + +**Spec:** `docs/superpowers/specs/2026-12-01-builder-agent-api-design.md` + +## Global Constraints + +- Builder only; no new package dependency of the library. A test-only package goes in through a separate `build(deps)` commit (Directory.Packages.props + lock files). +- New public API recorded in `src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt` (`$S/apisync.py`). +- Deterministic output: Describe and Schema are byte-identical for the same input (ordinal ordering). +- Diagnostics keep JSON-pointer locations; new code TB9207 (patch failed) only. +- Format with `dotnet format --include` the builder dirs; full check `$S/check.sh`. + +## Review Focus + +1. A construct or key the reader accepts but the vocabulary misses (or the reverse) — the cross-check test must cover every construct, including inlines, rows, cells, list items, styles, page, theme. +2. JSON pointer escaping (`~0`, `~1`) and array index `-` in Patch/Read; a pointer into a string-form paragraph. +3. Patch atomicity: a failing op in the middle leaves the input unchanged; `move` into its own child is an error. +4. Preview with a definition that imports but does not build, and with data that fails the fill — no exception escapes. +5. Schema accepts every exported definition of the sample and the test suite's JSON fixtures, and rejects an unknown key. + +--- + +### Task 1: Vocabulary and Describe + +**Files:** Create `Json/JsonVocabulary.cs` (internal), `Json/TemplateJsonDescribeOptions.cs`; modify `Json/TemplateJson.cs`. Test: `JsonVocabularyTests.cs`. + +**Interfaces:** +- Produces: `internal sealed record VocabularyKey(string Name, ValueKind Kind, bool Required, string Description)`; `internal sealed record Construct(string Name, string Group, string? Discriminator, IReadOnlyList Keys, string Description, string Example)`; `internal enum ValueKind { Text, Template, Number, Integer, Boolean, Length, Color, Line, Lines, Padding, Condition, Path, Format, StyleId, Blocks, Inlines, Rows, Cells, Items, Object, Array, Any }`; `internal static class JsonVocabulary { IReadOnlyList All; }`. Groups: `root`, `style`, `page`, `block`, `row`, `cell`, `item`, `inline`, `value`. +- Produces: `public static string TemplateJson.Describe(TemplateJsonDescribeOptions? options = null)` — JSON `{ "formatVersion": 1, "constructs": [...], "values": {...}, "components": [...], "data": {...}? }`; components list name and parameters (`name`, `type`: path/text/number/boolean/enum(values)/style/length/color/list of …). + +- [ ] Step 1: failing tests — `EveryConstruct_ExampleImports` (each example wrapped in a minimal definition at the right place imports and builds DOCX); `EveryConstruct_KeysMatchTheReader` (example + `"zzzUnknown": 1` → TB9200 whose message's "allowed here:" list equals the construct's keys, as sets); `Describe_ListsRegisteredComponents` (sample `SampleRunner.Components` → `terms`, `address` with their parameters and types); `Describe_IncludesDataWhenGiven`; `Describe_IsDeterministic`. +- [ ] Step 2: run, FAIL. `dotnet test tests/TriasDev.Templify.Builder.Tests --filter FullyQualifiedName~JsonVocabularyTests` +- [ ] Step 3: implement; component parameter types from `ComponentCatalog.Registration` (add an internal `Parameters` accessor). +- [ ] Step 4: PASS; whole builder suite green. +- [ ] Step 5: apisync, format, commit `feat(builder): describe the JSON vocabulary for agents (#274)`. + +### Task 2: JSON Schema + +**Files:** Create `Json/JsonSchemaWriter.cs`; modify `TemplateJson.cs`. Test: `JsonSchemaTests.cs`. Build commit: test package `JsonSchema.Net` in `Directory.Packages.props`, test csproj, lock files. + +**Interfaces:** `public static string TemplateJson.Schema(ComponentCatalog? components = null)` — draft 2020-12, `$defs` per construct, `additionalProperties: false`, required keys; a block is a string or one of the block constructs (each requiring its discriminator); value kinds map to patterns (Length `^-?[0-9]+(\.[0-9]+)?(pt|mm|cm|in)$`, Color `^(#[0-9A-Fa-f]{6}|\$[A-Za-z][A-Za-z0-9]*)$`); components: `component` enum of registered names when given. + +- [ ] Step 1: failing tests — `Schema_AcceptsTheSampleExport` (OrderConfirmation exported with components, both languages' texts); `Schema_AcceptsEveryVocabularyExample`; `Schema_RejectsAnUnknownKey`; `Schema_RejectsAnUnknownComponent_WhenComponentsGiven`; `Schema_IsDeterministic`. +- [ ] Step 2–4: FAIL → implement → PASS. +- [ ] Step 5: commits `build(deps): JsonSchema.Net for builder tests` then `feat(builder): JSON Schema of the definition format (#274)`. + +### Task 3: Outline and Read + +**Files:** Create `Json/JsonPointer.cs` (internal: parse/escape, resolve on `JsonNode`), `Json/TemplateJsonNode.cs`; modify `TemplateJson.cs`. Test: `JsonOutlineTests.cs`. + +**Interfaces:** `public sealed record TemplateJsonNode(string Pointer, string Kind, string Label, int Depth)`; `TemplateJson.Outline(string json)`; `TemplateJson.Read(string json, string pointer)`; internal `JsonPointer.Parse(string) : IReadOnlyList`, `JsonPointer.Escape(string)`. + +- [ ] Step 1: failing tests — `Outline_ListsBlocksWithPointersAndLabels` (sample export: sections, headings' text, tables, conditions, loops, components, nested depth); `Read_ReturnsTheSubtree`; `Read_EscapedPointer` (`~1`, `~0` in a style name); `Read_MissingOrMalformed_Throws`; `Outline_StringParagraph_IsParagraph`. +- [ ] Step 2–4: FAIL → implement → PASS. Step 5: commit `feat(builder): outline and read a JSON definition by pointer (#274)`. + +### Task 4: Patch + +**Files:** Create `Json/JsonPatch.cs` (internal RFC 6902 on `JsonNode`), `Json/TemplatePatchResult.cs`; modify `TemplateJson.cs`, `TemplateCheck.cs` (TB9207 in `CheckCodes`). Test: `JsonPatchTests.cs`. + +**Interfaces:** `public sealed class TemplatePatchResult { bool Applied; string Json; TemplateCheckResult Check; }`; `TemplateJson.Patch(string json, string patch, TemplateJsonImportOptions import, TemplateBuildOptions? build = null)` (throws `ArgumentException` without `import.Data`, like CheckDefinition). + +- [ ] Step 1: failing tests — each op on a definition (`add` with `-`, `remove` a section, `replace` a paragraph text, `move` a block, `copy`, `test` pass/fail); `FailingOp_LeavesTheInputUnchanged` (op 2 of 3 fails → Applied false, Json == input, problem TB9207 at `/1`); `MoveIntoOwnChild_Fails`; `PatchedButBroken_ReportsTheProblemAtItsPointer` (unknown data path → Applied true, Status Broken, TB9203 location); `NotJson_Fails`. +- [ ] Step 2–4: FAIL → implement → PASS. Step 5: commit `feat(builder): apply a JSON Patch to a definition and check it (#274)`. + +### Task 5: Preview + +**Files:** Create `Json/TemplatePreview.cs`; modify `TemplateJson.cs`. Test: `JsonPreviewTests.cs`. + +**Interfaces:** `public sealed class TemplatePreview { TemplateCheckResult Check; byte[]? Document; string? Text; }`; `TemplateJson.Preview(string json, TemplateJsonImportOptions import, TemplateBuildOptions build, string? data = null)`. + +- [ ] Step 1: failing tests — `Preview_FillsWithData` (both formats, text contains filled values); `Preview_WithoutData_UsesTheWitness`; `Preview_BrokenDefinition_ReturnsProblems_NoDocument`; `Preview_FillFailure_IsAProblem` (loop over a value); `Preview_BadDataJson_IsAProblem`. +- [ ] Step 2–4: FAIL → implement → PASS. Step 5: commit `feat(builder): preview a JSON definition (#274)`. + +### Task 6: Docs and agent trial + +**Files:** `docs/for-developers/template-builder.md` (section "Agent API": the six functions, a host tool mapping table, TB9207), builder README if it lists the API. + +- [ ] Step 1: docs; full `$S/check.sh` → ALL CHECKS PASSED; commit `docs(builder): agent API (#274)`. +- [ ] Step 2: trial — a Haiku subagent gets the sample definition and only these functions (via a tiny test-project harness or a scratch console that exposes them as commands) and 6–8 tasks; record results privately in `.superpowers/reviews/2026-12-01-agent-api/`; fix what the trial shows is unclear (descriptions, messages), each with a test. diff --git a/docs/superpowers/plans/2026-12-01-builder-formatting-gaps.md b/docs/superpowers/plans/2026-12-01-builder-formatting-gaps.md new file mode 100644 index 00000000..d55be5aa --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-builder-formatting-gaps.md @@ -0,0 +1,130 @@ +# Builder formatting gaps (#296) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Paragraph layout options, spacer, short rule, paragraph-style bottom border, per-side padding and borders, +table indent and space before, and no stacked spacer paragraphs — in C#, model, DOCX, ODT and JSON. + +**Architecture:** Each construct goes through the same path: public composer method → internal model field → +`DocxWriter` / `OdtWriter` → `JsonDefinition` (import) and `ModelJsonWriter` (export). `BuilderHarness.AssertInvariants` +checks package validity and the byte-identical JSON round trip for every test definition that uses it. + +**Tech Stack:** .NET 11 / C#, DocumentFormat.OpenXml, System.Xml.Linq, xUnit v3, LibreOffice (`soffice`) for round trips. + +**Spec:** `docs/superpowers/specs/2026-12-01-builder-formatting-gaps-design.md` + +## Global Constraints + +- Builder only (`src/TriasDev.Templify.Builder`, `tests/TriasDev.Templify.Builder.Tests`); the core library is untouched. +- Every new public symbol goes into `src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt` (sync with `$S/apisync.py `). +- Byte-identical round trip C# → JSON → import → build stays; definitions without the new options build byte-identically to before (F13 aside). +- Every new construct: both formats, JSON import + export, a LibreOffice round-trip test (`[Trait("Category", "LibreOffice")]`), 0 skipped locally. +- Format with `dotnet format --include ` only; full check `$S/check.sh `. +- Commits on `feat/fmt-296`, merged into `feature/builder` afterwards; no PR. Public repo: no customer names in text. + +## Review Focus + +1. A paragraph with options that also gets its style by inheritance (table cell, row style, default style) keeps the options — `StyleInheritance` rebuilds the record with `with`. Test in Task 1. +2. ODT paragraph with a right tab **and** options gets one automatic style with both (no lost tab stop). Test in Task 1. +3. Cell padding wider than its column: build error, not a negative content frame. Test in Task 4. +4. A header cell with its own bottom border and a table-style header rule: the cell's own line wins on DOCX and ODT. Test in Task 5. +5. A cell whose whole content is a conditional without else still ends with a paragraph after filling with the condition false (F13 must not drop that spacer). Test in Task 7. + +--- + +### Task 1: Paragraph options + +**Files:** +- Create: `src/TriasDev.Templify.Builder/ParagraphOptions.cs` +- Modify: `Model/DocumentModel.cs` (ParagraphBlock), `BlockComposer.cs`, `Writers/DocxWriter.cs` (`WriteParagraph`), `Writers/OdtWriter.cs` (`WriteParagraph`, `RightTabStyle`), `Json/JsonDefinition.cs` (`Block`/`Paragraph`), `Json/ModelJsonWriter.cs` +- Test: `tests/TriasDev.Templify.Builder.Tests/ParagraphOptionsTests.cs` + +**Interfaces:** +- Produces: `public sealed class ParagraphOptions { SpaceBefore(Length); SpaceAfter(Length); KeepWithNext(bool value = true); KeepLinesTogether(bool value = true) }` (each returns `ParagraphOptions`). +- Produces: `BlockComposer.Paragraph(ParagraphStyleKey? style, string text, Action options)`, `(ParagraphStyleKey? style, TemplatePath value, Action options)`, `(ParagraphStyleKey? style, Action content, Action options)`. +- Produces: `internal sealed record ParagraphOverrides(Length? SpaceBefore, Length? SpaceAfter, bool? KeepWithNext, bool? KeepLinesTogether) { bool IsEmpty }`; `ParagraphBlock(..., ParagraphOverrides? Options = null)` (null when the lambda set nothing). + +- [ ] **Step 1: Write the failing tests** (`ParagraphOptionsTests`, both formats via `Formats` theory data) + - `Options_AreWrittenAsDirectParagraphProperties`: DOCX `w:pPr` of the paragraph holds `w:pStyle`, `w:keepNext`, `w:spacing w:before="140"` (7 pt) and no `w:after`; ODT paragraph's automatic style has `style:parent-style-name` = the named style, `fo:keep-with-next="always"`, `fo:margin-top="7pt"` **and** `fo:margin-bottom` equal to the named style's space after (set it to 4 pt in the sheet). + - `Options_SurviveStyleInheritance` (Review Focus 1): unstyled paragraph with options in a table whose style sets `ParagraphStyle` → written with the inherited style and the options. + - `Odt_RightTabAndOptions_ShareOneAutomaticStyle` (Review Focus 2): the automatic style has the tab stop and `fo:keep-with-next`. + - `EmptyOptions_BuildLikeNoOptions`: `p => { }` builds byte-identical to the overload without options. + - `NegativeSpace_Throws`: `SpaceBefore(-1.Pt())` → `ArgumentOutOfRangeException`. + - `Json_ParagraphOptions_RoundTrip`: import `{"style":"Label","paragraph":"x","spaceBefore":"7pt","keepWithNext":true}`; `BuilderHarness.AssertInvariants` passes; export writes those keys. + - `LibreOffice_SpaceBeforeMovesTheParagraph` (LibreOffice trait): two paragraphs, the second with `SpaceBefore(20.Pt())`; in the PDF the gap between their baselines is the style's gap + 20 pt ± 1 pt in both formats (use `BoxRuleTests`' PDF helpers pattern; extract a shared helper only if needed). +- [ ] **Step 2: Run, expect compile failure / FAIL.** `dotnet test tests/TriasDev.Templify.Builder.Tests --filter "FullyQualifiedName~ParagraphOptionsTests&Category!=LibreOffice"` +- [ ] **Step 3: Implement.** DOCX: CT_PPrBase order (`pStyle`, `keepNext`, `keepLines`, `numPr`, `tabs`, `spacing`); ODT: one automatic style per signature (parent, options, tab position), margin pair resolved through the paragraph style chain (`StyleSheet` lookup of `SpaceBefore`/`SpaceAfter` along `BasedOn`, default 0). JSON keys on the paragraph block: `spaceBefore`, `spaceAfter`, `keepWithNext`, `keepLinesTogether`; export uses object form when options are present. +- [ ] **Step 4: Run Step 2's command and the LibreOffice test (`--filter "FullyQualifiedName~ParagraphOptionsTests"`). Expected: all PASS, 0 skipped.** +- [ ] **Step 5: apisync, format, commit** `feat(builder): paragraph layout options (#296)`. + +### Task 2: Spacer block + +**Files:** `Model/DocumentModel.cs` (`SpacerBlock(Length Height)`), `BlockComposer.cs`, both writers, `Writers/Spacers.cs` (`IsParagraph` includes `SpacerBlock`), JSON import/export, `Model` walkers if they switch on block types (grep `RuleBlock` and add `SpacerBlock` next to it everywhere). Test: `SpacerTests.cs`. + +**Interfaces:** Produces `BlockComposer Spacer(Length height)` (> 0 and ≤ 72 pt, else `ArgumentOutOfRangeException`); JSON `{"spacer": "14pt"}`. + +- [ ] **Step 1: Failing tests:** `Spacer_IsAnEmptyParagraphOfExactHeight` (DOCX: no `w:pStyle`, `w:spacing before=0 after=0 line=280 lineRule=exact`; ODT: automatic style, margins 0, `fo:line-height="14pt"`); `Spacer_OutOfRange_Throws` (0 and 73 pt); `Json_Spacer_RoundTrip` (AssertInvariants); `Spacer_EndsACellAsAParagraph` (cell `[Table, Spacer]` gets no Template Spacer); `LibreOffice_SpacerHeight` (gap between two paragraphs around a 14 pt spacer is 14 pt ± 1 pt larger than without). +- [ ] **Step 2: Run, expect FAIL.** `--filter "FullyQualifiedName~SpacerTests"` +- [ ] **Step 3: Implement** as specified in the spec ("Writers → Spacer"); ODT spacer style shared per height. +- [ ] **Step 4: Run, expect PASS** (incl. LibreOffice). +- [ ] **Step 5: apisync, format, commit** `feat(builder): spacer block (#296)`. + +### Task 3: Short rule and paragraph-style bottom border + +**Files:** `Model/DocumentModel.cs` (`RuleBlock` + `Length? Width`), `Model/StyleDefinitions.cs` (`ParagraphProperties.BorderBottom: BorderLine?`, `BorderBottomSpace: Length?`), `BlockComposer.cs`, `Styles/StyleSheetComposer.cs`, both writers (`RuleParagraph`/`RuleStyle`, style parts), `Tables.cs` `TableLayout.Check` (rule wider than its frame), JSON import/export. Test: `RuleBorderTests.cs`. + +**Interfaces:** `BlockComposer Rule(Length thickness, Color color, Length spaceAbove, Length spaceBelow, Length width)`; `ParagraphStyleComposer BorderBottom(Length width, Color color, Length space)` (width rule as for `Rule`: > 0, ≤ 6 pt; space ≥ 0). JSON rule `"width"`; paragraph style `"borderBottom"` (line string), `"borderBottomSpace"`. + +- [ ] **Step 1: Failing tests:** `ShortRule_IndentsTheEnd` (frame 170 mm in A4 default → DOCX `w:ind w:right` = twips(frame − 12 mm); ODT `fo:margin-right`); `ShortRule_WiderThanFrame_IsABuildError` (reuse the code `TableLayout.Check` uses for too-wide tables, message names the rule); `StyleBorderBottom_IsWritten` (DOCX style `w:pBdr/w:bottom w:sz=6 w:space=3`; ODT style `fo:border-bottom="0.75pt solid #…"`, `fo:padding-bottom="3pt"`); `Json_RuleWidthAndBorderBottom_RoundTrip`; `LibreOffice_ShortRuleEndsAtItsWidth` (render to PNG or PDF and check the line's x-extent; if no helper exists, assert via the PDF drawing operators the line length 12 mm ± 0.5 mm). +- [ ] **Step 2–4:** run `--filter "FullyQualifiedName~RuleBorderTests"` FAIL → implement → PASS. +- [ ] **Step 5: commit** `feat(builder): short rule and paragraph-style bottom border (#296)`. + +### Task 4: Per-side padding + +**Files:** `Model/DocumentModel.cs` (`internal sealed record Insets(Length Top, Length Right, Length Bottom, Length Left)`; `TableStyleDefinition.Padding: Insets` replaces `PaddingVertical`/`PaddingHorizontal`; `BoxStyleDefinition.Padding: Insets`; `TableCellModel.Padding: Insets?`), `Tables.cs` (`CellComposer.Padding`, `TableStyleComposer.CellPadding` overload, `TableLayout.CellFrame` takes left+right, `TableLayout.Check`), `Boxes.cs`, both writers, JSON (`Padding` helper accepts 1–4 values; cell `"padding"`), export shortest CSS form. Test: `PaddingTests.cs`. + +**Interfaces:** `CellComposer Padding(Length top, Length right, Length bottom, Length left)`; `TableStyleComposer CellPadding(Length top, Length right, Length bottom, Length left)`; `BoxStyleComposer Padding(Length top, Length right, Length bottom, Length left)`. Existing symmetric overloads stay and map to `Insets`. + +- [ ] **Step 1: Failing tests:** `TableStylePadding_PerSide` (DOCX `tblCellMar` top/left/bottom/right = 160/120/180/120 twips; ODT cell style four paddings); `CellPadding_OverridesTheTableStyle` (DOCX `tcMar`; ODT that cell's style only); `BoxPadding_PerSide`; `CellFrame_UsesTheCellsOwnPadding` (a right tab in that cell → DOCX tab position = cell width − left − right); `CellPadding_WiderThanColumn_IsABuildError` (Review Focus 3); `Json_Padding_FourValues_RoundTrip` (`"8pt 6pt 9pt"` and `"8pt 6pt 9pt 6pt"` both accepted; export writes `"8pt 6pt 9pt"`); `LibreOffice_PaddingTopAndBottomDiffer` (text top offset in a box with 12/6 pt padding differs from 6/12 pt by 6 pt ± 1). +- [ ] **Step 2–4:** `--filter "FullyQualifiedName~PaddingTests"` FAIL → implement → PASS; then the whole builder suite (existing box/table tests must stay byte-identical). +- [ ] **Step 5: commit** `feat(builder): per-side padding for cells, tables and boxes (#296)`. + +### Task 5: Per-side borders + +**Files:** Create `src/TriasDev.Templify.Builder/Sides.cs` (`[Flags] public enum Sides { None = 0, Top = 1, Right = 2, Bottom = 4, Left = 8, All = 15 }`). Modify model (`TableStyleDefinition.Outer` → `OuterTop`, `OuterRight`, `OuterBottom`, `OuterLeft`; `BoxStyleDefinition.AsTableStyle` sets all four; `TableCellModel.Borders: CellBorders?` with four nullable `BorderLine`s), `Tables.cs`, both writers (DOCX `tblBorders` per side, `tcBorders` merging own lines with the header rule — own wins; ODT edge lines: own line replaces the computed one on that side), JSON (`outerBorder` and cell `border`: string or `{"top"…}` object). Test: `BorderTests.cs`. + +**Interfaces:** `CellComposer Border(Sides sides, Length width, Color color)` (`Sides.None` → `ArgumentException`; repeated calls merge per side, last wins); `TableStyleComposer OuterBorder(Sides sides, Length width, Color color)`; existing `OuterBorder(Length, Color)` = `Sides.All`. + +- [ ] **Step 1: Failing tests:** `TableTopRuleOnly` (DOCX `tblBorders` top single, left/right/bottom nil; ODT first row cells `fo:border-top` line, last row `fo:border-bottom="none"`); `CellLeftBorder` (only that cell's left); `CellFrameOfItsOwn` (`Sides.All` on a middle cell); `HeaderCellOwnBottom_WinsOverHeaderRule` (Review Focus 4); `CellBorder_InRowLoop_IsKeptOnClones` (fill 3 items; all 3 DOCX cells carry `tcBorders/left`); `Json_Borders_RoundTrip` (string and object forms; export string when four equal); `Sides_None_Throws`; `LibreOffice_CellBorderIsDrawn` (PDF has a vertical line at the cell's left edge ± 1 pt). +- [ ] **Step 2–4:** `--filter "FullyQualifiedName~BorderTests"` FAIL → implement → PASS; whole builder suite stays green and byte-identical for existing definitions. +- [ ] **Step 5: commit** `feat(builder): per-side borders for cells and table styles (#296)`. + +### Task 6: Table indent and space before + +**Files:** model (`TableBlock.Indent: Length?`, `TableBlock.SpaceBefore: Length?`), `Tables.cs` (`TableComposer.Indent`, `TableComposer.SpaceBefore`; `TableLayout.Resolve`/`Check` with frame − indent), both writers, JSON table block keys `indent`, `spaceBefore`. Test: `TableIndentTests.cs`. + +**Interfaces:** `TableComposer Indent(Length indent)` (≥ 0, < frame checked at build: build error with the existing too-wide code); `TableComposer SpaceBefore(Length space)` (≥ 0). + +- [ ] **Step 1: Failing tests:** `Indent_NarrowsTheColumns` (relative columns sum to frame − 6 mm; DOCX `tblInd w:w=340 w:type=dxa`; ODT `fo:margin-left="6mm"` or its pt equivalent as the writer formats lengths); `Indent_NotSmallerThanFrame_IsABuildError`; `SpaceBefore_DocxParagraphBefore_OdtMarginTop` (DOCX a paragraph before the table with `w:spacing w:before`; ODT `fo:margin-top`); `Json_IndentSpaceBefore_RoundTrip`; `LibreOffice_IndentMovesTheText` (first cell text starts 6 mm (17 pt) ± 1.5 pt further right than without indent, both formats — this test decides the DOCX `tblInd` semantics; if DOCX is off by the cell padding, add the padding as Word's compatibility mode needs and note it in a code comment). +- [ ] **Step 2–4:** `--filter "FullyQualifiedName~TableIndentTests"` FAIL → implement → PASS. +- [ ] **Step 5: commit** `feat(builder): table indent and space before (#296)`. + +### Task 7: No stacked spacer paragraphs (F13) + +**Files:** `Writers/Spacers.cs` (`AtCellEnd`, `AtPartEnd`, `Used`), callers in both writers. Test: `SpacerStackingTests.cs`; update existing expectations that counted spacers. + +**Interfaces:** `Spacers.AtCellEnd(blocks, rawIsParagraph)` = the flattened content's last element is a table / raw table, or `MayBeEmpty(blocks)`; `Spacers.AtPartEnd` removed (callers drop it); new `internal static bool MayBeEmpty(IReadOnlyList blocks)` — true when every top-level block can be removed by filling (loop; conditional without else or with an empty or may-be-empty branch; component and list recursed). + +- [ ] **Step 1: Failing tests:** `BoxEndingWithConditional_HasOneSpacerAfterFilling` (box content `[Table, If(c, [P])]`, filled with c=false: exactly one Template Spacer after the table, both formats); `PartEndingWithConditionalAfterTable_HasOneSpacer`; `CellOnlyConditional_StillEndsWithAParagraph` (Review Focus 5: cell `[If(c,[P])]`, c=false → the cell has a paragraph, package valid); `CellEndingWithTable_StillGetsItsSpacer`; LibreOffice: `LibreOffice_BoxHeightDoesNotGrowBySpacers` (box with trailing conditional false vs. the same box without the conditional: heights equal ± 1.5 pt). +- [ ] **Step 2: Run, expect FAIL** `--filter "FullyQualifiedName~SpacerStackingTests"`. +- [ ] **Step 3: Implement**; update existing tests whose expected spacer counts change (each change must be a removed stacked spacer — list them in the commit message body). +- [ ] **Step 4: Whole builder suite + LibreOffice category, PASS, 0 skipped.** +- [ ] **Step 5: commit** `fix(builder): one spacer paragraph per position (#296)`. + +### Task 8: Docs, sample, full check + +**Files:** `docs/for-developers/template-builder.md` (vocabulary: paragraph options, spacer, rule width, style bottom border, padding/border per side, table indent and space before; JSON keys; support matrix; "named styles" rule now with the four layout options), `docs/superpowers/specs/2026-11-25-template-builder-design.md` 2.3 (one amendment line pointing to this design), `src/TriasDev.Templify.Builder/README.md` if it lists the vocabulary, the sample (`samples/…` order confirmation) uses at least `KeepWithNext` and a per-side cell border so `SampleTests` cover them. + +- [ ] **Step 1:** update docs and sample; regenerate sample expectations if `SampleTests` compare outputs. +- [ ] **Step 2:** `$S/check.sh ` → `ALL CHECKS PASSED`. +- [ ] **Step 3: commit** `docs(builder): formatting options (#296)`. diff --git a/docs/superpowers/specs/2026-11-25-builder-phase3-json-and-typed-data-design.md b/docs/superpowers/specs/2026-11-25-builder-phase3-json-and-typed-data-design.md new file mode 100644 index 00000000..2e25607f --- /dev/null +++ b/docs/superpowers/specs/2026-11-25-builder-phase3-json-and-typed-data-design.md @@ -0,0 +1,427 @@ +# Template builder, phase 3: JSON definitions and typed data paths + +- **Status:** Approved by the maintainer (2026-11-25). Builder check done. +- **Branch:** `feature/builder`. Nothing is released and nothing is merged to `main` in this phase. +- **Parent:** builder design spec `2026-11-25-template-builder-design.md`, epic #261, idea issue #274. + +## 1. Intent + +Phases 1 and 2 built the fluent C# builder. Phase 3 is exploratory. It answers two questions by building the core of +each and trying it on the real sample (`samples/TriasDev.Templify.Builder.Sample`): + +1. **JSON definitions.** Can a template written with the fluent C# API be exported to a JSON file, and can that file + be imported back into the same in-memory model, from which DOCX and ODT are built? What do the files look like, + and how large are they? +2. **Typed data paths.** Can data paths come from a C# data type (`o => o.Order.Number`) instead of strings + (`order["number"]`), and how does that feel in a real definition? + +The maintainer wants to **see the resulting files and the typed sample** and then decide how to change them. So the +output of this phase includes artefacts to look at, not only code. + +Why these two: in the longer term (#274), customers and their agents should change a stored definition instead of a +`.docx` copy. A file format that captures a definition exactly, and a catalogue of the data that exists, are the +foundations for that. The agent side (chat, MCP, patches, previews) is not part of this phase. + +## 2. Goals, non-goals, anti-goals + +**Goals** + +- Export: `ITemplateDefinition` + build options → JSON text (+ binary assets). +- Import: JSON text (+ assets) → an `ITemplateDefinition` that builds through the normal `TemplateBuilder.Build`. +- **Exact round trip:** for the sample, C# → JSON → import → build gives **the same bytes** (DOCX and ODT) as building + the C# definition directly. That is the acceptance test, and it is cheap because builds are deterministic. +- Hybrid component representation: registered components are written as references, others expanded (section 4.4). +- Import errors are the builder's normal diagnostics (`TB…`), plus a JSON-pointer location. +- Typed data paths (approach A, expression trees) and a data catalogue derived from a C# type, used to check the + paths of an imported JSON definition. +- The sample: its exported JSON files and a typed version of the definition, placed where the maintainer can look at + them, plus a short evaluation (sizes, readability, awkward spots). + +**Non-goals (this phase)** + +- Agents, in-app chat, MCP tools, JSON Patch, previews (#274 scenarios). +- YAML. JSON only (maintainer decision). +- Text keys and multi-language definitions. A JSON file holds the texts of the language it was exported in (section + 4.6). Keys come later. +- JSON Schema generation, schema versions with migrations. The file carries a format version number only. +- Overlays (a customer copy as a diff of the standard definition). +- A source generator for typed paths (approach B). Possible later on top of the same foundation. +- NuGet release, merge to `main`. + +**Anti-goals** (would make it a failure even if it works) + +- A second validation path: the importer must not check rules of its own that the composers also check, or + duplicate them differently. Import goes **through the composers**. +- A format that is a dump of internal classes (type names, private fields): the file must read as a document + description and be stable when internals are refactored. +- Breaking the fluent API or the output of existing definitions. Everything here is additive; existing tests and the + sample's bytes stay unchanged. + +## 3. Approaches considered + +### 3.1 File format + +| | | +|---|---| +| **JSON** (chosen) | `System.Text.Json` is in the BCL: no new dependency, a schema can follow, unambiguous. | +| YAML | Easier to read by hand, but a dependency (YamlDotNet) and ambiguities (implicit types). Dropped by the maintainer: only JSON. | + +### 3.2 What the file contains + +| | | +|---|---| +| A. Expanded model | What `Compose` produced: components expanded, texts resolved. Simplest, round trip nearly free; a stored file does not receive component changes. | +| B. Definition level | Components as references with parameters; needs a registry and serializable parameters. | +| **C. Hybrid** (chosen) | The model keeps a component's reference **and** its expansion. A registered component is written as a reference, an unregistered one expanded. Starts as A, grows into B without a format break. | + +### 3.3 Typed data paths + +| | | +|---|---| +| **A. Expression trees** (chosen) | `d.Path(o => o.Order.Number)`; no tooling; lambdas on every value. | +| B. Source generator | `d.Order.Number`; cleanest syntax; a Roslyn generator project, about twice the work. Deferred: B can be added later on the same foundation if A proves too noisy. | + +Both share the foundation: a catalogue of paths built from a C# type by reflection. + +## 4. JSON definitions + +### 4.1 Shape + +One JSON object per definition. Keys are camelCase; blocks are objects with **one discriminating key** (the block +kind), so a file reads like the C# that produced it. An excerpt of what the sample would export to (illustrative, the +exact names are the builder's call within these rules): + +```json +{ + "templifyDefinition": 1, + "identity": { "id": "order-confirmation", "version": 1 }, + "language": "en-GB", + "properties": { "title": "Order confirmation", "author": "Example Trading" }, + "styles": { + "defaults": { "font": "Liberation Sans", "size": "10pt", "color": "#1A1A1A" }, + "paragraph": { + "SectionHeading": { "name": "Section Heading", "basedOn": "BodyCopy", "size": "13pt", "bold": true, + "color": "#1F4E79", "outlineLevel": 1, "keepWithNext": true } + }, + "table": { "LineGrid": { "headerRule": "1pt #1F4E79", "rowRule": "0.5pt #D4D4D4", "cellPadding": "3pt 5pt" } } + }, + "page": { + "size": "A4", "margins": "25mm 20mm 22mm 20mm", + "header": [ { "paragraph": { "style": "SmallPrint", "content": [ + { "text": "Order confirmation " }, { "value": "order.number" }, { "tabRight": true }, + { "text": "Page " }, { "pageNumber": true } ] } } ] + }, + "content": [ + { "paragraph": { "style": "DocTitle", "content": "Order confirmation" } }, + { "component": "address", "params": { "address": "order.customer.address" } }, + { "if": "order.isExpress and order.total > 1000", + "then": [ { "paragraph": "Express shipping – free of charge for you." } ], + "elseIf": [ { "when": "order.isExpress", "then": [ { "paragraph": "Express shipping (plus €15.00)." } ] } ], + "else": [ { "paragraph": "Standard shipping." } ] }, + { "forEach": "order.lines", "as": "line", "body": [ + { "paragraph": { "content": [ { "value": "line.description" }, { "text": " — " }, + { "value": "line.amount", "format": "currency" } ] } } ] } + ] +} +``` + +Rules the builder follows: + +- **Shorthands** where the C# API has them: a paragraph with only text may be a string; `content` may be a string. + The writer always uses the shortest form, the reader accepts both. +- **Lengths** as strings with units (`"10pt"`, `"25mm"`), written in the unit the model stores (points, formatted + invariantly) unless an exact millimetre value exists. **Colours** as `#RRGGBB`. **Page sizes** by name when they + match a named size. +- **Paths** as Templify paths (`order.customer.name`; inside a loop `line.description`; loop metadata `line.@number` + or the builder's chosen spelling). **Value formats** as their specifier (`currency`, `date:d MMMM yyyy`, + `join:, `). +- **Conditions** as strings in Templify's condition syntax (`order.total > 1000 and order.isExpress`). The writer + uses the existing condition emitter; the reader needs a parser for that grammar (truth, comparisons, `in`, + `contains`/`startsWith`/`endsWith`, `exists`/`is empty`/`is not empty`, `not`, `and`/`or`, parentheses). This is + the builder's call for readability: the alternative, conditions as JSON trees, needs no parser but is several times + longer. The parser lives in the builder (D8: the builder uses core's public API only; core's parser is internal). +- **Styles:** the complete `StyleSheet` with resolved values (a theme record does not exist in JSON; its values do). +- **Images and embedded fonts** are not inlined. The file references them by content hash + (`"image": "sha256:3f1a…"`), and the export returns them as an asset map. Import takes an asset resolver. (Base64 + would make files unreadable.) +- **Raw blocks** are exported (both XML strings) so the round trip is exact, but **import refuses them** unless an + import option allows raw XML (default: refused, per #274's security note). +- **Determinism:** the writer emits keys in a fixed order and formats numbers invariantly. Export of the same + definition and options gives the same JSON text. + +### 4.2 API sketch (public, additive, namespace `TriasDev.Templify.Builder.Json`) + +```csharp +// Export +TemplateJsonDocument doc = TemplateJson.Export(new OrderConfirmation(theme), buildOptions, catalog); +string json = doc.Json; // the file +IReadOnlyDictionary assets = doc.Assets; // "sha256:…" → bytes (images, fonts) + +// Import: an ITemplateDefinition like any other +ITemplateDefinition imported = TemplateJson.Import(json, new TemplateJsonImportOptions +{ + Assets = assets, // or a resolver + Components = catalog, // registered components + Data = DataCatalog.From(), // optional: check paths against a data type (section 5) + AllowRawXml = false, +}); +GeneratedTemplate template = TemplateBuilder.Build(imported, buildOptions); +``` + +Names are the builder's call. Export needs build options because `Compose` runs for one language (texts, section 4.6). + +### 4.3 How import works + +The importer is an `ITemplateDefinition` whose `Compose` walks the JSON and calls the **same composers** the fluent API +calls (`c.Paragraph(...)`, `c.If(...)`, `t.Table(...)`). So every rule (styles defined, loop scopes, cell counts, +lengths) is checked once, in the composers. + +**When errors appear** (builder's call after the builder check): + +- **At `Import`:** the JSON is parsed into an intermediate tree at once. Structural problems (malformed JSON, unknown + keys or kinds, wrong value types, unknown components or assets, raw XML refused, paths outside the data catalogue) + are collected and thrown together, with JSON pointers. Nothing language-dependent can be checked yet. +- **At `Build`:** `Compose` replays the tree through the composers, once per language and format, as for C#. + - Composer rules that record diagnostics (`context.Error`, about 30) get the JSON pointer of the element being + composed: the importer tracks the current pointer while it composes. + - Composer rules that **throw** (about 200 argument checks: list levels, lengths, colours, path segments, style + ids) are caught by the importer per element and turned into a diagnostic with a generic code (a new + `TB9201` "invalid value", the exception's message and the pointer); composing continues with the next element. + The fluent C# API keeps throwing at the call, unchanged. If a composer is left half-way inside a lambda, the + importer abandons that element (and its children) only. + - Checks that run on the finished model (undefined styles, `TableLayout`) find the pointer through an internal map + from model blocks to JSON pointers that the importer fills; for C# definitions the map is empty and nothing + changes. + - All diagnostics of one build are reported together in one `TemplateBuildException`, like a C# build. +- `BuildDiagnostic` gets an optional location (additive public API, for example `string? Location`, a JSON pointer). + +### 4.4 Components (hybrid) + +- The model keeps, for each `ComponentBlock`, the component instance and its expansion (it already does). +- A **component catalog** maps a stable name to a component type: `catalog.Register("address")`. + A registrable component has serializable parameters: its constructor parameters / properties are `TemplatePath`, + `string`, numbers, `bool`, enums, style keys, or lists of those. Registration checks this and fails early + otherwise (for example a component taking a `BrandTheme`). +- **Export:** a registered component → `{ "component": "address", "params": { … } }`. An unregistered one → + its expansion as plain blocks (optionally tagged with the C# type name as a comment-like `"from"` key, the + builder's call). +- **Import:** a reference → the catalog creates the component from its parameters and composes it (so it expands with + the current component code). An unknown name → diagnostic. +- How the parameters are read from an instance (record properties, constructor parameters) is the builder's call; the + sample's `AddressBlock` must become registrable as part of this phase. + +### 4.5 Coverage + +Everything in the semantic model is exported: paragraphs and inlines (text, value, tab, right tab, line break, page +fields, images, inline conditionals, expressions), page breaks, conditionals and switches (a switch is exported as the +conditional it produces, or as a `switch` if the model keeps it, builder's call), loops, tables (columns, header rows, +rows, row loops, row conditionals, cells with spans, backgrounds, alignment, nested blocks), boxes, rules, lists (items, +levels, loops and conditionals over items), images, table of contents, components, raw blocks, page setup with headers +and footers, document properties, identity, and the complete style sheet. + +### 4.6 Texts and languages (deliberately minimal) + +`template.Texts["key"]` returns a string today, so the model holds resolved text. In this phase a JSON file is +**per language**: it records the language it was exported in (`"language"`), and its texts are literal strings. +Building it in another language works but keeps the exported texts. Text keys in the model (`{ "text": { "key": +"title" } }`) are a later step, as agreed with the maintainer. + +## 5. Typed data paths (approach A) + +### 5.1 API sketch + +```csharp +public sealed record OrderData(Order Order); +public sealed record Order(string Number, DateTime Date, decimal Total, bool IsExpress, Customer Customer, IReadOnlyList Lines); +public sealed record Line(string Description, int Quantity, decimal Amount); + +DataModel d = template.Data(); + +c.Paragraph(x => x.Value(d.Path(o => o.Order.Number))); // order.number +c.If(d.Path(o => o.Order.IsExpress) & d.Path(o => o.Order.Total).Gt(1000), …); // values are TemplatePaths, so conditions work unchanged +c.ForEach(d.Items(o => o.Order.Lines), "line", (line, b) => // line: LoopItem + b.Paragraph(x => + { + x.Value(line.Number); // loop metadata as today + x.Value(line.Path(l => l.Description)); // line.description + })); +c.Component(new AddressBlock(d.Path(o => o.Order.Customer.Address))); // TemplatePath
+ +public sealed record AddressBlock(TemplatePath
Address) : ITemplateComponent +{ + public void Compose(BlockComposer c) => c.Paragraph(x => + { + x.Value(Address.Path(a => a.Street)); // order.customer.address.street + x.LineBreak(); + x.Value(Address.Path(a => a.City)); + }); +} +``` + +- **Types go all the way through** (maintainer decision): `Path` returns a `TemplatePath`, where `T` is the + property's type. `TemplatePath` converts implicitly to `TemplatePath`, so everything that takes a path today + (values, conditions, `Gt`/`Eq`, components with `TemplatePath` parameters, the contract, scope checks) accepts it + unchanged. On an object it offers `Path(...)` for the next level, so a component can take a typed parameter + (`TemplatePath
`) and navigate inside it. Typed paths remain sugar that produces the same path values + (spec D9). +- `Items` returns a typed collection that `ForEach` accepts; the loop item is a `LoopItem` (a `LoopItem` with + `Path`), and its paths are `TemplatePath` too. +- `TemplatePath` is an allowed parameter type for registered components (section 4.4); in JSON it is a path + string like any other, and with a data catalogue the importer also checks that the path's type fits (an object + path for an object parameter). +- **Names:** C# property → JSON name with camelCase by default; `[JsonPropertyName]` wins; the policy can be set + (`template.Data(JsonNamingPolicy.SnakeCaseLower)`), because the data is usually JSON. +- **Supported expressions:** member access chains; collection indexers with constant indices (`o.Lines[0]`) and + dictionary indexers with constant keys. Anything else (method calls, computed values) is an `ArgumentException` at + the call, naming the expression. +- Collections: arrays, `List`, `IReadOnlyList`, `IEnumerable` (not `string`). + +### 5.2 Data catalogue + +`DataCatalog.From()` lists every path the type offers, with its kind (value, object, collection) and CLR +type, in the same canonical form as the data contract (`order.lines[].description`). It is used to: + +- check an imported JSON definition: a path not in the catalogue is a diagnostic with the JSON pointer; +- compare with a template's data contract (`contract ⊆ catalogue`); +- later (#274), tell an agent what data exists. + +Recursive types are cut at a depth limit (builder's call, with a test). + +Rules (builder's calls after the builder check): + +- The catalogue check is **opt-in** (`Data` in the import options). When a catalogue is given, a path it does not + contain is an **error** with the JSON pointer: passing a type is asking for the check. Without one, nothing is + checked. +- **Which paths are checked:** value, collection and component-parameter paths, and the paths in conditions. The + writer always quotes condition literals (`status = "paid"`), and the reader requires that, so every bare word in a + condition is a path and nothing is ambiguous. A bareword literal in a hand-written condition is a diagnostic that + says to quote it. +- **Open shapes:** a property typed as a dictionary, `object`, `JsonElement` or `JsonNode` is listed as *open*; + any path below it is accepted. + +### 5.3 Typed sample + +The sample gets typed data records for its sample JSON and a typed version of `OrderConfirmation`, including a typed +`AddressBlock` (alongside the string version, so both can be compared side by side). The typed version must produce **the same bytes** as the +string version. + +## 6. Verification + +- Round trip, both formats, both sample languages: `Build(C#) == Build(Import(Export(C#)))` byte for byte, and + `Export(Import(Export(C#))) == Export(C#)` text for text. +- Round trip over the builder's existing test definitions where practical (a test that exports every definition the + test suite builds would be ideal; the builder decides the mechanism). +- Import diagnostics: malformed JSON, unknown kinds and keys, wrong value types, unknown components, unknown assets, + raw XML refused, composer errors with JSON pointers, all errors reported together. +- Typed paths: name policies, `[JsonPropertyName]`, indexers, unsupported expressions, loop items, nested loops, + the typed sample's bytes equal the string sample's. +- Data catalogue: shape of the sample's catalogue, recursion limit, unknown paths in an imported definition. +- The usual invariants (test kit) on everything built from imported definitions. + +## 7. Artefacts for the maintainer + +- `~/Desktop/templify-builder-phase3/` (outside the repo): the sample's exported JSON for en-GB and de-DE, its assets, + the DOCX/ODT built from the imported JSON, the typed definition source next to the string one. +- A short evaluation note in the spec: file sizes (bytes, lines, rough token count), what reads well, what is + awkward, and what to change next. + +## 8. Left to the builder + +Exact JSON key names and shorthands within section 4.1's rules; the condition parser's implementation; how component +parameters are read; the public type names; the data catalogue's recursion limit; whether `switch` survives as its +own kind. + +## 9. Phase 3 evaluation (2026-11-25) + +Measured on the sample (`samples/TriasDev.Templify.Builder.Sample`, `dotnet run -- phase3 `), every builder +test and the new JSON/typed tests (519 builder tests after the review fixes, all green; every test that checks the invariants also +round-trips through JSON). + +### What works + +- **Exact round trip.** C# → JSON → import → build gives the same bytes for DOCX and ODT in both languages, for + the sample and for every definition in the builder's test suite. Re-exporting an import gives the same JSON text. +- **One validation path.** The importer only replays the JSON through the composers; all builder rules apply + unchanged, and diagnostics carry JSON pointers (`/content/2/body/0/paragraph/content/0/value`). Structural + problems come at `Import`, composer problems at `Build`, each time all of them at once. +- **Hybrid components.** A registered component is three lines (`{ "component": "address", "params": { "address": + "order.customer.address" } }`) and picks up changes to the component code on import; unregistered ones are + expanded as a `group`. +- **Typed paths** build byte-identical templates (`TypedOrderConfirmation` vs `OrderConfirmation`), and the data + catalogue of `OrderData` contains the sample's whole data contract; an import checks every path against it. + +### Numbers + +| | de-DE | en-GB | +|---|---|---| +| JSON (indented, as written) | 18,461 characters, 717 lines | 18,347 characters, 717 lines | +| approximate tokens (characters / 4) | ~4,600 | ~4,600 | +| same JSON without indentation | 7,620 characters | 7,506 characters | +| share: content / styles / page / properties | 71% / 13% / 7% / 1% | same | + +| definition | non-blank code lines | characters | +|---|---|---| +| `OrderConfirmation` (string paths) | 159 | 4,854 | +| `TypedOrderConfirmation` (typed paths) | 163 | 5,370 (+11%) | + +### What is awkward + +1. **Depth and verbosity of tables.** A table cell holding one value is about 12 indented lines + (`row → cells → content → paragraph → content → { "value" }`); content is 71% of the file. Indentation alone + accounts for more than half of the characters. +2. **One file per language.** The two files differ only in texts; every text change has to be made twice. This is + the known limit of section 4.6 (text keys come later). +3. **Raw XML is opaque in JSON**: escaped XML strings, readable only by copying them out. Acceptable for an escape + hatch, and refused by default on import. +4. **Typed paths cost characters, not lines**: `order.Path(o => o.Number)` instead of `order["number"]`. The gain is + the compiler (renames, typos), the catalogue check and typed components; the lambdas are noise in long value + lists. + +### Proposals for the next step + +1. **Shorter forms for the common cases**, accepted by the reader and preferred by the writer: + a paragraph or cell with one value (`{ "value": "line.quantity", "style": "TableText" }` as a cell), and a + compact writer layout that puts objects with only scalar members on one line (roughly halves the lines without + changing the format). +2. **Text keys** in the model (`{ "text": { "key": "title" } }`), so one JSON serves every language. +3. **JSON Schema** generated from the vocabulary, for editor completion and as the agent-facing contract (#274). +4. **Typed paths, approach B** (source generator) if the lambda noise matters in real definitions: same foundation + (`TemplatePath`, `DataCatalog`), shorter than the string version. + +### Compact format (2026-11-26) + +Proposal 1 was implemented (`2026-11-26-builder-compact-json-design.md`): placeholders inside strings, inherited +paragraph styles (style sheet default, table text styles, row text style), block/row/cell/item short forms and the +100-character layout. The round trip stays byte-identical (612 builder tests, every one round-tripping through JSON). + +| | phase 3 | compact | change | +|---|---|---|---| +| de-DE JSON | 18,461 characters, 717 lines | 8,861 characters, 273 lines | −52% / −62% | +| en-GB JSON | 18,347 characters, 717 lines | 8,705 characters, 270 lines | −53% / −62% | +| approximate tokens (de-DE) | ~4,600 | ~2,200 | −52% | +| without any whitespace (de-DE) | 7,620 characters | 6,134 characters | −20% | +| share: content / styles / page | 71% / 13% / 7% | 58% / 28% / 10% | | + +A table cell holding one value is now one line (`"{{line.amount:currency}}"`). The C# sample uses the inherited +styles too: `TypedOrderConfirmation.cs` shrank by 4% (8,585 → 8,276 characters); `OrderConfirmation.cs` stayed the +same size (its style sheet gained the default, the table text styles and a `Logo` style for the first-page logo, which +should not inherit body copy spacing). + +Still open from the list above: text keys (2), JSON Schema (3), the source generator (4). The styles are now the second +largest part of the file; they are written once per language file, so text keys would also halve that. + +### Text keys (2026-11-26) + +Proposal 2 was implemented (`2026-11-26-builder-json-text-keys-design.md`): texts are `[[key]]`, the translations sit +in an optional `texts` section (falling back to the host catalog), and the `language` member is gone. The sample now +exports **one** `order-confirmation.json` for de and en; importing it without any catalog builds the same bytes as the +C# definition in both languages. + +| | before (one file per language) | one file, with `texts` | +|---|---|---| +| JSON for de + en | 2 × ~8,800 characters, 2 × ~270 lines | 10,859 characters, 317 lines | +| approximate tokens for both languages | ~4,400 | ~2,700 | +| share: content / texts / styles / page | — | 41% / 27% / 22% / 6% | + +Without the `texts` section (keys only, translations from the host's catalog) the file is 8,249 characters and 255 lines. + diff --git a/docs/superpowers/specs/2026-11-25-template-builder-design.md b/docs/superpowers/specs/2026-11-25-template-builder-design.md new file mode 100644 index 00000000..77284105 --- /dev/null +++ b/docs/superpowers/specs/2026-11-25-template-builder-design.md @@ -0,0 +1,846 @@ +# Design: TriasDev.Templify.Builder — code-first template generation + +- **Issues:** epic [#261](https://github.com/TriasDev/templify/issues/261), spec task [#270](https://github.com/TriasDev/templify/issues/270), analysis [#260](https://github.com/TriasDev/templify/issues/260) +- **Date:** 2026-11-25 +- **Status:** Accepted (2026-11-25). Spikes done (section 9): the upload check works through core's validator once #271 is fixed; a box as a one-cell table works in both engines. + +## 1. Goal and binding decisions + +A new package, `TriasDev.Templify.Builder`, generates Templify templates from C# code, as `.docx` and as `.odt`. A +consuming application describes a template once: styles, blocks, placeholders, conditionals and loops. It then builds +that template at runtime in the language, format and customer theme it needs. Templify fills the result as it fills any +template today. + +The decisions below were taken in #260 and in the maintainer's answers to the review in #261. This spec does not reopen +them: + +| # | Decision | +|---|---| +| D1 | Templates are generated **at runtime**, in memory. Nothing is generated ahead of time and stored. The result is also available as bytes or a stream, so a user can download it. | +| D2 | Customer customisation is **data passed to the definition** (theme slots: colours, logo, fonts, a few texts). It is never done by editing a generated file. | +| D3 | A customer may download a generated template, edit it in Word or LibreOffice and upload it. From then on that copy **lives on its own**: no merging, no regeneration. Going back to the standard template is always possible. | +| D4 | Every generated template carries an **identity stamp**, and an uploaded copy can be checked against the current data contract. | +| D5 | **DOCX and ODT from the first task.** Every task delivers both formats. | +| D6 | The builder is a **project in this repository**, under the same rules: public API tracking, tests, LibreOffice round trips. | +| D7 | **Its own version line.** A separate release-please component; versions stay `0.x` until the API has carried one real multi-section document. | +| D8 | The builder uses **core's public API only**. No `InternalsVisibleTo` from core to the builder. | +| D9 | **Model paths are values** (`TemplatePath`, `LoopItem`). Typed paths (`m => m.Customer.Name`) come after the MVP, as sugar that produces the same values. | +| D10 | **No font embedding in the MVP.** Choosing one family per weight, which avoids Word for Mac ignoring an embedded bold face, is a token decision and needs no embedding. *Phase 2 (#288) adds `FontFace.Embedded` (section 3.3).* | + +Out of scope: + +- importing a letterhead or any other customer-supplied document; +- PDF output, and any layout engine of our own; +- reading a model back from a document; +- merging a customer's edits with a new version. + +## 2. Principles + +### 2.1 QuestPDF's ergonomics, not its container model + +QuestPDF can chain decorators (`.Padding().Border().Background()`) because it owns the layout. Word and LibreOffice +lay out flow documents themselves, from named styles. A decorator chain has no faithful mapping there, and it would push +users toward direct formatting, which makes a downloaded copy hard to edit (D3). + +The builder therefore takes from QuestPDF only the parts that carry over: + +- nested lambda descriptors; +- a definition class; +- reusable components. + +The public surface is a **closed vocabulary of semantic blocks** plus Templify constructs. The document model behind it is +`internal`. + +### 2.2 Invalid template syntax cannot be written + +Users never type marker text. Every Templify construct exists only where the engine supports it, and the writer emits it +in the shape the engine needs (section 3.6). If the engine has a limitation, **we fix the engine** and do not add a builder +workaround. The builder's conformance tests double as engine regression tests. + +### 2.3 Editability is an output requirement + +A downloaded template must be pleasant to adapt by hand. That means: + +- paragraph and character formatting comes from **named styles**, never direct formatting; since #296 one paragraph + may set four layout options of its own — space before and after, keep with next, keep lines together — written as a + visible override on its named style (`docs/superpowers/specs/2026-12-01-builder-formatting-gaps-design.md`); +- markers are **visible**, in a dedicated style; +- loop variables have **readable names**; +- lists are **real lists**; +- there are no invisible spacer or keeper hacks where the format has a native option. + +### 2.4 Admission rule for constructs + +A construct joins the vocabulary only when all of these hold: + +1. it has a defined mapping in **both** formats; +2. it has a LibreOffice round-trip test; +3. a real template needs it. + +A construct that maps differently between the formats is listed in the support matrix (section 6). The builder reports +it as a **build warning**; it never lets the formats diverge silently. + +### 2.5 Determinism + +The same definition, options and builder version give **the same bytes**, under any current culture. As a consequence: + +- `GeneratedTemplate.ContentHash` works as a cache key or ETag; +- snapshot tests are possible, in this repository and in consumers. + +## 3. Public API + +Namespace `TriasDev.Templify.Builder`. The listings show shape, not final signatures; task 1 freezes names in +`PublicAPI.Unshipped.txt`. + +### 3.1 API shape decision: composer classes with internal constructors + +The composers are **classes with internal constructors**, not interfaces: + +- users can neither implement nor derive from them; +- adding a member is non-breaking under RS0016/RS0017 and package validation. + +`CellComposer` and `BoxComposer` derive from `BlockComposer`, so every block container shares the same verbs. + +Users implement only three interfaces, each with a single member that will not grow: `ITemplateDefinition`, +`ITemplateComponent` and `ITextCatalog`. + +**Naming** (maintainer decision): the suffix is `…Composer`, as in `TemplateComposer`, `BlockComposer`, +`InlineComposer`, `TableComposer`, `RowComposer` and `ListComposer`. It matches `Compose`, and it does not clash with +the static `TemplateBuilder` entry point, the package name or core's types. Rejected: + +- `…Descriptor` (QuestPDF): odd for objects that add content; +- `…Builder`: a builder inside `TemplateBuilder`; +- `…Container`: suggests QuestPDF's decorator chain. + +### 3.2 Entry point and output + +```csharp +public interface ITemplateDefinition +{ + TemplateIdentity Identity { get; } + void Compose(TemplateComposer template); // runs on every Build; must not have side effects +} + +public sealed record TemplateIdentity(string Id, int Version); + +public sealed record TemplateBuildOptions +{ + public required TemplateFormat Format { get; init; } // core enum: Docx | Odt + public required CultureInfo Language { get; init; } + public ITextCatalog Texts { get; init; } = TextCatalog.Empty; +} + +public static class TemplateBuilder +{ + public static GeneratedTemplate Build(ITemplateDefinition definition, TemplateBuildOptions options); +} + +public sealed class GeneratedTemplate +{ + public TemplateFormat Format { get; } + public string FileExtension { get; } // ".docx" | ".odt" + public string MediaType { get; } + public ReadOnlyMemory Content { get; } + public string ContentHash { get; } // SHA-256, lower-case hex + public DataContract Contract { get; } + public TemplateStamp Stamp { get; } + public IReadOnlyList Warnings { get; } + public void WriteTo(Stream destination); + public Stream OpenRead(); +} + +public sealed class TemplateBuildException : Exception +{ + public IReadOnlyList Errors { get; } // all errors, not the first one +} +``` + +- **An invalid definition is a programming error, so `Build` throws.** It collects every error first (missing + translations, undefined style keys, an empty path used as a value, scope violations) and throws once. Core returns a + `ProcessingResult` because its errors come from users' templates and data; here they come from code. + - **Path syntax is checked where the path is written.** An invalid segment throws `ArgumentException` from the + `TemplatePath` indexer, so the stack trace points at the line in the definition. + - **Composers are valid only inside their lambda.** Using one afterwards throws `InvalidOperationException`. +- **`Compose` does not see the format.** Definitions cannot branch on it, except through `Raw` (section 3.9). +- **`TemplateFormat` is core's enum.** The builder depends on core anyway, so it does not define a second one. +- **Thread safety.** `Build` is a pure function. Concurrent builds share nothing mutable. + +### 3.3 Styles + +The builder ships value types and a stylesheet, but **no theme type**. A token vocabulary is product design, so the +product defines its theme as its own record and passes it to the definition's constructor. The customer's theme slots +arrive the same way. + +```csharp +public readonly record struct Length; // integer 1/1000 pt internally +public static class Units // 12.Pt(), 25.Mm() +{ + public static Length Pt(this double value); + public static Length Mm(this double value); +} +public readonly record struct Color; // Color.FromHex("1F4E79") +public sealed record FontFace(string Family); // referenced by name; no fallback (no ODF equivalent; additive later) +// #288: FontFace.Embedded(byte[] ttf) / Embedded(string family, byte[] ttf), IsEmbedded + +public sealed record ParagraphStyleKey(string Id, string DisplayName); // DisplayName is what Word / LibreOffice show +public sealed record CharacterStyleKey(string Id, string DisplayName); + +public sealed class StyleSheet +{ + public static StyleSheet Create(Action styles); +} +// usage (product code) +StyleSheet sheet = StyleSheet.Create(s => +{ + s.Defaults(d => d.Font(theme.Body).Size(10.5.Pt()).Color(theme.Ink)); + s.Paragraph(Styles.Body, p => p.LineHeight(15.Pt()).SpaceAfter(8.Pt())); + s.Paragraph(Styles.Heading1, p => p.BasedOn(Styles.Body).Font(theme.HeadingFont).Size(16.Pt()) + .SpaceBefore(20.Pt()).KeepWithNext().KeepLinesTogether().OutlineLevel(1)); + s.Character(Styles.Emphasis, c => c.Font(theme.MediumFont).Color(theme.Accent)); +}); +``` + +- **A key the stylesheet does not define is a build error.** +- **Paragraph and character styles become real named styles in both formats.** +- **The builder owns one well-known key, `BuilderStyles.TemplateMarker`** (display name "Template Marker"). + - By default it is visible and subtle: Courier New, 8 pt, grey `#737373`, no spacing, kept with the next + paragraph. It is written only when the template has markers. A style sheet that defines the key replaces the + default entirely. + - A product's stylesheet can change how it looks, and so can a customer, through the style in Word or LibreOffice. + - **There is no hidden-marker mode** (maintainer decision). A customer adapting a copy has to see the template's logic + to delete a block together with its markers (D3). +- **Table, box and list styles come later.** They are builder-level concepts (tasks 10, 14 and 15) that each writer + resolves. Word table styles have no ODF counterpart, so they are not mapped one to one. + +### 3.4 Content + +```csharp +public class BlockComposer // body, header, footer, cell, box, and the bodies of If and ForEach +{ + public void Paragraph(ParagraphStyleKey style, string text); + public void Paragraph(ParagraphStyleKey style, TemplatePath value, ValueFormat? format = null); + public void Paragraph(ParagraphStyleKey style, Action content); + public void PageBreak(); + public void Component(ITemplateComponent component); + + public IfChain If(Condition condition, Action then); + public void Switch(TemplatePath value, Action cases); + public void ForEach(TemplatePath collection, string itemName, Action body); + // later tasks: Table, List, Box, Rule, Image, TableOfContents, Raw +} + +public sealed class IfChain +{ + public IfChain ElseIf(Condition condition, Action then); + public void Else(Action otherwise); // void: nothing can follow an else +} + +public sealed class SwitchComposer +{ + public void Case(string value, Action then); + public void Case(IEnumerable values, Action then); // emitted as `in (...)` + public void Default(Action otherwise); // mandatory: a missing Default is a build error +} + +public sealed class InlineComposer +{ + public void Text(string text, CharacterStyleKey? style = null); // literal "{{" is a build error (TB1002): Templify has no escape for it + public void Value(TemplatePath path, ValueFormat? format = null, CharacterStyleKey? style = null); + public void Tab(); + public void TabRight(); // right tab stop at the frame's edge — task 9 (needs page setup) + public void LineBreak(); + // later tasks: If (inline, text only), Expression, Image, PageNumber, PageCount +} + +public sealed class ValueFormat // closed set: the engine's format specifiers +{ + public static ValueFormat Date(string pattern); + public static ValueFormat Number(string pattern); + public static ValueFormat Currency { get; } + public static ValueFormat Uppercase { get; } + public static ValueFormat Lowercase { get; } + public static ValueFormat Raw { get; } + public static ValueFormat YesNo { get; } + public static ValueFormat Checkbox { get; } + // further boolean formats as in core: TrueFalse, OnOff, Enabled, Active, Checkmark + public static ValueFormat Join(string? itemPath = null, string? separator = null); // :join, :join:Name:"; " + public static ValueFormat Custom(string specifier); // escape hatch, e.g. a registered boolean formatter +} +``` + +A `Switch` without any case writes its default unconditionally, with no markers. `Switch` exists because the engine cannot make a property depend on data: a fill colour per status, for example. The +answer is an if/elseif/else chain with one variant per value. A mandatory `Default` prevents the failure seen in practice, +where an unmapped value printed nothing. + +### 3.5 Paths, conditions, loops + +```csharp +public readonly struct TemplatePath +{ + public static TemplatePath Root(string path); // also: template.Data["order"] + public TemplatePath this[string relative] { get; } // "customer.address.city": dotted, each segment validated + public TemplatePath this[int index] { get; } // items[0] + public TemplatePath Key(string key); // one dictionary-key segment, validated against the engine's grammar + + public Condition Eq(string value); + public Condition Eq(double value); + public Condition NotEq(string value); + public Condition Gt(double value); // also Ge, Lt, Le + public Condition In(params string[] values); + public Condition Contains(string value); // also StartsWith, EndsWith + public Condition Exists { get; } + public Condition IsEmpty { get; } + public Condition IsNotEmpty { get; } + public static implicit operator Condition(TemplatePath path); // truthiness + public static Condition operator !(TemplatePath path); // C# does not apply the implicit conversion to find + public static Condition operator &(TemplatePath a, TemplatePath b); // operators when both operands are paths, + public static Condition operator |(TemplatePath a, TemplatePath b); // so TemplatePath declares them itself (#265) +} + +public abstract class Condition // a small AST +{ + public static Condition operator !(Condition operand); + public static Condition operator &(Condition left, Condition right); + public static Condition operator |(Condition left, Condition right); + public static Condition Raw(string expression, params TemplatePath[] uses); // checked with ConditionEvaluator.Validate +} + +public sealed class LoopItem // only exists inside a ForEach lambda +{ + public TemplatePath Self { get; } // {{item}} + public TemplatePath this[string relative] { get; } // {{item.relative}} + public Condition IsFirst { get; } + public Condition IsLast { get; } + public TemplatePath Index { get; } + public TemplatePath Number { get; } + public TemplatePath Count { get; } +} +``` + +- **One internal emitter** turns the AST into `{{#if}}`-dialect text. It owns: + - precedence, so `!a.Eq("x")` becomes `not (a = "x")`; + - quoting and escapes; + - escaping keyword-named segments as `[in]`; + - invariant number formatting. + + String operands are always quoted, so the engine's bareword rule never applies to generated templates. Numbers are + written in decimal notation (`100000000000000000000`, never `1E+20`): the condition lexer reads a number as one word + of digits, `.` and a leading `-`. Strings with `{{`, `}}`, control characters or typographic double quotes (which + the engine normalises to `"`) are rejected where they are written. +- **`ForEach` always emits a named iteration variable.** The names make the contract exact and the markers readable for + a customer editing the file. +- **Scope rules** (#266). A path remembers the loop whose variable it starts from. + - **Item names.** Letters, digits and `_`, starting with a letter or `_`. Not a Templify keyword (`in`, `this`, + `and`, `empty`, …), not the name of an enclosing loop's variable. Checked where written (`ArgumentException`). + - **TB4001.** A loop variable's path used outside its loop, for example a captured `LoopItem` after the loop. + - **TB4002.** `@index`/`@number`/`@count`/`@first`/`@last` of an outer loop used inside a nested loop: the + engine's metadata always refers to the innermost loop. An outer `LoopItem`'s *paths* stay usable in inner loops. + - **TB4003.** A path from the data's root whose first segment is the name of an enclosing loop variable: the engine + would resolve it to the item. + - **Known limit.** Inside a loop the engine also resolves names implicitly on the current item. A root path such as + `order.number` resolves to the item's `order` property if the item has one. The builder cannot see the data, so + the data contract (#267) and the item names chosen by the definition are the guard. +- **Product helpers.** For dictionary-keyed payloads, products write plain C# helpers over `TemplatePath`. The builder + needs no feature for that: + +```csharp +static Condition IsYes(TemplatePath scope, string question) => + scope["answers.byKey"].Key(question)["options.byKey"].Key("yes")["selected"]; +``` + +### 3.6 How the writers place markers + +| Engine rule | Guaranteed by | +|---|---| +| A block marker sits alone in its paragraph, as one run | `If`, `Switch` and `ForEach` exist only on block, row and list composers. The writer emits a one-run marker paragraph in `TemplateMarker`. | +| A table-row loop has `{{#foreach}}` and `{{/foreach}}` each in its own row, with the table's grid width | `ForEachRow` (task 11) emits full-grid marker rows. | +| `{{#elseif}}` comes before `{{#else}}`; `{{#else}}` comes last | `IfChain`; `Else` returns `void` | +| No loop inside a paragraph | `InlineComposer` has no `ForEach` | +| Loop metadata exists only inside a loop; iteration variable names are valid | `LoopItem`; names are validated at build | +| Every table cell ends with a paragraph | the writer (core also guarantees this after processing) | +| Placeholder and format syntax is valid | `TemplatePath` segment validation; the closed `ValueFormat` set | + +### 3.7 Components and sharing + +```csharp +public interface ITemplateComponent { void Compose(BlockComposer content); } +``` + +- **Simple blocks need no interface.** An extension method on `BlockComposer` is enough. +- **The model keeps a component as a unit** (`ComponentBlock`: the component and its content). This is the hook for + exporting definitions with component references (#274). A component composes in its caller's loop scope. +- **Implement `ITemplateComponent`** for a block with state, or one that is built through dependency injection. +- **Sharing sections between documents** means using the same component or method in several definitions. + +### 3.8 Localisation, contract, identity + +```csharp +public interface ITextCatalog { bool TryGet(string key, CultureInfo language, out string text); } +public static class TextCatalog +{ + public static ITextCatalog Empty { get; } + public static ITextCatalog FromResourceManager(ResourceManager resources); // no parent-culture fallback by default + public static ITextCatalog FromDictionary(IReadOnlyDictionary> texts); + public static ITextCatalog Combine(params ITextCatalog[] catalogs); // later catalogs override earlier ones +} +// in Compose: string title = template.Texts["invoiceTitle"]; (TemplateTexts, also .Language) +// every missing (key, language) pair is collected and reported in the single TemplateBuildException (TB5001) +// Lookup (#269): specific → neutral culture (de-AT → de), never the invariant culture — a missing German text fails +// the build instead of printing the default language. FromResourceManager(rm, neutralLanguage): the neutral .resx +// answers only for the declared neutral language (and its specific cultures). + +public sealed class DataContract +{ + public IReadOnlyList Entries { get; } // canonical paths: "order.items[].name" + public string Hash { get; } // over the sorted entries; independent of language, format and theme + public string ToJson(); + public static DataContract FromJson(string json); + public IReadOnlyDictionary CreateWitness(); // every path present, every collection with one item +} +public sealed record ContractEntry(string Path, ContractUsage Usage); // Value | Collection | Condition + +public sealed record TemplateStamp(string TemplateId, int Version, string ContractHash, string Language, + string BuilderVersion, string MinimumEngineVersion); + +public static class TemplateInspector +{ + public static TemplateInspection Inspect(Stream template); // format, Stamp (null = unknown origin) + public static UploadCheckResult CheckUpload(Stream template, DataContract current, TemplateIdentity? expected = null); +} +public static class TemplateStampRemover +{ + public static bool Remove(Stream document); // removes the stamp from a filled document, in place; DOCX and ODT +} +public sealed class UploadCheckResult +{ + public bool IsUsable { get; } // no syntax errors and no unknown paths + public TemplateFormat Format { get; } + public TemplateStamp? Stamp { get; } + public TemplateOrigin Origin { get; } // CurrentContract | DifferentContract | OtherTemplate | Unknown + public ValidationResult Syntax { get; } // core type + public IReadOnlyList UnknownPaths { get; } +} +``` + +- **The stamp says where a copy came from; it does not decide validity.** Other editors may drop custom properties, so a + missing stamp means "unknown origin", never "reject". A different contract hash is not an error either: an additive + payload change alters the hash while old copies stay valid. +- **Validity means the copy uses only known paths.** `CheckUpload` builds `current.CreateWitness()` and calls core's + `TemplateProcessor.ValidateTemplate(stream, witness)`. The missing variables and missing-condition-variable warnings + are the unknown paths. Core already resolves loop scopes, so this works on hand-edited copies with renamed aliases, + as spike 1 confirmed (section 9). + - `IsUsable` means: no `MissingVariable` errors, no `MissingConditionVariable` warnings, and no syntax errors. + - `UnknownPaths` lists the paths **as the copy writes them** (`l.discount`, with the customer's alias), because the + customer has to find them in that copy. Mapping them to canonical contract paths is not attempted. + - Unknown paths that are comparison operands (`{{#if order.priority = "high"}}`) are only found once #271 is fixed in + core. Task 7 depends on #271. +- **Stamp properties** (#268): `Templify.TemplateId`, `Templify.TemplateVersion`, `Templify.ContractHash`, + `Templify.Language`, `Templify.BuilderVersion`, `Templify.MinimumEngineVersion`, all strings. The versions are the + assemblies' informational versions without build metadata. `TemplateStampRemover` removes exactly the properties + with the `Templify.` prefix and keeps all others; in DOCX it deletes the custom-properties part if nothing else is + left. +- **Reading condition variables.** The engine does not yet expose the variable of a `MissingConditionVariable` + warning, so `CheckUpload` reads it from the message until #275 lands; a test pins the wording. +- **Where the stamp is stored.** DOCX: `docProps/custom.xml`. ODT: `meta:user-defined` in `meta.xml`. Core's + `DocumentProperties` option overwrites only the standard properties, so the stamp survives into filled documents. +- **The stamp stays in filled documents by default** (maintainer decision). Support can tell from a customer's document + which template and version produced it. A backend that sends documents to external recipients, and does not want + internal ids in their metadata, calls `TemplateStampRemover.Remove(stream)` after filling. Core does not change for + this. The helper removes only the builder's own properties, which use a builder-specific name prefix, and leaves every + other custom property alone. +- **Contract details** (#267). + - **Collected from the model:** values, every path of every condition (including `Switch` values and the declared + `uses` of `Condition.Raw`), loop collections, and the content of components. Loop metadata (`@index`, …) is not + data and is left out. + - **Canonical paths.** Loop variables are resolved: `line.description` inside `foreach line in order.lines` + becomes `order.lines[].description`, and an item printed as a whole becomes `order.lines[]`. + - **Hash.** SHA-256 over the sorted lines `" \n"` (usage in lower case), as lower-case hex. + - **JSON.** `{ "version": 1, "hash": …, "entries": [ { "path": …, "usage": "value|collection|condition" } ] }`. + `FromJson` recomputes the hash. + - **Witness.** Nested dictionaries, a one-item list per collection, `"x"` for every leaf. Filling a template with + its own witness raises no missing variable and no warning; a test asserts this for both formats. +- **The contract is the language parity check.** Its hash is equal across languages and formats; a test asserts this. That + replaces a hand-written EN/DE parity test. + +### 3.9 Escape hatch (task 17) + +```csharp +public sealed record RawBlock +{ + public required Func Docx { get; init; } // both are required: parity by signature + public required Func Odt { get; init; } + public IReadOnlyList Uses { get; init; } = []; // declared for the contract +} +``` + +It takes `XElement`, not OpenXML SDK types. SDK types never appear in the builder's public API, so the two packages +cannot become version-coupled through it. + +Font embedding as built (#288), in section 3.3's terms: + +- `FontFace.Embedded(ttf)` reads the family (name id 1, Windows English first) and `Embedded(family, ttf)` accepts a + family the file declares (id 1 or 16). The bytes are copied; equality is family plus file hash. +- TrueType outlines only: Word embeds TrueType, so `OTTO` (CFF), `ttcf` and WOFF are refused with a hint. +- `fsType`: installable (0) or editable (bit 3) only. A template is edited after download, so preview-and-print + (bit 2), restricted (bit 1) and bitmap-only (bit 9) are refused at `Embedded`. +- One file per family (TB2011 for two different files); one face (`embedRegular`) per family, matching the + one-family-per-weight rule. No subsetting: pass pre-subset files. +- Measured with LibreOffice 26.8: a family installed nowhere renders from the document in the PDF conversion, from + DOCX and from ODT (test `LibreOffice_RendersWithTheEmbeddedFont`, checked with `pdffonts`). Word is not tested on + CI; the DOCX passes the schema validation. + +As built (#285): + +- `c.Raw(RawBlock)` is on every `BlockComposer` (body, cells, boxes, headers, footers, loop and branch bodies). + `RawContext` gives the container's `Frame` width and `Placeholder(path, format?)`, which returns the placeholder + text only for a path declared in `Uses` (otherwise TB9102), so the contract cannot miss what the XML reads. `Uses` + paths are scope-checked like any other path (TB4001–4003) and recorded as values. +- Allowed roots: DOCX `w:p`, `w:tbl`; ODT `text:p`, `text:h`, `text:list`, `table:table`. Anything else, including + an element of the other format, is TB9101. The DOCX element becomes a typed `Paragraph`/`Table`, so the writer's + own rules apply to it (a paragraph between touching tables, the closing paragraph). +- The XML is written as given. It cannot add styles, numbering, relationships or ODT automatic styles; it may refer + to styles of the sheet. A construct that needs those belongs in the vocabulary, not in `Raw`. + +### 3.10 Example + +```csharp +public sealed class InvoiceTemplate(BrandTheme brand) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = new("invoice", Version: 3); + + public void Compose(TemplateComposer template) + { + var T = template.Texts; + TemplatePath invoice = template.Data["invoice"]; + + template.Styles(BrandStyles.Create(brand)); + template.Properties(p => p.Title(T["invoiceTitle"]).Author(brand.CompanyName)); + + template.Content(c => + { + c.Paragraph(BrandStyles.Title, T["invoiceTitle"]); + c.Paragraph(BrandStyles.Body, x => + { + x.Text(T["customer"] + ": "); + x.Value(invoice["customer.name"], style: BrandStyles.Strong); + }); + + c.ForEach(invoice["lines"], "line", (line, b) => + { + b.If(!line.IsFirst, r => r.Paragraph(BrandStyles.Separator, "")); + b.Paragraph(BrandStyles.Body, x => + { + x.Value(line["description"]); x.TabRight(); + x.Value(line["amount"], ValueFormat.Currency); + }); + }); + + c.Switch(invoice["status"], s => + { + s.Case(["paid", "settled"], b => b.Paragraph(BrandStyles.NoticeSuccess, T["paid"])); + s.Case("overdue", b => b.Paragraph(BrandStyles.NoticeDanger, T["overdue"])); + s.Default(b => b.Paragraph(BrandStyles.Notice, T["open"])); + }); + }); + } +} + +// at runtime, in the backend +GeneratedTemplate tpl = TemplateBuilder.Build(new InvoiceTemplate(theme with { Accent = tenant.Accent }), + new TemplateBuildOptions { Format = TemplateFormat.Odt, Language = CultureInfo.GetCultureInfo("de"), Texts = InvoiceTexts.Catalog }); +return Results.File(tpl.OpenRead(), tpl.MediaType, "invoice" + tpl.FileExtension); // download, or pass to TemplateProcessor +``` + +## 4. Internal architecture + +``` +ITemplateDefinition.Compose ──▶ composers ──▶ semantic model (internal, immutable) + │ + ▼ + analysis: scopes, style keys, frame widths, literal "{{", contract, capability per format + │ (errors → TemplateBuildException, warnings → GeneratedTemplate) + ▼ + TemplateSyntax: the one emitter of marker and placeholder text + ┌───────────┴───────────┐ + DocxWriter OdtWriter + └──────▶ DeterministicZip ◀──────┘ +``` + +- **Semantic model.** Blocks (`Paragraph`, `PageBreak`, `If`, `Switch`, `ForEach`, `ComponentScope`, and later + `Table`, `List`, `Box`, `Rule`, `Image`, `Toc`, `Raw`) and inlines (`Text`, `Value`, `Tab`, `Break`, and later + `InlineIf`, `Expression`, `Image`, `Field`). `If` and `ForEach` stay semantic until the writer, which chooses their + carrier: a marker paragraph, a full-grid row, or an ODT list item, which core treats like a row. +- **DocxWriter.** Builds the XML parts with the OpenXML SDK's typed elements, which keep the schema's child order. It + writes `document.xml`, `docProps/core.xml`, and later `styles.xml`, `settings.xml`, `docProps/custom.xml`, + `numbering.xml` and the header, footer and media parts. Ids come from counters: `docPr`, bookmarks, numbering. It + writes no rsids. The SDK stays behind the writer boundary. + + The writer assembles **the package itself** rather than through the SDK's packaging, because that packaging is not + deterministic. Measured with SDK 3.5.1 while building task 1, it gives every build: + - random relationship ids (`R2a7031b3f8ae41e2`); + - a random core-properties part name (`package/services/metadata/core-properties/.psmdcp`); + - the current time on every entry. + + The writer therefore uses fixed ids (`rId1`, …), the standard part names (`docProps/core.xml`) and a content-types + part of its own. +- **OdtWriter.** Uses `System.Xml.Linq` and `System.IO.Compression`, the same stack as core's ODT engine. It writes + `content.xml`, `styles.xml`, `meta.xml` and `META-INF/manifest.xml`, with `mimetype` first and stored. Automatic styles + get a builder prefix (`B…`), so they cannot collide with core's markdown `T{n}` styles. +- **DeterministicZip.** Writes both formats with a fixed entry order, a fixed timestamp (2000-01-01) and zeroed + external attributes. + - The bytes are reproducible on the same runtime and operating system family. + - They are not byte-identical between Windows and Unix: `ZipArchive` records the host platform in the "version made + by" field. That is acceptable, because `ContentHash` serves as a cache key within a deployment. + + Determinism also requires: + - no GUIDs; + - counter-based ids; + - invariant formatting of every number; + - integer units, rounded once per target unit; + - no creation or modification time unless the options set one. + +### 4.1 Format mapping (MVP part) + +| Concept | DOCX | ODT | +|---|---|---| +| Paragraph style | `w:style w:type="paragraph"`, `w:basedOn`, `w:next`, `w:outlineLvl` | `style:style style:family="paragraph"` in `office:styles`, `style:parent-style-name`, `style:next-style-name`, `style:default-outline-level`; a paragraph with an outline level is written as `text:h` | +| Character style | `w:style w:type="character"`, `w:rStyle` | `style:style style:family="text"`, `text:span text:style-name` | +| Defaults | `w:docDefaults` (font, size, colour, `w:lang`), widow control on | `style:default-style` per family; `fo:language` and `fo:country` | +| Spacing and keeping together | `w:spacing`, `w:keepNext`, `w:keepLines` | `fo:margin-top`/`fo:margin-bottom`, `fo:line-height` / `style:line-height-at-least`, `fo:keep-with-next`, `fo:keep-together` | +| Tab, right tab | `w:tab`; `w:tabs` with a right stop at the frame width | `text:tab`; `style:tab-stops` | +| Line break | `w:br` | `text:line-break` | +| Page break | a paragraph of its own: `w:p/w:r/w:br w:type="page"` | an empty paragraph of its own in the automatic style `TemplifyPageBreak` (`fo:break-after="page"`, so no empty line on the new page) | +| Character style on text | `w:rPr/w:rStyle` on the run | `text:span text:style-name` | +| Page (#277) | `w:sectPr`: `pgSz`, `pgMar` (top/right/bottom/left/header/footer), `titlePg`; always written (default A4, 25 mm margins, 12.5 mm header/footer distance) | `style:page-layout` "TemplifyPageLayout" + master page "Standard" | +| Header / footer | `header1.xml`, `footer1.xml` (+ `header2.xml`/`footer2.xml` for a distinct first page, empty for "none"), `headerReference`/`footerReference` | `style:header`/`style:footer` (+ ODF 1.3 `style:header-first`/`style:footer-first`); ODF measures the top margin to the header, so page `fo:margin-top` = header distance and the header's `fo:min-height` = top margin − header distance: the body starts where Word starts it | +| Page number / count | complex fields `PAGE` / `NUMPAGES` with a cached `1` | `text:page-number text:select-page="current"` / `text:page-count` | +| Table (#278) | `w:tbl`: `tblW`, `tblBorders` (outer + insideH/insideV from the table style), `tblLayout fixed`, `tblCellMar`; `tblGrid` from the resolved widths; cell `tcW` = the sum of its rounded grid columns (so `tcW` and `tblGrid` agree), `gridSpan`, `shd`, `vAlign`, header-rule as `tcBorders/bottom`; rows `cantSplit` (unless `AllowSplit`), header rows `tblHeader`; `SpaceAfter` as a 1 pt paragraph; a paragraph between two touching tables (Word would merge them) | `table:table` with automatic table, column, row (`keep-together`) and cell styles; `border-model="collapsing"` and per-cell borders (ODF has no table-level borders); header rows in `table:table-header-rows`; spans with `table:covered-table-cell`; `SpaceAfter` as the table's `fo:margin-bottom` | +| Row loops / row conditionals (#279) | marker rows: one `w:tc` with `gridSpan` = all columns and `tcW` = the table width, holding the marker paragraph | marker rows: one cell with `table:number-columns-spanned` = all columns plus `table:covered-table-cell`s | +| Inline conditional / expression (#281) | markers as plain runs inside the paragraph around the branch runs (`{{#if …}}`, `{{#elseif …}}`, `{{#else}}`, `{{/if}}`, nesting allowed); `{{(condition):format}}` as one run. Branch content is text and values only (`TextComposer`), no tabs, breaks or images. Expressions use the engine's inline dialect (only `true` is truthy) | the same text inside `text:p`, white-space encoded | +| Image (#280) | `word/media/imageN.{png,jpeg}`, each distinct image (by SHA-256) once; relationships per part (`document.xml.rels`, `header1.xml.rels`, …); inline DrawingML with a document-wide `docPr` counter and the alt text as `descr`; EMU = pt × 12 700 | `Pictures/.{png,jpeg}` + manifest entries; `draw:frame` (`text:anchor-type="as-char"`, unique `draw:name` per part prefix) with `draw:image` and `svg:title`/`svg:desc` (alt text) | +| Box / Rule (#282) | a box is a one-cell `w:tbl` over the container's width: the box style's border as `tblBorders`, padding as `tblCellMar`, background as the cell's `shd`; rows may split. A rule is an empty paragraph (exact 1 pt line) with a top `pBdr` and spacing | the same one-cell `table:table` with per-cell border, padding and background; a rule is an empty paragraph in an automatic style (`fo:border-top`, `fo:line-height` 1 pt) | +| Bullet list (#283) | items are paragraphs with `numPr` (`ilvl`, one `numId` per list style used) after `pStyle` (the list's item style); `numbering.xml` with an `abstractNum` of bullet levels (`lvlText`, `ind left/hanging`); loops and conditionals over items are block markers between item paragraphs | `text:list-style` (`text:list-level-style-bullet`, label alignment: tab stop at the indent, `fo:text-indent` = −hanging); each item is a `text:list` of its own, nested to its level — consecutive lists of one style read as one list, and loop/conditional markers stay paragraphs between them. LibreOffice's *text* export draws its own bullets per level; the rendered document shows the style's | +| Table of contents (#284) | a paragraph with a complex field `TOC \o "1-N" \h \z \u`, `w:dirty="true"`, no cached result | `text:table-of-content` (`text:outline-level` N, an entry template per level with link, text, right tab with dot leader, page number), empty `text:index-body` | +| TOC entry styles (#295) | paragraph styles `TOC1` … `TOC9` named "toc 1" … "toc 9", based on the entry style of that level (LibreOffice maps them to "Contents N") | `text:table-of-content-entry-template text:style-name` = the entry style; levels without one keep "Contents N" | +| Paragraph options (#296) | `w:pPr` of the paragraph: `keepNext`, `keepLines` after `pStyle`, `w:spacing` with only the attributes set | an automatic paragraph style with the named style as parent; when either spacing is set both `fo:margin-top` and `fo:margin-bottom` (the other resolved through `BasedOn`), `fo:keep-with-next`, `fo:keep-together`; one style per combination, shared with the right tab | +| Spacer (#296) | an unstyled `w:p` with `spacing before=0 after=0 line= lineRule=exact` | `text:p` in an automatic style (`…Gap1`): margins 0, fixed `fo:line-height` | +| Short rule, style bottom border (#296) | the rule paragraph gets `w:ind w:right` = frame − width; a style's `pBdr/bottom` with `w:space` in points | `fo:margin-right` = frame − width; a style's `fo:border-bottom` and `fo:padding-bottom` | +| Per-side padding and borders (#296) | `tblCellMar` per side; a cell's `tcMar`; `tblBorders` per side; a cell's `tcBorders` with its own sides (merged with the header rule, own wins) | the cell style's four paddings and four edge lines; a cell's own line replaces the computed one on that side | +| Table indent, space before (#296) | `tblInd` = indent + left cell margin (legacy layout measures it to the first cell's text); a 1 pt paragraph before the table carries the space before | `fo:margin-left`, `fo:margin-top` on the table | +| ODT parity (#298) | — | a derived paragraph style that sets only one of space before/after restates the other from its parent chain (LibreOffice reads both as one item); the first paragraph, table or rule after a page break (and the first of each branch of a conditional there; not in loops or cells) gets no space before, as LibreOffice's DOCX import does | +| End of a part | the body, headers and footers always end with a paragraph (Word keeps one after a final table; LibreOffice 26.8's text export loops forever on a DOCX whose body ends with a table — found in #279) | — | +| Column widths | fixed widths as given; relative weights share the container frame (page frame, or a cell's width minus its horizontal padding for nested tables) | same resolution | +| Right tab (`TabRight`) | `w:tabs/w:tab w:val="right"` at the frame width, measured from the frame's start | an automatic paragraph style with `style:tab-stop style:type="right"`, positioned at frame width − the style's start indent (ODF measures from the indent) | +| Marker | one-run paragraph in `TemplateMarker` | `text:p` in `TemplateMarker` with the marker as its only text | +| Language | `w:lang` in the defaults, `dc:language` | `fo:language` and `fo:country`, `dc:language` | +| Properties | `docProps/core.xml` (title, creator, subject), `docProps/custom.xml` (stamp) | `meta.xml` (`dc:title`, `meta:initial-creator`, `dc:subject`, `meta:user-defined`) | +| Embedded font (#288) | `word/fonts/fontN.odttf`, obfuscated (the first 32 bytes XOR the font key's 16 bytes in reverse order), related from `word/_rels/fontTable.xml.rels`; `word/fontTable.xml` `w:font` with `w:embedRegular r:id w:fontKey`; `word/settings.xml` `w:embedTrueTypeFonts`; the key is a GUID from the file's SHA-256 (deterministic); named relationship ids (`rIdSettings`, `rIdFontTable`), so numbered ids do not shift; nothing is written without embedded fonts | `Fonts/.ttf` + manifest (`application/x-font-ttf`); `style:font-face` with `svg:font-face-src/svg:font-face-uri` (`svg:font-face-format svg:string="truetype"`) | +| Raw block (#285) | the given `w:p` / `w:tbl`, as typed elements | the given `text:p` / `text:h` / `text:list` / `table:table` | + +Tables, boxes, lists, page setup, headers, footers, fields, images and the table of contents are mapped in the design +section of their tasks. The review's first draft is in #261. + +## 5. Verification + +Every builder test asserts these invariants for both formats, through a shared helper: + +1. **Structure.** `TemplateProcessor.ValidateTemplate` returns no errors. +2. **Contract.** `ValidateTemplate(witness)` reports no missing variables. The contract hash is equal across languages and formats. +3. **Render.** Processing sample data through `TemplateProcessor` with `MissingVariableBehavior.ThrowException` succeeds without warnings. +4. **Schema.** DOCX passes `OpenXmlValidator`; ODT passes core's `OdtDocumentVerifier` package checks. +5. **Determinism.** Two builds give equal bytes, also under tr-TR and ar-SA. +6. **LibreOffice.** In `[Trait("Category", "LibreOffice")]` tests, mandatory locally as for core: the built template and the filled document both open and convert. + +The consumer-facing test kit, `TriasDev.Templify.Builder.Testing` (task 18), packages the same checks plus a canonical +text dump for snapshot tests. A consumer builds at runtime, so its CI is where its definitions get verified. + +As built (#286), test-framework neutral: + +- `TemplateVerifier.VerifyAll(definitionFactory, options)` builds every language × format (`TemplateVerificationOptions`: + `Languages`, `Formats`, `Texts` per language, `SampleData` as JSON, `RequireEqualContracts`, `FailOnBuildWarnings`, + `DeterminismCultures` = tr-TR, ar-SA) and throws `TemplateVerificationException` listing every failure; `Verify` + returns the `TemplateVerificationReport` instead. Checks (`VerificationCheck`): build, structure (`ValidateTemplate`), + contract (`ValidateTemplate(witness)` reports no missing variable, and the witness fills without warnings), fill + (sample data, the target language as fill culture), package (template and every filled document), determinism + (a fresh definition from the factory under each culture), contract parity. Single checks: `CheckTemplate`, + `CheckFill`, `CheckPackage`. +- The ODT package check is the kit's own (no test-project code ships): `mimetype` first, stored, no data descriptor, + no extra field, ODT media type; manifest root type and listed files present; well-formed XML. +- `TemplateSnapshot.Create` dumps templates or filled documents in one notation for both formats (style per paragraph, + `→` tab, `↵` break, `[image]`, `{FIELD}`, `[list n]`, tables as indented rows/cells, then headers and footers). The + DOCX and ODT dumps of the same definition are equal unless DOCX needs layout paragraphs (after a table that ends a + part, between touching tables); a test asserts the equality. +- `LibreOfficeConverter` (`IsAvailable`, `Convert`, `ToPdf`, `ToText`) with a private profile per conversion. +- Dogfooding: the builder tests' `AssertInvariants`/`AssertPackage` are `CheckTemplate`/`CheckPackage`, so every builder + test now also fills the contract's witness. + +## 6. Support matrix + +| Target | Supported | +|---|---| +| DOCX in Microsoft Word (Windows, Mac) | yes | +| DOCX in LibreOffice (including the PDF conversion path) | yes | +| ODT in LibreOffice | yes | +| ODT in Word | best effort, not tested | + +Known behaviour of the converters, documented rather than worked around: + +- **Word's built-in style names.** LibreOffice maps a DOCX style named like a built-in Word style (`Body Text`, + `Heading 1`, `Title`) to its own style (`Text body`, `Heading 1`, …) when it opens the file. A display name of + your own (`Body Copy`) survives unchanged. Measured in task 2 (#263). + +- **Cell and box padding vs. border.** LibreOffice starts cell text after the padding plus (part of) the border + width; the two formats differ by under 2 pt for a 1 pt border (DOCX measures padding from the border's inner + edge, ODT centres collapsed borders on the edge). Measured in #282; accepted. + +The user-facing version of this matrix, the concepts and the known limits are on the documentation page +`docs/for-developers/template-builder.md` (#287). The sample `samples/TriasDev.Templify.Builder.Sample` uses every +construct, verifies itself with the test kit and runs as a builder test (`SampleTests`), so CI keeps it working. + +Known differences become build warnings when the construct is used. The first entries arrive with their tasks: + +- **table of contents (#284, measured):** a DOCX TOC field (dirty, `\o "1-N" \h \z \u`, no `\t`) is built by + Word on open (fill with `UpdateFieldsOnOpen = Auto`, which writes `w:updateFields`). LibreOffice does **not** + build a TOC on load or on PDF conversion, neither from DOCX nor from ODT (an empty `text:index-body`); it stays + empty until a user updates it. The build warns (TB9001, `GeneratedTemplate.Warnings`) in both formats. For a + server-side PDF with a TOC, the converter has to update the indexes (for example a LibreOffice macro); + out of scope for the MVP; +- paragraph-border "between" rules have no ODF equivalent, which is why boxes are tables (task 14). + +## 7. Packaging and release + +- **Projects:** + - `src/TriasDev.Templify.Builder`: TFMs as the library, its own `PublicAPI.Shipped.txt`/`PublicAPI.Unshipped.txt` + and `packages.lock.json`, and a `ProjectReference` to core, which becomes a NuGet dependency on the core version of + the build; + - `src/TriasDev.Templify.Builder.Testing` (#286): the consumer test kit, same TFMs, own `PublicAPI` files, released + with the builder on its version line; + - `tests/TriasDev.Templify.Builder.Tests`. + + All are added to `templify.slnx` under the existing solution folders. +- **Release.** + - **Since task 1:** the root release-please package has `exclude-paths` for `src/TriasDev.Templify.Builder`, + `src/TriasDev.Templify.Builder.Testing` and `tests/TriasDev.Templify.Builder.Tests`. A commit whose files all lie there does not bump core. A commit that also + touches shared files (`templify.slnx`, docs, CI) still counts for core; its release-notes entry is edited by hand, + as today. + - **Before the first preview release:** a second release-please package, component `templify-builder`, with tags + `builder-v0.x.y` and `bump-minor-pre-major`. The publish job packs and pushes the builder too. Until then nothing + publishes the builder, so it cannot reach NuGet by accident. + - **As built (#289):** package `src/TriasDev.Templify.Builder`, component `builder` (so the tags read + `builder-v0.x.y`), `release-type: simple` with `version.txt` as the single version source of the builder and the + test kit (both csproj files read it), `additional-paths` for the test kit, the builder tests and the sample (this option does not exist in release-please + and was ignored; replaced before the merge into main by the package `src` minus `src/TriasDev.Templify`, see + CONTRIBUTING.md "Builder releases"), + `bump-minor-pre-major`, the first release pinned with `release-as: 0.1.0` (manifest `0.0.0` = never released), + and `separate-pull-requests`, so core and builder get their own release PRs. A release-please dry run against + `feature/builder` showed core 1.11.0 (#253, #254, #255, #272 only) and builder 0.1.0 (the builder's features) + as separate release notes; without `separate-pull-requests` they were merged into one PR. + The release workflow has a separate `publish-builder` job on the per-path outputs + (`src/TriasDev.Templify.Builder--release_created`); the core `publish` job still keys on the root outputs. It runs + the builder tests, packs both packages and pushes them with Trusted Publishing (`nuget` environment). + - **Core first.** The builder package depends on the core version in `TriasDev.Templify.csproj`, and the builder + already needs core changes released after 1.10.0 (`:join` #273, `updateFields` position #256, …). + `publish-builder` refuses to publish unless that core version is on nuget.org and the core source is unchanged + since its tag. So the first preview follows the next core release (1.11.0). +- **Package validation.** Off until the first release. During `0.x` the baseline points at the previous `0.x` release. + Breaking changes are allowed there but must be deliberate: entries move in `PublicAPI.Shipped.txt`, and the package + validation difference is recorded in a compatibility suppression file. +- **The LibreOffice helper.** Core's test helper for finding and running `soffice` is shared with the builder tests by + linking its source file. There is no shared test project. + +## 8. Phase plan + +Phase 1 ends with a usable letter- or notice-type template with a data contract and an identity stamp: + +| Task | Issue | +|---|---| +| 0 Design spec, spikes | #270 | +| 1 Walking skeleton | #262 | +| 2 StyleSheet | #263 | +| 3 Inline content | #264 | +| 4 Block conditionals, `Switch` | #265 | +| 5 Paragraph loops, components | #266 | +| 6 Data contract | #267 | +| 7 Identity stamp, upload check | #268 | +| 8 Localisation | #269 | + +Phase 2 (tasks 9–19: page furniture, tables, row loops, images, inline conditionals, box and rule, lists, table of +contents, raw, test kit, sample and docs) is listed in #261. Its issues are written after phase 1. + +## 9. Spikes + +Both spikes ran on 2026-11-25 against `main` (da01316) on net11.0, with hand-built DOCX and ODT templates fed to the +public `TemplateProcessor`. The spike code was temporary and is not committed. Its findings carry over into the tests of +tasks 7 and 14. + +### 9.1 Spike 1: the upload check + +**Setup.** One template, as DOCX and as ODT, containing: + +- a value placeholder and a nested value placeholder; +- a dictionary-key condition (`order.flags.byKey.express.selected`); +- a named loop with a nested named loop that reads the outer item and the root; +- `{{@number}}`, and a condition on `@last`; +- a format specifier; +- an if/else on a comparison. + +The witness was the payload a `DataContract` of that template would produce: every path present, every collection with one +item. + +**Result.** The approach works. DOCX and ODT give identical results. + +| Variant | Reported | Verdict | +|---|---|---| +| Unchanged | nothing | correct: no false positives from loop aliases, nested scopes, outer-item access, `@number`, `@last`, a dictionary-key path or a format specifier | +| Two sections deleted by hand | nothing | correct | +| Loop alias renamed by hand (`line` → `l`) | nothing | correct | +| New unknown paths: a root value, a property in a loop, a property in a nested loop, a collection, a root truthiness condition | `order.endDate`, `line.discount`, `tag.color`, `order.attachments` (all `MissingVariable` errors); `order.archived` (`MissingConditionVariable` warning) | correct | +| Unknown property in a renamed loop | `l.discount` | correct; the name is the one the copy uses | +| Loop without an alias, implicit `{{discount}}` | `discount` | correct | +| Unknown paths in conditions: truthiness, `not`, inside a loop | `MissingConditionVariable` warnings | correct | +| Unknown paths in an inline expression `{{(a and b):yesno}}` | `MissingVariable` errors | correct | +| Unknown paths as comparison operands: `=`, `>`, `in (…)`, `is empty`, also inside a loop | **nothing** | gap. The bareword rule treats an unresolved operand as a string literal. Filed as **#271** (core validator); task 7 depends on it. | + +The "stamp removed" variant needs no engine check: the stamp is not part of validation. Task 7 covers it in +`TemplateInspector`. + +**Consequences for the design** (section 3.8): + +- `CheckUpload` combines `MissingVariables` with the `MissingConditionVariable` warnings. +- `UnknownPaths` keeps the copy's own names. +- No second path extractor is needed in the builder. + +### 9.2 Spike 2: a box as a one-cell table + +**Setup.** A body loop `{{#foreach box in boxes}}` around a one-cell table. The cell holds: + +- a paragraph with `{{box.title}}` and `{{@number}}`; +- a block `{{#if box.show}}`; +- a paragraph loop `{{#foreach item in box.items}}`; +- a nested two-column table with a header row, a table-row loop `{{#foreach row in box.rows}}` (marker rows with an empty + second cell) and a row reading the outer `box.title`; +- a trailing paragraph. + +A second one-cell table holds only a conditional that is false. The data has two boxes: one with everything shown and +three rows, one with `show = false` and empty collections. + +**Result.** Both engines processed everything correctly: + +- The box repeats once per item. +- The `If` removes or keeps its content. +- The paragraph loop and the nested row loop expand and read the outer variable. +- Empty collections leave only the inner header row. +- The cell whose only content was removed **keeps an empty paragraph** in both formats. +- ODT: the cloned tables get unique names (`Box`, `Box_2`, `Inner`, `Inner_2`). +- `ValidateTemplate` reported no errors for either template. +- LibreOffice 26.8 converted both filled documents to PDF, with the same text in the same order. + +**Consequence.** A box is a one-cell table, as section 6 assumes. No engine work is needed before task 14. + +## 10. Maintainer decisions on the open questions (2026-11-25) + +1. **Marker look.** Markers are visible and subtle by default, and they can be restyled through the `Template Marker` + style. There is no hidden-marker mode (section 3.3). +2. **Stamp in filled documents.** It is kept by default. `TemplateStampRemover.Remove` strips it for documents that go + to external recipients (section 3.8). +3. **Naming.** Composer types use the suffix `…Composer` (section 3.1). diff --git a/docs/superpowers/specs/2026-11-26-builder-compact-json-design.md b/docs/superpowers/specs/2026-11-26-builder-compact-json-design.md new file mode 100644 index 00000000..75ff2500 --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-compact-json-design.md @@ -0,0 +1,171 @@ +# Builder: compact JSON definitions (design) + +Status: draft for approval · 2026-11-26 · epic #261, follows phase 3 (#274) +Amends: `2026-11-25-builder-phase3-json-and-typed-data-design.md`, section 4.1 (shape). Everything else in that spec +(import pipeline, diagnostics, components, typed paths, determinism, round trip) stays as it is. + +## 1. Intent + +The phase 3 evaluation showed that the exported JSON is hard to read and expensive for agents: the sample is 717 lines +and ~18,000 characters, a table cell holding one value takes 12–14 lines, and `"style": "BodyCopy"` repeats on almost +every paragraph. The maintainer looked at the file and chose to make the format compact before going further +(proposal 1 of the evaluation). Translation keys (proposal 2) and a source generator (proposal 4) are separate work. + +A throwaway spike (Python reformatter, `~/Desktop/templify-builder-phase3/proposal-1/`) measured the syntactic part: + +| | lines | characters | +|---|---|---| +| phase 3 export | 717 | 18,461 | +| compact layout only | 425 | 13,500 | +| layout + short forms | 343 | 10,782 | + +The semantic shortcuts below (placeholders in strings, default paragraph style, table text styles) are expected to cut +the sample further, to roughly 200 lines; the real number goes into the evaluation. + +## 2. Goals, non-goals, anti-goals + +Goals +- A definition that a person or an agent can read top to bottom: one line per simple block, the text of a sentence + visible as one string. +- The same model as today: every JSON form maps to something the C# API can express, and C# → JSON → build stays + byte-identical to building from C# (every builder test keeps round-tripping through JSON). +- The C# API gets the two style features too (default paragraph style, table text styles), so C# definitions shrink + the same way. + +Non-goals +- Backwards compatibility with the phase 3 shape. Nothing was released; `templifyDefinition` stays `1` and the reader + accepts only the new shape. +- Conditions or loops inside strings. `{{#if}}`/`{{#foreach}}` stay structural objects; the JSON stays a tree, not a + second template language. +- Translation keys, JSON Schema, YAML. + +Anti-goals +- Two equally valid ways to write the same thing where one suffices: agents copy whatever they see, and every + alternative doubles what the reader, the docs and the diagnostics must cover. +- A shortcut that makes the output depend on where a block sits in a way the file does not show (the style + inheritance in 4.3 is the one exception, and its order is fixed and documented). + +## 3. Approaches (decided in the conversation, 2026-11-26) + +1. **Overall scope** — A: layout only; **B: layout + short forms (chosen)**; B + semantic shortcuts discussed one by + one below. B because the format is unreleased and readability, not only size, was the problem. +2. **Values in text** — a: keep `{"value": …}` objects; **b: Templify placeholders `{{…}}` inside strings (chosen)**. + The builder already rejects `{{` in literal text (`InlineComposer`), so `{{` in a JSON string can only be a value. +3. **Default paragraph style** — a: none (unstyled = Normal); **b: a named default in the style sheet (chosen)**; + c: make Normal itself the body style. b keeps the named style, is opt-in and symmetric in C# and JSON. +4. **Table text** — **a: text styles on the table style, override on the row (chosen)**; b: on each table; c: both. + a because text formatting is part of a table's design and is reused like its rules and background. + +## 4. The format + +### 4.1 Layout (writer) + +- Two-space indentation. An object or array whose single-line form fits in **100 characters** (counting indentation and + its key) is written on one line, `{"a": 1, "b": 2}` / `["x", "y"]` with a space after `,` and `:`; otherwise each + member goes on its own line and the rule applies again one level down. Strings are never wrapped. +- Deterministic: the same model always gives the same text. +- Key order: options first, then the key holding the payload — `{"style": "SectionHeading", "paragraph": "Kunde"}`, + `{"style": "LineGrid", "columns": […], "table": […]}`. Blocks whose kind key holds a head (`if`, `forEach`, + `component`, `forEachRow`, `rowsIf`, `group`) keep the head first, as today. + +### 4.2 Text with values + +Wherever inline content is expected (paragraph content, list item content, inline `if` branches, cell content given as +a string), a string is **text with placeholders**: + +```json +"Auftrag {{order.number}} · {{order.date:date:d. MMMM yyyy}}" +"Kostenloser Expressversand: {{(order.isExpress and order.total > 1000):yesno}}" +``` + +- `{{path}}`, `{{path:format}}` and `{{(condition)}}`, `{{(condition):format}}` — the syntax Templify itself reads, + with the builder's own path, format and condition parsers (the builder uses only the core's public API). +- Inline content is a string or an array of pieces. A piece is a string (text with placeholders) or an object: + - `{"text": "…", "style": "MutedText"}` — styled text; the string may contain placeholders, every resulting piece gets + the character style (`{"text": "{{order.number}}", "style": "StrongText"}` is a styled value); + - `{"if": …, "then": …, "else": …}` — inline condition; branches are inline content (string or array); + - `{"tab": true}`, `{"tabRight": true}`, `{"lineBreak": true}`, `{"pageNumber": true}`, `{"pageCount": true}`, + `{"image": …}` — unchanged. +- The `value` and `expression` objects are removed (anti-goal: one way per thing). +- Errors: a malformed placeholder (`{{` without `}}`, a bad path, an unknown format, a bad condition) is TB9200/TB9201 + at the string's pointer, the message quoting the placeholder; unknown paths and wrong kinds stay TB9203 per + placeholder. `}}` without `{{` stays literal text, as in Templify. +- Export merges a run of same-styled text and value pieces into one string, **only where import splits it back into the + same pieces**: two adjacent text inlines stay separate array entries, so the round trip stays byte-identical. + +### 4.3 Paragraph styles by inheritance + +New in the model and the C# API: + +```csharp +s.Defaults(d => d.Font(...).Size(...).Paragraph(Styles.BodyCopy)); +s.Table(Styles.LineGrid, t => t.RowRule(...).TextStyle(Styles.TableText).HeaderTextStyle(Styles.TableHeader)); +t.Row(r => r.TextStyle(Styles.TableHeader).Cell(...)); +``` + +```json +"defaults": {"font": "Liberation Sans", "size": "10pt", "color": "#1A1A1A", "paragraph": "BodyCopy"}, +"table": {"LineGrid": {"rowRule": "0.5pt #D4D4D4", "textStyle": "TableText", "headerTextStyle": "TableHeader", …}}, +{"textStyle": "TableHeader", "row": [{"span": 3, "content": "Gesamtbetrag"}, "{{order.total:currency}}"]} +``` + +A paragraph without its own style gets the first of: +1. inside a table cell: the row's `textStyle`; then the table style's `headerTextStyle` (header rows) or `textStyle` + (other rows); +2. the style sheet's default paragraph style; +3. none (Normal), as today. + +List items keep their list style's `itemStyle`; without one they inherit like any other paragraph (decided in the final review). The style is resolved at composition and stored in the model, so the +writers do not change and the document carries an explicit `pStyle` / `text:style-name`. Export omits a paragraph's +style when it equals the inherited one. Without `Paragraph(...)` in the defaults and without table text styles, +definitions build exactly as today. + +### 4.4 Short forms + +| Where | Form | +|---|---| +| block | a string = a paragraph in the inherited style: `"Zahlbar innerhalb von 14 Tagen."` | +| paragraph | `{"style": "SectionHeading", "paragraph": "Kunde"}`; `paragraph` holds inline content | +| box | `{"style": "SuccessBox", "box": [blocks]}` | +| list | `{"style": "Bullets", "list": [items]}`; an item is a string, `{"level": 1, "item": inline content}`, or `forEach`/`if` as today | +| table | `{"style": "LineGrid", "columns": […], "spaceAfter": "8pt", "table": [rows]}` | +| row | `{"header": true, "textStyle": …, "row": [cells]}` | +| cell | a string (one paragraph), an array of blocks, or `{"span": 3, "background": …, "align": …, "content": string or blocks}` when it has options | + +`toc`, `rule`, `raw`, `pageBreak`, `component`, `group`, `forEach`, `if` keep their phase 3 shape. + +### 4.5 The sample after the change (excerpt) + +```json +{"style": "LineGrid", "columns": ["10mm", 4, "16mm", "30mm"], "spaceAfter": "8pt", "table": [ + {"header": true, "row": ["#", "Beschreibung", "Menge", "Betrag"]}, + {"forEachRow": "order.lines", "as": "line", "rows": [ + {"row": ["{{@number}}", [ … description and tags … ], "{{line.quantity}}", "{{line.amount:currency}}"]} + ]}, + {"rowsIf": "order.discount > 0", "then": [{"row": [{"span": 3, "content": "Rabatt"}, "{{order.discount:currency}}"]}]}, + {"textStyle": "TableHeader", "row": [{"span": 3, "content": "Gesamtbetrag"}, "{{order.total:currency}}"]} +]} +``` + +(Shown hand-wrapped; the writer applies 4.1.) + +## 5. Calls left to the builder (made here, check while reading) + +- **Styled values** are `{"text": "{{…}}", "style": …}`, not a `value` object with a style (said differently in the + conversation; this removes `value`/`expression` entirely). Cost if wrong: re-add one object form. +- **No way to force "no style"** inside a scope that inherits one. The sample's first-page logo paragraph will get + `BodyCopy` (6 pt space after) unless the sample gives it its own style; the sample will define one if the layout + changes visibly. Cost if wrong: add an explicit "Normal" marker later. +- **Line width 100.** Cost: a constant. +- The sample's C# (`OrderConfirmation.cs`, `TypedOrderConfirmation.cs`) switches to the default paragraph style and + table text styles, so its documents are regenerated; the Desktop artefacts are refreshed. + +## 6. Verification + +- The existing JSON tests move to the new shape; `BuilderHarness.AssertJsonRoundTrip` keeps every builder test + round-tripping byte-identically. +- New tests: placeholder strings (paths, formats with quotes like `join:" · "`, expressions with `)` and `:` inside + quoted strings, malformed placeholders with pointers), merging/splitting on export, style inheritance order + (paragraph > row > table header/body > default > none, lists unaffected, nested box/if inside a cell), short forms + and their errors, writer layout (fits/does not fit at exactly 100). +- Phase 3 spec section 9 gets the new numbers (lines, characters, tokens) for the sample. diff --git a/docs/superpowers/specs/2026-11-26-builder-direction-review.md b/docs/superpowers/specs/2026-11-26-builder-direction-review.md new file mode 100644 index 00000000..2d452512 --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-direction-review.md @@ -0,0 +1,51 @@ +# Builder: direction review (2026-11-26) + +Status: findings of an independent review, accepted by the maintainer as the plan for phase 4 · epic #261 + +After phase 3 (JSON definitions, compact format, text keys, typed path generator) the maintainer asked independent +reviewers (separate agents, not the authors) whether the direction holds for the pilot product: a backend that today +ships about ten built-in templates in German and English, produced by a homegrown generator, and that wants runtime +generation, customer theming, customer-edited copies and, later, JSON definitions edited by LLM agents. This was not a +code review. The full reports contain the pilot's material and are kept outside the repository. + +## Verdicts + +| Question | Answer | +|---|---| +| Can the pilot's templates be described with the builder (C# and/or JSON)? | **Yes.** The largest template (778 placeholders, 67 tables, 54 loops, 203 conditionals) was described almost completely as one JSON definition; filled with the pilot's fixture it matches the original in pages and words (16 pages, 1,906 words), DOCX and ODT, both languages. | +| Is "C# definitions + a JSON form of the same model" the right architecture? | **Yes**; no alternative (keeping the generator, hand-maintained documents, a separate DSL, HTML→DOCX, a document model library) combines runtime generation, ODT, theme slots and per-customer definitions. Proven on few documents so far: port a real template before building the agent layer. | +| Can a cheap model (Haiku-class) edit JSON definitions? | **8 of 8 typical edits correct on the first try**, without a validator, each minimal: rename a heading, add a table column, change a row condition, move a section, add a conditional box, restyle headings; two of them on the large definition. | +| Is the JSON format a good basis for agents and people? | **Yes, keep it.** Before customer definitions are stored: close silent mistakes, a few cheap renames, theme tokens and named assets. | + +## Gaps found + +Builder (needed to port the built-in templates): +- indexed path segments (`items[0].textValue`) are rejected — 63 placeholders in 6 of 10 templates, some inside legal + sentences where a loop is no substitute; +- a cell or box ending with a conditional, loop or nested table ends with a table once Templify removes the markers; + LibreOffice then silently drops the outer table's borders and padding; +- two tables separated only by marker paragraphs merge into one after filling; +- a style display name with a comma gives schema-invalid DOCX without a diagnostic; +- table geometry for a risk matrix (rotated text, vertical merge, per-cell borders) — otherwise a `Raw` component. + +JSON format (before any customer definition is stored): +- silent mistakes: unknown value formats (`{{x:N2}}`), four-value padding truncated, a loop variable shadowing the data + root, incomplete `texts`, unknown data paths without a data catalogue; +- colours baked into styles and images addressed by hash: theme tokens and named assets are needed; +- naming: `textStyle` means a paragraph style, list `if` uses `items` for its branch, `texts` grouped by language rather + than by key, cell `align`; +- no named sections or definition-local fragments (one block repeats up to 23 times in the large definition). + +Lifecycle: a policy for evolving data contracts, re-checking stored customer copies and versioning components; a data +catalogue that does not need a CLR type. + +Agent layer (later): a JSON cheat sheet generated from the reader, error hints for common slips, edit operations +(replace section, set text, set style) instead of JSON Patch, JSON Schema, and a benchmark of 20–30 reference edits. + +## Plan (phase 4, in this order) + +1. Builder blockers: indexed paths; closing paragraph in cells and boxes; separated adjacent tables; style name check. +2. Port one real template end to end (in the pilot product, not in this repository) and compare in Word and in PDF. +3. JSON format round: theme tokens, named assets, strict reader, renames, `texts` by key, named sections. +4. Evolution policy for data contracts and customer copies. +5. Agent layer: cheat sheet, diagnostics, edit operations, schema, benchmark. diff --git a/docs/superpowers/specs/2026-11-26-builder-evolution-policy-design.md b/docs/superpowers/specs/2026-11-26-builder-evolution-policy-design.md new file mode 100644 index 00000000..f2b338ef --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-evolution-policy-design.md @@ -0,0 +1,55 @@ +# Builder phase 4, step 4: checking stored templates (design) + +Status: approved by the maintainer, 2026-11-26 · #294 · epic #261 + +## Intent + +The data a host gives its templates changes. A renamed or removed field silently prints nothing in a stored template +that still reads it: a customer's edited copy (DOCX/ODT) or a stored JSON definition. The host must be able to find +those templates and mark them. Templates the host builds from code are rebuilt and need nothing. + +**Boundary:** the library checks, the host decides. Storage, when to re-check (for example on deploy), how to show +the result (yellow, red) and fixing (by hand or by an agent that reads the host's changelog of data changes) belong to +the host. + +## Approaches + +1. **Check only (chosen).** One check for any stored template against the current data catalogue, with a status and a + list of problems. Renames are breaking changes; affected templates turn red. Simple, and works for any template, + also for ones the builder did not produce. +2. **Declared renames** (`formerly` marks in the catalogue, contract diff in CI, automatic rewriting of JSON + definitions). Rejected by the maintainer: every data change needs extra bookkeeping, and an agent with the host's + changelog can fix templates better than fixed rules. +3. **Updating Word copies in place** (component boundaries in the document). Rejected: fragile, Word edits break the + marks. Components are updated through JSON definitions, which name registered components and get the current + version on every build. + +## Design + +- **Check:** `TemplateInspector.Check(Stream, TemplateCheckOptions)` for DOCX/ODT and + `TemplateInspector.CheckDefinition(string json, …)` for JSON definitions. Both return a `TemplateCheckResult`: + - status `Ok`, `Warning` (works, but outdated or of unknown origin) or `Broken` (will not fill correctly); + - problems, each with a code, severity, message, and the data path and location when known. +- **Against the catalogue, not the contract:** a copy may read any field the data has (a customer may add one the + standard template does not use). The check replaces `CheckUpload`, which compared with the current template's + contract. +- **Broken:** a path the data does not have; a loop over something that is not a collection; template syntax errors; + a JSON definition that does not import or build. +- **Warning:** no stamp (unknown origin), the stamp names another template, an older definition version than expected, + a component built at an older version (or one no longer known). +- **Component versions:** `[ComponentVersion(n)]` on a component class (default 1); the stamp records the components a + template was built from and their versions. A JSON definition is never outdated by a component: it is rebuilt with + the current one. +- **Catalogue for agents and hosts:** `DataCatalog.ToJson()`. A host that commits this snapshot sees removed fields in + its diff, without code in the library. +- **Policy (docs):** adding fields is safe; renaming or removing one is a breaking change: re-check all stored + templates, the affected ones turn red. + +## Not in scope + +Contract diff, rename marks, rewriting templates, a definition hash in the stamp, reading a catalogue from JSON. + +## Left to the builder + +Codes (a new TB93xx range), the shape of the stamp property for components, whether `CheckDefinition` also builds, +how open catalogue shapes (dictionaries) are accepted in the check. diff --git a/docs/superpowers/specs/2026-11-26-builder-json-text-keys-design.md b/docs/superpowers/specs/2026-11-26-builder-json-text-keys-design.md new file mode 100644 index 00000000..18262eb5 --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-json-text-keys-design.md @@ -0,0 +1,71 @@ +# Builder: text keys in JSON definitions (design) + +Status: approved in conversation 2026-11-26 · epic #261, follows `2026-11-26-builder-compact-json-design.md` +Amends: phase 3 spec section 4.6 ("Texts and languages (deliberately minimal)"). + +## 1. Intent + +One JSON definition serves every language. Today `template.Texts["key"]` returns the translated string at composition, +so the export writes German or English text and there is one JSON file per language (the evaluation's proposal 2). +The maintainer wants a single template whose texts are keys, translated when the template is built. + +## 2. Decisions (maintainer, 2026-11-26) + +1. **Hybrid storage.** A JSON definition may carry its translations in a `texts` section, so it is self-contained + (an agent or a customer edits a sentence in the file); it may also carry only keys, translated from the host's + catalog (`TemplateBuildOptions.Texts`, resx etc.). When both exist, the JSON's text wins and missing keys fall + back to the catalog. +2. **Syntax `[[key]]`** inside any JSON string: data in `{{…}}`, texts in `[[…]]`. It works inside concatenations + (`"[[orderNo]] {{order.number}}"`) and inside formats (`"{{order.date:date:[[dateFormat]]}}"`). +3. **A missing translation is a build error** (TB5001), as for C# definitions today. + +## 3. Approach (builder's call) + +The C# API does not change. Texts flow as plain strings through C# code (concatenated, used as date patterns, in raw +XML, in document properties), so the key cannot be carried by a type. Instead the export composes the definition with +**key markers**: in export mode `TemplateTexts[key]` returns `U+E000 key U+E001` instead of a translation. Wherever a +text ends up in the model, the marker is there; the JSON writer turns every marker into `[[key]]`. The exported JSON +therefore no longer depends on the language, and the `language` member is dropped from the format. + +Import resolves `[[key]]` in every string of the definition (except the `texts` section) before the existing reader +sees it: from the JSON's `texts` for the build language (same culture fallback as `TextCatalog.FromDictionary`: +`de-DE` → `de` → invariant), else through `TemplateTexts` (catalog; a miss is TB5001). In export mode (re-exporting an +imported JSON) the reader resolves keys to markers again, so the round trip holds. A translated text must not contain +`{{` (like any literal text today); `[[` inside a translation is literal. + +Rules: +- A key is `[A-Za-z0-9_.-]+`. `[[` that does not start a valid `[[key]]` is TB9200 at the string's pointer. A lone `]]` + is literal. +- Export fails with TB9204 when a literal string of the definition contains `[[` (it would read as a key) or a key used + through `Texts[…]` is not a valid key. +- `texts` section: `{"": {"": "", …}, …}`; cultures as given (`"de"`, `"en-GB"`), keys in first-use + order. Written for the languages in `TemplateJsonExportOptions.TextLanguages`, each text looked up in the build + options' catalog; a key a language lacks is left out (the build reports it). Re-exporting an imported definition + without `TextLanguages` keeps the languages of its own `texts` section. + +Added after the final review: the export checks itself (imports its JSON, builds it for the options' language and +each `TextLanguages` entry the definition builds in, TB9204 on different bytes), which catches texts changed by code +(`string.Format`) and texts placed into quoted values; translations inside raw XML are XML-escaped on import; a `[` +directly before a key is TB9204 at export; re-export without `TextLanguages` writes the `texts` section verbatim. + +## 4. API (additive) + +```csharp +public sealed class TemplateJsonExportOptions +{ + public ComponentCatalog? Components { get; init; } + public IReadOnlyList? TextLanguages { get; init; } // null/empty: keys only +} +TemplateJson.Export(ITemplateDefinition definition, TemplateBuildOptions options, TemplateJsonExportOptions export) +``` + +The existing `Export(definition, options)` and `Export(definition, options, components)` stay (keys only, no `texts`). + +## 5. Verification + +- Every builder test keeps round-tripping (keys only; the build options' catalog translates). +- The sample exports **one** `order-confirmation.json` with `texts` for de and en; importing it **without** a catalog + builds byte-identical DOCX/ODT to the C# definition for de-DE and en-GB. +- Tests: markers in text/format/raw/properties/alt text become `[[key]]`; import resolves from `texts`, from the + catalog, JSON over catalog, culture fallback; TB5001 for a missing key; TB9200 for malformed `[[`; TB9204 for a literal + `[[` in C# text; a translation containing `{{` is rejected; re-export keeps `texts`. diff --git a/docs/superpowers/specs/2026-11-26-builder-phase4-step1-design.md b/docs/superpowers/specs/2026-11-26-builder-phase4-step1-design.md new file mode 100644 index 00000000..0375db97 --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-phase4-step1-design.md @@ -0,0 +1,44 @@ +# Builder phase 4, step 1: indexed paths and render-safe containers (design) + +Status: approved as part of the phase 4 plan (maintainer, 2026-11-26) · #290, #291 · epic #261 +Source: `2026-11-26-builder-direction-review.md` (gaps found by porting a real-world template). + +## #290 Indexed path segments + +Templify reads `{{Items[0].Name}}` (also inside conditions: its lexer keeps `[`, `]` in words). The builder rejects +it. Calls made here: + +- **Grammar:** a segment is `name` or `name[n]` with one constant index, `n` from 0 to 999 (the witness creates `n + 1` + items, so the cap keeps it small). `order["items[0].textValue"]`, `line["parts[1].name"]`, root `TemplatePath.Root`. +- **Typed paths:** a constant `int` index on a list or array (`o => o.Items[0].Name`, `o.Array[2]`) maps to `items[0]`; + a captured variable or computed index stays an error. +- **JSON:** works through the same paths, in text (`{{items[0].name}}`) and in conditions (`items[0].ok`). +- **Data contract:** the canonical path keeps the index (`order.items[0].textValue`), so the contract says exactly what + the template reads. The witness makes a collection as long as its highest index + 1, every item with the merged shape + of all its uses (loop and indexed), so `ValidateTemplate`/the upload check find every value. +- **Data catalogue and loop checks** treat `items[0]` like the item path `items[]` (kind check, "root path hidden by a + loop variable" compares the bare name). + +## #291 Render-safe containers + +1. **Closing paragraph:** when the content of a table cell (and so of a box) does not end with an ordinary paragraph + after flattening — it ends with a marker (`{{/if}}`, `{{/foreach}}`), a table or a raw block — the writer appends a + spacer paragraph. Once Templify removes the markers, the cell still ends with a paragraph, and LibreOffice keeps the + outer table's borders and padding. +2. **Tables apart:** a table followed by a marker paragraph gets a spacer paragraph after it, so it never touches a + table that follows the markers after filling. (Directly adjacent tables keep today's separator.) +3. The **spacer** is a paragraph in the builder's style "Template Spacer" (1 pt, no spacing before/after, exact 1 pt + line height), added to the style sheet only when a spacer is written — like "Template Marker". It is a writer + detail: it is not in the model, so JSON definitions and the data contract are unchanged. +4. **Style names:** a display name containing a comma is a build error (Word reads `w:name` commas as alias lists; the + DOCX is schema-invalid). + +## Verification + +- #290: string, typed and JSON forms give `items[0]`; the filled document shows the value at the index, also inside a + loop item and in a condition; the contract keeps the index; the witness validates the template (no missing + variables) when loops and indices share a collection; a captured index and an index above 999 are errors. +- #291: after filling with data that removes a conditional's content, the cell's last element is a paragraph (DOCX + `w:tc`, ODT `table:table-cell`) and the two tables around a removed conditional are separated by a paragraph; the + spacer style is only present when used; a comma in a style name is an error. (The lost border itself is only visible in + LibreOffice's rendering; the structural check is what the tests pin.) diff --git a/docs/superpowers/specs/2026-11-26-builder-typed-path-generator-design.md b/docs/superpowers/specs/2026-11-26-builder-typed-path-generator-design.md new file mode 100644 index 00000000..c7a3150c --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-builder-typed-path-generator-design.md @@ -0,0 +1,61 @@ +# Builder: source generator for typed data paths (design) + +Status: approved in conversation 2026-11-26 · epic #261 · approach B of phase 3 spec section 3.3, on the foundation of +approach A (`TemplatePath`, `LoopItem`, `TemplateCollection`). + +## 1. Intent + +Typed paths today need a lambda per value: `order.Path(o => o.Number)`, `line.Path(l => l.Quantity)`. The maintainer +wants to see the cleanest form, `order.Number`, `line.Quantity`, `address.Country.NotEq("DE")`, for the classes a +customer of the builder writes for their data. Targets are .NET 10 and 11 only; older language versions are not +supported. + +## 2. Decisions + +- **Maintainer:** approach 1 — a Roslyn source generator writes **C# 14 extension properties** on the existing types + `TemplatePath` and `LoopItem` (not a second, generated path API). A data property whose name an existing member + already uses (`Number`, `Count`, `Index` on a loop item; `Path`, `Items`, `Exists`, `IsEmpty` on a path) is not + generated; the lambda remains for that case. That is acceptable. +- **Builder's calls (stated in the conversation, not objected to):** + - Generation is automatic for every type used in `template.DataAs()` in the compilation and every type reachable + from it; `[assembly: TemplateData(typeof(X))]` adds roots that are not used through `DataAs` (component libraries). + The customer's classes need no attribute, no `partial`, no base class, and may live in other assemblies. + - Each generated property calls the existing lambda API (`path.Path(x => x.Number)`), so names follow exactly the same + rules (`[JsonPropertyName]`, the naming policy given to `DataAs`) and templates are byte-identical to the lambda form. + - The generator ships inside the `TriasDev.Templify.Builder` package (`analyzers/dotnet/cs`); nothing to install. + +## 3. What is generated + +One file, `TemplifyDataPaths.g.cs`, namespace `TriasDev.Templify.Builder` (already imported by definitions), one +`internal static class TemplifyDataPaths` with, per reachable object type `X`, an `extension(TemplatePath path)` and +an `extension(LoopItem item)` block: + +| Data property of type | Generated member | +|---|---| +| value (string, numbers, bool, enums, dates, Guid, …; nullable forms) or open (object, dictionaries, `JsonElement`) | `TemplatePath Name => path.Path(x => x.Name);` | +| object | `TemplatePath Name => …` — and `TProp` gets its own extension blocks | +| collection (array or `IEnumerable`, not string) | `TemplateCollection Name => path.Items(x => x.Name);` — and an object `TItem` gets extension blocks | + +The type rules mirror `DataCatalog` (value / open / collection / object). Properties: public, instance, readable, not +indexers, not `[JsonIgnore]` (always), including inherited ones (most derived wins). A property whose name collides with +a member of the receiver type (read from the compilation, including `object` members) is skipped with warning +**TBG001** naming the lambda to use. Types the generated code cannot name (private or protected, at any nesting level) +are skipped silently; they can still use lambdas. Without C# 14 (LangVersion below 14) the generator reports error +**TBG002** and generates nothing. Generated code is `#nullable disable` (no nullability mismatches in strict projects). + +Added after the final review: TBG001 is information, not a warning (collisions are accepted, and a file-located +generator diagnostic cannot be suppressed locally); types in `System.*` are not walked (the lambda API rejects their +members); `file` types, ref structs, ref-returning properties and names several base interfaces declare are skipped; +`[Obsolete]` is copied onto the generated property; the generated file marks its blocks with +`[assembly: GeneratedDataPaths(typeof(T), loopItem)]`, and a compilation that a referenced assembly gives access to its +internals does not generate those blocks again. + +## 4. Verification + +- Generator tests (`CSharpGeneratorDriver`): generated text per type rule, inheritance, `[JsonIgnore]`, keywords, + collisions (TBG001), LangVersion (TBG002), inaccessible types skipped, assembly attribute roots, deterministic output, + generated code compiles without warnings. +- End-to-end: the builder test project runs the generator; generated properties give the same paths as the lambdas, + also with `[JsonPropertyName]` and `DataAs(JsonNamingPolicy.SnakeCaseLower)`. +- The sample's `TypedOrderConfirmation` and `OrderAddressBlock` use the generated properties and still build the same + bytes as `OrderConfirmation`; the packed builder package contains the generator under `analyzers/dotnet/cs`. diff --git a/docs/superpowers/specs/2026-12-01-builder-agent-api-design.md b/docs/superpowers/specs/2026-12-01-builder-agent-api-design.md new file mode 100644 index 00000000..d1de8949 --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-builder-agent-api-design.md @@ -0,0 +1,77 @@ +# Builder: agent API for JSON definitions (#274) — design + +Issue #274 (epic #261). Phase 3 delivered the JSON definition format (import, export, components, JSON-pointer +diagnostics, `DataCatalog.ToJson`, `TemplateInspector.CheckDefinition`). What an agent still lacks is a way to learn the +vocabulary, find its way around a definition without reading all of it, change it in small validated steps, and see the +result. The maintainer agreed (2026-12-01): **library only**. The host keeps storage, auth, chat, the MCP server and PDF +conversion; Templify provides the functions the host's tools call. + +## Goals + +1. **Describe** — what an agent must know before editing: every JSON construct with its keys, what each key takes and + one example; the value forms (lengths, colours, lines, padding, conditions, formats); the host's registered + components with their parameters; optionally the data paths (`DataCatalog`). +2. **Schema** — a JSON Schema (draft 2020-12) of the format, generated from the same description, for editors and + agents that validate on their side. +3. **Outline and Read** — an outline of a definition (pointer, kind, short label per block, nested), and one subtree by + JSON pointer. +4. **Patch** — apply a JSON Patch (RFC 6902: add, remove, replace, move, copy, test) atomically, then check the result + exactly like `CheckDefinition`; return the new JSON and the problems. +5. **Preview** — build and fill with given data (or the contract's witness), return the filled document and its text. + +## Non-goals + +MCP server, chat, storage, PDF, YAML, schema migrations (the format is version 1; migrations come with version 2). + +## Approaches + +1. **Hand-written vocabulary as data, cross-checked against the reader — chosen.** One internal table describes each + construct (name, discriminating key, keys with a value kind, required flag, description, example). Describe and + Schema render it. A test proves it matches the reader: for every construct it imports the example (it must be + valid) and the example plus an unknown key, and compares the reader's "allowed here: …" list with the described + keys. Drift fails the build. +2. Derive the vocabulary by refactoring the reader around a shared key table — rejected: touches ~45 call sites of a + working reader for the same guarantee the cross-check gives. +3. Reflection over the C# composers — rejected: the JSON keys are not the C# names and the reader adds forms (strings + as paragraphs, shorthands) that the composers do not show. + +## Design + +Public API in `TriasDev.Templify.Builder.Json` (all additive): + +```csharp +string TemplateJson.Describe(TemplateJsonDescribeOptions? options = null); // JSON text for an agent +string TemplateJson.Schema(ComponentCatalog? components = null); // JSON Schema text +IReadOnlyList TemplateJson.Outline(string json); // flat, in document order, with depth +string TemplateJson.Read(string json, string pointer); // the subtree, indented +TemplatePatchResult TemplateJson.Patch(string json, string patch, TemplateJsonImportOptions import, TemplateBuildOptions? build = null); +TemplatePreview TemplateJson.Preview(string json, TemplateJsonImportOptions import, TemplateBuildOptions build, string? data = null); +``` + +- `TemplateJsonDescribeOptions { ComponentCatalog? Components; DataCatalog? Data }`. +- `TemplateJsonNode(string Pointer, string Kind, string Label, int Depth)`: kind is the construct name (`paragraph`, + `table`, `section`, `if`, `forEach`, `component`, …); label is a short human summary (the section name, the first + 40 characters of a paragraph's text, a condition, a loop's collection, a component's name). +- `Read` throws `ArgumentException` for a malformed pointer or a missing target. +- `TemplatePatchResult { bool Applied; string Json; TemplateCheckResult Check }`: `Applied` is false when the patch + itself fails (bad JSON, unknown op, missing path, failed `test`): then `Json` is the input unchanged and `Check` has + one problem with a new code TB9207 at the failing operation (`/3` of the patch). Otherwise `Json` is the patched text + (indented) and `Check` is `CheckDefinition(patched, import, build)`; the host saves only when the status is Ok (or + accepts warnings). +- `TemplatePreview { TemplateCheckResult Check; byte[]? Document; string? Text }`: when the definition does not + import or build, `Document`/`Text` are null and `Check` says why. `data` is JSON; null means the contract's witness. + Filling uses Templify's `TemplateProcessor`; fill errors become a problem (TB9302 as in `Check`). `Text` is the + filled document's paragraphs, one per line. +- Data catalogue: Patch requires `import.Data` (as `CheckDefinition`); Preview does not. + +## Constraints + +- Builder project only; no new package dependencies (JSON Patch and pointers implemented on `System.Text.Json.Nodes`). +- `PublicAPI.Unshipped.txt` updated; the describe output and schema are deterministic (stable order). +- A trial with a small model (Haiku) through these functions only, on 6–8 realistic edit tasks, before closing; its + report stays private (`.superpowers/reviews/`, gitignored). + +## Left to the builder + +Exact wording of descriptions, the label rules, the schema's treatment of open-ended values (conditions and formats +are strings with a description, not grammars), code TB9207's message. diff --git a/docs/superpowers/specs/2026-12-01-builder-formatting-gaps-design.md b/docs/superpowers/specs/2026-12-01-builder-formatting-gaps-design.md new file mode 100644 index 00000000..6c302357 --- /dev/null +++ b/docs/superpowers/specs/2026-12-01-builder-formatting-gaps-design.md @@ -0,0 +1,143 @@ +# Builder: formatting gaps (#296) — design + +Issue #296 (epic #261, phase 4 follow-up). Found by porting a real-world template end to end (#292): every deviation +from a style had to be a style of its own (17 of 37 paragraph styles existed only for that), cell and table geometry was +symmetric only, a short rule needed a one-cell table, and boxes ending with conditionals grew by stacked spacer +paragraphs. + +The maintainer opted out of design checkpoints for this follow-up ("сразу принимаю решение от ревьюера"); the calls +below are the implementer's and are listed as such. + +## Goals + +1. **Paragraph layout options** on one paragraph: space before, space after, keep with next, keep lines together. +2. **Spacer** block: vertical space of a given height without a style. +3. **Short rule** (`Rule` with a width) and a **bottom border on a paragraph style** (running heads). +4. **Per-side padding**: cell, table style, box style. +5. **Per-side borders**: one cell (one side or a frame of its own), the outer edges of a table style per side (a rule + only above a table). +6. **Table indent** and **space before a table**. +7. **No stacked spacer paragraphs** (F13): one per position. + +Every construct is in C#, in the model, in both writers, in JSON import and export (the byte-identical round trip C# → +JSON → import → build stays), in the docs and support matrix, and has a LibreOffice round-trip test (admission rule, +builder design 2.4). + +## Non-goals + +- Vertical merge, text direction, row height (the port did not need them). +- Direct character formatting, direct alignment or indents on a paragraph: those stay style-only. +- Removing a table style's line on one cell side ("no border"); only adding a line of the cell's own. +- Per-side borders on a box style (the port needed per-side padding only). +- A paragraph style's top/left/right borders (only bottom: the port's running head). + +## Approaches for paragraph options (the policy question) + +The builder design (2.3) says paragraph and character formatting come from named styles, never direct formatting. The +port showed the cost: copies of styles that differ in one spacing or in "keep with next" make the style list of a +downloaded template almost twice as long as the design has — the opposite of the editability the rule protects. + +1. **Direct paragraph properties for four layout options — chosen.** Space before, space after, keep with next and keep + lines together may be set on one paragraph; they are written as direct paragraph properties (DOCX `w:pPr`, ODT an + automatic paragraph style whose parent is the named style). Text formatting, alignment and indents stay in named + styles. In Word and LibreOffice a user sees the named style and a visible paragraph override, which is how people + format by hand anyway. The builder already writes rules and table space this way. +2. Automatic derived named styles ("Table Label + 7 pt above") — rejected: the style list grows exactly as before, only + without the author typing it. +3. Styles only, plus `Spacer` — rejected: the "keep with next" copies remain. + +The builder design's rule 2.3 is amended accordingly (docs). + +## Design + +### C# surface (all additive; builder is unreleased) + +```csharp +// paragraph options: three overloads with a nullable style (null = the inherited style) +c.Paragraph(Styles.TableLabel, "Label", p => p.SpaceBefore(7.Pt()).KeepWithNext()); +c.Paragraph(Styles.TableValue, order.Total, p => p.KeepLinesTogether()); +c.Paragraph(null, x => x.Text("…"), p => p.SpaceAfter(3.Pt())); + +c.Spacer(14.Pt()); // > 0 and at most 72 pt + +c.Rule(1.5.Pt(), ink, Length.Zero, 14.Pt(), 12.Mm()); // width: > 0, at most the frame (build error otherwise) +s.Paragraph(RunHead, p => p.BorderBottom(0.75.Pt(), line, 3.Pt())); // width, colour, space between text and line + +[Flags] public enum Sides { None = 0, Top = 1, Right = 2, Bottom = 4, Left = 8, All = 15 } +cell.Border(Sides.Left, 0.75.Pt(), theme.Line); +cell.Padding(8.Pt(), 6.Pt(), 9.Pt(), 6.Pt()); // top, right, bottom, left +s.Table(Marked, t => t.OuterBorder(Sides.Top, 0.75.Pt(), line).RowRule(0.5.Pt(), hairline)); +s.Table(Key, t => t.CellPadding(8.Pt(), 6.Pt(), 9.Pt(), 6.Pt())); +s.Box(Panel, b => b.Padding(12.Pt(), 12.Pt(), 6.Pt(), 12.Pt())); +table.Indent(6.Mm()).SpaceBefore(17.Pt()); +``` + +- `ParagraphOptions`: `SpaceBefore(Length)`, `SpaceAfter(Length)` (not negative), `KeepWithNext(bool = true)`, + `KeepLinesTogether(bool = true)`; an option set twice keeps the last value; an empty options lambda is no options. +- A cell's own line on a side replaces the table style's line on that side of that cell. On an edge shared with a + neighbour both formats draw the wider line (Word's conflict rule, ODF's collapsing model) — documented. +- A cell's padding replaces the table style's padding for that cell; the cell's content frame (images, right tabs, + nested tables) uses the cell's own left and right padding. +- The table indent narrows the frame the columns are resolved in; columns that do not fit are the existing build error. + +### JSON + +- Paragraph block: `{"style": "TableLabel", "paragraph": "Label", "spaceBefore": "7pt", "keepWithNext": true}` — + `spaceBefore`, `spaceAfter`, `keepWithNext`, `keepLinesTogether` next to `paragraph`. A paragraph with options is + exported in object form. +- `{"spacer": "14pt"}`. +- `{"rule": {"line": "1.5pt $ink", "spaceBelow": "14pt", "width": "12mm"}}`. +- Paragraph style: `"borderBottom": "0.75pt $line"`, `"borderBottomSpace": "3pt"`. +- Padding (`cellPadding`, box `padding`, cell `padding`): the CSS shorthand with one, two, three or four values; the + symmetric-only restriction is removed. Export writes the shortest form. +- Borders per side (`outerBorder` in a table style, `border` on a cell): a line string for all four sides, or an object + `{"top": "0.75pt $line", "left": …}` with the sides that are set. Export writes the string when all four are equal. +- Table block: `"indent"`, `"spaceBefore"` next to `"spaceAfter"`. + +### Writers + +- **DOCX** paragraph options in `w:pPr` in schema order (`keepNext`, `keepLines` after `pStyle`; `spacing` with only + the attributes set). ODT: one automatic paragraph style per distinct (parent, options, right tab) combination; when + either spacing is set it writes both `fo:margin-top` and `fo:margin-bottom`, the other one resolved through the style + chain (LibreOffice reads both as one item; #298 F10). +- **Spacer**: DOCX an unstyled paragraph with `spacing before=0 after=0 line= lineRule=exact`; ODT an + automatic paragraph style with margins 0 and a fixed `fo:line-height`. +- **Short rule**: the rule paragraph gets an end indent of frame − width (DOCX `w:ind w:right`, ODT `fo:margin-right`). +- **Paragraph style bottom border**: DOCX `w:pBdr/w:bottom` with `w:space` in points; ODT `fo:border-bottom` and + `fo:padding-bottom`. +- **Per-side padding**: DOCX `tblCellMar` per side and `tcMar` for a cell's own; ODT the cell style's four paddings. +- **Per-side borders**: DOCX `tblBorders` per side and `tcBorders` for a cell's own (merged with the header rule); + ODT the cell's edge lines. +- **Indent**: DOCX `tblInd` (dxa); ODT `fo:margin-left` on the table. Its LibreOffice round trip must show the same + position in both formats (Word's `tblInd` meaning differs by compatibility mode — check against what the builder + writes in `settings.xml`). +- **Space before a table**: DOCX a 1 pt paragraph before the table carrying the space (as space after is done today); + ODT `fo:margin-top` on the table. + +### Spacer paragraphs (F13) + +Today a container gets a 1 pt "Template Spacer" paragraph after every table that a marker follows, and another one at the +end of a cell or part that may end with a table. After the markers are removed these stack. Since every table that a +marker follows already has a spacer, a container can end with a table after filling only when the table is the last +element as written. New rule: + +- after a table that a marker follows: unchanged; +- at the end of a cell: only when the written content ends with a table (or raw table), or when everything in it may be + removed by filling (a loop, or a conditional without an else, or one with an empty branch); +- at the end of a part: never (a part ending with a written table already gets its closing paragraph from the writer; + one ending with markers had its spacer after the table). + +`Spacers.Used` follows the same rule. + +## Constraints + +- Builder only, on `feature/builder`; core library untouched. +- `PublicAPI.Unshipped.txt` of the builder updated; no change to the core public API. +- Byte-identical round trip and the existing build outputs of definitions that use none of the new options stay + byte-identical (except the F13 change, which removes spacer paragraphs — expected test updates). +- Docs: `docs/for-developers/template-builder.md` (vocabulary, JSON, support matrix), builder design 2.3 amended. + +## Left to the builder (implementer's calls, recorded in the plan) + +Names of internal model types, the split into tasks, the exact validation messages, the upper limit of `Spacer` (72 pt +chosen), and whether `Sides.None` is rejected (it is: an argument error). diff --git a/mkdocs.yml b/mkdocs.yml index d751b484..de6d45ec 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -101,6 +101,7 @@ nav: - For Developers: - Quick Start: for-developers/quick-start.md - OpenDocument (.odt): for-developers/opendocument.md + - Template Builder (preview): for-developers/template-builder.md - Text Template Processing: for-developers/text-templates.md - Condition Evaluation: for-developers/condition-evaluation.md - Processing Warnings: for-developers/processing-warnings.md diff --git a/release-please-config.json b/release-please-config.json index 95744a4f..ba55e9ba 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,19 +1,57 @@ { "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "separate-pull-requests": true, "packages": { ".": { "release-type": "simple", "component": "templify", "include-component-in-tag": false, + "exclude-paths": [ + "src/TriasDev.Templify.Builder", + "src/TriasDev.Templify.Builder.Testing", + "src/TriasDev.Templify.Builder.Generators", + "samples/TriasDev.Templify.Builder.Sample", + "tests/TriasDev.Templify.Builder.Tests", + "docs" + ], "changelog-sections": [ - { "type": "feat", "section": "Features" }, - { "type": "fix", "section": "Bug Fixes" }, - { "type": "perf", "section": "Performance Improvements" }, - { "type": "docs", "section": "Documentation", "hidden": true }, - { "type": "chore", "section": "Miscellaneous", "hidden": true }, - { "type": "ci", "section": "CI", "hidden": true }, - { "type": "test", "section": "Tests", "hidden": true }, - { "type": "refactor", "section": "Code Refactoring", "hidden": true } + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Performance Improvements" + }, + { + "type": "docs", + "section": "Documentation", + "hidden": true + }, + { + "type": "chore", + "section": "Miscellaneous", + "hidden": true + }, + { + "type": "ci", + "section": "CI", + "hidden": true + }, + { + "type": "test", + "section": "Tests", + "hidden": true + }, + { + "type": "refactor", + "section": "Code Refactoring", + "hidden": true + } ], "extra-files": [ { @@ -22,6 +60,57 @@ "xpath": "//Project/PropertyGroup/Version" } ] + }, + "src": { + "release-type": "simple", + "component": "builder", + "include-component-in-tag": true, + "bump-minor-pre-major": true, + "initial-version": "0.1.0", + "version-file": "TriasDev.Templify.Builder/version.txt", + "changelog-path": "TriasDev.Templify.Builder/CHANGELOG.md", + "exclude-paths": [ + "src/TriasDev.Templify" + ], + "changelog-sections": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Performance Improvements" + }, + { + "type": "docs", + "section": "Documentation", + "hidden": true + }, + { + "type": "chore", + "section": "Miscellaneous", + "hidden": true + }, + { + "type": "ci", + "section": "CI", + "hidden": true + }, + { + "type": "test", + "section": "Tests", + "hidden": true + }, + { + "type": "refactor", + "section": "Code Refactoring", + "hidden": true + } + ] } } } diff --git a/samples/TriasDev.Templify.Builder.Sample/OrderConfirmation.cs b/samples/TriasDev.Templify.Builder.Sample/OrderConfirmation.cs new file mode 100644 index 00000000..a3116355 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/OrderConfirmation.cs @@ -0,0 +1,294 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; + +namespace TriasDev.Templify.Builder.Sample; + +/// +/// The product's theme. The customer's "slots" (colours, fonts, logo) come in here; the definitions never hard-code +/// them, so one theme restyles every template. The values are theme tokens: the JSON form refers to them as +/// "$accent", and a host can replace them when it imports the JSON. +/// +public sealed record BrandTheme( + Color Ink, + Color Muted, + Color Accent, + Color Line, + Color HeaderBackground, + Color SuccessLine, + Color SuccessBackground, + Color WarningLine, + Color WarningBackground, + FontFace Body, + FontFace Heading, + ImageSource Logo) +{ + /// Creates the sample theme with the embedded logo. + public static BrandTheme CreateDefault() => new BrandTheme( + Ink: Color.Token("ink", Color.FromHex("1A1A1A")), + Muted: Color.Token("muted", Color.FromHex("6B6B6B")), + Accent: Color.Token("accent", Color.FromHex("1F4E79")), + Line: Color.Token("line", Color.FromHex("D4D4D4")), + HeaderBackground: Color.Token("headerBackground", Color.FromHex("F2F5F8")), + SuccessLine: Color.Token("successLine", Color.FromHex("96C6A8")), + SuccessBackground: Color.Token("successBackground", Color.FromHex("EFF6F1")), + WarningLine: Color.Token("warningLine", Color.FromHex("E3B27A")), + WarningBackground: Color.Token("warningBackground", Color.FromHex("FDF3E7")), + Body: FontFace.Token("body", new FontFace("Liberation Sans")), + Heading: FontFace.Token("heading", new FontFace("Liberation Sans")), + Logo: ImageSource.Png(SampleResources.Read("logo.png")).WithName("logo")); +} + +/// The style keys every template of the product shares. +public static class Styles +{ + public static readonly ParagraphStyleKey Title = new("DocTitle", "Document Title"); + public static readonly ParagraphStyleKey Subtitle = new("DocSubtitle", "Document Subtitle"); + public static readonly ParagraphStyleKey Heading = new("SectionHeading", "Section Heading"); + public static readonly ParagraphStyleKey Body = new("BodyCopy", "Body Copy"); + public static readonly ParagraphStyleKey TableText = new("TableText", "Table Text"); + public static readonly ParagraphStyleKey TableHeader = new("TableHeader", "Table Header"); + public static readonly ParagraphStyleKey Small = new("SmallPrint", "Small Print"); + public static readonly ParagraphStyleKey ListItem = new("ListItem", "List Item"); + public static readonly ParagraphStyleKey Logo = new("Logo", "Logo"); + public static readonly CharacterStyleKey Strong = new("StrongText", "Strong Text"); + public static readonly CharacterStyleKey Muted = new("MutedText", "Muted Text"); + public static readonly TableStyleKey Grid = new("LineGrid"); + public static readonly BoxStyleKey Success = new("SuccessBox"); + public static readonly BoxStyleKey Warning = new("WarningBox"); + public static readonly ListStyleKey Bullets = new("Bullets"); + + /// The style sheet, built from the theme. + public static StyleSheet Create(BrandTheme t) => StyleSheet.Create(s => + { + // Paragraphs without a style are body copy; table cells get the table style's text styles. + s.Defaults(d => d.Font(t.Body).Size(10.Pt()).Color(t.Ink).ParagraphStyle(Body)); + s.Paragraph(Body, p => p.SpaceAfter(6.Pt()).LineSpacing(1.15)); + s.Paragraph(Title, p => p.BasedOn(Body).Next(Subtitle).Font(t.Heading).Size(22.Pt()).Bold().Color(t.Accent).SpaceAfter(2.Pt())); + s.Paragraph(Subtitle, p => p.BasedOn(Body).Next(Body).Size(11.Pt()).Color(t.Muted).SpaceAfter(14.Pt())); + s.Paragraph(Heading, p => p.BasedOn(Body).Next(Body).Font(t.Heading).Size(13.Pt()).Bold().Color(t.Accent) + .SpaceBefore(14.Pt()).SpaceAfter(6.Pt()).KeepWithNext().OutlineLevel(1)); + s.Paragraph(TableText, p => p.BasedOn(Body).SpaceAfter(0.Pt())); + s.Paragraph(TableHeader, p => p.BasedOn(TableText).Bold()); + s.Paragraph(Small, p => p.BasedOn(Body).Size(8.Pt()).Color(t.Muted)); + s.Paragraph(ListItem, p => p.BasedOn(Body).SpaceAfter(2.Pt())); + s.Paragraph(Logo, p => p.SpaceAfter(0.Pt())); + s.Character(Strong, c => c.Bold()); + s.Character(Muted, c => c.Color(t.Muted)); + s.Table(Grid, g => g + .HeaderBackground(t.HeaderBackground) + .HeaderRule(1.Pt(), t.Accent) + .RowRule(0.5.Pt(), t.Line) + .CellPadding(3.Pt(), 5.Pt()) + .ParagraphStyle(TableText) + .HeaderParagraphStyle(TableHeader)); + s.Box(Success, b => b.Border(0.75.Pt(), t.SuccessLine).Background(t.SuccessBackground).Padding(6.Pt(), 8.Pt()).SpaceAfter(8.Pt())); + s.Box(Warning, b => b.Border(0.75.Pt(), t.WarningLine).Background(t.WarningBackground).Padding(6.Pt(), 8.Pt()).SpaceAfter(8.Pt())); + s.List(Bullets, l => l.ItemStyle(ListItem).Level(0, "•", 6.Mm(), 4.Mm()).Level(1, "–", 12.Mm(), 4.Mm())); + }); +} + +/// +/// A reusable block: any template that prints an address uses it. A record whose parameters are paths, so a +/// can write it to JSON as a reference. +/// +public sealed record AddressBlock(TemplatePath Address) : ITemplateComponent +{ + public void Compose(BlockComposer c) + { + c.Paragraph(x => + { + x.Value(Address["street"]).LineBreak().Value(Address["postalCode"]).Text(" ").Value(Address["city"]); + x.If(Address["country"].NotEq("DE"), t => t.Text(", ").Value(Address["country"])); + }); + } +} + +/// +/// The terms at the end of every document. It takes no parameters: the texts and the theme come from the build +/// (, ), so a JSON definition refers to it as +/// {"component": "terms"}. +/// +[ComponentVersion(1)] +public sealed record Terms : ITemplateComponent +{ + public void Compose(BlockComposer c) => c + .Paragraph(Styles.Heading, c.Texts["terms"]) + .Paragraph(Styles.Small, c.Texts["termsText"]) + .Rule(0.5.Pt(), c.Shared().Line, 12.Pt(), 4.Pt()); +} + +/// +/// An order confirmation that uses every construct of the builder: styles, page setup with headers and footers, +/// texts in two languages, values with formats, conditionals (block, switch, inline, expressions), loops (paragraphs, +/// table rows, list items), tables, boxes, rules, lists, images, a table of contents, components and a raw block. +/// +public sealed class OrderConfirmation(BrandTheme theme) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = new("order-confirmation", 1); + + public void Compose(TemplateComposer template) + { + TemplateTexts t = template.Texts; + TemplatePath order = template.Data["order"]; + + template.Share(theme); + template.Styles(Styles.Create(theme)); + template.Properties(p => p.Title(t["title"]).Author("Example Trading").Subject(t["title"])); + + template.Page(page => page + .Size(PageSize.A4) + .Margins(25.Mm(), 20.Mm(), 22.Mm(), 20.Mm()) + .Header(h => h.Paragraph(Styles.Small, x => x + .Text(t["title"] + " ").Value(order["number"]) + .TabRight() + .Text(t["page"] + " ").PageNumber().Text(" / ").PageCount())) + .Footer(f => f.Paragraph(Styles.Small, t["footer"])) + .FirstPage(first => + { + // The first page carries the logo instead of the running header. + first.Header(h => h.Paragraph(Styles.Logo, x => x.Image(theme.Logo, "Example Trading", ImageFit.Height(12.Mm())))); + first.Footer(f => f.Paragraph(Styles.Small, t["footer"])); + })); + + template.Content(c => + { + c.Paragraph(Styles.Title, t["title"]); + c.Paragraph(Styles.Subtitle, x => x + .Text(t["orderNo"] + " ").Value(Styles.Strong, order["number"]) + .Text(" · ").Value(order["date"], ValueFormat.Date(t["dateFormat"]))); + + c.TableOfContents(1); + + // Sections name the parts of the document; in JSON they are the units an editor reads or replaces. + c.Section("customer", b => Customer(b, t, order)); + c.Section("items", b => Items(b, t, order)); + c.Section("status", b => Status(b, t, order)); + c.Section("checks", b => Checks(b, t, order)); + c.Section("notes", b => Notes(b, t, order)); + + c.PageBreak(); + c.Component(new Terms()); + c.Raw(PrintedOn(t["printedOn"])); + }); + } + + private static void Customer(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.Paragraph(Styles.Heading, t["customer"]); + c.Paragraph(x => + { + x.Value(Styles.Strong, order["customer.name"]); + x.If(order["customer.isNew"], s => s.Text(Styles.Muted, " (" + t["newCustomer"] + ")")); + }); + c.If(order["customer.contact"].IsNotEmpty, b => b.Paragraph(x => + { + x.Text(Styles.Muted, t["attn"] + " "); + x.Value(order["customer.contact"]); + })); + c.Component(new AddressBlock(order["customer.address"])); + } + + private static void Items(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.Paragraph(Styles.Heading, t["items"]); + c.Table(table => + { + table.Style(Styles.Grid).SpaceAfter(8.Pt()); + table.Columns(cols => + { + cols.Fixed(10.Mm()); + cols.Relative(4); + cols.Fixed(16.Mm()); + cols.Fixed(30.Mm()); + }); + table.HeaderRow(r => r.Cell("#").Cell(t["description"]).Cell(t["quantity"]).Cell(t["amount"])); + table.ForEachRow(order["lines"], "line", (line, rows) => + { + rows.Row(r => + { + r.Cell(line.Loop.Number); + r.Cell(cell => + { + cell.Paragraph(x => + { + x.Value(line["description"]).Text(Styles.Muted, " — "); + x.If(line["inStock"], s => s.Text(Styles.Muted, t["inStock"])).Else(s => s.Text(Styles.Muted, t["backOrdered"])); + }); + cell.If(line["tags"].IsNotEmpty, b => b.Paragraph(Styles.Small, x => x.Value(line["tags"], ValueFormat.Join(separator: " · ")))); + }); + r.Cell(line["quantity"]); + r.Cell(cell => cell.Paragraph(x => x.Value(line["amount"], ValueFormat.Currency))); + }); + }); + table.RowsIf(order["discount"].Gt(0), rows => rows.Row(r => + { + r.Cell(cell => cell.ColumnSpan(3).Paragraph(t["discount"])); + r.Cell(cell => cell.Paragraph(x => x.Value(order["discount"], ValueFormat.Currency))); + })); + table.Row(r => + { + r.ParagraphStyle(Styles.TableHeader); + r.Cell(cell => cell.ColumnSpan(3).Border(Sides.Top, 1.Pt(), c.Shared().Accent).Paragraph(t["total"])); + r.Cell(cell => cell.Border(Sides.Top, 1.Pt(), c.Shared().Accent).Paragraph(x => x.Value(order["total"], ValueFormat.Currency))); + }); + }); + + c.Paragraph(null, x => x.Text(t["freeExpress"] + " ").Expression(order["isExpress"] & order["total"].Gt(1000), ValueFormat.YesNo), p => p.SpaceBefore(6.Pt())); + } + + private static void Status(BlockComposer c, TemplateTexts t, TemplatePath order) + { + // Every unknown status falls into Default. + c.Switch(order["status"], s => + { + s.Case("paid", b => b.Box(Styles.Success, x => x.Paragraph(t["statusPaid"]))); + s.Case(new[] { "overdue", "reminded" }, b => b.Box(Styles.Warning, x => x.Paragraph(t["statusOverdue"]))); + s.Default(b => b.Paragraph(t["statusOpen"])); + }); + + c.If(order["isExpress"] & order["total"].Gt(1000), b => b.Paragraph(t["expressFree"])) + .ElseIf(order["isExpress"], b => b.Paragraph(t["express"])) + .Else(b => b.Paragraph(t["standard"])); + } + + private static void Checks(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.If(order["checks"].IsNotEmpty, b => + { + b.Paragraph(Styles.Heading, t["checks"]); + b.List(Styles.Bullets, list => list.ForEach(order["checks"], "check", (check, items) => + { + items.Item(x => x.Value(check["title"]).Text(": ").Value(check["passed"], ValueFormat.Checkmark)); + items.If(check["note"].Exists, notes => notes.Item(1, check["note"])); + })); + }); + } + + private static void Notes(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.If(order["notes"].IsNotEmpty, b => b.Paragraph(Styles.Heading, t["notes"]).Paragraph(order["notes"])); + } + + /// + /// A raw block: a date field the application fills when it prints. The builder has no date-field construct, so + /// the XML is written per format. + /// + internal static RawBlock PrintedOn(string label) + { + XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + XNamespace text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + return new RawBlock + { + Docx = _ => new XElement(w + "p", + new XElement(w + "pPr", new XElement(w + "pStyle", new XAttribute(w + "val", Styles.Small.Id))), + new XElement(w + "r", new XElement(w + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), label + " ")), + new XElement(w + "fldSimple", new XAttribute(w + "instr", " DATE \\@ \"yyyy-MM-dd\" "), + new XElement(w + "r", new XElement(w + "t", "2026-01-01")))), + Odt = _ => new XElement(text + "p", new XAttribute(text + "style-name", Styles.Small.Id), + label + " ", + new XElement(text + "date", "2026-01-01")), + }; + } +} diff --git a/samples/TriasDev.Templify.Builder.Sample/OrderData.cs b/samples/TriasDev.Templify.Builder.Sample/OrderData.cs new file mode 100644 index 00000000..a336c740 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/OrderData.cs @@ -0,0 +1,32 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Sample; + +/// The data of an order confirmation, as C# types: the shape of sample-data.json. +public sealed record OrderData(Order Order); + +/// An order. +public sealed record Order( + string Number, + DateTime Date, + string Status, + bool IsExpress, + decimal Total, + decimal Discount, + string? Notes, + Customer Customer, + IReadOnlyList Lines, + IReadOnlyList Checks); + +/// The ordering customer. +public sealed record Customer(string Name, string? Contact, bool IsNew, Address Address); + +/// A postal address. +public sealed record Address(string Street, string PostalCode, string City, string Country); + +/// An order line. +public sealed record OrderLine(string Description, int Quantity, decimal Amount, bool InStock, IReadOnlyList Tags); + +/// A check run on the order. +public sealed record Check(string Title, bool Passed, string? Note); diff --git a/samples/TriasDev.Templify.Builder.Sample/Program.cs b/samples/TriasDev.Templify.Builder.Sample/Program.cs new file mode 100644 index 00000000..e5d9ff58 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/Program.cs @@ -0,0 +1,12 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +// Builds the sample order confirmation in German and English, as DOCX and ODT, verifies it, fills it with the sample +// data and writes everything to the folder given as the first argument (default: ./output). +using TriasDev.Templify.Builder.Sample; + +// "phase3 ": the JSON round trip (export, import, build, fill) instead. +bool phase3 = args.Length > 0 && args[0] == "phase3"; +string output = phase3 ? (args.Length > 1 ? args[1] : "output-phase3") : args.Length > 0 ? args[0] : "output"; +IReadOnlyList files = phase3 ? SampleRunner.RunPhase3(output, Console.Out) : SampleRunner.Run(output, Console.Out); +Console.WriteLine($"{files.Count} files written to {Path.GetFullPath(output)}"); diff --git a/samples/TriasDev.Templify.Builder.Sample/SampleResources.cs b/samples/TriasDev.Templify.Builder.Sample/SampleResources.cs new file mode 100644 index 00000000..27186089 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/SampleResources.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Sample; + +/// Reads the sample's embedded files (the logo and the sample data). +public static class SampleResources +{ + /// Reads an embedded resource. + public static byte[] Read(string name) + { + using Stream stream = typeof(SampleResources).Assembly.GetManifestResourceStream(name) + ?? throw new InvalidOperationException($"The sample has no embedded resource '{name}'."); + using MemoryStream copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + /// Gets the sample data as JSON. + public static string SampleData => System.Text.Encoding.UTF8.GetString(Read("sample-data.json")); +} diff --git a/samples/TriasDev.Templify.Builder.Sample/SampleRunner.cs b/samples/TriasDev.Templify.Builder.Sample/SampleRunner.cs new file mode 100644 index 00000000..3c55c792 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/SampleRunner.cs @@ -0,0 +1,165 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Testing; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Sample; + +/// +/// The sample's flow: verify the definition, then build every language and format, fill each template with the +/// sample data and write templates, filled documents and the data contract to a folder. +/// +public static class SampleRunner +{ + /// The languages the sample builds. + public static readonly CultureInfo[] Languages = [CultureInfo.GetCultureInfo("de-DE"), CultureInfo.GetCultureInfo("en-GB")]; + + /// The components a JSON definition of the sample may refer to by name. + public static ComponentCatalog Components { get; } = new ComponentCatalog().Register("address").Register("terms"); + + /// Runs the sample. + /// Where the files go. + /// Where progress goes. + /// The written files. + public static IReadOnlyList Run(string outputDirectory, TextWriter log) + { + ArgumentNullException.ThrowIfNull(outputDirectory); + ArgumentNullException.ThrowIfNull(log); + Directory.CreateDirectory(outputDirectory); + BrandTheme theme = BrandTheme.CreateDefault(); + string data = SampleResources.SampleData; + + // 1. What a consumer's CI does: every language and format builds, validates, fills and is deterministic. + TemplateVerificationReport report = TemplateVerifier.VerifyAll( + () => new OrderConfirmation(theme), + new TemplateVerificationOptions { Languages = Languages, Texts = _ => SampleTexts.Catalog, SampleData = [data] }); + log.WriteLine(report); + + // 2. What the application does at runtime: build the template, offer it for download, fill it. + List files = new List(); + foreach (VerifiedTemplate built in report.Templates) + { + GeneratedTemplate template = built.Template; + string name = $"order-confirmation.{built.Language.Name}"; + files.Add(Write(outputDirectory, $"{name}.template{template.FileExtension}", template.Content.ToArray())); + + TemplateProcessor processor = new TemplateProcessor(new PlaceholderReplacementOptions + { + Culture = built.Language, + MissingVariableBehavior = MissingVariableBehavior.ThrowException, + // Word builds the table of contents and the page fields when it opens the document. + UpdateFieldsOnOpen = UpdateFieldsOnOpenMode.Auto, + }); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + ProcessingResult result = processor.ProcessTemplate(input, output, data); + if (!result.IsSuccess) + { + throw new InvalidOperationException(result.ErrorMessage); + } + + files.Add(Write(outputDirectory, $"{name}.filled{template.FileExtension}", output.ToArray())); + log.WriteLine( + $"{name}{template.FileExtension}: {template.Content.Length / 1024.0:F1} KB, contract {template.Contract.Hash[..12]}, " + + $"{result.ReplacementCount} replacements, build warnings: {string.Join(", ", template.Warnings.Select(w => w.Code))}"); + } + + // 3. The data contract (the JSON shape the template reads) and the check of an unchanged template against the data. + GeneratedTemplate first = report.Templates[0].Template; + files.Add(Write(outputDirectory, "data-contract.json", System.Text.Encoding.UTF8.GetBytes(first.Contract.ToJson()))); + using (Stream upload = first.OpenRead()) + { + TemplateCheckResult check = TemplateInspector.Check(upload, new TemplateCheckOptions + { + Data = DataCatalog.From(), + Expected = new OrderConfirmation(theme).Identity, + Components = Components, + }); + log.WriteLine($"check of the unchanged template: {check.Status}{string.Concat(check.Problems.Select(p => "; " + p))}"); + } + + return files; + } + + /// + /// Phase 3 (#274): exports the definition to JSON per language, imports it again (checked against the data + /// catalogue of ), builds and fills DOCX and ODT from the import and checks that the + /// templates are the bytes the C# definition builds. + /// + /// Where the files go. + /// Where progress and sizes go. + /// The written files. + public static IReadOnlyList RunPhase3(string outputDirectory, TextWriter log) + { + ArgumentNullException.ThrowIfNull(outputDirectory); + ArgumentNullException.ThrowIfNull(log); + Directory.CreateDirectory(Path.Combine(outputDirectory, "assets")); + BrandTheme theme = BrandTheme.CreateDefault(); + string data = SampleResources.SampleData; + List files = new List(); + + // One JSON for every language: texts are [[key]] references, translated from the JSON's own "texts" section. + TemplateJsonDocument exported = TemplateJson.Export( + new OrderConfirmation(theme), + new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = Languages[0], Texts = SampleTexts.Catalog }, + new TemplateJsonExportOptions { Components = Components, TextLanguages = [CultureInfo.GetCultureInfo("de"), CultureInfo.GetCultureInfo("en")] }); + files.Add(Write(outputDirectory, "order-confirmation.json", System.Text.Encoding.UTF8.GetBytes(exported.Json))); + foreach ((string key, byte[] asset) in exported.Assets) + { + files.Add(Write(Path.Combine(outputDirectory, "assets"), key.Replace("sha256:", string.Empty, StringComparison.Ordinal)[..16] + ".png", asset)); + } + + int lines = exported.Json.Count(c => c == '\n'); + log.WriteLine($"order-confirmation.json: {exported.Json.Length} characters, {lines} lines, about {exported.Json.Length / 4} tokens"); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions + { + Assets = exported.Assets, + Components = Components, + Data = DataCatalog.From(), + Shared = [theme], + AllowRawXml = true, + }); + + foreach (CultureInfo language in Languages) + { + // The C# definition translates from the catalog; the imported JSON needs none. + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = language, Texts = SampleTexts.Catalog }; + string name = $"order-confirmation.{language.Name}"; + foreach (TemplateFormat format in new[] { TemplateFormat.Docx, TemplateFormat.Odt }) + { + TemplateBuildOptions formatOptions = options with { Format = format }; + GeneratedTemplate fromJson = TemplateBuilder.Build(imported, formatOptions with { Texts = TextCatalog.Empty }); + GeneratedTemplate fromCSharp = TemplateBuilder.Build(new OrderConfirmation(theme), formatOptions); + if (fromJson.ContentHash != fromCSharp.ContentHash) + { + throw new InvalidOperationException($"{name}{fromJson.FileExtension}: the template built from JSON differs from the C# one."); + } + + files.Add(Write(outputDirectory, $"{name}.from-json{fromJson.FileExtension}", fromJson.Content.ToArray())); + using Stream input = fromJson.OpenRead(); + using MemoryStream output = new MemoryStream(); + ProcessingResult result = new TemplateProcessor(new PlaceholderReplacementOptions { Culture = language, MissingVariableBehavior = MissingVariableBehavior.ThrowException }) + .ProcessTemplate(input, output, data); + if (!result.IsSuccess) + { + throw new InvalidOperationException(result.ErrorMessage); + } + + files.Add(Write(outputDirectory, $"{name}.from-json.filled{fromJson.FileExtension}", output.ToArray())); + log.WriteLine($"{name}.from-json{fromJson.FileExtension}: same bytes as C# ({fromJson.ContentHash[..12]})"); + } + } + + return files; + } + + private static string Write(string directory, string name, byte[] content) + { + string path = Path.Combine(directory, name); + File.WriteAllBytes(path, content); + return path; + } +} diff --git a/samples/TriasDev.Templify.Builder.Sample/SampleTexts.cs b/samples/TriasDev.Templify.Builder.Sample/SampleTexts.cs new file mode 100644 index 00000000..05af4686 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/SampleTexts.cs @@ -0,0 +1,50 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Sample; + +/// +/// The template texts in German and English. A real product would keep them in .resx files +/// (); a dictionary keeps the sample in one place. +/// +public static class SampleTexts +{ + private static readonly Dictionary _texts = new() + { + ["title"] = ("Auftragsbestätigung", "Order confirmation"), + ["orderNo"] = ("Auftrag", "Order"), + ["dateFormat"] = ("d. MMMM yyyy", "d MMMM yyyy"), + ["page"] = ("Seite", "Page"), + ["footer"] = ("Example Trading GmbH · Sample Street 1 · 80331 München", "Example Trading GmbH · Sample Street 1 · 80331 Munich"), + ["customer"] = ("Kunde", "Customer"), + ["newCustomer"] = ("Neukunde", "new customer"), + ["attn"] = ("z. Hd.", "Attn."), + ["items"] = ("Positionen", "Items"), + ["description"] = ("Beschreibung", "Description"), + ["quantity"] = ("Menge", "Qty"), + ["amount"] = ("Betrag", "Amount"), + ["inStock"] = ("auf Lager", "in stock"), + ["backOrdered"] = ("wird nachgeliefert", "back-ordered"), + ["discount"] = ("Rabatt", "Discount"), + ["total"] = ("Gesamtbetrag", "Total"), + ["freeExpress"] = ("Kostenloser Expressversand:", "Free express shipping:"), + ["statusPaid"] = ("Bezahlt – vielen Dank!", "Paid – thank you!"), + ["statusOverdue"] = ("Zahlung überfällig. Bitte begleichen Sie den Betrag umgehend.", "Payment overdue. Please settle the amount promptly."), + ["statusOpen"] = ("Zahlbar innerhalb von 14 Tagen.", "Payable within 14 days."), + ["expressFree"] = ("Expressversand – für Sie kostenlos.", "Express shipping – free of charge for you."), + ["express"] = ("Expressversand (zzgl. 15,00 €).", "Express shipping (plus €15.00)."), + ["standard"] = ("Standardversand.", "Standard shipping."), + ["checks"] = ("Prüfungen", "Checks"), + ["notes"] = ("Hinweise", "Notes"), + ["terms"] = ("Allgemeine Geschäftsbedingungen", "Terms and conditions"), + ["termsText"] = ( + "Es gelten unsere Allgemeinen Geschäftsbedingungen in der zum Zeitpunkt der Bestellung gültigen Fassung. Lieferzeiten sind unverbindlich, sofern nicht ausdrücklich anders vereinbart. Die Ware bleibt bis zur vollständigen Bezahlung unser Eigentum.", + "Our terms and conditions apply in the version valid at the time of the order. Delivery times are non-binding unless expressly agreed otherwise. The goods remain our property until paid in full."), + ["printedOn"] = ("Gedruckt am", "Printed on"), + }; + + /// Gets the catalog. + public static ITextCatalog Catalog { get; } = TextCatalog.FromDictionary(_texts.ToDictionary( + e => e.Key, + e => (IReadOnlyDictionary)new Dictionary { ["de"] = e.Value.De, ["en"] = e.Value.En })); +} diff --git a/samples/TriasDev.Templify.Builder.Sample/TriasDev.Templify.Builder.Sample.csproj b/samples/TriasDev.Templify.Builder.Sample/TriasDev.Templify.Builder.Sample.csproj new file mode 100644 index 00000000..7bfa3313 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/TriasDev.Templify.Builder.Sample.csproj @@ -0,0 +1,23 @@ + + + + + $(NoWarn);TPLB001 + Exe + net11.0 + + + + + + + + + + + + + + + diff --git a/samples/TriasDev.Templify.Builder.Sample/TypedOrderConfirmation.cs b/samples/TriasDev.Templify.Builder.Sample/TypedOrderConfirmation.cs new file mode 100644 index 00000000..96e3dcac --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/TypedOrderConfirmation.cs @@ -0,0 +1,173 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Sample; + +/// +/// The address block of with a typed parameter: the component navigates the address with +/// the compiler's help and builds the same output. +/// +public sealed record OrderAddressBlock(TemplatePath
Address) : ITemplateComponent +{ + public void Compose(BlockComposer c) + { + c.Paragraph(x => + { + x.Value(Address.Street).LineBreak().Value(Address.PostalCode).Text(" ").Value(Address.City); + x.If(Address.Country.NotEq("DE"), t => t.Text(", ").Value(Address.Country)); + }); + } +} + +/// +/// The order confirmation of , with data paths from instead of +/// strings: order.Number, line.Quantity are generated from the data classes (TriasDev.Templify.Builder's +/// source generator). It builds byte for byte the same templates. +/// +public sealed class TypedOrderConfirmation(BrandTheme theme) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = new("order-confirmation", 1); + + public void Compose(TemplateComposer template) + { + TemplateTexts t = template.Texts; + TemplatePath order = template.DataAs().Order; + + template.Share(theme); + template.Styles(Styles.Create(theme)); + template.Properties(p => p.Title(t["title"]).Author("Example Trading").Subject(t["title"])); + + template.Page(page => page + .Size(PageSize.A4) + .Margins(25.Mm(), 20.Mm(), 22.Mm(), 20.Mm()) + .Header(h => h.Paragraph(Styles.Small, x => x + .Text(t["title"] + " ").Value(order.Number) + .TabRight() + .Text(t["page"] + " ").PageNumber().Text(" / ").PageCount())) + .Footer(f => f.Paragraph(Styles.Small, t["footer"])) + .FirstPage(first => + { + first.Header(h => h.Paragraph(Styles.Logo, x => x.Image(theme.Logo, "Example Trading", ImageFit.Height(12.Mm())))); + first.Footer(f => f.Paragraph(Styles.Small, t["footer"])); + })); + + template.Content(c => + { + c.Paragraph(Styles.Title, t["title"]); + c.Paragraph(Styles.Subtitle, x => x + .Text(t["orderNo"] + " ").Value(Styles.Strong, order.Number) + .Text(" · ").Value(order.Date, ValueFormat.Date(t["dateFormat"]))); + + c.TableOfContents(1); + + c.Section("customer", b => Customer(b, t, order)); + c.Section("items", b => Items(b, t, order)); + c.Section("status", b => Status(b, t, order)); + c.Section("checks", b => Checks(b, t, order)); + c.Section("notes", b => Notes(b, t, order)); + + c.PageBreak(); + c.Component(new Terms()); + c.Raw(OrderConfirmation.PrintedOn(t["printedOn"])); + }); + } + + private static void Customer(BlockComposer c, TemplateTexts t, TemplatePath order) + { + TemplatePath customer = order.Customer; + c.Paragraph(Styles.Heading, t["customer"]); + c.Paragraph(x => + { + x.Value(Styles.Strong, customer.Name); + x.If(customer.IsNew, s => s.Text(Styles.Muted, " (" + t["newCustomer"] + ")")); + }); + c.If(customer.Contact.IsNotEmpty, b => b.Paragraph(x => + { + x.Text(Styles.Muted, t["attn"] + " "); + x.Value(customer.Contact); + })); + c.Component(new OrderAddressBlock(customer.Address)); + } + + private static void Items(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.Paragraph(Styles.Heading, t["items"]); + c.Table(table => + { + table.Style(Styles.Grid).SpaceAfter(8.Pt()); + table.Columns(cols => + { + cols.Fixed(10.Mm()); + cols.Relative(4); + cols.Fixed(16.Mm()); + cols.Fixed(30.Mm()); + }); + table.HeaderRow(r => r.Cell("#").Cell(t["description"]).Cell(t["quantity"]).Cell(t["amount"])); + table.ForEachRow(order.Lines, "line", (line, rows) => + { + rows.Row(r => + { + r.Cell(line.Loop.Number); + r.Cell(cell => + { + cell.Paragraph(x => + { + x.Value(line.Description).Text(Styles.Muted, " — "); + x.If(line.InStock, s => s.Text(Styles.Muted, t["inStock"])).Else(s => s.Text(Styles.Muted, t["backOrdered"])); + }); + cell.If(line.Tags.IsNotEmpty, b => b.Paragraph(Styles.Small, x => x.Value(line.Tags, ValueFormat.Join(separator: " · ")))); + }); + r.Cell(line.Quantity); + r.Cell(cell => cell.Paragraph(x => x.Value(line.Amount, ValueFormat.Currency))); + }); + }); + table.RowsIf(order.Discount.Gt(0), rows => rows.Row(r => + { + r.Cell(cell => cell.ColumnSpan(3).Paragraph(t["discount"])); + r.Cell(cell => cell.Paragraph(x => x.Value(order.Discount, ValueFormat.Currency))); + })); + table.Row(r => + { + r.ParagraphStyle(Styles.TableHeader); + r.Cell(cell => cell.ColumnSpan(3).Border(Sides.Top, 1.Pt(), c.Shared().Accent).Paragraph(t["total"])); + r.Cell(cell => cell.Border(Sides.Top, 1.Pt(), c.Shared().Accent).Paragraph(x => x.Value(order.Total, ValueFormat.Currency))); + }); + }); + + c.Paragraph(null, x => x.Text(t["freeExpress"] + " ").Expression(order.IsExpress & order.Total.Gt(1000), ValueFormat.YesNo), p => p.SpaceBefore(6.Pt())); + } + + private static void Status(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.Switch(order.Status, s => + { + s.Case("paid", b => b.Box(Styles.Success, x => x.Paragraph(t["statusPaid"]))); + s.Case(new[] { "overdue", "reminded" }, b => b.Box(Styles.Warning, x => x.Paragraph(t["statusOverdue"]))); + s.Default(b => b.Paragraph(t["statusOpen"])); + }); + + Condition expressFree = order.IsExpress & order.Total.Gt(1000); + c.If(expressFree, b => b.Paragraph(t["expressFree"])) + .ElseIf(order.IsExpress, b => b.Paragraph(t["express"])) + .Else(b => b.Paragraph(t["standard"])); + } + + private static void Checks(BlockComposer c, TemplateTexts t, TemplatePath order) + { + TemplateCollection checks = order.Checks; + c.If(checks.IsNotEmpty, b => + { + b.Paragraph(Styles.Heading, t["checks"]); + b.List(Styles.Bullets, list => list.ForEach(checks, "check", (check, items) => + { + items.Item(x => x.Value(check.Title).Text(": ").Value(check.Passed, ValueFormat.Checkmark)); + items.If(check.Note.Exists, notes => notes.Item(1, check.Note)); + })); + }); + } + + private static void Notes(BlockComposer c, TemplateTexts t, TemplatePath order) + { + c.If(order.Notes.IsNotEmpty, b => b.Paragraph(Styles.Heading, t["notes"]).Paragraph(order.Notes)); + } +} diff --git a/samples/TriasDev.Templify.Builder.Sample/logo.png b/samples/TriasDev.Templify.Builder.Sample/logo.png new file mode 100644 index 00000000..a5f267da Binary files /dev/null and b/samples/TriasDev.Templify.Builder.Sample/logo.png differ diff --git a/samples/TriasDev.Templify.Builder.Sample/packages.lock.json b/samples/TriasDev.Templify.Builder.Sample/packages.lock.json new file mode 100644 index 00000000..384cc505 --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/packages.lock.json @@ -0,0 +1,49 @@ +{ + "version": 2, + "dependencies": { + "net11.0": { + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + }, + "triasdev.templify.builder": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify": "[1.10.0, )" + } + }, + "triasdev.templify.builder.testing": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify.Builder": "[0.1.0, )" + } + }, + "DocumentFormat.OpenXml": { + "type": "CentralTransitive", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + } + } + } +} \ No newline at end of file diff --git a/samples/TriasDev.Templify.Builder.Sample/sample-data.json b/samples/TriasDev.Templify.Builder.Sample/sample-data.json new file mode 100644 index 00000000..9b70d4df --- /dev/null +++ b/samples/TriasDev.Templify.Builder.Sample/sample-data.json @@ -0,0 +1,25 @@ +{ + "order": { + "number": "EX-2026-0417", + "date": "2026-11-25T10:00:00", + "status": "paid", + "isExpress": true, + "total": 1849.5, + "discount": 0, + "notes": "Please deliver **before noon**.", + "customer": { + "name": "Example Trading GmbH", + "contact": "Erika Example", + "isNew": true, + "address": { "street": "Sample Street 12", "postalCode": "80331", "city": "Munich", "country": "DE" } + }, + "lines": [ + { "description": "Laptop 14\"", "quantity": 1, "amount": 1499.0, "inStock": true, "tags": [ "Hardware", "3-year warranty" ] }, + { "description": "USB-C dock", "quantity": 2, "amount": 175.25, "inStock": false, "tags": [] } + ], + "checks": [ + { "title": "Credit limit", "passed": true }, + { "title": "Export control", "passed": true } + ] + } +} diff --git a/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Shipped.md b/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..f50bb1fe --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Shipped.md @@ -0,0 +1,2 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md diff --git a/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Unshipped.md b/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..2d0ff803 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,9 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +TBG001 | TemplifyBuilder | Warning | TypedPathGenerator: a data property is not generated because the receiver type already has a member of that name +TBG002 | TemplifyBuilder | Error | TypedPathGenerator: the generated extension properties need C# 14 diff --git a/src/TriasDev.Templify.Builder.Generators/DataTypeModel.cs b/src/TriasDev.Templify.Builder.Generators/DataTypeModel.cs new file mode 100644 index 00000000..53823a4e --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/DataTypeModel.cs @@ -0,0 +1,71 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace TriasDev.Templify.Builder.Generators; + +/// An object type to generate extension properties for (fully qualified C# name). +internal sealed record DataTypeModel(string TypeName, bool IsItem, EquatableArray Properties); + +/// How a data property is reached. +internal enum PropertyKind +{ + /// TemplatePath<T> through Path(x => x.Name). + Path, + + /// TemplateCollection<TItem> through Items<TItem>(x => x.Name). + Collection, +} + +/// +/// A data property: its C# name (escaped if a keyword), its type (or item type for a collection) and the receivers it is +/// not generated for because they already have a member of that name. +/// +internal sealed record PropertyModel(string Name, string Identifier, PropertyKind Kind, string TypeName, bool SkipOnPath, bool SkipOnLoopItem, string? Obsolete); + +/// A name collision to report (TBG001). +internal sealed record CollisionModel(string TypeName, string Property, string Receiver, LocationModel? Location); + +/// A source location that survives between generator runs (a does not compare by value). +internal sealed record LocationModel(string FilePath, Microsoft.CodeAnalysis.Text.TextSpan Span, Microsoft.CodeAnalysis.Text.LinePositionSpan LineSpan) +{ + public Microsoft.CodeAnalysis.Location ToLocation() => Microsoft.CodeAnalysis.Location.Create(FilePath, Span, LineSpan); +} + +/// What one root (a DataAs<T> call or an assembly attribute) contributes. +internal sealed record RootModel(EquatableArray Types, EquatableArray Collisions); + +/// An immutable array that compares by its items, for the incremental pipeline's caching. +internal readonly struct EquatableArray : IEquatable>, IEnumerable + where T : IEquatable +{ + private readonly ImmutableArray _items; + + public EquatableArray(ImmutableArray items) => _items = items; + + public ImmutableArray Items => _items.IsDefault ? ImmutableArray.Empty : _items; + + public bool Equals(EquatableArray other) => Items.SequenceEqual(other.Items); + + public override bool Equals(object? obj) => obj is EquatableArray other && Equals(other); + + public override int GetHashCode() + { + int hash = 17; + foreach (T item in Items) + { + hash = (hash * 31) + item.GetHashCode(); + } + + return hash; + } + + public IEnumerator GetEnumerator() => ((IEnumerable)Items).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/TriasDev.Templify.Builder.Generators/IsExternalInit.cs b/src/TriasDev.Templify.Builder.Generators/IsExternalInit.cs new file mode 100644 index 00000000..07f86e50 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/IsExternalInit.cs @@ -0,0 +1,9 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace System.Runtime.CompilerServices; + +/// Lets netstandard2.0 code use records and init accessors. +internal static class IsExternalInit +{ +} diff --git a/src/TriasDev.Templify.Builder.Generators/PublicAPI.Shipped.txt b/src/TriasDev.Templify.Builder.Generators/PublicAPI.Shipped.txt new file mode 100644 index 00000000..7dc5c581 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/TriasDev.Templify.Builder.Generators/PublicAPI.Unshipped.txt b/src/TriasDev.Templify.Builder.Generators/PublicAPI.Unshipped.txt new file mode 100644 index 00000000..b57075a5 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/PublicAPI.Unshipped.txt @@ -0,0 +1,4 @@ +#nullable enable +TriasDev.Templify.Builder.Generators.TypedPathGenerator +TriasDev.Templify.Builder.Generators.TypedPathGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void +TriasDev.Templify.Builder.Generators.TypedPathGenerator.TypedPathGenerator() -> void diff --git a/src/TriasDev.Templify.Builder.Generators/TriasDev.Templify.Builder.Generators.csproj b/src/TriasDev.Templify.Builder.Generators/TriasDev.Templify.Builder.Generators.csproj new file mode 100644 index 00000000..4236535d --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/TriasDev.Templify.Builder.Generators.csproj @@ -0,0 +1,30 @@ + + + + + netstandard2.0 + true + true + false + false + + disable + + + + + + + + + + + + + + + + + + diff --git a/src/TriasDev.Templify.Builder.Generators/TypedPathGenerator.cs b/src/TriasDev.Templify.Builder.Generators/TypedPathGenerator.cs new file mode 100644 index 00000000..e5e43ab8 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/TypedPathGenerator.cs @@ -0,0 +1,530 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace TriasDev.Templify.Builder.Generators; + +/// +/// Generates typed data paths: for every data type used in TemplateComposer.DataAs<T>() (or named in +/// [assembly: TemplateData(typeof(T))]) and every type reachable from it, C# 14 extension properties on +/// TemplatePath<T> and LoopItem<T>, so a definition writes order.Number instead of +/// order.Path(o => o.Number). Each property calls that lambda API, so names follow the same rules. +/// +[Generator(LanguageNames.CSharp)] +public sealed class TypedPathGenerator : IIncrementalGenerator +{ + private const string BuilderNamespace = "TriasDev.Templify.Builder"; + private const string PathParameter = "__templifyPath"; + private const string ItemParameter = "__templifyItem"; + + private static readonly DiagnosticDescriptor _collision = new DiagnosticDescriptor( + "TBG001", + "Data property not generated", + "'{0}.{1}' is not generated for {2}: it already has a member '{1}', which '.{1}' means instead; write the lambda, for example .Path(x => x.{1})", + "TemplifyBuilder", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor _languageVersion = new DiagnosticDescriptor( + "TBG002", + "Typed data paths need C# 14", + "The typed data paths of TriasDev.Templify.Builder are C# 14 extension properties; set LangVersion to 14 or later (.NET 10 SDK or later)", + "TemplifyBuilder", + DiagnosticSeverity.Error, + isEnabledByDefault: true); + + private static readonly SymbolDisplayFormat _typeFormat = SymbolDisplayFormat.FullyQualifiedFormat; + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + IncrementalValuesProvider calls = context.SyntaxProvider + .CreateSyntaxProvider(static (node, _) => IsDataAsCall(node), static (syntax, token) => FromCall(syntax, token)) + .Where(static root => root is not null) + .Select(static (root, _) => root!); + + IncrementalValueProvider attributes = context.CompilationProvider.Select(static (compilation, token) => FromAttributes(compilation, token)); + + // Typed paths a referenced assembly generated and lets this one use (InternalsVisibleTo): not generated again, + // or both extension members would be in scope and every use ambiguous. + IncrementalValueProvider> covered = context.CompilationProvider.Select(static (compilation, _) => Covered(compilation)); + + IncrementalValueProvider supported = context.ParseOptionsProvider.Select(static (options, _) => + options is CSharpParseOptions csharp && csharp.LanguageVersion >= LanguageVersion.CSharp14); + + context.RegisterSourceOutput(calls.Collect().Combine(attributes).Combine(supported).Combine(covered), static (output, input) => + { + (((ImmutableArray fromCalls, RootModel? fromAttributes), bool languageSupported), EquatableArray coveredBlocks) = input; + List roots = fromCalls.ToList(); + if (fromAttributes is not null) + { + roots.Add(fromAttributes); + } + + List types = roots.SelectMany(r => r.Types) + .GroupBy(t => t.TypeName) + .Select(g => g.First() with { IsItem = g.Any(t => t.IsItem) }) + .Where(t => t.Properties.Items.Length > 0) + .OrderBy(t => t.TypeName, System.StringComparer.Ordinal) + .ToList(); + if (types.Count == 0) + { + return; + } + + if (!languageSupported) + { + output.ReportDiagnostic(Diagnostic.Create(_languageVersion, Location.None)); + return; + } + + foreach (CollisionModel collision in roots.SelectMany(r => r.Collisions).Distinct()) + { + output.ReportDiagnostic(Diagnostic.Create(_collision, collision.Location?.ToLocation() ?? Location.None, collision.TypeName, collision.Property, collision.Receiver)); + } + + string? source = Emit(types, new HashSet(coveredBlocks, System.StringComparer.Ordinal)); + if (source is not null) + { + output.AddSource("TemplifyDataPaths.g.cs", source); + } + }); + } + + private static bool IsDataAsCall(SyntaxNode node) => node is InvocationExpressionSyntax invocation && invocation.Expression switch + { + MemberAccessExpressionSyntax { Name: GenericNameSyntax { Identifier.ValueText: "DataAs" } } => true, + GenericNameSyntax { Identifier.ValueText: "DataAs" } => true, + _ => false, + }; + + private static RootModel? FromCall(GeneratorSyntaxContext context, CancellationToken token) + { + if (context.SemanticModel.GetSymbolInfo(context.Node, token).Symbol is not IMethodSymbol { Name: "DataAs", TypeArguments.Length: 1 } method + || method.ContainingType.ToDisplayString() != BuilderNamespace + ".TemplateComposer") + { + return null; + } + + return Build(context.SemanticModel.Compilation, [method.TypeArguments[0]], token); + } + + private static EquatableArray Covered(Compilation compilation) + { + List keys = new List(); + foreach (IAssemblySymbol assembly in compilation.SourceModule.ReferencedAssemblySymbols) + { + if (!assembly.GivesAccessTo(compilation.Assembly)) + { + continue; + } + + foreach (AttributeData attribute in assembly.GetAttributes()) + { + if (attribute.AttributeClass?.ToDisplayString() == BuilderNamespace + ".GeneratedDataPathsAttribute" + && attribute.ConstructorArguments.Length == 2 + && attribute.ConstructorArguments[0].Value is ITypeSymbol type + && attribute.ConstructorArguments[1].Value is bool loopItem) + { + keys.Add(BlockKey(type.ToDisplayString(_typeFormat), loopItem)); + } + } + } + + return new EquatableArray(keys.ToImmutableArray()); + } + + private static string BlockKey(string typeName, bool loopItem) => (loopItem ? "loop:" : "path:") + typeName; + + private static RootModel? FromAttributes(Compilation compilation, CancellationToken token) + { + List roots = compilation.Assembly.GetAttributes() + .Where(a => a.AttributeClass?.ToDisplayString() == BuilderNamespace + ".TemplateDataAttribute") + .Select(a => a.ConstructorArguments.Length == 1 ? a.ConstructorArguments[0].Value as ITypeSymbol : null) + .OfType() + .ToList(); + return roots.Count == 0 ? null : Build(compilation, roots, token); + } + + /// Every object type reachable from the roots, with its properties (the DataCatalog type rules). + private static RootModel? Build(Compilation compilation, IReadOnlyList roots, CancellationToken token) + { + INamedTypeSymbol? path = compilation.GetTypeByMetadataName(BuilderNamespace + ".TemplatePath`1"); + INamedTypeSymbol? loopItem = compilation.GetTypeByMetadataName(BuilderNamespace + ".LoopItem`1"); + if (path is null || loopItem is null) + { + return null; + } + + HashSet pathMembers = MemberNames(path); + HashSet loopMembers = MemberNames(loopItem); + List types = new List(); + List collisions = new List(); + HashSet seen = new HashSet(SymbolEqualityComparer.Default); + HashSet items = new HashSet(SymbolEqualityComparer.Default); + Queue pending = new Queue(roots); + while (pending.Count > 0) + { + token.ThrowIfCancellationRequested(); + ITypeSymbol type = pending.Dequeue(); + // Types of .NET itself are not walked: the lambda API rejects their members as data (PathExpression). + if (!seen.Add(type) || Classify(compilation, type) != Shape.Object || !IsAccessible(compilation, type) || IsSystem(type) || IsObsolete(type)) + { + continue; + } + + string typeName = type.ToDisplayString(_typeFormat); + List properties = new List(); + foreach (IPropertySymbol property in DataProperties(type)) + { + if (property.ReturnsByRef || property.ReturnsByRefReadonly || property.Type.IsRefLikeType || IsObsolete(property.Type)) + { + continue; + } + + ITypeSymbol bare = Unwrap(property.Type); + PropertyKind kind = PropertyKind.Path; + ITypeSymbol target = property.Type; + Shape shape = Classify(compilation, bare); + if (shape == Shape.Collection && ItemType(bare) is { } item) + { + kind = PropertyKind.Collection; + target = item; + items.Add(item); + pending.Enqueue(item); + } + else if (shape == Shape.Object) + { + pending.Enqueue(property.Type); + } + + if (!IsAccessible(compilation, target) || target.IsRefLikeType || IsObsolete(target)) + { + continue; + } + + bool skipOnPath = pathMembers.Contains(property.Name); + bool skipOnLoopItem = loopMembers.Contains(property.Name); + LocationModel? location = Where(property); + if (skipOnPath) + { + collisions.Add(new CollisionModel(type.Name, property.Name, "TemplatePath<" + type.Name + ">", location)); + } + + if (skipOnLoopItem) + { + collisions.Add(new CollisionModel(type.Name, property.Name, "LoopItem<" + type.Name + ">", location)); + } + + properties.Add(new PropertyModel(property.Name, Identifier(property.Name), kind, target.ToDisplayString(_typeFormat), skipOnPath, skipOnLoopItem, ObsoleteAttribute(property))); + } + + types.Add(new DataTypeModel(typeName, false, new EquatableArray(properties.ToImmutableArray()))); + } + + // LoopItem exists only for the items of a collection: only they get loop blocks and loop collisions. + types = types.Select(t => t with { IsItem = items.Any(i => i.ToDisplayString(_typeFormat) == t.TypeName) }).ToList(); + collisions = collisions.Where(c => c.Receiver.StartsWith("TemplatePath<", System.StringComparison.Ordinal) + || types.Any(t => t.IsItem && t.TypeName.EndsWith("." + c.TypeName, System.StringComparison.Ordinal) && c.Receiver == "LoopItem<" + c.TypeName + ">")).ToList(); + + return new RootModel(new EquatableArray(types.ToImmutableArray()), new EquatableArray(collisions.ToImmutableArray())); + } + + private static bool IsSystem(ITypeSymbol type) + { + string? name = type.ContainingNamespace?.ToDisplayString(); + return name is not null && (name == "System" || name.StartsWith("System.", System.StringComparison.Ordinal)); + } + + private static bool IsObsolete(ISymbol symbol) => + symbol.GetAttributes().Any(a => a.AttributeClass?.ToDisplayString() == "System.ObsoleteAttribute"); + + /// An obsolete data property stays obsolete: the attribute is copied, so its use warns where it is used, not in the generated file. + private static string? ObsoleteAttribute(IPropertySymbol property) + { + AttributeData? obsolete = property.GetAttributes().FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == "System.ObsoleteAttribute"); + if (obsolete is null) + { + return null; + } + + IEnumerable arguments = obsolete.ConstructorArguments.Select(a => a.Value switch + { + string text => SymbolDisplay.FormatLiteral(text, quote: true), + bool flag => flag ? "true" : "false", + _ => "null", + }); + return "[global::System.Obsolete(" + string.Join(", ", arguments) + ")]"; + } + + /// + /// Public readable instance properties, the type's own first, then inherited ones it does not hide. For an interface, + /// a name that only several base interfaces declare is ambiguous in C# and left out. + /// + private static IEnumerable DataProperties(ITypeSymbol type) + { + HashSet names = new HashSet(System.StringComparer.Ordinal); + if (type.TypeKind == TypeKind.Interface) + { + HashSet own = new HashSet(type.GetMembers().OfType().Select(p => p.Name), System.StringComparer.Ordinal); + foreach (IGrouping shared in type.AllInterfaces + .SelectMany(i => i.GetMembers().OfType().Select(p => (p.Name, Owner: i))) + .GroupBy(p => p.Name, p => p.Owner) + .Where(g => !own.Contains(g.Key) && g.Distinct(SymbolEqualityComparer.Default).Count() > 1)) + { + names.Add(shared.Key); + } + } + + IEnumerable chain = type.TypeKind == TypeKind.Interface + ? new[] { type }.Concat(type.AllInterfaces) + : Bases(type); + foreach (ITypeSymbol owner in chain) + { + foreach (IPropertySymbol property in owner.GetMembers().OfType()) + { + if (property.DeclaredAccessibility != Accessibility.Public || property.IsStatic || property.IsIndexer + || property.GetMethod is not { DeclaredAccessibility: Accessibility.Public } || IsIgnored(property) || !names.Add(property.Name)) + { + continue; + } + + yield return property; + } + } + } + + private static IEnumerable Bases(ITypeSymbol type) + { + for (ITypeSymbol? current = type; current is not null && current.SpecialType != SpecialType.System_Object && current.SpecialType != SpecialType.System_ValueType; current = current.BaseType) + { + yield return current; + } + } + + /// [JsonIgnore] without a condition, or with Condition = Always, hides a property. + private static bool IsIgnored(IPropertySymbol property) => property.GetAttributes().Any(a => + a.AttributeClass?.ToDisplayString() == "System.Text.Json.Serialization.JsonIgnoreAttribute" + && a.NamedArguments.Where(n => n.Key == "Condition").Select(n => n.Value.Value as int?).DefaultIfEmpty(1).First() == 1); + + private enum Shape + { + Value, + Open, + Collection, + Object, + Other, + } + + private static Shape Classify(Compilation compilation, ITypeSymbol type) + { + type = Unwrap(type); + if (IsValue(type)) + { + return Shape.Value; + } + + if (IsOpen(compilation, type)) + { + return Shape.Open; + } + + if (ItemType(type) is not null) + { + return Shape.Collection; + } + + return type.TypeKind is TypeKind.Class or TypeKind.Struct or TypeKind.Interface && type is INamedTypeSymbol ? Shape.Object : Shape.Other; + } + + private static ITypeSymbol Unwrap(ITypeSymbol type) => + type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable ? nullable.TypeArguments[0] : type; + + private static bool IsValue(ITypeSymbol type) + { + if (type.TypeKind == TypeKind.Enum) + { + return true; + } + + switch (type.SpecialType) + { + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + case SpecialType.System_String: + case SpecialType.System_IntPtr: + case SpecialType.System_UIntPtr: + case SpecialType.System_DateTime: + return true; + } + + return type.ToDisplayString() is "System.DateTimeOffset" or "System.DateOnly" or "System.TimeOnly" or "System.TimeSpan" or "System.Guid"; + } + + private static bool IsOpen(Compilation compilation, ITypeSymbol type) + { + if (type.SpecialType == SpecialType.System_Object || type.TypeKind == TypeKind.Dynamic) + { + return true; + } + + string name = type.ToDisplayString(); + if (name is "System.Text.Json.JsonElement" or "System.Dynamic.ExpandoObject") + { + return true; + } + + for (ITypeSymbol? current = type; current is not null; current = current.BaseType) + { + if (current.ToDisplayString() == "System.Text.Json.Nodes.JsonNode") + { + return true; + } + } + + return new[] { type }.Concat(type.AllInterfaces).Any(i => + i.ToDisplayString() == "System.Collections.IDictionary" + || (i is INamedTypeSymbol { IsGenericType: true } generic + && generic.OriginalDefinition.ToDisplayString() is "System.Collections.Generic.IDictionary" or "System.Collections.Generic.IReadOnlyDictionary")); + } + + private static ITypeSymbol? ItemType(ITypeSymbol type) + { + if (type is IArrayTypeSymbol array) + { + return array.ElementType; + } + + return new[] { type }.Concat(type.AllInterfaces) + .OfType() + .FirstOrDefault(i => i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) + ?.TypeArguments[0]; + } + + /// Whether the generated code (in the compilation's assembly) can name the type. + private static bool IsAccessible(Compilation compilation, ITypeSymbol type) => type switch + { + IArrayTypeSymbol array => IsAccessible(compilation, array.ElementType), + INamedTypeSymbol named => !named.IsFileLocal && compilation.IsSymbolAccessibleWithin(named.OriginalDefinition, compilation.Assembly) + && (named.ContainingType is null || IsAccessible(compilation, named.ContainingType)) + && named.TypeArguments.All(t => IsAccessible(compilation, t)), + ITypeParameterSymbol => false, + _ => type.TypeKind != TypeKind.Error && type.TypeKind != TypeKind.Pointer && type.TypeKind != TypeKind.FunctionPointer, + }; + + private static HashSet MemberNames(INamedTypeSymbol type) + { + HashSet names = new HashSet(type.GetMembers().Select(m => m.Name), System.StringComparer.Ordinal) + { + "Equals", "GetHashCode", "ToString", "GetType", "MemberwiseClone", "ReferenceEquals", + }; + return names; + } + + private static string Identifier(string name) => + SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None ? "@" + name : name; + + private static LocationModel? Where(IPropertySymbol property) => + property.Locations.FirstOrDefault(l => l.IsInSource) is { SourceTree: { } tree } location + ? new LocationModel(tree.FilePath, location.SourceSpan, location.GetLineSpan().Span) + : null; + + private static string? Emit(IReadOnlyList types, HashSet covered) + { + StringBuilder blocks = new StringBuilder(); + List marks = new List(); + foreach (DataTypeModel type in types) + { + if (!covered.Contains(BlockKey(type.TypeName, false)) + && Block(blocks, type, "global::" + BuilderNamespace + ".TemplatePath<" + type.TypeName + ">", PathParameter, p => !p.SkipOnPath)) + { + marks.Add("[assembly: global::" + BuilderNamespace + ".GeneratedDataPaths(typeof(" + type.TypeName + "), false)]"); + } + + if (type.IsItem && !covered.Contains(BlockKey(type.TypeName, true)) + && Block(blocks, type, "global::" + BuilderNamespace + ".LoopItem<" + type.TypeName + ">", ItemParameter, p => !p.SkipOnLoopItem)) + { + marks.Add("[assembly: global::" + BuilderNamespace + ".GeneratedDataPaths(typeof(" + type.TypeName + "), true)]"); + } + } + + if (marks.Count == 0) + { + return null; + } + + StringBuilder text = new StringBuilder(); + text.AppendLine("// "); + text.AppendLine("// Typed data paths of TriasDev.Templify.Builder: order.Number instead of order.Path(o => o.Number)."); + text.AppendLine("#nullable disable"); + + // The builder is experimental (TPLB001); the consumer opts in for its own code, the generated code never reports it. + text.AppendLine("#pragma warning disable TPLB001"); + text.AppendLine(); + foreach (string mark in marks) + { + text.AppendLine(mark); + } + + text.AppendLine(); + text.AppendLine("namespace " + BuilderNamespace); + text.AppendLine("{"); + text.AppendLine(" internal static class TemplifyDataPaths"); + text.AppendLine(" {"); + text.Append(blocks.ToString().TrimEnd('\n', '\r')); + text.AppendLine(); + text.AppendLine(" }"); + text.AppendLine("}"); + return text.ToString(); + } + + private static bool Block(StringBuilder text, DataTypeModel type, string receiver, string parameter, System.Func include) + { + List properties = type.Properties.Where(include).ToList(); + if (properties.Count == 0) + { + return false; + } + + if (text.Length > 0) + { + text.AppendLine(); + } + + text.AppendLine(" extension(" + receiver + " " + parameter + ")"); + text.AppendLine(" {"); + foreach (PropertyModel property in properties) + { + if (property.Obsolete is { } obsolete) + { + text.AppendLine(" " + obsolete); + } + + text.AppendLine(property.Kind == PropertyKind.Collection + ? " public global::" + BuilderNamespace + ".TemplateCollection<" + property.TypeName + "> " + property.Identifier + " => " + parameter + ".Items<" + property.TypeName + ">(__x => __x." + property.Identifier + ");" + : " public global::" + BuilderNamespace + ".TemplatePath<" + property.TypeName + "> " + property.Identifier + " => " + parameter + ".Path(__x => __x." + property.Identifier + ");"); + } + + text.AppendLine(" }"); + return true; + } +} diff --git a/src/TriasDev.Templify.Builder.Generators/packages.lock.json b/src/TriasDev.Templify.Builder.Generators/packages.lock.json new file mode 100644 index 00000000..2369839e --- /dev/null +++ b/src/TriasDev.Templify.Builder.Generators/packages.lock.json @@ -0,0 +1,126 @@ +{ + "version": 2, + "dependencies": { + ".NETStandard,Version=v2.0": { + "Microsoft.CodeAnalysis.CSharp": { + "type": "Direct", + "requested": "[5.0.0, )", + "resolved": "5.0.0", + "contentHash": "5DSyJ9bk+ATuDy7fp2Zt0mJStDVKbBoiz1DyfAwSa+k4H4IwykAUcV3URelw5b8/iVbfSaOwkwmPUZH6opZKCw==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.11.0", + "Microsoft.CodeAnalysis.Common": "[5.0.0]", + "System.Buffers": "4.6.0", + "System.Collections.Immutable": "9.0.0", + "System.Memory": "4.6.0", + "System.Numerics.Vectors": "4.6.0", + "System.Reflection.Metadata": "9.0.0", + "System.Runtime.CompilerServices.Unsafe": "6.1.0", + "System.Text.Encoding.CodePages": "8.0.0", + "System.Threading.Tasks.Extensions": "4.6.0" + } + }, + "Microsoft.CodeAnalysis.PublicApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "W4kJGezNIKLzo0Ak5FAQDFvkMf2U7DtGL4THmHyRSApfKsKt5V+eX/bU0ZLKAt/uf9Bb2o1bi0YDKj/GRB/vYQ==" + }, + "NETStandard.Library": { + "type": "Direct", + "requested": "[2.0.3, )", + "resolved": "2.0.3", + "contentHash": "st47PosZSHrjECdjeIzZQbzivYBJFv6P2nv4cj2ypdI204DO+vZ7l5raGMiX4eXMJ53RfOIg+/s4DHVZ54Nu2A==", + "dependencies": { + "Microsoft.NETCore.Platforms": "1.1.0" + } + }, + "Microsoft.CodeAnalysis.Analyzers": { + "type": "Transitive", + "resolved": "3.11.0", + "contentHash": "v/EW3UE8/lbEYHoC2Qq7AR/DnmvpgdtAMndfQNmpuIMx/Mto8L5JnuCfdBYtgvalQOtfNCnxFejxuRrryvUTsg==" + }, + "Microsoft.CodeAnalysis.Common": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "ZXRAdvH6GiDeHRyd3q/km8Z44RoM6FBWHd+gen/la81mVnAdHTEsEkO5J0TCNXBymAcx5UYKt5TvgKBhaLJEow==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.11.0", + "System.Buffers": "4.6.0", + "System.Collections.Immutable": "9.0.0", + "System.Memory": "4.6.0", + "System.Numerics.Vectors": "4.6.0", + "System.Reflection.Metadata": "9.0.0", + "System.Runtime.CompilerServices.Unsafe": "6.1.0", + "System.Text.Encoding.CodePages": "8.0.0", + "System.Threading.Tasks.Extensions": "4.6.0" + } + }, + "Microsoft.NETCore.Platforms": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.0", + "contentHash": "lN6tZi7Q46zFzAbRYXTIvfXcyvQQgxnY7Xm6C6xQ9784dEL1amjM6S6Iw4ZpsvesAKnRVsM4scrDQaDqSClkjA==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "9.0.0", + "contentHash": "QhkXUl2gNrQtvPmtBTQHb0YsUrDiDQ2QS09YbtTTiSjGcf7NBqtYbrG/BE06zcBPCKEwQGzIv13IVdXNOSub2w==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.0", + "contentHash": "OEkbBQoklHngJ8UD8ez2AERSk2g+/qpAaSWWCBFbpH727HxDq5ydVkuncBaKcKfwRqXGWx64dS6G1SUScMsitg==", + "dependencies": { + "System.Buffers": "4.6.0", + "System.Numerics.Vectors": "4.6.0", + "System.Runtime.CompilerServices.Unsafe": "6.1.0" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.0", + "contentHash": "t+SoieZsRuEyiw/J+qXUbolyO219tKQQI0+2/YI+Qv7YdGValA6WiuokrNKqjrTNsy5ABWU11bdKOzUdheteXg==" + }, + "System.Reflection.Metadata": { + "type": "Transitive", + "resolved": "9.0.0", + "contentHash": "ANiqLu3DxW9kol/hMmTWbt3414t9ftdIuiIU7j80okq2YzAueo120M442xk1kDJWtmZTqWQn7wHDvMRipVOEOQ==", + "dependencies": { + "System.Collections.Immutable": "9.0.0", + "System.Memory": "4.5.5" + } + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.0", + "contentHash": "5o/HZxx6RVqYlhKSq8/zronDkALJZUT2Vz0hx43f0gwe8mwlM0y2nYlqdBwLMzr262Bwvpikeb/yEwkAa5PADg==" + }, + "System.Text.Encoding.CodePages": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "OZIsVplFGaVY90G2SbpgU7EnCoOO5pw1t4ic21dBF3/1omrJFpAGoNAVpPyMVOC90/hvgkGG3VFqR13YgZMQfg==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.0", + "contentHash": "I5G6Y8jb0xRtGUC9Lahy7FUvlYlnGMMkbuKAQBy8Jb7Y6Yn8OlBEiUOY0PqZ0hy6Ua8poVA1ui1tAIiXNxGdsg==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.0" + } + } + } + } +} \ No newline at end of file diff --git a/src/TriasDev.Templify.Builder.Testing/Experimental.cs b/src/TriasDev.Templify.Builder.Testing/Experimental.cs new file mode 100644 index 00000000..e1ffe49d --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/Experimental.cs @@ -0,0 +1,6 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +// The builder packages are a preview (0.x): their API may change in any release, without the compatibility rules of +// the core library. Using them reports diagnostic TPLB001 until the consumer opts in (TPLB001). +[assembly: System.Diagnostics.CodeAnalysis.Experimental("TPLB001", UrlFormat = "https://github.com/TriasDev/templify/blob/main/docs/for-developers/template-builder.md#preview-status")] diff --git a/src/TriasDev.Templify.Builder.Testing/LibreOfficeConverter.cs b/src/TriasDev.Templify.Builder.Testing/LibreOfficeConverter.cs new file mode 100644 index 00000000..8bc2d35d --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/LibreOfficeConverter.cs @@ -0,0 +1,141 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Text; + +namespace TriasDev.Templify.Builder.Testing; + +/// +/// Converts documents with a local LibreOffice (headless soffice), for round-trip tests: a template or a +/// filled document must open and convert. Meant for local runs; check and skip otherwise. +/// +/// +/// LibreOffice is looked up in TEMPLIFY_SOFFICE (a path), then in the default install locations of macOS, +/// Windows and Linux. Every conversion uses its own temporary user profile, so conversions can run in parallel. +/// +public static class LibreOfficeConverter +{ + private static readonly Lazy _executable = new Lazy(FindExecutable); + + /// Gets the path of soffice, or null when LibreOffice was not found. + public static string? Executable => _executable.Value; + + /// Gets a value indicating whether LibreOffice was found. + public static bool IsAvailable => Executable != null; + + /// Converts a document and returns the converted file. + /// The document. + /// Its extension without the dot, e.g. docx. + /// The target of --convert-to, e.g. pdf or txt:Text (encoded):UTF8. + /// The converted file's extension, e.g. pdf. + /// How long to wait; default two minutes. + /// The converted file's bytes. + /// LibreOffice is not available, timed out or did not convert the document. + public static byte[] Convert(ReadOnlyMemory document, string inputExtension, string filter, string outputExtension, TimeSpan? timeout = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(inputExtension); + ArgumentException.ThrowIfNullOrWhiteSpace(filter); + ArgumentException.ThrowIfNullOrWhiteSpace(outputExtension); + string executable = Executable + ?? throw new InvalidOperationException("LibreOffice (soffice) was not found; set TEMPLIFY_SOFFICE to its path."); + + string directory = Path.Combine(Path.GetTempPath(), "templify-lo-" + Guid.NewGuid().ToString("N")); + string profile = Path.Combine(directory, "profile"); + Directory.CreateDirectory(profile); + try + { + string input = Path.Combine(directory, "document." + inputExtension.TrimStart('.')); + File.WriteAllBytes(input, document.ToArray()); + + ProcessStartInfo startInfo = new ProcessStartInfo(executable) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + WorkingDirectory = directory, + }; + startInfo.ArgumentList.Add("-env:UserInstallation=" + new Uri(profile).AbsoluteUri); + startInfo.ArgumentList.Add("--headless"); + startInfo.ArgumentList.Add("--norestore"); + startInfo.ArgumentList.Add("--convert-to"); + startInfo.ArgumentList.Add(filter); + startInfo.ArgumentList.Add("--outdir"); + startInfo.ArgumentList.Add(directory); + startInfo.ArgumentList.Add(input); + + using Process process = Process.Start(startInfo) ?? throw new InvalidOperationException("LibreOffice could not be started."); + Task stdout = process.StandardOutput.ReadToEndAsync(); + Task stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(timeout ?? TimeSpan.FromMinutes(2))) + { + process.Kill(entireProcessTree: true); + throw new InvalidOperationException("The LibreOffice conversion timed out."); + } + + string output = Path.Combine(directory, "document." + outputExtension.TrimStart('.')); + return File.Exists(output) + ? File.ReadAllBytes(output) + : throw new InvalidOperationException( + $"LibreOffice did not convert the document (exit code {process.ExitCode}). {stdout.Result} {stderr.Result}".Trim()); + } + finally + { + try + { + Directory.Delete(directory, recursive: true); + } + catch (IOException) + { + // A lingering LibreOffice process may still hold the profile; the temp directory is cleaned up later. + } + catch (UnauthorizedAccessException) + { + } + } + } + + /// Converts a built template to PDF. + /// The template. + /// The PDF bytes. + public static byte[] ToPdf(GeneratedTemplate template) + { + ArgumentNullException.ThrowIfNull(template); + return Convert(template.Content, template.FileExtension, "pdf", "pdf"); + } + + /// Converts a document to PDF. + /// The document. + /// Its extension, e.g. docx or odt. + /// The PDF bytes. + public static byte[] ToPdf(ReadOnlyMemory document, string extension) => Convert(document, extension, "pdf", "pdf"); + + /// Converts a document to plain text (UTF-8, line endings normalised to \n, no BOM). + /// The document. + /// Its extension, e.g. docx or odt. + /// The text. + public static string ToText(ReadOnlyMemory document, string extension) => + Encoding.UTF8.GetString(Convert(document, extension, "txt:Text (encoded):UTF8", "txt")) + .TrimStart('\uFEFF') + .Replace("\r\n", "\n", StringComparison.Ordinal); + + private static string? FindExecutable() + { + string? configured = Environment.GetEnvironmentVariable("TEMPLIFY_SOFFICE"); + if (!string.IsNullOrWhiteSpace(configured)) + { + return File.Exists(configured) ? configured : null; + } + + string[] candidates = + [ + "/Applications/LibreOffice.app/Contents/MacOS/soffice", + @"C:\Program Files\LibreOffice\program\soffice.exe", + "/usr/bin/soffice", + "/usr/bin/libreoffice", + "/usr/local/bin/soffice", + "/snap/bin/libreoffice", + ]; + return candidates.FirstOrDefault(File.Exists); + } +} diff --git a/src/TriasDev.Templify.Builder.Testing/PublicAPI.Shipped.txt b/src/TriasDev.Templify.Builder.Testing/PublicAPI.Shipped.txt new file mode 100644 index 00000000..7dc5c581 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/TriasDev.Templify.Builder.Testing/PublicAPI.Unshipped.txt b/src/TriasDev.Templify.Builder.Testing/PublicAPI.Unshipped.txt new file mode 100644 index 00000000..e252ffc6 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/PublicAPI.Unshipped.txt @@ -0,0 +1,84 @@ +#nullable enable +[TPLB001]override TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.Testing.TemplateVerificationReport.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.Testing.VerifiedTemplate.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.Testing.VerifiedTemplate.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.Testing.VerifiedTemplate.ToString() -> string! +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.Convert(System.ReadOnlyMemory document, string! inputExtension, string! filter, string! outputExtension, System.TimeSpan? timeout = null) -> byte[]! +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.Executable.get -> string? +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.IsAvailable.get -> bool +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.ToPdf(System.ReadOnlyMemory document, string! extension) -> byte[]! +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.ToPdf(TriasDev.Templify.Builder.GeneratedTemplate! template) -> byte[]! +[TPLB001]static TriasDev.Templify.Builder.Testing.LibreOfficeConverter.ToText(System.ReadOnlyMemory document, string! extension) -> string! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateSnapshot.Create(TriasDev.Templify.Builder.GeneratedTemplate! template) -> string! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateSnapshot.Create(TriasDev.Templify.Core.TemplateFormat format, System.ReadOnlyMemory package) -> string! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.operator !=(TriasDev.Templify.Builder.Testing.TemplateVerificationFailure? left, TriasDev.Templify.Builder.Testing.TemplateVerificationFailure? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.operator ==(TriasDev.Templify.Builder.Testing.TemplateVerificationFailure? left, TriasDev.Templify.Builder.Testing.TemplateVerificationFailure? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerifier.CheckFill(TriasDev.Templify.Builder.GeneratedTemplate! template, string! json, System.Globalization.CultureInfo? culture = null) -> System.Collections.Generic.IReadOnlyList! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerifier.CheckPackage(TriasDev.Templify.Core.TemplateFormat format, System.ReadOnlyMemory package) -> System.Collections.Generic.IReadOnlyList! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerifier.CheckTemplate(TriasDev.Templify.Builder.GeneratedTemplate! template) -> System.Collections.Generic.IReadOnlyList! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerifier.Verify(System.Func! definitionFactory, TriasDev.Templify.Builder.Testing.TemplateVerificationOptions? options = null) -> TriasDev.Templify.Builder.Testing.TemplateVerificationReport! +[TPLB001]static TriasDev.Templify.Builder.Testing.TemplateVerifier.VerifyAll(System.Func! definitionFactory, TriasDev.Templify.Builder.Testing.TemplateVerificationOptions? options = null) -> TriasDev.Templify.Builder.Testing.TemplateVerificationReport! +[TPLB001]static TriasDev.Templify.Builder.Testing.VerifiedTemplate.operator !=(TriasDev.Templify.Builder.Testing.VerifiedTemplate? left, TriasDev.Templify.Builder.Testing.VerifiedTemplate? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Testing.VerifiedTemplate.operator ==(TriasDev.Templify.Builder.Testing.VerifiedTemplate? left, TriasDev.Templify.Builder.Testing.VerifiedTemplate? right) -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.LibreOfficeConverter +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateSnapshot +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationException +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationException.Report.get -> TriasDev.Templify.Builder.Testing.TemplateVerificationReport! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationException.TemplateVerificationException(TriasDev.Templify.Builder.Testing.TemplateVerificationReport! report) -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.$() -> TriasDev.Templify.Builder.Testing.TemplateVerificationFailure! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Check.get -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Check.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Deconstruct(out System.Globalization.CultureInfo? Language, out TriasDev.Templify.Core.TemplateFormat? Format, out TriasDev.Templify.Builder.Testing.VerificationCheck Check, out string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Equals(TriasDev.Templify.Builder.Testing.TemplateVerificationFailure? other) -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Format.get -> TriasDev.Templify.Core.TemplateFormat? +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Format.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Language.get -> System.Globalization.CultureInfo? +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Language.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Message.get -> string! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.Message.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationFailure.TemplateVerificationFailure(System.Globalization.CultureInfo? Language, TriasDev.Templify.Core.TemplateFormat? Format, TriasDev.Templify.Builder.Testing.VerificationCheck Check, string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.DeterminismCultures.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.DeterminismCultures.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.FailOnBuildWarnings.get -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.FailOnBuildWarnings.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Formats.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Formats.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Languages.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Languages.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.RequireEqualContracts.get -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.RequireEqualContracts.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.SampleData.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.SampleData.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.TemplateVerificationOptions() -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Texts.get -> System.Func? +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationOptions.Texts.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationReport +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationReport.Failures.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationReport.IsSuccess.get -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerificationReport.Templates.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.Testing.TemplateVerifier +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Build = 0 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.BuildWarning = 7 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Contract = 2 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.ContractParity = 6 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Determinism = 5 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Fill = 3 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Package = 4 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerificationCheck.Structure = 1 -> TriasDev.Templify.Builder.Testing.VerificationCheck +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.$() -> TriasDev.Templify.Builder.Testing.VerifiedTemplate! +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Deconstruct(out System.Globalization.CultureInfo! Language, out TriasDev.Templify.Core.TemplateFormat Format, out TriasDev.Templify.Builder.GeneratedTemplate! Template) -> void +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Equals(TriasDev.Templify.Builder.Testing.VerifiedTemplate? other) -> bool +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Format.get -> TriasDev.Templify.Core.TemplateFormat +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Format.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Language.get -> System.Globalization.CultureInfo! +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Language.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Template.get -> TriasDev.Templify.Builder.GeneratedTemplate! +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.Template.init -> void +[TPLB001]TriasDev.Templify.Builder.Testing.VerifiedTemplate.VerifiedTemplate(System.Globalization.CultureInfo! Language, TriasDev.Templify.Core.TemplateFormat Format, TriasDev.Templify.Builder.GeneratedTemplate! Template) -> void diff --git a/src/TriasDev.Templify.Builder.Testing/README.md b/src/TriasDev.Templify.Builder.Testing/README.md new file mode 100644 index 00000000..13c87361 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/README.md @@ -0,0 +1,51 @@ +# TriasDev.Templify.Builder.Testing + +Test kit for [TriasDev.Templify.Builder](https://www.nuget.org/packages/TriasDev.Templify.Builder). The builder +generates templates at runtime, so your CI is where your template definitions get verified. The kit does not depend +on a test framework: call it from xUnit, NUnit or MSTest. + +> **Preview (0.x), experimental**, like the builder: opt in with `$(NoWarn);TPLB001`. + +```csharp +[Fact] +public void InvoiceTemplate_IsValid() => TemplateVerifier.VerifyAll( + () => new InvoiceTemplate(theme), + new TemplateVerificationOptions + { + Languages = [CultureInfo.GetCultureInfo("de-DE"), CultureInfo.GetCultureInfo("en-US")], + Texts = language => catalogs[language.Name], + SampleData = [File.ReadAllText("invoice-sample.json")], + }); +``` + +`VerifyAll` builds the definition for every language and format and throws `TemplateVerificationException`, listing +every failure, when one of these checks fails: + +- the definition builds; +- `ValidateTemplate` reports no errors; +- the data contract is complete: filling with the contract's witness raises no missing variable and no warning; +- every sample data document fills without missing variables and without warnings; +- the DOCX passes the OOXML schema validation, the ODT the package checks (template and filled documents); +- a second build gives the same bytes, also under the current cultures tr-TR and ar-SA; +- all languages and formats have the same data contract. + +`Verify` returns the same `TemplateVerificationReport` without throwing. `CheckTemplate`, `CheckFill` and +`CheckPackage` run single checks. + +## Snapshots + +`TemplateSnapshot.Create(template)` returns a canonical text dump (paragraphs with their styles, markers, tables, +headers and footers) for golden tests: + +```text +== body +Heading1 | Order {{order.number}} +TemplifyMarker | {{#if order.isPaid}} +Normal | Paid. +TemplifyMarker | {{/if}} +``` + +## LibreOffice + +`LibreOfficeConverter` converts templates and filled documents with a local LibreOffice (`TEMPLIFY_SOFFICE` or the +default install path). Check `LibreOfficeConverter.IsAvailable` and skip the test otherwise. diff --git a/src/TriasDev.Templify.Builder.Testing/TemplateSnapshot.cs b/src/TriasDev.Templify.Builder.Testing/TemplateSnapshot.cs new file mode 100644 index 00000000..d87f8db7 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/TemplateSnapshot.cs @@ -0,0 +1,422 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Testing; + +/// +/// A canonical text dump of a document's content for snapshot (golden) tests: one line per paragraph with its style, +/// tables as indented rows and cells, then the headers and footers. Works for templates and filled documents. +/// +/// +/// The notation is the same for both formats: +/// +/// == body +/// Heading1 | Order {{order.number}} +/// TemplifyMarker | {{#if order.isPaid}} +/// Normal | Total:→{{order.total:currency}} +/// table +/// row +/// cell +/// Normal | Owner +/// ListBullet [list 1] | first item +/// == header +/// Normal | {PAGE} / {NUMPAGES} +/// +/// +/// Text: a tab is →, a line break ↵, an image [image], a field {NAME} (its first word; +/// {TOC} for a table of contents). A paragraph without a style, and ODT's "Standard", is Normal; an ODT +/// automatic style is shown as its parent. Layout-only paragraphs one format needs stay visible (DOCX puts a paragraph +/// after a table that ends a part and between tables that touch), so compare snapshots per format. +/// +/// +public static class TemplateSnapshot +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + private static readonly XNamespace _rel = "http://schemas.openxmlformats.org/package/2006/relationships"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"; + + /// Dumps a built template. + /// The template. + /// The dump, lines separated by \n. + public static string Create(GeneratedTemplate template) + { + ArgumentNullException.ThrowIfNull(template); + return Create(template.Format, template.Content); + } + + /// Dumps a document package (a template or a filled document). + /// The format. + /// The package bytes. + /// The dump, lines separated by \n. + public static string Create(TemplateFormat format, ReadOnlyMemory package) + { + using MemoryStream stream = new MemoryStream(package.ToArray(), writable: false); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + List lines = format switch + { + TemplateFormat.Docx => new DocxDump(archive).Dump(), + TemplateFormat.Odt => new OdtDump(archive).Dump(), + _ => throw new ArgumentOutOfRangeException(nameof(format), format, "Only DOCX and ODT can be dumped."), + }; + return string.Join("\n", lines); + } + + private static XDocument? Load(ZipArchive archive, string name) + { + ZipArchiveEntry? entry = archive.GetEntry(name); + if (entry is null) + { + return null; + } + + using Stream stream = entry.Open(); + return XDocument.Load(stream); + } + + // An empty paragraph ends with "|", not "| ": editors strip trailing spaces from golden files. + private static string Line(int depth, string style, string? list, string text) => + new string(' ', depth * 2) + style + (list is null ? string.Empty : " [list " + list + "]") + (text.Length == 0 ? " |" : " | " + text); + + private sealed class DocxDump(ZipArchive archive) + { + private readonly List _lines = new List(); + + public List Dump() + { + XDocument document = Load(archive, "word/document.xml") ?? throw new InvalidDataException("The package has no word/document.xml."); + XElement body = document.Root?.Element(_w + "body") ?? throw new InvalidDataException("word/document.xml has no body."); + _lines.Add("== body"); + Blocks(body, 0); + + Dictionary targets = (Load(archive, "word/_rels/document.xml.rels")?.Root?.Elements(_rel + "Relationship") ?? []) + .ToDictionary(r => (string)r.Attribute("Id")!, r => (string)r.Attribute("Target")!, StringComparer.Ordinal); + XElement? section = body.Element(_w + "sectPr"); + foreach ((string kind, string type, string title) in new[] + { + ("header", "default", "header"), ("header", "first", "header first"), + ("footer", "default", "footer"), ("footer", "first", "footer first"), + }) + { + XElement? reference = section?.Elements(_w + kind + "Reference").FirstOrDefault(e => (string?)e.Attribute(_w + "type") == type); + if (reference?.Attribute(_r + "id") is { } id && targets.TryGetValue(id.Value, out string? target)) + { + XDocument? part = Load(archive, "word/" + target.TrimStart('/').Replace("word/", string.Empty, StringComparison.Ordinal)); + if (part?.Root is { } root) + { + _lines.Add("== " + title); + Blocks(root, 0); + } + } + } + + return _lines; + } + + private void Blocks(XElement container, int depth) + { + foreach (XElement element in container.Elements()) + { + if (element.Name == _w + "p") + { + Paragraph(element, depth); + } + else if (element.Name == _w + "tbl") + { + _lines.Add(new string(' ', depth * 2) + "table"); + foreach (XElement row in element.Elements(_w + "tr")) + { + _lines.Add(new string(' ', (depth + 1) * 2) + "row"); + foreach (XElement cell in row.Elements(_w + "tc")) + { + _lines.Add(new string(' ', (depth + 2) * 2) + "cell"); + Blocks(cell, depth + 3); + } + } + } + else if (element.Name == _w + "sdt") + { + if (element.Element(_w + "sdtContent") is { } content) + { + Blocks(content, depth); + } + } + else if (element.Name != _w + "sectPr" && element.Name != _w + "tcPr" && element.Name.LocalName != "bookmarkStart" && element.Name.LocalName != "bookmarkEnd") + { + _lines.Add(new string(' ', depth * 2) + "<" + element.Name.LocalName + ">"); + } + } + } + + private void Paragraph(XElement paragraph, int depth) + { + XElement? properties = paragraph.Element(_w + "pPr"); + string style = (string?)properties?.Element(_w + "pStyle")?.Attribute(_w + "val") ?? "Normal"; + string? list = null; + if (properties?.Element(_w + "numPr") is { } numbering) + { + int level = (int?)numbering.Element(_w + "ilvl")?.Attribute(_w + "val") ?? 0; + list = (level + 1).ToString(CultureInfo.InvariantCulture); + } + + StringBuilder text = new StringBuilder(); + bool inFieldResult = false; + bool inFieldCode = false; + StringBuilder code = new StringBuilder(); + foreach (XElement element in paragraph.Descendants()) + { + if (element.Name == _w + "fldChar") + { + switch ((string?)element.Attribute(_w + "fldCharType")) + { + case "begin": + inFieldCode = true; + code.Clear(); + break; + case "separate": + text.Append(FieldName(code.ToString())); + inFieldCode = false; + inFieldResult = true; + break; + case "end": + if (inFieldCode) + { + text.Append(FieldName(code.ToString())); + } + + inFieldCode = false; + inFieldResult = false; + break; + } + + continue; + } + + if (inFieldCode) + { + if (element.Name == _w + "instrText") + { + code.Append(element.Value); + } + + continue; + } + + if (inFieldResult || element.Ancestors(_w + "fldSimple").Any()) + { + continue; + } + + if (element.Name == _w + "fldSimple") + { + text.Append(FieldName((string?)element.Attribute(_w + "instr") ?? string.Empty)); + } + else if (element.Name == _w + "t") + { + text.Append(element.Value); + } + else if (element.Name == _w + "tab" && element.Parent?.Name == _w + "r") + { + text.Append('→'); + } + else if (element.Name == _w + "br") + { + string? type = (string?)element.Attribute(_w + "type"); + if (type is null or "textWrapping") + { + text.Append('↵'); + } + } + else if (element.Name == _w + "drawing") + { + text.Append("[image]"); + } + } + + _lines.Add(Line(depth, style, list, text.ToString())); + } + + private static string FieldName(string instruction) + { + string name = instruction.Trim().Split(' ', 2)[0]; + return "{" + name.ToUpperInvariant() + "}"; + } + } + + private sealed class OdtDump(ZipArchive archive) + { + private readonly List _lines = new List(); + private readonly Dictionary _automaticParents = new Dictionary(StringComparer.Ordinal); + + public List Dump() + { + XDocument content = Load(archive, "content.xml") ?? throw new InvalidDataException("The package has no content.xml."); + XDocument? styles = Load(archive, "styles.xml"); + foreach (XDocument document in new[] { content, styles }.OfType()) + { + foreach (XElement style in document.Root?.Element(_office + "automatic-styles")?.Elements(_style + "style") ?? []) + { + _automaticParents[(string)style.Attribute(_style + "name")!] = (string?)style.Attribute(_style + "parent-style-name") ?? "Standard"; + } + } + + XElement text = content.Root?.Element(_office + "body")?.Element(_office + "text") ?? throw new InvalidDataException("content.xml has no office:text."); + _lines.Add("== body"); + Blocks(text, 0, 0); + + XElement? master = styles?.Root?.Element(_office + "master-styles")?.Elements(_style + "master-page").FirstOrDefault(); + foreach ((string name, string title) in new[] { ("header", "header"), ("header-first", "header first"), ("footer", "footer"), ("footer-first", "footer first") }) + { + if (master?.Element(_style + name) is { } region) + { + _lines.Add("== " + title); + Blocks(region, 0, 0); + } + } + + return _lines; + } + + private void Blocks(XElement container, int depth, int listLevel) + { + foreach (XElement element in container.Elements()) + { + if (element.Name == _text + "p" || element.Name == _text + "h") + { + Paragraph(element, depth, listLevel); + } + else if (element.Name == _text + "list") + { + foreach (XElement item in element.Elements().Where(e => e.Name == _text + "list-item" || e.Name == _text + "list-header")) + { + Blocks(item, depth, listLevel + 1); + } + } + else if (element.Name == _table + "table") + { + _lines.Add(new string(' ', depth * 2) + "table"); + foreach (XElement row in Rows(element)) + { + _lines.Add(new string(' ', (depth + 1) * 2) + "row"); + foreach (XElement cell in row.Elements(_table + "table-cell")) + { + _lines.Add(new string(' ', (depth + 2) * 2) + "cell"); + Blocks(cell, depth + 3, 0); + } + } + } + else if (element.Name == _text + "table-of-content") + { + _lines.Add(Line(depth, "Normal", null, "{TOC}")); + } + else if (element.Name == _text + "section") + { + Blocks(element, depth, listLevel); + } + else if (element.Name.Namespace != _text || element.Name.LocalName is not ("sequence-decls" or "variable-decls" or "user-field-decls" or "soft-page-break")) + { + if (element.Name != _office + "forms" && element.Name != _table + "table-column" && element.Name != _table + "table-columns") + { + _lines.Add(new string(' ', depth * 2) + "<" + element.Name.LocalName + ">"); + } + } + } + } + + private static IEnumerable Rows(XElement table) + { + foreach (XElement child in table.Elements()) + { + if (child.Name == _table + "table-row") + { + yield return child; + } + else if (child.Name.Namespace == _table && child.Name.LocalName is "table-header-rows" or "table-rows" or "table-row-group") + { + foreach (XElement row in Rows(child)) + { + yield return row; + } + } + } + } + + private void Paragraph(XElement paragraph, int depth, int listLevel) + { + string style = (string?)paragraph.Attribute(_text + "style-name") ?? "Standard"; + if (_automaticParents.TryGetValue(style, out string? parent)) + { + style = parent; + } + + if (style == "Standard") + { + style = "Normal"; + } + + StringBuilder text = new StringBuilder(); + Inline(paragraph, text); + _lines.Add(Line(depth, style, listLevel > 0 ? listLevel.ToString(CultureInfo.InvariantCulture) : null, text.ToString())); + } + + private static void Inline(XElement element, StringBuilder text) + { + foreach (XNode node in element.Nodes()) + { + if (node is XText t) + { + text.Append(t.Value); + continue; + } + + if (node is not XElement child) + { + continue; + } + + if (child.Name == _text + "s") + { + text.Append(' ', (int?)child.Attribute(_text + "c") ?? 1); + } + else if (child.Name == _text + "tab") + { + text.Append('→'); + } + else if (child.Name == _text + "line-break") + { + text.Append('↵'); + } + else if (child.Name == _text + "span" || child.Name == _text + "a") + { + Inline(child, text); + } + else if (child.Name == _draw + "frame") + { + text.Append("[image]"); + } + else if (child.Name == _text + "page-number") + { + text.Append("{PAGE}"); + } + else if (child.Name == _text + "page-count") + { + text.Append("{NUMPAGES}"); + } + else if (child.Name.Namespace == _text && child.Name.LocalName is not ("bookmark" or "bookmark-start" or "bookmark-end" or "soft-page-break")) + { + text.Append('{').Append(child.Name.LocalName.ToUpperInvariant()).Append('}'); + } + } + } + } +} diff --git a/src/TriasDev.Templify.Builder.Testing/TemplateVerificationOptions.cs b/src/TriasDev.Templify.Builder.Testing/TemplateVerificationOptions.cs new file mode 100644 index 00000000..c1f18e39 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/TemplateVerificationOptions.cs @@ -0,0 +1,42 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Testing; + +/// What builds and checks. +public sealed class TemplateVerificationOptions +{ + /// Gets the languages to build in. Default: en-US. + public IReadOnlyList Languages { get; init; } = [CultureInfo.GetCultureInfo("en-US")]; + + /// Gets the formats to build. Default: DOCX and ODT. + public IReadOnlyList Formats { get; init; } = [TemplateFormat.Docx, TemplateFormat.Odt]; + + /// Gets the text catalog for a language, or null for . + public Func? Texts { get; init; } + + /// + /// Gets sample data documents (JSON). Every template is filled with each of them; the fill must succeed without + /// missing variables and without warnings. + /// + public IReadOnlyList SampleData { get; init; } = []; + + /// + /// Gets a value indicating whether all languages and formats must have the same data contract (the language parity + /// check). Default: true. + /// + public bool RequireEqualContracts { get; init; } = true; + + /// Gets a value indicating whether build warnings (such as TB9001) fail the verification. Default: false. + public bool FailOnBuildWarnings { get; init; } + + /// + /// Gets the current cultures under which a second build must give the same bytes. Default: tr-TR and ar-SA, the + /// cultures that break culture-sensitive formatting and casing. + /// + public IReadOnlyList DeterminismCultures { get; init; } = + [CultureInfo.GetCultureInfo("tr-TR"), CultureInfo.GetCultureInfo("ar-SA")]; +} diff --git a/src/TriasDev.Templify.Builder.Testing/TemplateVerificationReport.cs b/src/TriasDev.Templify.Builder.Testing/TemplateVerificationReport.cs new file mode 100644 index 00000000..8745af84 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/TemplateVerificationReport.cs @@ -0,0 +1,109 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Testing; + +/// The check a verification failure belongs to. +public enum VerificationCheck +{ + /// The definition did not build. + Build, + + /// ValidateTemplate reported errors. + Structure, + + /// The template reads data its contract does not declare, or the witness fill failed. + Contract, + + /// A fill with sample data failed or warned. + Fill, + + /// The DOCX schema validation or the ODT package check failed (template or filled document). + Package, + + /// A second build gave different bytes. + Determinism, + + /// Languages or formats have different data contracts. + ContractParity, + + /// The build reported a warning, and is set. + BuildWarning, +} + +/// One failed check. +/// The language of the build, or null for a check across builds. +/// The format of the build, or null for a check across builds. +/// The check that failed. +/// What failed. +public sealed record TemplateVerificationFailure(CultureInfo? Language, TemplateFormat? Format, VerificationCheck Check, string Message) +{ + /// + public override string ToString() + { + string target = Language is null ? "all" : Language.Name + "/" + Format?.ToString().ToLowerInvariant(); + return $"[{target}] {Check}: {Message}"; + } +} + +/// A template the verification built. +/// The language it was built in. +/// Its format. +/// The built template. +public sealed record VerifiedTemplate(CultureInfo Language, TemplateFormat Format, GeneratedTemplate Template); + +/// The result of . +public sealed class TemplateVerificationReport +{ + internal TemplateVerificationReport(IReadOnlyList templates, IReadOnlyList failures) + { + Templates = templates; + Failures = failures; + } + + /// Gets the templates that built, one per language and format. + public IReadOnlyList Templates { get; } + + /// Gets the failed checks; empty when everything passed. + public IReadOnlyList Failures { get; } + + /// Gets a value indicating whether every check passed. + public bool IsSuccess => Failures.Count == 0; + + /// Returns the failures, one per line, or a success line. + public override string ToString() + { + if (IsSuccess) + { + return $"Template verification passed ({Templates.Count} templates)."; + } + + StringBuilder text = new StringBuilder(); + text.Append(CultureInfo.InvariantCulture, $"Template verification failed ({Failures.Count} failures):"); + foreach (TemplateVerificationFailure failure in Failures) + { + text.AppendLine().Append(" ").Append(failure); + } + + return text.ToString(); + } +} + +/// Thrown by when a check fails; the message lists every failure. +public sealed class TemplateVerificationException : Exception +{ + /// Initializes a new instance of the class. + /// The failed report. + public TemplateVerificationException(TemplateVerificationReport report) + : base((report ?? throw new ArgumentNullException(nameof(report))).ToString()) + { + Report = report; + } + + /// Gets the report. + public TemplateVerificationReport Report { get; } +} diff --git a/src/TriasDev.Templify.Builder.Testing/TemplateVerifier.cs b/src/TriasDev.Templify.Builder.Testing/TemplateVerifier.cs new file mode 100644 index 00000000..748e4a89 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/TemplateVerifier.cs @@ -0,0 +1,398 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Validation; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Testing; + +/// +/// Verifies template definitions the way the builder's own tests do. A consumer builds at runtime, so its CI is where +/// its definitions get verified: call from any test framework. +/// +/// +/// +/// [Fact] +/// public void InvoiceTemplate_IsValid() => TemplateVerifier.VerifyAll( +/// () => new InvoiceTemplate(theme), +/// new TemplateVerificationOptions +/// { +/// Languages = [CultureInfo.GetCultureInfo("de-DE"), CultureInfo.GetCultureInfo("en-US")], +/// Texts = language => catalogs[language.Name], +/// SampleData = [File.ReadAllText("invoice-sample.json")], +/// }); +/// +/// +public static class TemplateVerifier +{ + private const string OdtMediaType = "application/vnd.oasis.opendocument.text"; + private static readonly XNamespace _manifest = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; + + /// + /// Builds the definition for every language and format and runs every check; throws when one fails. + /// + /// Creates the definition; called once per build, so state cannot leak between builds. + /// The languages, formats, texts and sample data; null for the defaults. + /// The successful report, with the built templates. + /// A check failed; the message lists every failure. + public static TemplateVerificationReport VerifyAll(Func definitionFactory, TemplateVerificationOptions? options = null) + { + TemplateVerificationReport report = Verify(definitionFactory, options); + return report.IsSuccess ? report : throw new TemplateVerificationException(report); + } + + /// + /// Builds the definition for every language and format and runs every check, collecting the failures: + /// the build; ValidateTemplate (no errors); the contract (filling with the contract's witness reports no + /// missing variable and no warning); fills with the sample data; the DOCX schema or ODT package of the template + /// and of every filled document; byte determinism (also under ); + /// equal contracts across languages and formats. + /// + /// Creates the definition; called once per build. + /// The languages, formats, texts and sample data; null for the defaults. + /// The report. + public static TemplateVerificationReport Verify(Func definitionFactory, TemplateVerificationOptions? options = null) + { + ArgumentNullException.ThrowIfNull(definitionFactory); + options ??= new TemplateVerificationOptions(); + if (options.Languages.Count == 0 || options.Formats.Count == 0) + { + throw new ArgumentException("At least one language and one format are needed.", nameof(options)); + } + + List templates = new List(); + List failures = new List(); + + foreach (CultureInfo language in options.Languages) + { + foreach (TemplateFormat format in options.Formats) + { + void Fail(VerificationCheck check, string message) => + failures.Add(new TemplateVerificationFailure(language, format, check, message)); + + TemplateBuildOptions buildOptions = new TemplateBuildOptions + { + Format = format, + Language = language, + Texts = options.Texts?.Invoke(language) ?? TextCatalog.Empty, + }; + + GeneratedTemplate template; + try + { + template = TemplateBuilder.Build(definitionFactory(), buildOptions); + } + catch (TemplateBuildException exception) + { + foreach (BuildDiagnostic error in exception.Errors) + { + Fail(VerificationCheck.Build, error.Code + " " + error.Message); + } + + continue; + } + + templates.Add(new VerifiedTemplate(language, format, template)); + if (options.FailOnBuildWarnings) + { + foreach (BuildDiagnostic warning in template.Warnings) + { + Fail(VerificationCheck.BuildWarning, warning.Code + " " + warning.Message); + } + } + + foreach ((VerificationCheck check, string message) in CheckTemplateCore(template)) + { + Fail(check, message); + } + + for (int i = 0; i < options.SampleData.Count; i++) + { + foreach (string problem in CheckFill(template, options.SampleData[i], language)) + { + Fail(VerificationCheck.Fill, $"sample data #{(i + 1).ToString(CultureInfo.InvariantCulture)}: {problem}"); + } + } + + foreach (CultureInfo culture in options.DeterminismCultures) + { + string? problem = CheckDeterminism(definitionFactory, buildOptions, template, culture); + if (problem != null) + { + Fail(VerificationCheck.Determinism, problem); + } + } + } + } + + if (options.RequireEqualContracts && templates.Count > 1) + { + VerifiedTemplate first = templates[0]; + foreach (VerifiedTemplate other in templates.Skip(1).Where(t => t.Template.Contract.Hash != first.Template.Contract.Hash)) + { + failures.Add(new TemplateVerificationFailure( + null, + null, + VerificationCheck.ContractParity, + $"{Describe(other)} reads different data than {Describe(first)}: {ContractDifference(first.Template.Contract, other.Template.Contract)}")); + } + } + + return new TemplateVerificationReport(templates, failures); + } + + /// + /// Checks one built template: ValidateTemplate reports no errors, the contract's witness fills it without + /// missing variables or warnings, and the template and the filled witness pass the package check. + /// + /// The template. + /// The problems; empty when the template is fine. + public static IReadOnlyList CheckTemplate(GeneratedTemplate template) + { + ArgumentNullException.ThrowIfNull(template); + return CheckTemplateCore(template).Select(p => p.Check + ": " + p.Message).ToList(); + } + + /// + /// Fills a template with JSON data, failing on missing variables, and checks the result: success, no warnings, + /// a valid package. + /// + /// The template. + /// The data. + /// The fill culture (numbers, dates); null for the invariant culture. + /// The problems; empty when the fill is fine. + public static IReadOnlyList CheckFill(GeneratedTemplate template, string json, CultureInfo? culture = null) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(json); + return Fill(template, culture, (processor, input, output) => processor.ProcessTemplate(input, output, json)); + } + + /// + /// Checks a document package: DOCX against the OOXML schema (OpenXmlValidator); ODT for its package + /// structure (mimetype first, stored, without an extra field; manifest entries present; well-formed XML). + /// Works for templates and for filled documents. + /// + /// The format. + /// The package bytes. + /// The problems; empty when the package is fine. + public static IReadOnlyList CheckPackage(TemplateFormat format, ReadOnlyMemory package) + { + try + { + return format switch + { + TemplateFormat.Docx => CheckDocx(package), + TemplateFormat.Odt => CheckOdt(package.Span), + _ => throw new ArgumentOutOfRangeException(nameof(format), format, "Only DOCX and ODT packages can be checked."), + }; + } + catch (Exception exception) when (exception is InvalidDataException or XmlException or OpenXmlPackageException or IOException or FormatException) + { + return [$"The package cannot be read: {exception.Message}"]; + } + } + + private static List<(VerificationCheck Check, string Message)> CheckTemplateCore(GeneratedTemplate template) + { + List<(VerificationCheck, string)> problems = new List<(VerificationCheck, string)>(); + TemplateProcessor processor = new TemplateProcessor(); + + using (Stream stream = template.OpenRead()) + { + ValidationResult validation = processor.ValidateTemplate(stream); + problems.AddRange(validation.Errors.Select(e => (VerificationCheck.Structure, $"{e.Type}: {e.Message}"))); + } + + IReadOnlyDictionary witness = template.Contract.CreateWitness(); + using (Stream stream = template.OpenRead()) + { + ValidationResult validation = processor.ValidateTemplate(stream, witness); + problems.AddRange(validation.MissingVariables.Select(v => (VerificationCheck.Contract, $"'{v}' is read but not in the data contract."))); + } + + problems.AddRange(Fill(template, null, (p, input, output) => p.ProcessTemplate(input, output, witness)) + .Select(p => (VerificationCheck.Contract, "witness fill: " + p))); + problems.AddRange(CheckPackage(template.Format, template.Content).Select(p => (VerificationCheck.Package, "template: " + p))); + return problems; + } + + private static List Fill(GeneratedTemplate template, CultureInfo? culture, Func fill) + { + TemplateProcessor processor = new TemplateProcessor(new PlaceholderReplacementOptions + { + MissingVariableBehavior = MissingVariableBehavior.ThrowException, + Culture = culture ?? CultureInfo.InvariantCulture, + }); + + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + ProcessingResult result; + try + { + result = fill(processor, input, output); + } + catch (InvalidOperationException exception) + { + // MissingVariableBehavior.ThrowException. + return [exception.Message]; + } + + if (!result.IsSuccess) + { + return [result.ErrorMessage ?? "Processing failed."]; + } + + List problems = result.Warnings.Select(w => $"warning {w.Type}: {w.Message}").ToList(); + problems.AddRange(CheckPackage(template.Format, output.ToArray()).Select(p => "filled document: " + p)); + return problems; + } + + private static string? CheckDeterminism(Func factory, TemplateBuildOptions options, GeneratedTemplate first, CultureInfo culture) + { + CultureInfo previous = CultureInfo.CurrentCulture; + CultureInfo previousUi = CultureInfo.CurrentUICulture; + try + { + CultureInfo.CurrentCulture = culture; + CultureInfo.CurrentUICulture = culture; + GeneratedTemplate again = TemplateBuilder.Build(factory(), options); + return again.ContentHash == first.ContentHash + ? null + : $"a second build under the current culture {culture.Name} gave different bytes{FirstDifference(first.Content.Span, again.Content.Span)}."; + } + catch (TemplateBuildException exception) + { + return $"a second build under the current culture {culture.Name} failed: {exception.Message}"; + } + finally + { + CultureInfo.CurrentCulture = previous; + CultureInfo.CurrentUICulture = previousUi; + } + } + + private static string FirstDifference(ReadOnlySpan left, ReadOnlySpan right) + { + int length = Math.Min(left.Length, right.Length); + int index = left[..length].CommonPrefixLength(right[..length]); + return $" (first difference at byte {index.ToString(CultureInfo.InvariantCulture)}; a definition must not depend on the current culture, the clock or random values)"; + } + + private static string Describe(VerifiedTemplate template) => + template.Language.Name + "/" + template.Format.ToString().ToLowerInvariant(); + + private static string ContractDifference(DataContract left, DataContract right) + { + HashSet a = left.Entries.ToHashSet(); + HashSet b = right.Entries.ToHashSet(); + IEnumerable missing = a.Except(b).Select(e => "-" + e.Path + " (" + e.Usage + ")"); + IEnumerable extra = b.Except(a).Select(e => "+" + e.Path + " (" + e.Usage + ")"); + return string.Join(", ", missing.Concat(extra)); + } + + private static List CheckDocx(ReadOnlyMemory package) + { + using MemoryStream stream = new MemoryStream(package.ToArray(), writable: false); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + return new OpenXmlValidator() + .Validate(document) + .Select(e => $"{e.Part?.Uri} {e.Path?.XPath}: {e.Description}") + .ToList(); + } + + private static List CheckOdt(ReadOnlySpan package) + { + List problems = new List(); + + // The mimetype entry: first, stored, no data descriptor, no extra field, the ODT media type (ODF 1.3 part 2, 3.3). + const int header = 30; + if (package.Length < header + 8 + OdtMediaType.Length || BinaryPrimitives.ReadUInt32LittleEndian(package) != 0x04034b50u) + { + return ["The package is not a ZIP file."]; + } + + if ((BinaryPrimitives.ReadUInt16LittleEndian(package[6..]) & 0x08) != 0) + { + problems.Add("The mimetype entry has a data descriptor."); + } + + if (BinaryPrimitives.ReadUInt16LittleEndian(package[8..]) != 0) + { + problems.Add("The mimetype entry is compressed; it must be stored."); + } + + ushort nameLength = BinaryPrimitives.ReadUInt16LittleEndian(package[26..]); + ushort extraLength = BinaryPrimitives.ReadUInt16LittleEndian(package[28..]); + if (nameLength != 8 || Encoding.ASCII.GetString(package.Slice(header, 8)) != "mimetype") + { + problems.Add("The first entry is not mimetype."); + return problems; + } + + if (extraLength != 0) + { + problems.Add("The mimetype entry has an extra field."); + } + + if (Encoding.ASCII.GetString(package.Slice(header + 8 + extraLength, OdtMediaType.Length)) != OdtMediaType) + { + problems.Add($"The mimetype is not {OdtMediaType}."); + } + + using MemoryStream stream = new MemoryStream(package.ToArray(), writable: false); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + HashSet names = archive.Entries.Select(e => e.FullName).ToHashSet(StringComparer.Ordinal); + ZipArchiveEntry? manifestEntry = archive.GetEntry("META-INF/manifest.xml"); + if (manifestEntry is null) + { + problems.Add("META-INF/manifest.xml is missing."); + } + else + { + XDocument manifest; + using (Stream manifestStream = manifestEntry.Open()) + { + manifest = XDocument.Load(manifestStream); + } + + foreach (XElement entry in manifest.Root?.Elements(_manifest + "file-entry") ?? []) + { + string path = (string?)entry.Attribute(_manifest + "full-path") ?? string.Empty; + if (path == "/") + { + if ((string?)entry.Attribute(_manifest + "media-type") != OdtMediaType) + { + problems.Add("The manifest's root entry does not have the ODT media type."); + } + } + else if (!path.EndsWith('/') && !names.Contains(path)) + { + problems.Add($"The manifest lists '{path}', which is not in the package."); + } + } + } + + foreach (ZipArchiveEntry entry in archive.Entries.Where(e => e.FullName.EndsWith(".xml", StringComparison.Ordinal))) + { + try + { + using Stream entryStream = entry.Open(); + XDocument.Load(entryStream); + } + catch (XmlException exception) + { + problems.Add($"{entry.FullName} is not well-formed XML: {exception.Message}"); + } + } + + return problems; + } +} diff --git a/src/TriasDev.Templify.Builder.Testing/TriasDev.Templify.Builder.Testing.csproj b/src/TriasDev.Templify.Builder.Testing/TriasDev.Templify.Builder.Testing.csproj new file mode 100644 index 00000000..68827ab9 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/TriasDev.Templify.Builder.Testing.csproj @@ -0,0 +1,30 @@ + + + + + $(NoWarn);TPLB001 + + net11.0;net10.0 + + + TriasDev.Templify.Builder.Testing + $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)../TriasDev.Templify.Builder/version.txt').Trim()) + Test kit for TriasDev.Templify.Builder: verify template definitions in your CI (build, validate, fill with sample data and the contract's witness, DOCX schema and ODT package checks, byte determinism, contract parity across languages and formats), snapshot dumps for golden tests and a LibreOffice conversion helper. Test-framework neutral. + word;docx;odt;opendocument;libreoffice;template;templify;builder;testing;snapshot + + + + + + + + + + + + + + + + + diff --git a/src/TriasDev.Templify.Builder.Testing/packages.lock.json b/src/TriasDev.Templify.Builder.Testing/packages.lock.json new file mode 100644 index 00000000..586d2468 --- /dev/null +++ b/src/TriasDev.Templify.Builder.Testing/packages.lock.json @@ -0,0 +1,91 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "DocumentFormat.OpenXml": { + "type": "Direct", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + }, + "Microsoft.CodeAnalysis.PublicApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "W4kJGezNIKLzo0Ak5FAQDFvkMf2U7DtGL4THmHyRSApfKsKt5V+eX/bU0ZLKAt/uf9Bb2o1bi0YDKj/GRB/vYQ==" + }, + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + }, + "triasdev.templify.builder": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify": "[1.10.0, )" + } + } + }, + "net11.0": { + "DocumentFormat.OpenXml": { + "type": "Direct", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + }, + "Microsoft.CodeAnalysis.PublicApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "W4kJGezNIKLzo0Ak5FAQDFvkMf2U7DtGL4THmHyRSApfKsKt5V+eX/bU0ZLKAt/uf9Bb2o1bi0YDKj/GRB/vYQ==" + }, + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + }, + "triasdev.templify.builder": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify": "[1.10.0, )" + } + } + } + } +} \ No newline at end of file diff --git a/src/TriasDev.Templify.Builder/BlockComposer.cs b/src/TriasDev.Templify.Builder/BlockComposer.cs new file mode 100644 index 00000000..c6934574 --- /dev/null +++ b/src/TriasDev.Templify.Builder/BlockComposer.cs @@ -0,0 +1,504 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Describes block-level content: the document body and, in later versions, cells, boxes, headers and the bodies +/// of conditionals and loops. Valid only inside the lambda it is passed to. +/// +public class BlockComposer +{ + private readonly BuildContext _context; + private readonly List _blocks; + private readonly LoopScope? _scope; + private bool _isOpen = true; + + internal BlockComposer(BuildContext context, List blocks, LoopScope? scope) + { + _context = context; + _blocks = blocks; + _scope = scope; + } + + /// Gets the loop scope this composer writes in. + internal LoopScope? Scope => _scope; + + /// Gets the blocks this composer writes to. + internal List Blocks => _blocks; + + /// Adds a paragraph with literal text, in the default paragraph style. + /// The text. Tabs and line breaks become the format's tab and line break. + /// This composer. + public BlockComposer Paragraph(string text) => AddText(null, text); + + /// Adds a paragraph with literal text. + /// The paragraph style; the style sheet must define it. + /// The text. Tabs and line breaks become the format's tab and line break. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey style, string text) + { + ArgumentNullException.ThrowIfNull(style); + AddText(style, text); + return this; + } + + /// Adds a paragraph that holds one value from the data, in the default paragraph style: {{path}}. + /// The data path of the value. + /// This composer. + public BlockComposer Paragraph(TemplatePath value) => AddValue(null, value); + + /// Adds a paragraph that holds one value from the data: {{path}}. + /// The paragraph style; the style sheet must define it. + /// The data path of the value. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey style, TemplatePath value) + { + ArgumentNullException.ThrowIfNull(style); + AddValue(style, value); + return this; + } + + /// Adds a paragraph with mixed content, in the default paragraph style. + /// Describes the paragraph's content. + /// This composer. + public BlockComposer Paragraph(Action content) => AddComposed(null, content); + + /// Adds a paragraph with mixed content: literal text and values. + /// The paragraph style; the style sheet must define it. + /// Describes the paragraph's content. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey style, Action content) + { + ArgumentNullException.ThrowIfNull(style); + AddComposed(style, content); + return this; + } + + /// Adds a paragraph with literal text and its own layout options. + /// The paragraph style, or null for the inherited one. + /// The text. Tabs and line breaks become the format's tab and line break. + /// The layout options: space before and after, keep with next, keep lines together. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey? style, string text, Action options) + { + ParagraphOverrides? overrides = ParagraphOptions.Compose(options); + AddText(style, text, overrides); + return this; + } + + /// Adds a paragraph that holds one value from the data, with its own layout options. + /// The paragraph style, or null for the inherited one. + /// The data path of the value. + /// The layout options: space before and after, keep with next, keep lines together. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey? style, TemplatePath value, Action options) + { + ParagraphOverrides? overrides = ParagraphOptions.Compose(options); + AddValue(style, value, overrides); + return this; + } + + /// Adds a paragraph with mixed content and its own layout options. + /// The paragraph style, or null for the inherited one. + /// Describes the paragraph's content. + /// The layout options: space before and after, keep with next, keep lines together. + /// This composer. + public BlockComposer Paragraph(ParagraphStyleKey? style, Action content, Action options) + { + ParagraphOverrides? overrides = ParagraphOptions.Compose(options); + AddComposed(style, content, overrides); + return this; + } + + /// Adds a paragraph holding one image at its natural size. + /// The image. + /// The text that describes the image; required. + /// This composer. + public BlockComposer Image(ImageSource image, string altText) => AddImage(null, image, altText, ImageFit.Natural); + + /// Adds a paragraph holding one image. + /// The image. + /// The text that describes the image; required. + /// How the image is sized; the aspect ratio is kept. + /// This composer. + public BlockComposer Image(ImageSource image, string altText, ImageFit fit) => AddImage(null, image, altText, fit); + + /// Adds a paragraph in a style holding one image (the style aligns and spaces it). + /// The paragraph style. + /// The image. + /// The text that describes the image; required. + /// How the image is sized; the aspect ratio is kept. + /// This composer. + public BlockComposer Image(ParagraphStyleKey style, ImageSource image, string altText, ImageFit fit) + { + ArgumentNullException.ThrowIfNull(style); + AddImage(style, image, altText, fit); + return this; + } + + private BlockComposer AddImage(ParagraphStyleKey? style, ImageSource image, string altText, ImageFit fit) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentNullException.ThrowIfNull(fit); + EnsureOpen(); + _blocks.Add(new ParagraphBlock(new Inline[] { InlineComposer.CreateImage(image, altText, fit) }, style)); + return this; + } + + /// Adds a page break: the content after it starts on a new page. + /// This composer. + public BlockComposer PageBreak() + { + EnsureOpen(); + _blocks.Add(new PageBreakBlock()); + return this; + } + + /// + /// Adds blocks shown only when a condition holds: {{#if …}} … {{/if}}. Continue with + /// and . + /// + /// The condition. + /// Describes the blocks shown when it holds. + /// The chain, to add elseif and else parts. + public IfChain If(Condition condition, Action then) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(then); + EnsureOpen(); + CheckCondition(_context, _scope, condition); + ConditionalBlock block = new ConditionalBlock(); + block.Branches.Add(new ConditionalBranch(condition, Compose(_context, _scope, then))); + _blocks.Add(block); + return new IfChain(_context, _scope, block, () => _isOpen); + } + + /// + /// Chooses blocks by a value: one case per value and a mandatory default, written as an if / elseif / else chain. + /// Use it where the design depends on data, for example a box coloured by a status. + /// + /// The data path of the value. + /// Describes the cases and the default. + /// This composer. + public BlockComposer Switch(TemplatePath value, Action cases) + { + ArgumentNullException.ThrowIfNull(cases); + EnsureOpen(); + _ = (Condition)value; // checks the path where it is written: not the root, not a number + LoopScope.CheckUse(_context, _scope, value); + SwitchComposer composer = new SwitchComposer(_context, _scope); + cases(composer); + _blocks.AddRange(composer.Close(value)); + return this; + } + + /// Repeats blocks for every item of a typed collection. + /// The item type. + /// The collection, from . + /// The iteration variable. + /// Describes the blocks for each item; it receives the typed item. + /// This composer. + public BlockComposer ForEach(TemplateCollection collection, string itemName, Action, BlockComposer> body) + { + ArgumentNullException.ThrowIfNull(body); + ForEach(collection.Untyped, itemName, (item, b) => body(new LoopItem(item, collection.Naming), b)); + return this; + } + + /// + /// Repeats blocks for every item of a collection: {{#foreach item in collection}} … {{/foreach}}. + /// The iteration variable is always named, so the template stays readable and an inner loop can still reach the + /// outer item. + /// + /// The data path of the collection; a path from the root or from an enclosing loop's item. + /// + /// The iteration variable: letters, digits and _; not a Templify keyword and not the name of an enclosing + /// loop's variable. + /// + /// Describes the blocks repeated for each item; it receives the item. + /// This composer. + public BlockComposer ForEach(TemplatePath collection, string itemName, Action body) + { + ArgumentNullException.ThrowIfNull(body); + EnsureOpen(); + if (collection.IsRoot || collection.IsMetadata) + { + throw new ArgumentException("A loop needs a collection path from the data or from a loop item.", nameof(collection)); + } + + LoopScope.CheckUse(_context, _scope, collection); + LoopScope scope = new LoopScope(LoopScope.ValidateItemName(itemName, _scope), LoopScope.ValidateCollection(collection, itemName), _scope); + List blocks = new List(); + BlockComposer composer = new BlockComposer(_context, blocks, scope); + body(new LoopItem(scope), composer); + composer.Close(); + _blocks.Add(new LoopBlock(collection, itemName, blocks)); + return this; + } + + /// Adds a table. + /// Describes the columns, header rows and rows. + /// This composer. + public BlockComposer Table(Action table) + { + ArgumentNullException.ThrowIfNull(table); + EnsureOpen(); + TableBlock block = new TableBlock(); + TableComposer composer = new TableComposer(_context, _scope, block); + table(composer); + composer.Close(); + _blocks.Add(block); + return this; + } + + /// + /// Adds a framed box around block content: a border, a background and padding from a box style. The content can + /// be anything a cell holds: paragraphs, conditions, loops, tables. + /// + /// The box style; the style sheet must define it. + /// Describes the box's content. + /// This composer. + public BlockComposer Box(BoxStyleKey style, Action content) + { + ArgumentNullException.ThrowIfNull(style); + ArgumentNullException.ThrowIfNull(content); + EnsureOpen(); + TableBlock box = new TableBlock { BoxStyle = style }; + box.Columns.Add(new ColumnSpec(null, 1)); + TableRowModel row = new TableRowModel(isHeader: false) { AllowSplit = true }; + TableCellModel cell = new TableCellModel(); + cell.Content.AddRange(Compose(_context, _scope, content)); + row.Cells.Add(cell); + box.Rows.Add(row); + _blocks.Add(box); + return this; + } + + /// Adds a horizontal rule across the container. + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// This composer. + public BlockComposer Rule(Length thickness, Color color) => Rule(thickness, color, Length.Zero, Length.Zero); + + /// Adds a horizontal rule across the container, with space above and below. + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// The space above the line. + /// The space below the line. + /// This composer. + public BlockComposer Rule(Length thickness, Color color, Length spaceAbove, Length spaceBelow) => AddRule(thickness, color, spaceAbove, spaceBelow, null); + + /// Adds a horizontal rule of a given width from the start of the container, with space above and below. + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// The space above the line. + /// The space below the line. + /// The rule's width; more than 0 and at most the container's width (checked when building). + /// This composer. + public BlockComposer Rule(Length thickness, Color color, Length spaceAbove, Length spaceBelow, Length width) => + AddRule(thickness, color, spaceAbove, spaceBelow, StyleRanges.Positive(width, nameof(width))); + + private BlockComposer AddRule(Length thickness, Color color, Length spaceAbove, Length spaceBelow, Length? width) + { + EnsureOpen(); + _blocks.Add(new RuleBlock(StyleRanges.Line(thickness, color, nameof(thickness)), StyleRanges.NotNegative(spaceAbove, nameof(spaceAbove)), StyleRanges.NotNegative(spaceBelow, nameof(spaceBelow)), width)); + return this; + } + + /// + /// Adds vertical space of a given height: an empty paragraph whose line is exactly that high, without a style of + /// its own (a gap that needs no "gap" style). + /// + /// The height; more than 0 and at most 72 pt. + /// This composer. + public BlockComposer Spacer(Length height) + { + EnsureOpen(); + if (height <= Length.Zero || height > 72.Pt()) + { + throw new ArgumentOutOfRangeException(nameof(height), height, "A spacer is more than 0 and at most 72 pt high."); + } + + _blocks.Add(new SpacerBlock(height)); + return this; + } + + /// Adds a bullet list: items at levels, loops and conditionals over items. + /// The list style; the style sheet must define it and every level used. + /// Describes the items. + /// This composer. + public BlockComposer List(ListStyleKey style, Action items) + { + ArgumentNullException.ThrowIfNull(style); + ArgumentNullException.ThrowIfNull(items); + EnsureOpen(); + ListBlock list = new ListBlock(style, new List()); + ListComposer composer = new ListComposer(_context, _scope, style, list.Items); + items(composer); + composer.Close(); + _blocks.Add(list); + return this; + } + + /// Adds a block written as format XML, for a construct the vocabulary does not have; both formats are required. + /// The DOCX and ODT XML and the paths it reads. + /// This composer. + public BlockComposer Raw(RawBlock raw) + { + ArgumentNullException.ThrowIfNull(raw); + ArgumentNullException.ThrowIfNull(raw.Docx); + ArgumentNullException.ThrowIfNull(raw.Odt); + ArgumentNullException.ThrowIfNull(raw.Uses); + EnsureOpen(); + foreach (TemplatePath path in raw.Uses) + { + LoopScope.CheckUse(_context, _scope, path); + } + + _blocks.Add(new RawXmlBlock(raw)); + return this; + } + + /// Adds a table of contents over the headings of outline levels 1 to 3. + /// This composer. + public BlockComposer TableOfContents() => TableOfContents(3); + + /// + /// Adds a table of contents over the headings (paragraph styles with an outline level) up to a level. It is built + /// by the application that opens the document: Word does for DOCX on open (fill with + /// UpdateFieldsOnOpen = Auto); LibreOffice — also when converting to PDF — does not, so it stays empty there + /// until a user updates it. The build reports this as a warning (). + /// + /// The deepest outline level listed, 1 to 9. + /// This composer. + public BlockComposer TableOfContents(int maxLevel) + { + EnsureOpen(); + if (maxLevel is < 1 or > 9) + { + throw new ArgumentOutOfRangeException(nameof(maxLevel), maxLevel, "The deepest level is between 1 and 9."); + } + + _blocks.Add(new TocBlock(maxLevel)); + return this; + } + + /// + /// Adds a table of contents with styled entries: c.TableOfContents(3, toc => toc.Level(1, Styles.TocPart)). + /// Levels without a style keep the application's own entry style. + /// + /// The deepest outline level listed, 1 to 9. + /// Sets the entry style per level. + /// This composer. + public BlockComposer TableOfContents(int maxLevel, Action entries) + { + ArgumentNullException.ThrowIfNull(entries); + TableOfContents(maxLevel); + TableOfContentsComposer composer = new TableOfContentsComposer(maxLevel); + entries(composer); + if (composer.Levels.Count > 0) + { + _blocks[^1] = new TocBlock(maxLevel, composer.Levels); + } + + return this; + } + + /// Adds a reusable component's content. + /// The component. + /// This composer. + public BlockComposer Component(ITemplateComponent component) + { + ArgumentNullException.ThrowIfNull(component); + EnsureOpen(); + _blocks.Add(new ComponentBlock(component, Compose(_context, _scope, component.Compose))); + return this; + } + + /// Gets the build's texts, for components: c.Texts["title"]. + public TemplateTexts Texts => _context.Texts ?? throw new InvalidOperationException("No texts in this composition."); + + /// Gets an object the definition shared with (or the JSON import's options). + /// The type it was shared as. + /// The object. + /// Nothing was shared as . + public T Shared() + where T : class => + _context.Shared.TryGetValue(typeof(T), out object? value) ? (T)value + : _context.Shared.Values.OfType().FirstOrDefault() + ?? throw new InvalidOperationException($"Nothing of type {typeof(T).Name} was shared with the components; call template.Share(…) in the definition."); + + /// + /// Adds a named section: a group of blocks with no output of its own. Its name marks the part in the JSON form + /// ({"section": "items", "blocks": […]}), where hosts and agents read, replace and compare it as a unit. + /// + /// The section's name: letters, digits, _, . or -; unique in a definition. + /// Describes the blocks. + /// This composer. + public BlockComposer Section(string name, Action content) + { + ArgumentNullException.ThrowIfNull(content); + Component(new SectionComponent(SectionComponent.ValidateName(name), content)); + return this; + } + + /// Reports paths of a condition that cannot be used here. + internal static void CheckCondition(BuildContext context, LoopScope? scope, Condition condition) + { + foreach (TemplatePath path in condition.Paths) + { + LoopScope.CheckUse(context, scope, path); + } + } + + /// Composes the blocks of a nested part (a branch, a cell, a loop body) in the given loop scope. + internal static List Compose(BuildContext context, LoopScope? scope, Action content) + { + List blocks = new List(); + BlockComposer composer = new BlockComposer(context, blocks, scope); + content(composer); + composer.Close(); + return blocks; + } + + internal void Close() => _isOpen = false; + + private BlockComposer AddText(ParagraphStyleKey? style, string text, ParagraphOverrides? options = null) + { + ArgumentNullException.ThrowIfNull(text); + EnsureOpen(); + List inlines = InlineComposer.TextInlines(text, null); + InlineComposer.CheckLiteralText(_context, inlines); + _blocks.Add(new ParagraphBlock(inlines, style, Options: options)); + return this; + } + + private BlockComposer AddValue(ParagraphStyleKey? style, TemplatePath value, ParagraphOverrides? options = null) + { + EnsureOpen(); + _blocks.Add(new ParagraphBlock(new Inline[] { InlineComposer.CreateValue(_context, _scope, value) }, style, Options: options)); + return this; + } + + private BlockComposer AddComposed(ParagraphStyleKey? style, Action content, ParagraphOverrides? options = null) + { + ArgumentNullException.ThrowIfNull(content); + EnsureOpen(); + InlineComposer composer = new InlineComposer(_context, _scope); + content(composer); + _blocks.Add(new ParagraphBlock(composer.Close(), style, Options: options)); + return this; + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException( + "A block composer was used outside the lambda it was passed to."); + } + } +} diff --git a/src/TriasDev.Templify.Builder/Boxes.cs b/src/TriasDev.Templify.Builder/Boxes.cs new file mode 100644 index 00000000..4ebb4510 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Boxes.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// Names a box style: border, background and padding of a framed box. +public sealed record BoxStyleKey +{ + /// Initializes a box style key. + /// Letters, digits, _ and -, starting with a letter or _. + public BoxStyleKey(string id) + { + Id = StyleKeyRules.ValidateId(id, nameof(id)); + } + + /// Gets the id. + public string Id { get; } +} + +/// Sets a box style's border, background and padding. +public sealed class BoxStyleComposer +{ + private readonly StyleSheetComposer _owner; + private readonly BoxStyleDefinition _style; + + internal BoxStyleComposer(StyleSheetComposer owner, BoxStyleDefinition style) + { + _owner = owner; + _style = style; + } + + /// Sets the border around the box. + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// This composer. + public BoxStyleComposer Border(Length width, Color color) + { + _owner.EnsureOpen(); + if (width <= Length.Zero || width > 6.Pt()) + { + throw new ArgumentOutOfRangeException(nameof(width), width, "A line is more than 0 and at most 6 pt wide."); + } + + _style.Border = new BorderLine(width, color); + return this; + } + + /// Sets the background. + /// The colour. + /// This composer. + public BoxStyleComposer Background(Color color) + { + _owner.EnsureOpen(); + _style.Background = color; + return this; + } + + /// Sets the same padding on all sides. + /// The padding. + /// This composer. + public BoxStyleComposer Padding(Length all) => Padding(all, all); + + /// Sets the padding between the border and the content. + /// Top and bottom. + /// Left and right. + /// This composer. + public BoxStyleComposer Padding(Length vertical, Length horizontal) => Padding(vertical, horizontal, vertical, horizontal); + + /// Sets the padding between the border and the content, per side. + /// The top padding. + /// The right padding. + /// The bottom padding. + /// The left padding. + /// This composer. + public BoxStyleComposer Padding(Length top, Length right, Length bottom, Length left) + { + _owner.EnsureOpen(); + _style.Padding = StyleRanges.Insets(top, right, bottom, left); + return this; + } + + /// Sets the space after the box. + /// The space. + /// This composer. + public BoxStyleComposer SpaceAfter(Length space) + { + _owner.EnsureOpen(); + _style.SpaceAfter = StyleRanges.NotNegative(space, nameof(space)); + return this; + } +} diff --git a/src/TriasDev.Templify.Builder/BuildContext.cs b/src/TriasDev.Templify.Builder/BuildContext.cs new file mode 100644 index 00000000..b8e4a81f --- /dev/null +++ b/src/TriasDev.Templify.Builder/BuildContext.cs @@ -0,0 +1,162 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// State shared by the composers of one build: the diagnostics collected while composing. +/// +internal sealed class BuildContext +{ + private readonly List _errors = new List(); + private readonly List _warnings = new List(); + + /// Gets the warnings found so far; they do not fail the build. + public IReadOnlyList Warnings => _warnings; + + /// Records a warning: the template builds, but something behaves differently than one might expect. + public void Warn(string code, string message) => _warnings.Add(new BuildDiagnostic(code, message)); + + /// Gets the errors found so far. + public IReadOnlyList Errors => _errors; + + /// Records an error; the build fails after composing, with every error found. + public void Error(string code, string message) => _errors.Add(new BuildDiagnostic(code, message) { Location = CurrentLocation }); + + /// Gets or sets the build's texts (for components). + public TemplateTexts? Texts { get; set; } + + /// Gets the objects a definition shares with its components, by type. + public Dictionary Shared { get; } = new Dictionary(); + + /// Where a JSON definition is being composed (a JSON pointer); null for C# definitions. + public string? CurrentLocation { get; set; } + + /// The JSON pointers of model blocks a JSON definition created, for checks that run on the finished model. + public System.Runtime.CompilerServices.ConditionalWeakTable Locations { get; } = new System.Runtime.CompilerServices.ConditionalWeakTable(); + + /// Sets to a block's JSON pointer (null when it has none). + public void At(Model.Block block) => CurrentLocation = Locations.TryGetValue(block, out string? location) ? location : null; + + /// Records an error at a location in a JSON definition. + public void Error(string code, string message, string? location) => _errors.Add(new BuildDiagnostic(code, message) { Location = location }); + + /// Records an error about a data path at a location. + public void Error(string code, string message, string? location, string dataPath) => + _errors.Add(new BuildDiagnostic(code, message) { Location = location, DataPath = dataPath }); + + /// Records problems found elsewhere, for example in a style sheet. + public void AddRange(IEnumerable problems) => _errors.AddRange(problems); +} + +/// Stable diagnostic codes. +internal static class DiagnosticCodes +{ + /// The definition has no identity. + public const string MissingIdentity = "TB0001"; + + /// The identity's id is empty. + public const string EmptyIdentityId = "TB0002"; + + /// A placeholder was given the empty (root) path. + public const string EmptyValuePath = "TB1001"; + + /// Literal text contains {{, which Templify would read as the start of a placeholder. + public const string LiteralOpenBraces = "TB1002"; + + /// was called more than once. + public const string StylesAlreadySet = "TB2000"; + + /// A style id is defined more than once. + public const string DuplicateStyleId = "TB2001"; + + /// A display name is used by several styles. + public const string DuplicateStyleName = "TB2002"; + + /// A style is based on a style the sheet does not define. + public const string UnknownBasedOn = "TB2003"; + + /// A paragraph style names a next style the sheet does not define. + public const string UnknownNextStyle = "TB2004"; + + /// Styles inherit from each other in a cycle. + public const string BasedOnCycle = "TB2005"; + + /// A style's display name contains a comma, which Word reads as a list of aliases (schema-invalid DOCX). + public const string InvalidStyleName = "TB2006"; + + /// Content uses a style the style sheet does not define. + public const string UndefinedStyle = "TB2010"; + + /// One font family is embedded with two different files. + public const string ConflictingEmbeddedFont = "TB2011"; + + /// A switch has no Default. + public const string SwitchWithoutDefault = "TB3001"; + + /// A switch names the same value in more than one case. + public const string DuplicateSwitchCase = "TB3002"; + + /// A path from a loop variable is used outside its loop. + public const string LoopVariableOutOfScope = "TB4001"; + + /// Loop metadata of an outer loop is used inside a nested loop. + public const string OuterLoopMetadata = "TB4002"; + + /// A path from the data's root starts with the name of an enclosing loop variable. + public const string RootPathHidden = "TB4003"; + + /// A text key has no translation for the build's language. + public const string MissingText = "TB5001"; + + /// The JSON export cannot write a text: a literal "[[" (read as a text key) or a key outside the key syntax. + public const string TextNotExportable = "TB9204"; + + /// A theme value the host sets on import names a token the definition's theme does not have; it is not used. + public const string UnusedThemeValue = "TB9205"; + + /// was called more than once. + public const string PageAlreadySet = "TB6001"; + + /// The margins leave no room for text. + public const string NoTextFrame = "TB6002"; + + /// A table has no columns. + public const string TableWithoutColumns = "TB7001"; + + /// A table's fixed columns do not fit its container. + public const string TableTooWide = "TB7002"; + + /// A row's cells do not span the table's columns. + public const string RowCellCount = "TB7003"; + + /// A raw block's XML has a root element that cannot stand at block level. + public const string InvalidRawBlock = "TB9101"; + + /// A raw block asks for a placeholder of a path it does not declare. + public const string UndeclaredRawPath = "TB9102"; + + /// A JSON definition is malformed: its structure, an unknown key or kind, a wrong value, an unknown asset or component. + public const string InvalidJson = "TB9200"; + + /// A value in a JSON definition is not accepted by the builder (a composer rejected it). + public const string InvalidJsonValue = "TB9201"; + + /// A JSON definition contains raw XML, which the import options do not allow. + public const string RawXmlNotAllowed = "TB9202"; + + /// A JSON definition reads a data path the data catalogue does not list. + public const string UnknownDataPath = "TB9203"; + + /// A table of contents is built only by an application that updates it (Word on open; not LibreOffice). + public const string TableOfContentsNotBuilt = "TB9001"; + + /// A list item uses a level its list style does not define. + public const string UndefinedListLevel = "TB8001"; + + /// A table of contents' entry style is a heading: it would list its own entries. + public const string TocEntryStyleIsHeading = "TB8002"; + + /// Two tables of contents give one level different entry styles; DOCX has one per level. + public const string ConflictingTocEntryStyles = "TB8003"; +} diff --git a/src/TriasDev.Templify.Builder/BuildDiagnostic.cs b/src/TriasDev.Templify.Builder/BuildDiagnostic.cs new file mode 100644 index 00000000..0f3db66b --- /dev/null +++ b/src/TriasDev.Templify.Builder/BuildDiagnostic.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// One problem found while building a template. +/// +/// A stable code for the kind of problem, for example TB1001. +/// A message that names the problem and where it is. +public sealed record BuildDiagnostic(string Code, string Message) +{ + /// Gets where the problem is in a JSON definition (a JSON pointer such as /content/3); null for C# definitions. + public string? Location { get; init; } + + /// Gets the data path a TB9203 problem is about (canonical form), for the check of stored definitions. + internal string? DataPath { get; init; } + + /// + public override string ToString() => $"{Code}: {Message}"; +} diff --git a/src/TriasDev.Templify.Builder/Components/ComponentCatalog.cs b/src/TriasDev.Templify.Builder/Components/ComponentCatalog.cs new file mode 100644 index 00000000..358b65bd --- /dev/null +++ b/src/TriasDev.Templify.Builder/Components/ComponentCatalog.cs @@ -0,0 +1,379 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using System.Text.Json; +using System.Text.RegularExpressions; +using TriasDev.Templify.Builder.Json; + +namespace TriasDev.Templify.Builder; + +/// +/// Components that a JSON definition refers to by name: an exported definition writes a registered component as +/// { "component": name, "params": { … } }, and an import creates it from the current component code, so a +/// stored definition picks up changes to the component. +/// +/// +/// A registrable component has one public constructor, and every parameter has a public property of the same name +/// (records satisfy this). Parameters are paths (, ), +/// , , , , , +/// , enums, style keys, , , their nullable forms, or +/// of those. +/// +public sealed partial class ComponentCatalog +{ + private readonly Dictionary _byName = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _byType = new Dictionary(); + + /// + /// Gets how C# property names become data names for typed parameters (), as the + /// definitions pass it to ; null for camelCase. + /// + public System.Text.Json.JsonNamingPolicy? DataNaming { get; init; } + + /// The registered components that have a : stamp name → version. + internal IReadOnlyDictionary Versions() => + _byType.Keys + .Select(type => (Name: ComponentVersions.NameOf(type), Version: ComponentVersions.VersionOf(type))) + .Where(c => c.Version is not null) + .GroupBy(c => c.Name, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.Max(c => c.Version!.Value), StringComparer.Ordinal); + + /// Gets the registered names. + public IReadOnlyCollection Names => _byName.Keys; + + /// Registers a component type under a name. + /// The component type. + /// The name in JSON: a letter, then letters and digits (address, verdictBox). + /// This catalog. + /// The name is malformed or taken, or the type cannot be written as parameters. + public ComponentCatalog Register(string name) + where TComponent : ITemplateComponent + { + ArgumentNullException.ThrowIfNull(name); + if (!NamePattern().IsMatch(name)) + { + throw new ArgumentException($"'{name}' is not a component name: a letter, then letters and digits.", nameof(name)); + } + + if (_byName.ContainsKey(name)) + { + throw new ArgumentException($"The name '{name}' is already registered.", nameof(name)); + } + + Type type = typeof(TComponent); + ConstructorInfo[] constructors = type.GetConstructors(); + if (constructors.Length != 1) + { + throw new ArgumentException($"{type.Name} needs exactly one public constructor to be registered.", nameof(TComponent)); + } + + List<(ParameterInfo Parameter, PropertyInfo Property)> parameters = new List<(ParameterInfo, PropertyInfo)>(); + foreach (ParameterInfo parameter in constructors[0].GetParameters()) + { + PropertyInfo? property = type.GetProperty(parameter.Name!, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); + if (property is null || !property.CanRead) + { + throw new ArgumentException($"{type.Name}: the parameter '{parameter.Name}' has no public property of the same name, so it cannot be written to JSON.", nameof(TComponent)); + } + + if (!IsAllowed(parameter.ParameterType)) + { + throw new ArgumentException( + $"{type.Name}: the parameter '{parameter.Name}' is a {parameter.ParameterType.Name}, which cannot be written to JSON (paths, strings, numbers, booleans, enums, style keys, lengths, colours and lists of those can).", + nameof(TComponent)); + } + + parameters.Add((parameter, property)); + } + + Registration registration = new Registration(name, type, constructors[0], parameters); + _byName.Add(name, registration); + _byType[type] = registration; + return this; + } + + internal Registration? Find(string name) => _byName.GetValueOrDefault(name); + + /// Gets the registrations, by name (ordinal). + internal IEnumerable Registrations => _byName.Values.OrderBy(r => r.Name, StringComparer.Ordinal); + + internal Registration? Find(Type type) => _byType.GetValueOrDefault(type); + + private static bool IsAllowed(Type type) + { + type = Nullable.GetUnderlyingType(type) ?? type; + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) + { + return IsAllowed(type.GetGenericArguments()[0]); + } + + return type == typeof(TemplatePath) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(TemplatePath<>)) + || type == typeof(string) || type == typeof(bool) || type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(decimal) + || type.IsEnum + || type == typeof(ParagraphStyleKey) || type == typeof(CharacterStyleKey) || type == typeof(BoxStyleKey) || type == typeof(TableStyleKey) || type == typeof(ListStyleKey) + || type == typeof(Length) || type == typeof(Color); + } + + [GeneratedRegex("^[A-Za-z][A-Za-z0-9]*$", RegexOptions.CultureInvariant)] + private static partial Regex NamePattern(); + + /// A registered component type: its name and how its parameters map to JSON. + internal sealed class Registration(string name, Type type, ConstructorInfo constructor, List<(ParameterInfo Parameter, PropertyInfo Property)> parameters) + { + public string Name { get; } = name; + + public Type Type { get; } = type; + + /// The parameters as JSON names and value types, for the description an agent reads. + public IEnumerable<(string Name, string Type)> DescribeParameters() => + ParameterTypes().Select(p => (p.Name, TypeName(p.Type))); + + /// The parameters as JSON names and CLR types, for the JSON Schema. + public IEnumerable<(string Name, Type Type)> ParameterTypes() => + parameters.Select(p => (JsonNamingPolicy.CamelCase.ConvertName(p.Parameter.Name!), p.Parameter.ParameterType)); + + private static string TypeName(Type type) + { + type = Nullable.GetUnderlyingType(type) ?? type; + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) + { + return "list of " + TypeName(type.GetGenericArguments()[0]); + } + + if (type.IsEnum) + { + return "one of " + string.Join(", ", Enum.GetNames(type).Select(n => char.ToLowerInvariant(n[0]) + n[1..])); + } + + return type == typeof(TemplatePath) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(TemplatePath<>)) ? "path" + : type == typeof(string) ? "text" + : type == typeof(bool) ? "boolean" + : type == typeof(int) || type == typeof(long) ? "integer" + : type == typeof(double) || type == typeof(decimal) ? "number" + : type == typeof(ParagraphStyleKey) ? "paragraph style" + : type == typeof(CharacterStyleKey) ? "character style" + : type == typeof(BoxStyleKey) ? "box style" + : type == typeof(TableStyleKey) ? "table style" + : type == typeof(ListStyleKey) ? "list style" + : type == typeof(Length) ? "length" + : type == typeof(Color) ? "color" + : type.Name; + } + + /// Gets a value indicating whether the component takes parameters (a reference without any has no params). + public bool HasParameters => parameters.Count > 0; + + /// Writes the component's parameters as a JSON object. + /// A typed path parameter uses another naming than , so it could not be read back. + public void WriteParameters(Utf8JsonWriter json, ITemplateComponent component, JsonNamingPolicy? dataNaming, Func colorText) + { + json.WriteStartObject(); + foreach ((ParameterInfo parameter, PropertyInfo property) in parameters) + { + object? value = property.GetValue(component); + if (value is not null && TypedPathNaming(value, out JsonNamingPolicy? naming) && (naming ?? JsonNamingPolicy.CamelCase) != (dataNaming ?? JsonNamingPolicy.CamelCase)) + { + throw new ArgumentException( + $"The component '{Name}' gets the typed path '{parameter.Name}' with a different naming policy than the catalog's DataNaming; set ComponentCatalog.DataNaming to the policy the definition passes to DataAs()."); + } + + json.WritePropertyName(JsonNamingPolicy.CamelCase.ConvertName(parameter.Name!)); + WriteValue(json, value, colorText); + } + + json.WriteEndObject(); + } + + private static bool TypedPathNaming(object value, out JsonNamingPolicy? naming) + { + naming = null; + Type type = value.GetType(); + if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(TemplatePath<>)) + { + return false; + } + + naming = (JsonNamingPolicy?)type.GetProperty("Naming", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(value); + return true; + } + + /// Creates the component from its JSON parameters. + public ITemplateComponent Create(JsonElement values, JsonNamingPolicy? dataNaming, Func resolvePath, Func paragraphStyle, Func characterStyle, Func color, string at) + { + if (values.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at, "'params' must be an object."); + } + + HashSet unknown = values.EnumerateObject().Select(p => p.Name).ToHashSet(StringComparer.Ordinal); + object?[] arguments = new object?[parameters.Count]; + for (int i = 0; i < parameters.Count; i++) + { + ParameterInfo parameter = parameters[i].Parameter; + string key = JsonNamingPolicy.CamelCase.ConvertName(parameter.Name!); + unknown.Remove(key); + arguments[i] = values.TryGetProperty(key, out JsonElement value) + ? ReadValue(value, parameter.ParameterType, dataNaming, resolvePath, paragraphStyle, characterStyle, color, at + "/" + key) + : throw new JsonImportException(at, $"The parameter '{key}' of '{Name}' is missing."); + } + + if (unknown.Count > 0) + { + string first = unknown.Order(StringComparer.Ordinal).First(); + throw new JsonImportException(at + "/" + first, $"'{Name}' has no parameter '{first}'."); + } + + try + { + return (ITemplateComponent)constructor.Invoke(arguments); + } + catch (TargetInvocationException exception) when (exception.InnerException is { } inner) + { + // The component rejected its parameters: reported as an invalid value (TB9201) at the reference. + throw new ArgumentException($"The component '{Name}' rejected its parameters: {inner.Message}", inner); + } + } + + private static void WriteValue(Utf8JsonWriter json, object? value, Func colorText) + { + switch (value) + { + case null: + json.WriteNullValue(); + break; + case TemplatePath path: + json.WriteStringValue(path.ToString()); + break; + case string text: + json.WriteStringValue(text); + break; + case bool flag: + json.WriteBooleanValue(flag); + break; + case int number: + json.WriteNumberValue(number); + break; + case long number: + json.WriteNumberValue(number); + break; + case double number: + json.WriteNumberValue(number); + break; + case decimal number: + json.WriteNumberValue(number); + break; + case Enum e: + string name = e.ToString(); + json.WriteStringValue(char.ToLowerInvariant(name[0]) + name[1..]); + break; + case ParagraphStyleKey key: + json.WriteStringValue(key.Id); + break; + case CharacterStyleKey key: + json.WriteStringValue(key.Id); + break; + case BoxStyleKey key: + json.WriteStringValue(key.Id); + break; + case TableStyleKey key: + json.WriteStringValue(key.Id); + break; + case ListStyleKey key: + json.WriteStringValue(key.Id); + break; + case Length length: + json.WriteStringValue(JsonValues.Length(length)); + break; + case Color color: + json.WriteStringValue(colorText(color)); // a theme colour stays "$token" + break; + case System.Collections.IEnumerable list: + json.WriteStartArray(); + foreach (object? item in list) + { + WriteValue(json, item, colorText); + } + + json.WriteEndArray(); + break; + default: + // A TemplatePath: written as its plain path. + if (value.GetType() is { IsGenericType: true } type && type.GetGenericTypeDefinition() == typeof(TemplatePath<>)) + { + json.WriteStringValue(value.ToString()); + break; + } + + throw new NotSupportedException($"A component parameter of type {value.GetType().Name} cannot be written."); + } + } + + private static object? ReadValue(JsonElement value, Type type, JsonNamingPolicy? dataNaming, Func resolvePath, Func paragraphStyle, Func characterStyle, Func color, string at) + { + Type? underlying = Nullable.GetUnderlyingType(type); + if (value.ValueKind == JsonValueKind.Null) + { + return underlying != null || !type.IsValueType ? null : throw new JsonImportException(at, "A value is required."); + } + + type = underlying ?? type; + try + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) + { + Type itemType = type.GetGenericArguments()[0]; + System.Collections.IList list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType))!; + int i = 0; + foreach (JsonElement item in value.EnumerateArray()) + { + list.Add(ReadValue(item, itemType, dataNaming, resolvePath, paragraphStyle, characterStyle, color, at + "/" + i++)); + } + + return list; + } + + if (type == typeof(TemplatePath)) + { + return resolvePath(value.GetString()!, null); + } + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(TemplatePath<>)) + { + TemplatePath path = resolvePath(value.GetString()!, DataCatalog.KindOfType(type.GetGenericArguments()[0])); + return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance, null, [path, dataNaming], null); + } + + if (type.IsEnum) + { + string text = value.GetString()!; + return Enum.TryParse(type, text, ignoreCase: true, out object? parsed) && !text.Any(char.IsDigit) + ? parsed + : throw new JsonImportException(at, $"'{text}' is not one of {string.Join(", ", Enum.GetNames(type))}."); + } + + return type switch + { + _ when type == typeof(string) => value.GetString(), + _ when type == typeof(bool) => value.GetBoolean(), + _ when type == typeof(int) => value.GetInt32(), + _ when type == typeof(long) => value.GetInt64(), + _ when type == typeof(double) => value.GetDouble(), + _ when type == typeof(decimal) => value.GetDecimal(), + _ when type == typeof(ParagraphStyleKey) => paragraphStyle(value.GetString()!), + _ when type == typeof(CharacterStyleKey) => characterStyle(value.GetString()!), + _ when type == typeof(BoxStyleKey) => new BoxStyleKey(value.GetString()!), + _ when type == typeof(TableStyleKey) => new TableStyleKey(value.GetString()!), + _ when type == typeof(ListStyleKey) => new ListStyleKey(value.GetString()!), + _ when type == typeof(Length) => JsonValues.TryLength(value.GetString(), out Length length) ? length : throw new JsonImportException(at, $"{value} is not a length."), + _ when type == typeof(Color) => color(value.GetString()!, at), + _ => throw new JsonImportException(at, $"A parameter of type {type.Name} cannot be read."), + }; + } + catch (Exception exception) when (exception is InvalidOperationException or FormatException) + { + throw new JsonImportException(at, $"{value} is not a {type.Name}: {exception.Message}"); + } + } + } +} diff --git a/src/TriasDev.Templify.Builder/Components/ComponentVersionAttribute.cs b/src/TriasDev.Templify.Builder/Components/ComponentVersionAttribute.cs new file mode 100644 index 00000000..cd00a79b --- /dev/null +++ b/src/TriasDev.Templify.Builder/Components/ComponentVersionAttribute.cs @@ -0,0 +1,57 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// The version of a component (), for standard blocks whose changes stored copies +/// should pick up (terms, legal notes). The stamp of every template records the versioned components it was built +/// from, and the check of stored templates reports copies built from an older version. Components without it are not +/// tracked. +/// +/// +/// A JSON export names a versioned component by its registration (), so builds from the +/// JSON always use its current version; exporting an unregistered versioned component is an error (TB9204). +/// +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class ComponentVersionAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The version, 1 or more. + /// The version is less than 1. + public ComponentVersionAttribute(int version) + { + ArgumentOutOfRangeException.ThrowIfLessThan(version, 1); + Version = version; + } + + /// Gets the version. + public int Version { get; } +} + +/// How the stamp names components and reads their versions. +internal static class ComponentVersions +{ + /// The component's name in the stamp: its type name without a generic suffix (Card`1 → Card). + public static string NameOf(Type type) => type.Name.Split('`')[0]; + + /// The component's version; null when it is not versioned. + public static int? VersionOf(Type type) => + type.GetCustomAttributes(typeof(ComponentVersionAttribute), inherit: false) is [ComponentVersionAttribute attribute, ..] ? attribute.Version : null; + + /// The versioned components of a composed body, name → version. + public static IReadOnlyDictionary In(IEnumerable blocks) + { + SortedDictionary result = new SortedDictionary(StringComparer.Ordinal); + foreach (Model.ComponentBlock block in Model.BlockTree.All(blocks).OfType()) + { + Type type = block.Component.GetType(); + if (VersionOf(type) is { } version) + { + result[NameOf(type)] = Math.Max(result.GetValueOrDefault(NameOf(type)), version); + } + } + + return result; + } +} diff --git a/src/TriasDev.Templify.Builder/Condition.cs b/src/TriasDev.Templify.Builder/Condition.cs new file mode 100644 index 00000000..34e439e4 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Condition.cs @@ -0,0 +1,292 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; +using TriasDev.Templify.Conditionals; + +namespace TriasDev.Templify.Builder; + +/// +/// A condition of a conditional block: built from comparisons and combined with +/// !, & and |. The builder writes it as Templify condition text, with the engine's +/// precedence, quoting and keyword escaping. +/// +/// +/// +/// Condition paid = order["status"].Eq("paid") | order["status"].Eq("settled"); +/// Condition large = order["total"].Gt(1000) & !order["customer.isVip"]; +/// +/// +public abstract class Condition +{ + private protected Condition() + { + } + + /// Gets the binding strength: 1 or, 2 and, 3 not, 4 comparisons, 5 postfix, 6 operands. + internal abstract int Precedence { get; } + + /// Gets the data paths the condition reads. + internal abstract IEnumerable Paths { get; } + + /// Negates a condition: not (…). + /// The condition to negate. + /// The negated condition. + public static Condition operator !(Condition operand) => new NotCondition(operand ?? throw new ArgumentNullException(nameof(operand))); + + /// Both conditions hold: … and …. + /// The first condition. + /// The second condition. + /// The combined condition. + public static Condition operator &(Condition left, Condition right) => + new LogicalCondition("and", 2, left ?? throw new ArgumentNullException(nameof(left)), right ?? throw new ArgumentNullException(nameof(right))); + + /// At least one condition holds: … or …. + /// The first condition. + /// The second condition. + /// The combined condition. + public static Condition operator |(Condition left, Condition right) => + new LogicalCondition("or", 1, left ?? throw new ArgumentNullException(nameof(left)), right ?? throw new ArgumentNullException(nameof(right))); + + /// + /// A condition written as Templify text, for what the typed API does not cover. It is checked with + /// where it is written. + /// + /// The condition text, for example Count > 0 and not IsArchived. + /// The data paths the text reads, declared for the template's data contract. + /// The condition. + /// The text is not a valid condition, or contains {{ or }}. + public static Condition Raw(string expression, params TemplatePath[] uses) + { + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(uses); + if (expression.Contains("{{", StringComparison.Ordinal) || expression.Contains("}}", StringComparison.Ordinal) || expression.Any(char.IsControl)) + { + throw new ArgumentException("A condition must not contain '{{', '}}' or control characters.", nameof(expression)); + } + + ConditionValidationResult validation = new ConditionEvaluator().Validate(expression); + if (!validation.IsValid) + { + throw new ArgumentException( + $"'{expression}' is not a valid condition: {string.Join("; ", validation.Issues.Select(i => i.Message))}", + nameof(expression)); + } + + return new RawCondition(expression.Trim(), uses); + } + + /// Returns the condition as Templify writes it, for example status = "paid" or total > 1000. + /// The condition text. + public override string ToString() + { + StringBuilder text = new StringBuilder(); + Write(text); + return text.ToString(); + } + + /// Writes the condition text. + internal abstract void Write(StringBuilder text); + + /// Writes an operand, in parentheses when it binds looser than . + private protected static void WriteOperand(StringBuilder text, Condition operand, int minimum) + { + if (operand.Precedence < minimum) + { + text.Append('('); + operand.Write(text); + text.Append(')'); + } + else + { + operand.Write(text); + } + } +} + +/// Writes the operands of conditions: paths, strings and numbers. +internal static class ConditionText +{ + /// + /// Words the condition lexer reads as operators or literals. A path that is exactly such a word is written in + /// brackets ([in]), the engine's escape. + /// + private static readonly HashSet _keywords = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "and", "or", "not", "in", "is", "empty", "exists", "contains", "startswith", "endswith", "true", "false", "null", + }; + + public static void Path(StringBuilder text, TemplatePath path) + { + string value = path.ToString(); + text.Append(_keywords.Contains(value) ? "[" + value + "]" : value); + } + + /// + /// A path as the right operand of a comparison. A one-segment path is written in brackets ([limit], the + /// engine's identifier escape): a bare word there reads as a forgotten quote in the JSON form, which rejects it. + /// + public static void OtherPath(StringBuilder text, TemplatePath path) + { + string value = path.ToString(); + text.Append(value.All(c => char.IsLetterOrDigit(c) || c == '_') ? "[" + value + "]" : value); + } + + public static string CheckPath(TemplatePath path, string parameterName) + { + string value = path.ToString(); + if (value.Length > 0 && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _)) + { + throw new ArgumentException($"The path '{value}' reads as a number in a condition and cannot be used there.", parameterName); + } + + return value; + } + + public static string String(string value, string parameterName) + { + ArgumentNullException.ThrowIfNull(value, parameterName); + if (value.Contains("{{", StringComparison.Ordinal) || value.Contains("}}", StringComparison.Ordinal) || value.Any(char.IsControl)) + { + throw new ArgumentException($"'{value}' cannot be compared in a condition: it must not contain '{{{{', '}}}}' or control characters.", parameterName); + } + + // The engine turns typographic double quotes into '"' before it reads a condition. + if (value.Any(c => c is '“' or '”' or '„' or '‟' or '″')) + { + throw new ArgumentException($"'{value}' contains typographic quotes, which Templify reads as '\"'.", parameterName); + } + + return "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\""; + } + + public static string Number(double value, string parameterName) + { + // The condition lexer reads a number as one word of digits, '.' and a leading '-': no exponent ("1E+20"). + if (double.IsNaN(value) || double.IsInfinity(value) || Math.Abs(value) > 7.9e27) + { + throw new ArgumentOutOfRangeException(parameterName, value, "A condition compares with a finite number of at most 7.9e27."); + } + + // The shortest text that reads back as the same double ("R"), without an exponent. A cast to decimal is exact on + // .NET 11 (19.99 → 19.989999999999998436805981328) and rounded on .NET 10, which made the bytes differ by runtime. + string shortest = value.ToString("R", CultureInfo.InvariantCulture); + return shortest.Contains('E', StringComparison.Ordinal) + ? decimal.Parse(shortest, NumberStyles.Float, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) + : shortest; + } +} + +/// A path's truthiness: {{#if path}}. +internal sealed class TruthCondition(TemplatePath path) : Condition +{ + internal override int Precedence => 6; + + internal override IEnumerable Paths => [path]; + + internal override void Write(StringBuilder text) => ConditionText.Path(text, path); +} + +/// A binary comparison or string operator: path = "x", path > 3, path contains "x". +internal sealed class ComparisonCondition(TemplatePath path, string op, string literal) : Condition +{ + internal override int Precedence => 4; + + internal override IEnumerable Paths => [path]; + + internal override void Write(StringBuilder text) + { + ConditionText.Path(text, path); + text.Append(' ').Append(op).Append(' ').Append(literal); + } +} + +/// +/// A path compared with another path: a.id = b.id. Templify reads an operand that does not resolve as its text, so +/// the data contract (which lists both paths) is what keeps the comparison meaningful. +/// +internal sealed class PathComparisonCondition(TemplatePath path, string op, TemplatePath other) : Condition +{ + internal override int Precedence => 4; + + internal override IEnumerable Paths => [path, other]; + + internal override void Write(StringBuilder text) + { + ConditionText.Path(text, path); + text.Append(' ').Append(op).Append(' '); + ConditionText.OtherPath(text, other); + } +} + +/// Membership in a list literal: path in ("a", "b"). +internal sealed class InCondition(TemplatePath path, IReadOnlyList literals) : Condition +{ + internal override int Precedence => 4; + + internal override IEnumerable Paths => [path]; + + internal override void Write(StringBuilder text) + { + ConditionText.Path(text, path); + text.Append(" in (").Append(string.Join(", ", literals)).Append(')'); + } +} + +/// A postfix operator: path exists, path is empty, path is not empty. +internal sealed class PostfixCondition(TemplatePath path, string op) : Condition +{ + internal override int Precedence => 5; + + internal override IEnumerable Paths => [path]; + + internal override void Write(StringBuilder text) + { + ConditionText.Path(text, path); + text.Append(' ').Append(op); + } +} + +/// not …; any operand other than a plain path is parenthesised, for readability. +internal sealed class NotCondition(Condition operand) : Condition +{ + internal override int Precedence => 3; + + internal override IEnumerable Paths => operand.Paths; + + internal override void Write(StringBuilder text) + { + text.Append("not "); + WriteOperand(text, operand, 6); + } +} + +/// … and … / … or …, left-associative. +internal sealed class LogicalCondition(string op, int precedence, Condition left, Condition right) : Condition +{ + internal override int Precedence => precedence; + + internal override IEnumerable Paths => left.Paths.Concat(right.Paths); + + internal override void Write(StringBuilder text) + { + WriteOperand(text, left, precedence); + text.Append(' ').Append(op).Append(' '); + WriteOperand(text, right, precedence + 1); + } +} + +/// Condition text written by hand; always parenthesised when it is an operand. +internal sealed class RawCondition(string expression, IReadOnlyList uses) : Condition +{ + internal string Expression => expression; + + internal IReadOnlyList Uses => uses; + + internal override int Precedence => 0; + + internal override IEnumerable Paths => uses; + + internal override void Write(StringBuilder text) => text.Append(expression); +} diff --git a/src/TriasDev.Templify.Builder/DataContract.cs b/src/TriasDev.Templify.Builder/DataContract.cs new file mode 100644 index 00000000..d29610df --- /dev/null +++ b/src/TriasDev.Templify.Builder/DataContract.cs @@ -0,0 +1,351 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// How a template uses a data path. +public enum ContractUsage +{ + /// The value is printed: {{path}}. + Value = 0, + + /// The path is a collection a loop runs over: {{#foreach x in path}}. + Collection = 1, + + /// The value is tested in a condition: {{#if path …}}. + Condition = 2, +} + +/// One data path a template uses, in canonical form. +/// +/// The canonical path: from the data's root, with [] for "every item of a collection", for example +/// order.lines[].description. Loop variable names do not appear in it. +/// +/// How the template uses the path. +public sealed record ContractEntry(string Path, ContractUsage Usage); + +/// +/// The data a template needs: every path it prints, tests or loops over, in canonical form. Built with the template +/// (). +/// +/// +/// +/// The depends only on the entries, not on the language, the format or the theme, so it is the +/// same for every build of a definition that reads the same data, which makes it a cheap parity check between +/// languages. +/// +/// +/// builds data in which every path exists. Validating an uploaded copy of a template +/// against it (TemplateProcessor.ValidateTemplate(stream, witness)) reports the paths the copy uses that +/// the current data no longer provides. +/// +/// +public sealed class DataContract +{ + private const int JsonVersion = 1; + + internal DataContract(IEnumerable entries) + { + Entries = entries + .Distinct() + .OrderBy(e => e.Path, StringComparer.Ordinal) + .ThenBy(e => e.Usage) + .ToList(); + Hash = ComputeHash(Entries); + } + + /// Gets the entries, sorted by path (ordinal) and usage. + public IReadOnlyList Entries { get; } + + /// Gets the SHA-256 of the entries as lower-case hex. + public string Hash { get; } + + /// Reads a contract written by . + /// The JSON. + /// The contract. + /// The JSON is not a data contract. + public static DataContract FromJson(string json) + { + ArgumentNullException.ThrowIfNull(json); + try + { + JsonNode? root = JsonNode.Parse(json); + if (root?["version"]?.GetValue() != JsonVersion || root["entries"] is not JsonArray entries) + { + throw new FormatException($"Not a data contract of version {JsonVersion}."); + } + + List result = new List(); + foreach (JsonNode? entry in entries) + { + string path = entry?["path"]?.GetValue() ?? throw new FormatException("An entry has no path."); + string usage = entry["usage"]?.GetValue() ?? throw new FormatException("An entry has no usage."); + if (path.Length == 0 || !Enum.TryParse(usage, ignoreCase: true, out ContractUsage parsed) || !Enum.IsDefined(parsed)) + { + throw new FormatException($"Invalid entry: '{path}' ({usage})."); + } + + result.Add(new ContractEntry(path, parsed)); + } + + return new DataContract(result); + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException) + { + throw new FormatException("Not a data contract: " + exception.Message, exception); + } + } + + /// Writes the contract as JSON: a version, the hash and the entries. + /// The JSON, indented. + public string ToJson() + { + JsonObject root = new JsonObject + { + ["version"] = JsonVersion, + ["hash"] = Hash, + ["entries"] = new JsonArray(Entries + .Select(e => (JsonNode)new JsonObject { ["path"] = e.Path, ["usage"] = e.Usage.ToString().ToLowerInvariant() }) + .ToArray()), + }; + return root.ToJsonString(new JsonSerializerOptions { WriteIndented = true }); + } + + /// + /// Builds data in which every path of the contract exists: each collection holds one item (or as many as its highest + /// index needs, items[2] → three), every item with the shape of all its uses; each value is the text "x". + /// + /// The data, as nested dictionaries and lists. + public IReadOnlyDictionary CreateWitness() + { + WitnessNode root = new WitnessNode(); + foreach (ContractEntry entry in Entries) + { + WitnessNode node = root; + foreach (string segment in entry.Path.Split('.')) + { + int bracket = segment.IndexOf('[', StringComparison.Ordinal); + if (bracket < 0) + { + node = node.Child(segment); + continue; + } + + // items[] (every item) or items[2] (one item): the same item shape, at least index + 1 items. + string index = segment[(bracket + 1)..^1]; + node = node.Child(segment[..bracket]).Item(index.Length == 0 ? 1 : int.Parse(index, System.Globalization.CultureInfo.InvariantCulture) + 1); + } + + if (entry.Usage == ContractUsage.Collection) + { + node.Item(); + } + } + + return root.ToData() as IReadOnlyDictionary ?? new Dictionary(StringComparer.Ordinal); + } + + private static string ComputeHash(IEnumerable entries) + { + StringBuilder text = new StringBuilder(); + foreach (ContractEntry entry in entries) + { + text.Append(entry.Usage.ToString().ToLowerInvariant()).Append(' ').Append(entry.Path).Append('\n'); + } + + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } + + /// + /// Collects the contract of a composed body: values, conditions and loop collections, with loop variables + /// resolved to canonical paths. + /// + internal static DataContract Collect(IEnumerable body) + { + List entries = new List(); + Walk(body, entries); + return new DataContract(entries); + } + + private static void Walk(IEnumerable blocks, List entries) + { + foreach (Block block in blocks) + { + switch (block) + { + case ParagraphBlock paragraph: + foreach (Inline inline in InlineConditional.Descendants(paragraph.Inlines)) + { + switch (inline) + { + case ValueInline value: + Add(entries, value.Path, ContractUsage.Value); + break; + case InlineConditional conditional: + foreach (TemplatePath path in conditional.Branches.SelectMany(b => b.Condition.Paths)) + { + Add(entries, path, ContractUsage.Condition); + } + + break; + case ExpressionInline expression: + foreach (TemplatePath path in expression.Condition.Paths) + { + Add(entries, path, ContractUsage.Condition); + } + + break; + } + } + + break; + + case ConditionalBlock conditional: + foreach (ConditionalBranch branch in conditional.Branches) + { + foreach (TemplatePath path in branch.Condition.Paths) + { + Add(entries, path, ContractUsage.Condition); + } + + Walk(branch.Body, entries); + } + + if (conditional.Else is { } otherwise) + { + Walk(otherwise, entries); + } + + break; + + case LoopBlock loop: + Add(entries, loop.Collection, ContractUsage.Collection); + Walk(loop.Body, entries); + break; + + case ComponentBlock component: + Walk(component.Body, entries); + break; + + case ListBlock list: + Walk(list.Items, entries); + break; + + case RawXmlBlock raw: + foreach (TemplatePath path in raw.Raw.Uses) + { + Add(entries, path, ContractUsage.Value); + } + + break; + + case TableBlock table: + WalkRows(table.Rows, entries); + break; + } + } + } + + private static void WalkRows(IEnumerable items, List entries) + { + foreach (TableRowItem item in items) + { + switch (item) + { + case TableRowModel row: + foreach (TableCellModel cell in row.Cells) + { + Walk(cell.Content, entries); + } + + break; + + case TableRowLoop loop: + Add(entries, loop.Collection, ContractUsage.Collection); + WalkRows(loop.Rows, entries); + break; + + case TableRowConditional conditional: + foreach ((Condition condition, List rows) in conditional.Branches) + { + foreach (TemplatePath path in condition.Paths) + { + Add(entries, path, ContractUsage.Condition); + } + + WalkRows(rows, entries); + } + + WalkRows(conditional.Else ?? [], entries); + break; + } + } + } + + private static void Add(List entries, TemplatePath path, ContractUsage usage) + { + if (!path.IsRoot && !path.IsMetadata) + { + entries.Add(new ContractEntry(Canonical(path), usage)); + } + } + + /// line.description in a loop over order.lines → order.lines[].description. + internal static string Canonical(TemplatePath path) + { + if (path.Scope is not { } scope) + { + return path.ToString(); + } + + string text = path.ToString(); + string rest = text.Length > scope.ItemName.Length ? text[scope.ItemName.Length..] : string.Empty; + return Canonical(scope.Collection) + "[]" + rest; + } + + /// A node of the witness tree: a dictionary, a one-item list, or a leaf. + private sealed class WitnessNode + { + private readonly Dictionary _children = new Dictionary(StringComparer.Ordinal); + private WitnessNode? _item; + private int _count; + + public WitnessNode Child(string name) + { + if (!_children.TryGetValue(name, out WitnessNode? child)) + { + child = new WitnessNode(); + _children[name] = child; + } + + return child; + } + + public WitnessNode Item(int count = 1) + { + _count = Math.Max(_count, count); + return _item ??= new WitnessNode(); + } + + public object? ToData() + { + if (_item != null) + { + return Enumerable.Range(0, _count).Select(_ => _item.ToData()).ToList(); + } + + if (_children.Count > 0) + { + return _children.ToDictionary(c => c.Key, c => c.Value.ToData(), StringComparer.Ordinal); + } + + return "x"; + } + } +} diff --git a/src/TriasDev.Templify.Builder/Experimental.cs b/src/TriasDev.Templify.Builder/Experimental.cs new file mode 100644 index 00000000..e1ffe49d --- /dev/null +++ b/src/TriasDev.Templify.Builder/Experimental.cs @@ -0,0 +1,6 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +// The builder packages are a preview (0.x): their API may change in any release, without the compatibility rules of +// the core library. Using them reports diagnostic TPLB001 until the consumer opts in (TPLB001). +[assembly: System.Diagnostics.CodeAnalysis.Experimental("TPLB001", UrlFormat = "https://github.com/TriasDev/templify/blob/main/docs/for-developers/template-builder.md#preview-status")] diff --git a/src/TriasDev.Templify.Builder/GeneratedDataPathsAttribute.cs b/src/TriasDev.Templify.Builder/GeneratedDataPathsAttribute.cs new file mode 100644 index 00000000..870ec8ba --- /dev/null +++ b/src/TriasDev.Templify.Builder/GeneratedDataPathsAttribute.cs @@ -0,0 +1,23 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.ComponentModel; + +namespace TriasDev.Templify.Builder; + +/// +/// Written by the typed path generator: this assembly has generated typed paths for . A project this +/// assembly gives access to its internals (for example its test project) uses them instead of generating them again. +/// +/// The data type. +/// True for the properties on LoopItem<T>, false for those on TemplatePath<T>. +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] +[EditorBrowsable(EditorBrowsableState.Never)] +public sealed class GeneratedDataPathsAttribute(Type type, bool loopItem) : Attribute +{ + /// Gets the data type. + public Type Type { get; } = type; + + /// Gets a value indicating whether the generated properties are on LoopItem<T>. + public bool LoopItem { get; } = loopItem; +} diff --git a/src/TriasDev.Templify.Builder/GeneratedTemplate.cs b/src/TriasDev.Templify.Builder/GeneratedTemplate.cs new file mode 100644 index 00000000..c7108bfd --- /dev/null +++ b/src/TriasDev.Templify.Builder/GeneratedTemplate.cs @@ -0,0 +1,70 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Security.Cryptography; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// +/// A built template: its bytes and what describes them. Hand it to a user as a download, or fill it with +/// . +/// +public sealed class GeneratedTemplate +{ + private readonly byte[] _content; + + internal GeneratedTemplate(TemplateFormat format, byte[] content, DataContract contract, TemplateStamp stamp, IReadOnlyList warnings) + { + Warnings = warnings; + Format = format; + _content = content; + Contract = contract; + Stamp = stamp; + ContentHash = Convert.ToHexStringLower(SHA256.HashData(content)); + } + + /// Gets the file format of the template. + public TemplateFormat Format { get; } + + /// Gets the file extension for the format, including the dot: .docx or .odt. + public string FileExtension => Format == TemplateFormat.Docx ? ".docx" : ".odt"; + + /// Gets the media type for the format, for example for an HTTP download. + public string MediaType => Format == TemplateFormat.Docx + ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + : "application/vnd.oasis.opendocument.text"; + + /// Gets the data the template needs: every path it prints, tests or loops over. + public DataContract Contract { get; } + + /// + /// Gets the warnings of the build: the template is valid, but something behaves differently than one might expect, + /// for example an ODT table of contents that LibreOffice does not rebuild on load. + /// + public IReadOnlyList Warnings { get; } + + /// Gets the stamp written into the template's document properties. + public TemplateStamp Stamp { get; } + + /// Gets the template's bytes. + public ReadOnlyMemory Content => _content; + + /// + /// Gets the SHA-256 of as lower-case hex. Builds are deterministic, so the hash can serve + /// as a cache key or an HTTP ETag. + /// + public string ContentHash { get; } + + /// Writes the template's bytes to a stream. + /// The stream to write to. + public void WriteTo(Stream destination) + { + ArgumentNullException.ThrowIfNull(destination); + destination.Write(_content); + } + + /// Opens a new read-only, seekable stream over the template's bytes. + /// A stream positioned at the start. + public Stream OpenRead() => new MemoryStream(_content, writable: false); +} diff --git a/src/TriasDev.Templify.Builder/ITemplateDefinition.cs b/src/TriasDev.Templify.Builder/ITemplateDefinition.cs new file mode 100644 index 00000000..34ef0b8c --- /dev/null +++ b/src/TriasDev.Templify.Builder/ITemplateDefinition.cs @@ -0,0 +1,23 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// Describes one template in code. runs on every build, +/// so one definition yields every language and format. +/// +/// +/// must not have side effects: a build is a pure function of the definition and the +/// . Pass product data that the template depends on, such as a customer's theme, +/// through the definition's constructor. +/// +public interface ITemplateDefinition +{ + /// Gets the identity of the template: a stable id and the version of its definition. + TemplateIdentity Identity { get; } + + /// Describes the template's content. + /// The composer to describe the template with. It is valid only during this call. + void Compose(TemplateComposer template); +} diff --git a/src/TriasDev.Templify.Builder/IfChain.cs b/src/TriasDev.Templify.Builder/IfChain.cs new file mode 100644 index 00000000..c5638936 --- /dev/null +++ b/src/TriasDev.Templify.Builder/IfChain.cs @@ -0,0 +1,177 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Continues a conditional started with : more conditions with , a +/// last part with . Nothing can follow , so the order Templify requires is the +/// only one that can be written. +/// +public sealed class IfChain +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly ConditionalBlock _block; + private readonly Func _isOpen; + + internal IfChain(BuildContext context, LoopScope? scope, ConditionalBlock block, Func isOpen) + { + _context = context; + _scope = scope; + _block = block; + _isOpen = isOpen; + } + + /// Adds a further condition, tested when the ones before it do not hold: {{#elseif …}}. + /// The condition. + /// Describes the blocks shown when the condition holds. + /// This chain. + public IfChain ElseIf(Condition condition, Action then) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(then); + EnsureOpen(); + BlockComposer.CheckCondition(_context, _scope, condition); + _block.Branches.Add(new ConditionalBranch(condition, BlockComposer.Compose(_context, _scope, then))); + return this; + } + + /// Adds the part shown when no condition holds: {{#else}}. It ends the chain. + /// Describes the blocks. + public void Else(Action otherwise) + { + ArgumentNullException.ThrowIfNull(otherwise); + EnsureOpen(); + _block.Else = BlockComposer.Compose(_context, _scope, otherwise); + } + + private void EnsureOpen() + { + if (_block.Else != null) + { + throw new InvalidOperationException("The conditional already has an else part; nothing can follow it."); + } + + if (!_isOpen()) + { + throw new InvalidOperationException("A conditional was continued outside the lambda it was started in."); + } + } +} + +/// +/// Describes the cases of : one per value, and a mandatory . +/// Valid only inside the lambda it is passed to. +/// +public sealed class SwitchComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly List<(IReadOnlyList Values, List Body)> _cases = new List<(IReadOnlyList, List)>(); + private List? _default; + private bool _isOpen = true; + + internal SwitchComposer(BuildContext context, LoopScope? scope) + { + _context = context; + _scope = scope; + } + + /// Adds a case for one value: value = "x". + /// The value. + /// Describes the blocks for this value. + /// This composer. + public SwitchComposer Case(string value, Action then) + { + ArgumentNullException.ThrowIfNull(value); + Case(new[] { value }, then); + return this; + } + + /// Adds a case for several values: value in ("x", "y"). + /// The values; at least one. + /// Describes the blocks for these values. + /// This composer. + public SwitchComposer Case(IEnumerable values, Action then) + { + ArgumentNullException.ThrowIfNull(values); + ArgumentNullException.ThrowIfNull(then); + EnsureOpen(); + string[] list = values.ToArray(); + if (list.Length == 0) + { + throw new ArgumentException("A case needs at least one value.", nameof(values)); + } + + foreach (string value in list) + { + ConditionText.String(value, nameof(values)); + } + + _cases.Add((list, BlockComposer.Compose(_context, _scope, then))); + return this; + } + + /// + /// Adds the part for every other value, including values added to the data later. Mandatory: a switch that maps + /// some values and prints nothing for the rest is a silent gap. + /// + /// Describes the blocks. + /// This composer. + public SwitchComposer Default(Action otherwise) + { + ArgumentNullException.ThrowIfNull(otherwise); + EnsureOpen(); + if (_default != null) + { + throw new InvalidOperationException("The switch already has a default."); + } + + _default = BlockComposer.Compose(_context, _scope, otherwise); + return this; + } + + /// Ends composing and returns the blocks: a conditional chain, or the default alone when there are no cases. + internal IEnumerable Close(TemplatePath value) + { + _isOpen = false; + + if (_default is null) + { + _context.Error( + DiagnosticCodes.SwitchWithoutDefault, + $"The switch on '{value.Text}' has no Default. Add one, so values without a case do not print nothing."); + } + + foreach (IGrouping duplicate in _cases.SelectMany(c => c.Values).GroupBy(v => v, StringComparer.Ordinal).Where(g => g.Count() > 1)) + { + _context.Error( + DiagnosticCodes.DuplicateSwitchCase, + $"The switch on '{value.Text}' has more than one case for \"{duplicate.Key}\"; only the first would ever apply."); + } + + if (_cases.Count == 0) + { + return _default ?? new List(); + } + + ConditionalBlock block = new ConditionalBlock { Else = _default }; + foreach ((IReadOnlyList values, List body) in _cases) + { + block.Branches.Add(new ConditionalBranch(values.Count == 1 ? value.Eq(values[0]) : value.In(values.ToArray()), body)); + } + + return new Block[] { block }; + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A switch composer was used outside the lambda it was passed to."); + } + } +} diff --git a/src/TriasDev.Templify.Builder/Images.cs b/src/TriasDev.Templify.Builder/Images.cs new file mode 100644 index 00000000..c223d812 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Images.cs @@ -0,0 +1,250 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Security.Cryptography; + +namespace TriasDev.Templify.Builder; + +/// +/// An image to place in a template: PNG or JPEG bytes, for example a customer's logo passed in as a theme slot. Its +/// pixel size and resolution are read from the file. +/// +public sealed class ImageSource +{ + private ImageSource(byte[] data, bool isPng, int pixelWidth, int pixelHeight, double dpiX, double dpiY) + { + Data = data; + IsPng = isPng; + PixelWidth = pixelWidth; + PixelHeight = pixelHeight; + DpiX = dpiX; + DpiY = dpiY; + Hash = Convert.ToHexStringLower(SHA256.HashData(data)); + } + + /// Gets the name the JSON form gives the image in its assets; null for a generated one (image-1). + public string? Name { get; private init; } + + /// The same image under a name, for the JSON form's assets ("logo": "sha256:…"). + /// The name: letters, digits, _, . or -. + /// The named image. + public ImageSource WithName(string name) + { + ArgumentNullException.ThrowIfNull(name); + if (!Json.AssetNames.IsValid(name)) + { + throw new ArgumentException($"'{name}' is not an asset name: use letters, digits, '_', '.' or '-'.", nameof(name)); + } + + return new ImageSource(Data, IsPng, PixelWidth, PixelHeight, DpiX, DpiY) { Name = name }; + } + + /// Gets the width in pixels. + public int PixelWidth { get; } + + /// Gets the height in pixels. + public int PixelHeight { get; } + + /// Gets the width at the image's own resolution (96 dpi when the file names none). + public Length NaturalWidth => Length.FromPoints(PixelWidth * 72.0 / DpiX); + + /// Gets the height at the image's own resolution (96 dpi when the file names none). + public Length NaturalHeight => Length.FromPoints(PixelHeight * 72.0 / DpiY); + + internal byte[] Data { get; } + + internal bool IsPng { get; } + + internal double DpiX { get; } + + internal double DpiY { get; } + + /// The SHA-256 of the bytes: equal images are stored once. + internal string Hash { get; } + + internal string Extension => IsPng ? "png" : "jpeg"; + + internal string MediaType => IsPng ? "image/png" : "image/jpeg"; + + /// A PNG image. + /// The file's bytes. + /// The image. + /// The bytes are not a PNG image. + public static ImageSource Png(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + return TryPng(data) ?? throw new ArgumentException("The bytes are not a PNG image.", nameof(data)); + } + + /// A JPEG image. + /// The file's bytes. + /// The image. + /// The bytes are not a JPEG image. + public static ImageSource Jpeg(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + return TryJpeg(data) ?? throw new ArgumentException("The bytes are not a JPEG image.", nameof(data)); + } + + /// A PNG or JPEG image, told apart by its signature (for uploads of unknown type). + /// The file's bytes. + /// The image. + /// The bytes are neither a PNG nor a JPEG image. + public static ImageSource FromBytes(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + return TryPng(data) ?? TryJpeg(data) ?? throw new ArgumentException("The bytes are neither a PNG nor a JPEG image.", nameof(data)); + } + + private static ImageSource? TryPng(byte[] data) + { + ReadOnlySpan signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + if (data.Length < 33 || !data.AsSpan(0, 8).SequenceEqual(signature) || !data.AsSpan(12, 4).SequenceEqual("IHDR"u8)) + { + return null; + } + + int width = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(16, 4)); + int height = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(20, 4)); + double dpiX = 96; + double dpiY = 96; + + // pHYs (pixels per metre, unit 1) before the image data. + for (int offset = 8; offset + 12 <= data.Length;) + { + int length = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(offset, 4)); + if (length < 0 || offset + 12 + length > data.Length) + { + break; + } + + ReadOnlySpan type = data.AsSpan(offset + 4, 4); + if (type.SequenceEqual("pHYs"u8) && length >= 9 && data[offset + 16] == 1) + { + int ppmX = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(offset + 8, 4)); + int ppmY = BinaryPrimitives.ReadInt32BigEndian(data.AsSpan(offset + 12, 4)); + if (ppmX > 0 && ppmY > 0) + { + dpiX = ppmX * 0.0254; + dpiY = ppmY * 0.0254; + } + } + + if (type.SequenceEqual("IDAT"u8)) + { + break; + } + + offset += 12 + length; + } + + return width > 0 && height > 0 ? new ImageSource(data.ToArray(), true, width, height, dpiX, dpiY) : null; + } + + private static ImageSource? TryJpeg(byte[] data) + { + if (data.Length < 4 || data[0] != 0xFF || data[1] != 0xD8) + { + return null; + } + + double dpiX = 96; + double dpiY = 96; + int offset = 2; + while (offset + 4 <= data.Length) + { + if (data[offset] != 0xFF) + { + return null; + } + + byte marker = data[offset + 1]; + int length = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(offset + 2, 2)); + if (marker == 0xE0 && length >= 14 && offset + 16 <= data.Length && data.AsSpan(offset + 4, 5).SequenceEqual("JFIF\0"u8)) + { + byte units = data[offset + 11]; + int densityX = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(offset + 12, 2)); + int densityY = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(offset + 14, 2)); + if (units is 1 or 2 && densityX > 0 && densityY > 0) + { + dpiX = units == 1 ? densityX : densityX * 2.54; + dpiY = units == 1 ? densityY : densityY * 2.54; + } + } + + // Start of frame (baseline, progressive, …); C4, C8 and CC are not frames. + if (marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC) && offset + 9 <= data.Length) + { + int height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(offset + 5, 2)); + int width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(offset + 7, 2)); + return width > 0 && height > 0 ? new ImageSource(data.ToArray(), false, width, height, dpiX, dpiY) : null; + } + + offset += 2 + length; + } + + return null; + } +} + +/// How an image is sized: its natural size, a given width or height, or fitted into a box. The aspect ratio is always kept. +public sealed class ImageFit +{ + private readonly Length? _width; + private readonly Length? _height; + private readonly bool _exact; + + private ImageFit(Length? width, Length? height, bool exact = false) + { + _width = width; + _height = height; + _exact = exact; + } + + /// Gets the image's natural size (its pixels at its own resolution). + public static ImageFit Natural { get; } = new ImageFit(null, null); + + /// A given width; the height follows. + /// The width. + /// The fit. + public static ImageFit Width(Length width) => new ImageFit(StyleRanges.Positive(width, nameof(width)), null); + + /// A given height; the width follows. + /// The height. + /// The fit. + public static ImageFit Height(Length height) => new ImageFit(null, StyleRanges.Positive(height, nameof(height))); + + /// As large as fits into a box, for example a logo area. + /// The box width. + /// The box height. + /// The fit. + public static ImageFit Within(Length width, Length height) => + new ImageFit(StyleRanges.Positive(width, nameof(width)), StyleRanges.Positive(height, nameof(height))); + + /// The image at exactly this size, stretched if the proportions differ. + /// The width. + /// The height. + /// The fit. + public static ImageFit Exact(Length width, Length height) => + new ImageFit(StyleRanges.Positive(width, nameof(width)), StyleRanges.Positive(height, nameof(height)), exact: true); + + /// The size of an image under this fit. + internal (Length Width, Length Height) Resolve(ImageSource image) + { + if (_exact) + { + return (_width!.Value, _height!.Value); + } + + double ratio = image.NaturalHeight.Points / image.NaturalWidth.Points; + return (_width, _height) switch + { + ({ } w, { } h) when h.Points / w.Points < ratio => (Length.FromPoints(h.Points / ratio), h), + ({ } w, { }) => (w, Length.FromPoints(w.Points * ratio)), + ({ } w, null) => (w, Length.FromPoints(w.Points * ratio)), + (null, { } h) => (Length.FromPoints(h.Points / ratio), h), + _ => (image.NaturalWidth, image.NaturalHeight), + }; + } +} diff --git a/src/TriasDev.Templify.Builder/InlineComposer.cs b/src/TriasDev.Templify.Builder/InlineComposer.cs new file mode 100644 index 00000000..95a867fc --- /dev/null +++ b/src/TriasDev.Templify.Builder/InlineComposer.cs @@ -0,0 +1,306 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Describes the content of one paragraph. Valid only inside the lambda it is passed to. +/// +public sealed class InlineComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly List _inlines = new List(); + private bool _isOpen = true; + + internal InlineComposer(BuildContext context, LoopScope? scope) + { + _context = context; + _scope = scope; + } + + /// Adds literal text in the paragraph's formatting. + /// The text. Tabs and line breaks become the format's tab and line break. + /// This composer. + public InlineComposer Text(string text) => AddText(text, null); + + /// Adds literal text in a character style. + /// The character style; the style sheet must define it. + /// The text. Tabs and line breaks become the format's tab and line break. + /// This composer. + public InlineComposer Text(CharacterStyleKey style, string text) + { + ArgumentNullException.ThrowIfNull(style); + AddText(text, style); + return this; + } + + /// Adds a value from the data: {{path}}. + /// The data path of the value. + /// This composer. + public InlineComposer Value(TemplatePath path) => AddValue(path, null, null); + + /// Adds a formatted value from the data, for example {{order.date:date:yyyy-MM-dd}}. + /// The data path of the value. + /// How Templify formats the value. + /// This composer. + public InlineComposer Value(TemplatePath path, ValueFormat format) + { + ArgumentNullException.ThrowIfNull(format); + AddValue(path, format, null); + return this; + } + + /// Adds a value from the data in a character style. + /// The character style; the style sheet must define it. + /// The data path of the value. + /// This composer. + public InlineComposer Value(CharacterStyleKey style, TemplatePath path) + { + ArgumentNullException.ThrowIfNull(style); + AddValue(path, null, style); + return this; + } + + /// Adds a formatted value from the data in a character style. + /// The character style; the style sheet must define it. + /// The data path of the value. + /// How Templify formats the value. + /// This composer. + public InlineComposer Value(CharacterStyleKey style, TemplatePath path, ValueFormat format) + { + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(style); + AddValue(path, format, style); + return this; + } + + /// Adds a tab. + /// This composer. + public InlineComposer Tab() => AddText("\t", null); + + /// Adds a line break inside the paragraph. + /// This composer. + public InlineComposer LineBreak() => AddText("\n", null); + + /// + /// Adds a tab to a right-aligned tab stop at the end of the text frame, for example to push an amount or a page + /// number to the right margin. + /// + /// This composer. + public InlineComposer TabRight() + { + EnsureOpen(); + _inlines.Add(new RightTabInline()); + return this; + } + + /// + /// Adds text shown only when a condition holds, inside this paragraph: {{#if …}}…{{/if}}. Continue with + /// and . + /// + /// The condition. + /// Describes the text shown when it holds. + /// The chain, to add elseif and else parts. + public InlineIfChain If(Condition condition, Action then) + { + EnsureOpen(); + return InlineIfChain.Start(_context, _scope, _inlines, condition, then, () => _isOpen); + } + + /// + /// Adds the result of a condition, for example as Yes/No: {{(condition):yesno}}. Inline expressions use the + /// engine's stricter dialect: only true is truthy. + /// + /// The condition. + /// A boolean format such as or . + /// This composer. + public InlineComposer Expression(Condition condition, ValueFormat format) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(format); + EnsureOpen(); + BlockComposer.CheckCondition(_context, _scope, condition); + _inlines.Add(new ExpressionInline(condition, format)); + return this; + } + + /// Adds an image at its natural size, inline with the text. + /// The image. + /// The text that describes the image (accessibility); required. + /// This composer. + public InlineComposer Image(ImageSource image, string altText) => Image(image, altText, ImageFit.Natural); + + /// Adds an image inline with the text. + /// The image. + /// The text that describes the image (accessibility); required. + /// How the image is sized; the aspect ratio is kept. + /// This composer. + public InlineComposer Image(ImageSource image, string altText, ImageFit fit) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentNullException.ThrowIfNull(fit); + EnsureOpen(); + _inlines.Add(CreateImage(image, altText, fit)); + return this; + } + + internal static ImageInline CreateImage(ImageSource image, string altText, ImageFit fit) + { + ArgumentNullException.ThrowIfNull(altText); + if (string.IsNullOrWhiteSpace(altText) || altText.Any(c => char.IsControl(c) && c is not ('\t' or '\n' or '\r'))) + { + throw new ArgumentException("An image needs an alternative text without control characters.", nameof(altText)); + } + + (Length width, Length height) = fit.Resolve(image); + return new ImageInline(image, altText, width, height); + } + + /// Adds the current page number (a field Word and LibreOffice update). + /// This composer. + public InlineComposer PageNumber() => AddField(PageField.Number, null); + + /// Adds the current page number in a character style. + /// The character style; the style sheet must define it. + /// This composer. + public InlineComposer PageNumber(CharacterStyleKey style) + { + ArgumentNullException.ThrowIfNull(style); + AddField(PageField.Number, style); + return this; + } + + /// Adds the number of pages (a field Word and LibreOffice update). + /// This composer. + public InlineComposer PageCount() => AddField(PageField.Count, null); + + /// Adds the number of pages in a character style. + /// The character style; the style sheet must define it. + /// This composer. + public InlineComposer PageCount(CharacterStyleKey style) + { + ArgumentNullException.ThrowIfNull(style); + AddField(PageField.Count, style); + return this; + } + + internal static ValueInline CreateValue(BuildContext context, LoopScope? scope, TemplatePath path, ValueFormat? format = null, CharacterStyleKey? style = null) + { + LoopScope.CheckUse(context, scope, path); + if (path.IsRoot) + { + context.Error( + DiagnosticCodes.EmptyValuePath, + "A value placeholder was given the root of the data (template.Data or default(TemplatePath)); append a segment, for example template.Data[\"customer\"][\"name\"]."); + } + + return new ValueInline(path, format, style); + } + + /// + /// Reports literal text that contains {{, also across adjacent pieces of text: Templify would read it as the + /// start of a placeholder, and Templify has no escape for it. + /// + internal static void CheckLiteralText(BuildContext context, IReadOnlyList inlines) + { + StringBuilder literal = new StringBuilder(); + foreach (Inline inline in inlines) + { + if (inline is TextInline text) + { + literal.Append(text.Text); + continue; + } + + Check(literal); + literal.Clear(); + } + + Check(literal); + + void Check(StringBuilder text) + { + string value = text.ToString(); + if (value.Contains("{{", StringComparison.Ordinal)) + { + context.Error( + DiagnosticCodes.LiteralOpenBraces, + $"Literal text contains '{{{{', which Templify reads as the start of a placeholder: \"{value}\". Write values with Value(path), not as text (a path interpolated into a string, $\"…{{path}}\", is written this way too)."); + } + } + } + + internal IReadOnlyList Close() + { + _isOpen = false; + CheckLiteralText(_context, _inlines); + return _inlines; + } + + /// + /// Literal text as inlines. A tab or a line break is an inline of its own, also inside a longer text: Text("a\tb") + /// is Text("a"), Tab(), Text("b"), and so is the paragraph "a\tb", so the JSON form writes all of them as "a\tb". + /// + internal static List TextInlines(string text, CharacterStyleKey? style) + { + text = text.Replace("\r\n", "\n", StringComparison.Ordinal); // a Windows line break is one break + List inlines = new List(); + int start = 0; + for (int i = 0; i <= text.Length; i++) + { + if (i < text.Length && text[i] is not ('\t' or '\n')) + { + continue; + } + + if (i > start) + { + inlines.Add(new TextInline(text[start..i], style)); + } + + if (i < text.Length) + { + inlines.Add(new TextInline(text[i].ToString(), style)); + } + + start = i + 1; + } + + return inlines; + } + + private InlineComposer AddText(string text, CharacterStyleKey? style) + { + ArgumentNullException.ThrowIfNull(text); + EnsureOpen(); + _inlines.AddRange(TextInlines(text, style)); + return this; + } + + private InlineComposer AddField(PageField field, CharacterStyleKey? style) + { + EnsureOpen(); + _inlines.Add(new PageFieldInline(field, style)); + return this; + } + + private InlineComposer AddValue(TemplatePath path, ValueFormat? format, CharacterStyleKey? style) + { + EnsureOpen(); + _inlines.Add(CreateValue(_context, _scope, path, format, style)); + return this; + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException( + "An inline composer was used outside the lambda it was passed to."); + } + } +} diff --git a/src/TriasDev.Templify.Builder/InlineConditionals.cs b/src/TriasDev.Templify.Builder/InlineConditionals.cs new file mode 100644 index 00000000..1b5b343d --- /dev/null +++ b/src/TriasDev.Templify.Builder/InlineConditionals.cs @@ -0,0 +1,184 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Describes the text of one branch of an inline conditional: literal text and values (and nested inline +/// conditionals). Images, tabs and breaks are not available here. Valid only inside the lambda it is passed to. +/// +public sealed class TextComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly List _inlines = new List(); + private bool _isOpen = true; + + internal TextComposer(BuildContext context, LoopScope? scope) + { + _context = context; + _scope = scope; + } + + /// Adds literal text. + /// The text. + /// This composer. + public TextComposer Text(string text) => AddText(text, null); + + /// Adds literal text in a character style. + /// The character style; the style sheet must define it. + /// The text. + /// This composer. + public TextComposer Text(CharacterStyleKey style, string text) + { + ArgumentNullException.ThrowIfNull(style); + return AddText(text, style); + } + + /// Adds a value from the data. + /// The data path. + /// This composer. + public TextComposer Value(TemplatePath path) => AddValue(path, null, null); + + /// Adds a formatted value from the data. + /// The data path. + /// How Templify formats the value. + /// This composer. + public TextComposer Value(TemplatePath path, ValueFormat format) + { + ArgumentNullException.ThrowIfNull(format); + return AddValue(path, format, null); + } + + /// Adds a value from the data in a character style. + /// The character style. + /// The data path. + /// This composer. + public TextComposer Value(CharacterStyleKey style, TemplatePath path) + { + ArgumentNullException.ThrowIfNull(style); + return AddValue(path, null, style); + } + + /// Adds a nested inline conditional. + /// The condition. + /// Describes the text shown when it holds. + /// The chain, to add elseif and else parts. + public InlineIfChain If(Condition condition, Action then) + { + EnsureOpen(); + return InlineIfChain.Start(_context, _scope, _inlines, condition, then, () => _isOpen); + } + + internal IReadOnlyList Close() + { + _isOpen = false; + InlineComposer.CheckLiteralText(_context, _inlines); + return _inlines; + } + + private TextComposer AddText(string text, CharacterStyleKey? style) + { + ArgumentNullException.ThrowIfNull(text); + EnsureOpen(); + if (text.Any(c => c is '\t' or '\n' or '\r')) + { + throw new ArgumentException("Inline conditional text cannot hold tabs or line breaks; use a block conditional.", nameof(text)); + } + + if (text.Length > 0) + { + _inlines.Add(new TextInline(text, style)); + } + + return this; + } + + private TextComposer AddValue(TemplatePath path, ValueFormat? format, CharacterStyleKey? style) + { + EnsureOpen(); + _inlines.Add(InlineComposer.CreateValue(_context, _scope, path, format, style)); + return this; + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A text composer was used outside the lambda it was passed to."); + } + } +} + +/// Continues an inline conditional: and a last . +public sealed class InlineIfChain +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly InlineConditional _conditional; + private readonly Func _isOpen; + + private InlineIfChain(BuildContext context, LoopScope? scope, InlineConditional conditional, Func isOpen) + { + _context = context; + _scope = scope; + _conditional = conditional; + _isOpen = isOpen; + } + + /// Adds text for a further condition: {{#elseif …}}. + /// The condition. + /// Describes the text. + /// This chain. + public InlineIfChain ElseIf(Condition condition, Action then) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(then); + EnsureOpen(); + BlockComposer.CheckCondition(_context, _scope, condition); + _conditional.Branches.Add((condition, Compose(_context, _scope, then))); + return this; + } + + /// Adds the text shown when no condition holds: {{#else}}. It ends the chain. + /// Describes the text. + public void Else(Action otherwise) + { + ArgumentNullException.ThrowIfNull(otherwise); + EnsureOpen(); + _conditional.Else = Compose(_context, _scope, otherwise); + } + + internal static InlineIfChain Start(BuildContext context, LoopScope? scope, List target, Condition condition, Action then, Func isOpen) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(then); + BlockComposer.CheckCondition(context, scope, condition); + InlineConditional conditional = new InlineConditional(); + conditional.Branches.Add((condition, Compose(context, scope, then))); + target.Add(conditional); + return new InlineIfChain(context, scope, conditional, isOpen); + } + + private static IReadOnlyList Compose(BuildContext context, LoopScope? scope, Action text) + { + TextComposer composer = new TextComposer(context, scope); + text(composer); + return composer.Close(); + } + + private void EnsureOpen() + { + if (_conditional.Else != null) + { + throw new InvalidOperationException("The inline conditional already has an else part; nothing can follow it."); + } + + if (!_isOpen()) + { + throw new InvalidOperationException("An inline conditional was continued outside the lambda it was started in."); + } + } +} diff --git a/src/TriasDev.Templify.Builder/Json/AssetNames.cs b/src/TriasDev.Templify.Builder/Json/AssetNames.cs new file mode 100644 index 00000000..016befc9 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/AssetNames.cs @@ -0,0 +1,22 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder.Json; + +/// Names of the JSON form's assets ("logo": "sha256:…"). +internal static partial class AssetNames +{ + public static bool IsValid(string name) => Pattern().IsMatch(name); + + /// A name made from free text (a font family): letters and digits kept, everything else a dash. + public static string From(string text) + { + string name = Regex.Replace(text, "[^A-Za-z0-9_.-]+", "-").Trim('-'); + return name.Length == 0 ? "asset" : name; + } + + [GeneratedRegex("^[A-Za-z0-9_.-]+$")] + private static partial Regex Pattern(); +} diff --git a/src/TriasDev.Templify.Builder/Json/ConditionParser.cs b/src/TriasDev.Templify.Builder/Json/ConditionParser.cs new file mode 100644 index 00000000..75d1f8a6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/ConditionParser.cs @@ -0,0 +1,409 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Reads a condition in Templify's syntax, as the builder writes it, back into a . The +/// conditions are built through 's methods, so the same rules apply as in C#. +/// +/// +/// Grammar (loosest first): or, and, not, then a path with an optional comparison +/// (= != > >= < <=, in (…), contains, startswith, endswith) or postfix +/// (exists, is empty, is not empty), or a parenthesised condition. Literals are double-quoted +/// strings (\" and \\ escapes) or invariant numbers; a bare word is never a literal: after a comparison or +/// string operator a word with a dot or an index, or an escaped word ([limit]), is a path (a.id = b.id, #297). +/// +internal static class ConditionParser +{ + private static readonly HashSet _keywords = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "and", "or", "not", "in", "is", "empty", "exists", "contains", "startswith", "endswith", + }; + + /// Parses a condition. + /// The condition text. + /// Turns a path as written (keyword escapes removed) into a path with its loop scope. + /// The condition. + /// The text is not a condition; the message names the 0-based column. + public static Condition Parse(string text, Func resolvePath) + { + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(resolvePath); + Parser parser = new Parser(Tokenize(text), text.Length, resolvePath); + Condition condition = parser.Or(); + parser.ExpectEnd(); + return condition; + } + + private enum Kind + { + Word, + String, + Number, + Operator, + Open, + Close, + Comma, + } + + private sealed record Token(Kind Kind, string Text, int Column, string? Value = null); + + private static List Tokenize(string text) + { + List tokens = new List(); + int i = 0; + while (i < text.Length) + { + char c = text[i]; + if (char.IsWhiteSpace(c)) + { + i++; + continue; + } + + int start = i; + switch (c) + { + case '(': + tokens.Add(new Token(Kind.Open, "(", i++)); + continue; + case ')': + tokens.Add(new Token(Kind.Close, ")", i++)); + continue; + case ',': + tokens.Add(new Token(Kind.Comma, ",", i++)); + continue; + case '"': + tokens.Add(ReadString(text, ref i)); + continue; + case '=': + // "==" is "=", as in Templify. + tokens.Add(new Token(Kind.Operator, "=", i)); + i += i + 1 < text.Length && text[i + 1] == '=' ? 2 : 1; + continue; + case '!' or '>' or '<': + i++; + if (i < text.Length && text[i] == '=') + { + i++; + } + else if (c == '!') + { + throw Error("'!' must be followed by '='", start); + } + + tokens.Add(new Token(Kind.Operator, text[start..i], start)); + continue; + } + + while (i < text.Length && !char.IsWhiteSpace(text[i]) && text[i] is not ('(' or ')' or ',' or '"' or '=' or '!' or '>' or '<')) + { + i++; + } + + if (i == start) + { + throw Error($"unexpected '{c}'", start); + } + + string word = text[start..i]; + bool number = decimal.TryParse(word, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out _); + tokens.Add(new Token(number ? Kind.Number : Kind.Word, word, start)); + } + + return tokens; + } + + private static Token ReadString(string text, ref int i) + { + int start = i++; + StringBuilder value = new StringBuilder(); + while (i < text.Length) + { + char c = text[i++]; + if (c == '"') + { + return new Token(Kind.String, text[start..i], start, value.ToString()); + } + + if (c == '\\' && i < text.Length && text[i] is '"' or '\\') + { + value.Append(text[i++]); + continue; + } + + value.Append(c); + } + + throw Error("the string is not closed", start); + } + + private static FormatException Error(string message, int column) => + new FormatException($"Condition: {message} at column {column.ToString(CultureInfo.InvariantCulture)}."); + + private sealed class Parser(List tokens, int length, Func resolvePath) + { + private int _position; + + private Token? Current => _position < tokens.Count ? tokens[_position] : null; + + private int Column => Current?.Column ?? length; + + public void ExpectEnd() + { + if (Current is { } token) + { + throw Error($"unexpected '{token.Text}'", token.Column); + } + } + + public Condition Or() + { + Condition left = And(); + while (IsKeyword("or")) + { + _position++; + left = left | And(); + } + + return left; + } + + private Condition And() + { + Condition left = Unary(); + while (IsKeyword("and")) + { + _position++; + left = left & Unary(); + } + + return left; + } + + private Condition Unary() + { + // Iterative, so a long chain of 'not' cannot exhaust the stack. + int nots = 0; + while (IsKeyword("not")) + { + _position++; + nots++; + } + + Condition condition = Primary(); + for (int i = 0; i < nots; i++) + { + condition = !condition; + } + + return condition; + } + + private Condition Primary() + { + Token token = Current ?? throw Error("a condition is missing", length); + if (token.Kind == Kind.Open) + { + _position++; + Condition inner = Or(); + Expect(Kind.Close, "')'"); + return inner; + } + + if (token.Kind != Kind.Word || (_keywords.Contains(token.Text) && !token.Text.StartsWith('['))) + { + throw Error($"a path is expected, not '{token.Text}'", token.Column); + } + + _position++; + TemplatePath path = Resolve(token); + return Rest(path); + } + + private Condition Rest(TemplatePath path) + { + Token? next = Current; + if (next is { Kind: Kind.Operator }) + { + _position++; + return Comparison(path, next); + } + + if (next is not { Kind: Kind.Word }) + { + return path; + } + + switch (next.Text.ToLowerInvariant()) + { + case "in": + _position++; + return In(path); + case "contains": + _position++; + return OtherPath() is { } containsPath ? path.Contains(containsPath) : path.Contains(StringLiteral(next.Text)); + case "startswith": + _position++; + return OtherPath() is { } prefixPath ? path.StartsWith(prefixPath) : path.StartsWith(StringLiteral(next.Text)); + case "endswith": + _position++; + return OtherPath() is { } suffixPath ? path.EndsWith(suffixPath) : path.EndsWith(StringLiteral(next.Text)); + case "exists": + _position++; + return path.Exists; + case "is": + _position++; + if (IsKeyword("not")) + { + _position++; + ExpectKeyword("empty"); + return path.IsNotEmpty; + } + + ExpectKeyword("empty"); + return path.IsEmpty; + default: + return path; + } + } + + private Condition Comparison(TemplatePath path, Token op) + { + if (OtherPath() is { } other) + { + return op.Text switch + { + "=" => path.Eq(other), + "!=" => path.NotEq(other), + ">" => path.Gt(other), + ">=" => path.Ge(other), + "<" => path.Lt(other), + _ => path.Le(other), + }; + } + + Token literal = Literal(); + if (literal.Kind == Kind.String) + { + return op.Text switch + { + "=" => path.Eq(literal.Value!), + "!=" => path.NotEq(literal.Value!), + _ => throw Error($"'{op.Text}' compares with a number, not a string", literal.Column), + }; + } + + double number = double.Parse(literal.Text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + return op.Text switch + { + "=" => path.Eq(number), + "!=" => path.NotEq(number), + ">" => path.Gt(number), + ">=" => path.Ge(number), + "<" => path.Lt(number), + _ => path.Le(number), + }; + } + + /// + /// A path as the right operand (#297): a word with a dot or an index (owner.id, items[0]), loop + /// metadata (@index) or an escaped word ([limit]). A plain word stays an error: it is most likely a literal without quotes. + /// + private TemplatePath? OtherPath() + { + if (Current is not { Kind: Kind.Word } token + || !(token.Text.Contains('.', StringComparison.Ordinal) || token.Text.Contains('[', StringComparison.Ordinal) || token.Text.StartsWith('@'))) + { + return null; + } + + _position++; + return Resolve(token); + } + + private Condition In(TemplatePath path) + { + Expect(Kind.Open, "'('"); + List values = new List { StringLiteral("in") }; + while (Current is { Kind: Kind.Comma }) + { + _position++; + values.Add(StringLiteral("in")); + } + + Expect(Kind.Close, "')'"); + return path.In(values.ToArray()); + } + + private string StringLiteral(string op) + { + Token literal = Literal(); + return literal.Kind == Kind.String + ? literal.Value! + : throw Error($"'{op}' takes a quoted string, not {literal.Text}", literal.Column); + } + + private Token Literal() + { + Token token = Current ?? throw Error("a value is missing", length); + if (token.Kind == Kind.Word) + { + throw Error($"'{token.Text}' is not a value: quote the literal (\"{token.Text}\"), or write [{token.Text}] to compare with that top-level value", token.Column); + } + + if (token.Kind is not (Kind.String or Kind.Number)) + { + throw Error($"a value is expected, not '{token.Text}'", token.Column); + } + + _position++; + return token; + } + + private TemplatePath Resolve(Token token) + { + string text = token.Text; + if (text.StartsWith('[') && text.EndsWith(']') && text.IndexOf('[', 1) < 0) + { + text = text[1..^1]; + } + + try + { + return resolvePath(text); + } + catch (ArgumentException exception) + { + throw Error($"'{token.Text}' is not a path ({exception.Message})", token.Column); + } + } + + private bool IsKeyword(string keyword) => + Current is { Kind: Kind.Word } token && string.Equals(token.Text, keyword, StringComparison.OrdinalIgnoreCase); + + private void ExpectKeyword(string keyword) + { + if (!IsKeyword(keyword)) + { + throw Error($"'{keyword}' is expected", Column); + } + + _position++; + } + + private void Expect(Kind kind, string what) + { + if (Current?.Kind != kind) + { + throw Error($"{what} is expected", Column); + } + + _position++; + } + } +} diff --git a/src/TriasDev.Templify.Builder/Json/EmbeddedTexts.cs b/src/TriasDev.Templify.Builder/Json/EmbeddedTexts.cs new file mode 100644 index 00000000..8a188824 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/EmbeddedTexts.cs @@ -0,0 +1,106 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// The texts section of a JSON definition: {"title": {"de": "…", "en": "…"}}. Looked up like +/// (de-DE finds de). +/// +internal sealed class EmbeddedTexts +{ + private EmbeddedTexts(IReadOnlyList sections, ITextCatalog catalog) + { + Sections = sections; + Catalog = catalog; + } + + /// Gets an empty section. + public static EmbeddedTexts None { get; } = new EmbeddedTexts([], TextCatalog.Empty); + + /// Gets the keys and their translations exactly as in the file (re-exported unchanged). + public IReadOnlyList Sections { get; } + + /// Gets the texts as a catalog. + public ITextCatalog Catalog { get; } + + /// + /// Reads the section of a definition: key first, {"title": {"de": "…", "en": "…"}}. Every key has the languages + /// of the others (a regional language is covered by its parent); a key the section does not have comes from the host's + /// catalog (TB5001 when that has none either). Malformed parts are reported to and skipped. + /// + public static EmbeddedTexts Read(JsonElement root, Action? fail = null) + { + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("texts", out JsonElement texts)) + { + return None; + } + + if (texts.ValueKind != JsonValueKind.Object) + { + fail?.Invoke("/texts", "The texts are an object of keys, for example { \"title\": { \"de\": \"…\", \"en\": \"…\" } }."); + return None; + } + + List entries = new List(); + Dictionary> byKey = new Dictionary>(StringComparer.Ordinal); + foreach (JsonProperty key in texts.EnumerateObject()) + { + string at = "/texts/" + JsonComposition.Escape(key.Name); + if (key.Value.ValueKind != JsonValueKind.Object) + { + fail?.Invoke(at, "A text is an object of languages, for example { \"de\": \"Titel\", \"en\": \"Title\" }."); + continue; + } + + List> translations = new List>(); + foreach (JsonProperty language in key.Value.EnumerateObject()) + { + if (language.Value.ValueKind != JsonValueKind.String) + { + fail?.Invoke(at + "/" + JsonComposition.Escape(language.Name), "A translation is a string."); + continue; + } + + if (translations.Any(t => string.Equals(t.Key, language.Name, StringComparison.OrdinalIgnoreCase))) + { + fail?.Invoke(at, $"The language '{language.Name}' appears twice in the text '{key.Name}'."); + continue; + } + + translations.Add(new KeyValuePair(language.Name, language.Value.GetString()!)); + } + + entries.Add(new TextSection(key.Name, translations)); + byKey[key.Name] = translations.ToDictionary(t => t.Key, t => t.Value, StringComparer.OrdinalIgnoreCase); + } + + // Every text has the languages of the others, so an added key cannot miss a language without a word. A regional + // language is covered by its parent ("de-CH" by "de"), as the build looks it up. + List languages = entries.SelectMany(e => e.Translations.Select(t => t.Key)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + foreach (TextSection entry in entries) + { + HashSet own = entry.Translations.Select(t => t.Key).ToHashSet(StringComparer.OrdinalIgnoreCase); + List missing = languages.Where(l => !LanguageChain(l).Any(own.Contains)).ToList(); + if (missing.Count > 0) + { + fail?.Invoke( + "/texts/" + JsonComposition.Escape(entry.Key), + $"The text '{entry.Key}' has no {string.Join(", ", missing.Select(l => $"'{l}'"))} translation; every text has the languages of the others ({string.Join(", ", languages)})."); + } + } + + return new EmbeddedTexts(entries, TextCatalog.FromDictionary(byKey)); + } + + /// A language name and its parents: de-CH, de. + private static IEnumerable LanguageChain(string language) + { + for (string name = language; name.Length > 0; name = name.LastIndexOf('-') is int dash and > 0 ? name[..dash] : string.Empty) + { + yield return name; + } + } +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonDefinition.cs b/src/TriasDev.Templify.Builder/Json/JsonDefinition.cs new file mode 100644 index 00000000..ce5671c0 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonDefinition.cs @@ -0,0 +1,1863 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Xml; +using System.Xml.Linq; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// A definition read from JSON. replays the JSON through the same composers the fluent API +/// uses, so every rule is checked once and reported like a C# definition's, with the JSON pointer as location. +/// +/// +/// Problems are reported, never thrown: a malformed element (unknown key or kind, wrong value type, unknown asset) +/// is TB9200 at its pointer, a value a composer rejects is TB9201, raw XML without permission TB9202. The element is +/// skipped and composing goes on, so one build lists every problem. +/// +internal sealed class JsonDefinition(JsonElement root, TemplateIdentity identity, TemplateJsonImportOptions options) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = identity; + + /// Gets the definition's own translations (its texts section). + internal EmbeddedTexts Texts { get; } = EmbeddedTexts.Read(root); + + /// Composes through a fresh : the definition holds no per-build state, so one import can be built concurrently. + public void Compose(TemplateComposer template) => new JsonComposition(root, Identity, options, Texts).Compose(template); +} + +/// One composition of a JSON definition: the loop scope and diagnostics of a single build. +internal sealed class JsonComposition +{ + private readonly JsonElement _source; + private readonly TemplateJsonImportOptions _options; + private readonly EmbeddedTexts _texts; + + /// The parameters of a component reference without params. + private static readonly JsonElement _noParameters = JsonDocument.Parse("{}").RootElement.Clone(); + private JsonElement _root; + private readonly Dictionary _paragraphStyles = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _characterStyles = new Dictionary(StringComparer.Ordinal); + private readonly List<(string Name, LoopItem Item)> _scope = new List<(string, LoopItem)>(); + private readonly HashSet _sectionNames = new HashSet(StringComparer.Ordinal); + private readonly Dictionary _assetsByName = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _themeColors = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _themeFonts = new Dictionary(StringComparer.Ordinal); + private BuildContext _context = null!; + private TemplateComposer _template = null!; + + public JsonComposition(JsonElement root, TemplateIdentity identity, TemplateJsonImportOptions options, EmbeddedTexts texts) + { + _texts = texts; + _source = root; + _root = root; + Identity = identity; + _options = options; + if (_root.TryGetProperty("styles", out JsonElement styles) && styles.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty style in Members(styles, "paragraph")) + { + _paragraphStyles[style.Name] = style.Name == BuilderStyles.TemplateMarker.Id + ? BuilderStyles.TemplateMarker + : new ParagraphStyleKey(style.Name, PlainString(style.Value, "name") ?? style.Name); + } + + foreach (JsonProperty style in Members(styles, "character")) + { + _characterStyles[style.Name] = new CharacterStyleKey(style.Name, PlainString(style.Value, "name") ?? style.Name); + } + } + } + + public TemplateIdentity Identity { get; } + + public void Compose(TemplateComposer template) + { + _template = template; + _context = template.Context; + _scope.Clear(); + _sectionNames.Clear(); + foreach (object shared in _options.Shared ?? []) + { + _context.Shared[shared.GetType()] = shared; + } + + // Components read c.Texts: the JSON's texts first, then the catalog, like [[key]] in the JSON itself. + _context.Texts = template.Texts.Preferring(_texts.Catalog); + + _root = WithTranslations(_source); + + Keys(_root, string.Empty, "$schema", "templifyDefinition", "identity", "texts", "assets", "theme", "properties", "styles", "page", "content", "components"); + ReadAssets(); + ReadTheme(); + if (_root.TryGetProperty("components", out _)) + { + Fail("/components", "The root key 'components' is reserved for components defined inside the definition (a later version)."); + } + _ = EmbeddedTexts.Read(_root, Fail); + if (_root.TryGetProperty("styles", out JsonElement styles)) + { + Guard("/styles", () => + { + if (Keys(styles, "/styles", "defaults", "paragraph", "character", "table", "box", "list")) + { + template.Styles(StyleSheet.Create(s => Styles(s, styles))); + } + }); + } + + if (_root.TryGetProperty("properties", out JsonElement properties)) + { + Guard("/properties", () => + { + Keys(properties, "/properties", "title", "author", "subject"); + template.Properties(p => + { + Apply(String(properties, "title", "/properties"), v => p.Title(v)); + Apply(String(properties, "author", "/properties"), v => p.Author(v)); + Apply(String(properties, "subject", "/properties"), v => p.Subject(v)); + }); + }); + } + + if (_root.TryGetProperty("page", out JsonElement page)) + { + Guard("/page", () => template.Page(p => Page(p, page, "/page"))); + } + + if (_root.TryGetProperty("content", out JsonElement content)) + { + template.Content(c => Blocks(c, content, "/content")); + } + + _context.CurrentLocation = null; + } + + // ── styles ─────────────────────────────────────────────────────────────── + + private void Styles(StyleSheetComposer s, JsonElement styles) + { + if (styles.TryGetProperty("defaults", out JsonElement defaults)) + { + const string at = "/styles/defaults"; + Guard(at, () => + { + Keys(defaults, at, "font", "size", "color", "paragraphStyle"); + s.Defaults(d => + { + Apply(Font(defaults, at), v => d.Font(v)); + Apply(Length(defaults, "size", at), v => d.Size(v)); + Apply(Color(defaults, "color", at), v => d.Color(v)); + Apply(String(defaults, "paragraphStyle", at), v => d.ParagraphStyle(ParagraphStyle(v))); + }); + }); + } + + foreach (JsonProperty style in Members(styles, "paragraph")) + { + JsonElement e = style.Value; + string at = "/styles/paragraph/" + Escape(style.Name); + Guard(at, () => + { + Keys(e, at, "name", "basedOn", "next", "font", "size", "color", "bold", "italic", "spaceBefore", "spaceAfter", "lineSpacing", + "lineHeight", "minimumLineHeight", "alignment", "indentStart", "indentEnd", "firstLineIndent", "keepWithNext", "keepLinesTogether", "outlineLevel", "borderBottom", "borderBottomSpace"); + s.Paragraph(_paragraphStyles[style.Name], p => + { + Apply(String(e, "basedOn", at), v => p.BasedOn(ParagraphStyle(v))); + Apply(String(e, "next", at), v => p.Next(ParagraphStyle(v))); + Apply(Font(e, at), v => p.Font(v)); + Apply(Length(e, "size", at), v => p.Size(v)); + Apply(Color(e, "color", at), v => p.Color(v)); + Apply(Bool(e, "bold", at), v => p.Bold(v)); + Apply(Bool(e, "italic", at), v => p.Italic(v)); + Apply(Length(e, "spaceBefore", at), v => p.SpaceBefore(v)); + Apply(Length(e, "spaceAfter", at), v => p.SpaceAfter(v)); + Apply(Number(e, "lineSpacing", at), v => p.LineSpacing(v)); + Apply(Length(e, "lineHeight", at), v => p.LineHeight(v)); + Apply(Length(e, "minimumLineHeight", at), v => p.MinimumLineHeight(v)); + Apply(String(e, "alignment", at), v => p.Alignment(Enum(v, at + "/alignment"))); + Apply(Length(e, "indentStart", at), v => p.IndentStart(v)); + Apply(Length(e, "indentEnd", at), v => p.IndentEnd(v)); + Apply(Length(e, "firstLineIndent", at), v => p.FirstLineIndent(v)); + Apply(Bool(e, "keepWithNext", at), v => p.KeepWithNext(v)); + Apply(Bool(e, "keepLinesTogether", at), v => p.KeepLinesTogether(v)); + Apply(Int(e, "outlineLevel", at), v => p.OutlineLevel(v)); + if (Border(e, "borderBottom", at) is { } bottom) + { + p.BorderBottom(bottom.Width, bottom.Color, Length(e, "borderBottomSpace", at) ?? Builder.Length.Zero); + } + else if (e.TryGetProperty("borderBottomSpace", out _)) + { + Fail(at + "/borderBottomSpace", "'borderBottomSpace' needs 'borderBottom'."); + } + }); + }); + } + + foreach (JsonProperty style in Members(styles, "character")) + { + JsonElement e = style.Value; + string at = "/styles/character/" + Escape(style.Name); + Guard(at, () => + { + Keys(e, at, "name", "basedOn", "font", "size", "color", "bold", "italic"); + s.Character(_characterStyles[style.Name], c => + { + Apply(String(e, "basedOn", at), v => c.BasedOn(CharacterStyle(v))); + Apply(Font(e, at), v => c.Font(v)); + Apply(Length(e, "size", at), v => c.Size(v)); + Apply(Color(e, "color", at), v => c.Color(v)); + Apply(Bool(e, "bold", at), v => c.Bold(v)); + Apply(Bool(e, "italic", at), v => c.Italic(v)); + }); + }); + } + + foreach (JsonProperty style in Members(styles, "table")) + { + JsonElement e = style.Value; + string at = "/styles/table/" + Escape(style.Name); + Guard(at, () => + { + Keys(e, at, "outerBorder", "rowRule", "columnRule", "headerRule", "headerBackground", "cellPadding", "paragraphStyle", "headerParagraphStyle"); + s.Table(new TableStyleKey(style.Name), t => + { + foreach ((Sides sides, Model.BorderLine line) in Edges(e, "outerBorder", at)) + { + t.OuterBorder(sides, line.Width, line.Color); + } + + Apply(Border(e, "rowRule", at), v => t.RowRule(v.Width, v.Color)); + Apply(Border(e, "columnRule", at), v => t.ColumnRule(v.Width, v.Color)); + Apply(Border(e, "headerRule", at), v => t.HeaderRule(v.Width, v.Color)); + Apply(Color(e, "headerBackground", at), v => t.HeaderBackground(v)); + if (Padding(e, "cellPadding", at) is { } padding) + { + t.CellPadding(padding.Top, padding.Right, padding.Bottom, padding.Left); + } + + Apply(String(e, "paragraphStyle", at), v => t.ParagraphStyle(ParagraphStyle(v))); + Apply(String(e, "headerParagraphStyle", at), v => t.HeaderParagraphStyle(ParagraphStyle(v))); + }); + }); + } + + foreach (JsonProperty style in Members(styles, "box")) + { + JsonElement e = style.Value; + string at = "/styles/box/" + Escape(style.Name); + Guard(at, () => + { + Keys(e, at, "border", "background", "padding", "spaceAfter"); + s.Box(new BoxStyleKey(style.Name), b => + { + Apply(Border(e, "border", at), v => b.Border(v.Width, v.Color)); + Apply(Color(e, "background", at), v => b.Background(v)); + if (Padding(e, "padding", at) is { } padding) + { + b.Padding(padding.Top, padding.Right, padding.Bottom, padding.Left); + } + + Apply(Length(e, "spaceAfter", at), v => b.SpaceAfter(v)); + }); + }); + } + + foreach (JsonProperty style in Members(styles, "list")) + { + JsonElement e = style.Value; + string at = "/styles/list/" + Escape(style.Name); + Guard(at, () => + { + Keys(e, at, "itemStyle", "levels"); + s.List(new ListStyleKey(style.Name), l => + { + Apply(String(e, "itemStyle", at), v => l.ItemStyle(ParagraphStyle(v))); + int i = 0; + foreach (JsonElement level in Array(e, "levels", at)) + { + string levelAt = at + "/levels/" + i++; + Guard(levelAt, () => + { + Keys(level, levelAt, "level", "bullet", "indent", "hanging"); + l.Level( + Int(level, "level", levelAt) ?? 0, + String(level, "bullet", levelAt) ?? throw Missing(levelAt, "bullet"), + Length(level, "indent", levelAt) ?? throw Missing(levelAt, "indent"), + Length(level, "hanging", levelAt) ?? throw Missing(levelAt, "hanging")); + }); + } + }); + }); + } + } + + // ── page ───────────────────────────────────────────────────────────────── + + private void Page(PageComposer p, JsonElement page, string at) + { + Keys(page, at, "size", "margins", "headerFooterDistance", "header", "footer", "firstPage"); + if (page.TryGetProperty("size", out JsonElement size)) + { + if (size.ValueKind == JsonValueKind.String) + { + if (JsonValues.TryPageSize(size.GetString(), out PageSize? named)) + { + p.Size(named!); + } + else + { + Fail(at + "/size", $"'{size.GetString()}' is not a page size (A4, A5, Letter, Legal, or {{ \"width\", \"height\" }})."); + } + } + else if (Keys(size, at + "/size", "width", "height")) + { + // Both are needed: a size with one of them was ignored before #274. + Length width = Length(size, "width", at + "/size") ?? throw Missing(at + "/size", "width"); + Length height = Length(size, "height", at + "/size") ?? throw Missing(at + "/size", "height"); + p.Size(new PageSize(width, height)); + } + } + + if (Box(page, "margins", at) is { } margins) + { + p.Margins(margins.Top, margins.Right, margins.Bottom, margins.Left); + } + + if (String(page, "headerFooterDistance", at) is { } distances) + { + string[] parts = distances.Split(' '); + if (parts.Length == 2 && JsonValues.TryLength(parts[0], out Length header) && JsonValues.TryLength(parts[1], out Length footer)) + { + p.HeaderFooterDistance(header, footer); + } + else + { + Fail(at + "/headerFooterDistance", $"'{distances}' is not two lengths (header, footer)."); + } + } + + if (page.TryGetProperty("header", out JsonElement headerBlocks)) + { + p.Header(b => Blocks(b, headerBlocks, at + "/header")); + } + + if (page.TryGetProperty("footer", out JsonElement footerBlocks)) + { + p.Footer(b => Blocks(b, footerBlocks, at + "/footer")); + } + + if (page.TryGetProperty("firstPage", out JsonElement first) && Keys(first, at + "/firstPage", "header", "footer")) + { + p.FirstPage(f => + { + if (first.TryGetProperty("header", out JsonElement firstHeader)) + { + if (IsNone(firstHeader)) + { + f.NoHeader(); + } + else + { + f.Header(b => Blocks(b, firstHeader, at + "/firstPage/header")); + } + } + + if (first.TryGetProperty("footer", out JsonElement firstFooter)) + { + if (IsNone(firstFooter)) + { + f.NoFooter(); + } + else + { + f.Footer(b => Blocks(b, firstFooter, at + "/firstPage/footer")); + } + } + }); + } + } + + private static bool IsNone(JsonElement element) => element.ValueKind == JsonValueKind.String && element.GetString() == "none"; + + // ── blocks ─────────────────────────────────────────────────────────────── + + private void Blocks(BlockComposer c, JsonElement blocks, string at) + { + int i = 0; + foreach (JsonElement block in Items(blocks, at, "a list of blocks ([ … ])")) + { + string blockAt = at + "/" + i++; + int before = c.Blocks.Count; + Guard(blockAt, () => Block(c, block, blockAt)); + for (int added = before; added < c.Blocks.Count; added++) + { + _context.Locations.AddOrUpdate(c.Blocks[added], blockAt); + } + } + } + + private void Block(BlockComposer c, JsonElement block, string at) + { + if (block.ValueKind == JsonValueKind.String) + { + Paragraph(c, null, block, at); + return; + } + + if (block.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at, "A block is a string (a paragraph) or an object such as { \"paragraph\": … }."); + } + + if (block.TryGetProperty("paragraph", out JsonElement paragraph)) + { + Keys(block, at, "style", "paragraph", "spaceBefore", "spaceAfter", "keepWithNext", "keepLinesTogether"); + Paragraph(c, String(block, "style", at), paragraph, at + "/paragraph", LayoutOptions(block, at)); + } + else if (block.TryGetProperty("pageBreak", out _)) + { + Keys(block, at, "pageBreak"); + Flag(block, "pageBreak", at); + c.PageBreak(); + } + else if (block.TryGetProperty("if", out JsonElement condition)) + { + Keys(block, at, "if", "then", "elseIf", "else"); + IfChain chain = c.If(Condition(condition, at + "/if"), b => Blocks(b, Required(block, "then", at), at + "/then")); + int i = 0; + foreach (JsonElement branch in Array(block, "elseIf", at)) + { + string branchAt = at + "/elseIf/" + i++; + Keys(branch, branchAt, "if", "then"); + chain = chain.ElseIf(Condition(Required(branch, "if", branchAt), branchAt + "/if"), b => Blocks(b, Required(branch, "then", branchAt), branchAt + "/then")); + } + + if (block.TryGetProperty("else", out JsonElement otherwise)) + { + chain.Else(b => Blocks(b, otherwise, at + "/else")); + } + } + else if (block.TryGetProperty("forEach", out JsonElement collection)) + { + Keys(block, at, "forEach", "as", "body"); + string name = String(block, "as", at) ?? throw Missing(at, "as"); + JsonElement body = Required(block, "body", at); + c.ForEach(Path(collection, at + "/forEach", DataKind.Collection), name, (item, b) => InScope(name, item, () => Blocks(b, body, at + "/body"))); + } + else if (block.TryGetProperty("component", out JsonElement component)) + { + Keys(block, at, "component", "params"); + string name = String(block, "component", at)!; + ComponentCatalog.Registration registration = _options.Components?.Find(name) + ?? throw new JsonImportException(at, $"The component '{name}' is not registered (TemplateJsonImportOptions.Components)."); + JsonElement parameters = block.TryGetProperty("params", out JsonElement given) ? given : _noParameters; + c.Component(registration.Create(parameters, _options.Components!.DataNaming, (text, kind) => Resolve(text, at + "/params", kind), ParagraphStyle, CharacterStyle, ParameterColor, at + "/params")); + } + else if (block.TryGetProperty("section", out _)) + { + Keys(block, at, "section", "blocks"); + string name = String(block, "section", at) ?? throw Missing(at, "section"); + if (!SectionComponent.IsValidName(name)) + { + throw new JsonImportException(at + "/section", $"'{name}' is not a section name: use letters, digits, '_', '.' or '-'."); + } + + if (!_sectionNames.Add(name)) + { + throw new JsonImportException(at + "/section", $"The section name '{name}' is used twice; names are unique in a definition."); + } + + JsonElement blocks = Required(block, "blocks", at); + c.Section(name, b => Blocks(b, blocks, at + "/blocks")); + } + else if (block.TryGetProperty("list", out JsonElement list)) + { + Keys(block, at, "style", "list"); + string style = String(block, "style", at) ?? throw Missing(at, "style"); + c.List(new ListStyleKey(style), l => ListItems(l, list, at + "/list")); + } + else if (block.TryGetProperty("box", out JsonElement box)) + { + Keys(block, at, "style", "box"); + string style = String(block, "style", at) ?? throw Missing(at, "style"); + c.Box(new BoxStyleKey(style), b => Blocks(b, box, at + "/box")); + } + else if (block.TryGetProperty("table", out _)) + { + Keys(block, at, "style", "columns", "indent", "spaceBefore", "spaceAfter", "table"); + c.Table(t => Table(t, block, at)); + } + else if (block.TryGetProperty("rule", out JsonElement rule)) + { + Keys(block, at, "rule"); + at += "/rule"; + Keys(rule, at, "line", "spaceAbove", "spaceBelow", "width"); + Model.BorderLine line = Border(rule, "line", at) ?? throw Missing(at, "line"); + Length above = Length(rule, "spaceAbove", at) ?? Builder.Length.Zero; + Length below = Length(rule, "spaceBelow", at) ?? Builder.Length.Zero; + if (Length(rule, "width", at) is { } width) + { + c.Rule(line.Width, line.Color, above, below, width); + } + else + { + c.Rule(line.Width, line.Color, above, below); + } + } + else if (block.TryGetProperty("spacer", out _)) + { + Keys(block, at, "spacer"); + c.Spacer(Length(block, "spacer", at) ?? throw Missing(at, "spacer")); + } + else if (block.TryGetProperty("toc", out JsonElement toc)) + { + Keys(block, at, "toc"); + Keys(toc, at + "/toc", "maxLevel", "levels"); + int maxLevel = Int(toc, "maxLevel", at + "/toc") ?? 3; + if (toc.TryGetProperty("levels", out JsonElement levelsValue)) + { + string levelsAt = at + "/toc/levels"; + if (levelsValue.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(levelsAt, "'levels' is an object of entry styles by level, for example { \"1\": \"TocPart\" }."); + } + + c.TableOfContents(maxLevel, t => + { + foreach (JsonProperty level in Members(toc, "levels")) + { + if (!int.TryParse(level.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int number)) + { + throw new JsonImportException(levelsAt + "/" + Escape(level.Name), $"'{level.Name}' is not a level: use \"1\" to \"{maxLevel}\"."); + } + + string style = level.Value.ValueKind == JsonValueKind.String ? level.Value.GetString()! : throw new JsonImportException(levelsAt + "/" + Escape(level.Name), "An entry style is the id of a paragraph style."); + t.Level(number, ParagraphStyle(style)); + } + }); + } + else + { + c.TableOfContents(maxLevel); + } + } + else if (block.TryGetProperty("raw", out JsonElement raw)) + { + Keys(block, at, "raw"); + Raw(c, raw, at + "/raw"); + } + else + { + throw new JsonImportException(at, $"Unknown block {Names(block)}; expected a string (a paragraph), paragraph, pageBreak, if, forEach, component, section, list, box, table, rule, spacer, toc or raw."); + } + } + + /// The layout options next to a paragraph's content; null when none is given. + private Action? LayoutOptions(JsonElement block, string at) + { + Length? spaceBefore = Length(block, "spaceBefore", at); + Length? spaceAfter = Length(block, "spaceAfter", at); + bool? keepWithNext = Bool(block, "keepWithNext", at); + bool? keepLinesTogether = Bool(block, "keepLinesTogether", at); + if (spaceBefore is null && spaceAfter is null && keepWithNext is null && keepLinesTogether is null) + { + return null; + } + + return p => + { + Apply(spaceBefore, v => p.SpaceBefore(v)); + Apply(spaceAfter, v => p.SpaceAfter(v)); + Apply(keepWithNext, v => p.KeepWithNext(v)); + Apply(keepLinesTogether, v => p.KeepLinesTogether(v)); + }; + } + + /// A paragraph: its content is a string (text with placeholders) or a list of inlines. + private void Paragraph(BlockComposer c, string? styleId, JsonElement content, string at, Action? options = null) + { + if (content.ValueKind is not (JsonValueKind.String or JsonValueKind.Array)) + { + throw new JsonImportException(at, "A paragraph holds a string or a list of inlines, for example { \"style\": \"Heading\", \"paragraph\": \"Title\" }."); + } + + ParagraphStyleKey? style = styleId is { } id ? ParagraphStyle(id) : null; + if (options is not null) + { + if (IsPlainText(content)) + { + c.Paragraph(style, content.GetString()!, options); + } + else + { + c.Paragraph(style, x => Inlines(x, content, at), options); + } + + return; + } + + if (IsPlainText(content)) + { + if (style is null) + { + c.Paragraph(content.GetString()!); + } + else + { + c.Paragraph(style, content.GetString()!); + } + } + else if (style is null) + { + c.Paragraph(x => Inlines(x, content, at)); + } + else + { + c.Paragraph(style, x => Inlines(x, content, at)); + } + } + + private void ItemContent(ListComposer l, int level, JsonElement content, string at) + { + if (content.ValueKind is not (JsonValueKind.String or JsonValueKind.Array)) + { + throw new JsonImportException(at, "A list item holds a string or a list of inlines."); + } + + if (IsPlainText(content)) + { + l.Item(level, content.GetString()!); + } + else + { + l.Item(level, x => Inlines(x, content, at)); + } + } + + /// The content of a cell: a string (one paragraph) or a list of blocks. + private void CellBlocks(BlockComposer c, JsonElement content, string at, string? style = null) + { + if (content.ValueKind == JsonValueKind.String) + { + int before = c.Blocks.Count; + Guard(at, () => Paragraph(c, style, content, at)); + for (int added = before; added < c.Blocks.Count; added++) + { + _context.Locations.AddOrUpdate(c.Blocks[added], at); + } + + return; + } + + Blocks(c, content, at); + } + + private void ListItems(ListComposer l, JsonElement items, string at) + { + int i = 0; + foreach (JsonElement item in Items(items, at, "a list of items")) + { + string itemAt = at + "/" + i++; + Guard(itemAt, () => ListItem(l, item, itemAt)); + } + } + + private void ListItem(ListComposer l, JsonElement item, string at) + { + if (item.ValueKind == JsonValueKind.String) + { + ItemContent(l, 0, item, at); + } + else if (item.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at, "A list item is a string, { \"level\": …, \"item\": … }, forEach or if."); + } + else if (item.TryGetProperty("item", out JsonElement content)) + { + Keys(item, at, "level", "item"); + ItemContent(l, Int(item, "level", at) ?? 0, content, at + "/item"); + } + else if (item.TryGetProperty("forEach", out JsonElement collection)) + { + Keys(item, at, "forEach", "as", "items"); + string name = String(item, "as", at) ?? throw Missing(at, "as"); + JsonElement body = Required(item, "items", at); + l.ForEach(Path(collection, at + "/forEach", DataKind.Collection), name, (loopItem, li) => InScope(name, loopItem, () => ListItems(li, body, at + "/items"))); + } + else if (item.TryGetProperty("if", out JsonElement condition)) + { + Keys(item, at, "if", "then", "elseIf", "else"); + ListIfChain chain = l.If(Condition(condition, at + "/if"), li => ListItems(li, Required(item, "then", at), at + "/then")); + int b = 0; + foreach (JsonElement branch in Array(item, "elseIf", at)) + { + string branchAt = at + "/elseIf/" + b++; + Keys(branch, branchAt, "if", "then"); + chain = chain.ElseIf(Condition(Required(branch, "if", branchAt), branchAt + "/if"), li => ListItems(li, Required(branch, "then", branchAt), branchAt + "/then")); + } + + if (item.TryGetProperty("else", out JsonElement otherwise)) + { + chain.Else(li => ListItems(li, otherwise, at + "/else")); + } + } + else + { + throw new JsonImportException(at, $"Unknown list item {Names(item)}; expected item, forEach or if."); + } + } + + private void Raw(BlockComposer c, JsonElement raw, string at) + { + Keys(raw, at, "docx", "odt", "uses"); + if (!_options.AllowRawXml) + { + _context.Error(DiagnosticCodes.RawXmlNotAllowed, "Raw XML is not allowed in this import (TemplateJsonImportOptions.AllowRawXml).", at); + return; + } + + XElement docx = WithoutNamespaceDeclarations(XElement.Parse(String(raw, "docx", at) ?? throw Missing(at, "docx"))); + XElement odt = WithoutNamespaceDeclarations(XElement.Parse(String(raw, "odt", at) ?? throw Missing(at, "odt"))); + List uses = new List(); + int i = 0; + foreach (JsonElement use in Array(raw, "uses", at)) + { + uses.Add(Path(use, at + "/uses/" + i++)); + } + + c.Raw(new RawBlock { Docx = _ => new XElement(docx), Odt = _ => new XElement(odt), Uses = uses }); + } + + /// + /// The element as code would build it: parsed XML carries its xmlns declarations as attributes, which the + /// writer would then repeat inside the part; without them the part's own prefixes apply, as for a C# raw block. + /// + private static XElement WithoutNamespaceDeclarations(XElement element) + { + foreach (XElement e in element.DescendantsAndSelf()) + { + e.Attributes().Where(a => a.IsNamespaceDeclaration).Remove(); + } + + return element; + } + + // ── tables ─────────────────────────────────────────────────────────────── + + /// A table block: its options beside the table key, which holds the rows. + private void Table(TableComposer t, JsonElement table, string at) + { + Apply(String(table, "style", at), v => t.Style(new TableStyleKey(v))); + if (table.TryGetProperty("columns", out JsonElement columns)) + { + t.Columns(cols => + { + int i = 0; + foreach (JsonElement column in Items(columns, at + "/columns", "a list of columns")) + { + string columnAt = at + "/columns/" + i++; + Guard(columnAt, () => + { + if (column.ValueKind == JsonValueKind.Number) + { + cols.Relative(column.GetDouble()); + } + else if (JsonValues.TryLength(column.ValueKind == JsonValueKind.String ? column.GetString() : null, out Length width)) + { + cols.Fixed(width); + } + else + { + Fail(columnAt, "A column is a relative weight (a number) or a fixed width (\"30mm\")."); + } + }); + } + }); + } + + Apply(Length(table, "indent", at), v => t.Indent(v)); + Apply(Length(table, "spaceBefore", at), v => t.SpaceBefore(v)); + Apply(Length(table, "spaceAfter", at), v => t.SpaceAfter(v)); + Rows(new RowTarget(r => t.Row(r), (c, n, r) => t.ForEachRow(c, n, r), t.RowsIf, r => t.HeaderRow(r)), Required(table, "table", at), at + "/table"); + } + + private sealed record RowTarget( + Action> Row, + Action> ForEachRow, + Func, RowsIfChain> RowsIf, + Action>? HeaderRow); + + private static RowTarget Target(RowsComposer rows) => new RowTarget(r => rows.Row(r), (c, n, r) => rows.ForEachRow(c, n, r), rows.RowsIf, null); + + private void Rows(RowTarget target, JsonElement rows, string at) + { + int i = 0; + foreach (JsonElement item in Items(rows, at, "a list of rows")) + { + string rowAt = at + "/" + i++; + Guard(rowAt, () => RowItem(target, item, rowAt)); + } + } + + private void RowItem(RowTarget target, JsonElement item, string at) + { + if (item.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at, "A row item is an object: row, forEachRow or rowsIf."); + } + + if (item.TryGetProperty("row", out _)) + { + Keys(item, at, "header", "allowSplit", "paragraphStyle", "row"); + Action cells = r => Row(r, item, at); + if (Bool(item, "header", at) == true) + { + if (target.HeaderRow is null) + { + throw new JsonImportException(at, "A header row cannot be inside a row loop or row conditional."); + } + + target.HeaderRow(cells); + } + else + { + target.Row(cells); + } + } + else if (item.TryGetProperty("forEachRow", out JsonElement collection)) + { + Keys(item, at, "forEachRow", "as", "rows"); + string name = String(item, "as", at) ?? throw Missing(at, "as"); + JsonElement body = Required(item, "rows", at); + target.ForEachRow(Path(collection, at + "/forEachRow", DataKind.Collection), name, (loopItem, inner) => InScope(name, loopItem, () => Rows(Target(inner), body, at + "/rows"))); + } + else if (item.TryGetProperty("rowsIf", out JsonElement condition)) + { + Keys(item, at, "rowsIf", "then", "elseIf", "else"); + RowsIfChain chain = target.RowsIf(Condition(condition, at + "/rowsIf"), inner => Rows(Target(inner), Required(item, "then", at), at + "/then")); + int b = 0; + foreach (JsonElement branch in Array(item, "elseIf", at)) + { + string branchAt = at + "/elseIf/" + b++; + Keys(branch, branchAt, "if", "then"); + chain = chain.ElseIf(Condition(Required(branch, "if", branchAt), branchAt + "/if"), inner => Rows(Target(inner), Required(branch, "then", branchAt), branchAt + "/then")); + } + + if (item.TryGetProperty("else", out JsonElement otherwise)) + { + chain.Else(inner => Rows(Target(inner), otherwise, at + "/else")); + } + } + else + { + throw new JsonImportException(at, $"Unknown row {Names(item)}; expected row, forEachRow or rowsIf."); + } + } + + private void Row(RowComposer r, JsonElement row, string at) + { + if (Bool(row, "allowSplit", at) == true) + { + r.AllowSplit(); + } + + if (String(row, "paragraphStyle", at) is { } paragraphStyle) + { + r.ParagraphStyle(ParagraphStyle(paragraphStyle)); + } + + int i = 0; + foreach (JsonElement cell in Items(Required(row, "row", at), at + "/row", "a list of cells")) + { + string cellAt = at + "/row/" + i++; + Guard(cellAt, () => + { + if (cell.ValueKind == JsonValueKind.String) + { + r.Cell(c => CellBlocks(c, cell, cellAt)); + return; + } + + if (cell.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(cellAt, "A cell is a string (one paragraph) or an object: { \"content\": [ blocks ] }, { \"style\": \"…\", \"content\": \"…\" }, with span, background and verticalAlign as options."); + } + + Keys(cell, cellAt, "span", "background", "verticalAlign", "border", "padding", "style", "content"); + JsonElement content = Required(cell, "content", cellAt); + string? style = String(cell, "style", cellAt); + if (style is not null && content.ValueKind != JsonValueKind.String) + { + throw new JsonImportException(cellAt + "/content", "With \"style\" a cell's content is one string, a paragraph in that style; without it, write blocks as a list."); + } + + r.Cell(c => + { + Apply(Int(cell, "span", cellAt), v => c.ColumnSpan(v)); + Apply(Color(cell, "background", cellAt), v => c.Background(v)); + Apply(String(cell, "verticalAlign", cellAt), v => c.VerticalAlignment(Enum(v, cellAt + "/verticalAlign"))); + foreach ((Sides sides, Model.BorderLine line) in Edges(cell, "border", cellAt)) + { + c.Border(sides, line.Width, line.Color); + } + + if (Padding(cell, "padding", cellAt) is { } padding) + { + c.Padding(padding.Top, padding.Right, padding.Bottom, padding.Left); + } + CellBlocks(c, content, cellAt + "/content", style); + }); + }); + } + } + + // ── inlines ────────────────────────────────────────────────────────────── + + /// Inline content: a string (text with placeholders) or a list of inlines. + private void Inlines(InlineComposer x, JsonElement inlines, string at) + { + if (inlines.ValueKind == JsonValueKind.String) + { + Guard(at, () => Text(x, inlines.GetString()!, null, at)); + return; + } + + int i = 0; + foreach (JsonElement inline in Items(inlines, at, "a string or a list of inlines")) + { + string inlineAt = at + "/" + i++; + Guard(inlineAt, () => Inline(x, inline, inlineAt)); + } + } + + private void Inline(InlineComposer x, JsonElement inline, string at) + { + if (inline.ValueKind == JsonValueKind.String) + { + Text(x, inline.GetString()!, null, at); + return; + } + + if (inline.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at, "An inline is a string or an object such as { \"text\": …, \"style\": … }."); + } + + CharacterStyleKey? style = String(inline, "style", at) is { } id ? CharacterStyle(id) : null; + if (inline.TryGetProperty("text", out _)) + { + Keys(inline, at, "text", "style"); + Text(x, String(inline, "text", at) ?? throw Missing(at, "text"), style, at); + } + else if (inline.TryGetProperty("tabRight", out _)) + { + Keys(inline, at, "tabRight"); + Flag(inline, "tabRight", at); + x.TabRight(); + } + else if (inline.TryGetProperty("pageNumber", out _)) + { + Keys(inline, at, "pageNumber", "style"); + Flag(inline, "pageNumber", at); + if (style is null) + { + x.PageNumber(); + } + else + { + x.PageNumber(style); + } + } + else if (inline.TryGetProperty("pageCount", out _)) + { + Keys(inline, at, "pageCount", "style"); + Flag(inline, "pageCount", at); + if (style is null) + { + x.PageCount(); + } + else + { + x.PageCount(style); + } + } + else if (inline.TryGetProperty("image", out JsonElement image)) + { + Keys(inline, at, "image", "alt", "width", "height"); + string name = image.ValueKind == JsonValueKind.String ? image.GetString()! : throw new JsonImportException(at + "/image", "An image names an entry of \"assets\"."); + byte[] data = Asset(image, at + "/image"); + Length? width = Length(inline, "width", at); + Length? height = Length(inline, "height", at); + + // One size is enough: the other follows from the image's proportions. + ImageFit fit = (width, height) switch + { + ({ } w, { } h) => ImageFit.Exact(w, h), + ({ } w, null) => ImageFit.Width(w), + (null, { } h) => ImageFit.Height(h), + _ => ImageFit.Natural, + }; + x.Image(ImageSource.FromBytes(data).WithName(name), String(inline, "alt", at) ?? string.Empty, fit); + } + else if (inline.TryGetProperty("expression", out JsonElement expression)) + { + // Expressions are written in text as {{(condition):format}}; the object form is only for raw conditions, + // which have no text form. + Keys(inline, at, "expression", "format"); + if (expression.ValueKind != JsonValueKind.Object) + { + throw new JsonImportException(at + "/expression", "Write an expression in text as \"{{(condition):format}}\"; the expression object is only for a raw condition { \"raw\": …, \"uses\": … }."); + } + + x.Expression(Condition(expression, at + "/expression"), Format(String(inline, "format", at) ?? throw Missing(at, "format"), at)); + } + else if (inline.TryGetProperty("if", out JsonElement condition)) + { + Keys(inline, at, "if", "then", "elseIf", "else"); + InlineIfChain chain = x.If(Condition(condition, at + "/if"), t => TextInlines(t, Required(inline, "then", at), at + "/then")); + int i = 0; + foreach (JsonElement branch in Array(inline, "elseIf", at)) + { + string branchAt = at + "/elseIf/" + i++; + Keys(branch, branchAt, "if", "then"); + chain = chain.ElseIf(Condition(Required(branch, "if", branchAt), branchAt + "/if"), t => TextInlines(t, Required(branch, "then", branchAt), branchAt + "/then")); + } + + if (inline.TryGetProperty("else", out JsonElement otherwise)) + { + chain.Else(t => TextInlines(t, otherwise, at + "/else")); + } + } + else + { + throw new JsonImportException(at, $"Unknown inline {Names(inline)}; expected a string (a tab or line break is \\t or \\n in it), text, tabRight, pageNumber, pageCount, image, expression or if."); + } + } + + /// Text with placeholders, every piece in . + private void Text(InlineComposer x, string text, CharacterStyleKey? style, string at) + { + foreach (TextPiece piece in Pieces(text, at)) + { + switch (piece) + { + case TextPiece.Literal literal when style is null: + x.Text(literal.Text); + break; + case TextPiece.Literal literal: + x.Text(style, literal.Text); + break; + case TextPiece.Value value: + (TemplatePath path, ValueFormat? format) = ValuePiece(value, at); + switch (format, style) + { + case (null, null): + x.Value(path); + break; + case (null, { } s): + x.Value(s, path); + break; + case ({ } f, null): + x.Value(path, f); + break; + default: + x.Value(style!, path, format!); + break; + } + + break; + case TextPiece.Expression expression: + if (style is not null) + { + throw new JsonImportException(at, $"The expression '{TextTemplate.Write([expression])}' cannot have a character style."); + } + + x.Expression(ConditionText(expression.Condition, at), Format(expression.Format ?? throw new JsonImportException(at, $"The expression '{TextTemplate.Write([expression])}' needs a format, for example {{{{(…):yesno}}}}."), at)); + break; + } + } + } + + /// The inlines of an inline conditional: a string, or a list of strings, styled text and nested conditionals. + private void TextInlines(TextComposer t, JsonElement inlines, string at) + { + if (inlines.ValueKind == JsonValueKind.String) + { + Guard(at, () => Text(t, inlines.GetString()!, null, at)); + return; + } + + int i = 0; + foreach (JsonElement inline in Items(inlines, at, "a string or a list of inlines")) + { + string inlineAt = at + "/" + i++; + Guard(inlineAt, () => TextInline(t, inline, inlineAt)); + } + } + + private void TextInline(TextComposer t, JsonElement inline, string at) + { + if (inline.ValueKind == JsonValueKind.String) + { + Text(t, inline.GetString()!, null, at); + return; + } + + CharacterStyleKey? style = String(inline, "style", at) is { } id ? CharacterStyle(id) : null; + if (inline.TryGetProperty("text", out _)) + { + Keys(inline, at, "text", "style"); + Text(t, String(inline, "text", at) ?? throw Missing(at, "text"), style, at); + } + else if (inline.TryGetProperty("if", out JsonElement condition)) + { + Keys(inline, at, "if", "then", "elseIf", "else"); + InlineIfChain chain = t.If(Condition(condition, at + "/if"), inner => TextInlines(inner, Required(inline, "then", at), at + "/then")); + int b = 0; + foreach (JsonElement branch in Array(inline, "elseIf", at)) + { + string branchAt = at + "/elseIf/" + b++; + Keys(branch, branchAt, "if", "then"); + chain = chain.ElseIf(Condition(Required(branch, "if", branchAt), branchAt + "/if"), inner => TextInlines(inner, Required(branch, "then", branchAt), branchAt + "/then")); + } + + if (inline.TryGetProperty("else", out JsonElement otherwise)) + { + chain.Else(inner => TextInlines(inner, otherwise, at + "/else")); + } + } + else + { + throw new JsonImportException(at, "Inside an inline conditional only strings, { \"text\": …, \"style\": … } and if are allowed."); + } + } + + /// Text with placeholders inside an inline conditional (no expressions, no formatted styled values). + private void Text(TextComposer t, string text, CharacterStyleKey? style, string at) + { + foreach (TextPiece piece in Pieces(text, at)) + { + switch (piece) + { + case TextPiece.Literal literal: + _ = style is null ? t.Text(literal.Text) : t.Text(style, literal.Text); + break; + case TextPiece.Value value: + (TemplatePath path, ValueFormat? format) = ValuePiece(value, at); + if (format is not null && style is not null) + { + throw new JsonImportException(at, $"Inside an inline conditional the value '{TextTemplate.Write([value])}' cannot have both a format and a character style."); + } + + _ = format is not null ? t.Value(path, format) : style is null ? t.Value(path) : t.Value(style, path); + break; + case TextPiece.Expression expression: + throw new JsonImportException(at, $"Inside an inline conditional an expression ('{TextTemplate.Write([expression])}') is not allowed."); + } + } + } + + /// A string without placeholders: composed as literal text, exactly like the C# overloads that take a string. + private static bool IsPlainText(JsonElement element) => + element.ValueKind == JsonValueKind.String && !element.GetString()!.Contains("{{", StringComparison.Ordinal); + + private static IReadOnlyList Pieces(string text, string at) + { + try + { + return TextTemplate.Parse(text); + } + catch (FormatException exception) + { + throw new JsonImportException(at, exception.Message); + } + } + + /// The path and format of a value placeholder; :join reads a collection, every other value a single value. + private (TemplatePath Path, ValueFormat? Format) ValuePiece(TextPiece.Value value, string at) + { + bool join = value.Format is "join" || value.Format?.StartsWith("join:", StringComparison.Ordinal) == true; + return (Resolve(value.Path, at, join ? null : DataKind.Value), value.Format is { } specifier ? Format(specifier, at) : null); + } + + private static readonly HashSet _plainFormats = new HashSet(StringComparer.Ordinal) + { + "currency", "uppercase", "lowercase", "raw", "yesno", "truefalse", "onoff", "enabled", "active", "checkbox", "checkmark", "check", "join", + }; + + /// A value format Templify knows (or the host registered); anything else is an error instead of a silently ignored format. + private ValueFormat Format(string specifier, string at) + { + bool known = _plainFormats.Contains(specifier) + || _options.AcceptsAnyValueFormat + || (_options.ValueFormats?.Contains(specifier) ?? false) + || specifier.StartsWith("join:", StringComparison.Ordinal) + || (specifier.StartsWith("date:", StringComparison.Ordinal) && specifier.Length > "date:".Length) + || (specifier.StartsWith("number:", StringComparison.Ordinal) && specifier.Length > "number:".Length); + if (!known) + { + throw new JsonImportException( + at, + $"Unknown value format '{specifier}'. Known: currency, number: (number:N2), date: (date:d MMMM yyyy), yesno, truefalse, onoff, enabled, active, checkbox, checkmark, uppercase, lowercase, raw, join, join:, join::\"\"."); + } + + return ValueFormat.Custom(specifier); + } + + // ── text keys ────────────────────────────────────────────────────────────── + + /// + /// The definition with every [[key]] replaced by the build language's text (key markers while exporting). + /// Malformed keys are TB9200, missing texts TB5001, a text containing {{ TB9201, each at the string. + /// + private JsonElement WithTranslations(JsonElement source) + { + using MemoryStream stream = new MemoryStream(); + using (Utf8JsonWriter output = new Utf8JsonWriter(stream)) + { + Translate(source, string.Empty, output); + } + + using JsonDocument document = JsonDocument.Parse(stream.ToArray()); + return document.RootElement.Clone(); + } + + private void Translate(JsonElement element, string at, Utf8JsonWriter output) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + output.WriteStartObject(); + foreach (JsonProperty property in element.EnumerateObject()) + { + output.WritePropertyName(property.Name); + if (at.Length == 0 && property.Name == "texts") + { + // The translations themselves are literal: a "[[" inside one is text. + property.Value.WriteTo(output); + continue; + } + + Translate(property.Value, at + "/" + Escape(property.Name), output); + } + + output.WriteEndObject(); + break; + case JsonValueKind.Array: + output.WriteStartArray(); + int i = 0; + foreach (JsonElement item in element.EnumerateArray()) + { + Translate(item, at + "/" + i++, output); + } + + output.WriteEndArray(); + break; + case JsonValueKind.String: + string text = element.GetString()!; + try + { + // Raw XML is markup: a translation goes in as XML text (C# put it into an XElement). + bool markup = at.EndsWith("/raw/docx", StringComparison.Ordinal) || at.EndsWith("/raw/odt", StringComparison.Ordinal); + text = TextKeys.Resolve(text, key => markup ? System.Security.SecurityElement.Escape(Text(key, at)) : Text(key, at)); + } + catch (FormatException exception) + { + Fail(at, exception.Message); + } + + output.WriteStringValue(text); + break; + default: + element.WriteTo(output); + break; + } + } + + private string Text(string key, string at) + { + string? outer = _context.CurrentLocation; + _context.CurrentLocation = at; + try + { + string text = _template.Texts.Resolve(key, _texts.Catalog); + if (!_template.Texts.WritesKeys && text.Contains("{{", StringComparison.Ordinal)) + { + _context.Error(DiagnosticCodes.InvalidJsonValue, $"The text '{key}' ({_template.Texts.Language.Name}) contains '{{{{', which would read as a value; texts are literal.", at); + return "[" + key + "]"; + } + + return text; + } + finally + { + _context.CurrentLocation = outer; + } + } + + // ── paths, conditions, scope ───────────────────────────────────────────── + + private void InScope(string name, LoopItem item, Action compose) + { + _scope.Add((name, item)); + try + { + compose(); + } + finally + { + _scope.RemoveAt(_scope.Count - 1); + } + } + + /// + /// A path as written in JSON: a first segment naming an enclosing loop's item reads from that item, @index + /// and its kin from the innermost loop, anything else from the data root — as the fluent API would build it. + /// + internal TemplatePath ResolvePath(string text) + { + if (text.StartsWith('@')) + { + if (_scope.Count == 0) + { + throw new ArgumentException($"'{text}' is loop metadata and can only be used inside a loop."); + } + + return TemplatePath.ForMetadata(_scope[^1].Item.Scope, text[1..]); + } + + int dot = text.IndexOf('.', StringComparison.Ordinal); + string first = dot < 0 ? text : text[..dot]; + for (int i = _scope.Count - 1; i >= 0; i--) + { + if (_scope[i].Name == first) + { + return dot < 0 ? _scope[i].Item.Self : _scope[i].Item[text[(dot + 1)..]]; + } + } + + return _template.Data[text]; + } + + private TemplatePath Path(JsonElement path, string at, DataKind? expected = null) + { + if (path.ValueKind != JsonValueKind.String) + { + throw new JsonImportException(at, "A path is a string such as \"order.customer.name\"."); + } + + return Resolve(path.GetString()!, at, expected); + } + + /// + /// Resolves a path and, with a data catalogue, checks that the data has it and that its kind fits the use + /// (a value for a value, a collection for a loop, an object for an object parameter; open shapes fit anything). + /// Problems are TB9203 at the pointer. + /// + private TemplatePath Resolve(string text, string at, DataKind? expected = null) + { + TemplatePath path = ResolvePath(text); + if (_options.Data is { } catalog && !path.IsMetadata && !path.IsRoot) + { + string canonical = DataContract.Canonical(path); + DataKind? kind = catalog.KindOf(canonical); + if (kind is null) + { + _context.Error(DiagnosticCodes.UnknownDataPath, $"The data has no '{canonical}' (written as '{text}').", at, canonical); + } + else if (expected is { } wanted && kind != wanted && kind != DataKind.Open) + { + _context.Error(DiagnosticCodes.UnknownDataPath, $"'{canonical}' is {Article(kind.Value)}, not {Article(wanted)}.", at, canonical); + } + } + + return path; + } + + private static string Article(DataKind kind) => kind switch + { + DataKind.Value => "a value", + DataKind.Object => "an object", + DataKind.Collection => "a collection", + _ => "an open shape", + }; + + /// Conditions longer than this, or nested deeper, are refused before they are parsed (stack safety). + private const int MaximumConditionLength = 10_000; + + private const int MaximumConditionDepth = 64; + + private Condition Condition(JsonElement condition, string at) + { + if (condition.ValueKind == JsonValueKind.Object) + { + Keys(condition, at, "raw", "uses"); + List uses = new List(); + int i = 0; + foreach (JsonElement use in Array(condition, "uses", at)) + { + uses.Add(Path(use, at + "/uses/" + i++)); + } + + string raw = String(condition, "raw", at) ?? throw Missing(at, "raw"); + CheckConditionSize(raw, at); + return Builder.Condition.Raw(raw, uses.ToArray()); + } + + if (condition.ValueKind != JsonValueKind.String) + { + throw new JsonImportException(at, "A condition is a string such as \"order.total > 1000\"."); + } + + return ConditionText(condition.GetString()!, at); + } + + private Condition ConditionText(string text, string at) + { + CheckConditionSize(text, at); + try + { + return ConditionParser.Parse(text, path => Resolve(path, at)); + } + catch (FormatException exception) + { + throw new JsonImportException(at, exception.Message); + } + } + + /// Refuses conditions whose length or parenthesis depth could exhaust the stack of a recursive parser. + private static void CheckConditionSize(string text, string at) + { + int depth = 0; + bool inString = false; + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (inString) + { + if (c == '\\') + { + i++; + } + else if (c == '"') + { + inString = false; + } + + continue; + } + + switch (c) + { + case '"': + inString = true; + break; + case '(': + if (++depth > MaximumConditionDepth) + { + throw new JsonImportException(at, $"The condition is nested deeper than {MaximumConditionDepth} levels."); + } + + break; + case ')': + depth--; + break; + } + } + + if (text.Length > MaximumConditionLength) + { + throw new JsonImportException(at, $"The condition is longer than {MaximumConditionLength} characters."); + } + } + + // ── value helpers ──────────────────────────────────────────────────────── + + private ParagraphStyleKey ParagraphStyle(string id) => + _paragraphStyles.TryGetValue(id, out ParagraphStyleKey? key) ? key + : id == BuilderStyles.TemplateMarker.Id ? BuilderStyles.TemplateMarker + : new ParagraphStyleKey(id, id); + + private CharacterStyleKey CharacterStyle(string id) => + _characterStyles.TryGetValue(id, out CharacterStyleKey? key) ? key : new CharacterStyleKey(id, id); + + private FontFace? Font(JsonElement owner, string at) + { + if (!owner.TryGetProperty("font", out JsonElement font)) + { + return null; + } + + if (font.ValueKind == JsonValueKind.String && font.GetString()!.StartsWith('$')) + { + string token = font.GetString()![1..]; + return _themeFonts.TryGetValue(token, out FontFace? themed) + ? FontFace.Token(token, themed) + : throw new JsonImportException(at + "/font", $"The theme has no font '{token}' ({string.Join(", ", _themeFonts.Keys)})."); + } + + if (font.ValueKind == JsonValueKind.String) + { + return new FontFace(font.GetString()!); + } + + Keys(font, at + "/font", "family", "embedded"); + string family = String(font, "family", at + "/font") ?? throw Missing(at + "/font", "family"); + return FontFace.Embedded(family, Asset(Required(font, "embedded", at + "/font"), at + "/font/embedded")); + } + + /// The content of an asset named in the definition's assets. + private byte[] Asset(JsonElement key, string at) + { + string? name = key.ValueKind == JsonValueKind.String ? key.GetString() : null; + return name != null && _assetsByName.TryGetValue(name, out byte[]? data) + ? data + : throw new JsonImportException(at, $"The asset '{name}' is not in the definition's \"assets\" ({string.Join(", ", _assetsByName.Keys)})."); + } + + /// The assets section: names to content keys, each key in . + private void ReadAssets() + { + _assetsByName.Clear(); + if (!_root.TryGetProperty("assets", out JsonElement assets)) + { + return; + } + + if (assets.ValueKind != JsonValueKind.Object) + { + Fail("/assets", "The assets are an object of names and content keys, for example { \"logo\": \"sha256:…\" }."); + return; + } + + foreach (JsonProperty asset in assets.EnumerateObject()) + { + string at = "/assets/" + Escape(asset.Name); + if (!AssetNames.IsValid(asset.Name)) + { + Fail(at, $"'{asset.Name}' is not an asset name: use letters, digits, '_', '.' or '-'."); + } + else if (asset.Value.ValueKind != JsonValueKind.String || _options.Assets is not { } contents || !contents.TryGetValue(asset.Value.GetString()!, out byte[]? data)) + { + Fail(at, $"The asset '{asset.Name}' refers to content that is not in TemplateJsonImportOptions.Assets."); + } + else + { + _assetsByName[asset.Name] = data; + } + } + } + + private Length? Length(JsonElement owner, string name, string at) => + Value(owner, name, at, "a length such as \"10pt\" or \"25mm\"", (string text, out Length value) => JsonValues.TryLength(text, out value)); + + private Color? Color(JsonElement owner, string name, string at) => + PlainString(owner, name) is { } token && token.StartsWith('$') + ? ThemeColor(token[1..], at + "/" + Escape(name)) + : Value(owner, name, at, "a colour such as \"#1F4E79\" or a theme colour \"$accent\"", (string text, out Color value) => JsonValues.TryColor(text, out value)); + + /// A colour parameter of a component: "$token" from the theme, else "#RRGGBB". + private Builder.Color ParameterColor(string text, string at) => + text.StartsWith('$') ? ThemeColor(text[1..], at) + : JsonValues.TryColor(text, out Builder.Color color) ? color + : throw new JsonImportException(at, $"'{text}' is not a colour such as \"#1F4E79\" or a theme colour \"$accent\"."); + + private Builder.Color ThemeColor(string token, string at) => + _themeColors.TryGetValue(token, out Builder.Color color) + ? Builder.Color.Token(token, color) + : throw new JsonImportException(at, $"The theme has no colour '{token}' ({string.Join(", ", _themeColors.Keys)})."); + + /// The theme section: colors and fonts by token name; the host's values replace the file's. + private void ReadTheme() + { + _themeColors.Clear(); + _themeFonts.Clear(); + if (_root.TryGetProperty("theme", out JsonElement theme)) + { + const string at = "/theme"; + if (theme.ValueKind != JsonValueKind.Object) + { + Fail(at, "The theme is an object: { \"colors\": { \"accent\": \"#1F4E79\" }, \"fonts\": { \"body\": \"Liberation Sans\" } }."); + } + else if (Keys(theme, at, "colors", "fonts")) + { + foreach (JsonProperty color in Members(theme, "colors")) + { + string colorAt = at + "/colors/" + Escape(color.Name); + if (!ThemeTokens.IsValid(color.Name)) + { + Fail(colorAt, $"'{color.Name}' is not a theme token name: a letter, then letters, digits, '_', '.' or '-'."); + } + else if (color.Value.ValueKind == JsonValueKind.String && JsonValues.TryColor(color.Value.GetString(), out Builder.Color value)) + { + _themeColors[color.Name] = value; + } + else + { + Fail(colorAt, "A theme colour is \"#RRGGBB\"."); + } + } + + foreach (JsonProperty font in Members(theme, "fonts")) + { + string fontAt = at + "/fonts/" + Escape(font.Name); + if (!ThemeTokens.IsValid(font.Name)) + { + Fail(fontAt, $"'{font.Name}' is not a theme token name: a letter, then letters, digits, '_', '.' or '-'."); + continue; + } + + Guard(fontAt, () => + { + if (font.Value.ValueKind == JsonValueKind.String) + { + _themeFonts[font.Name] = new FontFace(font.Value.GetString()!); + return; + } + + Keys(font.Value, fontAt, "family", "embedded"); + string family = String(font.Value, "family", fontAt) ?? throw Missing(fontAt, "family"); + _themeFonts[font.Name] = FontFace.Embedded(family, Asset(Required(font.Value, "embedded", fontAt), fontAt + "/embedded")); + }); + } + } + } + + // The host's values replace the file's: a colour token takes a colour, a font token a family. A token the file does + // not have is not used (a host may apply one palette to many definitions), which the build reports as a warning. + foreach ((string token, string value) in _options.Theme ?? new Dictionary()) + { + if (_themeColors.ContainsKey(token)) + { + if (JsonValues.TryColor(value, out Builder.Color color)) + { + _themeColors[token] = color; + } + else + { + Fail("/theme/colors/" + Escape(token), $"TemplateJsonImportOptions.Theme gives the colour '{token}' the value '{value}', which is not a colour \"#RRGGBB\"."); + } + } + else if (_themeFonts.ContainsKey(token)) + { + _themeFonts[token] = new FontFace(value); + } + else + { + _context.Warn(DiagnosticCodes.UnusedThemeValue, $"TemplateJsonImportOptions.Theme sets '{token}', which the definition's theme does not have; it is not used."); + } + } + } + + private (Length Top, Length Right, Length Bottom, Length Left)? Box(JsonElement owner, string name, string at) => + Value(owner, name, at, "one to four lengths", (string text, out (Length, Length, Length, Length) value) => JsonValues.TryBox(text, out value)); + + /// Padding: one to four lengths in CSS order. + private (Length Top, Length Right, Length Bottom, Length Left)? Padding(JsonElement owner, string name, string at) => Box(owner, name, at); + + /// Lines per side: a line string for all four sides, or an object with the sides that are set. + private List<(Sides Sides, Model.BorderLine Line)> Edges(JsonElement owner, string name, string at) + { + if (!owner.TryGetProperty(name, out JsonElement value)) + { + return []; + } + + if (value.ValueKind != JsonValueKind.Object) + { + return Border(owner, name, at) is { } all ? [(Sides.All, all)] : []; + } + + string edgesAt = at + "/" + Escape(name); + Keys(value, edgesAt, "top", "right", "bottom", "left"); + List<(Sides, Model.BorderLine)> edges = new List<(Sides, Model.BorderLine)>(); + foreach ((string side, Sides sides) in new[] { ("top", Sides.Top), ("right", Sides.Right), ("bottom", Sides.Bottom), ("left", Sides.Left) }) + { + if (Border(value, side, edgesAt) is { } line) + { + edges.Add((sides, line)); + } + } + + return edges; + } + + private Model.BorderLine? Border(JsonElement owner, string name, string at) + { + if (String(owner, name, at) is not { } text) + { + return null; + } + + string[] parts = text.Split(' '); + if (parts.Length == 2 && parts[1].StartsWith('$') && JsonValues.TryLength(parts[0], out Length width)) + { + return new Model.BorderLine(width, ThemeColor(parts[1][1..], at + "/" + Escape(name))); + } + + return JsonValues.TryBorder(text, out Model.BorderLine? line) + ? line + : throw new JsonImportException(at + "/" + name, $"'{text}' is not a line such as \"0.5pt #D4D4D4\" or \"0.5pt $line\"."); + } + + private delegate bool TryParse(string text, out T value); + + private static T? Value(JsonElement owner, string name, string at, string expected, TryParse parse) + where T : struct + { + if (String(owner, name, at) is not { } text) + { + return null; + } + + return parse(text, out T value) ? value : throw new JsonImportException(at + "/" + name, $"'{text}' is not {expected}."); + } + + private static T Enum(string text, string at) + where T : struct, System.Enum => + !text.Any(char.IsDigit) && System.Enum.TryParse(text, ignoreCase: true, out T value) && System.Enum.IsDefined(value) + ? value + : throw new JsonImportException(at, $"'{text}' is not one of {string.Join(", ", System.Enum.GetNames().Select(n => char.ToLowerInvariant(n[0]) + n[1..]))}."); + + /// A string member; another JSON type is a problem at its pointer. + private static string? String(JsonElement owner, string name, string at) => + Member(owner, name, at, JsonValueKind.String, "a string")?.GetString(); + + private static bool? Bool(JsonElement owner, string name, string at) => + Member(owner, name, at, JsonValueKind.True, "true or false")?.GetBoolean(); + + private static int? Int(JsonElement owner, string name, string at) => + Member(owner, name, at, JsonValueKind.Number, "a whole number") is { } number + ? number.TryGetInt32(out int value) ? value : throw new JsonImportException(at + "/" + name, "A whole number is expected.") + : null; + + private static double? Number(JsonElement owner, string name, string at) => + Member(owner, name, at, JsonValueKind.Number, "a number")?.GetDouble(); + + private static JsonElement? Member(JsonElement owner, string name, string at, JsonValueKind kind, string expected) + { + if (owner.ValueKind != JsonValueKind.Object || !owner.TryGetProperty(name, out JsonElement value)) + { + return null; + } + + bool matches = kind == JsonValueKind.True ? value.ValueKind is JsonValueKind.True or JsonValueKind.False : value.ValueKind == kind; + return matches ? value : throw new JsonImportException(at + "/" + name, $"'{name}' must be {expected}, not {value.ValueKind.ToString().ToLowerInvariant()}."); + } + + private static string? PlainString(JsonElement owner, string name) => + owner.ValueKind == JsonValueKind.Object && owner.TryGetProperty(name, out JsonElement value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + private IEnumerable Array(JsonElement owner, string name, string at) => + owner.ValueKind == JsonValueKind.Object && owner.TryGetProperty(name, out JsonElement value) ? Items(value, at + "/" + name, "a list") : []; + + private IEnumerable Items(JsonElement list, string at, string expected) + { + if (list.ValueKind == JsonValueKind.Array) + { + return list.EnumerateArray(); + } + + Fail(at, char.ToUpperInvariant(expected[0]) + expected[1..] + " is expected."); + return []; + } + + private static IEnumerable Members(JsonElement owner, string name) => + owner.ValueKind == JsonValueKind.Object && owner.TryGetProperty(name, out JsonElement value) && value.ValueKind == JsonValueKind.Object ? value.EnumerateObject() : []; + + private static JsonElement Required(JsonElement owner, string name, string at) => + owner.ValueKind == JsonValueKind.Object && owner.TryGetProperty(name, out JsonElement value) ? value : throw Missing(at, name); + + /// A flag such as "pageBreak": true: anything but true is a problem, never a silent element. + private static void Flag(JsonElement owner, string name, string at) + { + if (owner.GetProperty(name).ValueKind != JsonValueKind.True) + { + throw new JsonImportException(at + "/" + name, $"'{name}' must be true; leave the element out instead."); + } + } + + private static JsonImportException Missing(string at, string name) => new JsonImportException(at, $"'{name}' is missing."); + + /// Reports every key of an object that its kind does not have; false when the element is not an object. + private bool Keys(JsonElement element, string at, params string[] allowed) + { + if (element.ValueKind != JsonValueKind.Object) + { + Fail(at, "An object { … } is expected."); + return false; + } + + foreach (JsonProperty property in element.EnumerateObject().Where(p => !allowed.Contains(p.Name, StringComparer.Ordinal))) + { + Fail(at + "/" + Escape(property.Name), $"Unknown key '{property.Name}'; allowed here: {string.Join(", ", allowed)}."); + } + + return true; + } + + private static string Names(JsonElement element) => + element.ValueKind == JsonValueKind.Object ? string.Join(", ", element.EnumerateObject().Select(p => "'" + p.Name + "'")) : element.ValueKind.ToString(); + + private static void Apply(T? value, Action apply) + where T : struct + { + if (value is { } v) + { + apply(v); + } + } + + private static void Apply(T? value, Action apply) + where T : class + { + if (value is not null) + { + apply(value); + } + } + + /// RFC 6901: '~' and '/' in a key. + internal static string Escape(string key) => key.Replace("~", "~0", StringComparison.Ordinal).Replace("/", "~1", StringComparison.Ordinal); + + private void Fail(string at, string message) => _context.Error(DiagnosticCodes.InvalidJson, message, at); + + /// + /// Composes one element at its pointer: errors composers record get the pointer; a structural problem is TB9200, + /// a value a composer rejects () TB9201; the element is skipped either way. + /// + private void Guard(string at, Action compose) + { + string? outer = _context.CurrentLocation; + _context.CurrentLocation = at; + try + { + compose(); + } + catch (JsonImportException exception) + { + Fail(exception.Location, exception.Message); + } + catch (XmlException exception) + { + Fail(at, "The XML is not well-formed: " + exception.Message); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) + { + _context.Error(DiagnosticCodes.InvalidJsonValue, exception.Message, at); + } + finally + { + _context.CurrentLocation = outer; + } + } +} + +/// A structural problem found while composing a JSON definition; caught per element. +internal sealed class JsonImportException(string location, string message) : Exception(message) +{ + public string Location { get; } = location; +} + diff --git a/src/TriasDev.Templify.Builder/Json/JsonLayout.cs b/src/TriasDev.Templify.Builder/Json/JsonLayout.cs new file mode 100644 index 00000000..bb3d8e73 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonLayout.cs @@ -0,0 +1,90 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Lays out JSON for reading: an object or array whose one-line form fits in the width (counting its key, not its +/// indentation, so a member reads the same at every depth) is written on one line, otherwise one member per line, +/// recursively. Strings are never wrapped, and values keep the escaping of the input. +/// +internal static class JsonLayout +{ + /// The default line width. + public const int DefaultWidth = 100; + + private const string Indent = " "; + + /// Formats valid JSON; the result ends with a line break. + public static string Format(string json, int width = DefaultWidth) + { + ArgumentNullException.ThrowIfNull(json); + using JsonDocument document = JsonDocument.Parse(json); + StringBuilder text = new StringBuilder(); + Write(text, document.RootElement, 0, 0, width); + return text.Append('\n').ToString(); + } + + private static void Write(StringBuilder text, JsonElement element, int depth, int prefix, int width) + { + string single = SingleLine(element); + if (element.ValueKind is not (JsonValueKind.Object or JsonValueKind.Array) || prefix + single.Length <= width || IsEmpty(element)) + { + text.Append(single); + return; + } + + string inner = string.Concat(Enumerable.Repeat(Indent, depth + 1)); + bool isObject = element.ValueKind == JsonValueKind.Object; + text.Append(isObject ? '{' : '[').Append('\n'); + bool first = true; + if (isObject) + { + foreach (JsonProperty property in element.EnumerateObject()) + { + Separator(text, ref first); + string key = Key(property.Name) + ": "; + text.Append(inner).Append(key); + Write(text, property.Value, depth + 1, key.Length, width); + } + } + else + { + foreach (JsonElement item in element.EnumerateArray()) + { + Separator(text, ref first); + text.Append(inner); + Write(text, item, depth + 1, 0, width); + } + } + + text.Append('\n').Append(string.Concat(Enumerable.Repeat(Indent, depth))).Append(isObject ? '}' : ']'); + } + + private static void Separator(StringBuilder text, ref bool first) + { + if (!first) + { + text.Append(",\n"); + } + + first = false; + } + + private static bool IsEmpty(JsonElement element) => + element.ValueKind == JsonValueKind.Object ? !element.EnumerateObject().Any() : element.GetArrayLength() == 0; + + private static string SingleLine(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Object => "{" + string.Join(", ", element.EnumerateObject().Select(p => Key(p.Name) + ": " + SingleLine(p.Value))) + "}", + JsonValueKind.Array => "[" + string.Join(", ", element.EnumerateArray().Select(SingleLine)) + "]", + _ => element.GetRawText(), + }; + + /// A property name, escaped like the writer escapes it. + private static string Key(string name) => "\"" + JsonEncodedText.Encode(name, JavaScriptEncoder.UnsafeRelaxedJsonEscaping) + "\""; +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonOutline.cs b/src/TriasDev.Templify.Builder/Json/JsonOutline.cs new file mode 100644 index 00000000..6739dc25 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonOutline.cs @@ -0,0 +1,247 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace TriasDev.Templify.Builder.Json; + +/// The outline of a definition: its blocks, rows, cells and items with pointers and short labels. +internal static class JsonOutline +{ + private const int LabelLength = 40; + + public static List Build(string json) + { + if (Parse(json) is not JsonObject root) + { + throw new ArgumentException("A definition is a JSON object.", nameof(json)); + } + + List nodes = new List(); + if (root["page"] is JsonObject page) + { + foreach (string part in new[] { "header", "footer" }) + { + Blocks(nodes, page[part], "/page/" + part, 0); + } + + if (page["firstPage"] is JsonObject first) + { + Blocks(nodes, first["header"], "/page/firstPage/header", 0); + Blocks(nodes, first["footer"], "/page/firstPage/footer", 0); + } + } + + Blocks(nodes, root["content"], "/content", 0); + return nodes; + } + + /// Parses a definition, reporting malformed JSON as an argument error. + public static JsonNode Parse(string json) + { + ArgumentNullException.ThrowIfNull(json); + try + { + return JsonNode.Parse(json) ?? throw new ArgumentException("The JSON is null.", nameof(json)); + } + catch (JsonException exception) + { + throw new ArgumentException("The text is not JSON: " + exception.Message, nameof(json), exception); + } + } + + private static void Blocks(List nodes, JsonNode? blocks, string at, int depth) + { + if (blocks is not JsonArray list) + { + return; + } + + for (int i = 0; i < list.Count; i++) + { + Block(nodes, list[i], at + "/" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), depth); + } + } + + private static void Block(List nodes, JsonNode? block, string at, int depth) + { + if (block is JsonValue value && value.TryGetValue(out string? text)) + { + nodes.Add(new TemplateJsonNode(at, "paragraph", Short(text), depth)); + return; + } + + if (block is not JsonObject o) + { + return; + } + + string kind = Kind(o, ["paragraph", "pageBreak", "spacer", "if", "forEach", "section", "component", "list", "box", "table", "rule", "toc", "raw"]); + nodes.Add(new TemplateJsonNode(at, kind, BlockLabel(kind, o), depth)); + switch (kind) + { + case "section": + Blocks(nodes, o["blocks"], at + "/blocks", depth + 1); + break; + case "forEach": + Blocks(nodes, o["body"], at + "/body", depth + 1); + break; + case "box": + Blocks(nodes, o["box"], at + "/box", depth + 1); + break; + case "if": + Branches(nodes, o, at, depth, Blocks); + break; + case "list": + Items(nodes, o["list"], at + "/list", depth + 1); + break; + case "table": + Rows(nodes, o["table"], at + "/table", depth + 1); + break; + } + } + + /// then, every elseIf (its own node) and else, each holding what lists. + private static void Branches(List nodes, JsonObject o, string at, int depth, Action, JsonNode?, string, int> children) + { + children(nodes, o["then"], at + "/then", depth + 1); + if (o["elseIf"] is JsonArray branches) + { + for (int i = 0; i < branches.Count; i++) + { + string branchAt = at + "/elseIf/" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + nodes.Add(new TemplateJsonNode(branchAt, "elseIf", Condition((branches[i] as JsonObject)?["if"]), depth + 1)); + children(nodes, (branches[i] as JsonObject)?["then"], branchAt + "/then", depth + 2); + } + } + + children(nodes, o["else"], at + "/else", depth + 1); + } + + private static void Items(List nodes, JsonNode? items, string at, int depth) + { + if (items is not JsonArray list) + { + return; + } + + for (int i = 0; i < list.Count; i++) + { + string itemAt = at + "/" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + switch (list[i]) + { + case JsonValue value when value.TryGetValue(out string? text): + nodes.Add(new TemplateJsonNode(itemAt, "item", Short(text), depth)); + break; + case JsonObject o when o.ContainsKey("forEach"): + nodes.Add(new TemplateJsonNode(itemAt, "forEach", Loop(o, "forEach"), depth)); + Items(nodes, o["items"], itemAt + "/items", depth + 1); + break; + case JsonObject o when o.ContainsKey("if"): + nodes.Add(new TemplateJsonNode(itemAt, "if", Condition(o["if"]), depth)); + Branches(nodes, o, itemAt, depth, Items); + break; + case JsonObject o: + nodes.Add(new TemplateJsonNode(itemAt, "item", Short(Text(o["item"])), depth)); + break; + } + } + } + + private static void Rows(List nodes, JsonNode? rows, string at, int depth) + { + if (rows is not JsonArray list) + { + return; + } + + for (int i = 0; i < list.Count; i++) + { + string rowAt = at + "/" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (list[i] is not JsonObject o) + { + continue; + } + + if (o.ContainsKey("forEachRow")) + { + nodes.Add(new TemplateJsonNode(rowAt, "forEachRow", Loop(o, "forEachRow"), depth)); + Rows(nodes, o["rows"], rowAt + "/rows", depth + 1); + } + else if (o.ContainsKey("rowsIf")) + { + nodes.Add(new TemplateJsonNode(rowAt, "rowsIf", Condition(o["rowsIf"]), depth)); + Branches(nodes, o, rowAt, depth, Rows); + } + else + { + JsonArray cells = o["row"] as JsonArray ?? []; + // The columns it covers first (spans count), so adding a column shows which rows still need a cell. + int columns = cells.Sum(c => c is JsonObject co && co["span"] is JsonValue span && span.TryGetValue(out int n) ? n : 1); + string label = columns.ToString(System.Globalization.CultureInfo.InvariantCulture) + " columns: " + + Short(string.Join(" | ", cells.Select(c => c is JsonObject co ? Text(co["content"]) : Text(c)))); + nodes.Add(new TemplateJsonNode(rowAt, o["header"]?.GetValueKind() == JsonValueKind.True ? "headerRow" : "row", label, depth)); + for (int c = 0; c < cells.Count; c++) + { + // A cell with blocks of its own is listed with them; a one-paragraph cell is in the row's label. + if (cells[c] is JsonObject cell && cell["content"] is JsonArray content) + { + string cellAt = rowAt + "/row/" + c.ToString(System.Globalization.CultureInfo.InvariantCulture); + nodes.Add(new TemplateJsonNode(cellAt, "cell", Short(Text(content)), depth + 1)); + Blocks(nodes, content, cellAt + "/content", depth + 2); + } + } + } + } + } + + private static string Kind(JsonObject o, string[] keys) => keys.FirstOrDefault(o.ContainsKey) ?? "unknown"; + + private static string BlockLabel(string kind, JsonObject o) => kind switch + { + "paragraph" => Short((Str(o["style"]) is { } style ? style + ": " : string.Empty) + Text(o["paragraph"])), + "section" => Str(o["section"]) ?? string.Empty, + "if" => Condition(o["if"]), + "forEach" => Loop(o, "forEach"), + "component" => Str(o["component"]) ?? string.Empty, + "list" or "box" => Str(o["style"]) ?? string.Empty, + "table" => (Str(o["style"]) is { } tableStyle ? tableStyle + ", " : string.Empty) + ((o["columns"] as JsonArray)?.Count ?? 0).ToString(System.Globalization.CultureInfo.InvariantCulture) + " columns", + "rule" => Str((o["rule"] as JsonObject)?["line"]) ?? string.Empty, + "spacer" => Str(o["spacer"]) ?? string.Empty, + "toc" => "up to level " + ((o["toc"] as JsonObject)?["maxLevel"] is JsonValue level && level.TryGetValue(out int maxLevel) ? maxLevel : 3).ToString(System.Globalization.CultureInfo.InvariantCulture), + _ => string.Empty, + }; + + private static string Loop(JsonObject o, string key) => Str(o[key]) + " as " + Str(o["as"]); + + private static string Condition(JsonNode? condition) => condition switch + { + JsonValue value when value.TryGetValue(out string? text) => text, + JsonObject raw => Str(raw["raw"]) ?? string.Empty, + _ => string.Empty, + }; + + /// The text of a string, a list of inlines (strings and styled text) or of blocks (their first paragraph). + private static string Text(JsonNode? content) => content switch + { + JsonValue value when value.TryGetValue(out string? text) => text, + JsonArray items => string.Concat(items.Select(i => i switch + { + JsonValue v when v.TryGetValue(out string? t) => t, + JsonObject o when o["text"] is { } t => Str(t), + JsonObject o when o["paragraph"] is { } p => Text(p), + _ => string.Empty, + })), + _ => string.Empty, + }; + + /// A string value, or null for anything else: the outline reads any JSON without checking it. + private static string? Str(JsonNode? node) => node is JsonValue value && value.TryGetValue(out string? text) ? text : null; + + private static string Short(string text) + { + string line = text.ReplaceLineEndings(" "); + return line.Length <= LabelLength ? line : line[..LabelLength].TrimEnd() + "…"; + } +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonPatch.cs b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs new file mode 100644 index 00000000..ae2a8e42 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs @@ -0,0 +1,162 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace TriasDev.Templify.Builder.Json; + +/// A JSON Patch operation that cannot be applied; is its position in the patch. +internal sealed class JsonPatchException(int index, string message) : Exception(message) +{ + public int Index { get; } = index; +} + +/// JSON Patch (RFC 6902) on : add, remove, replace, move, copy, test. +internal static class JsonPatch +{ + /// Applies the operations to a copy of ; all or none. + /// An operation is malformed or cannot be applied; the input is unchanged. + public static JsonNode? Apply(JsonNode? document, string patch) + { + JsonArray operations; + try + { + operations = JsonNode.Parse(patch) as JsonArray ?? throw new JsonPatchException(-1, "A JSON Patch is an array of operations: [ { \"op\": \"replace\", \"path\": \"/content/0/paragraph\", \"value\": \"…\" } ]."); + } + catch (JsonException exception) + { + throw new JsonPatchException(-1, "The patch is not JSON: " + exception.Message); + } + + JsonNode? root = document?.DeepClone(); + for (int i = 0; i < operations.Count; i++) + { + try + { + root = Operation(root, operations[i] as JsonObject ?? throw new ArgumentException("An operation is an object with \"op\" and \"path\".")); + } + catch (ArgumentException exception) + { + throw new JsonPatchException(i, $"Operation {i}: {exception.Message}"); + } + } + + return root; + } + + private static JsonNode? Operation(JsonNode? root, JsonObject operation) + { + string op = Member(operation, "op"); + string path = Member(operation, "path"); + switch (op) + { + case "add": + return Add(root, path, Value(operation)); + case "remove": + Remove(root, path); + return root; + case "replace": + JsonPointer.Resolve(root, path); + if (path.Length == 0) + { + return Value(operation); + } + + Remove(root, path); + return Add(root, path, Value(operation)); + case "move": + string from = Member(operation, "from"); + if (path.StartsWith(from + "/", StringComparison.Ordinal)) + { + throw new ArgumentException($"'{from}' cannot be moved into itself ('{path}')."); + } + + if (from == path) + { + JsonPointer.Resolve(root, from); + return root; + } + + JsonNode? moved = JsonPointer.Resolve(root, from)?.DeepClone(); + Remove(root, from); + return Add(root, path, moved); + case "copy": + return Add(root, path, JsonPointer.Resolve(root, Member(operation, "from"))?.DeepClone()); + case "test": + if (!JsonNode.DeepEquals(JsonPointer.Resolve(root, path), Value(operation))) + { + throw new ArgumentException($"the value at '{path}' is not the expected one."); + } + + return root; + default: + throw new ArgumentException($"'{op}' is not an operation (add, remove, replace, move, copy, test)."); + } + } + + private static JsonNode? Add(JsonNode? root, string path, JsonNode? value) + { + IReadOnlyList tokens = JsonPointer.Parse(path); + if (tokens.Count == 0) + { + return value; + } + + JsonNode? parent = Parent(root, tokens); + string last = tokens[^1]; + switch (parent) + { + case JsonObject o: + o[last] = value; + break; + case JsonArray a: + a.Insert(JsonPointer.Index(last, a.Count, allowEnd: true, path), value); + break; + default: + throw new ArgumentException($"'{path}': the parent is not an object or array."); + } + + return root; + } + + private static void Remove(JsonNode? root, string path) + { + IReadOnlyList tokens = JsonPointer.Parse(path); + if (tokens.Count == 0) + { + throw new ArgumentException("The whole document cannot be removed."); + } + + JsonNode? parent = Parent(root, tokens); + string last = tokens[^1]; + switch (parent) + { + case JsonObject o when o.ContainsKey(last): + o.Remove(last); + break; + case JsonObject: + throw new ArgumentException($"'{path}' names nothing."); + case JsonArray a: + a.RemoveAt(JsonPointer.Index(last, a.Count, allowEnd: false, path)); + break; + default: + throw new ArgumentException($"'{path}': the parent is not an object or array."); + } + } + + /// The node that holds the last token. + private static JsonNode? Parent(JsonNode? root, IReadOnlyList tokens) + { + string parent = string.Concat(tokens.Take(tokens.Count - 1).Select(t => "/" + JsonPointer.Escape(t))); + return JsonPointer.Resolve(root, parent); + } + + private static string Member(JsonObject operation, string name) => + operation[name] is JsonValue value && value.TryGetValue(out string? text) + ? text + : throw new ArgumentException($"\"{name}\" is missing or not a string."); + + private static JsonNode? Value(JsonObject operation) => + operation.TryGetPropertyValue("value", out JsonNode? value) ? value?.DeepClone() : throw new ArgumentException("\"value\" is missing."); +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonPointer.cs b/src/TriasDev.Templify.Builder/Json/JsonPointer.cs new file mode 100644 index 00000000..3eeb466d --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonPointer.cs @@ -0,0 +1,92 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json.Nodes; + +namespace TriasDev.Templify.Builder.Json; + +/// JSON Pointer (RFC 6901): parsing, escaping and resolving on . +internal static class JsonPointer +{ + /// The reference tokens of a pointer: "" is the whole document; otherwise it starts with /. + /// The pointer is malformed. + public static IReadOnlyList Parse(string pointer) + { + ArgumentNullException.ThrowIfNull(pointer); + if (pointer.Length == 0) + { + return []; + } + + if (pointer[0] != '/') + { + throw new ArgumentException($"'{pointer}' is not a JSON pointer: it starts with '/' (or is empty for the whole document).", nameof(pointer)); + } + + return pointer[1..].Split('/').Select(token => Unescape(token, pointer)).ToList(); + } + + /// Escapes one reference token: ~ as ~0, / as ~1. + public static string Escape(string token) => token.Replace("~", "~0", StringComparison.Ordinal).Replace("/", "~1", StringComparison.Ordinal); + + /// The node a pointer names. + /// The pointer is malformed or names nothing. + public static JsonNode? Resolve(JsonNode? root, string pointer) + { + JsonNode? node = root; + string at = string.Empty; + foreach (string token in Parse(pointer)) + { + node = Child(node, token, at, pointer); + at += "/" + Escape(token); + } + + return node; + } + + /// A child of an object (by name) or array (by index); is the parent's pointer. + public static JsonNode? Child(JsonNode? parent, string token, string at, string pointer) => parent switch + { + JsonObject o when o.TryGetPropertyValue(token, out JsonNode? value) => value, + JsonObject => throw new ArgumentException($"'{pointer}': the object at '{Show(at)}' has no member '{token}'.", nameof(pointer)), + JsonArray a when Index(token, a.Count, allowEnd: false, pointer) is int i => a[i], + _ => throw new ArgumentException($"'{pointer}': the value at '{Show(at)}' is not an object or array, so it has no '{token}'.", nameof(pointer)), + }; + + /// An array index token: digits without a leading zero, below (or equal, with -, when appending). + public static int Index(string token, int count, bool allowEnd, string pointer) + { + if (allowEnd && token == "-") + { + return count; + } + + bool digits = token.Length > 0 && token.All(char.IsAsciiDigit) && (token.Length == 1 || token[0] != '0'); + if (!digits || !int.TryParse(token, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int index)) + { + throw new ArgumentException($"'{pointer}': '{token}' is not an array index.", nameof(pointer)); + } + + if (index > count || (index == count && !allowEnd)) + { + throw new ArgumentException($"'{pointer}': index {index} is past the end of an array of {count}.", nameof(pointer)); + } + + return index; + } + + private static string Show(string at) => at.Length == 0 ? "(root)" : at; + + private static string Unescape(string token, string pointer) + { + for (int i = 0; i < token.Length; i++) + { + if (token[i] == '~' && (i + 1 >= token.Length || token[i + 1] is not ('0' or '1'))) + { + throw new ArgumentException($"'{pointer}' is not a JSON pointer: '~' is followed by 0 or 1.", nameof(pointer)); + } + } + + return token.Replace("~1", "/", StringComparison.Ordinal).Replace("~0", "~", StringComparison.Ordinal); + } +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonSchemaWriter.cs b/src/TriasDev.Templify.Builder/Json/JsonSchemaWriter.cs new file mode 100644 index 00000000..fb796ec6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonSchemaWriter.cs @@ -0,0 +1,217 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Renders as a JSON Schema (draft 2020-12). Every construct is a $defs entry with +/// its keys, required keys and no others; block, row, cell, item and inline lists accept their constructs (each +/// identified by its required key) and the string shorthands. Conditions, paths and formats are strings: their grammar +/// is checked by the import, not by the schema. +/// +internal static class JsonSchemaWriter +{ + private const string Length = "-?[0-9]+(\\.[0-9]+)?(pt|mm|cm|in)"; + private const string Color = "(#[0-9A-Fa-f]{6}|\\$[^\\s]+)"; + + public static string Write(ComponentCatalog? components) + { + JsonObject defs = new JsonObject + { + ["length"] = Pattern("^" + Length + "$", "A length with a unit: 6pt, 10mm, 2cm, 0.5in."), + ["color"] = Pattern("^" + Color + "$", "#RRGGBB or a theme token $name."), + ["line"] = Pattern("^" + Length + " " + Color + "$", "Thickness and colour: 0.5pt #D4D4D4."), + ["padding"] = Pattern("^" + Length + "( " + Length + "){0,3}$", "One to four lengths in CSS order."), + ["twoLengths"] = Pattern("^" + Length + " " + Length + "$", "Two lengths."), + }; + + foreach (Construct construct in JsonVocabulary.All) + { + defs[construct.Name] = construct.Name == "component" && components is not null + ? Components(construct, components) + : Object(construct); + } + + // Group choices are named any…: "row", "item" and "cell" are also construct names. + defs["anyBlock"] = OneOf(Group("block"), withString: true); + defs["blocks"] = ArrayOf(Ref("anyBlock")); + defs["anyItem"] = OneOf(Group("item"), withString: true); + defs["items"] = ArrayOf(Ref("anyItem")); + defs["anyRow"] = OneOf(Group("row"), withString: false); + defs["rows"] = ArrayOf(Ref("anyRow")); + defs["anyCell"] = OneOf(Group("cell"), withString: true); + defs["cells"] = ArrayOf(Ref("anyCell")); + defs["anyInline"] = OneOf(Group("inline"), withString: true); + defs["inlines"] = new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "string" }, ArrayOf(Ref("anyInline"))) }; + defs["anyTextInline"] = OneOf(["text", "inlineIf"], withString: true); + defs["textInlines"] = new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "string" }, ArrayOf(Ref("anyTextInline"))) }; + + JsonObject schema = new JsonObject + { + ["$schema"] = "https://json-schema.org/draft/2020-12/schema", + ["title"] = "Templify template definition, format " + ModelJsonWriter.FormatVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["$ref"] = "#/$defs/definition", + ["$defs"] = defs, + }; + return schema.ToJsonString(new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + } + + private static IEnumerable Group(string group) => + JsonVocabulary.All.Where(c => c.Group == group && c.Discriminator is not null).Select(c => c.Name); + + private static JsonObject Object(Construct construct) + { + JsonObject properties = new JsonObject(); + foreach (VocabularyKey key in construct.Keys) + { + JsonObject value = Value(key, construct); + value["description"] = key.Description; + properties[key.Name] = value; + } + + JsonObject result = new JsonObject + { + ["type"] = "object", + ["description"] = construct.Description, + ["properties"] = properties, + ["additionalProperties"] = false, + }; + string[] required = construct.Keys.Where(k => k.Required).Select(k => k.Name).ToArray(); + if (required.Length > 0) + { + result["required"] = new JsonArray(required.Select(r => (JsonNode)r!).ToArray()); + } + + return result; + } + + /// The schema of one key's value. + private static JsonObject Value(VocabularyKey key, Construct owner) => key.Kind switch + { + ValueKind.Text or ValueKind.Template or ValueKind.Name or ValueKind.Path or ValueKind.Format or ValueKind.StyleId => new JsonObject { ["type"] = "string" }, + ValueKind.Number => new JsonObject { ["type"] = "number" }, + ValueKind.Integer => new JsonObject { ["type"] = "integer" }, + ValueKind.True => new JsonObject { ["const"] = true }, + ValueKind.Boolean => new JsonObject { ["type"] = "boolean" }, + ValueKind.Length => Ref("length"), + ValueKind.Color => Ref("color"), + ValueKind.Line => Ref("line"), + ValueKind.Edges => new JsonObject { ["oneOf"] = new JsonArray(Ref("line"), Ref("edges")) }, + ValueKind.Padding => Ref("padding"), + ValueKind.PageSize => new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["enum"] = new JsonArray("A4", "A5", "Letter", "Legal") }, Ref("pageSize")) }, + ValueKind.TwoLengths => Ref("twoLengths"), + ValueKind.Font => new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "string" }, Ref("font")) }, + ValueKind.Condition => new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "string" }, Ref("rawCondition")) }, + ValueKind.Blocks => Ref("blocks"), + ValueKind.BlocksOrNone => new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["const"] = "none" }, Ref("blocks")) }, + ValueKind.BlocksOrText => new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "string" }, Ref("blocks")) }, + ValueKind.Inlines => Ref("inlines"), + ValueKind.TextInlines => Ref("textInlines"), + ValueKind.Rows => Ref("rows"), + ValueKind.Cells => Ref("cells"), + ValueKind.Items => Ref("items"), + ValueKind.Branches => ArrayOf(Branch(owner)), + ValueKind.Columns => ArrayOf(new JsonObject { ["oneOf"] = new JsonArray(new JsonObject { ["type"] = "number" }, Ref("length")) }), + ValueKind.Map => key.Construct is { } inner + ? new JsonObject { ["type"] = "object", ["additionalProperties"] = Ref(inner) } + : new JsonObject { ["type"] = "object" }, + ValueKind.List => key.Construct is { } inner ? ArrayOf(Ref(inner)) : new JsonObject { ["type"] = "array" }, + _ => key.Construct is { } inner ? Ref(inner) : new JsonObject { ["type"] = "object" }, + }; + + /// An elseIf branch whose then takes what the owning conditional's then takes. + private static JsonObject Branch(Construct owner) + { + VocabularyKey then = owner.Keys.Single(k => k.Name == "then"); + return new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject + { + ["if"] = Value(new VocabularyKey("if", ValueKind.Condition, false, string.Empty), owner), + ["then"] = Value(then, owner), + }, + ["required"] = new JsonArray("if", "then"), + ["additionalProperties"] = false, + }; + } + + /// A component reference per registered component: its name and its parameters. + private static JsonObject Components(Construct construct, ComponentCatalog components) + { + JsonArray choices = new JsonArray(); + foreach (ComponentCatalog.Registration registration in components.Registrations) + { + JsonObject parameters = new JsonObject(); + foreach ((string name, Type type) in registration.ParameterTypes()) + { + parameters[name] = Parameter(type); + } + + JsonObject properties = new JsonObject { ["component"] = new JsonObject { ["const"] = registration.Name } }; + JsonArray required = new JsonArray("component"); + if (parameters.Count > 0) + { + properties["params"] = new JsonObject + { + ["type"] = "object", + ["properties"] = parameters, + ["required"] = new JsonArray(parameters.Select(p => (JsonNode)p.Key!).ToArray()), + ["additionalProperties"] = false, + }; + required.Add("params"); + } + + choices.Add(new JsonObject { ["type"] = "object", ["properties"] = properties, ["required"] = required, ["additionalProperties"] = false }); + } + + return new JsonObject { ["description"] = construct.Description, ["oneOf"] = choices }; + } + + private static JsonObject Parameter(Type type) + { + type = Nullable.GetUnderlyingType(type) ?? type; + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) + { + return ArrayOf(Parameter(type.GetGenericArguments()[0])); + } + + if (type.IsEnum) + { + return new JsonObject { ["enum"] = new JsonArray(Enum.GetNames(type).Select(n => (JsonNode)(char.ToLowerInvariant(n[0]) + n[1..]))!.ToArray()) }; + } + + return type == typeof(bool) ? new JsonObject { ["type"] = "boolean" } + : type == typeof(int) || type == typeof(long) ? new JsonObject { ["type"] = "integer" } + : type == typeof(double) || type == typeof(decimal) ? new JsonObject { ["type"] = "number" } + : type == typeof(Builder.Length) ? Ref("length") + : type == typeof(Builder.Color) ? Ref("color") + : new JsonObject { ["type"] = "string" }; + } + + private static JsonObject OneOf(IEnumerable constructs, bool withString) + { + JsonArray choices = new JsonArray(); + if (withString) + { + choices.Add(new JsonObject { ["type"] = "string" }); + } + + foreach (string name in constructs) + { + choices.Add(Ref(name)); + } + + return new JsonObject { ["oneOf"] = choices }; + } + + private static JsonObject Ref(string name) => new JsonObject { ["$ref"] = "#/$defs/" + name }; + + private static JsonObject ArrayOf(JsonObject items) => new JsonObject { ["type"] = "array", ["items"] = items }; + + private static JsonObject Pattern(string pattern, string description) => + new JsonObject { ["type"] = "string", ["pattern"] = pattern, ["description"] = description }; +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonValues.cs b/src/TriasDev.Templify.Builder/Json/JsonValues.cs new file mode 100644 index 00000000..609f8ca6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonValues.cs @@ -0,0 +1,166 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.RegularExpressions; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// How values are written in JSON definitions: lengths with units, colours as #RRGGBB, page sizes by name, +/// borders and boxes CSS-style. Always invariant, so a file reads the same under every culture. +/// +internal static partial class JsonValues +{ + private const double MillimetersPerPoint = 25.4 / 72.0; + + private static readonly (string Name, PageSize Size)[] _pageSizes = + { + ("A4", PageSize.A4), ("A5", PageSize.A5), ("Letter", PageSize.Letter), ("Legal", PageSize.Legal), + }; + + /// + /// A length in its shortest exact form: whole or half points as points (10pt, 10.5pt), else + /// millimetres when a value with at most two decimals gives the same length (25mm), else points. + /// + public static string Length(Length value) + { + if (value.Millipoints % 500 == 0) + { + return Number(value.Millipoints / 1000.0) + "pt"; + } + + double millimeters = Math.Round(value.Millipoints / 1000.0 * MillimetersPerPoint, 2, MidpointRounding.AwayFromZero); + if (Builder.Length.FromMillimeters(millimeters).Millipoints == value.Millipoints) + { + return Number(millimeters) + "mm"; + } + + return Number(value.Millipoints / 1000.0) + "pt"; + } + + /// Reads a length with a unit: pt, mm, cm or in. + public static bool TryLength(string? text, out Length value) + { + value = default; + Match match = text is null ? Match.Empty : LengthPattern().Match(text); + if (!match.Success || !double.TryParse(match.Groups[1].Value, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out double number)) + { + return false; + } + + try + { + value = match.Groups[2].Value switch + { + "pt" => Builder.Length.FromPoints(number), + "mm" => Builder.Length.FromMillimeters(number), + "cm" => Builder.Length.FromMillimeters(number * 10), + _ => Builder.Length.FromPoints(number * 72), + }; + return true; + } + catch (ArgumentException) + { + return false; + } + } + + /// A colour as #RRGGBB, upper case. + public static string Color(Color value) => "#" + value.Hex; + + /// Reads #RRGGBB in either case. + public static bool TryColor(string? text, out Color value) + { + value = default; + if (text is null || !ColorPattern().IsMatch(text)) + { + return false; + } + + value = Builder.Color.FromHex(text[1..]); + return true; + } + + /// The name of a named page size, or null. + public static string? PageSizeName(PageSize size) => _pageSizes.FirstOrDefault(p => p.Size == size).Name; + + /// Reads a page size name. + public static bool TryPageSize(string? name, out PageSize? size) + { + size = _pageSizes.FirstOrDefault(p => p.Name == name).Size; + return size is not null; + } + + /// A border line: 0.5pt #D4D4D4. + public static string Border(BorderLine line) => Length(line.Width) + " " + Color(line.Color); + + /// Reads a border line. + public static bool TryBorder(string? text, out BorderLine? line) + { + line = null; + string[] parts = text?.Split(' ') ?? []; + if (parts.Length != 2 || !TryLength(parts[0], out Length width) || !TryColor(parts[1], out Color color)) + { + return false; + } + + line = new BorderLine(width, color); + return true; + } + + /// Four sides CSS-style: one value when all are equal, two for vertical/horizontal pairs, else four. + public static string Box(Length top, Length right, Length bottom, Length left) + { + if (top == right && top == bottom && top == left) + { + return Length(top); + } + + return top == bottom && right == left + ? Length(top) + " " + Length(right) + : string.Join(" ", Length(top), Length(right), Length(bottom), Length(left)); + } + + /// Reads one, two, three or four lengths (CSS order: top, right, bottom, left). + public static bool TryBox(string? text, out (Length Top, Length Right, Length Bottom, Length Left) box) + { + box = default; + string[] parts = text?.Split(' ') ?? []; + Length[] values = new Length[parts.Length]; + for (int i = 0; i < parts.Length; i++) + { + if (!TryLength(parts[i], out values[i])) + { + return false; + } + } + + switch (values.Length) + { + case 1: + box = (values[0], values[0], values[0], values[0]); + return true; + case 2: + box = (values[0], values[1], values[0], values[1]); + return true; + case 3: + box = (values[0], values[1], values[2], values[1]); + return true; + case 4: + box = (values[0], values[1], values[2], values[3]); + return true; + default: + return false; + } + } + + private static string Number(double value) => value.ToString("0.###", CultureInfo.InvariantCulture); + + [GeneratedRegex("^(-?[0-9]+(?:\\.[0-9]+)?)(pt|mm|cm|in)$", RegexOptions.CultureInvariant)] + private static partial Regex LengthPattern(); + + [GeneratedRegex("^#[0-9A-Fa-f]{6}$", RegexOptions.CultureInvariant)] + private static partial Regex ColorPattern(); +} diff --git a/src/TriasDev.Templify.Builder/Json/JsonVocabulary.cs b/src/TriasDev.Templify.Builder/Json/JsonVocabulary.cs new file mode 100644 index 00000000..ba6ab8d6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/JsonVocabulary.cs @@ -0,0 +1,602 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// What a key of a JSON construct takes. +internal enum ValueKind +{ + /// Literal text. + Text, + + /// Text with placeholders {{path}}, expressions {{(condition):format}} and text keys [[key]]. + Template, + + /// A number. + Number, + + /// A whole number. + Integer, + + /// true only: the key names the construct. + True, + + /// true or false. + Boolean, + + /// A length with a unit: "6pt", "10mm", "2cm", "0.5in". + Length, + + /// A colour: "#1F4E79" or a theme token "$accent". + Color, + + /// A line: thickness and colour, "0.5pt #D4D4D4". + Line, + + /// A line for all sides, or an object with top, right, bottom, left. + Edges, + + /// One to four lengths in CSS order: "6pt", "6pt 8pt", "8pt 6pt 9pt 6pt". + Padding, + + /// A page size: "A4", "A5", "Letter", "Legal", or { "width", "height" }. + PageSize, + + /// Two lengths: header and footer distance. + TwoLengths, + + /// A font family, a theme token "$body", or { "family", "embedded" }. + Font, + + /// A condition in Templify's syntax, or { "raw", "uses" }. + Condition, + + /// A data path: "order.lines", "line.amount". + Path, + + /// A name: letters, digits, _. + Name, + + /// A value format: date:…, number:…, currency, yesno, … + Format, + + /// The id of a style the definition's style sheet defines. + StyleId, + + /// A list of blocks. + Blocks, + + /// A list of blocks, or "none". + BlocksOrNone, + + /// A string (one paragraph), or a list of blocks. + BlocksOrText, + + /// A string, or a list of inlines. + Inlines, + + /// A string, or a list of text inlines (text, styled text, nested if). + TextInlines, + + /// A list of row items. + Rows, + + /// A list of cells. + Cells, + + /// A list of list items. + Items, + + /// A list of { "if", "then" } branches. + Branches, + + /// A list of columns: a number is a relative weight, a length a fixed width. + Columns, + + /// An object whose members are named by the author (styles by id, texts by key, …). + Map, + + /// A list of objects described elsewhere. + List, + + /// An object described elsewhere. + Object, +} + +/// A key of a JSON construct. +internal sealed record VocabularyKey(string Name, ValueKind Kind, bool Required, string Description, string? Construct = null); + +/// +/// A JSON construct: where it is written (), the key that identifies it among its siblings +/// (; null for a construct that is a whole value), its keys and an example. +/// +internal sealed record Construct(string Name, string Group, string? Discriminator, IReadOnlyList Keys, string Description, string Example); + +/// +/// The JSON definition format as data: what an agent needs to know before editing, and what the JSON Schema is made of. +/// A test cross-checks every construct against the reader (its example imports; its keys are the reader's "allowed here" +/// list), so this table cannot drift from what accepts. +/// +internal static class JsonVocabulary +{ + private static VocabularyKey K(string name, ValueKind kind, string description, bool required = false, string? construct = null) => + new VocabularyKey(name, kind, required, description, construct); + + /// Gets every construct, in the order a definition is read. + public static IReadOnlyList All { get; } = + [ + // ── root ────────────────────────────────────────────────────────────── + new Construct("definition", "root", null, + [ + K("$schema", ValueKind.Text, "Optional URI of the JSON Schema, for editors."), + K("templifyDefinition", ValueKind.Integer, "The format version: 1.", required: true), + K("identity", ValueKind.Object, "{ \"id\": \"order-confirmation\", \"version\": 1 }: the template's id and the definition's version.", required: true), + K("texts", ValueKind.Map, "Translatable texts: { \"title\": { \"de\": \"…\", \"en\": \"…\" } }, used as [[title]] in any text."), + K("assets", ValueKind.Map, "Images by name: { \"logo\": \"sha256:…\" }; the bytes come with the import."), + K("theme", ValueKind.Object, "Colour and font tokens used as $name.", construct: "theme"), + K("properties", ValueKind.Object, "Document properties.", construct: "properties"), + K("styles", ValueKind.Object, "The style sheet.", construct: "styles"), + K("page", ValueKind.Object, "Page size, margins, header and footer.", construct: "page"), + K("content", ValueKind.Blocks, "The document body."), + K("components", ValueKind.Object, "Reserved for components defined inside a definition (a later version); not allowed yet."), + ], + "A template definition. Only templifyDefinition, identity and content are needed.", + """{ "templifyDefinition": 1, "identity": { "id": "example", "version": 1 }, "content": [ "Hello {{customer.name}}" ] }"""), + + new Construct("properties", "root", null, + [ + K("title", ValueKind.Template, "Document title."), + K("author", ValueKind.Template, "Author."), + K("subject", ValueKind.Template, "Subject."), + ], + "Standard document properties.", + """{ "title": "[[title]]", "author": "Example Trading" }"""), + + new Construct("theme", "root", null, + [ + K("colors", ValueKind.Map, "Colour tokens: { \"accent\": \"#1F4E79\" }, used as \"$accent\"."), + K("fonts", ValueKind.Map, "Font tokens: { \"body\": \"Liberation Sans\" } or an embedded font { \"body\": { \"family\", \"embedded\" } }, used as \"$body\"."), + ], + "Named colours and fonts; the host may override them per customer.", + """{ "colors": { "accent": "#1F4E79" }, "fonts": { "body": "Liberation Sans" } }"""), + + new Construct("font", "root", null, + [ + K("family", ValueKind.Text, "The family name.", required: true), + K("embedded", ValueKind.Name, "The asset holding the font file (TrueType or OpenType).", required: true), + ], + "A font embedded in the document, where a font is expected (defaults, styles, theme fonts); a plain family name is not embedded.", + """{ "family": "Templify Embed Test", "embedded": "bodyFont" }"""), + + // ── styles ──────────────────────────────────────────────────────────── + new Construct("styles", "style", null, + [ + K("defaults", ValueKind.Object, "Default font, size, colour and paragraph style.", construct: "defaults"), + K("paragraph", ValueKind.Map, "Paragraph styles by id.", construct: "paragraphStyle"), + K("character", ValueKind.Map, "Character styles by id.", construct: "characterStyle"), + K("table", ValueKind.Map, "Table styles by id.", construct: "tableStyle"), + K("box", ValueKind.Map, "Box styles by id.", construct: "boxStyle"), + K("list", ValueKind.Map, "Bullet list styles by id.", construct: "listStyle"), + ], + "The style sheet. Formatting comes from named styles; a paragraph may only add space before/after and keep options.", + """{ "paragraph": { "Body": { "name": "Body Copy", "spaceAfter": "6pt" } } }"""), + + new Construct("defaults", "style", null, + [ + K("font", ValueKind.Font, "Default font."), + K("size", ValueKind.Length, "Default font size."), + K("color", ValueKind.Color, "Default text colour."), + K("paragraphStyle", ValueKind.StyleId, "The paragraph style of paragraphs without one."), + ], + "Document defaults.", + """{ "font": "Liberation Sans", "size": "10pt", "paragraphStyle": "Body" }"""), + + new Construct("paragraphStyle", "style", null, + [ + K("name", ValueKind.Text, "Display name in Word and LibreOffice (unique, no comma)."), + K("basedOn", ValueKind.StyleId, "The parent paragraph style."), + K("next", ValueKind.StyleId, "The style of the next paragraph when typing in Word."), + K("font", ValueKind.Font, "Font."), + K("size", ValueKind.Length, "Font size."), + K("color", ValueKind.Color, "Text colour."), + K("bold", ValueKind.Boolean, "Bold."), + K("italic", ValueKind.Boolean, "Italic."), + K("spaceBefore", ValueKind.Length, "Space above."), + K("spaceAfter", ValueKind.Length, "Space below."), + K("lineSpacing", ValueKind.Number, "Line spacing as a multiple (1.15)."), + K("lineHeight", ValueKind.Length, "Exact line height."), + K("minimumLineHeight", ValueKind.Length, "Minimum line height."), + K("alignment", ValueKind.Name, "start, center, end or justify."), + K("indentStart", ValueKind.Length, "Start indent."), + K("indentEnd", ValueKind.Length, "End indent."), + K("firstLineIndent", ValueKind.Length, "First-line indent; negative for a hanging indent."), + K("keepWithNext", ValueKind.Boolean, "Keep on the page of the next paragraph."), + K("keepLinesTogether", ValueKind.Boolean, "Keep the lines on one page."), + K("outlineLevel", ValueKind.Integer, "Makes it a heading of this level (1–9), listed by a table of contents."), + K("borderBottom", ValueKind.Line, "A line under the paragraph."), + K("borderBottomSpace", ValueKind.Length, "Space between the text and borderBottom (0–31 pt)."), + ], + "A paragraph style, under styles.paragraph by its id.", + """{ "name": "Section Heading", "basedOn": "Body", "size": "13pt", "bold": true, "keepWithNext": true, "outlineLevel": 1 }"""), + + new Construct("characterStyle", "style", null, + [ + K("name", ValueKind.Text, "Display name."), + K("basedOn", ValueKind.StyleId, "The parent character style."), + K("font", ValueKind.Font, "Font."), + K("size", ValueKind.Length, "Font size."), + K("color", ValueKind.Color, "Text colour."), + K("bold", ValueKind.Boolean, "Bold."), + K("italic", ValueKind.Boolean, "Italic."), + ], + "A character style, under styles.character by its id; used by styled text inlines.", + """{ "name": "Emphasis", "italic": true }"""), + + new Construct("tableStyle", "style", null, + [ + K("outerBorder", ValueKind.Edges, "Lines around the table, all sides or per side."), + K("rowRule", ValueKind.Line, "Line between rows."), + K("columnRule", ValueKind.Line, "Line between columns."), + K("headerRule", ValueKind.Line, "Line under the header rows."), + K("headerBackground", ValueKind.Color, "Background of header rows."), + K("cellPadding", ValueKind.Padding, "Space inside cells."), + K("paragraphStyle", ValueKind.StyleId, "Paragraph style of body cells."), + K("headerParagraphStyle", ValueKind.StyleId, "Paragraph style of header cells."), + ], + "A table style, under styles.table by its id.", + """{ "rowRule": "0.5pt #D4D4D4", "headerRule": "1pt $accent", "cellPadding": "3pt 5pt", "paragraphStyle": "Body" }"""), + + new Construct("boxStyle", "style", null, + [ + K("border", ValueKind.Line, "Frame line."), + K("background", ValueKind.Color, "Background."), + K("padding", ValueKind.Padding, "Space inside the frame."), + K("spaceAfter", ValueKind.Length, "Space after the box."), + ], + "A box style, under styles.box by its id.", + """{ "border": "0.75pt #96C6A8", "background": "#EFF6F1", "padding": "6pt 8pt" }"""), + + new Construct("listStyle", "style", null, + [ + K("itemStyle", ValueKind.StyleId, "Paragraph style of the items."), + K("levels", ValueKind.List, "The levels.", construct: "listLevel"), + ], + "A bullet list style, under styles.list by its id.", + """{ "itemStyle": "Body", "levels": [ { "level": 0, "bullet": "•", "indent": "6mm", "hanging": "4mm" } ] }"""), + + new Construct("listLevel", "style", null, + [ + K("level", ValueKind.Integer, "0 to 8; 0 when left out."), + K("bullet", ValueKind.Text, "The bullet character.", required: true), + K("indent", ValueKind.Length, "Text indent.", required: true), + K("hanging", ValueKind.Length, "How far the bullet hangs left of the text.", required: true), + ], + "One level of a list style.", + """{ "level": 1, "bullet": "–", "indent": "12mm", "hanging": "4mm" }"""), + + new Construct("edges", "style", null, + [ + K("top", ValueKind.Line, "Top line."), + K("right", ValueKind.Line, "Right line."), + K("bottom", ValueKind.Line, "Bottom line."), + K("left", ValueKind.Line, "Left line."), + ], + "Lines per side, where a line for all sides is also accepted (a table style's outerBorder, a cell's border).", + """{ "top": "0.75pt $accent" }"""), + + // ── page ────────────────────────────────────────────────────────────── + new Construct("page", "page", null, + [ + K("size", ValueKind.PageSize, "Page size; A4 when left out."), + K("margins", ValueKind.Padding, "Page edge to body text; 25mm on all sides when left out."), + K("headerFooterDistance", ValueKind.TwoLengths, "Page edge to header and to footer: \"12.5mm 12.5mm\"."), + K("header", ValueKind.Blocks, "Header of every page."), + K("footer", ValueKind.Blocks, "Footer of every page."), + K("firstPage", ValueKind.Object, "A different first page.", construct: "firstPage"), + ], + "The page setup.", + """{ "size": "A4", "margins": "25mm 20mm", "footer": [ "[[footer]]" ] }"""), + + new Construct("pageSize", "page", null, + [ + K("width", ValueKind.Length, "Width.", required: true), + K("height", ValueKind.Length, "Height.", required: true), + ], + "A page size of its own.", + """{ "width": "210mm", "height": "297mm" }"""), + + new Construct("firstPage", "page", null, + [ + K("header", ValueKind.BlocksOrNone, "Header of the first page; \"none\" for none."), + K("footer", ValueKind.BlocksOrNone, "Footer of the first page; \"none\" for none."), + ], + "The first page's header and footer.", + """{ "header": "none" }"""), + + // ── blocks ──────────────────────────────────────────────────────────── + new Construct("paragraph", "block", "paragraph", + [ + K("paragraph", ValueKind.Inlines, "The text: a string, or a list of inlines.", required: true), + K("style", ValueKind.StyleId, "Paragraph style; the inherited one when left out."), + K("spaceBefore", ValueKind.Length, "Space above, on top of the style."), + K("spaceAfter", ValueKind.Length, "Space below, on top of the style."), + K("keepWithNext", ValueKind.Boolean, "Keep on the page of the next paragraph."), + K("keepLinesTogether", ValueKind.Boolean, "Keep the lines on one page."), + ], + "A paragraph. A plain string in a block list is a paragraph in the inherited style.", + """{ "style": "Heading", "paragraph": "[[customer]]" }"""), + + new Construct("pageBreak", "block", "pageBreak", + [K("pageBreak", ValueKind.True, "true.", required: true)], + "The content after it starts on a new page.", + """{ "pageBreak": true }"""), + + new Construct("spacer", "block", "spacer", + [K("spacer", ValueKind.Length, "The height, at most 72pt.", required: true)], + "Vertical space without a style.", + """{ "spacer": "14pt" }"""), + + new Construct("if", "block", "if", + [ + K("if", ValueKind.Condition, "The condition.", required: true), + K("then", ValueKind.Blocks, "Blocks shown when it holds.", required: true), + K("elseIf", ValueKind.Branches, "Further conditions, in order.", construct: "branch"), + K("else", ValueKind.Blocks, "Blocks shown when none holds."), + ], + "Blocks shown only when a condition holds.", + """{ "if": "order.status = \"paid\"", "then": [ "Paid." ], "elseIf": [ { "if": "order.status = \"overdue\"", "then": [ "Overdue." ] } ], "else": [ "Open." ] }"""), + + new Construct("branch", "block", null, + [ + K("if", ValueKind.Condition, "The condition.", required: true), + K("then", ValueKind.Blocks, "What is shown when it holds (blocks, rows, items or inlines, as the conditional it belongs to).", required: true), + ], + "One elseIf branch of any conditional.", + """{ "if": "order.status = \"overdue\"", "then": [ "Overdue." ] }"""), + + new Construct("forEach", "block", "forEach", + [ + K("forEach", ValueKind.Path, "The collection.", required: true), + K("as", ValueKind.Name, "The item's name, used in paths inside: line.amount.", required: true), + K("body", ValueKind.Blocks, "Blocks repeated for each item.", required: true), + ], + "Repeats blocks for every item. Inside, {{@index}}, {{@number}}, {{@first}}, {{@last}}, {{@count}} are the loop's metadata.", + """{ "forEach": "order.lines", "as": "line", "body": [ "{{@number}}. {{line.description}}" ] }"""), + + new Construct("section", "block", "section", + [ + K("section", ValueKind.Name, "The section's name (letters, digits, _ . -), unique in the definition.", required: true), + K("blocks", ValueKind.Blocks, "Its blocks.", required: true), + ], + "A named group of blocks with no output of its own: the unit to find, read, replace or remove.", + """{ "section": "items", "blocks": [ "Items" ] }"""), + + new Construct("component", "block", "component", + [ + K("component", ValueKind.Name, "A component the host registered (see components).", required: true), + K("params", ValueKind.Map, "Its parameters by name; left out for a component without parameters."), + ], + "A reusable part the host provides; its content is the host's current version.", + """{ "component": "address", "params": { "address": "order.customer.address" } }"""), + + new Construct("list", "block", "list", + [ + K("list", ValueKind.Items, "The items.", required: true), + K("style", ValueKind.StyleId, "The list style.", required: true), + ], + "A bullet list.", + """{ "style": "Bullets", "list": [ "First", { "level": 1, "item": "Nested" } ] }"""), + + new Construct("box", "block", "box", + [ + K("box", ValueKind.Blocks, "The content.", required: true), + K("style", ValueKind.StyleId, "The box style.", required: true), + ], + "A framed, shaded block.", + """{ "style": "Panel", "box": [ "Paid – thank you!" ] }"""), + + new Construct("table", "block", "table", + [ + K("table", ValueKind.Rows, "The rows: header rows first.", required: true), + K("columns", ValueKind.Columns, "The columns: [\"10mm\", 4, 1] (fixed widths and relative weights).", required: true), + K("style", ValueKind.StyleId, "The table style."), + K("indent", ValueKind.Length, "Distance from the start of the frame; narrows the columns."), + K("spaceBefore", ValueKind.Length, "Space before the table."), + K("spaceAfter", ValueKind.Length, "Space after the table."), + ], + "A table.", + """{ "style": "Grid", "columns": [ 3, 1 ], "table": [ { "header": true, "row": [ "Item", "Amount" ] }, { "forEachRow": "order.lines", "as": "line", "rows": [ { "row": [ "{{line.description}}", "{{line.amount:currency}}" ] } ] } ] }"""), + + new Construct("rule", "block", "rule", + [K("rule", ValueKind.Object, "The rule.", required: true, construct: "ruleLine")], + "A horizontal line.", + """{ "rule": { "line": "0.5pt #D4D4D4", "spaceAbove": "4pt", "spaceBelow": "8pt" } }"""), + + new Construct("ruleLine", "block", null, + [ + K("line", ValueKind.Line, "Thickness (at most 6pt) and colour.", required: true), + K("spaceAbove", ValueKind.Length, "Space above."), + K("spaceBelow", ValueKind.Length, "Space below."), + K("width", ValueKind.Length, "A shorter rule: its width from the start."), + ], + "The value of rule.", + """{ "line": "1.5pt #1A1A1A", "spaceBelow": "14pt", "width": "12mm" }"""), + + new Construct("toc", "block", "toc", + [K("toc", ValueKind.Object, "The table of contents.", required: true, construct: "tocOptions")], + "A table of contents over the headings (styles with an outline level); Word and index-refreshing converters build it.", + """{ "toc": { "maxLevel": 2 } }"""), + + new Construct("tocOptions", "block", null, + [ + K("maxLevel", ValueKind.Integer, "The deepest level listed, 1–9; 3 when left out."), + K("levels", ValueKind.Map, "Entry styles by level: { \"1\": \"TocPart\" } (document-wide)."), + ], + "The value of toc.", + """{ "maxLevel": 2, "levels": { "1": "TocPart" } }"""), + + new Construct("raw", "block", "raw", + [K("raw", ValueKind.Object, "The XML.", required: true, construct: "rawXml")], + "A block written as format XML, only when the host allows raw XML.", + """{ "raw": { "docx": "Raw", "odt": "Raw", "uses": [] } }"""), + + new Construct("rawXml", "block", null, + [ + K("docx", ValueKind.Text, "The WordprocessingML paragraph or table.", required: true), + K("odt", ValueKind.Text, "The ODF paragraph, heading, list or table.", required: true), + K("uses", ValueKind.List, "The data paths the XML reads; none when left out."), + ], + "The value of raw.", + """{ "docx": "", "odt": "", "uses": [] }"""), + + // ── list items ──────────────────────────────────────────────────────── + new Construct("item", "item", "item", + [ + K("item", ValueKind.Inlines, "The text.", required: true), + K("level", ValueKind.Integer, "The level, 0 when left out; a string item is level 0."), + ], + "A list item. A plain string is an item at level 0.", + """{ "level": 1, "item": "{{check.note}}" }"""), + + new Construct("itemForEach", "item", "forEach", + [ + K("forEach", ValueKind.Path, "The collection.", required: true), + K("as", ValueKind.Name, "The item's name.", required: true), + K("items", ValueKind.Items, "Items repeated for each.", required: true), + ], + "Repeats list items.", + """{ "forEach": "order.checks", "as": "check", "items": [ "{{check.title}}" ] }"""), + + new Construct("itemIf", "item", "if", + [ + K("if", ValueKind.Condition, "The condition.", required: true), + K("then", ValueKind.Items, "Items shown when it holds.", required: true), + K("elseIf", ValueKind.Branches, "Further conditions.", construct: "branch"), + K("else", ValueKind.Items, "Items shown when none holds."), + ], + "List items shown only when a condition holds.", + """{ "if": "check.note exists", "then": [ { "level": 1, "item": "{{check.note}}" } ] }"""), + + // ── rows and cells ──────────────────────────────────────────────────── + new Construct("row", "row", "row", + [ + K("row", ValueKind.Cells, "The cells.", required: true), + K("header", ValueKind.Boolean, "A header row, repeated on every page; header rows come first."), + K("allowSplit", ValueKind.Boolean, "Let the row break across pages."), + K("paragraphStyle", ValueKind.StyleId, "Paragraph style of this row's cells."), + ], + "A table row.", + """{ "header": true, "row": [ "Item", "Amount" ] }"""), + + new Construct("forEachRow", "row", "forEachRow", + [ + K("forEachRow", ValueKind.Path, "The collection.", required: true), + K("as", ValueKind.Name, "The item's name.", required: true), + K("rows", ValueKind.Rows, "Rows repeated for each item.", required: true), + ], + "Repeats rows.", + """{ "forEachRow": "order.lines", "as": "line", "rows": [ { "row": [ "{{line.description}}", "{{line.amount:currency}}" ] } ] }"""), + + new Construct("rowsIf", "row", "rowsIf", + [ + K("rowsIf", ValueKind.Condition, "The condition.", required: true), + K("then", ValueKind.Rows, "Rows shown when it holds.", required: true), + K("elseIf", ValueKind.Branches, "Further conditions.", construct: "branch"), + K("else", ValueKind.Rows, "Rows shown when none holds."), + ], + "Rows shown only when a condition holds.", + """{ "rowsIf": "order.discount > 0", "then": [ { "row": [ "Discount", "{{order.discount:currency}}" ] } ] }"""), + + new Construct("cell", "cell", "content", + [ + K("content", ValueKind.BlocksOrText, "A string (one paragraph) or a list of blocks.", required: true), + K("style", ValueKind.StyleId, "Paragraph style when content is one string."), + K("span", ValueKind.Integer, "Columns spanned."), + K("background", ValueKind.Color, "Background."), + K("verticalAlign", ValueKind.Name, "top, center or bottom."), + K("border", ValueKind.Edges, "The cell's own lines, all sides or per side."), + K("padding", ValueKind.Padding, "The cell's own padding."), + ], + "A cell with options. A plain string is a cell with one paragraph.", + """{ "span": 2, "background": "#F2F5F8", "content": [ "Total" ] }"""), + + // ── inlines ─────────────────────────────────────────────────────────── + new Construct("text", "inline", "text", + [ + K("text", ValueKind.Template, "The text.", required: true), + K("style", ValueKind.StyleId, "Character style."), + ], + "Styled text. A plain string in an inline list is unstyled text.", + """{ "text": "{{order.number}}", "style": "Strong" }"""), + + new Construct("tabRight", "inline", "tabRight", + [K("tabRight", ValueKind.True, "true.", required: true)], + "A tab to a right-aligned stop at the end of the line.", + """{ "tabRight": true }"""), + + new Construct("pageNumber", "inline", "pageNumber", + [ + K("pageNumber", ValueKind.True, "true.", required: true), + K("style", ValueKind.StyleId, "Character style."), + ], + "The page number.", + """{ "pageNumber": true }"""), + + new Construct("pageCount", "inline", "pageCount", + [ + K("pageCount", ValueKind.True, "true.", required: true), + K("style", ValueKind.StyleId, "Character style."), + ], + "The number of pages.", + """{ "pageCount": true }"""), + + new Construct("image", "inline", "image", + [ + K("image", ValueKind.Name, "An entry of assets.", required: true), + K("alt", ValueKind.Text, "Text describing the image.", required: true), + K("width", ValueKind.Length, "Width; the height follows from the proportions when left out."), + K("height", ValueKind.Length, "Height."), + ], + "An image.", + """{ "image": "logo", "alt": "Logo", "height": "12mm" }"""), + + new Construct("expression", "inline", "expression", + [ + K("expression", ValueKind.Condition, "{ \"raw\": …, \"uses\": … } only; other expressions are written in text as {{(condition):format}}.", required: true), + K("format", ValueKind.Format, "The format, for example yesno.", required: true), + ], + "An expression over a raw condition.", + """{ "expression": { "raw": "Count > 0", "uses": [ "Count" ] }, "format": "yesno" }"""), + + new Construct("inlineIf", "inline", "if", + [ + K("if", ValueKind.Condition, "The condition.", required: true), + K("then", ValueKind.TextInlines, "Text shown when it holds.", required: true), + K("elseIf", ValueKind.Branches, "Further conditions.", construct: "branch"), + K("else", ValueKind.TextInlines, "Text shown when none holds."), + ], + "Text inside a paragraph shown only when a condition holds (text, styled text and nested ifs only).", + """{ "if": "line.inStock", "then": [ " (in stock)" ], "else": [ { "text": " (back-ordered)", "style": "Strong" } ] }"""), + + new Construct("rawCondition", "value", null, + [ + K("raw", ValueKind.Text, "The condition text, any Templify condition.", required: true), + K("uses", ValueKind.List, "The data paths it reads; none when left out."), + ], + "A condition written as Templify text where the string form cannot say it.", + """{ "raw": "Count > 0 and IsActive", "uses": [ "Count", "IsActive" ] }"""), + ]; + + /// The value forms, for the description. + public static IReadOnlyList<(string Name, string Description)> Values { get; } = + [ + ("text", "Literal text with {{path}} (a value), {{path:format}}, {{(condition):format}} (an expression) and [[key]] (a translatable text). \\t is a tab, \\n a line break. Markdown in values (**bold**) is rendered."), + ("path", "A data path with dots: order.customer.name; an index: order.lines[0].amount; inside a loop the item's name: line.amount; loop metadata: @index, @number, @first, @last, @count."), + ("condition", "Templify's syntax: a path alone (truthy), comparisons = != > >= < <= with a quoted string or a number (order.status = \"paid\", order.total > 1000) or another path (entry.ownerId = owner.id; a top-level path is written [limit]); in (\"a\", \"b\"); contains, startswith, endswith; exists, is empty, is not empty; and, or, not, parentheses."), + ("format", "date:yyyy-MM-dd, number:N2, currency, uppercase, lowercase, raw, join (join:\", \", join:name:\"; \"), yesno, checkbox, checkmark, truefalse, onoff, enabled, active, and host formats."), + ("length", "A number with pt, mm, cm or in: \"6pt\", \"10mm\"."), + ("color", "\"#1F4E79\" or a theme token \"$accent\"."), + ("line", "Thickness and colour: \"0.5pt #D4D4D4\", \"1pt $accent\"."), + ("padding", "One to four lengths in CSS order (top, right, bottom, left): \"6pt\", \"6pt 8pt\", \"8pt 6pt 9pt\", \"8pt 6pt 9pt 6pt\"."), + ]; +} diff --git a/src/TriasDev.Templify.Builder/Json/ModelJsonWriter.cs b/src/TriasDev.Templify.Builder/Json/ModelJsonWriter.cs new file mode 100644 index 00000000..81fcef2b --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/ModelJsonWriter.cs @@ -0,0 +1,1352 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Xml.Linq; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Writes a composed definition as JSON (design spec phase 3, section 4.1): one key per block kind, shorthands where +/// the C# API has them, fixed key order, values in ' forms. Binary data goes to the assets. +/// +internal sealed class ModelJsonWriter +{ + /// The format version written as templifyDefinition. + public const int FormatVersion = 1; + + private readonly Utf8JsonWriter _json; + private StyleSheet _styles = StyleSheet.Empty; + + private readonly HashSet _sectionNames = new HashSet(StringComparer.Ordinal); + + // The assets section: name → "sha256:…", in first-use order; unnamed images get one name per content (image-1, …). + private readonly List> _assetNames = new List>(); + private readonly Dictionary _unnamed = new Dictionary(StringComparer.Ordinal); + + // The theme section: token → value, in first-use order. + private readonly List> _themeColors = new List>(); + private readonly List> _themeFonts = new List>(); + private readonly List _problems = new List(); + + // The text keys inside registered components: the JSON holds only the reference, its texts section the translations. + private readonly List _componentKeys = new List(); + + /// The paragraph style the blocks being written inherit; a paragraph with this style is written without one. + private ParagraphStyleKey? _inherited; + + private readonly SortedDictionary _assets = new SortedDictionary(StringComparer.Ordinal); + private readonly PageSetup _page; + private readonly ComponentCatalog? _components; + + private ModelJsonWriter(Utf8JsonWriter json, PageSetup page, ComponentCatalog? components) + { + _json = json; + _page = page; + _components = components; + } + + /// Writes the definition. + public static (string Json, IReadOnlyDictionary Assets) Write(ComposedTemplate composed, TemplateIdentity identity, ComponentCatalog? components, Func, IReadOnlyList>? texts = null, bool indented = true) + { + using MemoryStream stream = new MemoryStream(); + ModelJsonWriter writer; + using (Utf8JsonWriter json = new Utf8JsonWriter(stream, new JsonWriterOptions + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + })) + { + writer = new ModelJsonWriter(json, composed.Model.Page, components); + writer.Document(composed, identity); + } + + if (writer._problems.Count > 0) + { + throw new TemplateBuildException(writer._problems); + } + + ThemeSection theme = writer.Theme(); + string written = WithTextKeys(Encoding.UTF8.GetString(stream.ToArray()), texts, writer._componentKeys, writer._assetNames, theme); + return (indented ? JsonLayout.Format(written) : written, writer._assets); + } + + /// + /// Turns the key markers of the composed texts into [[key]] in every string. A literal [[ (the import + /// would read a key) or a key outside the key syntax cannot be written: TB9204 at the string's pointer. + /// + private static string WithTextKeys(string json, Func, IReadOnlyList>? texts, IReadOnlyList componentKeys, IReadOnlyList> assets, ThemeSection theme) + { + using JsonDocument document = JsonDocument.Parse(json); + List problems = new List(); + List keys = UsedKeys(document.RootElement).Concat(componentKeys).Distinct(StringComparer.Ordinal).Where(TextKeys.IsKey).ToList(); + IReadOnlyList sections = texts?.Invoke(keys) ?? []; + using MemoryStream stream = new MemoryStream(); + using (Utf8JsonWriter output = new Utf8JsonWriter(stream, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping })) + { + output.WriteStartObject(); + foreach (JsonProperty property in document.RootElement.EnumerateObject()) + { + output.WritePropertyName(property.Name); + Copy(property.Value, "/" + JsonComposition.Escape(property.Name), output, problems); + if (property.Name == "identity") + { + if (sections.Count > 0) + { + Texts(output, sections); + } + + if (assets.Count > 0) + { + output.WriteStartObject("assets"); + foreach ((string name, string key) in assets) + { + output.WriteString(name, key); + } + + output.WriteEndObject(); + } + + WriteTheme(output, theme); + } + } + + output.WriteEndObject(); + } + + if (problems.Count > 0) + { + throw new TemplateBuildException(problems); + } + + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static void Texts(Utf8JsonWriter output, IReadOnlyList sections) + { + output.WriteStartObject("texts"); + foreach (TextSection section in sections) + { + output.WriteStartObject(section.Key); + foreach ((string language, string text) in section.Translations) + { + output.WriteString(language, text); + } + + output.WriteEndObject(); + } + + output.WriteEndObject(); + } + + + /// Whether the import reads back into exactly (literal "[[" or "[" before a key would not). + private static bool ReadsBack(string written, string text) + { + try + { + return TextKeys.Resolve(written, TextKeys.Marker) == text; + } + catch (FormatException) + { + return false; + } + } + + /// The keys of the text markers, in document order. + private static IEnumerable UsedKeys(JsonElement element) => element.ValueKind switch + { + JsonValueKind.Object => element.EnumerateObject().SelectMany(p => UsedKeys(p.Value)), + JsonValueKind.Array => element.EnumerateArray().SelectMany(UsedKeys), + JsonValueKind.String => TextKeys.MarkedKeys(element.GetString()!), + _ => [], + }; + + private static void Copy(JsonElement element, string at, Utf8JsonWriter output, List problems) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + output.WriteStartObject(); + foreach (JsonProperty property in element.EnumerateObject()) + { + output.WritePropertyName(property.Name); + Copy(property.Value, at + "/" + JsonComposition.Escape(property.Name), output, problems); + } + + output.WriteEndObject(); + break; + case JsonValueKind.Array: + output.WriteStartArray(); + int i = 0; + foreach (JsonElement item in element.EnumerateArray()) + { + Copy(item, at + "/" + i++, output, problems); + } + + output.WriteEndArray(); + break; + case JsonValueKind.String: + string text = element.GetString()!; + string written = TextKeys.MarkersToKeys(text); + List invalid = TextKeys.MarkedKeys(text).Where(k => !TextKeys.IsKey(k)).Distinct(StringComparer.Ordinal).ToList(); + foreach (string key in invalid) + { + problems.Add(new BuildDiagnostic(DiagnosticCodes.TextNotExportable, $"The text key '{key}' cannot be written as [[key]]: use letters, digits, '_', '.' or '-'.") { Location = at }); + } + + if (invalid.Count == 0 && written.Contains("[[", StringComparison.Ordinal) && !ReadsBack(written, text)) + { + problems.Add(new BuildDiagnostic(DiagnosticCodes.TextNotExportable, $"The text \"{written}\" contains '[[' that a JSON definition would not read back as written (a text key is [[key]]); change the text.") { Location = at }); + } + + output.WriteStringValue(written); + break; + default: + element.WriteTo(output); + break; + } + } + + private void Document(ComposedTemplate composed, TemplateIdentity identity) + { + DocumentModel model = composed.Model; + _json.WriteStartObject(); + _json.WriteNumber("templifyDefinition", FormatVersion); + _json.WriteStartObject("identity"); + _json.WriteString("id", identity.Id); + _json.WriteNumber("version", identity.Version); + _json.WriteEndObject(); + + if (model.Info.Title != null || model.Info.Author != null || model.Info.Subject != null) + { + _json.WriteStartObject("properties"); + StringIf("title", model.Info.Title); + StringIf("author", model.Info.Author); + StringIf("subject", model.Info.Subject); + _json.WriteEndObject(); + } + + _styles = composed.UserStyles; + _inherited = _styles.DefaultParagraphStyle; + Styles(composed.UserStyles); + Page(model.Page); + _json.WritePropertyName("content"); + Blocks(model.Body); + _json.WriteEndObject(); + } + + // ── styles ─────────────────────────────────────────────────────────────── + + private void Styles(StyleSheet sheet) + { + bool hasDefaults = HasText(sheet.Defaults) || sheet.DefaultParagraphStyle != null; + if (!hasDefaults && sheet.ParagraphStyles.Count == 0 && sheet.CharacterStyles.Count == 0 && sheet.TableStyles.Count == 0 + && sheet.BoxStyles.Count == 0 && sheet.ListStyles.Count == 0) + { + return; + } + + _json.WriteStartObject("styles"); + if (hasDefaults) + { + _json.WriteStartObject("defaults"); + Text(sheet.Defaults); + StringIf("paragraphStyle", sheet.DefaultParagraphStyle?.Id); + _json.WriteEndObject(); + } + + Section("paragraph", sheet.ParagraphStyles, style => + { + _json.WriteStartObject(style.Key.Id); + _json.WriteString("name", style.Key.DisplayName); + StringIf("basedOn", style.BasedOn?.Id); + StringIf("next", style.Next?.Id); + Text(style.Text); + ParagraphProperties p = style.Paragraph; + LengthIf("spaceBefore", p.SpaceBefore); + LengthIf("spaceAfter", p.SpaceAfter); + if (p.LineHeight is { } line) + { + switch (line.Rule) + { + case LineHeightRule.Proportional: + _json.WriteNumber("lineSpacing", line.Multiple); + break; + case LineHeightRule.Exact: + _json.WriteString("lineHeight", JsonValues.Length(line.Height)); + break; + default: + _json.WriteString("minimumLineHeight", JsonValues.Length(line.Height)); + break; + } + } + + if (p.Alignment is { } alignment) + { + _json.WriteString("alignment", Enum(alignment)); + } + + LengthIf("indentStart", p.IndentStart); + LengthIf("indentEnd", p.IndentEnd); + LengthIf("firstLineIndent", p.FirstLineIndent); + BoolIf("keepWithNext", p.KeepWithNext); + BoolIf("keepLinesTogether", p.KeepLinesTogether); + if (p.OutlineLevel is { } level) + { + _json.WriteNumber("outlineLevel", level); + } + + BorderIf("borderBottom", p.BorderBottom); + LengthIf("borderBottomSpace", p.BorderBottom is null ? null : p.BorderBottomSpace); + + _json.WriteEndObject(); + }); + + Section("character", sheet.CharacterStyles, style => + { + _json.WriteStartObject(style.Key.Id); + _json.WriteString("name", style.Key.DisplayName); + StringIf("basedOn", style.BasedOn?.Id); + Text(style.Text); + _json.WriteEndObject(); + }); + + Section("table", sheet.TableStyles, style => + { + _json.WriteStartObject(style.Key.Id); + EdgesIf("outerBorder", style.Outer); + BorderIf("rowRule", style.RowRule); + BorderIf("columnRule", style.ColumnRule); + BorderIf("headerRule", style.HeaderRule); + ColorIf("headerBackground", style.HeaderBackground); + if (style.Padding != TableStyleDefinition.DefaultPadding) + { + // Two values (vertical horizontal) as before when the sides pair up; four otherwise. + Insets p = style.Padding; + _json.WriteString("cellPadding", p.Top == p.Bottom && p.Left == p.Right + ? JsonValues.Length(p.Top) + " " + JsonValues.Length(p.Right) + : JsonValues.Box(p.Top, p.Right, p.Bottom, p.Left)); + } + + StringIf("paragraphStyle", style.ParagraphStyle?.Id); + StringIf("headerParagraphStyle", style.HeaderParagraphStyle?.Id); + _json.WriteEndObject(); + }); + + Section("box", sheet.BoxStyles, style => + { + _json.WriteStartObject(style.Key.Id); + BorderIf("border", style.Border); + ColorIf("background", style.Background); + if (style.Padding != Insets.Of(6.Pt(), 6.Pt())) + { + _json.WriteString("padding", JsonValues.Box(style.Padding.Top, style.Padding.Right, style.Padding.Bottom, style.Padding.Left)); + } + + LengthIf("spaceAfter", style.SpaceAfter); + _json.WriteEndObject(); + }); + + Section("list", sheet.ListStyles, style => + { + _json.WriteStartObject(style.Key.Id); + StringIf("itemStyle", style.ItemStyle?.Id); + _json.WriteStartArray("levels"); + foreach ((int level, ListLevel definition) in style.Levels) + { + _json.WriteStartObject(); + _json.WriteNumber("level", level); + _json.WriteString("bullet", definition.Bullet); + _json.WriteString("indent", JsonValues.Length(definition.Indent)); + _json.WriteString("hanging", JsonValues.Length(definition.Hanging)); + _json.WriteEndObject(); + } + + _json.WriteEndArray(); + _json.WriteEndObject(); + }); + + _json.WriteEndObject(); + } + + private void Section(string name, IReadOnlyList items, Action write) + { + if (items.Count == 0) + { + return; + } + + _json.WriteStartObject(name); + foreach (T item in items) + { + write(item); + } + + _json.WriteEndObject(); + } + + private static bool HasText(TextProperties text) => + text.Font != null || text.Size != null || text.Color != null || text.Bold != null || text.Italic != null; + + private void Text(TextProperties text) + { + if (text.Font is { } font) + { + if (font.TokenName is { } token) + { + ThemeValue(_themeFonts, token, font); + _json.WriteString("font", "$" + token); + } + else + { + _json.WritePropertyName("font"); + FontValue(font); + } + } + + LengthIf("size", text.Size); + ColorIf("color", text.Color); + BoolIf("bold", text.Bold); + BoolIf("italic", text.Italic); + } + + // ── page ───────────────────────────────────────────────────────────────── + + private void Page(PageSetup page) + { + PageSetupBuilder defaults = new PageSetupBuilder(); + bool size = page.Size != defaults.Size; + bool margins = page.Top != defaults.Top || page.Right != defaults.Right || page.Bottom != defaults.Bottom || page.Left != defaults.Left; + bool distances = page.HeaderDistance != defaults.HeaderDistance || page.FooterDistance != defaults.FooterDistance; + if (!size && !margins && !distances && page.Header == null && page.Footer == null && !page.DistinctFirstPage) + { + return; + } + + _json.WriteStartObject("page"); + if (size) + { + if (JsonValues.PageSizeName(page.Size) is { } name) + { + _json.WriteString("size", name); + } + else + { + _json.WriteStartObject("size"); + _json.WriteString("width", JsonValues.Length(page.Size.Width)); + _json.WriteString("height", JsonValues.Length(page.Size.Height)); + _json.WriteEndObject(); + } + } + + if (margins) + { + _json.WriteString("margins", JsonValues.Box(page.Top, page.Right, page.Bottom, page.Left)); + } + + if (distances) + { + _json.WriteString("headerFooterDistance", JsonValues.Length(page.HeaderDistance) + " " + JsonValues.Length(page.FooterDistance)); + } + + if (page.Header is { } header) + { + _json.WritePropertyName("header"); + Blocks(header); + } + + if (page.Footer is { } footer) + { + _json.WritePropertyName("footer"); + Blocks(footer); + } + + if (page.DistinctFirstPage) + { + _json.WriteStartObject("firstPage"); + FirstPagePart("header", page.FirstHeader, page.Header); + FirstPagePart("footer", page.FirstFooter, page.Footer); + _json.WriteEndObject(); + } + + _json.WriteEndObject(); + } + + /// The first page's part: omitted when it is the running one, "none" when empty. + private void FirstPagePart(string name, List? first, List? running) + { + if (first is null || ReferenceEquals(first, running)) + { + return; + } + + if (first.Count == 0) + { + _json.WriteString(name, "none"); + return; + } + + _json.WritePropertyName(name); + Blocks(first); + } + + // ── blocks ─────────────────────────────────────────────────────────────── + + private void Blocks(IEnumerable blocks) + { + _json.WriteStartArray(); + foreach (Block block in blocks) + { + Block(block); + } + + _json.WriteEndArray(); + } + + /// A component type's name as a section name: Card`1 is Card; anything else unusable becomes Component. + private static string ComponentSectionName(Type type) + { + string name = type.Name.Split('`')[0]; + return SectionComponent.IsValidName(name) ? name : "Component"; + } + + /// The text keys a component's blocks use, in order (written aside, only to find the markers). + private List KeysIn(List body) + { + using MemoryStream stream = new MemoryStream(); + ModelJsonWriter aside; + using (Utf8JsonWriter json = new Utf8JsonWriter(stream)) + { + aside = new ModelJsonWriter(json, _page, _components) { _styles = _styles, _inherited = _inherited }; + aside.Blocks(body); + } + + using JsonDocument document = JsonDocument.Parse(stream.ToArray()); + return UsedKeys(document.RootElement).Concat(aside._componentKeys).ToList(); + } + + private void Block(Block block) + { + switch (block) + { + case ParagraphBlock paragraph when IsPlainParagraph(paragraph, out string? text): + _json.WriteStringValue(text); + break; + + case ParagraphBlock paragraph: + _json.WriteStartObject(); + StringIf("style", Equals(paragraph.Style, _inherited) ? null : paragraph.Style?.Id); + _json.WritePropertyName("paragraph"); + InlineContent(paragraph.Inlines); + if (paragraph.Options is { } options) + { + LengthIf("spaceBefore", options.SpaceBefore); + LengthIf("spaceAfter", options.SpaceAfter); + BoolIf("keepWithNext", options.KeepWithNext); + BoolIf("keepLinesTogether", options.KeepLinesTogether); + } + + _json.WriteEndObject(); + break; + + case PageBreakBlock: + _json.WriteStartObject(); + _json.WriteBoolean("pageBreak", true); + _json.WriteEndObject(); + break; + + case ConditionalBlock conditional: + Conditional(conditional.Branches.Select(b => (b.Condition, (Action)(() => Blocks(b.Body)))).ToList(), conditional.Else is { } e ? () => Blocks(e) : null); + break; + + case LoopBlock loop: + _json.WriteStartObject(); + _json.WriteString("forEach", loop.Collection.ToString()); + _json.WriteString("as", loop.ItemName); + _json.WritePropertyName("body"); + Blocks(loop.Body); + _json.WriteEndObject(); + break; + + case ComponentBlock component when _components?.Find(component.Component.GetType()) is { } registration: + _json.WriteStartObject(); + _json.WriteString("component", registration.Name); + if (registration.HasParameters) + { + _json.WritePropertyName("params"); + registration.WriteParameters(_json, component.Component, _components!.DataNaming, ColorText); + } + + _json.WriteEndObject(); + _componentKeys.AddRange(KeysIn(component.Body)); + break; + + case ComponentBlock component: + // A section, or a component the catalog does not know: its blocks under a name unique in the file. A + // versioned component would lose its version that way (its content frozen in the JSON). + if (component.Component is not SectionComponent && ComponentVersions.VersionOf(component.Component.GetType()) is { } version) + { + _problems.Add(new BuildDiagnostic( + DiagnosticCodes.TextNotExportable, + $"The component {component.Component.GetType().Name} has a version ({version}): register it in the ComponentCatalog of the export, so the JSON names it and builds always use its current version.")); + } + + _json.WriteStartObject(); + _json.WriteString("section", SectionName(component.Component is SectionComponent section ? section.Name : ComponentSectionName(component.Component.GetType()))); + _json.WritePropertyName("blocks"); + Blocks(component.Body); + _json.WriteEndObject(); + break; + + case ListBlock list: + _json.WriteStartObject(); + _json.WriteString("style", list.Style.Id); + _json.WritePropertyName("list"); + ListItems(list.Items); + _json.WriteEndObject(); + break; + + case TableBlock { BoxStyle: { } boxStyle } box: + _json.WriteStartObject(); + _json.WriteString("style", boxStyle.Id); + _json.WritePropertyName("box"); + TableRowModel boxRow = box.AllRows().Single(); + Inheriting(StyleInheritance.ForCell(_styles, box, boxRow), () => Blocks(boxRow.Cells.Single().Content)); + _json.WriteEndObject(); + break; + + case TableBlock table: + Table(table); + break; + + case SpacerBlock spacer: + _json.WriteStartObject(); + _json.WriteString("spacer", JsonValues.Length(spacer.Height)); + _json.WriteEndObject(); + break; + + case RuleBlock rule: + _json.WriteStartObject(); + _json.WriteStartObject("rule"); + _json.WriteString("line", BorderText(rule.Line)); + if (rule.SpaceBefore != Length.Zero || rule.SpaceAfter != Length.Zero) + { + _json.WriteString("spaceAbove", JsonValues.Length(rule.SpaceBefore)); + _json.WriteString("spaceBelow", JsonValues.Length(rule.SpaceAfter)); + } + + LengthIf("width", rule.Width); + + _json.WriteEndObject(); + _json.WriteEndObject(); + break; + + case TocBlock toc: + _json.WriteStartObject(); + _json.WriteStartObject("toc"); + _json.WriteNumber("maxLevel", toc.MaxLevel); + if (toc.EntryStyles is { Count: > 0 } entryStyles) + { + _json.WriteStartObject("levels"); + foreach ((int level, ParagraphStyleKey style) in entryStyles) + { + _json.WriteString(level.ToString(System.Globalization.CultureInfo.InvariantCulture), style.Id); + } + + _json.WriteEndObject(); + } + + _json.WriteEndObject(); + _json.WriteEndObject(); + break; + + case RawXmlBlock raw: + RawContext context = new RawContext(raw.Raw, _page.FrameWidth); + _json.WriteStartObject(); + _json.WriteStartObject("raw"); + _json.WriteString("docx", CanonicalXml(raw.Raw.Docx(context))); + _json.WriteString("odt", CanonicalXml(raw.Raw.Odt(context))); + Paths("uses", raw.Raw.Uses); + _json.WriteEndObject(); + _json.WriteEndObject(); + break; + + default: + throw new NotSupportedException($"The JSON export does not know the block {block.GetType().Name}."); + } + } + + /// The name, or with "-2", "-3", … when the file already has it (names are unique in a file). + private string SectionName(string name) + { + string unique = name; + for (int i = 2; !_sectionNames.Add(unique); i++) + { + unique = name + "-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + return unique; + } + + /// A paragraph written as a bare string: inherited style, not a list item, one unstyled run. + private bool IsPlainParagraph(ParagraphBlock paragraph, out string? text) + { + text = null; + return paragraph.List is null && paragraph.Options is null && Equals(paragraph.Style, _inherited) && IsSingleString(paragraph.Inlines, out text); + } + + private void Inheriting(ParagraphStyleKey? inherited, Action write) + { + ParagraphStyleKey? outer = _inherited; + _inherited = inherited; + try + { + write(); + } + finally + { + _inherited = outer; + } + } + + private void Conditional(List<(Condition Condition, Action Write)> branches, Action? otherwise) + { + _json.WriteStartObject(); + _json.WritePropertyName("if"); + Condition(branches[0].Condition); + _json.WritePropertyName("then"); + branches[0].Write(); + if (branches.Count > 1) + { + _json.WriteStartArray("elseIf"); + foreach ((Condition condition, Action write) in branches.Skip(1)) + { + _json.WriteStartObject(); + _json.WritePropertyName("if"); + Condition(condition); + _json.WritePropertyName("then"); + write(); + _json.WriteEndObject(); + } + + _json.WriteEndArray(); + } + + if (otherwise != null) + { + _json.WritePropertyName("else"); + otherwise(); + } + + _json.WriteEndObject(); + } + + private void ListItems(IEnumerable items) + { + _json.WriteStartArray(); + foreach (Block item in items) + { + switch (item) + { + case ParagraphBlock { List: { } info } paragraph when info.Level == 0 && IsSingleString(paragraph.Inlines, out string? text): + _json.WriteStringValue(text); + break; + + case ParagraphBlock { List: { } info } paragraph: + _json.WriteStartObject(); + if (info.Level != 0) + { + _json.WriteNumber("level", info.Level); + } + + _json.WritePropertyName("item"); + InlineContent(paragraph.Inlines); + _json.WriteEndObject(); + break; + + case LoopBlock loop: + _json.WriteStartObject(); + _json.WriteString("forEach", loop.Collection.ToString()); + _json.WriteString("as", loop.ItemName); + _json.WritePropertyName("items"); + ListItems(loop.Body); + _json.WriteEndObject(); + break; + + case ConditionalBlock conditional: + Conditional( + conditional.Branches.Select(b => (b.Condition, (Action)(() => ListItems(b.Body)))).ToList(), + conditional.Else is { } e ? () => ListItems(e) : null); + break; + + default: + throw new NotSupportedException($"A list cannot hold {item.GetType().Name}."); + } + } + + _json.WriteEndArray(); + } + + // ── tables ─────────────────────────────────────────────────────────────── + + private void Table(TableBlock table) + { + _json.WriteStartObject(); + StringIf("style", table.Style?.Id); + if (table.Columns.Count > 0) + { + _json.WriteStartArray("columns"); + foreach (ColumnSpec column in table.Columns) + { + if (column.Fixed is { } width) + { + _json.WriteStringValue(JsonValues.Length(width)); + } + else + { + _json.WriteNumberValue(column.Weight); + } + } + + _json.WriteEndArray(); + } + + LengthIf("indent", table.Indent); + LengthIf("spaceBefore", table.SpaceBefore); + LengthIf("spaceAfter", table.SpaceAfter); + _json.WritePropertyName("table"); + Rows(table, table.Rows); + _json.WriteEndObject(); + } + + private void Rows(TableBlock table, IEnumerable rows) + { + _json.WriteStartArray(); + foreach (TableRowItem item in rows) + { + switch (item) + { + case TableRowModel row: + _json.WriteStartObject(); + if (row.IsHeader) + { + _json.WriteBoolean("header", true); + } + + if (row.AllowSplit) + { + _json.WriteBoolean("allowSplit", true); + } + + StringIf("paragraphStyle", row.ParagraphStyle?.Id); + _json.WriteStartArray("row"); + Inheriting(StyleInheritance.ForCell(_styles, table, row), () => + { + foreach (TableCellModel cell in row.Cells) + { + Cell(cell); + } + }); + _json.WriteEndArray(); + _json.WriteEndObject(); + break; + + case TableRowLoop loop: + _json.WriteStartObject(); + _json.WriteString("forEachRow", loop.Collection.ToString()); + _json.WriteString("as", loop.ItemName); + _json.WritePropertyName("rows"); + Rows(table, loop.Rows); + _json.WriteEndObject(); + break; + + case TableRowConditional conditional: + _json.WriteStartObject(); + _json.WritePropertyName("rowsIf"); + Condition(conditional.Branches[0].Condition); + _json.WritePropertyName("then"); + Rows(table, conditional.Branches[0].Rows); + if (conditional.Branches.Count > 1) + { + _json.WriteStartArray("elseIf"); + foreach ((Condition condition, List branchRows) in conditional.Branches.Skip(1)) + { + _json.WriteStartObject(); + _json.WritePropertyName("if"); + Condition(condition); + _json.WritePropertyName("then"); + Rows(table, branchRows); + _json.WriteEndObject(); + } + + _json.WriteEndArray(); + } + + if (conditional.Else is { } otherwise) + { + _json.WritePropertyName("else"); + Rows(table, otherwise); + } + + _json.WriteEndObject(); + break; + } + } + + _json.WriteEndArray(); + } + + /// A cell: a string (one plain paragraph), a list of blocks, or an object when it has options. + private void Cell(TableCellModel cell) + { + bool hasOptions = cell.Span != 1 || cell.Background != null || cell.VerticalAlignment != null || cell.Padding != null || cell.Borders != null; + string? text = null; + ParagraphBlock? single = cell.Content is [ParagraphBlock { List: null, Options: null } only] && IsSingleString(only.Inlines, out text) ? only : null; + bool ownStyle = single is not null && !Equals(single.Style, _inherited) && single.Style is not null; + if (!hasOptions && single is not null && !ownStyle) + { + _json.WriteStringValue(text); + return; + } + + // A cell is a string or an object; one paragraph in its own style is {"style", "content": "…"}. + _json.WriteStartObject(); + if (cell.Span != 1) + { + _json.WriteNumber("span", cell.Span); + } + + ColorIf("background", cell.Background); + if (cell.VerticalAlignment is { } alignment) + { + _json.WriteString("verticalAlign", Enum(alignment)); + } + + EdgesIf("border", cell.Borders ?? Edges.None); + if (cell.Padding is { } padding) + { + _json.WriteString("padding", JsonValues.Box(padding.Top, padding.Right, padding.Bottom, padding.Left)); + } + + if (single is not null) + { + StringIf("style", ownStyle ? single.Style!.Id : null); + _json.WriteString("content", text); + } + else + { + _json.WritePropertyName("content"); + Blocks(cell.Content); + } + + _json.WriteEndObject(); + } + + + // ── inlines ────────────────────────────────────────────────────────────── + + /// + /// Inline content: one string when it is a single unstyled run of text and placeholders, else a list of runs + /// (strings, styled {"text": …}) and inline objects. + /// + private void InlineContent(IReadOnlyList inlines) + { + List parts = Runs(inlines); + if (parts is [TextRun { Style: null } only]) + { + _json.WriteStringValue(TextTemplate.Write(only.Pieces)); + return; + } + + _json.WriteStartArray(); + foreach (object part in parts) + { + if (part is TextRun run) + { + if (run.Style is null) + { + _json.WriteStringValue(TextTemplate.Write(run.Pieces)); + } + else + { + _json.WriteStartObject(); + _json.WriteString("text", TextTemplate.Write(run.Pieces)); + _json.WriteString("style", run.Style.Id); + _json.WriteEndObject(); + } + } + else + { + InlineObject((Inline)part); + } + } + + _json.WriteEndArray(); + } + + /// Whether the inlines are written as one string (a single unstyled run). + private static bool IsSingleString(IReadOnlyList inlines, out string? text) + { + text = Runs(inlines) is [TextRun { Style: null } only] ? TextTemplate.Write(only.Pieces) : null; + return text != null; + } + + /// A run of text and placeholders in one character style, written as one string. + private sealed record TextRun(List Pieces, CharacterStyleKey? Style); + + /// + /// Groups text, values and expressions of one character style into runs, but only where the import splits the + /// string back into the same inlines: two texts never join (the import would read one text), and a text ending + /// with '{' never joins a following placeholder (the import would read "{{{"). + /// + private static List Runs(IReadOnlyList inlines) + { + List parts = new List(); + TextRun? current = null; + foreach (Inline inline in inlines) + { + (TextPiece? piece, CharacterStyleKey? style) = inline switch + { + TextInline text => ((TextPiece?)new TextPiece.Literal(text.Text), text.Style), + ValueInline value => (new TextPiece.Value(value.Path.ToString(), value.Format?.Specifier), value.Style), + ExpressionInline { Condition: not RawCondition } expression => (new TextPiece.Expression(expression.Condition.ToString(), expression.Format?.Specifier), null), + _ => (null, null), + }; + + if (piece is null) + { + current = null; + parts.Add(inline); + continue; + } + + TextPiece? last = current?.Pieces[^1]; + bool joins = current != null + && Equals(current.Style, style) + && !(piece is TextPiece.Literal { Text: var literal } && last is TextPiece.Literal { Text: var previous } && !IsControl(literal) && !IsControl(previous)) + && !(piece is not TextPiece.Literal && last is TextPiece.Literal { Text: var before } && before.EndsWith('{')); + if (joins) + { + current!.Pieces.Add(piece); + } + else + { + current = new TextRun([piece], style); + parts.Add(current); + } + } + + return parts; + } + + /// A tab or line break: the import splits a string at it, so it joins the texts around it. + private static bool IsControl(string text) => text is "\t" or "\n"; + + private void InlineObject(Inline inline) + { + _json.WriteStartObject(); + switch (inline) + { + case PageFieldInline field: + _json.WriteBoolean(field.Field == PageField.Number ? "pageNumber" : "pageCount", true); + StringIf("style", field.Style?.Id); + break; + case RightTabInline: + _json.WriteBoolean("tabRight", true); + break; + case ImageInline image: + _json.WriteString("image", ImageAsset(image.Image)); + _json.WriteString("alt", image.AltText); + + // One size when the other follows from the image's proportions (the import computes it the same way). + if (ImageFit.Height(image.Height).Resolve(image.Image) == (image.Width, image.Height)) + { + _json.WriteString("height", JsonValues.Length(image.Height)); + } + else if (ImageFit.Width(image.Width).Resolve(image.Image) == (image.Width, image.Height)) + { + _json.WriteString("width", JsonValues.Length(image.Width)); + } + else + { + _json.WriteString("width", JsonValues.Length(image.Width)); + _json.WriteString("height", JsonValues.Length(image.Height)); + } + break; + case ExpressionInline expression: + // Only raw conditions get here: every other expression is written in text as {{(condition):format}}. + _json.WritePropertyName("expression"); + Condition(expression.Condition); + StringIf("format", expression.Format?.Specifier); + break; + case InlineConditional conditional: + _json.WritePropertyName("if"); + Condition(conditional.Branches[0].Condition); + _json.WritePropertyName("then"); + InlineContent(conditional.Branches[0].Inlines); + if (conditional.Branches.Count > 1) + { + _json.WriteStartArray("elseIf"); + foreach ((Condition condition, IReadOnlyList branch) in conditional.Branches.Skip(1)) + { + _json.WriteStartObject(); + _json.WritePropertyName("if"); + Condition(condition); + _json.WritePropertyName("then"); + InlineContent(branch); + _json.WriteEndObject(); + } + + _json.WriteEndArray(); + } + + if (conditional.Else is { } otherwise) + { + _json.WritePropertyName("else"); + InlineContent(otherwise); + } + + break; + default: + throw new NotSupportedException($"The JSON export does not know the inline {inline.GetType().Name}."); + } + + _json.WriteEndObject(); + } + + // ── values ─────────────────────────────────────────────────────────────── + + private void Condition(Condition condition) + { + if (condition is RawCondition raw) + { + _json.WriteStartObject(); + _json.WriteString("raw", raw.Expression); + Paths("uses", raw.Uses); + _json.WriteEndObject(); + return; + } + + _json.WriteStringValue(condition.ToString()); + } + + /// + /// XML text that does not depend on how the element was built: an element built in code and the same element + /// parsed back declare their namespace prefixes differently, so the text is parsed once and written again. + /// + private static string CanonicalXml(XElement element) => + XElement.Parse(element.ToString(SaveOptions.DisableFormatting)).ToString(SaveOptions.DisableFormatting); + + private void Paths(string name, IEnumerable paths) + { + _json.WriteStartArray(name); + foreach (TemplatePath path in paths) + { + _json.WriteStringValue(path.ToString()); + } + + _json.WriteEndArray(); + } + + /// The theme's values, in first-use order; embedded fonts become assets. + private ThemeSection Theme() => new ThemeSection( + _themeColors.Select(c => new KeyValuePair(c.Key, JsonValues.Color(c.Value))).ToList(), + _themeFonts.Select(f => (f.Key, f.Value.Family, f.Value.Embedding is { } file ? Asset(file.Hash, file.Data, null, "font-" + AssetNames.From(f.Value.Family)) : null)).ToList()); + + private static void WriteTheme(Utf8JsonWriter output, ThemeSection theme) + { + if (theme.Colors.Count == 0 && theme.Fonts.Count == 0) + { + return; + } + + output.WriteStartObject("theme"); + if (theme.Colors.Count > 0) + { + output.WriteStartObject("colors"); + foreach ((string name, string value) in theme.Colors) + { + output.WriteString(name, value); + } + + output.WriteEndObject(); + } + + if (theme.Fonts.Count > 0) + { + output.WriteStartObject("fonts"); + foreach ((string name, string family, string? embedded) in theme.Fonts) + { + if (embedded is null) + { + output.WriteString(name, family); + } + else + { + output.WriteStartObject(name); + output.WriteString("family", family); + output.WriteString("embedded", embedded); + output.WriteEndObject(); + } + } + + output.WriteEndObject(); + } + + output.WriteEndObject(); + } + + /// The asset name for content; the name is kept unless it already names other content. + private string Asset(string hash, byte[] data, string? name, string generated) + { + string key = "sha256:" + hash; + _assets[key] = data; + if (name is null && _unnamed.TryGetValue(key, out string? known)) + { + return known; + } + + string wanted = name ?? generated; + string unique = wanted; + for (int i = 2; _assetNames.Any(a => a.Key == unique && a.Value != key); i++) + { + unique = wanted + "-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + if (!_assetNames.Any(a => a.Key == unique)) + { + _assetNames.Add(new KeyValuePair(unique, key)); + } + + if (name is null) + { + _unnamed[key] = unique; + } + + return unique; + } + + private string ImageAsset(ImageSource image) => + Asset(image.Hash, image.Data, image.Name, "image-" + (_unnamed.Count + 1).ToString(System.Globalization.CultureInfo.InvariantCulture)); + + private static string Enum(T value) + where T : struct, System.Enum + { + string name = value.ToString(); + return char.ToLowerInvariant(name[0]) + name[1..]; + } + + private void StringIf(string name, string? value) + { + if (value != null) + { + _json.WriteString(name, value); + } + } + + private void LengthIf(string name, Length? value) + { + if (value is { } length) + { + _json.WriteString(name, JsonValues.Length(length)); + } + } + + private void ColorIf(string name, Color? value) + { + if (value is { } color) + { + _json.WriteString(name, ColorText(color)); + } + } + + /// Lines per side: one line string when all four are equal, else an object with the sides that are set. + private void EdgesIf(string name, Edges edges) + { + if (edges.IsEmpty) + { + return; + } + + if (edges.Top is { } all && edges.Right == all && edges.Bottom == all && edges.Left == all) + { + _json.WriteString(name, BorderText(all)); + return; + } + + _json.WriteStartObject(name); + BorderIf("top", edges.Top); + BorderIf("right", edges.Right); + BorderIf("bottom", edges.Bottom); + BorderIf("left", edges.Left); + _json.WriteEndObject(); + } + + private void BorderIf(string name, BorderLine? value) + { + if (value is { } line) + { + _json.WriteString(name, BorderText(line)); + } + } + + /// A colour: "$token" for a theme colour (its value goes to the theme), else "#RRGGBB". + private string ColorText(Color color) + { + if (color.TokenName is not { } token) + { + return JsonValues.Color(color); + } + + ThemeValue(_themeColors, token, color); + return "$" + token; + } + + private string BorderText(BorderLine line) => JsonValues.Length(line.Width) + " " + ColorText(line.Color); + + private void FontValue(FontFace font) + { + if (font.Embedding is { } file) + { + _json.WriteStartObject(); + _json.WriteString("family", font.Family); + _json.WriteString("embedded", Asset(file.Hash, file.Data, null, "font-" + AssetNames.From(font.Family))); + _json.WriteEndObject(); + } + else + { + _json.WriteStringValue(font.Family); + } + } + + /// Records a theme value; one token has one value in a definition. + private void ThemeValue(List> values, string token, T value) + { + int index = values.FindIndex(v => v.Key == token); + if (index < 0) + { + values.Add(new KeyValuePair(token, value)); + } + else if (!Equals(values[index].Value, value)) + { + _problems.Add(new BuildDiagnostic(DiagnosticCodes.TextNotExportable, $"The theme token '{token}' has two values in the definition ({values[index].Value} and {value}); a token has one value.")); + } + } + + private void BoolIf(string name, bool? value) + { + if (value is { } flag) + { + _json.WriteBoolean(name, flag); + } + } +} + +/// A key of the texts section and its translations (language name as written, text), in order. +internal sealed record TextSection(string Key, IReadOnlyList> Translations); + +/// The theme section: colour tokens and font tokens (family, embedded font asset or null). +internal sealed record ThemeSection(IReadOnlyList> Colors, IReadOnlyList<(string Name, string Family, string? Embedded)> Fonts); diff --git a/src/TriasDev.Templify.Builder/Json/PreviewText.cs b/src/TriasDev.Templify.Builder/Json/PreviewText.cs new file mode 100644 index 00000000..f03c3a9e --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/PreviewText.cs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// The text of a filled document as a person reads it: one line per paragraph, the body first, then the headers and +/// footers; tabs as tabs, line breaks as new lines, ODF's space runs as spaces. +/// +internal static class PreviewText +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + + public static string Of(byte[] package, TemplateFormat format) + { + using ZipArchive zip = new ZipArchive(new MemoryStream(package)); + XDocument Load(string name) + { + using Stream stream = zip.GetEntry(name)!.Open(); + return XDocument.Load(stream, LoadOptions.PreserveWhitespace); + } + + List lines = new List(); + if (format == TemplateFormat.Docx) + { + IEnumerable parts = new[] { "word/document.xml" } + .Concat(zip.Entries.Select(e => e.FullName).Where(n => n.StartsWith("word/header", StringComparison.Ordinal)).Order(StringComparer.Ordinal)) + .Concat(zip.Entries.Select(e => e.FullName).Where(n => n.StartsWith("word/footer", StringComparison.Ordinal)).Order(StringComparer.Ordinal)); + foreach (string part in parts) + { + lines.AddRange(Load(part).Descendants(_w + "p").Select(Docx)); + } + } + else + { + XName[] paragraphs = [_text + "p", _text + "h"]; + lines.AddRange(Load("content.xml").Descendants(_office + "text").Descendants().Where(e => paragraphs.Contains(e.Name)).Select(Odt)); + lines.AddRange(Load("styles.xml").Descendants(_style + "master-page").Descendants().Where(e => paragraphs.Contains(e.Name)).Select(Odt)); + } + + return string.Join("\n", lines); + } + + private static string Docx(XElement paragraph) + { + StringBuilder text = new StringBuilder(); + foreach (XElement element in paragraph.Descendants().Where(e => e.Ancestors(_w + "p").First() == paragraph)) + { + if (element.Name == _w + "t") + { + text.Append(element.Value); + } + else if (element.Name == _w + "tab" && element.Parent?.Name == _w + "r") + { + text.Append('\t'); + } + else if (element.Name == _w + "br" || element.Name == _w + "cr") + { + text.Append('\n'); + } + } + + return text.ToString(); + } + + private static string Odt(XElement paragraph) + { + StringBuilder text = new StringBuilder(); + Append(paragraph, text); + return text.ToString(); + } + + private static void Append(XElement element, StringBuilder text) + { + foreach (XNode node in element.Nodes()) + { + switch (node) + { + case XText value: + text.Append(value.Value); + break; + case XElement child when child.Name == _text + "s": + text.Append(' ', int.TryParse((string?)child.Attribute(_text + "c"), out int count) ? count : 1); + break; + case XElement child when child.Name == _text + "tab": + text.Append('\t'); + break; + case XElement child when child.Name == _text + "line-break": + text.Append('\n'); + break; + case XElement child when child.Name == _text + "p" || child.Name == _text + "h" || child.Name == _text + "note": + break; // listed as their own lines (a note's paragraphs), not inside this one + case XElement child: + Append(child, text); + break; + } + } + } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJson.cs b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs new file mode 100644 index 00000000..ceb6da06 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs @@ -0,0 +1,392 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; + +using System.Text.Json.Nodes; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Template definitions as JSON: export a definition written in C#, and import a JSON definition as an +/// that builds like any other. +/// +public static class TemplateJson +{ + /// + /// Exports a definition: it is composed and checked as for a build (same errors), then written as JSON. Texts from + /// are written as [[key]], so the JSON serves every language; the + /// language and format of do not matter. + /// + /// The definition. + /// The options to compose with. + /// The JSON and its assets. + /// The definition does not build, or a text cannot be written (TB9204). + public static TemplateJsonDocument Export(ITemplateDefinition definition, TemplateBuildOptions options) => + Export(definition, options, new TemplateJsonExportOptions()); + + /// + /// Exports a definition; components registered in are written as references with + /// their parameters, others as the blocks they produced. + /// + /// The definition. + /// The options to compose with. + /// The registered components, or null. + /// The JSON and its assets. + /// The definition does not build, or a text cannot be written (TB9204). + public static TemplateJsonDocument Export(ITemplateDefinition definition, TemplateBuildOptions options, ComponentCatalog? components) => + Export(definition, options, new TemplateJsonExportOptions { Components = components }); + + /// + /// Exports a definition with components and, for , the + /// translations in a texts section (from the definition's own texts if it was imported, then from + /// ). + /// + /// The definition. + /// The options to compose with; their catalog supplies the translations. + /// What to write besides the definition. + /// The JSON and its assets. + /// The definition does not build, or a text cannot be written (TB9204). + public static TemplateJsonDocument Export(ITemplateDefinition definition, TemplateBuildOptions options, TemplateJsonExportOptions export) + { + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(export); + ComposedTemplate composed = TemplateBuilder.Compose(definition, options, keyMarkers: true); + EmbeddedTexts own = (definition as JsonDefinition)?.Texts ?? EmbeddedTexts.None; + ITextCatalog catalog = options.Texts ?? TextCatalog.Empty; + IReadOnlyList languages = export.TextLanguages ?? []; + List untranslated = new List(); + Func, IReadOnlyList> texts = keys => languages.Count == 0 + ? own.Sections + : keys.Select(key => new TextSection(key, Translations(key))) + .Where(section => section.Translations.Count > 0) + .ToList(); + (string json, IReadOnlyDictionary assets) = ModelJsonWriter.Write(composed, definition.Identity!, export.Components, texts, export.Indented); + if (untranslated.Count > 0) + { + // Every text in the file has every language (the import's rule), so a missing one is named here. + throw new TemplateBuildException(untranslated); + } + + List> Translations(string key) + { + List> found = new List>(); + foreach (CultureInfo language in languages) + { + if (own.Catalog.TryGet(key, language, out string text) || catalog.TryGet(key, language, out text)) + { + found.Add(new KeyValuePair(language.Name, text)); + } + else + { + untranslated.Add(new BuildDiagnostic( + DiagnosticCodes.TextNotExportable, + $"The text '{key}' has no translation for '{language.Name}', which TemplateJsonExportOptions.TextLanguages asks for; add it to the catalog or leave the language out.") + { Location = "/texts/" + JsonComposition.Escape(key) }); + } + } + + return found; + } + + // The host shares the same objects with an import (TemplateJsonImportOptions.Shared); the check does it for it. + CheckBuildsTheSame(definition, options, export, json, assets, composed.Context.Shared.Values.ToList()); + return new TemplateJsonDocument(json, assets); + } + + /// + /// The export checks itself: the JSON, imported and built, must give the bytes the definition gives, for the + /// options' language and every language of the texts section the definition builds in. A text the code + /// changed (string.Format, ToUpper) or one used where JSON cannot hold it would otherwise give a + /// different template without a word: TB9204. + /// + private static void CheckBuildsTheSame(ITemplateDefinition definition, TemplateBuildOptions options, TemplateJsonExportOptions export, string json, IReadOnlyDictionary assets, IReadOnlyList shared) + { + ITemplateDefinition imported; + try + { + imported = Import(json, new TemplateJsonImportOptions { Assets = assets, Components = export.Components, Shared = shared, AllowRawXml = true, AcceptsAnyValueFormat = true }); + } + catch (TemplateBuildException exception) + { + throw NotTheSame(options.Language, string.Join(" ", exception.Errors.Select(e => e.Code + ": " + e.Message))); + } + + foreach (CultureInfo language in new[] { options.Language }.Concat(export.TextLanguages ?? []).DistinctBy(l => l.Name)) + { + TemplateBuildOptions languageOptions = options with { Language = language }; + GeneratedTemplate expected = TemplateBuilder.Build(definition, languageOptions); + + string actual; + try + { + actual = TemplateBuilder.Build(imported, languageOptions).ContentHash; + } + catch (TemplateBuildException exception) + { + throw NotTheSame(language, string.Join(" ", exception.Errors.Select(e => e.Code + ": " + e.Message))); + } + + if (actual != expected.ContentHash) + { + throw NotTheSame(language, FirstDifference(expected, TemplateBuilder.Build(imported, languageOptions))); + } + } + } + + /// Where the C# build and the JSON build part: the first paragraph whose text differs, or that the texts are equal. + private static string FirstDifference(GeneratedTemplate csharp, GeneratedTemplate json) + { + List expected = ParagraphTexts(csharp); + List actual = ParagraphTexts(json); + for (int i = 0; i < Math.Max(expected.Count, actual.Count); i++) + { + string left = i < expected.Count ? expected[i] : "(none)"; + string right = i < actual.Count ? actual[i] : "(none)"; + if (left != right) + { + return $"paragraph {i + 1} reads \"{left}\" from C# but \"{right}\" from the JSON — a text changed by code (string.Format, ToUpper, concatenated into a quoted value) or used where the JSON cannot hold it."; + } + } + + return "the texts are the same, so something else differs — for example a column width or another value the definition computes per language, which the JSON holds only once."; + } + + private static List ParagraphTexts(GeneratedTemplate template) => ParagraphTexts(template.Content.ToArray(), template.Format); + + private static List ParagraphTexts(byte[] package, TriasDev.Templify.Core.TemplateFormat format) + { + using System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(new MemoryStream(package)); + string part = format == TriasDev.Templify.Core.TemplateFormat.Docx ? "word/document.xml" : "content.xml"; + using Stream stream = zip.GetEntry(part)!.Open(); + System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(stream); + return document.Descendants() + .Where(e => e.Name.LocalName is "p" or "h") + .Select(p => string.Concat(p.DescendantNodes().OfType().Where(t => t.Parent!.Name.LocalName != "instrText").Select(t => t.Value))) + .ToList(); + } + + private static TemplateBuildException NotTheSame(CultureInfo language, string reason) => + new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.TextNotExportable, $"The JSON would not build the same template for {language.Name}: {reason}")]); + + /// + /// Describes the definition format for an agent: every construct with where it is written, its keys, what they take + /// and an example; the value forms; with options, the host's components and the data paths. Deterministic JSON. + /// + /// The components and data to list; null for the format alone. + /// The description as indented JSON. + public static string Describe(TemplateJsonDescribeOptions? options = null) => TemplateJsonDescribe.Write(options ?? new TemplateJsonDescribeOptions()); + + /// + /// The JSON Schema (draft 2020-12) of the definition format, for editors and agents that validate on their side. + /// With components, a component reference must name a registered component and give its parameters. The import + /// stays the authority: it also checks conditions, paths, styles and data. + /// + /// The host's registered components; null to accept any component name. + /// The schema as indented JSON. + public static string Schema(ComponentCatalog? components = null) => JsonSchemaWriter.Write(components); + + /// + /// The outline of a definition, for an agent to find its way without reading all of it: every block, row, cell with + /// blocks of its own, list item, elseIf branch, in document order (page parts first, then the content), with its + /// JSON pointer, its kind, a short label and its depth. It reads the JSON as it is; it does not check it. + /// + /// The definition. + /// The outline. + /// The text is not JSON. + public static IReadOnlyList Outline(string json) => JsonOutline.Build(json); + + /// One part of a definition by JSON pointer (RFC 6901), for example /content/3/blocks/1. + /// The definition. + /// The pointer; empty for the whole definition. + /// The part as indented JSON. + /// The text is not JSON, or the pointer is malformed or names nothing. + public static string Read(string json, string pointer) + { + JsonNode? node = JsonPointer.Resolve(JsonOutline.Parse(json), pointer); + return node is null ? "null" : node.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + } + + /// + /// Applies a JSON Patch (RFC 6902: add, remove, replace, move, copy, test) to a definition, all operations or none, + /// and checks the result like : the import with the data catalogue + /// and, with , the build. The host saves when the check + /// is Ok; an agent reads the problems, located by JSON pointer, and sends the next patch. + /// + /// The definition. + /// The patch: a JSON array of operations. + /// The import options; is required. + /// The options to build with; null to check the import only. + /// Whether it applied, the new definition and its check. + /// The definition is not JSON, or the import options have no data catalogue. + public static TemplatePatchResult Patch(string json, string patch, TemplateJsonImportOptions import, TemplateBuildOptions? build = null) + { + ArgumentNullException.ThrowIfNull(patch); + ArgumentNullException.ThrowIfNull(import); + if (import.Data is null) + { + throw new ArgumentException("Checking a patched definition needs the current data catalogue (TemplateJsonImportOptions.Data).", nameof(import)); + } + + JsonNode document = JsonOutline.Parse(json); + JsonNode? patched; + try + { + patched = JsonPatch.Apply(document, patch); + } + catch (JsonPatchException exception) + { + TemplateCheckProblem problem = new TemplateCheckProblem(CheckCodes.PatchFailed, TemplateCheckSeverity.Error, exception.Message) + { + Location = exception.Index < 0 ? string.Empty : "/" + exception.Index.ToString(System.Globalization.CultureInfo.InvariantCulture), + }; + return new TemplatePatchResult(false, json, new TemplateCheckResult(TriasDev.Templify.Core.TemplateFormat.Unknown, null, [problem])); + } + + string text = patched is null ? "null" : patched.ToJsonString(_indented); + return new TemplatePatchResult(true, text, TemplateInspector.CheckDefinition(text, import, build)); + } + + /// + /// Builds a definition and fills it, so an agent (or the person it works for) sees the result: the filled + /// document and its text. Problems never throw: an import or build error, a fill failure or bad data JSON gives no + /// document and a Broken check; values the data lacks are warnings. + /// + /// The definition. + /// The import options (assets, components, …); a data catalogue is not needed. + /// The format, language and texts to build with. + /// The data as JSON; null to fill with the contract's witness (every value present). + /// The preview. + public static TemplatePreview Preview(string json, TemplateJsonImportOptions import, TemplateBuildOptions build, string? data = null) + { + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(import); + ArgumentNullException.ThrowIfNull(build); + static TemplatePreview Failed(IEnumerable problems) => + new TemplatePreview(new TemplateCheckResult(TriasDev.Templify.Core.TemplateFormat.Unknown, null, problems.ToList()), null, null); + + GeneratedTemplate template; + try + { + template = TemplateBuilder.Build(Import(json, import), build); + } + catch (TemplateBuildException exception) + { + return Failed(exception.Errors.Select(TemplateInspector.AsProblem)); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) + { + return Failed([TemplateInspector.AsProblem(exception)]); + } + + TriasDev.Templify.Core.TemplateProcessor processor = new TriasDev.Templify.Core.TemplateProcessor( + new TriasDev.Templify.Core.PlaceholderReplacementOptions { Culture = build.Language }); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + TriasDev.Templify.Core.ProcessingResult result; + try + { + result = data is null + ? processor.ProcessTemplate(input, output, template.Contract.CreateWitness()) + : processor.ProcessTemplate(input, output, data); + } + catch (Exception exception) when (exception is System.Text.Json.JsonException or ArgumentException) + { + return Failed([new TemplateCheckProblem(CheckCodes.WrongKind, TemplateCheckSeverity.Error, "The data is not JSON: " + exception.Message)]); + } + + if (!result.IsSuccess) + { + return Failed([new TemplateCheckProblem(CheckCodes.WrongKind, TemplateCheckSeverity.Error, result.ErrorMessage ?? "Filling failed.")]); + } + + // The fill's warnings (a loop over missing data, a failed expression) and every value the data lacks. + List warnings = result.Warnings + .Select(w => new TemplateCheckProblem(w.VariableName is null ? CheckCodes.WrongKind : CheckCodes.UnknownPath, TemplateCheckSeverity.Warning, w.Message) { DataPath = w.VariableName }) + .ToList(); + warnings.AddRange(result.MissingVariables + .Distinct(StringComparer.Ordinal) + .Where(path => !warnings.Any(w => w.DataPath == path)) + .Select(path => new TemplateCheckProblem(CheckCodes.UnknownPath, TemplateCheckSeverity.Warning, $"The data has no value for '{path}'; the placeholder stays.") { DataPath = path })); + byte[] filled = output.ToArray(); + return new TemplatePreview(new TemplateCheckResult(template.Format, null, warnings), filled, PreviewText.Of(filled, template.Format)); + } + + private static readonly System.Text.Json.JsonSerializerOptions _indented = new System.Text.Json.JsonSerializerOptions + { + WriteIndented = true, + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + /// + /// Imports a JSON definition. The result builds with like a C# definition; + /// problems are reported as build errors with the JSON pointer in . + /// + /// The JSON text. + /// The assets and what the import allows; null for none. + /// The definition. + /// The text is not a JSON definition (TB9200). + public static ITemplateDefinition Import(string json, TemplateJsonImportOptions? options = null) + { + ArgumentNullException.ThrowIfNull(json); + options ??= new TemplateJsonImportOptions(); + System.Text.Json.JsonElement root; + try + { + using System.Text.Json.JsonDocument document = System.Text.Json.JsonDocument.Parse(json); + root = document.RootElement.Clone(); + } + catch (System.Text.Json.JsonException exception) + { + throw Invalid(string.Empty, "The text is not JSON: " + exception.Message); + } + + if (root.ValueKind != System.Text.Json.JsonValueKind.Object + || !root.TryGetProperty("templifyDefinition", out System.Text.Json.JsonElement version) + || version.ValueKind != System.Text.Json.JsonValueKind.Number + || !version.TryGetInt32(out int formatVersion) + || formatVersion != ModelJsonWriter.FormatVersion) + { + throw Invalid("/templifyDefinition", $"A JSON definition starts with \"templifyDefinition\": {ModelJsonWriter.FormatVersion}."); + } + + if (!root.TryGetProperty("identity", out System.Text.Json.JsonElement identity) + || identity.ValueKind != System.Text.Json.JsonValueKind.Object + || !identity.TryGetProperty("id", out System.Text.Json.JsonElement id) || id.ValueKind != System.Text.Json.JsonValueKind.String + || !identity.TryGetProperty("version", out System.Text.Json.JsonElement number)) + { + throw Invalid("/identity", "The identity { \"id\": …, \"version\": … } is missing or incomplete."); + } + + if (number.ValueKind != System.Text.Json.JsonValueKind.Number || !number.TryGetInt32(out int identityVersion)) + { + throw Invalid("/identity/version", "The identity's version is a whole number, for example 1."); + } + + JsonDefinition definition = new JsonDefinition(root, new TemplateIdentity(id.GetString()!, identityVersion), options); + CheckStructure(definition); + return definition; + } + + /// + /// Composes the definition once without a language, keeping only the problems of the JSON itself (structure, + /// assets, raw XML, data paths): those are thrown now, together. The composers' rules are checked at build time. + /// + private static void CheckStructure(JsonDefinition definition) + { + BuildContext context = new BuildContext(); + TemplateComposer composer = new TemplateComposer(context, new TemplateTexts(context, TextCatalog.Empty, System.Globalization.CultureInfo.InvariantCulture)); + definition.Compose(composer); + List problems = context.Errors + .Where(e => e.Code is DiagnosticCodes.InvalidJson or DiagnosticCodes.RawXmlNotAllowed or DiagnosticCodes.UnknownDataPath) + .ToList(); + if (problems.Count > 0) + { + throw new TemplateBuildException(problems); + } + } + + private static TemplateBuildException Invalid(string location, string message) => + new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.InvalidJson, message) { Location = location }]); +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribe.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribe.cs new file mode 100644 index 00000000..11c70cf7 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribe.cs @@ -0,0 +1,121 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; + +namespace TriasDev.Templify.Builder.Json; + +/// Renders (and the host's components and data) as the description an agent reads. +internal static class TemplateJsonDescribe +{ + public static string Write(TemplateJsonDescribeOptions options) + { + using MemoryStream stream = new MemoryStream(); + using (Utf8JsonWriter json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })) + { + json.WriteStartObject(); + json.WriteNumber("formatVersion", ModelJsonWriter.FormatVersion); + json.WriteString("about", "A Templify template definition: JSON that builds a DOCX and an ODT template. Blocks are paragraphs, tables, lists, boxes, conditionals and loops; text holds {{data.path}} values and [[key]] texts. Each construct below lists where it is written (in), the key that identifies it (key) and its keys."); + // An index first: the construct names by where they are written, to find the right one quickly. + json.WriteStartObject("index"); + foreach (IGrouping group in JsonVocabulary.All.GroupBy(c => c.Group)) + { + json.WriteStartArray(group.Key); + foreach (Construct construct in group) + { + json.WriteStringValue(construct.Name); + } + + json.WriteEndArray(); + } + + json.WriteEndObject(); + json.WriteStartObject("values"); + foreach ((string name, string description) in JsonVocabulary.Values) + { + json.WriteString(name, description); + } + + json.WriteEndObject(); + json.WriteStartArray("constructs"); + foreach (Construct construct in JsonVocabulary.All) + { + json.WriteStartObject(); + json.WriteString("name", construct.Name); + json.WriteString("in", construct.Group); + if (construct.Discriminator is { } key) + { + json.WriteString("key", key); + } + + json.WriteString("description", construct.Description); + json.WriteStartArray("keys"); + foreach (VocabularyKey k in construct.Keys) + { + json.WriteStartObject(); + json.WriteString("name", k.Name); + json.WriteString("value", Kind(k.Kind)); + json.WriteBoolean("required", k.Required); + if (k.Construct is { } inner) + { + json.WriteString("construct", inner); + } + + json.WriteString("description", k.Description); + json.WriteEndObject(); + } + + json.WriteEndArray(); + json.WritePropertyName("example"); + using (JsonDocument example = JsonDocument.Parse(construct.Example)) + { + example.RootElement.WriteTo(json); + } + + json.WriteEndObject(); + } + + json.WriteEndArray(); + if (options.Components is { } components) + { + json.WriteStartArray("components"); + foreach (ComponentCatalog.Registration registration in components.Registrations) + { + json.WriteStartObject(); + json.WriteString("name", registration.Name); + json.WriteStartArray("parameters"); + foreach ((string name, string type) in registration.DescribeParameters()) + { + json.WriteStartObject(); + json.WriteString("name", name); + json.WriteString("type", type); + json.WriteEndObject(); + } + + json.WriteEndArray(); + json.WriteEndObject(); + } + + json.WriteEndArray(); + } + + if (options.Data is { } data) + { + json.WritePropertyName("data"); + using JsonDocument catalog = JsonDocument.Parse(data.ToJson()); + catalog.RootElement.WriteTo(json); + } + + json.WriteEndObject(); + } + + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + + /// The value kind as the description names it: camelCase. + internal static string Kind(ValueKind kind) + { + string name = kind.ToString(); + return char.ToLowerInvariant(name[0]) + name[1..]; + } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribeOptions.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribeOptions.cs new file mode 100644 index 00000000..76663afb --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonDescribeOptions.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// What adds to the format's vocabulary. +public sealed class TemplateJsonDescribeOptions +{ + /// Gets the host's registered components, listed with their parameters; null for none. + public ComponentCatalog? Components { get; init; } + + /// Gets the data the templates read, listed with its paths; null for none. + public DataCatalog? Data { get; init; } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonDocument.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonDocument.cs new file mode 100644 index 00000000..d579f1da --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonDocument.cs @@ -0,0 +1,23 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// A definition exported to JSON: the text, and the binary files it refers to by content hash. +public sealed class TemplateJsonDocument +{ + internal TemplateJsonDocument(string json, IReadOnlyDictionary assets) + { + Json = json; + Assets = assets; + } + + /// Gets the JSON text. + public string Json { get; } + + /// + /// Gets the images and embedded fonts the JSON refers to, keyed as in the JSON (sha256:<hex>), in key + /// order. + /// + public IReadOnlyDictionary Assets { get; } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonExportOptions.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonExportOptions.cs new file mode 100644 index 00000000..979fdb93 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonExportOptions.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; + +namespace TriasDev.Templify.Builder.Json; + +/// What a JSON export writes besides the definition. +public sealed class TemplateJsonExportOptions +{ + /// Gets the components written as references with their parameters; others are written as the blocks they produced. + public ComponentCatalog? Components { get; init; } + + /// + /// Gets the languages whose translations are written into the JSON's texts section, so the file is + /// self-contained. Null or empty: only the [[key]] references are written (an imported definition keeps the + /// languages of its own texts); the build then translates from . + /// + public IReadOnlyList? TextLanguages { get; init; } + + /// + /// Gets a value indicating whether the JSON is laid out for reading (the default): what fits in 100 columns on one + /// line, otherwise one member per line, ending with a line break. False writes it on one line without whitespace, + /// for storage and transport; the import reads both the same way. + /// + public bool Indented { get; init; } = true; +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs new file mode 100644 index 00000000..f9b3b725 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs @@ -0,0 +1,41 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// What a JSON import may use. +public sealed class TemplateJsonImportOptions +{ + /// Gets the images and embedded fonts the JSON refers to (keys as in ). + public IReadOnlyDictionary? Assets { get; init; } + + /// Gets the data the JSON may read: every path outside the catalogue is an error (TB9203). Null for no check. + public DataCatalog? Data { get; init; } + + /// Gets the components the JSON may refer to by name. + public ComponentCatalog? Components { get; init; } + + /// + /// Gets value format names the host registered with Templify (for example a boolean formatter "janein") that a + /// definition may use besides the built-in ones; any other unknown format is an error. + /// + public IReadOnlyCollection? ValueFormats { get; init; } + + /// + /// Gets theme values the host sets instead of the file's theme (a customer's brand): token name to a colour + /// ("#00A000") or a font family. + /// + public IReadOnlyDictionary? Theme { get; init; } + + /// Gets objects shared with registered components (), as does in C#. + public IReadOnlyList? Shared { get; init; } + + /// Gets a value indicating whether raw XML blocks are accepted. Default: false (a JSON definition is input from outside). + public bool AllowRawXml { get; init; } + + /// + /// Whether any value format is accepted: the export's self-check, which reads back what the C# definition wrote + /// (host formats included); the host's own list applies when it imports. + /// + internal bool AcceptsAnyValueFormat { get; init; } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonNode.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonNode.cs new file mode 100644 index 00000000..cb1b725f --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonNode.cs @@ -0,0 +1,35 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// One entry of a definition's outline (). +public sealed class TemplateJsonNode +{ + internal TemplateJsonNode(string pointer, string kind, string label, int depth) + { + Pointer = pointer; + Kind = kind; + Label = label; + Depth = depth; + } + + /// Gets the JSON pointer of the block, row, cell, item or branch. + public string Pointer { get; } + + /// + /// Gets the construct: paragraph, pageBreak, spacer, section, if, elseIf, forEach, component, list, item, box, table, + /// headerRow, row, forEachRow, rowsIf, cell, rule, toc or raw. A then or else part is not an entry of its own: its + /// blocks follow with their pointers. + /// + public string Kind { get; } + + /// Gets a short summary: a section's name, a paragraph's style and text, a condition, a loop, a row's columns and cells. + public string Label { get; } + + /// Gets how deep it sits: 0 for the content's and the page parts' own blocks. + public int Depth { get; } + + /// + public override string ToString() => $"{Pointer} [{Kind}] {Label}"; +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplatePatchResult.cs b/src/TriasDev.Templify.Builder/Json/TemplatePatchResult.cs new file mode 100644 index 00000000..09b83939 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplatePatchResult.cs @@ -0,0 +1,28 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// The result of : the changed definition and its check. +public sealed class TemplatePatchResult +{ + internal TemplatePatchResult(bool applied, string json, TemplateCheckResult check) + { + Applied = applied; + Json = json; + Check = check; + } + + /// + /// Gets a value indicating whether the patch could be applied. When it could not (a malformed operation, a missing + /// path, a failed test), nothing changed: is the input and has one TB9207 + /// problem located at the operation (/1 is the second). + /// + public bool Applied { get; } + + /// Gets the definition after the patch (indented), or the input when it was not applied. + public string Json { get; } + + /// Gets the check of the patched definition, as gives it; save it only when it is Ok. + public TemplateCheckResult Check { get; } +} diff --git a/src/TriasDev.Templify.Builder/Json/TemplatePreview.cs b/src/TriasDev.Templify.Builder/Json/TemplatePreview.cs new file mode 100644 index 00000000..06bf02ff --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TemplatePreview.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Json; + +/// The result of : the filled document, its text and what went wrong. +public sealed class TemplatePreview +{ + internal TemplatePreview(TemplateCheckResult check, byte[]? document, string? text) + { + Check = check; + Document = document; + Text = text; + } + + /// + /// Gets the problems: the import's and the build's (then there is no document), a fill failure (TB9302), and data + /// the template reads that the data did not have (TB9301 warnings, the placeholder stays in the text). + /// + public TemplateCheckResult Check { get; } + + /// Gets the filled document (DOCX or ODT, as the build options say), or null when it could not be made; a host converts it to PDF. + public byte[]? Document { get; } + + /// Gets the filled document's paragraphs, one per line (body, then headers and footers as the format stores them), or null. + public string? Text { get; } +} diff --git a/src/TriasDev.Templify.Builder/Json/TextKeys.cs b/src/TriasDev.Templify.Builder/Json/TextKeys.cs new file mode 100644 index 00000000..fd723108 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TextKeys.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder.Json; + +/// +/// Text keys in JSON definitions. The export composes with key markers (), so a translated text +/// can be found wherever the definition's code put it; the JSON writes it as [[key]], and the import puts the +/// build language's translation back. +/// +internal static partial class TextKeys +{ + /// Starts a key marker (a private-use character, never in real text). + public const char MarkerStart = ''; + + /// Ends a key marker. + public const char MarkerEnd = ''; + + private const string Open = "[["; + private const string Close = "]]"; + + /// The marker of a key, returned by the texts while exporting. + public static string Marker(string key) => MarkerStart + key + MarkerEnd; + + /// Whether a key can be written as [[key]]. + public static bool IsKey(string key) => KeyPattern().IsMatch(key); + + /// Whether a text holds a key marker. + public static bool HasMarkers(string text) => text.Contains(MarkerStart, StringComparison.Ordinal); + + /// The keys of the markers in a text, in order. + public static IEnumerable MarkedKeys(string text) + { + int position = 0; + while ((position = text.IndexOf(MarkerStart, position)) >= 0) + { + int end = text.IndexOf(MarkerEnd, position + 1); + if (end < 0) + { + yield break; + } + + yield return text[(position + 1)..end]; + position = end + 1; + } + } + + /// Replaces every marker by [[key]]. + public static string MarkersToKeys(string text) => + HasMarkers(text) ? MarkerText().Replace(text, m => Open + m.Groups[1].Value + Close) : text; + + /// + /// Replaces every [[key]] by 's text. A lone ]] is text; a [[ that + /// does not start a key is an error. + /// + /// A [[ does not start a valid key. + public static string Resolve(string text, Func lookup) + { + int start = text.IndexOf(Open, StringComparison.Ordinal); + if (start < 0) + { + return text; + } + + StringBuilder result = new StringBuilder(); + int position = 0; + while (start >= 0) + { + int end = text.IndexOf(Close, start + Open.Length, StringComparison.Ordinal); + string key = end < 0 ? string.Empty : text[(start + Open.Length)..end]; + if (end < 0 || !IsKey(key)) + { + string shown = end < 0 ? text[start..] : text[start..(end + Close.Length)]; + throw new FormatException($"'{shown}' is not a text key: write [[key]] with letters, digits, '_', '.' or '-'."); + } + + result.Append(text, position, start - position).Append(lookup(key)); + position = end + Close.Length; + start = text.IndexOf(Open, position, StringComparison.Ordinal); + } + + return result.Append(text, position, text.Length - position).ToString(); + } + + [GeneratedRegex("^[A-Za-z0-9_.-]+$")] + private static partial Regex KeyPattern(); + + [GeneratedRegex("([^]*)")] + private static partial Regex MarkerText(); +} diff --git a/src/TriasDev.Templify.Builder/Json/TextTemplate.cs b/src/TriasDev.Templify.Builder/Json/TextTemplate.cs new file mode 100644 index 00000000..68fbdc16 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/TextTemplate.cs @@ -0,0 +1,219 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; + +namespace TriasDev.Templify.Builder.Json; + +/// A piece of a JSON text string: literal text, a value placeholder or an expression placeholder. +internal abstract record TextPiece +{ + private TextPiece() + { + } + + /// Literal text. + /// The text. + public sealed record Literal(string Text) : TextPiece; + + /// {{path}} or {{path:format}}. + /// The path text. + /// The format specifier text; null without one. + public sealed record Value(string Path, string? Format) : TextPiece; + + /// {{(condition)}} or {{(condition):format}}. + /// The condition text, without the outer parentheses. + /// The format specifier text; null without one. + public sealed record Expression(string Condition, string? Format) : TextPiece; +} + +/// +/// Splits a JSON text string into literal text and Templify placeholders, and writes pieces back. The builder never +/// lets literal text contain {{, so every {{ in a string starts a placeholder. Paths, formats and +/// conditions are returned as text; the JSON reader checks them with its own parsers. +/// +internal static class TextTemplate +{ + private const string Open = "{{"; + private const string Close = "}}"; + + /// Splits ; a string without placeholders is one literal (also when empty). + /// A placeholder is malformed; the message quotes it. + public static IReadOnlyList Parse(string text) + { + ArgumentNullException.ThrowIfNull(text); + List pieces = new List(); + int position = 0; + while (position < text.Length) + { + int start = text.IndexOf(Open, position, StringComparison.Ordinal); + if (start < 0) + { + break; + } + + if (start > position) + { + pieces.Add(new TextPiece.Literal(text[position..start])); + } + + position = start + Open.Length < text.Length && text[start + Open.Length] == '(' + ? ParseExpression(text, start, pieces) + : ParseValue(text, start, pieces); + } + + if (position < text.Length || pieces.Count == 0) + { + pieces.Add(new TextPiece.Literal(text[position..])); + } + + return pieces; + } + + /// Writes pieces as one string, the inverse of . + public static string Write(IEnumerable pieces) + { + ArgumentNullException.ThrowIfNull(pieces); + StringBuilder text = new StringBuilder(); + foreach (TextPiece piece in pieces) + { + text.Append(piece switch + { + TextPiece.Literal literal => literal.Text, + TextPiece.Value value => Open + value.Path + (value.Format is null ? string.Empty : ":" + value.Format) + Close, + TextPiece.Expression expression => Open + "(" + expression.Condition + ")" + (expression.Format is null ? string.Empty : ":" + expression.Format) + Close, + _ => throw new ArgumentException("Unknown text piece.", nameof(pieces)), + }); + } + + return text.ToString(); + } + + private static int ParseValue(string text, int start, List pieces) + { + int end = text.IndexOf(Close, start + Open.Length, StringComparison.Ordinal); + if (end < 0) + { + throw Malformed(text, start, "it has no closing '}}'"); + } + + string inner = text[(start + Open.Length)..end]; + int colon = inner.IndexOf(':', StringComparison.Ordinal); + string path = colon < 0 ? inner : inner[..colon]; + string? format = colon < 0 ? null : inner[(colon + 1)..]; + if (path.Length == 0) + { + throw Malformed(text, start, "it names no data path"); + } + + if (format is { Length: 0 }) + { + throw Malformed(text, start, "the format after ':' is empty"); + } + + pieces.Add(new TextPiece.Value(path, format)); + return end + Close.Length; + } + + private static int ParseExpression(string text, int start, List pieces) + { + int open = start + Open.Length; + int closeParen = MatchingParenthesis(text, open); + if (closeParen < 0) + { + throw Malformed(text, start, "its '(' has no matching ')'"); + } + + string condition = text[(open + 1)..closeParen]; + if (condition.Trim().Length == 0) + { + throw Malformed(text, start, "the condition is empty"); + } + + int after = closeParen + 1; + if (text.AsSpan(after).StartsWith(Close, StringComparison.Ordinal)) + { + pieces.Add(new TextPiece.Expression(condition, null)); + return after + Close.Length; + } + + if (after < text.Length && text[after] == ':') + { + int end = text.IndexOf(Close, after, StringComparison.Ordinal); + if (end < 0) + { + throw Malformed(text, start, "it has no closing '}}'"); + } + + string format = text[(after + 1)..end]; + if (format.Length == 0) + { + throw Malformed(text, start, "the format after ':' is empty"); + } + + pieces.Add(new TextPiece.Expression(condition, format)); + return end + Close.Length; + } + + throw Malformed(text, start, "after the condition's ')' only ':format' and '}}' may follow"); + } + + /// The index of the ')' matching the '(' at , skipping quoted strings; -1 when none. + private static int MatchingParenthesis(string text, int open) + { + int depth = 0; + for (int i = open; i < text.Length; i++) + { + char c = text[i]; + if (c is '"' or '\'') + { + i = EndOfString(text, i); + if (i < 0) + { + return -1; + } + } + else if (c == '(') + { + depth++; + } + else if (c == ')' && --depth == 0) + { + return i; + } + else if (c == '}' && i + 1 < text.Length && text[i + 1] == '}') + { + // A condition never contains '}}' (Condition rejects it): the placeholder ends here. + return -1; + } + } + + return -1; + } + + /// The index of the quote closing the string literal that starts at ; -1 when none. + private static int EndOfString(string text, int quote) + { + char delimiter = text[quote]; + for (int i = quote + 1; i < text.Length; i++) + { + if (text[i] == '\\') + { + i++; + } + else if (text[i] == delimiter) + { + return i; + } + } + + return -1; + } + + private static FormatException Malformed(string text, int start, string reason) + { + int end = text.IndexOf(Close, start + Open.Length, StringComparison.Ordinal); + string placeholder = end < 0 ? text[start..] : text[start..(end + Close.Length)]; + return new FormatException($"The placeholder '{placeholder}' is malformed: {reason}."); + } +} diff --git a/src/TriasDev.Templify.Builder/Json/ThemeTokens.cs b/src/TriasDev.Templify.Builder/Json/ThemeTokens.cs new file mode 100644 index 00000000..cf758476 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Json/ThemeTokens.cs @@ -0,0 +1,26 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder.Json; + +/// Names of theme tokens ("$accent"). +internal static partial class ThemeTokens +{ + public static bool IsValid(string name) => Pattern().IsMatch(name); + + public static string Validate(string name, string parameter) + { + ArgumentNullException.ThrowIfNull(name, parameter); + if (!IsValid(name)) + { + throw new ArgumentException($"'{name}' is not a theme token name: a letter, then letters, digits, '_', '.' or '-'.", parameter); + } + + return name; + } + + [GeneratedRegex("^[A-Za-z][A-Za-z0-9_.-]*$")] + private static partial Regex Pattern(); +} diff --git a/src/TriasDev.Templify.Builder/Lists.cs b/src/TriasDev.Templify.Builder/Lists.cs new file mode 100644 index 00000000..213f8c26 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Lists.cs @@ -0,0 +1,245 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// Names a bullet list style: a bullet, an indent and a hanging indent per level. +public sealed record ListStyleKey +{ + /// Initializes a list style key. + /// Letters, digits, _ and -, starting with a letter or _. + public ListStyleKey(string id) + { + Id = StyleKeyRules.ValidateId(id, nameof(id)); + } + + /// Gets the id. + public string Id { get; } +} + +/// Sets a list style's levels and the paragraph style of its items. +public sealed class ListStyleComposer +{ + private readonly StyleSheetComposer _owner; + private readonly ListStyleDefinition _style; + + internal ListStyleComposer(StyleSheetComposer owner, ListStyleDefinition style) + { + _owner = owner; + _style = style; + } + + /// Defines a level. + /// The level: 0 is the top level, at most 8. + /// The bullet, for example • or –. + /// Where the item text starts, from the container's start. + /// How far left of the text the bullet sits. + /// This composer. + public ListStyleComposer Level(int level, string bullet, Length indent, Length hanging) + { + _owner.EnsureOpen(); + if (level is < 0 or > 8) + { + throw new ArgumentOutOfRangeException(nameof(level), level, "A list level is between 0 and 8."); + } + + ArgumentNullException.ThrowIfNull(bullet); + if (bullet.Length is 0 or > 4 || bullet.Any(char.IsControl)) + { + throw new ArgumentException("A bullet is one to four printable characters.", nameof(bullet)); + } + + if (hanging > indent) + { + throw new ArgumentOutOfRangeException(nameof(hanging), hanging, "The bullet cannot sit left of the container: the hanging indent is at most the indent."); + } + + _style.Levels[level] = new ListLevel(bullet, StyleRanges.NotNegative(indent, nameof(indent)), StyleRanges.NotNegative(hanging, nameof(hanging))); + return this; + } + + /// Sets the paragraph style of the list's items. + /// The paragraph style; the style sheet must define it. + /// This composer. + public ListStyleComposer ItemStyle(ParagraphStyleKey style) + { + _owner.EnsureOpen(); + _style.ItemStyle = style ?? throw new ArgumentNullException(nameof(style)); + return this; + } +} + +/// +/// Describes the items of a bullet list: items at a level, loops and conditionals over items. Valid only inside the +/// lambda it is passed to. +/// +public sealed class ListComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly ListStyleKey _style; + private readonly List _blocks; + private readonly BlockComposer _blocksComposer; + private bool _isOpen = true; + + internal ListComposer(BuildContext context, LoopScope? scope, ListStyleKey style, List blocks) + { + _context = context; + _scope = scope; + _style = style; + _blocks = blocks; + + // Loops and conditionals over items are block loops and conditionals; this composer writes them and lives as + // long as the list composer, so an if chain can be continued while the list is open. + _blocksComposer = new BlockComposer(context, blocks, scope); + } + + /// Adds a top-level item with literal text. + /// The text. + /// This composer. + public ListComposer Item(string text) => Item(0, text); + + /// Adds an item with literal text. + /// The level: 0 is the top level. + /// The text. + /// This composer. + public ListComposer Item(int level, string text) + { + ArgumentNullException.ThrowIfNull(text); + Item(level, x => x.Text(text)); + return this; + } + + /// Adds a top-level item holding one value. + /// The data path. + /// This composer. + public ListComposer Item(TemplatePath value) => Item(0, x => x.Value(value)); + + /// Adds an item holding one value. + /// The level: 0 is the top level. + /// The data path. + /// This composer. + public ListComposer Item(int level, TemplatePath value) => Item(level, x => x.Value(value)); + + /// Adds a top-level item with mixed content. + /// Describes the item's text. + /// This composer. + public ListComposer Item(Action content) => Item(0, content); + + /// Adds an item with mixed content. + /// The level: 0 is the top level, at most 8. + /// Describes the item's text. + /// This composer. + public ListComposer Item(int level, Action content) + { + ArgumentNullException.ThrowIfNull(content); + EnsureOpen(); + if (level is < 0 or > 8) + { + throw new ArgumentOutOfRangeException(nameof(level), level, "A list level is between 0 and 8."); + } + + InlineComposer composer = new InlineComposer(_context, _scope); + content(composer); + _blocks.Add(new ParagraphBlock(composer.Close(), null, new ListItemInfo(_style, level))); + return this; + } + + /// Repeats items for every item of a typed collection. + /// The item type. + /// The collection, from . + /// The iteration variable. + /// Describes the items for each element; it receives the typed element. + /// This composer. + public ListComposer ForEach(TemplateCollection collection, string itemName, Action, ListComposer> items) + { + ArgumentNullException.ThrowIfNull(items); + ForEach(collection.Untyped, itemName, (item, l) => items(new LoopItem(item, collection.Naming), l)); + return this; + } + + /// Repeats items for every item of a collection. + /// The data path of the collection. + /// The iteration variable. + /// Describes the items for each element; it receives the element. + /// This composer. + public ListComposer ForEach(TemplatePath collection, string itemName, Action items) + { + ArgumentNullException.ThrowIfNull(items); + EnsureOpen(); + _blocksComposer.ForEach(collection, itemName, (item, body) => + { + ListComposer inner = new ListComposer(_context, body.Scope, _style, body.Blocks); + items(item, inner); + inner.Close(); + }); + return this; + } + + /// Adds items shown only when a condition holds. + /// The condition. + /// Describes the items. + /// The chain, to add elseif and else items. + public ListIfChain If(Condition condition, Action items) + { + ArgumentNullException.ThrowIfNull(items); + EnsureOpen(); + IfChain chain = _blocksComposer.If(condition, body => Compose(body, items)); + return new ListIfChain(chain, this); + } + + internal void Close() + { + _isOpen = false; + _blocksComposer.Close(); + } + + internal void Compose(BlockComposer body, Action items) + { + ListComposer inner = new ListComposer(_context, body.Scope, _style, body.Blocks); + items(inner); + inner.Close(); + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A list composer was used outside the lambda it was passed to."); + } + } +} + +/// Continues conditional list items: and a last . +public sealed class ListIfChain +{ + private readonly IfChain _chain; + private readonly ListComposer _list; + + internal ListIfChain(IfChain chain, ListComposer list) + { + _chain = chain; + _list = list; + } + + /// Adds items for a further condition. + /// The condition. + /// Describes the items. + /// This chain. + public ListIfChain ElseIf(Condition condition, Action items) + { + ArgumentNullException.ThrowIfNull(items); + _chain.ElseIf(condition, body => _list.Compose(body, items)); + return this; + } + + /// Adds the items shown when no condition holds. It ends the chain. + /// Describes the items. + public void Else(Action items) + { + ArgumentNullException.ThrowIfNull(items); + _chain.Else(body => _list.Compose(body, items)); + } +} diff --git a/src/TriasDev.Templify.Builder/Loops.cs b/src/TriasDev.Templify.Builder/Loops.cs new file mode 100644 index 00000000..a13b1849 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Loops.cs @@ -0,0 +1,195 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder; + +/// +/// The current item of a loop. It exists only inside the loop's lambda; paths +/// from it start with the loop's iteration variable ({{line.amount}}) and are checked to be used inside that loop. +/// +public sealed class LoopItem +{ + private readonly LoopScope _scope; + + /// The loop's scope (for the JSON importer's metadata paths). + internal LoopScope Scope => _scope; + + internal LoopItem(LoopScope scope) + { + _scope = scope; + } + + /// Gets the item itself: {{line}}. + public TemplatePath Self => TemplatePath.ForItem(_scope); + + /// Gets a path from the item: item["amount"] is {{line.amount}}. + /// Dot-separated segments. + public TemplatePath this[string relative] => Self[relative]; + + /// + /// Gets the loop's metadata: line.Loop.Number is {{@number}}. It is a member of its own, so a data + /// property named Number, Count or Index never reads as the metadata. + /// + public LoopInfo Loop => new LoopInfo(_scope); +} + +/// The metadata of the current loop item (). Only in this loop's own body, not in nested loops. +public sealed class LoopInfo +{ + private readonly LoopScope _scope; + + internal LoopInfo(LoopScope scope) + { + _scope = scope; + } + + /// Gets the 0-based position of the item: {{@index}}. + public TemplatePath Index => TemplatePath.ForMetadata(_scope, "index"); + + /// Gets the 1-based position of the item: {{@number}}. + public TemplatePath Number => TemplatePath.ForMetadata(_scope, "number"); + + /// Gets the number of items: {{@count}}. + public TemplatePath Count => TemplatePath.ForMetadata(_scope, "count"); + + /// Gets a condition that holds for the first item: @first. + public Condition IsFirst => TemplatePath.ForMetadata(_scope, "first"); + + /// Gets a condition that holds for the last item: @last. + public Condition IsLast => TemplatePath.ForMetadata(_scope, "last"); +} + +/// +/// A reusable block of template content, the counterpart of QuestPDF's IComponent. Use it for content shared +/// by several templates or built through dependency injection; a plain extension method on +/// is enough for simple blocks. +/// +/// +/// The template keeps a component as a unit, not only the content it expands to, so that later versions can export +/// a definition with its components (see the builder's roadmap). +/// +public interface ITemplateComponent +{ + /// Describes the component's content. + /// The composer to describe the content with; valid only during this call. + void Compose(BlockComposer content); +} + +/// One loop while the template is composed: its iteration variable and the loop around it. +internal sealed partial class LoopScope(string itemName, TemplatePath collection, LoopScope? parent) +{ + public string ItemName { get; } = itemName; + + public TemplatePath Collection { get; } = collection; + + public LoopScope? Parent { get; } = parent; + + /// This scope and the scopes around it, innermost first. + public static IEnumerable Chain(LoopScope? scope) + { + for (LoopScope? current = scope; current != null; current = current.Parent) + { + yield return current; + } + } + + /// + /// A loop's collection path has no index: Templify's loop marker takes letters, digits, _ and . only, so + /// {{#foreach l in groups[1].lines}} would stay text in the filled document. + /// + public static TemplatePath ValidateCollection(TemplatePath collection, string itemName) + { + // foreach order in order.lines: inside, "order" would be the item, not the data's root. + if (collection.Scope is null && string.Equals(collection.ToString().Split('.', '[')[0], itemName, StringComparison.Ordinal)) + { + throw new ArgumentException( + $"The loop variable '{itemName}' hides the data path '{collection.Text}' it loops over; choose another name.", + nameof(itemName)); + } + + if (collection.ToString().Contains('[', StringComparison.Ordinal)) + { + throw new ArgumentException( + $"Templify cannot loop over '{collection.Text}': a loop's collection path has no list index (its loop marker takes letters, digits, '_' and '.' only).", + nameof(collection)); + } + + return collection; + } + + /// Checks an iteration variable name where it is written. + public static string ValidateItemName(string itemName, LoopScope? enclosing) + { + ArgumentNullException.ThrowIfNull(itemName); + if (!NamePattern().IsMatch(itemName)) + { + throw new ArgumentException( + $"'{itemName}' is not a valid loop variable name: use letters, digits and '_', starting with a letter or '_'.", + nameof(itemName)); + } + + if (_reserved.Contains(itemName)) + { + throw new ArgumentException($"'{itemName}' cannot name a loop variable: it is a Templify keyword.", nameof(itemName)); + } + + if (Chain(enclosing).Any(s => string.Equals(s.ItemName, itemName, StringComparison.Ordinal))) + { + throw new ArgumentException( + $"The loop variable '{itemName}' is already used by an enclosing loop; choose another name so both stay reachable.", + nameof(itemName)); + } + + return itemName; + } + + /// + /// Reports a path used where it cannot work: an iteration variable outside its loop, metadata of an outer loop, or + /// a path from the data's root whose first segment a loop variable hides. + /// + public static void CheckUse(BuildContext context, LoopScope? current, TemplatePath path) + { + if (path.IsRoot) + { + return; + } + + if (path.Scope is { } owner && !Chain(current).Contains(owner)) + { + context.Error( + DiagnosticCodes.LoopVariableOutOfScope, + $"'{path.Text}' uses the loop variable '{owner.ItemName}' outside its loop (foreach {owner.ItemName} in {owner.Collection.Text})."); + return; + } + + if (path.IsMetadata && path.Scope != current) + { + context.Error( + DiagnosticCodes.OuterLoopMetadata, + $"'{path.Text}' of the loop over '{path.Scope!.Collection.Text}' is used inside a nested loop; Templify's loop metadata always refers to the innermost loop."); + return; + } + + if (path.Scope is null) + { + string first = path.ToString().Split('.')[0].Split('[')[0]; + LoopScope? hiding = Chain(current).FirstOrDefault(s => string.Equals(s.ItemName, first, StringComparison.Ordinal)); + if (hiding != null) + { + context.Error( + DiagnosticCodes.RootPathHidden, + $"'{path.Text}' starts at the data's root, but inside the loop over '{hiding.Collection.Text}' the name '{first}' is the loop variable. Rename the loop variable."); + } + } + } + + private static readonly HashSet _reserved = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "in", "this", "and", "or", "not", "is", "empty", "exists", "contains", "startswith", "endswith", "true", "false", "null", + }; + + [GeneratedRegex(@"^[A-Za-z_]\w*$", RegexOptions.CultureInvariant)] + private static partial Regex NamePattern(); +} diff --git a/src/TriasDev.Templify.Builder/Model/DocumentModel.cs b/src/TriasDev.Templify.Builder/Model/DocumentModel.cs new file mode 100644 index 00000000..53b3034c --- /dev/null +++ b/src/TriasDev.Templify.Builder/Model/DocumentModel.cs @@ -0,0 +1,522 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; + +namespace TriasDev.Templify.Builder.Model; + +/// The format-neutral description of a template that the writers turn into a package. +/// The blocks of the document body, in order. +/// The document language. +/// The named styles; when the definition sets none. +/// The standard document properties. +/// The builder's stamp, written as custom document properties. +/// The page setup, header and footer. +internal sealed record DocumentModel(IReadOnlyList Body, CultureInfo Language, StyleSheet Styles, DocumentInfo Info, TemplateStamp Stamp, PageSetup Page); + +/// +/// Page size, margins (page edge to body text), header/footer distances (page edge to header/footer), and the +/// header and footer parts. With DistinctFirstPage, FirstHeader/FirstFooter are the first +/// page's (empty for none). +/// +internal sealed record PageSetup( + PageSize Size, + Length Top, + Length Right, + Length Bottom, + Length Left, + Length HeaderDistance, + Length FooterDistance, + List? Header, + List? Footer, + bool DistinctFirstPage, + List? FirstHeader, + List? FirstFooter) +{ + /// Gets the width of the text frame: the page width minus the side margins. + public Length FrameWidth => Size.Width - Left - Right; + + /// Gets every block of the header and footer parts. + public IEnumerable AllBlocks => + (Header ?? []).Concat(Footer ?? []).Concat(FirstHeader ?? []).Concat(FirstFooter ?? []); +} + +/// A block-level element of the document. +internal abstract record Block; + +/// A paragraph. +/// The paragraph content, in order. +/// The paragraph style; null for the format's default paragraph style (or the list's item style). +/// For a list item: its list style and level. +/// The paragraph's own layout options on top of its style; null for none. +internal sealed record ParagraphBlock(IReadOnlyList Inlines, ParagraphStyleKey? Style = null, ListItemInfo? List = null, ParagraphOverrides? Options = null) : Block; + +/// Layout options set on one paragraph (); null members are the style's. +internal sealed record ParagraphOverrides(Length? SpaceBefore, Length? SpaceAfter, bool? KeepWithNext, bool? KeepLinesTogether) +{ + public bool IsEmpty => SpaceBefore is null && SpaceAfter is null && KeepWithNext is null && KeepLinesTogether is null; +} + +/// A paragraph's place in a bullet list. +internal sealed record ListItemInfo(ListStyleKey Style, int Level); + +/// +/// A bullet list as one unit: its items (paragraphs with ) and the loops and conditionals +/// over them. Writers see the items only: and expand it. +/// +internal sealed record ListBlock(ListStyleKey Style, List Items) : Block; + +/// One level of a list style. +internal sealed record ListLevel(string Bullet, Length Indent, Length Hanging); + +/// A list style as defined in a . +internal sealed class ListStyleDefinition(ListStyleKey key) +{ + public ListStyleKey Key { get; } = key; + + public SortedDictionary Levels { get; } = new SortedDictionary(); + + public ParagraphStyleKey? ItemStyle { get; set; } +} + +/// A page break: the content after it starts on a new page. +internal sealed record PageBreakBlock : Block; + +/// An if / elseif / else chain. Branches and the else part are filled while the chain is composed. +internal sealed record ConditionalBlock : Block +{ + public List Branches { get; } = new List(); + + /// Gets or sets the else part; null when there is none. + public List? Else { get; set; } +} + +/// A paragraph-level loop: {{#foreach item in collection}} … {{/foreach}}. +internal sealed record LoopBlock(TemplatePath Collection, string ItemName, List Body) : Block; + +/// Space on the four sides of a cell's content. +internal sealed record Insets(Length Top, Length Right, Length Bottom, Length Left) +{ + public static Insets Of(Length vertical, Length horizontal) => new Insets(vertical, horizontal, vertical, horizontal); +} + +/// Lines on the four sides; a null side has no line of its own. +internal sealed record Edges(BorderLine? Top, BorderLine? Right, BorderLine? Bottom, BorderLine? Left) +{ + public static Edges None { get; } = new Edges(null, null, null, null); + + public bool IsEmpty => Top is null && Right is null && Bottom is null && Left is null; + + /// These edges with on the given sides. + public Edges With(Sides sides, BorderLine line) => new Edges( + sides.HasFlag(Sides.Top) ? line : Top, + sides.HasFlag(Sides.Right) ? line : Right, + sides.HasFlag(Sides.Bottom) ? line : Bottom, + sides.HasFlag(Sides.Left) ? line : Left); +} + +/// A line: width and colour. +internal sealed record BorderLine(Length Width, Color Color); + +/// A column of a table: a fixed width, or a weight (when is null). +internal sealed record ColumnSpec(Length? Fixed, double Weight); + +/// A table: columns, rows (header rows first) and options. A box is a one-cell table with a box style. +internal sealed record TableBlock : Block +{ + public TableStyleKey? Style { get; set; } + + /// Gets or sets the box style when this table is a Box. + public BoxStyleKey? BoxStyle { get; set; } + + public List Columns { get; } = new List(); + + public List Rows { get; } = new List(); + + public Length? SpaceAfter { get; set; } + + /// Gets or sets the space before the table. + public Length? SpaceBefore { get; set; } + + /// Gets or sets the distance from the start of the frame to the table; it narrows the columns. + public Length? Indent { get; set; } + + /// The width the columns share: the frame minus the indent. + public Length ColumnFrame(Length frame) => frame - (Indent ?? Length.Zero); + + /// Every row of the table, also inside row loops and row conditionals. + public IEnumerable AllRows() => TableRowItem.Flatten(Rows); +} + +/// An item of a table's row list: a row, or (later) a row loop or row conditional. +internal abstract class TableRowItem +{ + public static IEnumerable Flatten(IEnumerable items) + { + foreach (TableRowItem item in items) + { + foreach (TableRowModel row in item.ContainedRows()) + { + yield return row; + } + } + } + + protected abstract IEnumerable ContainedRows(); +} + +/// A table row. +internal sealed class TableRowModel(bool isHeader) : TableRowItem +{ + public bool IsHeader { get; } = isHeader; + + public bool AllowSplit { get; set; } + + /// Gets or sets the paragraph style of this row's paragraphs without their own (overrides the table style). + public ParagraphStyleKey? ParagraphStyle { get; set; } + + public List Cells { get; } = new List(); + + protected override IEnumerable ContainedRows() => [this]; +} + +/// A loop over table rows: {{#foreach item in collection}} and {{/foreach}} in marker rows. +internal sealed class TableRowLoop(TemplatePath collection, string itemName) : TableRowItem +{ + public TemplatePath Collection { get; } = collection; + + public string ItemName { get; } = itemName; + + public List Rows { get; } = new List(); + + protected override IEnumerable ContainedRows() => Flatten(Rows); +} + +/// Conditional table rows: if / elseif / else in marker rows. +internal sealed class TableRowConditional : TableRowItem +{ + public List<(Condition Condition, List Rows)> Branches { get; } = new List<(Condition, List)>(); + + public List? Else { get; set; } + + protected override IEnumerable ContainedRows() => + Flatten(Branches.SelectMany(b => b.Rows).Concat(Else ?? [])); +} + +/// A table cell. +internal sealed class TableCellModel +{ + public List Content { get; } = new List(); + + public int Span { get; set; } = 1; + + public Color? Background { get; set; } + + public CellVerticalAlignment? VerticalAlignment { get; set; } + + /// Gets or sets the cell's own lines, replacing the table style's on those sides; null for none. + public Edges? Borders { get; set; } + + /// Gets or sets the cell's own padding, replacing the table style's; null for the style's. + public Insets? Padding { get; set; } +} + +/// A box style as defined in a . +internal sealed class BoxStyleDefinition(BoxStyleKey key) +{ + public BoxStyleKey Key { get; } = key; + + public BorderLine? Border { get; set; } + + public Color? Background { get; set; } + + public Insets Padding { get; set; } = Insets.Of(6.Pt(), 6.Pt()); + + public Length? SpaceAfter { get; set; } + + /// The box as a table style: the border all round, the background on its cell. + public TableStyleDefinition AsTableStyle() => new TableStyleDefinition(new TableStyleKey("Box_" + Key.Id)) + { + Outer = new Edges(Border, Border, Border, Border), + BodyBackground = Background, + Padding = Padding, + }; +} + +/// A block of format XML (escape hatch). +internal sealed record RawXmlBlock(RawBlock Raw) : Block; + +/// A table of contents over the headings up to . +/// The deepest outline level listed. +/// The paragraph style of the entries per level; null or missing levels for the application's own. +internal sealed record TocBlock(int MaxLevel, IReadOnlyDictionary? EntryStyles = null) : Block; + +/// Vertical space: an empty paragraph whose line is exactly high. +internal sealed record SpacerBlock(Length Height) : Block; + +/// A horizontal rule: an empty paragraph whose top border is the line. +/// The line. +/// The space above the line. +/// The space below the line. +/// The rule's width from the start of the frame; null for the whole frame. +internal sealed record RuleBlock(BorderLine Line, Length SpaceBefore, Length SpaceAfter, Length? Width = null) : Block; + +/// A table style as defined in a . +internal sealed class TableStyleDefinition(TableStyleKey key) +{ + /// Word's default cell margin left and right (108 twips). + public static readonly Length DefaultPaddingHorizontal = 5.4.Pt(); + + public TableStyleKey Key { get; } = key; + + /// Gets or sets the lines around the table, per side. + public Edges Outer { get; set; } = Edges.None; + + public BorderLine? RowRule { get; set; } + + public BorderLine? ColumnRule { get; set; } + + public BorderLine? HeaderRule { get; set; } + + public Color? HeaderBackground { get; set; } + + /// Gets or sets the background of body cells without their own (boxes). + public Color? BodyBackground { get; set; } + + /// Gets the padding a table without a style has: Word's default cell margins. + public static Insets DefaultPadding { get; } = Insets.Of(Length.Zero, DefaultPaddingHorizontal); + + public Insets Padding { get; set; } = DefaultPadding; + + /// Gets or sets the paragraph style of body-row paragraphs without their own. + public ParagraphStyleKey? ParagraphStyle { get; set; } + + /// Gets or sets the paragraph style of header-row paragraphs without their own. + public ParagraphStyleKey? HeaderParagraphStyle { get; set; } +} + +/// Walks the block tree. +internal static class BlockTree +{ + /// Every block, also inside conditionals, loops, components and table cells, in document order. + public static IEnumerable All(IEnumerable blocks) + { + foreach (Block block in blocks) + { + yield return block; + foreach (Block inner in All(Children(block, intoCells: true))) + { + yield return inner; + } + } + } + + /// The tables of a container, through conditionals, loops and components but not into table cells. + public static IEnumerable Tables(IEnumerable blocks) + { + foreach (Block block in blocks) + { + if (block is TableBlock table) + { + yield return table; + continue; + } + + foreach (TableBlock inner in Tables(Children(block, intoCells: false))) + { + yield return inner; + } + } + } + + /// The blocks of a container, through conditionals, loops, components and lists but not into table cells. + public static IEnumerable InContainer(IEnumerable blocks) + { + foreach (Block block in blocks) + { + yield return block; + foreach (Block inner in InContainer(Children(block, intoCells: false))) + { + yield return inner; + } + } + } + + /// Every paragraph at any depth. + public static IEnumerable Paragraphs(IEnumerable blocks) => All(blocks).OfType(); + + /// Whether conditionals or loops occur at any depth, also as table rows (they need the marker style). + public static bool HasMarkers(IEnumerable blocks) => + All(blocks).Any(b => b is ConditionalBlock or LoopBlock || (b is TableBlock table && HasRowMarkers(table.Rows))); + + private static bool HasRowMarkers(IEnumerable items) => items.Any(i => i is TableRowLoop or TableRowConditional); + + private static IEnumerable Children(Block block, bool intoCells) => block switch + { + ConditionalBlock conditional => conditional.Branches.SelectMany(b => b.Body).Concat(conditional.Else ?? []), + LoopBlock loop => loop.Body, + ComponentBlock component => component.Body, + ListBlock list => list.Items, + TableBlock table when intoCells => table.AllRows().SelectMany(r => r.Cells).SelectMany(c => c.Content), + _ => [], + }; +} + +/// +/// The entry styles of a template's tables of contents, per level. DOCX keeps them for the whole document (Word's +/// "toc N"), so every table of contents uses them, also one that sets none; the build checks that tables agree. +/// +internal static class TocEntries +{ + public static SortedDictionary Of(IEnumerable blocks) + { + SortedDictionary levels = new SortedDictionary(); + foreach (TocBlock toc in BlockTree.All(blocks).OfType()) + { + foreach ((int level, ParagraphStyleKey style) in toc.EntryStyles ?? new Dictionary()) + { + levels.TryAdd(level, style); + } + } + + return levels; + } +} + +/// The content of a component, kept as a unit together with the component that produced it. +internal sealed record ComponentBlock(ITemplateComponent Component, List Body) : Block; + +/// One condition of a and the blocks it guards. +internal sealed record ConditionalBranch(Condition Condition, List Body); + +/// A marker paragraph, produced from a by . +/// The marker, for example {{#if order.isPaid}}. +internal sealed record MarkerBlock(string Text) : Block; + +/// Turns conditional blocks into marker paragraphs around their content, in document order. +internal static class BlockFlattener +{ + public static IEnumerable Flatten(IEnumerable blocks) + { + foreach (Block block in blocks) + { + if (block is LoopBlock loop) + { + yield return new MarkerBlock(TemplateSyntax.ForEach(loop.ItemName, loop.Collection)); + foreach (Block inner in Flatten(loop.Body)) + { + yield return inner; + } + + yield return new MarkerBlock(TemplateSyntax.EndForEach); + continue; + } + + if (block is ListBlock list) + { + foreach (Block inner in Flatten(list.Items)) + { + yield return inner; + } + + continue; + } + + if (block is ComponentBlock component) + { + foreach (Block inner in Flatten(component.Body)) + { + yield return inner; + } + + continue; + } + + if (block is not ConditionalBlock conditional) + { + yield return block; + continue; + } + + for (int i = 0; i < conditional.Branches.Count; i++) + { + ConditionalBranch branch = conditional.Branches[i]; + yield return new MarkerBlock(i == 0 ? TemplateSyntax.If(branch.Condition) : TemplateSyntax.ElseIf(branch.Condition)); + foreach (Block inner in Flatten(branch.Body)) + { + yield return inner; + } + } + + if (conditional.Else is { } otherwise) + { + yield return new MarkerBlock(TemplateSyntax.Else); + foreach (Block inner in Flatten(otherwise)) + { + yield return inner; + } + } + + yield return new MarkerBlock(TemplateSyntax.EndIf); + } + } + +} + +/// Content inside a paragraph. +/// The character style; null for the paragraph's own formatting. +internal abstract record Inline(CharacterStyleKey? Style); + +/// Literal text. Tabs and line breaks in it are written as the format's tab and line break. +/// The text. +/// The character style, or null. +internal sealed record TextInline(string Text, CharacterStyleKey? Style = null) : Inline(Style); + +/// The kinds of page field. +internal enum PageField +{ + Number, + Count, +} + +/// A page number or page count field. +internal sealed record PageFieldInline(PageField Field, CharacterStyleKey? Style = null) : Inline(Style); + +/// An inline conditional: if / elseif / else markers inside one paragraph around text. +internal sealed record InlineConditional() : Inline((CharacterStyleKey?)null) +{ + public List<(Condition Condition, IReadOnlyList Inlines)> Branches { get; } = new List<(Condition, IReadOnlyList)>(); + + public IReadOnlyList? Else { get; set; } + + /// The inlines inside, also of nested conditionals. + public static IEnumerable Descendants(IEnumerable inlines) + { + foreach (Inline inline in inlines) + { + yield return inline; + if (inline is InlineConditional conditional) + { + foreach (Inline inner in Descendants(conditional.Branches.SelectMany(b => b.Inlines).Concat(conditional.Else ?? []))) + { + yield return inner; + } + } + } + } +} + +/// An inline expression: {{(condition):format}}. +internal sealed record ExpressionInline(Condition Condition, ValueFormat? Format) : Inline((CharacterStyleKey?)null); + +/// An image inside a paragraph, sized already. +internal sealed record ImageInline(ImageSource Image, string AltText, Length Width, Length Height) : Inline((CharacterStyleKey?)null); + +/// A tab to a right-aligned tab stop at the end of the text frame. +internal sealed record RightTabInline() : Inline((CharacterStyleKey?)null); + +/// A placeholder for a value from the data. +/// The data path; never empty. +/// The format specifier, or null. +/// The character style, or null. +internal sealed record ValueInline(TemplatePath Path, ValueFormat? Format = null, CharacterStyleKey? Style = null) : Inline(Style); diff --git a/src/TriasDev.Templify.Builder/Page.cs b/src/TriasDev.Templify.Builder/Page.cs new file mode 100644 index 00000000..5f7dc516 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Page.cs @@ -0,0 +1,256 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// A page size (portrait). +public sealed record PageSize +{ + /// Initializes a page size. + /// The width; greater than zero. + /// The height; greater than zero. + public PageSize(Length width, Length height) + { + if (width <= Length.Zero || height <= Length.Zero) + { + throw new ArgumentOutOfRangeException(nameof(width), "A page has a positive width and height."); + } + + Width = width; + Height = height; + } + + /// Gets the width. + public Length Width { get; } + + /// Gets the height. + public Length Height { get; } + + /// Gets A4, 210 × 297 mm. + public static PageSize A4 { get; } = new PageSize(210.Mm(), 297.Mm()); + + /// Gets A5, 148 × 210 mm. + public static PageSize A5 { get; } = new PageSize(148.Mm(), 210.Mm()); + + /// Gets US Letter, 8.5 × 11 in. + public static PageSize Letter { get; } = new PageSize(612.Pt(), 792.Pt()); + + /// Gets US Legal, 8.5 × 14 in. + public static PageSize Legal { get; } = new PageSize(612.Pt(), 1008.Pt()); +} + +/// +/// Describes the page: size, margins, header and footer. Valid only inside the lambda passed to +/// . Without it a template is A4 with 25 mm margins. +/// +public sealed class PageComposer +{ + private readonly BuildContext _context; + private readonly PageSetupBuilder _setup; + private bool _isOpen = true; + + internal PageComposer(BuildContext context, PageSetupBuilder setup) + { + _context = context; + _setup = setup; + } + + /// Sets the page size. + /// The size, for example . + /// This composer. + public PageComposer Size(PageSize size) + { + EnsureOpen(); + _setup.Size = size ?? throw new ArgumentNullException(nameof(size)); + return this; + } + + /// Sets all four margins: the distances from the page edges to the body text. + /// The top margin. + /// The right margin. + /// The bottom margin. + /// The left margin. + /// This composer. + public PageComposer Margins(Length top, Length right, Length bottom, Length left) + { + EnsureOpen(); + _setup.Top = StyleRanges.NotNegative(top, nameof(top)); + _setup.Right = StyleRanges.NotNegative(right, nameof(right)); + _setup.Bottom = StyleRanges.NotNegative(bottom, nameof(bottom)); + _setup.Left = StyleRanges.NotNegative(left, nameof(left)); + return this; + } + + /// Sets the same margin on all four sides. + /// The margin. + /// This composer. + public PageComposer Margins(Length all) => Margins(all, all, all, all); + + /// Sets the distances from the top edge to the header and from the bottom edge to the footer. + /// The header distance; at most the top margin. + /// The footer distance; at most the bottom margin. + /// This composer. + public PageComposer HeaderFooterDistance(Length header, Length footer) + { + EnsureOpen(); + _setup.HeaderDistance = StyleRanges.NotNegative(header, nameof(header)); + _setup.FooterDistance = StyleRanges.NotNegative(footer, nameof(footer)); + return this; + } + + /// Describes the header of every page (and of the first page, unless sets one). + /// Describes the header's blocks: paragraphs, values, conditions, page numbers. + /// This composer. + public PageComposer Header(Action header) + { + ArgumentNullException.ThrowIfNull(header); + EnsureOpen(); + _setup.Header = BlockComposer.Compose(_context, null, header); + return this; + } + + /// Describes the footer of every page (and of the first page, unless sets one). + /// Describes the footer's blocks. + /// This composer. + public PageComposer Footer(Action footer) + { + ArgumentNullException.ThrowIfNull(footer); + EnsureOpen(); + _setup.Footer = BlockComposer.Compose(_context, null, footer); + return this; + } + + /// + /// Gives the first page its own header and footer, for example none on a cover page. What the first page does not + /// set, it takes from the default header and footer. + /// + /// Describes the first page's header and footer. + /// This composer. + public PageComposer FirstPage(Action firstPage) + { + ArgumentNullException.ThrowIfNull(firstPage); + EnsureOpen(); + _setup.DistinctFirstPage = true; + FirstPageComposer composer = new FirstPageComposer(_context, _setup); + firstPage(composer); + composer.Close(); + return this; + } + + internal void Close() => _isOpen = false; + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A page composer was used outside the lambda it was passed to."); + } + } +} + +/// Describes the first page's header and footer. Valid only inside the lambda it is passed to. +public sealed class FirstPageComposer +{ + private readonly BuildContext _context; + private readonly PageSetupBuilder _setup; + private bool _isOpen = true; + + internal FirstPageComposer(BuildContext context, PageSetupBuilder setup) + { + _context = context; + _setup = setup; + } + + /// Describes the first page's header. + /// Describes the header's blocks. + /// This composer. + public FirstPageComposer Header(Action header) + { + ArgumentNullException.ThrowIfNull(header); + EnsureOpen(); + _setup.FirstHeader = BlockComposer.Compose(_context, null, header); + return this; + } + + /// Describes the first page's footer. + /// Describes the footer's blocks. + /// This composer. + public FirstPageComposer Footer(Action footer) + { + ArgumentNullException.ThrowIfNull(footer); + EnsureOpen(); + _setup.FirstFooter = BlockComposer.Compose(_context, null, footer); + return this; + } + + /// Leaves the first page without a header. + /// This composer. + public FirstPageComposer NoHeader() + { + EnsureOpen(); + _setup.FirstHeader = new List(); + return this; + } + + /// Leaves the first page without a footer. + /// This composer. + public FirstPageComposer NoFooter() + { + EnsureOpen(); + _setup.FirstFooter = new List(); + return this; + } + + internal void Close() => _isOpen = false; + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A first-page composer was used outside the lambda it was passed to."); + } + } +} + +/// Collects the page setup while it is composed. +internal sealed class PageSetupBuilder +{ + public PageSize Size { get; set; } = PageSize.A4; + + public Length Top { get; set; } = 25.Mm(); + + public Length Right { get; set; } = 25.Mm(); + + public Length Bottom { get; set; } = 25.Mm(); + + public Length Left { get; set; } = 25.Mm(); + + public Length HeaderDistance { get; set; } = 12.5.Mm(); + + public Length FooterDistance { get; set; } = 12.5.Mm(); + + public List? Header { get; set; } + + public List? Footer { get; set; } + + public bool DistinctFirstPage { get; set; } + + public List? FirstHeader { get; set; } + + public List? FirstFooter { get; set; } + + public PageSetup ToSetup() + { + return new PageSetup( + Size, Top, Right, Bottom, Left, + Length.Min(HeaderDistance, Top), + Length.Min(FooterDistance, Bottom), + Header, + Footer, + DistinctFirstPage, + DistinctFirstPage ? FirstHeader ?? Header : null, + DistinctFirstPage ? FirstFooter ?? Footer : null); + } +} diff --git a/src/TriasDev.Templify.Builder/ParagraphOptions.cs b/src/TriasDev.Templify.Builder/ParagraphOptions.cs new file mode 100644 index 00000000..10d685b4 --- /dev/null +++ b/src/TriasDev.Templify.Builder/ParagraphOptions.cs @@ -0,0 +1,69 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Layout options of one paragraph: space before and after, keep with next, keep lines together. They are written as the +/// paragraph's own properties on top of its named style (a visible override in Word and LibreOffice); text formatting, +/// alignment and indents come from styles only. Valid only inside the lambda it is passed to. +/// +public sealed class ParagraphOptions +{ + private Length? _spaceBefore; + private Length? _spaceAfter; + private bool? _keepWithNext; + private bool? _keepLinesTogether; + + internal ParagraphOptions() + { + } + + /// Sets the space above the paragraph. + /// The space; not negative. + /// These options. + public ParagraphOptions SpaceBefore(Length space) + { + _spaceBefore = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Sets the space below the paragraph. + /// The space; not negative. + /// These options. + public ParagraphOptions SpaceAfter(Length space) + { + _spaceAfter = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Keeps the paragraph on the same page as the next one. + /// Whether to keep it with the next paragraph. + /// These options. + public ParagraphOptions KeepWithNext(bool value = true) + { + _keepWithNext = value; + return this; + } + + /// Keeps the paragraph's lines on one page. + /// Whether to keep its lines together. + /// These options. + public ParagraphOptions KeepLinesTogether(bool value = true) + { + _keepLinesTogether = value; + return this; + } + + /// Runs the options lambda; null when it set nothing. + internal static ParagraphOverrides? Compose(Action options) + { + ArgumentNullException.ThrowIfNull(options); + ParagraphOptions composer = new ParagraphOptions(); + options(composer); + ParagraphOverrides result = new ParagraphOverrides(composer._spaceBefore, composer._spaceAfter, composer._keepWithNext, composer._keepLinesTogether); + return result.IsEmpty ? null : result; + } +} diff --git a/src/TriasDev.Templify.Builder/PublicAPI.Shipped.txt b/src/TriasDev.Templify.Builder/PublicAPI.Shipped.txt new file mode 100644 index 00000000..7dc5c581 --- /dev/null +++ b/src/TriasDev.Templify.Builder/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt new file mode 100644 index 00000000..aa2736cc --- /dev/null +++ b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt @@ -0,0 +1,813 @@ +#nullable enable +[TPLB001]override TriasDev.Templify.Builder.BoxStyleKey.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.BoxStyleKey.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.BoxStyleKey.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.BuildDiagnostic.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.BuildDiagnostic.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.BuildDiagnostic.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.CharacterStyleKey.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.CharacterStyleKey.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.CharacterStyleKey.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.Color.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.Color.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.Color.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.Condition.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.ContractEntry.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.ContractEntry.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.ContractEntry.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.DataCatalogEntry.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.DataCatalogEntry.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.DataCatalogEntry.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.FontFace.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.FontFace.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.FontFace.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.Length.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.Length.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.Length.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.ListStyleKey.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.ListStyleKey.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.ListStyleKey.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.PageSize.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.PageSize.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.PageSize.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.ParagraphStyleKey.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.ParagraphStyleKey.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.ParagraphStyleKey.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.RawBlock.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.RawBlock.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.RawBlock.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TableStyleKey.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TableStyleKey.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TableStyleKey.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateBuildOptions.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateBuildOptions.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateBuildOptions.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateCollection.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateCollection.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateCollection.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateIdentity.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateIdentity.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateIdentity.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateInspection.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateInspection.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateInspection.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplatePath.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateStamp.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateStamp.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateStamp.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.ValueFormat.ToString() -> string! +[TPLB001]static TriasDev.Templify.Builder.BoxStyleKey.operator !=(TriasDev.Templify.Builder.BoxStyleKey? left, TriasDev.Templify.Builder.BoxStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.BoxStyleKey.operator ==(TriasDev.Templify.Builder.BoxStyleKey? left, TriasDev.Templify.Builder.BoxStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.BuildDiagnostic.operator !=(TriasDev.Templify.Builder.BuildDiagnostic? left, TriasDev.Templify.Builder.BuildDiagnostic? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.BuildDiagnostic.operator ==(TriasDev.Templify.Builder.BuildDiagnostic? left, TriasDev.Templify.Builder.BuildDiagnostic? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.BuilderStyles.TemplateMarker.get -> TriasDev.Templify.Builder.ParagraphStyleKey! +[TPLB001]static TriasDev.Templify.Builder.CharacterStyleKey.operator !=(TriasDev.Templify.Builder.CharacterStyleKey? left, TriasDev.Templify.Builder.CharacterStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.CharacterStyleKey.operator ==(TriasDev.Templify.Builder.CharacterStyleKey? left, TriasDev.Templify.Builder.CharacterStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Color.FromHex(string! hex) -> TriasDev.Templify.Builder.Color +[TPLB001]static TriasDev.Templify.Builder.Color.FromRgb(byte red, byte green, byte blue) -> TriasDev.Templify.Builder.Color +[TPLB001]static TriasDev.Templify.Builder.Color.operator !=(TriasDev.Templify.Builder.Color left, TriasDev.Templify.Builder.Color right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Color.operator ==(TriasDev.Templify.Builder.Color left, TriasDev.Templify.Builder.Color right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Condition.operator !(TriasDev.Templify.Builder.Condition! operand) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.Condition.operator &(TriasDev.Templify.Builder.Condition! left, TriasDev.Templify.Builder.Condition! right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.Condition.operator |(TriasDev.Templify.Builder.Condition! left, TriasDev.Templify.Builder.Condition! right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.Condition.Raw(string! expression, params TriasDev.Templify.Builder.TemplatePath[]! uses) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.ContractEntry.operator !=(TriasDev.Templify.Builder.ContractEntry? left, TriasDev.Templify.Builder.ContractEntry? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.ContractEntry.operator ==(TriasDev.Templify.Builder.ContractEntry? left, TriasDev.Templify.Builder.ContractEntry? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.DataCatalog.ForType(System.Type! type, System.Text.Json.JsonNamingPolicy? naming = null) -> TriasDev.Templify.Builder.DataCatalog! +[TPLB001]static TriasDev.Templify.Builder.DataCatalog.From(System.Text.Json.JsonNamingPolicy? naming = null) -> TriasDev.Templify.Builder.DataCatalog! +[TPLB001]static TriasDev.Templify.Builder.DataCatalogEntry.operator !=(TriasDev.Templify.Builder.DataCatalogEntry? left, TriasDev.Templify.Builder.DataCatalogEntry? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.DataCatalogEntry.operator ==(TriasDev.Templify.Builder.DataCatalogEntry? left, TriasDev.Templify.Builder.DataCatalogEntry? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.DataContract.FromJson(string! json) -> TriasDev.Templify.Builder.DataContract! +[TPLB001]static TriasDev.Templify.Builder.FontFace.Embedded(byte[]! fontFile) -> TriasDev.Templify.Builder.FontFace! +[TPLB001]static TriasDev.Templify.Builder.FontFace.Embedded(string! family, byte[]! fontFile) -> TriasDev.Templify.Builder.FontFace! +[TPLB001]static TriasDev.Templify.Builder.FontFace.operator !=(TriasDev.Templify.Builder.FontFace? left, TriasDev.Templify.Builder.FontFace? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.FontFace.operator ==(TriasDev.Templify.Builder.FontFace? left, TriasDev.Templify.Builder.FontFace? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.ImageFit.Exact(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.ImageFit! +[TPLB001]static TriasDev.Templify.Builder.ImageFit.Height(TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.ImageFit! +[TPLB001]static TriasDev.Templify.Builder.ImageFit.Natural.get -> TriasDev.Templify.Builder.ImageFit! +[TPLB001]static TriasDev.Templify.Builder.ImageFit.Width(TriasDev.Templify.Builder.Length width) -> TriasDev.Templify.Builder.ImageFit! +[TPLB001]static TriasDev.Templify.Builder.ImageFit.Within(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.ImageFit! +[TPLB001]static TriasDev.Templify.Builder.ImageSource.FromBytes(byte[]! data) -> TriasDev.Templify.Builder.ImageSource! +[TPLB001]static TriasDev.Templify.Builder.ImageSource.Jpeg(byte[]! data) -> TriasDev.Templify.Builder.ImageSource! +[TPLB001]static TriasDev.Templify.Builder.ImageSource.Png(byte[]! data) -> TriasDev.Templify.Builder.ImageSource! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Export(TriasDev.Templify.Builder.ITemplateDefinition! definition, TriasDev.Templify.Builder.TemplateBuildOptions! options, TriasDev.Templify.Builder.ComponentCatalog? components) -> TriasDev.Templify.Builder.Json.TemplateJsonDocument! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Export(TriasDev.Templify.Builder.ITemplateDefinition! definition, TriasDev.Templify.Builder.TemplateBuildOptions! options) -> TriasDev.Templify.Builder.Json.TemplateJsonDocument! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Import(string! json, TriasDev.Templify.Builder.Json.TemplateJsonImportOptions? options = null) -> TriasDev.Templify.Builder.ITemplateDefinition! +[TPLB001]static TriasDev.Templify.Builder.Length.FromMillimeters(double millimeters) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Length.FromPoints(double points) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Length.operator -(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Length.operator -(TriasDev.Templify.Builder.Length value) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Length.operator !=(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.operator +(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Length.operator <(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.operator <=(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.operator ==(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.operator >(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.operator >=(TriasDev.Templify.Builder.Length left, TriasDev.Templify.Builder.Length right) -> bool +[TPLB001]static TriasDev.Templify.Builder.Length.Zero.get -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.ListStyleKey.operator !=(TriasDev.Templify.Builder.ListStyleKey? left, TriasDev.Templify.Builder.ListStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.ListStyleKey.operator ==(TriasDev.Templify.Builder.ListStyleKey? left, TriasDev.Templify.Builder.ListStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.PageSize.A4.get -> TriasDev.Templify.Builder.PageSize! +[TPLB001]static TriasDev.Templify.Builder.PageSize.A5.get -> TriasDev.Templify.Builder.PageSize! +[TPLB001]static TriasDev.Templify.Builder.PageSize.Legal.get -> TriasDev.Templify.Builder.PageSize! +[TPLB001]static TriasDev.Templify.Builder.PageSize.Letter.get -> TriasDev.Templify.Builder.PageSize! +[TPLB001]static TriasDev.Templify.Builder.PageSize.operator !=(TriasDev.Templify.Builder.PageSize? left, TriasDev.Templify.Builder.PageSize? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.PageSize.operator ==(TriasDev.Templify.Builder.PageSize? left, TriasDev.Templify.Builder.PageSize? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.ParagraphStyleKey.operator !=(TriasDev.Templify.Builder.ParagraphStyleKey? left, TriasDev.Templify.Builder.ParagraphStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.ParagraphStyleKey.operator ==(TriasDev.Templify.Builder.ParagraphStyleKey? left, TriasDev.Templify.Builder.ParagraphStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.RawBlock.operator !=(TriasDev.Templify.Builder.RawBlock? left, TriasDev.Templify.Builder.RawBlock? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.RawBlock.operator ==(TriasDev.Templify.Builder.RawBlock? left, TriasDev.Templify.Builder.RawBlock? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.StyleSheet.Create(System.Action! styles) -> TriasDev.Templify.Builder.StyleSheet! +[TPLB001]static TriasDev.Templify.Builder.TableStyleKey.operator !=(TriasDev.Templify.Builder.TableStyleKey? left, TriasDev.Templify.Builder.TableStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TableStyleKey.operator ==(TriasDev.Templify.Builder.TableStyleKey? left, TriasDev.Templify.Builder.TableStyleKey? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateBuilder.Build(TriasDev.Templify.Builder.ITemplateDefinition! definition, TriasDev.Templify.Builder.TemplateBuildOptions! options) -> TriasDev.Templify.Builder.GeneratedTemplate! +[TPLB001]static TriasDev.Templify.Builder.TemplateBuildOptions.operator !=(TriasDev.Templify.Builder.TemplateBuildOptions? left, TriasDev.Templify.Builder.TemplateBuildOptions? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateBuildOptions.operator ==(TriasDev.Templify.Builder.TemplateBuildOptions? left, TriasDev.Templify.Builder.TemplateBuildOptions? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateCollection.implicit operator TriasDev.Templify.Builder.Condition!(TriasDev.Templify.Builder.TemplateCollection collection) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplateCollection.implicit operator TriasDev.Templify.Builder.TemplatePath(TriasDev.Templify.Builder.TemplateCollection collection) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]static TriasDev.Templify.Builder.TemplateCollection.operator !=(TriasDev.Templify.Builder.TemplateCollection left, TriasDev.Templify.Builder.TemplateCollection right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateCollection.operator ==(TriasDev.Templify.Builder.TemplateCollection left, TriasDev.Templify.Builder.TemplateCollection right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateIdentity.operator !=(TriasDev.Templify.Builder.TemplateIdentity? left, TriasDev.Templify.Builder.TemplateIdentity? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateIdentity.operator ==(TriasDev.Templify.Builder.TemplateIdentity? left, TriasDev.Templify.Builder.TemplateIdentity? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateInspection.operator !=(TriasDev.Templify.Builder.TemplateInspection? left, TriasDev.Templify.Builder.TemplateInspection? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateInspection.operator ==(TriasDev.Templify.Builder.TemplateInspection? left, TriasDev.Templify.Builder.TemplateInspection? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateInspector.Inspect(System.IO.Stream! template) -> TriasDev.Templify.Builder.TemplateInspection! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.implicit operator TriasDev.Templify.Builder.Condition!(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator !(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator !=(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator &(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator ==(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator |(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.Root(string! path) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.implicit operator TriasDev.Templify.Builder.Condition!(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.implicit operator TriasDev.Templify.Builder.TemplatePath(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator !(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator !=(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator &(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.Condition! right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator ==(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.TemplatePath right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplatePath.operator |(TriasDev.Templify.Builder.TemplatePath left, TriasDev.Templify.Builder.Condition! right) -> TriasDev.Templify.Builder.Condition! +[TPLB001]static TriasDev.Templify.Builder.TemplateStamp.operator !=(TriasDev.Templify.Builder.TemplateStamp? left, TriasDev.Templify.Builder.TemplateStamp? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateStamp.operator ==(TriasDev.Templify.Builder.TemplateStamp? left, TriasDev.Templify.Builder.TemplateStamp? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateStampRemover.Remove(System.IO.Stream! document) -> bool +[TPLB001]static TriasDev.Templify.Builder.TextCatalog.Combine(params TriasDev.Templify.Builder.ITextCatalog![]! catalogs) -> TriasDev.Templify.Builder.ITextCatalog! +[TPLB001]static TriasDev.Templify.Builder.TextCatalog.Empty.get -> TriasDev.Templify.Builder.ITextCatalog! +[TPLB001]static TriasDev.Templify.Builder.TextCatalog.FromDictionary(System.Collections.Generic.IReadOnlyDictionary!>! texts) -> TriasDev.Templify.Builder.ITextCatalog! +[TPLB001]static TriasDev.Templify.Builder.TextCatalog.FromResourceManager(System.Resources.ResourceManager! resources, System.Globalization.CultureInfo? neutralLanguage = null) -> TriasDev.Templify.Builder.ITextCatalog! +[TPLB001]static TriasDev.Templify.Builder.Units.Mm(this double millimeters) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Units.Mm(this int millimeters) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Units.Pt(this double points) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.Units.Pt(this int points) -> TriasDev.Templify.Builder.Length +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Active.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Checkbox.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Checkmark.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Currency.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Custom(string! specifier) -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Date(string! pattern) -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Enabled.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Join(string? itemPath = null, string? separator = null) -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Lowercase.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Number(string! pattern) -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.OnOff.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Raw.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.TrueFalse.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.Uppercase.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]static TriasDev.Templify.Builder.ValueFormat.YesNo.get -> TriasDev.Templify.Builder.ValueFormat! +[TPLB001]TriasDev.Templify.Builder.BlockComposer +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Box(TriasDev.Templify.Builder.BoxStyleKey! style, System.Action! content) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Component(TriasDev.Templify.Builder.ITemplateComponent! component) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.ForEach(TriasDev.Templify.Builder.TemplatePath collection, string! itemName, System.Action! body) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.ForEach(TriasDev.Templify.Builder.TemplateCollection collection, string! itemName, System.Action!, TriasDev.Templify.Builder.BlockComposer!>! body) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.If(TriasDev.Templify.Builder.Condition! condition, System.Action! then) -> TriasDev.Templify.Builder.IfChain! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Image(TriasDev.Templify.Builder.ImageSource! image, string! altText, TriasDev.Templify.Builder.ImageFit! fit) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Image(TriasDev.Templify.Builder.ImageSource! image, string! altText) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Image(TriasDev.Templify.Builder.ParagraphStyleKey! style, TriasDev.Templify.Builder.ImageSource! image, string! altText, TriasDev.Templify.Builder.ImageFit! fit) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.List(TriasDev.Templify.Builder.ListStyleKey! style, System.Action! items) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.PageBreak() -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(string! text) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(System.Action! content) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey! style, string! text) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey! style, System.Action! content) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey! style, TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Raw(TriasDev.Templify.Builder.RawBlock! raw) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Rule(TriasDev.Templify.Builder.Length thickness, TriasDev.Templify.Builder.Color color, TriasDev.Templify.Builder.Length spaceAbove, TriasDev.Templify.Builder.Length spaceBelow) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Rule(TriasDev.Templify.Builder.Length thickness, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Switch(TriasDev.Templify.Builder.TemplatePath value, System.Action! cases) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Table(System.Action! table) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.TableOfContents() -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.TableOfContents(int maxLevel) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.Background(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.Border(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.Padding(TriasDev.Templify.Builder.Length all) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.Padding(TriasDev.Templify.Builder.Length vertical, TriasDev.Templify.Builder.Length horizontal) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.SpaceAfter(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleKey +[TPLB001]TriasDev.Templify.Builder.BoxStyleKey.$() -> TriasDev.Templify.Builder.BoxStyleKey! +[TPLB001]TriasDev.Templify.Builder.BoxStyleKey.BoxStyleKey(string! id) -> void +[TPLB001]TriasDev.Templify.Builder.BoxStyleKey.Equals(TriasDev.Templify.Builder.BoxStyleKey? other) -> bool +[TPLB001]TriasDev.Templify.Builder.BoxStyleKey.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.$() -> TriasDev.Templify.Builder.BuildDiagnostic! +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.BuildDiagnostic(string! Code, string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Code.get -> string! +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Code.init -> void +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Deconstruct(out string! Code, out string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Equals(TriasDev.Templify.Builder.BuildDiagnostic? other) -> bool +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Location.get -> string? +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Location.init -> void +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Message.get -> string! +[TPLB001]TriasDev.Templify.Builder.BuildDiagnostic.Message.init -> void +[TPLB001]TriasDev.Templify.Builder.BuilderStyles +[TPLB001]TriasDev.Templify.Builder.CellComposer +[TPLB001]TriasDev.Templify.Builder.CellComposer.Background(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.CellComposer! +[TPLB001]TriasDev.Templify.Builder.CellComposer.ColumnSpan(int columns) -> TriasDev.Templify.Builder.CellComposer! +[TPLB001]TriasDev.Templify.Builder.CellComposer.VerticalAlignment(TriasDev.Templify.Builder.CellVerticalAlignment alignment) -> TriasDev.Templify.Builder.CellComposer! +[TPLB001]TriasDev.Templify.Builder.CellVerticalAlignment +[TPLB001]TriasDev.Templify.Builder.CellVerticalAlignment.Bottom = 2 -> TriasDev.Templify.Builder.CellVerticalAlignment +[TPLB001]TriasDev.Templify.Builder.CellVerticalAlignment.Center = 1 -> TriasDev.Templify.Builder.CellVerticalAlignment +[TPLB001]TriasDev.Templify.Builder.CellVerticalAlignment.Top = 0 -> TriasDev.Templify.Builder.CellVerticalAlignment +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.BasedOn(TriasDev.Templify.Builder.CharacterStyleKey! parent) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.Bold(bool value = true) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.Color(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.Font(TriasDev.Templify.Builder.FontFace! font) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.Italic(bool value = true) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleComposer.Size(TriasDev.Templify.Builder.Length size) -> TriasDev.Templify.Builder.CharacterStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey.$() -> TriasDev.Templify.Builder.CharacterStyleKey! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey.CharacterStyleKey(string! id, string! displayName) -> void +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey.DisplayName.get -> string! +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey.Equals(TriasDev.Templify.Builder.CharacterStyleKey? other) -> bool +[TPLB001]TriasDev.Templify.Builder.CharacterStyleKey.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.Color +[TPLB001]TriasDev.Templify.Builder.Color.B.get -> byte +[TPLB001]TriasDev.Templify.Builder.Color.Color() -> void +[TPLB001]TriasDev.Templify.Builder.Color.Equals(TriasDev.Templify.Builder.Color other) -> bool +[TPLB001]TriasDev.Templify.Builder.Color.G.get -> byte +[TPLB001]TriasDev.Templify.Builder.Color.R.get -> byte +[TPLB001]TriasDev.Templify.Builder.ColumnsComposer +[TPLB001]TriasDev.Templify.Builder.ColumnsComposer.Fixed(TriasDev.Templify.Builder.Length width) -> TriasDev.Templify.Builder.ColumnsComposer! +[TPLB001]TriasDev.Templify.Builder.ColumnsComposer.Relative(double weight) -> TriasDev.Templify.Builder.ColumnsComposer! +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog.ComponentCatalog() -> void +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog.DataNaming.get -> System.Text.Json.JsonNamingPolicy? +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog.DataNaming.init -> void +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog.Names.get -> System.Collections.Generic.IReadOnlyCollection! +[TPLB001]TriasDev.Templify.Builder.ComponentCatalog.Register(string! name) -> TriasDev.Templify.Builder.ComponentCatalog! +[TPLB001]TriasDev.Templify.Builder.Condition +[TPLB001]TriasDev.Templify.Builder.ContractEntry +[TPLB001]TriasDev.Templify.Builder.ContractEntry.$() -> TriasDev.Templify.Builder.ContractEntry! +[TPLB001]TriasDev.Templify.Builder.ContractEntry.ContractEntry(string! Path, TriasDev.Templify.Builder.ContractUsage Usage) -> void +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Deconstruct(out string! Path, out TriasDev.Templify.Builder.ContractUsage Usage) -> void +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Equals(TriasDev.Templify.Builder.ContractEntry? other) -> bool +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Path.get -> string! +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Path.init -> void +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Usage.get -> TriasDev.Templify.Builder.ContractUsage +[TPLB001]TriasDev.Templify.Builder.ContractEntry.Usage.init -> void +[TPLB001]TriasDev.Templify.Builder.ContractUsage +[TPLB001]TriasDev.Templify.Builder.ContractUsage.Collection = 1 -> TriasDev.Templify.Builder.ContractUsage +[TPLB001]TriasDev.Templify.Builder.ContractUsage.Condition = 2 -> TriasDev.Templify.Builder.ContractUsage +[TPLB001]TriasDev.Templify.Builder.ContractUsage.Value = 0 -> TriasDev.Templify.Builder.ContractUsage +[TPLB001]TriasDev.Templify.Builder.DataCatalog +[TPLB001]TriasDev.Templify.Builder.DataCatalog.Contains(string! path) -> bool +[TPLB001]TriasDev.Templify.Builder.DataCatalog.Entries.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.$() -> TriasDev.Templify.Builder.DataCatalogEntry! +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.ClrType.get -> System.Type! +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.ClrType.init -> void +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.DataCatalogEntry(string! Path, TriasDev.Templify.Builder.DataKind Kind, System.Type! ClrType) -> void +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Deconstruct(out string! Path, out TriasDev.Templify.Builder.DataKind Kind, out System.Type! ClrType) -> void +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Equals(TriasDev.Templify.Builder.DataCatalogEntry? other) -> bool +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Kind.get -> TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Kind.init -> void +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Path.get -> string! +[TPLB001]TriasDev.Templify.Builder.DataCatalogEntry.Path.init -> void +[TPLB001]TriasDev.Templify.Builder.DataContract +[TPLB001]TriasDev.Templify.Builder.DataContract.CreateWitness() -> System.Collections.Generic.IReadOnlyDictionary! +[TPLB001]TriasDev.Templify.Builder.DataContract.Entries.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.DataContract.Hash.get -> string! +[TPLB001]TriasDev.Templify.Builder.DataContract.ToJson() -> string! +[TPLB001]TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DataKind.Collection = 2 -> TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DataKind.Object = 1 -> TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DataKind.Open = 3 -> TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DataKind.Value = 0 -> TriasDev.Templify.Builder.DataKind +[TPLB001]TriasDev.Templify.Builder.DefaultStyleComposer +[TPLB001]TriasDev.Templify.Builder.DefaultStyleComposer.Color(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.DefaultStyleComposer! +[TPLB001]TriasDev.Templify.Builder.DefaultStyleComposer.Font(TriasDev.Templify.Builder.FontFace! font) -> TriasDev.Templify.Builder.DefaultStyleComposer! +[TPLB001]TriasDev.Templify.Builder.DefaultStyleComposer.Size(TriasDev.Templify.Builder.Length size) -> TriasDev.Templify.Builder.DefaultStyleComposer! +[TPLB001]TriasDev.Templify.Builder.DocumentPropertiesComposer +[TPLB001]TriasDev.Templify.Builder.DocumentPropertiesComposer.Author(string! author) -> TriasDev.Templify.Builder.DocumentPropertiesComposer! +[TPLB001]TriasDev.Templify.Builder.DocumentPropertiesComposer.Subject(string! subject) -> TriasDev.Templify.Builder.DocumentPropertiesComposer! +[TPLB001]TriasDev.Templify.Builder.DocumentPropertiesComposer.Title(string! title) -> TriasDev.Templify.Builder.DocumentPropertiesComposer! +[TPLB001]TriasDev.Templify.Builder.FirstPageComposer +[TPLB001]TriasDev.Templify.Builder.FirstPageComposer.Footer(System.Action! footer) -> TriasDev.Templify.Builder.FirstPageComposer! +[TPLB001]TriasDev.Templify.Builder.FirstPageComposer.Header(System.Action! header) -> TriasDev.Templify.Builder.FirstPageComposer! +[TPLB001]TriasDev.Templify.Builder.FirstPageComposer.NoFooter() -> TriasDev.Templify.Builder.FirstPageComposer! +[TPLB001]TriasDev.Templify.Builder.FirstPageComposer.NoHeader() -> TriasDev.Templify.Builder.FirstPageComposer! +[TPLB001]TriasDev.Templify.Builder.FontFace +[TPLB001]TriasDev.Templify.Builder.FontFace.$() -> TriasDev.Templify.Builder.FontFace! +[TPLB001]TriasDev.Templify.Builder.FontFace.Equals(TriasDev.Templify.Builder.FontFace? other) -> bool +[TPLB001]TriasDev.Templify.Builder.FontFace.Family.get -> string! +[TPLB001]TriasDev.Templify.Builder.FontFace.FontFace(string! family) -> void +[TPLB001]TriasDev.Templify.Builder.FontFace.IsEmbedded.get -> bool +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.Content.get -> System.ReadOnlyMemory +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.ContentHash.get -> string! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.Contract.get -> TriasDev.Templify.Builder.DataContract! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.FileExtension.get -> string! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.Format.get -> TriasDev.Templify.Core.TemplateFormat +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.MediaType.get -> string! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.OpenRead() -> System.IO.Stream! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.Stamp.get -> TriasDev.Templify.Builder.TemplateStamp! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.Warnings.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.GeneratedTemplate.WriteTo(System.IO.Stream! destination) -> void +[TPLB001]TriasDev.Templify.Builder.IfChain +[TPLB001]TriasDev.Templify.Builder.IfChain.Else(System.Action! otherwise) -> void +[TPLB001]TriasDev.Templify.Builder.IfChain.ElseIf(TriasDev.Templify.Builder.Condition! condition, System.Action! then) -> TriasDev.Templify.Builder.IfChain! +[TPLB001]TriasDev.Templify.Builder.ImageFit +[TPLB001]TriasDev.Templify.Builder.ImageSource +[TPLB001]TriasDev.Templify.Builder.ImageSource.NaturalHeight.get -> TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.ImageSource.NaturalWidth.get -> TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.ImageSource.PixelHeight.get -> int +[TPLB001]TriasDev.Templify.Builder.ImageSource.PixelWidth.get -> int +[TPLB001]TriasDev.Templify.Builder.InlineComposer +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Expression(TriasDev.Templify.Builder.Condition! condition, TriasDev.Templify.Builder.ValueFormat! format) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.If(TriasDev.Templify.Builder.Condition! condition, System.Action! then) -> TriasDev.Templify.Builder.InlineIfChain! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Image(TriasDev.Templify.Builder.ImageSource! image, string! altText, TriasDev.Templify.Builder.ImageFit! fit) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Image(TriasDev.Templify.Builder.ImageSource! image, string! altText) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.LineBreak() -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.PageCount() -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.PageCount(TriasDev.Templify.Builder.CharacterStyleKey! style) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.PageNumber() -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.PageNumber(TriasDev.Templify.Builder.CharacterStyleKey! style) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Tab() -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.TabRight() -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Text(TriasDev.Templify.Builder.CharacterStyleKey! style, string! text) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Text(string! text) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Value(TriasDev.Templify.Builder.CharacterStyleKey! style, TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Value(TriasDev.Templify.Builder.CharacterStyleKey! style, TriasDev.Templify.Builder.TemplatePath path, TriasDev.Templify.Builder.ValueFormat! format) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Value(TriasDev.Templify.Builder.TemplatePath path, TriasDev.Templify.Builder.ValueFormat! format) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineComposer.Value(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.InlineComposer! +[TPLB001]TriasDev.Templify.Builder.InlineIfChain +[TPLB001]TriasDev.Templify.Builder.InlineIfChain.Else(System.Action! otherwise) -> void +[TPLB001]TriasDev.Templify.Builder.InlineIfChain.ElseIf(TriasDev.Templify.Builder.Condition! condition, System.Action! then) -> TriasDev.Templify.Builder.InlineIfChain! +[TPLB001]TriasDev.Templify.Builder.ITemplateComponent +[TPLB001]TriasDev.Templify.Builder.ITemplateComponent.Compose(TriasDev.Templify.Builder.BlockComposer! content) -> void +[TPLB001]TriasDev.Templify.Builder.ITemplateDefinition +[TPLB001]TriasDev.Templify.Builder.ITemplateDefinition.Compose(TriasDev.Templify.Builder.TemplateComposer! template) -> void +[TPLB001]TriasDev.Templify.Builder.ITemplateDefinition.Identity.get -> TriasDev.Templify.Builder.TemplateIdentity! +[TPLB001]TriasDev.Templify.Builder.ITextCatalog +[TPLB001]TriasDev.Templify.Builder.ITextCatalog.TryGet(string! key, System.Globalization.CultureInfo! language, out string! text) -> bool +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJson +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDocument +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDocument.Assets.get -> System.Collections.Generic.IReadOnlyDictionary! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDocument.Json.get -> string! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.AllowRawXml.get -> bool +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.AllowRawXml.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Assets.get -> System.Collections.Generic.IReadOnlyDictionary? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Assets.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Components.get -> TriasDev.Templify.Builder.ComponentCatalog? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Components.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Data.get -> TriasDev.Templify.Builder.DataCatalog? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Data.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.TemplateJsonImportOptions() -> void +[TPLB001]TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.Length.CompareTo(TriasDev.Templify.Builder.Length other) -> int +[TPLB001]TriasDev.Templify.Builder.Length.Equals(TriasDev.Templify.Builder.Length other) -> bool +[TPLB001]TriasDev.Templify.Builder.Length.Length() -> void +[TPLB001]TriasDev.Templify.Builder.Length.Millimeters.get -> double +[TPLB001]TriasDev.Templify.Builder.Length.Points.get -> double +[TPLB001]TriasDev.Templify.Builder.ListComposer +[TPLB001]TriasDev.Templify.Builder.ListComposer.ForEach(TriasDev.Templify.Builder.TemplatePath collection, string! itemName, System.Action! items) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.ForEach(TriasDev.Templify.Builder.TemplateCollection collection, string! itemName, System.Action!, TriasDev.Templify.Builder.ListComposer!>! items) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.If(TriasDev.Templify.Builder.Condition! condition, System.Action! items) -> TriasDev.Templify.Builder.ListIfChain! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(int level, string! text) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(int level, System.Action! content) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(int level, TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(string! text) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(System.Action! content) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListComposer.Item(TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.ListComposer! +[TPLB001]TriasDev.Templify.Builder.ListIfChain +[TPLB001]TriasDev.Templify.Builder.ListIfChain.Else(System.Action! items) -> void +[TPLB001]TriasDev.Templify.Builder.ListIfChain.ElseIf(TriasDev.Templify.Builder.Condition! condition, System.Action! items) -> TriasDev.Templify.Builder.ListIfChain! +[TPLB001]TriasDev.Templify.Builder.ListStyleComposer +[TPLB001]TriasDev.Templify.Builder.ListStyleComposer.ItemStyle(TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.ListStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ListStyleComposer.Level(int level, string! bullet, TriasDev.Templify.Builder.Length indent, TriasDev.Templify.Builder.Length hanging) -> TriasDev.Templify.Builder.ListStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ListStyleKey +[TPLB001]TriasDev.Templify.Builder.ListStyleKey.$() -> TriasDev.Templify.Builder.ListStyleKey! +[TPLB001]TriasDev.Templify.Builder.ListStyleKey.Equals(TriasDev.Templify.Builder.ListStyleKey? other) -> bool +[TPLB001]TriasDev.Templify.Builder.ListStyleKey.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.ListStyleKey.ListStyleKey(string! id) -> void +[TPLB001]TriasDev.Templify.Builder.LoopItem +[TPLB001]TriasDev.Templify.Builder.LoopItem.Self.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopItem.this[string! relative].get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopItem +[TPLB001]TriasDev.Templify.Builder.LoopItem.Item.get -> TriasDev.Templify.Builder.LoopItem! +[TPLB001]TriasDev.Templify.Builder.LoopItem.Items(System.Linq.Expressions.Expression!>!>! member) -> TriasDev.Templify.Builder.TemplateCollection +[TPLB001]TriasDev.Templify.Builder.LoopItem.Path(System.Linq.Expressions.Expression!>! member) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopItem.Self.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.PageComposer +[TPLB001]TriasDev.Templify.Builder.PageComposer.FirstPage(System.Action! firstPage) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.Footer(System.Action! footer) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.Header(System.Action! header) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.HeaderFooterDistance(TriasDev.Templify.Builder.Length header, TriasDev.Templify.Builder.Length footer) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.Margins(TriasDev.Templify.Builder.Length all) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.Margins(TriasDev.Templify.Builder.Length top, TriasDev.Templify.Builder.Length right, TriasDev.Templify.Builder.Length bottom, TriasDev.Templify.Builder.Length left) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageComposer.Size(TriasDev.Templify.Builder.PageSize! size) -> TriasDev.Templify.Builder.PageComposer! +[TPLB001]TriasDev.Templify.Builder.PageSize +[TPLB001]TriasDev.Templify.Builder.PageSize.$() -> TriasDev.Templify.Builder.PageSize! +[TPLB001]TriasDev.Templify.Builder.PageSize.Equals(TriasDev.Templify.Builder.PageSize? other) -> bool +[TPLB001]TriasDev.Templify.Builder.PageSize.Height.get -> TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.PageSize.PageSize(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Length height) -> void +[TPLB001]TriasDev.Templify.Builder.PageSize.Width.get -> TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Alignment(TriasDev.Templify.Builder.TextAlignment alignment) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.BasedOn(TriasDev.Templify.Builder.ParagraphStyleKey! parent) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Bold(bool value = true) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Color(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.FirstLineIndent(TriasDev.Templify.Builder.Length indent) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Font(TriasDev.Templify.Builder.FontFace! font) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.IndentEnd(TriasDev.Templify.Builder.Length indent) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.IndentStart(TriasDev.Templify.Builder.Length indent) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Italic(bool value = true) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.KeepLinesTogether(bool value = true) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.KeepWithNext(bool value = true) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.LineHeight(TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.LineSpacing(double multiple) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.MinimumLineHeight(TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Next(TriasDev.Templify.Builder.ParagraphStyleKey! next) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.OutlineLevel(int level) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.Size(TriasDev.Templify.Builder.Length size) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.SpaceAfter(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.SpaceBefore(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey.$() -> TriasDev.Templify.Builder.ParagraphStyleKey! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey.DisplayName.get -> string! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey.Equals(TriasDev.Templify.Builder.ParagraphStyleKey? other) -> bool +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleKey.ParagraphStyleKey(string! id, string! displayName) -> void +[TPLB001]TriasDev.Templify.Builder.RawBlock +[TPLB001]TriasDev.Templify.Builder.RawBlock.$() -> TriasDev.Templify.Builder.RawBlock! +[TPLB001]TriasDev.Templify.Builder.RawBlock.Docx.get -> System.Func! +[TPLB001]TriasDev.Templify.Builder.RawBlock.Docx.init -> void +[TPLB001]TriasDev.Templify.Builder.RawBlock.Equals(TriasDev.Templify.Builder.RawBlock? other) -> bool +[TPLB001]TriasDev.Templify.Builder.RawBlock.Odt.get -> System.Func! +[TPLB001]TriasDev.Templify.Builder.RawBlock.Odt.init -> void +[TPLB001]TriasDev.Templify.Builder.RawBlock.RawBlock() -> void +[TPLB001]TriasDev.Templify.Builder.RawBlock.Uses.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.RawBlock.Uses.init -> void +[TPLB001]TriasDev.Templify.Builder.RawContext +[TPLB001]TriasDev.Templify.Builder.RawContext.Frame.get -> TriasDev.Templify.Builder.Length +[TPLB001]TriasDev.Templify.Builder.RawContext.Placeholder(TriasDev.Templify.Builder.TemplatePath path, TriasDev.Templify.Builder.ValueFormat? format = null) -> string! +[TPLB001]TriasDev.Templify.Builder.RowComposer +[TPLB001]TriasDev.Templify.Builder.RowComposer.AllowSplit() -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.Cell(string! text) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.Cell(System.Action! cell) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.Cell(TriasDev.Templify.Builder.ParagraphStyleKey! style, string! text) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.Cell(TriasDev.Templify.Builder.ParagraphStyleKey! style, TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.Cell(TriasDev.Templify.Builder.TemplatePath value) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.RowsComposer +[TPLB001]TriasDev.Templify.Builder.RowsComposer.ForEachRow(TriasDev.Templify.Builder.TemplatePath collection, string! itemName, System.Action! rows) -> TriasDev.Templify.Builder.RowsComposer! +[TPLB001]TriasDev.Templify.Builder.RowsComposer.ForEachRow(TriasDev.Templify.Builder.TemplateCollection collection, string! itemName, System.Action!, TriasDev.Templify.Builder.RowsComposer!>! rows) -> TriasDev.Templify.Builder.RowsComposer! +[TPLB001]TriasDev.Templify.Builder.RowsComposer.Row(System.Action! row) -> TriasDev.Templify.Builder.RowsComposer! +[TPLB001]TriasDev.Templify.Builder.RowsComposer.RowsIf(TriasDev.Templify.Builder.Condition! condition, System.Action! rows) -> TriasDev.Templify.Builder.RowsIfChain! +[TPLB001]TriasDev.Templify.Builder.RowsIfChain +[TPLB001]TriasDev.Templify.Builder.RowsIfChain.Else(System.Action! rows) -> void +[TPLB001]TriasDev.Templify.Builder.RowsIfChain.ElseIf(TriasDev.Templify.Builder.Condition! condition, System.Action! rows) -> TriasDev.Templify.Builder.RowsIfChain! +[TPLB001]TriasDev.Templify.Builder.StyleSheet +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.Box(TriasDev.Templify.Builder.BoxStyleKey! key, System.Action! style) -> void +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.Character(TriasDev.Templify.Builder.CharacterStyleKey! key, System.Action! style) -> void +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.Defaults(System.Action! defaults) -> void +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.List(TriasDev.Templify.Builder.ListStyleKey! key, System.Action! style) -> void +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey! key, System.Action! style) -> void +[TPLB001]TriasDev.Templify.Builder.StyleSheetComposer.Table(TriasDev.Templify.Builder.TableStyleKey! key, System.Action! style) -> void +[TPLB001]TriasDev.Templify.Builder.SwitchComposer +[TPLB001]TriasDev.Templify.Builder.SwitchComposer.Case(string! value, System.Action! then) -> TriasDev.Templify.Builder.SwitchComposer! +[TPLB001]TriasDev.Templify.Builder.SwitchComposer.Case(System.Collections.Generic.IEnumerable! values, System.Action! then) -> TriasDev.Templify.Builder.SwitchComposer! +[TPLB001]TriasDev.Templify.Builder.SwitchComposer.Default(System.Action! otherwise) -> TriasDev.Templify.Builder.SwitchComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer +[TPLB001]TriasDev.Templify.Builder.TableComposer.Columns(System.Action! columns) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.ForEachRow(TriasDev.Templify.Builder.TemplatePath collection, string! itemName, System.Action! rows) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.ForEachRow(TriasDev.Templify.Builder.TemplateCollection collection, string! itemName, System.Action!, TriasDev.Templify.Builder.RowsComposer!>! rows) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.HeaderRow(System.Action! row) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.Row(System.Action! row) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.RowsIf(TriasDev.Templify.Builder.Condition! condition, System.Action! rows) -> TriasDev.Templify.Builder.RowsIfChain! +[TPLB001]TriasDev.Templify.Builder.TableComposer.SpaceAfter(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.Style(TriasDev.Templify.Builder.TableStyleKey! style) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.CellPadding(TriasDev.Templify.Builder.Length vertical, TriasDev.Templify.Builder.Length horizontal) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.ColumnRule(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.HeaderBackground(TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.HeaderRule(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.OuterBorder(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.RowRule(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleKey +[TPLB001]TriasDev.Templify.Builder.TableStyleKey.$() -> TriasDev.Templify.Builder.TableStyleKey! +[TPLB001]TriasDev.Templify.Builder.TableStyleKey.Equals(TriasDev.Templify.Builder.TableStyleKey? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TableStyleKey.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.TableStyleKey.TableStyleKey(string! id) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateBuilder +[TPLB001]TriasDev.Templify.Builder.TemplateBuildException +[TPLB001]TriasDev.Templify.Builder.TemplateBuildException.Errors.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.TemplateBuildException.TemplateBuildException(System.Collections.Generic.IReadOnlyList! errors) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.$() -> TriasDev.Templify.Builder.TemplateBuildOptions! +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Equals(TriasDev.Templify.Builder.TemplateBuildOptions? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Format.get -> TriasDev.Templify.Core.TemplateFormat +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Format.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Language.get -> System.Globalization.CultureInfo! +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Language.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.TemplateBuildOptions() -> void +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Texts.get -> TriasDev.Templify.Builder.ITextCatalog! +[TPLB001]TriasDev.Templify.Builder.TemplateBuildOptions.Texts.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCollection +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.Equals(TriasDev.Templify.Builder.TemplateCollection other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.Exists.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.IsEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.IsNotEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.TemplateCollection() -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCollection.Untyped.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplateComposer +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Content(System.Action! content) -> TriasDev.Templify.Builder.TemplateComposer! +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Data.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.DataAs(System.Text.Json.JsonNamingPolicy? naming = null) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Page(System.Action! page) -> TriasDev.Templify.Builder.TemplateComposer! +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Properties(System.Action! properties) -> TriasDev.Templify.Builder.TemplateComposer! +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Styles(TriasDev.Templify.Builder.StyleSheet! styles) -> TriasDev.Templify.Builder.TemplateComposer! +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Texts.get -> TriasDev.Templify.Builder.TemplateTexts! +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.$() -> TriasDev.Templify.Builder.TemplateIdentity! +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Deconstruct(out string! Id, out int Version) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Equals(TriasDev.Templify.Builder.TemplateIdentity? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Id.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Id.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.TemplateIdentity(string! Id, int Version) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Version.get -> int +[TPLB001]TriasDev.Templify.Builder.TemplateIdentity.Version.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateInspection +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.$() -> TriasDev.Templify.Builder.TemplateInspection! +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Deconstruct(out TriasDev.Templify.Core.TemplateFormat Format, out TriasDev.Templify.Builder.TemplateStamp? Stamp) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Equals(TriasDev.Templify.Builder.TemplateInspection? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Format.get -> TriasDev.Templify.Core.TemplateFormat +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Format.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Stamp.get -> TriasDev.Templify.Builder.TemplateStamp? +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.Stamp.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateInspection.TemplateInspection(TriasDev.Templify.Core.TemplateFormat Format, TriasDev.Templify.Builder.TemplateStamp? Stamp) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateInspector +[TPLB001]TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Contains(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.EndsWith(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Equals(TriasDev.Templify.Builder.TemplatePath other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Exists.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Ge(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Gt(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.In(params string![]! values) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.IsEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.IsNotEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Le(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Lt(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.StartsWith(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.TemplatePath() -> void +[TPLB001]TriasDev.Templify.Builder.TemplatePath.this[string! relative].get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Contains(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.EndsWith(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Equals(TriasDev.Templify.Builder.TemplatePath other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Exists.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Ge(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Gt(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.In(params string![]! values) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.IsEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.IsNotEmpty.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Items(System.Linq.Expressions.Expression!>!>! member) -> TriasDev.Templify.Builder.TemplateCollection +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Le(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Lt(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(double value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Path(System.Linq.Expressions.Expression!>! member) -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplatePath.StartsWith(string! value) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.TemplatePath() -> void +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Untyped.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.TemplateStamp +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.$() -> TriasDev.Templify.Builder.TemplateStamp! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.BuilderVersion.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.BuilderVersion.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.ContractHash.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.ContractHash.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Deconstruct(out string! TemplateId, out int Version, out string! ContractHash, out string! Language, out string! BuilderVersion, out string! MinimumEngineVersion) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Equals(TriasDev.Templify.Builder.TemplateStamp? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Language.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Language.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.MinimumEngineVersion.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.MinimumEngineVersion.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.TemplateId.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.TemplateId.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.TemplateStamp(string! TemplateId, int Version, string! ContractHash, string! Language, string! BuilderVersion, string! MinimumEngineVersion) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Version.get -> int +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Version.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateStampRemover +[TPLB001]TriasDev.Templify.Builder.TemplateTexts +[TPLB001]TriasDev.Templify.Builder.TemplateTexts.Language.get -> System.Globalization.CultureInfo! +[TPLB001]TriasDev.Templify.Builder.TemplateTexts.this[string! key].get -> string! +[TPLB001]TriasDev.Templify.Builder.TextAlignment +[TPLB001]TriasDev.Templify.Builder.TextAlignment.Center = 1 -> TriasDev.Templify.Builder.TextAlignment +[TPLB001]TriasDev.Templify.Builder.TextAlignment.End = 2 -> TriasDev.Templify.Builder.TextAlignment +[TPLB001]TriasDev.Templify.Builder.TextAlignment.Justify = 3 -> TriasDev.Templify.Builder.TextAlignment +[TPLB001]TriasDev.Templify.Builder.TextAlignment.Start = 0 -> TriasDev.Templify.Builder.TextAlignment +[TPLB001]TriasDev.Templify.Builder.TextCatalog +[TPLB001]TriasDev.Templify.Builder.TextComposer +[TPLB001]TriasDev.Templify.Builder.TextComposer.If(TriasDev.Templify.Builder.Condition! condition, System.Action! then) -> TriasDev.Templify.Builder.InlineIfChain! +[TPLB001]TriasDev.Templify.Builder.TextComposer.Text(TriasDev.Templify.Builder.CharacterStyleKey! style, string! text) -> TriasDev.Templify.Builder.TextComposer! +[TPLB001]TriasDev.Templify.Builder.TextComposer.Text(string! text) -> TriasDev.Templify.Builder.TextComposer! +[TPLB001]TriasDev.Templify.Builder.TextComposer.Value(TriasDev.Templify.Builder.CharacterStyleKey! style, TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.TextComposer! +[TPLB001]TriasDev.Templify.Builder.TextComposer.Value(TriasDev.Templify.Builder.TemplatePath path, TriasDev.Templify.Builder.ValueFormat! format) -> TriasDev.Templify.Builder.TextComposer! +[TPLB001]TriasDev.Templify.Builder.TextComposer.Value(TriasDev.Templify.Builder.TemplatePath path) -> TriasDev.Templify.Builder.TextComposer! +[TPLB001]TriasDev.Templify.Builder.Units +[TPLB001]TriasDev.Templify.Builder.ValueFormat +[TPLB001]TriasDev.Templify.Builder.ValueFormat.Specifier.get -> string! +[TPLB001]TriasDev.Templify.Builder.DefaultStyleComposer.ParagraphStyle(TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.DefaultStyleComposer! +[TPLB001]TriasDev.Templify.Builder.RowComposer.ParagraphStyle(TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.RowComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.HeaderParagraphStyle(TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.ParagraphStyle(TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Export(TriasDev.Templify.Builder.ITemplateDefinition! definition, TriasDev.Templify.Builder.TemplateBuildOptions! options, TriasDev.Templify.Builder.Json.TemplateJsonExportOptions! export) -> TriasDev.Templify.Builder.Json.TemplateJsonDocument! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.Components.get -> TriasDev.Templify.Builder.ComponentCatalog? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.Components.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.Indented.get -> bool +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.Indented.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.TemplateJsonExportOptions() -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.TextLanguages.get -> System.Collections.Generic.IReadOnlyList? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonExportOptions.TextLanguages.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateDataAttribute +[TPLB001]TriasDev.Templify.Builder.TemplateDataAttribute.TemplateDataAttribute(System.Type! type) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateDataAttribute.Type.get -> System.Type! +[TPLB001]TriasDev.Templify.Builder.GeneratedDataPathsAttribute +[TPLB001]TriasDev.Templify.Builder.GeneratedDataPathsAttribute.GeneratedDataPathsAttribute(System.Type! type, bool loopItem) -> void +[TPLB001]TriasDev.Templify.Builder.GeneratedDataPathsAttribute.LoopItem.get -> bool +[TPLB001]TriasDev.Templify.Builder.GeneratedDataPathsAttribute.Type.get -> System.Type! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.ValueFormats.get -> System.Collections.Generic.IReadOnlyCollection? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.ValueFormats.init -> void +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Section(string! name, System.Action! content) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.ImageSource.Name.get -> string? +[TPLB001]TriasDev.Templify.Builder.ImageSource.WithName(string! name) -> TriasDev.Templify.Builder.ImageSource! +[TPLB001]static TriasDev.Templify.Builder.Color.Token(string! name, TriasDev.Templify.Builder.Color value) -> TriasDev.Templify.Builder.Color +[TPLB001]static TriasDev.Templify.Builder.FontFace.Token(string! name, TriasDev.Templify.Builder.FontFace! face) -> TriasDev.Templify.Builder.FontFace! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Shared() -> T! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Texts.get -> TriasDev.Templify.Builder.TemplateTexts! +[TPLB001]TriasDev.Templify.Builder.Color.TokenName.get -> string? +[TPLB001]TriasDev.Templify.Builder.FontFace.TokenName.get -> string? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Shared.get -> System.Collections.Generic.IReadOnlyList? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Shared.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Theme.get -> System.Collections.Generic.IReadOnlyDictionary? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.Theme.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateComposer.Share(T! value) -> TriasDev.Templify.Builder.TemplateComposer! +[TPLB001]TriasDev.Templify.Builder.DataCatalog.ToJson() -> string! +[TPLB001]TriasDev.Templify.Builder.ComponentVersionAttribute.ComponentVersionAttribute(int version) -> void +[TPLB001]TriasDev.Templify.Builder.ComponentVersionAttribute.Version.get -> int +[TPLB001]TriasDev.Templify.Builder.ComponentVersionAttribute +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Components.get -> System.Collections.Generic.IReadOnlyDictionary! +[TPLB001]TriasDev.Templify.Builder.TemplateStamp.Components.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.$() -> TriasDev.Templify.Builder.TemplateCheckOptions! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Components.get -> TriasDev.Templify.Builder.ComponentCatalog? +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Components.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Data.get -> TriasDev.Templify.Builder.DataCatalog! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Data.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Equals(TriasDev.Templify.Builder.TemplateCheckOptions? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Expected.get -> TriasDev.Templify.Builder.TemplateIdentity? +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.Expected.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.TemplateCheckOptions() -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.$() -> TriasDev.Templify.Builder.TemplateCheckProblem! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Code.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Code.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.DataPath.get -> string? +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.DataPath.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Deconstruct(out string! Code, out TriasDev.Templify.Builder.TemplateCheckSeverity Severity, out string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Equals(TriasDev.Templify.Builder.TemplateCheckProblem? other) -> bool +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Location.get -> string? +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Location.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Message.get -> string! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Message.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Severity.get -> TriasDev.Templify.Builder.TemplateCheckSeverity +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.Severity.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckProblem.TemplateCheckProblem(string! Code, TriasDev.Templify.Builder.TemplateCheckSeverity Severity, string! Message) -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckResult +[TPLB001]TriasDev.Templify.Builder.TemplateCheckResult.Format.get -> TriasDev.Templify.Core.TemplateFormat +[TPLB001]TriasDev.Templify.Builder.TemplateCheckResult.Problems.get -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.TemplateCheckResult.Stamp.get -> TriasDev.Templify.Builder.TemplateStamp? +[TPLB001]TriasDev.Templify.Builder.TemplateCheckResult.Status.get -> TriasDev.Templify.Builder.TemplateCheckStatus +[TPLB001]TriasDev.Templify.Builder.TemplateCheckSeverity +[TPLB001]TriasDev.Templify.Builder.TemplateCheckSeverity.Error = 1 -> TriasDev.Templify.Builder.TemplateCheckSeverity +[TPLB001]TriasDev.Templify.Builder.TemplateCheckSeverity.Warning = 0 -> TriasDev.Templify.Builder.TemplateCheckSeverity +[TPLB001]TriasDev.Templify.Builder.TemplateCheckStatus +[TPLB001]TriasDev.Templify.Builder.TemplateCheckStatus.Broken = 2 -> TriasDev.Templify.Builder.TemplateCheckStatus +[TPLB001]TriasDev.Templify.Builder.TemplateCheckStatus.Ok = 0 -> TriasDev.Templify.Builder.TemplateCheckStatus +[TPLB001]TriasDev.Templify.Builder.TemplateCheckStatus.Warning = 1 -> TriasDev.Templify.Builder.TemplateCheckStatus +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckOptions.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckOptions.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckOptions.ToString() -> string! +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckProblem.Equals(object? obj) -> bool +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckProblem.GetHashCode() -> int +[TPLB001]override TriasDev.Templify.Builder.TemplateCheckProblem.ToString() -> string! +[TPLB001]static TriasDev.Templify.Builder.TemplateCheckOptions.operator !=(TriasDev.Templify.Builder.TemplateCheckOptions? left, TriasDev.Templify.Builder.TemplateCheckOptions? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateCheckOptions.operator ==(TriasDev.Templify.Builder.TemplateCheckOptions? left, TriasDev.Templify.Builder.TemplateCheckOptions? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateCheckProblem.operator !=(TriasDev.Templify.Builder.TemplateCheckProblem? left, TriasDev.Templify.Builder.TemplateCheckProblem? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateCheckProblem.operator ==(TriasDev.Templify.Builder.TemplateCheckProblem? left, TriasDev.Templify.Builder.TemplateCheckProblem? right) -> bool +[TPLB001]static TriasDev.Templify.Builder.TemplateInspector.Check(System.IO.Stream! template, TriasDev.Templify.Builder.TemplateCheckOptions! options) -> TriasDev.Templify.Builder.TemplateCheckResult! +[TPLB001]static TriasDev.Templify.Builder.TemplateInspector.CheckDefinition(string! json, TriasDev.Templify.Builder.Json.TemplateJsonImportOptions! import, TriasDev.Templify.Builder.TemplateBuildOptions? build = null, TriasDev.Templify.Builder.TemplateIdentity? expected = null) -> TriasDev.Templify.Builder.TemplateCheckResult! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey? style, System.Action! content, System.Action! options) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey? style, TriasDev.Templify.Builder.TemplatePath value, System.Action! options) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Paragraph(TriasDev.Templify.Builder.ParagraphStyleKey? style, string! text, System.Action! options) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphOptions +[TPLB001]TriasDev.Templify.Builder.ParagraphOptions.KeepLinesTogether(bool value = true) -> TriasDev.Templify.Builder.ParagraphOptions! +[TPLB001]TriasDev.Templify.Builder.ParagraphOptions.KeepWithNext(bool value = true) -> TriasDev.Templify.Builder.ParagraphOptions! +[TPLB001]TriasDev.Templify.Builder.ParagraphOptions.SpaceAfter(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.ParagraphOptions! +[TPLB001]TriasDev.Templify.Builder.ParagraphOptions.SpaceBefore(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.ParagraphOptions! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Spacer(TriasDev.Templify.Builder.Length height) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.Rule(TriasDev.Templify.Builder.Length thickness, TriasDev.Templify.Builder.Color color, TriasDev.Templify.Builder.Length spaceAbove, TriasDev.Templify.Builder.Length spaceBelow, TriasDev.Templify.Builder.Length width) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.ParagraphStyleComposer.BorderBottom(TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color, TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.ParagraphStyleComposer! +[TPLB001]TriasDev.Templify.Builder.BoxStyleComposer.Padding(TriasDev.Templify.Builder.Length top, TriasDev.Templify.Builder.Length right, TriasDev.Templify.Builder.Length bottom, TriasDev.Templify.Builder.Length left) -> TriasDev.Templify.Builder.BoxStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CellComposer.Padding(TriasDev.Templify.Builder.Length top, TriasDev.Templify.Builder.Length right, TriasDev.Templify.Builder.Length bottom, TriasDev.Templify.Builder.Length left) -> TriasDev.Templify.Builder.CellComposer! +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.CellPadding(TriasDev.Templify.Builder.Length top, TriasDev.Templify.Builder.Length right, TriasDev.Templify.Builder.Length bottom, TriasDev.Templify.Builder.Length left) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.CellComposer.Border(TriasDev.Templify.Builder.Sides sides, TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.CellComposer! +[TPLB001]TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.All = TriasDev.Templify.Builder.Sides.Top | TriasDev.Templify.Builder.Sides.Right | TriasDev.Templify.Builder.Sides.Bottom | TriasDev.Templify.Builder.Sides.Left -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.Bottom = 4 -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.Left = 8 -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.None = 0 -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.Right = 2 -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.Sides.Top = 1 -> TriasDev.Templify.Builder.Sides +[TPLB001]TriasDev.Templify.Builder.TableStyleComposer.OuterBorder(TriasDev.Templify.Builder.Sides sides, TriasDev.Templify.Builder.Length width, TriasDev.Templify.Builder.Color color) -> TriasDev.Templify.Builder.TableStyleComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.Indent(TriasDev.Templify.Builder.Length indent) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TableComposer.SpaceBefore(TriasDev.Templify.Builder.Length space) -> TriasDev.Templify.Builder.TableComposer! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Contains(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.EndsWith(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Ge(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Gt(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Le(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Lt(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.StartsWith(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Contains(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.EndsWith(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Eq(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Ge(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Gt(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Le(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.Lt(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.NotEq(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.TemplatePath.StartsWith(TriasDev.Templify.Builder.TemplatePath other) -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.BlockComposer.TableOfContents(int maxLevel, System.Action! entries) -> TriasDev.Templify.Builder.BlockComposer! +[TPLB001]TriasDev.Templify.Builder.TableOfContentsComposer +[TPLB001]TriasDev.Templify.Builder.TableOfContentsComposer.Level(int level, TriasDev.Templify.Builder.ParagraphStyleKey! style) -> TriasDev.Templify.Builder.TableOfContentsComposer! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions.Components.get -> TriasDev.Templify.Builder.ComponentCatalog? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions.Components.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions.Data.get -> TriasDev.Templify.Builder.DataCatalog? +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions.Data.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions.TemplateJsonDescribeOptions() -> void +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Describe(TriasDev.Templify.Builder.Json.TemplateJsonDescribeOptions? options = null) -> string! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Schema(TriasDev.Templify.Builder.ComponentCatalog? components = null) -> string! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Read(string! json, string! pointer) -> string! +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePatchResult +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePatchResult.Applied.get -> bool +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePatchResult.Check.get -> TriasDev.Templify.Builder.TemplateCheckResult! +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePatchResult.Json.get -> string! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Patch(string! json, string! patch, TriasDev.Templify.Builder.Json.TemplateJsonImportOptions! import, TriasDev.Templify.Builder.TemplateBuildOptions? build = null) -> TriasDev.Templify.Builder.Json.TemplatePatchResult! +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePreview +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePreview.Check.get -> TriasDev.Templify.Builder.TemplateCheckResult! +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePreview.Document.get -> byte[]? +[TPLB001]TriasDev.Templify.Builder.Json.TemplatePreview.Text.get -> string? +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Preview(string! json, TriasDev.Templify.Builder.Json.TemplateJsonImportOptions! import, TriasDev.Templify.Builder.TemplateBuildOptions! build, string? data = null) -> TriasDev.Templify.Builder.Json.TemplatePreview! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonNode +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonNode.Depth.get -> int +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonNode.Kind.get -> string! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonNode.Label.get -> string! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonNode.Pointer.get -> string! +[TPLB001]override TriasDev.Templify.Builder.Json.TemplateJsonNode.ToString() -> string! +[TPLB001]static TriasDev.Templify.Builder.Json.TemplateJson.Outline(string! json) -> System.Collections.Generic.IReadOnlyList! +[TPLB001]TriasDev.Templify.Builder.LoopInfo +[TPLB001]TriasDev.Templify.Builder.LoopInfo.Count.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopInfo.Index.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopInfo.IsFirst.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.LoopInfo.IsLast.get -> TriasDev.Templify.Builder.Condition! +[TPLB001]TriasDev.Templify.Builder.LoopInfo.Number.get -> TriasDev.Templify.Builder.TemplatePath +[TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo! +[TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo! diff --git a/src/TriasDev.Templify.Builder/README.md b/src/TriasDev.Templify.Builder/README.md new file mode 100644 index 00000000..b2c171c6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/README.md @@ -0,0 +1,93 @@ +# TriasDev.Templify.Builder + +> **Preview (0.x), experimental.** The API may change in any release until the first stable one. Using it reports +> diagnostic `TPLB001`; opt in with `$(NoWarn);TPLB001` in your project. + +Describe Templify templates in C# and generate them at runtime as Word (`.docx`) or OpenDocument Text (`.odt`) +files. [TriasDev.Templify](https://www.nuget.org/packages/TriasDev.Templify) then fills the generated templates with +data. + +- **One definition, every format and language.** Named styles from your theme, texts from a catalog, DOCX and ODT + from the same code. +- **Invalid template syntax cannot be written.** Markers, conditions, loops and value formats come from the API, in + the shapes the engine supports. +- **A data contract and an identity stamp.** Every build lists the data it needs, and an uploaded, hand-edited copy + can be checked against it. + +```csharp +using System.Globalization; +using TriasDev.Templify.Builder; +using TriasDev.Templify.Core; + +public sealed class InvoiceTemplate(BrandTheme theme) : ITemplateDefinition +{ + private static readonly ParagraphStyleKey Title = new("Title1", "Invoice Title"); + private static readonly ParagraphStyleKey Body = new("Body", "Body Copy"); + private static readonly CharacterStyleKey Strong = new("Strong", "Strong Text"); + + public TemplateIdentity Identity { get; } = new("invoice", 1); + + public void Compose(TemplateComposer template) + { + TemplateTexts t = template.Texts; + TemplatePath order = template.Data["order"]; + + template.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.Font(theme.BodyFont).Size(10.5.Pt()).Color(theme.Ink)); + s.Paragraph(Body, p => p.SpaceAfter(6.Pt())); + s.Paragraph(Title, p => p.BasedOn(Body).Size(18.Pt()).Color(theme.Accent).OutlineLevel(1)); + s.Character(Strong, c => c.Bold()); + })); + template.Properties(p => p.Title(t["invoice"])); + + template.Content(c => + { + c.Paragraph(Title, x => { x.Text(t["invoice"] + " "); x.Value(order["number"]); }); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(Body, x => + { + x.Value(line["description"]); + x.Tab(); + x.Value(Strong, line["amount"], ValueFormat.Currency); + })); + c.Switch(order["status"], s => + { + s.Case("paid", b => b.Paragraph(Body, t["paid"])); + s.Default(b => b.Paragraph(Body, t["open"])); + }); + }); + } +} + +GeneratedTemplate template = TemplateBuilder.Build( + new InvoiceTemplate(theme), + new TemplateBuildOptions { Format = TemplateFormat.Odt, Language = CultureInfo.GetCultureInfo("de-DE"), Texts = texts }); + +// Hand it to a user as a download (template.OpenRead(), template.MediaType, "invoice" + template.FileExtension) +// or fill it right away: +using MemoryStream output = new MemoryStream(); +new TemplateProcessor().ProcessTemplate(template.OpenRead(), output, json); + +// Later, check a copy the user edited and uploaded against the current data (Ok, Warning or Broken): +TemplateCheckResult check = TemplateInspector.Check(upload, new TemplateCheckOptions { Data = DataCatalog.From() }); +``` + +The output is deterministic: the same definition and options produce the same bytes on the same runtime and operating +system family, so `GeneratedTemplate.ContentHash` can serve as a cache key. Requires TriasDev.Templify 1.11.0 or later. + +The [documentation page](https://triasdev.github.io/templify/for-developers/template-builder/) explains the +concepts, the support matrix and the known limits. The sample +[`samples/TriasDev.Templify.Builder.Sample`](https://github.com/TriasDev/templify/tree/main/samples/TriasDev.Templify.Builder.Sample) +uses every construct. Verify your definitions in CI with +[TriasDev.Templify.Builder.Testing](https://www.nuget.org/packages/TriasDev.Templify.Builder.Testing): + +```csharp +[Fact] +public void InvoiceTemplate_IsValid() => TemplateVerifier.VerifyAll( + () => new InvoiceTemplate(theme), + new TemplateVerificationOptions { Languages = [de, en], Texts = _ => texts, SampleData = [sampleJson] }); +``` + +The design and the roadmap are in the +[design spec](https://github.com/TriasDev/templify/blob/main/docs/superpowers/specs/2026-11-25-template-builder-design.md) +and in [epic #261](https://github.com/TriasDev/templify/issues/261). diff --git a/src/TriasDev.Templify.Builder/Raw.cs b/src/TriasDev.Templify.Builder/Raw.cs new file mode 100644 index 00000000..11bd5381 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Raw.cs @@ -0,0 +1,96 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; + +namespace TriasDev.Templify.Builder; + +/// +/// A block written as format XML, for a construct the builder's vocabulary does not have (a field, vertical text, a +/// special table). Both formats are required, so a template never silently lacks content in one of them. +/// +/// +/// +/// DOCX: a w:p or w:tbl element (WordprocessingML namespace). ODT: a text:p, text:h, +/// table:table or text:list element. The XML is written as given; the built template is still +/// validated by the builder's tests and by TemplateProcessor.ValidateTemplate. +/// +/// +/// Paths the XML reads through placeholders are declared in so the data contract stays complete. +/// Raw blocks are not available to declarative definitions. +/// +/// +public sealed record RawBlock +{ + /// Gets the DOCX element. + public required Func Docx { get; init; } + + /// Gets the ODT element. + public required Func Odt { get; init; } + + /// Gets the data paths the XML's placeholders read (recorded as values in the contract). + public IReadOnlyList Uses { get; init; } = []; +} + +/// What a raw block's XML may depend on. +public sealed class RawContext +{ + private readonly IReadOnlyList _uses; + + internal RawContext(RawBlock raw, Length frame) + { + _uses = raw.Uses; + Frame = frame; + } + + /// Gets the width of the container the block sits in (page frame, cell or box content). + public Length Frame { get; } + + /// + /// Returns the placeholder text for a path declared in , for example + /// {{customer.name}}; put it into one text run (w:t) or one text node so the engine finds it whole. + /// + /// A path from . + /// The format, or null. + /// The path is not declared in . + public string Placeholder(TemplatePath path, ValueFormat? format = null) + { + if (path.IsRoot || !_uses.Contains(path)) + { + throw new TemplateBuildException([new BuildDiagnostic( + DiagnosticCodes.UndeclaredRawPath, + $"The raw block reads '{path.Text}', which is not declared in its Uses; the data contract would miss it.")]); + } + + return TemplateSyntax.Placeholder(path, format); + } + + /// The root elements a DOCX raw block may have. + internal static readonly XName[] DocxRoots = + { + XName.Get("p", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), + XName.Get("tbl", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), + }; + + /// The root elements an ODT raw block may have. + internal static readonly XName[] OdtRoots = + { + XName.Get("p", "urn:oasis:names:tc:opendocument:xmlns:text:1.0"), + XName.Get("h", "urn:oasis:names:tc:opendocument:xmlns:text:1.0"), + XName.Get("list", "urn:oasis:names:tc:opendocument:xmlns:text:1.0"), + XName.Get("table", "urn:oasis:names:tc:opendocument:xmlns:table:1.0"), + }; + + /// Checks a raw element's root and returns it; a wrong root is a definition error. + internal static XElement Check(XElement? element, XName[] allowed, string format) + { + if (element is null || !allowed.Contains(element.Name)) + { + throw new TemplateBuildException([new BuildDiagnostic( + DiagnosticCodes.InvalidRawBlock, + $"A raw {format} block must be one of {string.Join(", ", allowed.Select(n => n.LocalName))} in its namespace, not '{element?.Name}'.")]); + } + + return element; + } +} diff --git a/src/TriasDev.Templify.Builder/SectionComponent.cs b/src/TriasDev.Templify.Builder/SectionComponent.cs new file mode 100644 index 00000000..0e7d6f67 --- /dev/null +++ b/src/TriasDev.Templify.Builder/SectionComponent.cs @@ -0,0 +1,30 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder; + +/// A named section (): its blocks, under a name the JSON form keeps. +internal sealed partial class SectionComponent(string name, Action content) : ITemplateComponent +{ + public string Name { get; } = name; + + public void Compose(BlockComposer c) => content(c); + + public static string ValidateName(string name) + { + ArgumentNullException.ThrowIfNull(name); + if (!NamePattern().IsMatch(name)) + { + throw new ArgumentException($"'{name}' is not a section name: use letters, digits, '_', '.' or '-'.", nameof(name)); + } + + return name; + } + + public static bool IsValidName(string name) => NamePattern().IsMatch(name); + + [GeneratedRegex("^[A-Za-z0-9_.-]+$")] + private static partial Regex NamePattern(); +} diff --git a/src/TriasDev.Templify.Builder/Sides.cs b/src/TriasDev.Templify.Builder/Sides.cs new file mode 100644 index 00000000..128662b9 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Sides.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// Sides of a cell or table, combinable: Sides.Top | Sides.Bottom. +[Flags] +public enum Sides +{ + /// No side. + None = 0, + + /// The top side. + Top = 1, + + /// The right side. + Right = 2, + + /// The bottom side. + Bottom = 4, + + /// The left side. + Left = 8, + + /// All four sides. + All = Top | Right | Bottom | Left, +} diff --git a/src/TriasDev.Templify.Builder/StyleInheritance.cs b/src/TriasDev.Templify.Builder/StyleInheritance.cs new file mode 100644 index 00000000..055cd071 --- /dev/null +++ b/src/TriasDev.Templify.Builder/StyleInheritance.cs @@ -0,0 +1,88 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Gives every paragraph without a style of its own the style it inherits: in a table cell the row's text style, +/// then the table style's header or body text style; everywhere the style sheet's default paragraph style. List items +/// keep their list style's item style and inherit only when it has none. Runs once after composition, so writers see +/// explicit styles only. +/// +internal static class StyleInheritance +{ + /// Applies the inherited styles to the body and every header and footer part. + public static void Apply(List body, PageSetup page, StyleSheet styles, BuildContext context) + { + foreach (List? part in new[] { body, page.Header, page.Footer, page.FirstHeader, page.FirstFooter }) + { + if (part != null) + { + Apply(part, styles.DefaultParagraphStyle, styles, context); + } + } + } + + /// Applies to the unstyled paragraphs of a container, recursively. + public static void Apply(List blocks, ParagraphStyleKey? inherited, StyleSheet styles, BuildContext context) + { + for (int i = 0; i < blocks.Count; i++) + { + switch (blocks[i]) + { + // A list item takes its list style's item style (the writers apply it); only without one it inherits. + case ParagraphBlock { Style: null } paragraph when inherited != null + && (paragraph.List is null || styles.Find(paragraph.List.Style)?.ItemStyle is null): + ParagraphBlock styled = paragraph with { Style = inherited }; + if (context.Locations.TryGetValue(paragraph, out string? location)) + { + context.Locations.AddOrUpdate(styled, location); + } + + blocks[i] = styled; + break; + case ConditionalBlock conditional: + foreach (ConditionalBranch branch in conditional.Branches) + { + Apply(branch.Body, inherited, styles, context); + } + + if (conditional.Else != null) + { + Apply(conditional.Else, inherited, styles, context); + } + + break; + case LoopBlock loop: + Apply(loop.Body, inherited, styles, context); + break; + case ComponentBlock component: + Apply(component.Body, inherited, styles, context); + break; + case ListBlock list: + Apply(list.Items, inherited, styles, context); + break; + case TableBlock table: + foreach (TableRowModel row in table.AllRows()) + { + ParagraphStyleKey? cellStyle = ForCell(styles, table, row); + foreach (TableCellModel cell in row.Cells) + { + Apply(cell.Content, cellStyle, styles, context); + } + } + + break; + } + } + } + + /// The style a paragraph in a cell of inherits. + public static ParagraphStyleKey? ForCell(StyleSheet styles, TableBlock table, TableRowModel row) + { + TableStyleDefinition? style = styles.Resolve(table); + return row.ParagraphStyle ?? (row.IsHeader ? style?.HeaderParagraphStyle : style?.ParagraphStyle) ?? styles.DefaultParagraphStyle; + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/BuilderStyles.cs b/src/TriasDev.Templify.Builder/Styles/BuilderStyles.cs new file mode 100644 index 00000000..34bfeec1 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/BuilderStyles.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// Styles the builder owns. +public static class BuilderStyles +{ + /// + /// The paragraph style of the Templify markers ({{#if …}}, {{/if}}, …). Markers are visible on purpose: + /// whoever adapts a downloaded template has to see its logic to delete a block together with its markers. Templify + /// removes the marker paragraphs when it fills the template. + /// + /// + /// By default it is small, muted and monospace (Courier New, 8 pt, grey, no spacing, kept with the next paragraph). + /// A style sheet may define this key to change how markers look; it then replaces the default entirely. + /// + public static ParagraphStyleKey TemplateMarker { get; } = ParagraphStyleKey.BuiltIn("TemplifyMarker", "Template Marker"); + + /// The paragraph style of spacer paragraphs that keep cells and tables apart once markers are removed (1 pt, invisible). + internal static ParagraphStyleKey TemplateSpacer { get; } = ParagraphStyleKey.BuiltIn("TemplifySpacer", "Template Spacer"); + + /// The definition of . + internal static ParagraphStyleDefinition SpacerDefinition() + { + ParagraphStyleDefinition definition = new ParagraphStyleDefinition(TemplateSpacer); + definition.Text.Size = 1.Pt(); + definition.Paragraph.SpaceBefore = Length.Zero; + definition.Paragraph.SpaceAfter = Length.Zero; + definition.Paragraph.LineHeight = new LineHeight(LineHeightRule.Exact, 1.Pt(), 0); + return definition; + } + + /// The default definition of . + internal static ParagraphStyleDefinition DefaultMarkerDefinition() + { + ParagraphStyleDefinition definition = new ParagraphStyleDefinition(TemplateMarker); + definition.Text.Font = new FontFace("Courier New"); + definition.Text.Size = 8.Pt(); + definition.Text.Color = Color.FromHex("737373"); + definition.Paragraph.SpaceBefore = Length.Zero; + definition.Paragraph.SpaceAfter = Length.Zero; + definition.Paragraph.KeepWithNext = true; + return definition; + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/Color.cs b/src/TriasDev.Templify.Builder/Styles/Color.cs new file mode 100644 index 00000000..1cf8cacc --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/Color.cs @@ -0,0 +1,98 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; + +namespace TriasDev.Templify.Builder; + +/// An opaque RGB colour. +public readonly struct Color : IEquatable +{ + private Color(byte red, byte green, byte blue, string? token = null) + { + R = red; + G = green; + B = blue; + TokenName = token; + } + + /// + /// Gets the theme token the colour came from (); the JSON form writes "$name" for it and + /// lists the value in its theme. Null for a plain colour. Equality compares the colour only. + /// + public string? TokenName { get; } + + /// + /// A colour of the theme: under a name, so the JSON form refers to it as "$name" and a + /// host can replace it (TemplateJsonImportOptions.Theme). + /// + /// The token's name: a letter, then letters, digits, _, . or -. + /// The colour. + /// The colour with its token. + public static Color Token(string name, Color value) => new Color(value.R, value.G, value.B, Json.ThemeTokens.Validate(name, nameof(name))); + + /// Gets the red component. + public byte R { get; } + + /// Gets the green component. + public byte G { get; } + + /// Gets the blue component. + public byte B { get; } + + /// Creates a colour from its components. + /// The red component. + /// The green component. + /// The blue component. + /// The colour. + public static Color FromRgb(byte red, byte green, byte blue) => new Color(red, green, blue); + + /// Creates a colour from six hex digits, with or without a leading #: 1F4E79, #1f4e79. + /// The hex value. + /// The colour. + /// The value is not six hex digits. + public static Color FromHex(string hex) + { + ArgumentNullException.ThrowIfNull(hex); + ReadOnlySpan digits = hex.AsSpan(); + if (digits.StartsWith("#")) + { + digits = digits[1..]; + } + + if (digits.Length != 6 || !int.TryParse(digits, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out int value)) + { + throw new ArgumentException($"'{hex}' is not a colour: expected six hex digits, for example \"1F4E79\".", nameof(hex)); + } + + return new Color((byte)(value >> 16), (byte)(value >> 8), (byte)value); + } + + /// Returns the colour as #RRGGBB. + /// The hex value with a leading #. + public override string ToString() => "#" + Hex; + + /// Six upper-case hex digits, as WordprocessingML writes colours. + internal string Hex => string.Create(CultureInfo.InvariantCulture, $"{R:X2}{G:X2}{B:X2}"); + + /// + public bool Equals(Color other) => R == other.R && G == other.G && B == other.B; + + /// + public override bool Equals(object? obj) => obj is Color other && Equals(other); + + /// + public override int GetHashCode() => (R << 16) | (G << 8) | B; + + /// Compares two colours. + /// The first colour. + /// The second colour. + /// when both are equal. + public static bool operator ==(Color left, Color right) => left.Equals(right); + + /// Compares two colours. + /// The first colour. + /// The second colour. + /// when they differ. + public static bool operator !=(Color left, Color right) => !left.Equals(right); +} diff --git a/src/TriasDev.Templify.Builder/Styles/FontFace.cs b/src/TriasDev.Templify.Builder/Styles/FontFace.cs new file mode 100644 index 00000000..e3b50502 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/FontFace.cs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// A font family. By default it is referenced by name and has to be installed where the document is opened or +/// converted; puts the font file into the document. +/// +/// +/// Word for Mac ignores an embedded bold face. A design that needs a weight on every platform names the weight's +/// family, for example new FontFace("Geist SemiBold"), instead of using Bold() on a regular family; with +/// embedding, embed each weight's file as its own family. +/// +public sealed record FontFace +{ + /// Initializes a font face. + /// The family name, for example Source Sans 3. + /// The name is empty or contains quotes or control characters. + public FontFace(string family) + : this(family, embedding: null) + { + } + + private FontFace(string family, FontFile? embedding) + { + ArgumentNullException.ThrowIfNull(family); + if (string.IsNullOrWhiteSpace(family) || family.Trim() != family || family.Any(c => char.IsControl(c) || c is '"' or '\'')) + { + throw new ArgumentException( + $"'{family}' is not a font family name: it must be non-empty, without leading or trailing spaces, quotes or control characters.", + nameof(family)); + } + + Family = family; + Embedding = embedding; + } + + /// Gets the theme token the font came from (); null for a plain font. Equality ignores it. + public string? TokenName { get; private init; } + + /// A font of the theme: under a name the JSON form refers to as "$name". + /// The token's name: a letter, then letters, digits, _, . or -. + /// The font. + /// The font with its token. + public static FontFace Token(string name, FontFace face) + { + ArgumentNullException.ThrowIfNull(face); + return face with { TokenName = Json.ThemeTokens.Validate(name, nameof(name)) }; + } + + /// Gets the family name. + public string Family { get; } + + /// Gets a value indicating whether the font file is embedded in the document. + public bool IsEmbedded => Embedding != null; + + /// The embedded font file, or null. + internal FontFile? Embedding { get; } + + /// + /// A font embedded in the document, so a server-side PDF conversion and a recipient without the font installed + /// see it. The family name is the one the file declares (its name table, name id 1). + /// + /// A TrueType font file (.ttf), one weight and style. Pass a subset to keep documents small; the builder does not subset. + /// The font face. + /// + /// The bytes are not a TrueType font (OpenType CFF, collections and WOFF are not supported), or the font's + /// embedding permission (fsType) does not allow editable embedding. + /// + public static FontFace Embedded(byte[] fontFile) + { + FontFile file = FontFile.Read(fontFile, nameof(fontFile)); + return new FontFace(file.Family, file); + } + + /// + /// A font embedded in the document under a family name the file declares (name id 1 or 16), for files that name + /// their family in more than one way. + /// + /// The family name; one of the file's family names. + /// A TrueType font file (.ttf). + /// The font face. + /// See ; also when the file does not declare . + public static FontFace Embedded(string family, byte[] fontFile) + { + ArgumentNullException.ThrowIfNull(family); + FontFile file = FontFile.Read(fontFile, nameof(fontFile)); + if (!file.Families.Contains(family, StringComparer.Ordinal)) + { + throw new ArgumentException( + $"The font file declares the family {string.Join(" / ", file.Families.Select(f => "'" + f + "'"))}, not '{family}'.", + nameof(family)); + } + + return new FontFace(family, file); + } + + /// Two font faces are equal when they name the same family and embed the same file (or none). + /// The other font face. + /// Whether they are equal. + public bool Equals(FontFace? other) => + other is not null && Family == other.Family && Embedding?.Hash == other.Embedding?.Hash; + + /// + public override int GetHashCode() => HashCode.Combine(Family, Embedding?.Hash); +} diff --git a/src/TriasDev.Templify.Builder/Styles/FontFile.cs b/src/TriasDev.Templify.Builder/Styles/FontFile.cs new file mode 100644 index 00000000..170ab4bc --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/FontFile.cs @@ -0,0 +1,221 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; + +namespace TriasDev.Templify.Builder; + +/// +/// A TrueType font file to embed: its bytes, family names and embedding permission, read from the file's tables +/// (OpenType specification: table directory, name, OS/2) without a font library. +/// +internal sealed class FontFile +{ + private FontFile(byte[] data, string family, IReadOnlyList families) + { + Data = data; + Family = family; + Families = families; + Hash = Convert.ToHexStringLower(SHA256.HashData(data)); + } + + /// The file's bytes (a copy: the caller's array may change). + public byte[] Data { get; } + + /// The family name (name id 1, Windows English first). + public string Family { get; } + + /// Every family name the file declares (name ids 1 and 16). + public IReadOnlyList Families { get; } + + /// The SHA-256 of the bytes, lower-case hex. + public string Hash { get; } + + /// + /// The DOCX font key, a GUID derived from the content (deterministic output), as Word writes it: + /// {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}. + /// + public string DocxFontKey + { + get + { + string hex = Hash[..32].ToUpperInvariant(); + return $"{{{hex[..8]}-{hex[8..12]}-{hex[12..16]}-{hex[16..20]}-{hex[20..]}}}"; + } + } + + /// + /// The obfuscated DOCX font part (ECMA-376 part 1, 17.8.1): the first 32 bytes XOR the key, which is the font + /// key's 16 bytes in reverse order. + /// + public byte[] ObfuscatedForDocx() + { + string hex = DocxFontKey.Replace("{", string.Empty, StringComparison.Ordinal) + .Replace("}", string.Empty, StringComparison.Ordinal) + .Replace("-", string.Empty, StringComparison.Ordinal); + byte[] key = new byte[16]; + for (int i = 0; i < 16; i++) + { + key[i] = byte.Parse(hex.AsSpan((15 - i) * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); + } + + byte[] result = (byte[])Data.Clone(); + for (int i = 0; i < 32 && i < result.Length; i++) + { + result[i] ^= key[i % 16]; + } + + return result; + } + + /// Reads and checks a font file. + /// Not a TrueType font, unreadable tables, or embedding not permitted. + public static FontFile Read(byte[] data, string parameterName) + { + ArgumentNullException.ThrowIfNull(data, parameterName); + ReadOnlySpan span = data; + if (span.Length < 12) + { + throw new ArgumentException("The bytes are not a font file.", parameterName); + } + + uint version = BinaryPrimitives.ReadUInt32BigEndian(span); + switch (version) + { + case 0x00010000u: + case 0x74727565u: // 'true' + break; + case 0x4F54544Fu: // 'OTTO' + throw new ArgumentException("The font has PostScript (CFF) outlines; Word embeds TrueType fonts only. Use the font's TrueType (.ttf) version.", parameterName); + case 0x74746366u: // 'ttcf' + throw new ArgumentException("The bytes are a font collection (.ttc); pass the single font's .ttf file.", parameterName); + case 0x774F4646u: // 'wOFF' + case 0x774F4632u: // 'wOF2' + throw new ArgumentException("The bytes are a web font (WOFF); pass the font's .ttf file.", parameterName); + default: + throw new ArgumentException("The bytes are not a TrueType font file.", parameterName); + } + + ReadOnlySpan name = Table(span, "name", parameterName); + ReadOnlySpan os2 = Table(span, "OS/2", parameterName); + CheckEmbeddingPermission(os2, parameterName); + + List<(int Priority, string Name)> families = ReadFamilyNames(name, parameterName); + if (families.Count == 0) + { + throw new ArgumentException("The font file declares no family name.", parameterName); + } + + string family = families.OrderBy(f => f.Priority).First().Name; + IReadOnlyList all = families.Select(f => f.Name).Distinct(StringComparer.Ordinal).ToList(); + return new FontFile((byte[])data.Clone(), family, all); + } + + private static ReadOnlySpan Table(ReadOnlySpan font, string tag, string parameterName) + { + int count = BinaryPrimitives.ReadUInt16BigEndian(font[4..]); + byte[] wanted = Encoding.ASCII.GetBytes(tag); + for (int i = 0; i < count; i++) + { + int record = 12 + (i * 16); + if (record + 16 > font.Length) + { + break; + } + + if (font.Slice(record, 4).SequenceEqual(wanted)) + { + long offset = BinaryPrimitives.ReadUInt32BigEndian(font[(record + 8)..]); + long length = BinaryPrimitives.ReadUInt32BigEndian(font[(record + 12)..]); + if (offset + length > font.Length) + { + throw new ArgumentException($"The font's '{tag}' table lies outside the file.", parameterName); + } + + return font.Slice((int)offset, (int)length); + } + } + + throw new ArgumentException($"The font file has no '{tag}' table.", parameterName); + } + + /// + /// fsType (OS/2 offset 8): 0 installable, bit 1 restricted, bit 2 preview and print, bit 3 editable, bit 9 + /// bitmap only. A template is edited after download, so it needs installable or editable embedding. + /// + private static void CheckEmbeddingPermission(ReadOnlySpan os2, string parameterName) + { + if (os2.Length < 10) + { + throw new ArgumentException("The font's 'OS/2' table is too short.", parameterName); + } + + int fsType = BinaryPrimitives.ReadUInt16BigEndian(os2[8..]); + int usage = fsType & 0x000F; + if ((fsType & 0x0200) != 0) + { + throw new ArgumentException("The font's licence allows embedding bitmaps only (fsType bit 9); it cannot be embedded.", parameterName); + } + + if (usage != 0 && (usage & 0x0008) == 0) + { + string reason = (usage & 0x0004) != 0 + ? "preview and print only (fsType 0x0004): a template is edited after download, so it needs editable embedding" + : "no embedding (restricted licence, fsType 0x0002)"; + throw new ArgumentException($"The font's licence allows {reason}.", parameterName); + } + } + + /// Family names (ids 1 and 16) with a priority: Windows English id 1 first. + private static List<(int Priority, string Name)> ReadFamilyNames(ReadOnlySpan table, string parameterName) + { + if (table.Length < 6) + { + throw new ArgumentException("The font's 'name' table is too short.", parameterName); + } + + int count = BinaryPrimitives.ReadUInt16BigEndian(table[2..]); + int storage = BinaryPrimitives.ReadUInt16BigEndian(table[4..]); + List<(int, string)> names = new List<(int, string)>(); + for (int i = 0; i < count; i++) + { + int record = 6 + (i * 12); + if (record + 12 > table.Length) + { + break; + } + + int platform = BinaryPrimitives.ReadUInt16BigEndian(table[record..]); + int encoding = BinaryPrimitives.ReadUInt16BigEndian(table[(record + 2)..]); + int language = BinaryPrimitives.ReadUInt16BigEndian(table[(record + 4)..]); + int nameId = BinaryPrimitives.ReadUInt16BigEndian(table[(record + 6)..]); + int length = BinaryPrimitives.ReadUInt16BigEndian(table[(record + 8)..]); + int offset = BinaryPrimitives.ReadUInt16BigEndian(table[(record + 10)..]); + if (nameId is not (1 or 16) || storage + offset + length > table.Length) + { + continue; + } + + ReadOnlySpan bytes = table.Slice(storage + offset, length); + string? text = platform switch + { + 3 when encoding is 0 or 1 or 10 => Encoding.BigEndianUnicode.GetString(bytes), + 0 => Encoding.BigEndianUnicode.GetString(bytes), + 1 when encoding == 0 => Encoding.Latin1.GetString(bytes), + _ => null, + }; + if (string.IsNullOrWhiteSpace(text)) + { + continue; + } + + int priority = (nameId == 1 ? 0 : 10) + (platform == 3 ? 0 : 2) + (platform == 3 && language == 0x409 ? 0 : 1); + names.Add((priority, text.Trim())); + } + + return names; + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/Length.cs b/src/TriasDev.Templify.Builder/Styles/Length.cs new file mode 100644 index 00000000..49513cc1 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/Length.cs @@ -0,0 +1,135 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; + +namespace TriasDev.Templify.Builder; + +/// +/// A length in a document: a font size, a spacing, an indent. Stored as an integer number of 1/1000 points, so +/// lengths add up exactly and every writer rounds only once, to its own unit. +/// +/// Write lengths with the extension methods in : 12.Pt(), 25.Mm(). +public readonly struct Length : IEquatable, IComparable +{ + private const double MillimetersPerPoint = 25.4 / 72.0; + + private Length(int millipoints) + { + Millipoints = millipoints; + } + + /// Gets the zero length. + public static Length Zero => default; + + /// Gets the length in points. + public double Points => Millipoints / 1000.0; + + /// Gets the length in millimeters. + public double Millimeters => Points * MillimetersPerPoint; + + /// Gets the length in 1/1000 points. + internal int Millipoints { get; } + + /// Creates a length from points (1/72 inch). + /// The length in points. + /// The length, rounded to 1/1000 point. + public static Length FromPoints(double points) => new Length(ToMillipoints(points * 1000.0, nameof(points))); + + /// Creates a length from millimeters. + /// The length in millimeters. + /// The length, rounded to 1/1000 point. + public static Length FromMillimeters(double millimeters) => + new Length(ToMillipoints(millimeters / MillimetersPerPoint * 1000.0, nameof(millimeters))); + + /// Adds two lengths. + /// The first length. + /// The second length. + /// The sum. + public static Length operator +(Length left, Length right) => new Length(checked(left.Millipoints + right.Millipoints)); + + /// Subtracts a length. + /// The length to subtract from. + /// The length to subtract. + /// The difference. + public static Length operator -(Length left, Length right) => new Length(checked(left.Millipoints - right.Millipoints)); + + /// Negates a length, for example for a hanging indent: -4.5.Mm(). + /// The length. + /// The negated length. + public static Length operator -(Length value) => new Length(checked(-value.Millipoints)); + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when both are equal. + public static bool operator ==(Length left, Length right) => left.Equals(right); + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when they differ. + public static bool operator !=(Length left, Length right) => !left.Equals(right); + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when is shorter. + public static bool operator <(Length left, Length right) => left.Millipoints < right.Millipoints; + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when is longer. + public static bool operator >(Length left, Length right) => left.Millipoints > right.Millipoints; + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when is not longer. + public static bool operator <=(Length left, Length right) => left.Millipoints <= right.Millipoints; + + /// Compares two lengths. + /// The first length. + /// The second length. + /// when is not shorter. + public static bool operator >=(Length left, Length right) => left.Millipoints >= right.Millipoints; + + /// + public int CompareTo(Length other) => Millipoints.CompareTo(other.Millipoints); + + /// + public bool Equals(Length other) => Millipoints == other.Millipoints; + + /// + public override bool Equals(object? obj) => obj is Length other && Equals(other); + + /// + public override int GetHashCode() => Millipoints; + + /// Returns the length in points, for example 10.5pt. + /// The length in points, invariant culture. + public override string ToString() => FormatPoints() + "pt"; + + /// The shorter of two lengths. + internal static Length Min(Length a, Length b) => a <= b ? a : b; + + /// The length in points with up to three decimals, invariant culture, without a unit. + internal string FormatPoints() => (Millipoints / 1000m).ToString("0.###", CultureInfo.InvariantCulture); + + /// The length in twentieths of a point (twips), as WordprocessingML spacing and indents use. + internal int Twips => (int)Math.Round(Millipoints / 50.0, MidpointRounding.AwayFromZero); + + /// The length in half points, as WordprocessingML font sizes use. + internal int HalfPoints => (int)Math.Round(Millipoints / 500.0, MidpointRounding.AwayFromZero); + + private static int ToMillipoints(double value, string parameterName) + { + if (double.IsNaN(value) || double.IsInfinity(value) || Math.Abs(value) > int.MaxValue) + { + throw new ArgumentOutOfRangeException(parameterName, "The length is not a finite value in range."); + } + + return (int)Math.Round(value, MidpointRounding.AwayFromZero); + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/StyleDefinitions.cs b/src/TriasDev.Templify.Builder/Styles/StyleDefinitions.cs new file mode 100644 index 00000000..1dfc85be --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/StyleDefinitions.cs @@ -0,0 +1,94 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Model; + +/// Text formatting that a style sets; unset properties are inherited. +internal sealed class TextProperties +{ + public FontFace? Font { get; set; } + + public Length? Size { get; set; } + + public Color? Color { get; set; } + + public bool? Bold { get; set; } + + public bool? Italic { get; set; } +} + +/// How the height of a paragraph's lines is set. +internal enum LineHeightRule +{ + /// A multiple of the single line height (). + Proportional, + + /// Exactly . + Exact, + + /// At least . + AtLeast, +} + +/// The line height of a paragraph style. +internal sealed record LineHeight(LineHeightRule Rule, Length Height, double Multiple); + +/// Paragraph formatting that a style sets; unset properties are inherited. +internal sealed class ParagraphProperties +{ + public Length? SpaceBefore { get; set; } + + public Length? SpaceAfter { get; set; } + + public LineHeight? LineHeight { get; set; } + + public TextAlignment? Alignment { get; set; } + + public Length? IndentStart { get; set; } + + public Length? IndentEnd { get; set; } + + public Length? FirstLineIndent { get; set; } + + public bool? KeepWithNext { get; set; } + + public bool? KeepLinesTogether { get; set; } + + public int? OutlineLevel { get; set; } + + /// Gets or sets the line under the paragraph. + public BorderLine? BorderBottom { get; set; } + + /// Gets or sets the space between the text and . + public Length? BorderBottomSpace { get; set; } +} + +/// A paragraph style as defined in a . +internal sealed class ParagraphStyleDefinition(ParagraphStyleKey key) +{ + public ParagraphStyleKey Key { get; } = key; + + public ParagraphStyleKey? BasedOn { get; set; } + + public ParagraphStyleKey? Next { get; set; } + + public ParagraphProperties Paragraph { get; } = new ParagraphProperties(); + + public TextProperties Text { get; } = new TextProperties(); +} + +/// A character style as defined in a . +internal sealed class CharacterStyleDefinition(CharacterStyleKey key) +{ + public CharacterStyleKey Key { get; } = key; + + public CharacterStyleKey? BasedOn { get; set; } + + public TextProperties Text { get; } = new TextProperties(); +} + +/// The standard document properties. +internal sealed record DocumentInfo(string? Title, string? Author, string? Subject) +{ + public static DocumentInfo Empty { get; } = new DocumentInfo(null, null, null); +} diff --git a/src/TriasDev.Templify.Builder/Styles/StyleKeys.cs b/src/TriasDev.Templify.Builder/Styles/StyleKeys.cs new file mode 100644 index 00000000..04b3e30d --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/StyleKeys.cs @@ -0,0 +1,128 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder; + +/// Text alignment of a paragraph, relative to the writing direction. +public enum TextAlignment +{ + /// Aligned to the start of the line (left in left-to-right text). + Start = 0, + + /// Centered. + Center = 1, + + /// Aligned to the end of the line (right in left-to-right text). + End = 2, + + /// Justified. + Justify = 3, +} + +/// +/// Names a paragraph style. Define it once as a static field, use it in the and on paragraphs. +/// +public sealed record ParagraphStyleKey +{ + /// Initializes a paragraph style key. + /// The style's id in the document: letters, digits, _ and -, starting with a letter or _. + /// + /// The name Word and LibreOffice show in their style lists. A name of one of Word's built-in styles (for example + /// Body Text) is translated to LibreOffice's own style when LibreOffice opens the DOCX (Text body). + /// + /// The id or the display name is invalid, or the id is reserved by the builder. + public ParagraphStyleKey(string id, string displayName) + { + Id = StyleKeyRules.ValidateId(id, nameof(id)); + DisplayName = StyleKeyRules.ValidateDisplayName(displayName, nameof(displayName)); + } + + /// A key the builder owns; its id may use the reserved prefix. + private ParagraphStyleKey(string id, string displayName, bool builtIn) + { + _ = builtIn; + Id = id; + DisplayName = displayName; + } + + /// Creates a key the builder owns. + internal static ParagraphStyleKey BuiltIn(string id, string displayName) => new ParagraphStyleKey(id, displayName, builtIn: true); + + /// Gets the style's id in the document. + public string Id { get; } + + /// Gets the name Word and LibreOffice show. + public string DisplayName { get; } +} + +/// +/// Names a character style. Define it once as a static field, use it in the and on text. +/// +public sealed record CharacterStyleKey +{ + /// Initializes a character style key. + /// The style's id in the document: letters, digits, _ and -, starting with a letter or _. + /// The name Word and LibreOffice show in their style lists. + /// The id or the display name is invalid, or the id is reserved by the builder. + public CharacterStyleKey(string id, string displayName) + { + Id = StyleKeyRules.ValidateId(id, nameof(id)); + DisplayName = StyleKeyRules.ValidateDisplayName(displayName, nameof(displayName)); + } + + /// Gets the style's id in the document. + public string Id { get; } + + /// Gets the name Word and LibreOffice show. + public string DisplayName { get; } +} + +/// The rules style keys follow in both formats. +internal static partial class StyleKeyRules +{ + /// + /// Ids the builder writes itself: the default paragraph style of each format and Word's default character style. + /// + /// The prefix of the styles the builder owns (for example its page-break style). + public const string ReservedPrefix = "Templify"; + + public static readonly IReadOnlySet ReservedIds = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "Normal", "Standard", "DefaultParagraphFont", + }; + + public static string ValidateId(string id, string parameterName) + { + ArgumentNullException.ThrowIfNull(id, parameterName); + if (!IdPattern().IsMatch(id)) + { + throw new ArgumentException( + $"'{id}' is not a valid style id: use letters, digits, '_' and '-', starting with a letter or '_'.", + parameterName); + } + + if (ReservedIds.Contains(id) || id.StartsWith(ReservedPrefix, StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException($"The style id '{id}' is reserved by the builder (as are ids starting with '{ReservedPrefix}'); choose another id.", parameterName); + } + + return id; + } + + public static string ValidateDisplayName(string displayName, string parameterName) + { + ArgumentNullException.ThrowIfNull(displayName, parameterName); + if (string.IsNullOrWhiteSpace(displayName) || displayName.Any(char.IsControl)) + { + throw new ArgumentException("A style's display name must be non-empty and contain no control characters.", parameterName); + } + + return displayName; + } + + // ODF style names are NCNames, WordprocessingML style ids are free text: this is the subset both accept. + [GeneratedRegex("^[A-Za-z_][A-Za-z0-9_-]*$", RegexOptions.CultureInvariant)] + private static partial Regex IdPattern(); +} diff --git a/src/TriasDev.Templify.Builder/Styles/StyleSheet.cs b/src/TriasDev.Templify.Builder/Styles/StyleSheet.cs new file mode 100644 index 00000000..400aa2eb --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/StyleSheet.cs @@ -0,0 +1,279 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// The named styles of a template: defaults, paragraph styles and character styles. Both writers turn them into +/// real named styles, so a downloaded template stays editable in Word and LibreOffice. +/// +/// +/// A style sheet is immutable and can be shared by many definitions and builds. Build it from a product's theme, +/// for example in a method StyleSheet Create(BrandTheme theme), so a customer's theme slots flow into the +/// styles. Problems that involve several styles (a duplicate id, an unknown BasedOn, a cycle) are reported by +/// , together with every other problem of the definition. +/// +public sealed class StyleSheet +{ + private StyleSheet( + TextProperties defaults, + IReadOnlyList paragraphStyles, + IReadOnlyList characterStyles, + IReadOnlyList tableStyles, + IReadOnlyList boxStyles, + IReadOnlyList listStyles, + ParagraphStyleKey? defaultParagraphStyle) + { + DefaultParagraphStyle = defaultParagraphStyle; + BoxStyles = boxStyles; + ListStyles = listStyles; + Defaults = defaults; + ParagraphStyles = paragraphStyles; + CharacterStyles = characterStyles; + TableStyles = tableStyles; + Problems = Validate(paragraphStyles, characterStyles); + foreach (IGrouping duplicate in tableStyles.Select(t => t.Key.Id).Concat(boxStyles.Select(b => b.Key.Id)).Concat(listStyles.Select(l => l.Key.Id)).GroupBy(id => id, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) + { + ((List)Problems).Add(new BuildDiagnostic(DiagnosticCodes.DuplicateStyleId, $"The table, box or list style id '{duplicate.Key}' is defined more than once.")); + } + + foreach ((ParagraphStyleKey key, string usage) in InheritedStyleUses().Where(u => Find(u.Key) == null)) + { + ((List)Problems).Add(new BuildDiagnostic(DiagnosticCodes.UndefinedStyle, $"{usage} is the paragraph style '{key.Id}', which the style sheet does not define.")); + } + } + + /// Gets the paragraph style of paragraphs without one of their own; null when there is none. + internal ParagraphStyleKey? DefaultParagraphStyle { get; } + + /// The paragraph styles the sheet hands down (default, table text styles), with where each is set. + internal IEnumerable<(ParagraphStyleKey Key, string Usage)> InheritedStyleUses() + { + if (DefaultParagraphStyle is { } fallback) + { + yield return (fallback, "The default paragraph style"); + } + + foreach (TableStyleDefinition table in TableStyles) + { + if (table.ParagraphStyle is { } text) + { + yield return (text, $"The text style of the table style '{table.Key.Id}'"); + } + + if (table.HeaderParagraphStyle is { } header) + { + yield return (header, $"The header text style of the table style '{table.Key.Id}'"); + } + } + } + + /// Gets the list styles in definition order. + internal IReadOnlyList ListStyles { get; } + + /// Finds the definition of a list style. + internal ListStyleDefinition? Find(ListStyleKey key) => ListStyles.FirstOrDefault(s => s.Key == key); + + /// Gets the box styles in definition order. + internal IReadOnlyList BoxStyles { get; } + + /// Finds the definition of a box style. + internal BoxStyleDefinition? Find(BoxStyleKey key) => BoxStyles.FirstOrDefault(s => s.Key == key); + + /// The effective style of a table: its box style or its table style; null when it has none or it is undefined. + internal TableStyleDefinition? Resolve(TableBlock table) => + table.BoxStyle is { } box ? Find(box)?.AsTableStyle() + : table.Style is { } key ? Find(key) + : null; + + /// The space after a table: its own, else its box style's. + internal Length? SpaceAfterOf(TableBlock table) => + table.SpaceAfter ?? (table.BoxStyle is { } box ? Find(box)?.SpaceAfter : null); + + /// Gets the table styles in definition order. + internal IReadOnlyList TableStyles { get; } + + /// Finds the definition of a table style. + internal TableStyleDefinition? Find(TableStyleKey key) => TableStyles.FirstOrDefault(s => s.Key == key); + + /// Gets the default text formatting. + internal TextProperties Defaults { get; } + + /// Gets the paragraph styles in definition order. + internal IReadOnlyList ParagraphStyles { get; } + + /// Gets the character styles in definition order. + internal IReadOnlyList CharacterStyles { get; } + + /// Gets the problems found in the style sheet; reported when a template uses it. + internal IReadOnlyList Problems { get; } + + /// Gets an empty style sheet: default formatting of the application that opens the document. + internal static StyleSheet Empty { get; } = new StyleSheet(new TextProperties(), [], [], [], [], [], null); + + /// Creates a style sheet. + /// Defines the defaults and the styles. + /// The style sheet. + public static StyleSheet Create(Action styles) + { + ArgumentNullException.ThrowIfNull(styles); + StyleSheetComposer composer = new StyleSheetComposer(); + styles(composer); + composer.Close(); + return new StyleSheet(composer.DefaultText, composer.ParagraphStyles, composer.CharacterStyles, composer.TableStyles, composer.BoxStyles, composer.ListStyles, composer.DefaultParagraphStyle); + } + + /// A copy of this style sheet with one more paragraph style (the builder's own default styles). + internal StyleSheet WithParagraphStyle(ParagraphStyleDefinition definition) => + new StyleSheet(Defaults, ParagraphStyles.Append(definition).ToList(), CharacterStyles, TableStyles, BoxStyles, ListStyles, DefaultParagraphStyle); + + /// Finds the definition of a paragraph style. + /// Every font face the styles use, defaults first, in definition order (with repeats). + internal IEnumerable Fonts => new[] { Defaults.Font } + .Concat(ParagraphStyles.Select(s => s.Text.Font)) + .Concat(CharacterStyles.Select(s => s.Text.Font)) + .OfType(); + + /// The embedded font of each family that embeds one, in first-use order. + internal IReadOnlyList EmbeddedFonts => Fonts + .Where(f => f.IsEmbedded) + .DistinctBy(f => f.Family, StringComparer.Ordinal) + .ToList(); + + internal ParagraphStyleDefinition? Find(ParagraphStyleKey key) => ParagraphStyles.FirstOrDefault(s => s.Key == key); + + /// Finds the definition of a character style. + internal CharacterStyleDefinition? Find(CharacterStyleKey key) => CharacterStyles.FirstOrDefault(s => s.Key == key); + + /// The start indent of a paragraph style, through its BasedOn chain; zero when none is set. + internal Length IndentStartOf(ParagraphStyleKey? key) => Inherited(key, p => p.IndentStart) ?? Length.Zero; + + /// The space before of a paragraph style, through its BasedOn chain; zero when none is set. + internal Length SpaceBeforeOf(ParagraphStyleKey? key) => Inherited(key, p => p.SpaceBefore) ?? Length.Zero; + + /// The space after of a paragraph style, through its BasedOn chain; zero when none is set. + internal Length SpaceAfterOf(ParagraphStyleKey? key) => Inherited(key, p => p.SpaceAfter) ?? Length.Zero; + + private Length? Inherited(ParagraphStyleKey? key, Func property) + { + HashSet seen = new HashSet(StringComparer.Ordinal); + for (ParagraphStyleDefinition? style = key is null ? null : Find(key); style != null && seen.Add(style.Key.Id); style = style.BasedOn is { } b ? Find(b) : null) + { + if (property(style.Paragraph) is { } value) + { + return value; + } + } + + return null; + } + + /// + /// The outline level of a paragraph style, through its BasedOn chain; null when it is not a heading. + /// + internal int? OutlineLevelOf(ParagraphStyleKey key) + { + HashSet seen = new HashSet(StringComparer.Ordinal); + for (ParagraphStyleDefinition? style = Find(key); style != null && seen.Add(style.Key.Id); style = style.BasedOn is { } b ? Find(b) : null) + { + if (style.Paragraph.OutlineLevel is int level) + { + return level; + } + } + + return null; + } + + private static List Validate( + IReadOnlyList paragraphStyles, + IReadOnlyList characterStyles) + { + List problems = new List(); + + // Word keeps style ids and names in one namespace for all style types; ODF per family. The stricter rule holds. + IEnumerable<(string Id, string Name, string Kind)> all = paragraphStyles.Select(s => (s.Key.Id, s.Key.DisplayName, "paragraph")) + .Concat(characterStyles.Select(s => (s.Key.Id, s.Key.DisplayName, "character"))); + foreach (IGrouping group in all.GroupBy(s => s.Id, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.DuplicateStyleId, + $"The style id '{group.Key}' is defined more than once ({string.Join(", ", group.Select(s => s.Kind + " style '" + s.Name + "'"))}). Style ids are unique across paragraph and character styles.")); + } + + foreach (IGrouping group in all.GroupBy(s => s.Name, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1 && g.Select(s => s.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count() > 1)) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.DuplicateStyleName, + $"The display name '{group.Key}' is used by several styles ({string.Join(", ", group.Select(s => s.Id))}). Word requires unique style names.")); + } + + foreach ((string Id, string Name, string Kind) style in all.Where(s => s.Name.Contains(',', StringComparison.Ordinal))) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.InvalidStyleName, + $"The {style.Kind} style '{style.Id}' has the display name '{style.Name}': a comma is not allowed (Word reads it as a list of aliases).")); + } + + foreach (ParagraphStyleDefinition style in paragraphStyles) + { + if (style.BasedOn is { } basedOn && !paragraphStyles.Any(s => s.Key == basedOn)) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.UnknownBasedOn, + $"Paragraph style '{style.Key.Id}' is based on '{basedOn.Id}', which the style sheet does not define.")); + } + + if (style.Next is { } next && !paragraphStyles.Any(s => s.Key == next)) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.UnknownNextStyle, + $"Paragraph style '{style.Key.Id}' names '{next.Id}' as its next style, which the style sheet does not define.")); + } + } + + foreach (CharacterStyleDefinition style in characterStyles) + { + if (style.BasedOn is { } basedOn && !characterStyles.Any(s => s.Key == basedOn)) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.UnknownBasedOn, + $"Character style '{style.Key.Id}' is based on '{basedOn.Id}', which the style sheet does not define.")); + } + } + + AddCycles(paragraphStyles.Select(s => (s.Key.Id, s.BasedOn?.Id)), "Paragraph", problems); + AddCycles(characterStyles.Select(s => (s.Key.Id, s.BasedOn?.Id)), "Character", problems); + return problems; + } + + private static void AddCycles(IEnumerable<(string Id, string? BasedOn)> styles, string kind, List problems) + { + Dictionary parents = new Dictionary(StringComparer.Ordinal); + foreach ((string id, string? basedOn) in styles) + { + parents.TryAdd(id, basedOn); + } + + HashSet reported = new HashSet(StringComparer.Ordinal); + foreach (string start in parents.Keys) + { + List chain = new List(); + string? current = start; + while (current != null && parents.ContainsKey(current) && !chain.Contains(current)) + { + chain.Add(current); + current = parents[current]; + } + + if (current != null && chain.Contains(current) && current == start && reported.Add(string.Join(">", chain.OrderBy(s => s, StringComparer.Ordinal)))) + { + problems.Add(new BuildDiagnostic( + DiagnosticCodes.BasedOnCycle, + $"{kind} styles inherit from each other in a cycle: {string.Join(" → ", chain)} → {start}.")); + } + } + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/StyleSheetComposer.cs b/src/TriasDev.Templify.Builder/Styles/StyleSheetComposer.cs new file mode 100644 index 00000000..2c8219cc --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/StyleSheetComposer.cs @@ -0,0 +1,533 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Defines the defaults and the styles of a . Valid only inside the lambda passed to +/// . +/// +public sealed class StyleSheetComposer +{ + private bool _isOpen = true; + + internal StyleSheetComposer() + { + } + + internal TextProperties DefaultText { get; } = new TextProperties(); + + internal ParagraphStyleKey? DefaultParagraphStyle { get; set; } + + internal List ParagraphStyles { get; } = new List(); + + internal List CharacterStyles { get; } = new List(); + + internal List TableStyles { get; } = new List(); + + internal List BoxStyles { get; } = new List(); + + internal List ListStyles { get; } = new List(); + + /// Defines a bullet list style. + /// The style's key. + /// Sets the levels and the item paragraph style. + public void List(ListStyleKey key, Action style) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + ListStyleDefinition definition = new ListStyleDefinition(key); + style(new ListStyleComposer(this, definition)); + ListStyles.Add(definition); + } + + /// Defines a box style. + /// The style's key. + /// Sets the border, background and padding. + public void Box(BoxStyleKey key, Action style) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + BoxStyleDefinition definition = new BoxStyleDefinition(key); + style(new BoxStyleComposer(this, definition)); + BoxStyles.Add(definition); + } + + /// Defines a table style. + /// The style's key. + /// Sets the borders, rules, padding and header shading. + public void Table(TableStyleKey key, Action style) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + TableStyleDefinition definition = new TableStyleDefinition(key); + style(new TableStyleComposer(this, definition)); + TableStyles.Add(definition); + } + + /// Sets the default text formatting every style starts from. + /// Sets font, size and colour. + public void Defaults(Action defaults) + { + ArgumentNullException.ThrowIfNull(defaults); + EnsureOpen(); + DefaultStyleComposer composer = new DefaultStyleComposer(this, DefaultText); + defaults(composer); + } + + /// Defines a paragraph style. + /// The style's key. + /// Sets the style's formatting. + public void Paragraph(ParagraphStyleKey key, Action style) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + ParagraphStyleDefinition definition = new ParagraphStyleDefinition(key); + style(new ParagraphStyleComposer(this, definition)); + ParagraphStyles.Add(definition); + } + + /// Defines a character style. + /// The style's key. + /// Sets the style's formatting. + public void Character(CharacterStyleKey key, Action style) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + CharacterStyleDefinition definition = new CharacterStyleDefinition(key); + style(new CharacterStyleComposer(this, definition)); + CharacterStyles.Add(definition); + } + + internal void Close() => _isOpen = false; + + internal void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A style sheet composer was used after StyleSheet.Create returned."); + } + } +} + +/// Sets the default text formatting of a . +public sealed class DefaultStyleComposer +{ + private readonly TextProperties _text; + + private readonly StyleSheetComposer _owner; + + internal DefaultStyleComposer(StyleSheetComposer owner, TextProperties text) + { + _owner = owner; + _text = text; + } + + /// Sets the font family. + /// The font. + /// This composer. + public DefaultStyleComposer Font(FontFace font) + { + _owner.EnsureOpen(); + _text.Font = font ?? throw new ArgumentNullException(nameof(font)); + return this; + } + + /// Sets the font size. + /// The size; greater than zero. + /// This composer. + public DefaultStyleComposer Size(Length size) + { + _owner.EnsureOpen(); + _text.Size = StyleRanges.FontSize(size); + return this; + } + + /// Sets the text colour. + /// The colour. + /// This composer. + public DefaultStyleComposer Color(Color color) + { + _owner.EnsureOpen(); + _text.Color = color; + return this; + } + + /// + /// Sets the paragraph style of every paragraph that has no style of its own and gets none from its container (a + /// table's text styles, a list's item style). + /// + /// The paragraph style; the style sheet must define it. + /// This composer. + public DefaultStyleComposer ParagraphStyle(ParagraphStyleKey style) + { + _owner.EnsureOpen(); + _owner.DefaultParagraphStyle = style ?? throw new ArgumentNullException(nameof(style)); + return this; + } +} + +/// Sets the formatting of a paragraph style. Unset properties are inherited from BasedOn or the defaults. +public sealed class ParagraphStyleComposer +{ + private readonly ParagraphStyleDefinition _style; + + private readonly StyleSheetComposer _owner; + + internal ParagraphStyleComposer(StyleSheetComposer owner, ParagraphStyleDefinition style) + { + _owner = owner; + _style = style; + } + + /// Inherits every unset property from another paragraph style. + /// The style to inherit from. + /// This composer. + public ParagraphStyleComposer BasedOn(ParagraphStyleKey parent) + { + _owner.EnsureOpen(); + _style.BasedOn = parent ?? throw new ArgumentNullException(nameof(parent)); + return this; + } + + /// Sets the style Word and LibreOffice switch to for the next paragraph when the user presses Enter. + /// The next paragraph's style. + /// This composer. + public ParagraphStyleComposer Next(ParagraphStyleKey next) + { + _owner.EnsureOpen(); + _style.Next = next ?? throw new ArgumentNullException(nameof(next)); + return this; + } + + /// Sets the font family. + /// The font. + /// This composer. + public ParagraphStyleComposer Font(FontFace font) + { + _owner.EnsureOpen(); + _style.Text.Font = font ?? throw new ArgumentNullException(nameof(font)); + return this; + } + + /// Sets the font size. + /// The size; greater than zero. + /// This composer. + public ParagraphStyleComposer Size(Length size) + { + _owner.EnsureOpen(); + _style.Text.Size = StyleRanges.FontSize(size); + return this; + } + + /// Sets the text colour. + /// The colour. + /// This composer. + public ParagraphStyleComposer Color(Color color) + { + _owner.EnsureOpen(); + _style.Text.Color = color; + return this; + } + + /// Sets bold text. + /// to switch off bold inherited from BasedOn. + /// This composer. + public ParagraphStyleComposer Bold(bool value = true) + { + _owner.EnsureOpen(); + _style.Text.Bold = value; + return this; + } + + /// Sets italic text. + /// to switch off italic inherited from BasedOn. + /// This composer. + public ParagraphStyleComposer Italic(bool value = true) + { + _owner.EnsureOpen(); + _style.Text.Italic = value; + return this; + } + + /// Sets the space above the paragraph. + /// The space; not negative. + /// This composer. + public ParagraphStyleComposer SpaceBefore(Length space) + { + _owner.EnsureOpen(); + _style.Paragraph.SpaceBefore = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Sets the space below the paragraph. + /// The space; not negative. + /// This composer. + public ParagraphStyleComposer SpaceAfter(Length space) + { + _owner.EnsureOpen(); + _style.Paragraph.SpaceAfter = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Sets an exact line height. + /// The height of every line; greater than zero. + /// This composer. + public ParagraphStyleComposer LineHeight(Length height) + { + _owner.EnsureOpen(); + _style.Paragraph.LineHeight = new Model.LineHeight(LineHeightRule.Exact, StyleRanges.Positive(height, nameof(height)), 0); + return this; + } + + /// Sets a minimum line height; lines grow with larger text. + /// The minimum height of every line; greater than zero. + /// This composer. + public ParagraphStyleComposer MinimumLineHeight(Length height) + { + _owner.EnsureOpen(); + _style.Paragraph.LineHeight = new Model.LineHeight(LineHeightRule.AtLeast, StyleRanges.Positive(height, nameof(height)), 0); + return this; + } + + /// Sets the line spacing as a multiple of single spacing, for example 1.15. + /// The multiple; between 0.25 and 10. + /// This composer. + public ParagraphStyleComposer LineSpacing(double multiple) + { + _owner.EnsureOpen(); + if (double.IsNaN(multiple) || multiple < 0.25 || multiple > 10) + { + throw new ArgumentOutOfRangeException(nameof(multiple), multiple, "The line spacing must be between 0.25 and 10."); + } + + _style.Paragraph.LineHeight = new Model.LineHeight(LineHeightRule.Proportional, Length.Zero, Math.Round(multiple, 3)); + return this; + } + + /// Sets the alignment. + /// The alignment. + /// This composer. + public ParagraphStyleComposer Alignment(TextAlignment alignment) + { + _owner.EnsureOpen(); + if (!Enum.IsDefined(alignment)) + { + throw new ArgumentOutOfRangeException(nameof(alignment), alignment, "Unknown alignment."); + } + + _style.Paragraph.Alignment = alignment; + return this; + } + + /// Sets the indent at the start of the lines (left in left-to-right text). + /// The indent; not negative. + /// This composer. + public ParagraphStyleComposer IndentStart(Length indent) + { + _owner.EnsureOpen(); + _style.Paragraph.IndentStart = StyleRanges.NotNegative(indent, nameof(indent)); + return this; + } + + /// Sets the indent at the end of the lines (right in left-to-right text). + /// The indent; not negative. + /// This composer. + public ParagraphStyleComposer IndentEnd(Length indent) + { + _owner.EnsureOpen(); + _style.Paragraph.IndentEnd = StyleRanges.NotNegative(indent, nameof(indent)); + return this; + } + + /// Sets the indent of the first line relative to ; negative for a hanging indent. + /// The first-line indent. + /// This composer. + public ParagraphStyleComposer FirstLineIndent(Length indent) + { + _owner.EnsureOpen(); + _style.Paragraph.FirstLineIndent = indent; + return this; + } + + /// Keeps the paragraph on the same page as the next one (for headings). + /// to switch off a setting inherited from BasedOn. + /// This composer. + public ParagraphStyleComposer KeepWithNext(bool value = true) + { + _owner.EnsureOpen(); + _style.Paragraph.KeepWithNext = value; + return this; + } + + /// Keeps all lines of the paragraph on one page. + /// to switch off a setting inherited from BasedOn. + /// This composer. + public ParagraphStyleComposer KeepLinesTogether(bool value = true) + { + _owner.EnsureOpen(); + _style.Paragraph.KeepLinesTogether = value; + return this; + } + + /// Draws a line under the paragraph, for example under a running head. + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// The space between the text and the line; 0 to 31 pt (what DOCX holds), in whole points in DOCX. + /// This composer. + public ParagraphStyleComposer BorderBottom(Length width, Color color, Length space) + { + _owner.EnsureOpen(); + _style.Paragraph.BorderBottom = StyleRanges.Line(width, color, nameof(width)); + _style.Paragraph.BorderBottomSpace = StyleRanges.NotNegative(space, nameof(space)) > 31.Pt() + ? throw new ArgumentOutOfRangeException(nameof(space), space, "The space between text and border is at most 31 pt.") + : space; + return this; + } + + /// + /// Makes the style a heading of the given outline level: it appears in the navigation pane and the table of + /// contents, and ODT writes its paragraphs as headings (text:h). + /// + /// The level, 1 (top) to 9. + /// This composer. + public ParagraphStyleComposer OutlineLevel(int level) + { + _owner.EnsureOpen(); + if (level is < 1 or > 9) + { + throw new ArgumentOutOfRangeException(nameof(level), level, "The outline level must be between 1 and 9."); + } + + _style.Paragraph.OutlineLevel = level; + return this; + } +} + +/// Sets the formatting of a character style. Unset properties are inherited. +public sealed class CharacterStyleComposer +{ + private readonly CharacterStyleDefinition _style; + + private readonly StyleSheetComposer _owner; + + internal CharacterStyleComposer(StyleSheetComposer owner, CharacterStyleDefinition style) + { + _owner = owner; + _style = style; + } + + /// Inherits every unset property from another character style. + /// The style to inherit from. + /// This composer. + public CharacterStyleComposer BasedOn(CharacterStyleKey parent) + { + _owner.EnsureOpen(); + _style.BasedOn = parent ?? throw new ArgumentNullException(nameof(parent)); + return this; + } + + /// Sets the font family. + /// The font. + /// This composer. + public CharacterStyleComposer Font(FontFace font) + { + _owner.EnsureOpen(); + _style.Text.Font = font ?? throw new ArgumentNullException(nameof(font)); + return this; + } + + /// Sets the font size. + /// The size; greater than zero. + /// This composer. + public CharacterStyleComposer Size(Length size) + { + _owner.EnsureOpen(); + _style.Text.Size = StyleRanges.FontSize(size); + return this; + } + + /// Sets the text colour. + /// The colour. + /// This composer. + public CharacterStyleComposer Color(Color color) + { + _owner.EnsureOpen(); + _style.Text.Color = color; + return this; + } + + /// Sets bold text. + /// to switch off inherited bold. + /// This composer. + public CharacterStyleComposer Bold(bool value = true) + { + _owner.EnsureOpen(); + _style.Text.Bold = value; + return this; + } + + /// Sets italic text. + /// to switch off inherited italic. + /// This composer. + public CharacterStyleComposer Italic(bool value = true) + { + _owner.EnsureOpen(); + _style.Text.Italic = value; + return this; + } +} + +/// Range checks for style values; they throw where the value is written. +internal static class StyleRanges +{ + public static Length FontSize(Length size) + { + if (size <= Length.Zero || size > 1638.Pt()) + { + throw new ArgumentOutOfRangeException(nameof(size), size, "The font size must be greater than 0 and at most 1638 pt."); + } + + return size; + } + + public static Length NotNegative(Length value, string parameterName) + { + if (value < Length.Zero) + { + throw new ArgumentOutOfRangeException(parameterName, value, "The value must not be negative."); + } + + return value; + } + + public static BorderLine Line(Length width, Color color, string parameterName) => + width <= Length.Zero || width > 6.Pt() + ? throw new ArgumentOutOfRangeException(parameterName, width, "A line is more than 0 and at most 6 pt wide.") + : new BorderLine(width, color); + + public static Insets Insets(Length top, Length right, Length bottom, Length left) => new Insets( + NotNegative(top, nameof(top)), NotNegative(right, nameof(right)), NotNegative(bottom, nameof(bottom)), NotNegative(left, nameof(left))); + + public static Sides Sides(Sides sides, string parameterName) => + sides == Builder.Sides.None || (sides & ~Builder.Sides.All) != 0 + ? throw new ArgumentException("Name at least one side: Top, Right, Bottom, Left or All.", parameterName) + : sides; + + public static Length Positive(Length value, string parameterName) + { + if (value <= Length.Zero) + { + throw new ArgumentOutOfRangeException(parameterName, value, "The value must be greater than zero."); + } + + return value; + } +} diff --git a/src/TriasDev.Templify.Builder/Styles/Units.cs b/src/TriasDev.Templify.Builder/Styles/Units.cs new file mode 100644 index 00000000..3e984e57 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Styles/Units.cs @@ -0,0 +1,30 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// Extension methods that write lengths the way a design reads: 12.Pt(), 10.5.Pt(), 25.Mm(). +/// +public static class Units +{ + /// A length in points. + /// The length in points. + /// The length. + public static Length Pt(this int points) => Length.FromPoints(points); + + /// A length in points. + /// The length in points. + /// The length. + public static Length Pt(this double points) => Length.FromPoints(points); + + /// A length in millimeters. + /// The length in millimeters. + /// The length. + public static Length Mm(this int millimeters) => Length.FromMillimeters(millimeters); + + /// A length in millimeters. + /// The length in millimeters. + /// The length. + public static Length Mm(this double millimeters) => Length.FromMillimeters(millimeters); +} diff --git a/src/TriasDev.Templify.Builder/TableOfContentsComposer.cs b/src/TriasDev.Templify.Builder/TableOfContentsComposer.cs new file mode 100644 index 00000000..75e76014 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TableOfContentsComposer.cs @@ -0,0 +1,40 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// The look of a table of contents' entries: a paragraph style per level. DOCX keeps entry styles for the whole document +/// (Word's "toc 1" … "toc 9"), so every table of contents in a template uses the same style for a level. +/// +public sealed class TableOfContentsComposer +{ + private readonly int _maxLevel; + + internal TableOfContentsComposer(int maxLevel) + { + _maxLevel = maxLevel; + } + + /// Gets the entry styles set so far, by level. + internal SortedDictionary Levels { get; } = new SortedDictionary(); + + /// Sets the paragraph style of the entries of one level. + /// The level, 1 to the table's deepest level. + /// + /// The entry style; the style sheet must define it, and it must not be a heading (an outline level would list the + /// entries themselves). + /// + /// This composer. + public TableOfContentsComposer Level(int level, ParagraphStyleKey style) + { + ArgumentNullException.ThrowIfNull(style); + if (level < 1 || level > _maxLevel) + { + throw new ArgumentOutOfRangeException(nameof(level), level, $"The level is between 1 and the deepest level listed ({_maxLevel})."); + } + + Levels[level] = style; + return this; + } +} diff --git a/src/TriasDev.Templify.Builder/Tables.cs b/src/TriasDev.Templify.Builder/Tables.cs new file mode 100644 index 00000000..3b77a614 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Tables.cs @@ -0,0 +1,821 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// Vertical alignment of a table cell's content. +public enum CellVerticalAlignment +{ + /// At the top. + Top = 0, + + /// Centered. + Center = 1, + + /// At the bottom. + Bottom = 2, +} + +/// +/// Names a table style: borders, rules, padding and header shading. Table styles are a builder concept: Word table +/// styles have no ODF counterpart, so each writer turns the style into the format's own formatting. +/// +public sealed record TableStyleKey +{ + /// Initializes a table style key. + /// Letters, digits, _ and -, starting with a letter or _. + public TableStyleKey(string id) + { + Id = StyleKeyRules.ValidateId(id, nameof(id)); + } + + /// Gets the id. + public string Id { get; } +} + +/// Sets a table style's borders, rules, padding and header shading. Unset parts are absent. +public sealed class TableStyleComposer +{ + private readonly StyleSheetComposer _owner; + private readonly TableStyleDefinition _style; + + internal TableStyleComposer(StyleSheetComposer owner, TableStyleDefinition style) + { + _owner = owner; + _style = style; + } + + /// Sets the paragraph style of body-row paragraphs that have no style of their own. + /// The paragraph style; the style sheet must define it. + /// This composer. + public TableStyleComposer ParagraphStyle(ParagraphStyleKey style) + { + _owner.EnsureOpen(); + _style.ParagraphStyle = style ?? throw new ArgumentNullException(nameof(style)); + return this; + } + + /// Sets the paragraph style of header-row paragraphs that have no style of their own. + /// The paragraph style; the style sheet must define it. + /// This composer. + public TableStyleComposer HeaderParagraphStyle(ParagraphStyleKey style) + { + _owner.EnsureOpen(); + _style.HeaderParagraphStyle = style ?? throw new ArgumentNullException(nameof(style)); + return this; + } + + /// Sets the border around the table. + /// The line width. + /// The colour. + /// This composer. + public TableStyleComposer OuterBorder(Length width, Color color) => OuterBorder(Sides.All, width, color); + + /// Sets the border on some sides of the table, for example only a rule above it. + /// The sides; not . + /// The line width. + /// The colour. + /// This composer. + public TableStyleComposer OuterBorder(Sides sides, Length width, Color color) + { + _owner.EnsureOpen(); + _style.Outer = _style.Outer.With(StyleRanges.Sides(sides, nameof(sides)), Line(width, color)); + return this; + } + + /// Sets the rules between rows. + /// The line width. + /// The colour. + /// This composer. + public TableStyleComposer RowRule(Length width, Color color) + { + _owner.EnsureOpen(); + _style.RowRule = Line(width, color); + return this; + } + + /// Sets the rules between columns. + /// The line width. + /// The colour. + /// This composer. + public TableStyleComposer ColumnRule(Length width, Color color) + { + _owner.EnsureOpen(); + _style.ColumnRule = Line(width, color); + return this; + } + + /// Sets the rule under the header rows. + /// The line width. + /// The colour. + /// This composer. + public TableStyleComposer HeaderRule(Length width, Color color) + { + _owner.EnsureOpen(); + _style.HeaderRule = Line(width, color); + return this; + } + + /// Sets the background of the header rows. + /// The colour. + /// This composer. + public TableStyleComposer HeaderBackground(Color color) + { + _owner.EnsureOpen(); + _style.HeaderBackground = color; + return this; + } + + /// Sets the space between a cell's edges and its content. + /// Top and bottom. + /// Left and right. + /// This composer. + public TableStyleComposer CellPadding(Length vertical, Length horizontal) => CellPadding(vertical, horizontal, vertical, horizontal); + + /// Sets the space between a cell's edges and its content, per side. + /// The top padding. + /// The right padding. + /// The bottom padding. + /// The left padding. + /// This composer. + public TableStyleComposer CellPadding(Length top, Length right, Length bottom, Length left) + { + _owner.EnsureOpen(); + _style.Padding = StyleRanges.Insets(top, right, bottom, left); + return this; + } + + private static BorderLine Line(Length width, Color color) + { + if (width <= Length.Zero || width > 6.Pt()) + { + throw new ArgumentOutOfRangeException(nameof(width), width, "A line is more than 0 and at most 6 pt wide."); + } + + return new BorderLine(width, color); + } +} + +/// Defines a table's columns. Valid only inside the lambda it is passed to. +public sealed class ColumnsComposer +{ + private readonly List _columns; + + internal ColumnsComposer(List columns) + { + _columns = columns; + } + + /// Adds a column of a fixed width. + /// The width; greater than zero. + /// This composer. + public ColumnsComposer Fixed(Length width) + { + _columns.Add(new ColumnSpec(StyleRanges.Positive(width, nameof(width)), 0)); + return this; + } + + /// Adds a column that takes a share of the width the fixed columns leave: Relative(2) is twice Relative(1). + /// The share; greater than zero. + /// This composer. + public ColumnsComposer Relative(double weight) + { + if (double.IsNaN(weight) || weight <= 0 || weight > 1000) + { + throw new ArgumentOutOfRangeException(nameof(weight), weight, "A relative column weight is greater than 0 and at most 1000."); + } + + _columns.Add(new ColumnSpec(null, weight)); + return this; + } +} + +/// +/// Describes a table: columns, header rows and rows. Valid only inside the lambda passed to +/// . Tables always have a fixed layout: the widths are the definition's, not the content's. +/// +public sealed class TableComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly TableBlock _table; + private bool _isOpen = true; + + internal TableComposer(BuildContext context, LoopScope? scope, TableBlock table) + { + _context = context; + _scope = scope; + _table = table; + } + + /// Applies a table style. + /// The style; the style sheet must define it. + /// This composer. + public TableComposer Style(TableStyleKey style) + { + EnsureOpen(); + _table.Style = style ?? throw new ArgumentNullException(nameof(style)); + return this; + } + + /// Defines the columns. Relative columns share what fixed columns leave of the container's width. + /// Adds the columns. + /// This composer. + public TableComposer Columns(Action columns) + { + ArgumentNullException.ThrowIfNull(columns); + EnsureOpen(); + _table.Columns.Clear(); + columns(new ColumnsComposer(_table.Columns)); + return this; + } + + /// Sets the space after the table. + /// The space; not negative. + /// This composer. + public TableComposer SpaceAfter(Length space) + { + EnsureOpen(); + _table.SpaceAfter = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Sets the space before the table. + /// The space; not negative. + /// This composer. + public TableComposer SpaceBefore(Length space) + { + EnsureOpen(); + _table.SpaceBefore = StyleRanges.NotNegative(space, nameof(space)); + return this; + } + + /// Steps the table in from the start of its frame; the columns share the rest. + /// The distance; not negative and less than the frame (checked when building). + /// This composer. + public TableComposer Indent(Length indent) + { + EnsureOpen(); + // No indent is the table at the frame's start: zero writes nothing, so both formats place it alike. + _table.Indent = StyleRanges.NotNegative(indent, nameof(indent)) == Length.Zero ? null : indent; + return this; + } + + /// Adds a header row, repeated at the top of every page. Header rows come before all other rows. + /// Describes the row's cells. + /// This composer. + public TableComposer HeaderRow(Action row) + { + ArgumentNullException.ThrowIfNull(row); + EnsureOpen(); + if (_table.Rows.Count > _table.Rows.OfType().Count(r => r.IsHeader)) + { + throw new InvalidOperationException("Header rows come before all other rows of a table."); + } + + _table.Rows.Add(ComposeRow(row, isHeader: true)); + return this; + } + + /// Adds a row. + /// Describes the row's cells. + /// This composer. + public TableComposer Row(Action row) + { + ArgumentNullException.ThrowIfNull(row); + EnsureOpen(); + _table.Rows.Add(ComposeRow(row, isHeader: false)); + return this; + } + + /// Repeats rows for every item of a typed collection. + /// The item type. + /// The collection, from . + /// The iteration variable. + /// Describes the rows for each item; it receives the typed item. + /// This composer. + public TableComposer ForEachRow(TemplateCollection collection, string itemName, Action, RowsComposer> rows) + { + ArgumentNullException.ThrowIfNull(rows); + ForEachRow(collection.Untyped, itemName, (item, r) => rows(new LoopItem(item, collection.Naming), r)); + return this; + } + + /// + /// Repeats rows for every item of a collection: {{#foreach item in collection}} and {{/foreach}} in marker + /// rows of their own, which Templify removes when it fills the table. + /// + /// The data path of the collection. + /// The iteration variable (rules as for ). + /// Describes the rows repeated for each item; it receives the item. + /// This composer. + public TableComposer ForEachRow(TemplatePath collection, string itemName, Action rows) + { + EnsureOpen(); + _table.Rows.Add(RowsComposer.ComposeLoop(_context, _scope, collection, itemName, rows)); + return this; + } + + /// Adds rows shown only when a condition holds: {{#if …}} … {{/if}} in marker rows. + /// The condition. + /// Describes the rows. + /// The chain, to add elseif and else rows. + public RowsIfChain RowsIf(Condition condition, Action rows) + { + EnsureOpen(); + return RowsComposer.ComposeConditional(_context, _scope, _table.Rows, condition, rows, () => _isOpen); + } + + internal void Close() => _isOpen = false; + + private TableRowModel ComposeRow(Action row, bool isHeader) => RowsComposer.ComposeRow(_context, _scope, row, isHeader); + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A table composer was used outside the lambda it was passed to."); + } + } +} + +/// +/// Describes body rows inside a row loop or a row conditional: rows, nested row conditionals and loops. Valid only +/// inside the lambda it is passed to. +/// +public sealed class RowsComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly List _rows; + private bool _isOpen = true; + + internal RowsComposer(BuildContext context, LoopScope? scope, List rows) + { + _context = context; + _scope = scope; + _rows = rows; + } + + /// Adds a row. + /// Describes the row's cells. + /// This composer. + public RowsComposer Row(Action row) + { + ArgumentNullException.ThrowIfNull(row); + EnsureOpen(); + _rows.Add(ComposeRow(_context, _scope, row, isHeader: false)); + return this; + } + + /// Repeats rows for every item of a typed collection. + /// The item type. + /// The collection, from . + /// The iteration variable. + /// Describes the rows for each item; it receives the typed item. + /// This composer. + public RowsComposer ForEachRow(TemplateCollection collection, string itemName, Action, RowsComposer> rows) + { + ArgumentNullException.ThrowIfNull(rows); + ForEachRow(collection.Untyped, itemName, (item, r) => rows(new LoopItem(item, collection.Naming), r)); + return this; + } + + /// Repeats rows for every item of a collection, in marker rows of their own. + /// The data path of the collection. + /// The iteration variable. + /// Describes the rows repeated for each item. + /// This composer. + public RowsComposer ForEachRow(TemplatePath collection, string itemName, Action rows) + { + EnsureOpen(); + _rows.Add(ComposeLoop(_context, _scope, collection, itemName, rows)); + return this; + } + + /// Adds rows shown only when a condition holds, in marker rows of their own. + /// The condition. + /// Describes the rows. + /// The chain, to add elseif and else rows. + public RowsIfChain RowsIf(Condition condition, Action rows) + { + EnsureOpen(); + return ComposeConditional(_context, _scope, _rows, condition, rows, () => _isOpen); + } + + internal void Close() => _isOpen = false; + + internal static TableRowModel ComposeRow(BuildContext context, LoopScope? scope, Action row, bool isHeader) + { + TableRowModel model = new TableRowModel(isHeader); + RowComposer composer = new RowComposer(context, scope, model); + row(composer); + composer.Close(); + return model; + } + + internal static List Compose(BuildContext context, LoopScope? scope, Action rows) + { + List items = new List(); + RowsComposer composer = new RowsComposer(context, scope, items); + rows(composer); + composer.Close(); + return items; + } + + internal static TableRowLoop ComposeLoop(BuildContext context, LoopScope? scope, TemplatePath collection, string itemName, Action rows) + { + ArgumentNullException.ThrowIfNull(rows); + if (collection.IsRoot || collection.IsMetadata) + { + throw new ArgumentException("A row loop needs a collection path from the data or from a loop item.", nameof(collection)); + } + + LoopScope.CheckUse(context, scope, collection); + LoopScope loopScope = new LoopScope(LoopScope.ValidateItemName(itemName, scope), LoopScope.ValidateCollection(collection, itemName), scope); + TableRowLoop loop = new TableRowLoop(collection, itemName); + RowsComposer composer = new RowsComposer(context, loopScope, loop.Rows); + rows(new LoopItem(loopScope), composer); + composer.Close(); + return loop; + } + + internal static RowsIfChain ComposeConditional(BuildContext context, LoopScope? scope, List target, Condition condition, Action rows, Func isOpen) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(rows); + BlockComposer.CheckCondition(context, scope, condition); + TableRowConditional conditional = new TableRowConditional(); + conditional.Branches.Add((condition, Compose(context, scope, rows))); + target.Add(conditional); + return new RowsIfChain(context, scope, conditional, isOpen); + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A rows composer was used outside the lambda it was passed to."); + } + } +} + +/// Continues conditional rows: and a last . +public sealed class RowsIfChain +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly TableRowConditional _conditional; + private readonly Func _isOpen; + + internal RowsIfChain(BuildContext context, LoopScope? scope, TableRowConditional conditional, Func isOpen) + { + _context = context; + _scope = scope; + _conditional = conditional; + _isOpen = isOpen; + } + + /// Adds rows for a further condition: {{#elseif …}}. + /// The condition. + /// Describes the rows. + /// This chain. + public RowsIfChain ElseIf(Condition condition, Action rows) + { + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(rows); + EnsureOpen(); + BlockComposer.CheckCondition(_context, _scope, condition); + _conditional.Branches.Add((condition, RowsComposer.Compose(_context, _scope, rows))); + return this; + } + + /// Adds the rows shown when no condition holds: {{#else}}. It ends the chain. + /// Describes the rows. + public void Else(Action rows) + { + ArgumentNullException.ThrowIfNull(rows); + EnsureOpen(); + _conditional.Else = RowsComposer.Compose(_context, _scope, rows); + } + + private void EnsureOpen() + { + if (_conditional.Else != null) + { + throw new InvalidOperationException("The conditional rows already have an else part; nothing can follow it."); + } + + if (!_isOpen()) + { + throw new InvalidOperationException("Conditional rows were continued outside the lambda they were started in."); + } + } +} + +/// Describes the cells of a row. Valid only inside the lambda it is passed to. +public sealed class RowComposer +{ + private readonly BuildContext _context; + private readonly LoopScope? _scope; + private readonly TableRowModel _row; + private bool _isOpen = true; + + internal RowComposer(BuildContext context, LoopScope? scope, TableRowModel row) + { + _context = context; + _scope = scope; + _row = row; + } + + /// Adds a cell with literal text in the inherited paragraph style (row, table style, style sheet default). + /// The text. + /// This composer. + public RowComposer Cell(string text) => Cell(c => c.Paragraph(text)); + + /// Adds a cell with literal text. + /// The paragraph style. + /// The text. + /// This composer. + public RowComposer Cell(ParagraphStyleKey style, string text) => Cell(c => c.Paragraph(style, text)); + + /// Adds a cell holding one value from the data. + /// The data path. + /// This composer. + public RowComposer Cell(TemplatePath value) => Cell(c => c.Paragraph(value)); + + /// Adds a cell holding one value from the data. + /// The paragraph style. + /// The data path. + /// This composer. + public RowComposer Cell(ParagraphStyleKey style, TemplatePath value) => Cell(c => c.Paragraph(style, value)); + + /// Adds a cell with any block content and the cell's own options (span, background, alignment). + /// Describes the cell. + /// This composer. + public RowComposer Cell(Action cell) + { + ArgumentNullException.ThrowIfNull(cell); + EnsureOpen(); + TableCellModel model = new TableCellModel(); + CellComposer composer = new CellComposer(_context, model, _scope); + cell(composer); + composer.Close(); + _row.Cells.Add(model); + return this; + } + + /// + /// Sets the paragraph style of this row's paragraphs that have no style of their own, instead of the table + /// style's text style (for example a totals row). + /// + /// The paragraph style. + /// This composer. + public RowComposer ParagraphStyle(ParagraphStyleKey style) + { + ArgumentNullException.ThrowIfNull(style); + EnsureOpen(); + _row.ParagraphStyle = style; + return this; + } + + /// Lets the row break across pages; by default a row is kept on one page. + /// This composer. + public RowComposer AllowSplit() + { + EnsureOpen(); + _row.AllowSplit = true; + return this; + } + + internal void Close() => _isOpen = false; + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException("A row composer was used outside the lambda it was passed to."); + } + } +} + +/// +/// Describes a table cell: any block content (paragraphs, conditions, loops, nested tables) plus the cell's options. +/// Valid only inside the lambda it is passed to. +/// +public sealed class CellComposer : BlockComposer +{ + private readonly TableCellModel _cell; + + internal CellComposer(BuildContext context, TableCellModel cell, LoopScope? scope) + : base(context, cell.Content, scope) + { + _cell = cell; + } + + /// Lets the cell span several columns. + /// The number of columns; at least 1. + /// This composer. + public CellComposer ColumnSpan(int columns) + { + if (columns < 1) + { + throw new ArgumentOutOfRangeException(nameof(columns), columns, "A cell spans at least one column."); + } + + _cell.Span = columns; + return this; + } + + /// + /// Draws a line of the cell's own on some sides, replacing the table style's line there. On an edge shared with a + /// neighbour both formats draw the wider line. Repeated calls add sides; the last line for a side wins. + /// + /// The sides; not . + /// The line width; more than 0 and at most 6 pt. + /// The colour. + /// This composer. + public CellComposer Border(Sides sides, Length width, Color color) + { + _cell.Borders = (_cell.Borders ?? Edges.None).With(StyleRanges.Sides(sides, nameof(sides)), StyleRanges.Line(width, color, nameof(width))); + return this; + } + + /// Sets the cell's own padding, replacing the table style's for this cell. + /// The top padding. + /// The right padding. + /// The bottom padding. + /// The left padding. + /// This composer. + public CellComposer Padding(Length top, Length right, Length bottom, Length left) + { + _cell.Padding = StyleRanges.Insets(top, right, bottom, left); + return this; + } + + /// Sets the cell's background. + /// The colour. + /// This composer. + public CellComposer Background(Color color) + { + _cell.Background = color; + return this; + } + + /// Sets the vertical alignment of the cell's content. + /// The alignment. + /// This composer. + public CellComposer VerticalAlignment(CellVerticalAlignment alignment) + { + if (!Enum.IsDefined(alignment)) + { + throw new ArgumentOutOfRangeException(nameof(alignment), alignment, "Unknown alignment."); + } + + _cell.VerticalAlignment = alignment; + return this; + } +} + +/// Resolves column widths against the frame a table sits in, and checks that they fit. +internal static class TableLayout +{ + /// The widths of the columns: fixed ones as given, relative ones sharing the rest. + public static Length[] Resolve(IReadOnlyList columns, Length frame) + { + Length fixedSum = columns.Where(c => c.Fixed is not null).Aggregate(Length.Zero, (sum, c) => sum + c.Fixed!.Value); + Length rest = frame - fixedSum; + double weights = columns.Where(c => c.Fixed is null).Sum(c => c.Weight); + Length[] widths = new Length[columns.Count]; + Length assigned = Length.Zero; + int lastRelative = columns.ToList().FindLastIndex(c => c.Fixed is null); + for (int i = 0; i < columns.Count; i++) + { + if (columns[i].Fixed is { } fixedWidth) + { + widths[i] = fixedWidth; + } + else if (i == lastRelative) + { + widths[i] = rest - assigned; + } + else + { + widths[i] = Length.FromPoints(rest.Points * columns[i].Weight / weights); + assigned += widths[i]; + } + } + + return widths; + } + + /// The width a cell's content has: its columns minus its left and right padding. + public static Length CellFrame(Length[] widths, int firstColumn, int span, Insets padding) + { + Length width = Length.Zero; + for (int i = firstColumn; i < Math.Min(firstColumn + span, widths.Length); i++) + { + width += widths[i]; + } + + return width - padding.Left - padding.Right; + } + + /// The padding of a cell: its own, else its table style's, else Word's default. + public static Insets PaddingOf(TableCellModel cell, TableStyleDefinition? style) => cell.Padding ?? style?.Padding ?? TableStyleDefinition.DefaultPadding; + + /// Reports tables whose columns do not fit, whose rows have the wrong number of cells, or whose style is undefined. + public static void Check(IEnumerable blocks, Length frame, StyleSheet styles, BuildContext context) + { + CheckRules(blocks, frame, context); + foreach (TableBlock table in BlockTree.Tables(blocks)) + { + CheckTable(table, frame, styles, context); + } + } + + /// Reports rules of a container that are wider than its frame. + private static void CheckRules(IEnumerable blocks, Length frame, BuildContext context) + { + foreach (RuleBlock rule in BlockTree.InContainer(blocks).OfType().Where(r => r.Width > frame)) + { + context.At(rule); + context.Error(DiagnosticCodes.TableTooWide, $"A rule is {rule.Width} wide, but its container is {frame} wide."); + } + } + + private static void CheckTable(TableBlock table, Length frame, StyleSheet styles, BuildContext context) + { + context.At(table); + if (table.Columns.Count == 0) + { + context.Error(DiagnosticCodes.TableWithoutColumns, "A table has no columns; define them with Columns(...)."); + return; + } + + if (table.Style is { } style && styles.Find(style) == null) + { + context.Error(DiagnosticCodes.UndefinedStyle, $"A table uses the table style '{style.Id}', which the template's style sheet does not define."); + } + + if (table.BoxStyle is { } box && styles.Find(box) == null) + { + context.Error(DiagnosticCodes.UndefinedStyle, $"A box uses the box style '{box.Id}', which the template's style sheet does not define."); + } + + // Compared in twips, the unit written: 160 mm and an A4 frame (210 − 25 − 25 mm) differ by a rounding millipoint. + if (table.Indent is { } indent && indent.Twips >= frame.Twips) + { + context.Error(DiagnosticCodes.TableTooWide, $"A table is indented by {indent}, but its container is only {frame} wide."); + return; + } + + frame = table.ColumnFrame(frame); + Length fixedSum = table.Columns.Where(c => c.Fixed is not null).Aggregate(Length.Zero, (sum, c) => sum + c.Fixed!.Value); + bool hasRelative = table.Columns.Any(c => c.Fixed is null); + if (fixedSum > frame || (hasRelative && fixedSum == frame)) + { + context.Error( + DiagnosticCodes.TableTooWide, + $"A table's fixed columns take {fixedSum} of the {frame} available{(hasRelative ? ", leaving nothing for its relative columns" : string.Empty)}."); + return; + } + + Length[] widths = Resolve(table.Columns, frame); + TableStyleDefinition? tableStyle = styles.Resolve(table); + foreach (TableRowModel row in table.AllRows()) + { + int cells = row.Cells.Sum(c => c.Span); + if (cells != table.Columns.Count) + { + context.Error( + DiagnosticCodes.RowCellCount, + $"A table row spans {cells} column(s), but the table has {table.Columns.Count}."); + continue; + } + + int column = 0; + foreach (TableCellModel cell in row.Cells) + { + // Only padding the definition sets is an error when it takes the whole width: a narrow gutter column + // with Word's default cell margins built before #296 and still does. + Insets padding = PaddingOf(cell, tableStyle); + Length cellFrame = CellFrame(widths, column, cell.Span, padding); + bool ownPadding = cell.Padding != null || (tableStyle != null && tableStyle.Padding != TableStyleDefinition.DefaultPadding); + if (cellFrame <= Length.Zero && ownPadding) + { + context.At(table); + context.Error(DiagnosticCodes.TableTooWide, $"A cell's left and right padding ({padding.Left}, {padding.Right}) take all of its {cellFrame + padding.Left + padding.Right} width."); + } + else + { + Check(cell.Content, cellFrame, styles, context); + } + + column += cell.Span; + } + } + } +} diff --git a/src/TriasDev.Templify.Builder/TemplateBuildException.cs b/src/TriasDev.Templify.Builder/TemplateBuildException.cs new file mode 100644 index 00000000..7fef8106 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateBuildException.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// Thrown by when a template definition is invalid. It lists every problem +/// found, not only the first one. +/// +/// +/// An invalid definition is a programming error, so it is reported by an exception rather than a result object. +/// +public sealed class TemplateBuildException : Exception +{ + /// Initializes a new instance with the problems found. + /// The problems found; at least one. + public TemplateBuildException(IReadOnlyList errors) + : base(CreateMessage(errors)) + { + Errors = errors; + } + + /// Gets every problem found in the definition. + public IReadOnlyList Errors { get; } + + private static string CreateMessage(IReadOnlyList errors) + { + ArgumentNullException.ThrowIfNull(errors); + string count = errors.Count == 1 ? "1 error" : $"{errors.Count} errors"; + return $"The template definition is invalid ({count}):" + Environment.NewLine + + string.Join(Environment.NewLine, errors.Select(e => " " + e)); + } +} diff --git a/src/TriasDev.Templify.Builder/TemplateBuildOptions.cs b/src/TriasDev.Templify.Builder/TemplateBuildOptions.cs new file mode 100644 index 00000000..f2f13941 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateBuildOptions.cs @@ -0,0 +1,29 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// +/// What one build produces: the file format and the document language. +/// +public sealed record TemplateBuildOptions +{ + /// + /// Gets the file format to write: or . + /// + public required TemplateFormat Format { get; init; } + + /// + /// Gets the language of the document. It is written into the document properties; it must be a specific + /// or neutral culture, not the invariant culture. + /// + public required CultureInfo Language { get; init; } + + /// + /// Gets the literal texts the definition reads through ; empty by default. + /// + public ITextCatalog Texts { get; init; } = TextCatalog.Empty; +} diff --git a/src/TriasDev.Templify.Builder/TemplateBuilder.cs b/src/TriasDev.Templify.Builder/TemplateBuilder.cs new file mode 100644 index 00000000..fb334790 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateBuilder.cs @@ -0,0 +1,228 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Model; +using TriasDev.Templify.Builder.Writers; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// +/// Builds templates from s. +/// +public static class TemplateBuilder +{ + /// + /// Builds a template. The same definition and options always give the same bytes on the same runtime and + /// operating system family, so the result can be cached by . + /// + /// The template definition. + /// The format and language to build. + /// The built template. + /// The options name an unsupported format or the invariant culture. + /// The definition is invalid; the exception lists every problem. + /// Thread-safe: concurrent builds share no state. + public static GeneratedTemplate Build(ITemplateDefinition definition, TemplateBuildOptions options) + { + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(options); + ComposedTemplate composed = Compose(definition, options); + DocumentModel model = composed.Model; + byte[] content = options.Format == TemplateFormat.Docx ? DocxWriter.Write(model) : OdtWriter.Write(model); + return new GeneratedTemplate(options.Format, content, composed.Contract, model.Stamp, composed.Context.Warnings); + } + + /// + /// Runs the definition and every check, and returns the model the writers and the JSON export start from; the + /// definition's own style sheet is kept apart (without the injected marker style). + /// + internal static ComposedTemplate Compose(ITemplateDefinition definition, TemplateBuildOptions options) => Compose(definition, options, keyMarkers: false); + + /// Composes a definition; with its texts are key markers (JSON export). + internal static ComposedTemplate Compose(ITemplateDefinition definition, TemplateBuildOptions options, bool keyMarkers) + { + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(options); + ValidateOptions(options); + + BuildContext context = new BuildContext(); + ValidateIdentity(definition.Identity, context); + + TemplateComposer composer = new TemplateComposer(context, new TemplateTexts(context, options.Texts ?? TextCatalog.Empty, options.Language, keyMarkers)); + definition.Compose(composer); + (List body, StyleSheet styles, DocumentInfo info, PageSetup page) = composer.Close(); + StyleInheritance.Apply(body, page, styles, context); + StyleSheet userStyles = styles; + List allBlocks = body.Concat(page.AllBlocks).ToList(); + + if (page.FrameWidth <= Length.Zero) + { + context.Error( + DiagnosticCodes.NoTextFrame, + $"The margins leave no room for text: the page is {page.Size.Width} wide, the side margins take {page.Left + page.Right}."); + } + + if (Writers.Spacers.Used(new IReadOnlyList?[] { body, page.Header, page.Footer, page.FirstHeader, page.FirstFooter }.OfType>())) + { + styles = styles.WithParagraphStyle(BuilderStyles.SpacerDefinition()); + } + + if (BlockTree.HasMarkers(allBlocks) && styles.Find(BuilderStyles.TemplateMarker) == null) + { + styles = styles.WithParagraphStyle(BuilderStyles.DefaultMarkerDefinition()); + } + + context.AddRange(styles.Problems); + foreach (IGrouping family in styles.Fonts.Where(f => f.IsEmbedded).Distinct().GroupBy(f => f.Family, StringComparer.Ordinal).Where(g => g.Count() > 1)) + { + context.Error( + DiagnosticCodes.ConflictingEmbeddedFont, + $"The font family '{family.Key}' is embedded with {family.Count()} different files; a document can embed one file per family."); + } + + CheckStylesAreDefined(allBlocks, styles, context); + TableLayout.Check(allBlocks, page.FrameWidth, styles, context); + CheckTocEntryStyles(allBlocks, styles, context); + context.CurrentLocation = null; + + if (context.Errors.Count > 0) + { + throw new TemplateBuildException(context.Errors); + } + + if (BlockTree.All(allBlocks).OfType().Any()) + { + context.Warn( + DiagnosticCodes.TableOfContentsNotBuilt, + options.Format == TemplateFormat.Docx + ? "The table of contents is a field without a result: Word builds it when it opens the document (fill with UpdateFieldsOnOpen = Auto), and so do converters that refresh indexes on load (for example Stirling-PDF); a plain LibreOffice conversion (soffice --convert-to pdf) does not." + : "The table of contents is an index without entries: converters that refresh indexes on load (for example Stirling-PDF) build it; LibreOffice opening the document and a plain conversion (soffice --convert-to pdf) do not, until a user updates it (Tools > Update > Update All)."); + } + + DataContract contract = DataContract.Collect(allBlocks); + TemplateStamp stamp = TemplateStamp.For(definition.Identity!, contract, options.Language, ComponentVersions.In(allBlocks)); + return new ComposedTemplate(new DocumentModel(body, options.Language, styles, info, stamp, page), userStyles, contract, context); + } + + /// Entry styles of tables of contents: defined, not headings, one per level across the template. + private static void CheckTocEntryStyles(IReadOnlyList blocks, StyleSheet styles, BuildContext context) + { + Dictionary used = new Dictionary(); + foreach (TocBlock toc in BlockTree.All(blocks).OfType()) + { + context.At(toc); + foreach ((int level, ParagraphStyleKey style) in toc.EntryStyles ?? new Dictionary()) + { + if (styles.Find(style) == null) + { + context.Error(DiagnosticCodes.UndefinedStyle, $"A table of contents uses the entry style '{style.Id}' for level {level}, which the template's style sheet does not define."); + } + else if (styles.OutlineLevelOf(style) is int outline) + { + context.Error(DiagnosticCodes.TocEntryStyleIsHeading, $"The entry style '{style.Id}' of level {level} is a heading (outline level {outline}); the table of contents would list its own entries."); + } + + if (used.TryGetValue(level, out ParagraphStyleKey? earlier) && earlier != style) + { + context.Error(DiagnosticCodes.ConflictingTocEntryStyles, $"Two tables of contents give level {level} the entry styles '{earlier.Id}' and '{style.Id}'; DOCX has one entry style per level."); + } + + used.TryAdd(level, style); + } + } + + // DOCX writes "toc N" (id TOCN) for every styled level: a user style must not take that id or name. + foreach (int level in used.Keys) + { + string id = "TOC" + level.ToString(System.Globalization.CultureInfo.InvariantCulture); + string name = "toc " + level.ToString(System.Globalization.CultureInfo.InvariantCulture); + foreach ((string ownId, string ownName) in styles.ParagraphStyles.Select(s => (s.Key.Id, s.Key.DisplayName)).Concat(styles.CharacterStyles.Select(s => (s.Key.Id, s.Key.DisplayName)))) + { + if (string.Equals(ownId, id, StringComparison.OrdinalIgnoreCase)) + { + context.Error(DiagnosticCodes.DuplicateStyleId, $"The style id '{ownId}' is the one Word gives the entries of table-of-contents level {level}, which has an entry style; choose another id."); + } + else if (string.Equals(ownName, name, StringComparison.OrdinalIgnoreCase)) + { + context.Error(DiagnosticCodes.DuplicateStyleName, $"The style name '{ownName}' is the one Word gives the entries of table-of-contents level {level}, which has an entry style; choose another name."); + } + } + } + } + + private static void CheckStylesAreDefined(IReadOnlyList body, StyleSheet styles, BuildContext context) + { + // An undefined inherited style is reported once by the style sheet, not again for every paragraph using it. + HashSet reported = styles.InheritedStyleUses().Where(u => styles.Find(u.Key) == null).Select(u => "p:" + u.Key.Id).ToHashSet(StringComparer.Ordinal); + foreach (ParagraphBlock paragraph in BlockTree.Paragraphs(body)) + { + context.At(paragraph); + if (paragraph.List is { } item) + { + ListStyleDefinition? list = styles.Find(item.Style); + if (list == null && reported.Add("l:" + item.Style.Id)) + { + context.Error(DiagnosticCodes.UndefinedStyle, $"A list uses the list style '{item.Style.Id}', which the template's style sheet does not define."); + } + else if (list != null && !list.Levels.ContainsKey(item.Level) && reported.Add($"lv:{item.Style.Id}:{item.Level}")) + { + context.Error(DiagnosticCodes.UndefinedListLevel, $"A list item uses level {item.Level}, which the list style '{item.Style.Id}' does not define."); + } + else if (list?.ItemStyle is { } itemStyle && styles.Find(itemStyle) == null && reported.Add("p:" + itemStyle.Id)) + { + context.Error(DiagnosticCodes.UndefinedStyle, $"The list style '{item.Style.Id}' uses the item style '{itemStyle.Id}', which the template's style sheet does not define."); + } + } + + if (paragraph.Style is { } style && styles.Find(style) == null && reported.Add("p:" + style.Id)) + { + context.Error( + DiagnosticCodes.UndefinedStyle, + $"A paragraph uses the style '{style.Id}' (\"{style.DisplayName}\"), which the template's style sheet does not define."); + } + + foreach (Inline inline in InlineConditional.Descendants(paragraph.Inlines)) + { + if (inline.Style is { } characterStyle && styles.Find(characterStyle) == null && reported.Add("c:" + characterStyle.Id)) + { + context.Error( + DiagnosticCodes.UndefinedStyle, + $"Text uses the character style '{characterStyle.Id}' (\"{characterStyle.DisplayName}\"), which the template's style sheet does not define."); + } + } + } + } + + private static void ValidateOptions(TemplateBuildOptions options) + { + if (options.Format is not (TemplateFormat.Docx or TemplateFormat.Odt)) + { + throw new ArgumentException( + $"Unsupported template format '{options.Format}'. Use TemplateFormat.Docx or TemplateFormat.Odt.", + nameof(options)); + } + + if (options.Language is null || string.IsNullOrEmpty(options.Language.Name)) + { + throw new ArgumentException( + "The document language must be a named culture (for example \"de-DE\" or \"en\"), not the invariant culture.", + nameof(options)); + } + } + + private static void ValidateIdentity(TemplateIdentity? identity, BuildContext context) + { + if (identity is null) + { + context.Error(DiagnosticCodes.MissingIdentity, "The template definition has no identity (ITemplateDefinition.Identity is null)."); + } + else if (string.IsNullOrWhiteSpace(identity.Id)) + { + context.Error(DiagnosticCodes.EmptyIdentityId, "The template identity has an empty id."); + } + } +} + +/// A composed and checked definition: the model, the definition's own style sheet, the contract and the diagnostics. +internal sealed record ComposedTemplate(DocumentModel Model, StyleSheet UserStyles, DataContract Contract, BuildContext Context); diff --git a/src/TriasDev.Templify.Builder/TemplateCheck.cs b/src/TriasDev.Templify.Builder/TemplateCheck.cs new file mode 100644 index 00000000..0946aa45 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateCheck.cs @@ -0,0 +1,116 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// Whether a stored template still works with the current data. +public enum TemplateCheckStatus +{ + /// No problems. + Ok = 0, + + /// The template works, but is outdated or of unknown origin (only warnings). + Warning = 1, + + /// The template will not fill correctly (at least one error). + Broken = 2, +} + +/// How serious a problem of a check is. +public enum TemplateCheckSeverity +{ + /// The template works, but should be looked at. + Warning = 0, + + /// The template will not fill correctly. + Error = 1, +} + +/// One problem a check found. +/// The code: TB93xx for documents (see the developer docs), the build's codes for JSON definitions. +/// How serious it is. +/// What is wrong, in English. +public sealed record TemplateCheckProblem(string Code, TemplateCheckSeverity Severity, string Message) +{ + /// Gets the data path concerned, as the template writes it (with its loop variable names); null when none. + public string? DataPath { get; init; } + + /// Gets where the problem is: the engine's location in a document, the JSON pointer in a definition; null when unknown. + public string? Location { get; init; } + + /// + public override string ToString() => $"{Code}: {Message}"; +} + +/// What to check a stored template against. +public sealed record TemplateCheckOptions +{ + /// Gets the current data: every path a template may read. + public required DataCatalog Data { get; init; } + + /// Gets the identity the template should have (the current definition); null to leave the stamp's identity unjudged. + public TemplateIdentity? Expected { get; init; } + + /// + /// Gets the current components, to compare a copy's component versions with; null to leave them unjudged. Every + /// versioned component the host uses should be registered. + /// + public ComponentCatalog? Components { get; init; } +} + +/// The result of or . +public sealed class TemplateCheckResult +{ + internal TemplateCheckResult(TemplateFormat format, TemplateStamp? stamp, IReadOnlyList problems) + { + Format = format; + Stamp = stamp; + Problems = problems; + Status = problems.Any(p => p.Severity == TemplateCheckSeverity.Error) ? TemplateCheckStatus.Broken + : problems.Count > 0 ? TemplateCheckStatus.Warning + : TemplateCheckStatus.Ok; + } + + /// Gets the status: with any error, with only warnings. + public TemplateCheckStatus Status { get; } + + /// Gets the problems, errors first. + public IReadOnlyList Problems { get; } + + /// Gets the file format; for a JSON definition or an unreadable file. + public TemplateFormat Format { get; } + + /// Gets the builder's stamp of a document; null when it has none, and for a JSON definition. + public TemplateStamp? Stamp { get; } +} + +/// The codes of (TB9304 and TB9305 also of ). +internal static class CheckCodes +{ + /// The template's syntax is broken, or the file is not a template. + public const string Syntax = "TB9300"; + + /// The template reads a path the data does not have. + public const string UnknownPath = "TB9301"; + + /// Filling with the data's shape fails, for example a loop over a value. + public const string WrongKind = "TB9302"; + + /// The template has no builder stamp. + public const string NoStamp = "TB9303"; + + /// The stamp names another template. + public const string OtherTemplate = "TB9304"; + + /// The stamp names an older version of the template. + public const string OlderVersion = "TB9305"; + + /// A component the template was built from is at an older version, or no longer registered. + public const string OlderComponent = "TB9306"; + + /// A JSON Patch could not be applied to a definition (malformed, missing path, failed test). + public const string PatchFailed = "TB9207"; +} + diff --git a/src/TriasDev.Templify.Builder/TemplateComposer.cs b/src/TriasDev.Templify.Builder/TemplateComposer.cs new file mode 100644 index 00000000..61c6f278 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateComposer.cs @@ -0,0 +1,204 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder; + +/// +/// Describes a whole template. Passed to ; valid only during that call. +/// +public sealed class TemplateComposer +{ + private readonly BuildContext _context; + + /// The build's diagnostics (for the JSON importer, which reports through it). + internal BuildContext Context => _context; + private readonly List _body = new List(); + private readonly DocumentPropertiesComposer _properties = new DocumentPropertiesComposer(); + private StyleSheet? _styles; + private PageSetupBuilder? _page; + private bool _isOpen = true; + + internal TemplateComposer(BuildContext context, TemplateTexts texts) + { + context.Texts = texts; + _context = context; + Texts = texts; + } + + /// + /// Shares an object with the components of this definition (), for example the + /// theme, so a component needs only data paths as parameters and can be registered for JSON. + /// + /// The type components ask for. + /// The object. + /// This composer. + public TemplateComposer Share(T value) + where T : class + { + ArgumentNullException.ThrowIfNull(value); + _context.Shared[typeof(T)] = value; + return this; + } + + /// Gets the texts of the build's language: template.Texts["invoiceTitle"]. + public TemplateTexts Texts { get; } + + /// + /// Gets the root of the data the template is filled with. Append segments with the indexer: + /// template.Data["customer"]. + /// + public TemplatePath Data => default; + + /// + /// Gets the root of the data, typed by a C# model of it: paths are chosen with + /// and named as the data's JSON (camelCase by default; + /// wins). + /// + /// The data's type. + /// How C# property names become data names; null for camelCase. + /// The root. + public TemplatePath DataAs(System.Text.Json.JsonNamingPolicy? naming = null) => new TemplatePath(default, naming); + + /// Sets the template's named styles. Call it once. + /// The style sheet, typically built from the product's theme. + /// This composer. + public TemplateComposer Styles(StyleSheet styles) + { + ArgumentNullException.ThrowIfNull(styles); + EnsureOpen(); + if (_styles != null) + { + _context.Error(DiagnosticCodes.StylesAlreadySet, "TemplateComposer.Styles was called more than once; a template has one style sheet."); + return this; + } + + _styles = styles; + return this; + } + + /// + /// Describes the page: size, margins, header and footer. Call it once; without it a template is A4 with 25 mm + /// margins and no header or footer. + /// + /// Describes the page. + /// This composer. + public TemplateComposer Page(Action page) + { + ArgumentNullException.ThrowIfNull(page); + EnsureOpen(); + if (_page != null) + { + _context.Error(DiagnosticCodes.PageAlreadySet, "TemplateComposer.Page was called more than once; a template has one page setup."); + return this; + } + + _page = new PageSetupBuilder(); + PageComposer composer = new PageComposer(_context, _page); + page(composer); + composer.Close(); + return this; + } + + /// Sets the standard document properties: title, author, subject. + /// Sets the properties. Several calls combine; a later value replaces an earlier one. + /// This composer. + public TemplateComposer Properties(Action properties) + { + ArgumentNullException.ThrowIfNull(properties); + EnsureOpen(); + properties(_properties); + return this; + } + + /// Describes the document body. Several calls append to the body in order. + /// Describes the body's blocks. + /// This composer. + public TemplateComposer Content(Action content) + { + ArgumentNullException.ThrowIfNull(content); + EnsureOpen(); + BlockComposer composer = new BlockComposer(_context, _body, null); + content(composer); + composer.Close(); + return this; + } + + /// Ends composing and returns what was composed. + internal (List Body, StyleSheet Styles, DocumentInfo Info, PageSetup Page) Close() + { + _isOpen = false; + _properties.Close(); + return (_body, _styles ?? StyleSheet.Empty, _properties.ToInfo(), (_page ?? new PageSetupBuilder()).ToSetup()); + } + + private void EnsureOpen() + { + if (!_isOpen) + { + throw new InvalidOperationException( + "The template composer was used after ITemplateDefinition.Compose returned. It is valid only during that call."); + } + } +} + +/// Sets the standard document properties. Valid only during . +public sealed class DocumentPropertiesComposer +{ + private string? _title; + private string? _author; + private string? _subject; + private bool _isOpen = true; + + internal DocumentPropertiesComposer() + { + } + + /// Sets the document title. + /// The title. + /// This composer. + public DocumentPropertiesComposer Title(string title) + { + _title = Validate(title, nameof(title)); + return this; + } + + /// Sets the author (creator). + /// The author, for example the product or the company. + /// This composer. + public DocumentPropertiesComposer Author(string author) + { + _author = Validate(author, nameof(author)); + return this; + } + + /// Sets the subject. + /// The subject. + /// This composer. + public DocumentPropertiesComposer Subject(string subject) + { + _subject = Validate(subject, nameof(subject)); + return this; + } + + internal void Close() => _isOpen = false; + + internal DocumentInfo ToInfo() => new DocumentInfo(_title, _author, _subject); + + private string Validate(string value, string parameterName) + { + ArgumentNullException.ThrowIfNull(value, parameterName); + if (!_isOpen) + { + throw new InvalidOperationException("The document properties composer was used after ITemplateDefinition.Compose returned."); + } + + if (value.Any(c => char.IsControl(c) && c is not ('\t' or '\n' or '\r'))) + { + throw new ArgumentException("A document property must not contain control characters.", parameterName); + } + + return value; + } +} diff --git a/src/TriasDev.Templify.Builder/TemplateDataAttribute.cs b/src/TriasDev.Templify.Builder/TemplateDataAttribute.cs new file mode 100644 index 00000000..9cad80a9 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateDataAttribute.cs @@ -0,0 +1,17 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// Adds a data type to the typed path generator. Types used in and every type +/// reachable from them are generated anyway; this attribute is for types that are not, for example the parameter types of +/// components in a component library: [assembly: TemplateData(typeof(Address))]. +/// +/// The data type. +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] +public sealed class TemplateDataAttribute(Type type) : Attribute +{ + /// Gets the data type. + public Type Type { get; } = type; +} diff --git a/src/TriasDev.Templify.Builder/TemplateIdentity.cs b/src/TriasDev.Templify.Builder/TemplateIdentity.cs new file mode 100644 index 00000000..465a950a --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateIdentity.cs @@ -0,0 +1,11 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// The identity of a template definition: a stable id chosen by the product and the version of the definition. +/// +/// A stable, non-empty id, for example invoice. +/// The version of the definition. Increase it when the template changes. +public sealed record TemplateIdentity(string Id, int Version); diff --git a/src/TriasDev.Templify.Builder/TemplateInspector.cs b/src/TriasDev.Templify.Builder/TemplateInspector.cs new file mode 100644 index 00000000..a9db1563 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateInspector.cs @@ -0,0 +1,263 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.IO.Compression; +using System.Xml.Linq; +using DocumentFormat.OpenXml.CustomProperties; +using DocumentFormat.OpenXml.Packaging; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// What found in a template. +/// The file format; for anything else. +/// The builder's stamp; null when there is none. +public sealed record TemplateInspection(TemplateFormat Format, TemplateStamp? Stamp); + +/// +/// Reads the builder's stamp from a template and checks stored templates (copies and JSON definitions) against the +/// current data. +/// +public static class TemplateInspector +{ + /// Reads a template's format and stamp. + /// The template; it is read, not changed. + /// The format and the stamp. + public static TemplateInspection Inspect(Stream template) + { + ArgumentNullException.ThrowIfNull(template); + byte[] bytes = ReadAll(template); + TemplateFormat format = DetectFormat(bytes); + return new TemplateInspection(format, ReadStamp(bytes, format)); + } + + /// + /// Checks a stored template (a DOCX or ODT copy, typically edited by a user) against the current data: its syntax, + /// every path it reads (against the catalogue, so a copy may read fields the standard template does not), a trial + /// fill, and its stamp (identity, version, component versions). + /// + /// The template; it is read, not changed. + /// The current data catalogue, and the identity and components to compare the stamp with. + /// The status and the problems. + public static TemplateCheckResult Check(Stream template, TemplateCheckOptions options) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(options); + byte[] bytes = ReadAll(template); + TemplateFormat format = DetectFormat(bytes); + TemplateStamp? stamp = ReadStamp(bytes, format); + List problems = new List(); + + if (format == TemplateFormat.Unknown) + { + problems.Add(new TemplateCheckProblem(CheckCodes.Syntax, TemplateCheckSeverity.Error, "The file is not a DOCX or ODT template.")); + return new TemplateCheckResult(format, stamp, problems); + } + + CatalogueCheck catalogue = options.Data.CheckTemplate(bytes); + ValidationResult validation = catalogue.Validation; + foreach (ValidationError error in validation.Errors.Where(e => e.Type != ValidationErrorType.MissingVariable)) + { + problems.Add(new TemplateCheckProblem(CheckCodes.Syntax, TemplateCheckSeverity.Error, error.Message) { Location = error.Location }); + } + + foreach (string path in validation.MissingVariables.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)) + { + problems.Add(new TemplateCheckProblem(CheckCodes.UnknownPath, TemplateCheckSeverity.Error, $"The data has no '{path}'.") { DataPath = path }); + } + + foreach (ValidationWarning warning in validation.Warnings.Where(w => w.Type == ValidationWarningType.MissingConditionVariable)) + { + foreach (string path in DataCatalog.MissingNames(new ValidationResult { Warnings = [warning] })) + { + problems.Add(new TemplateCheckProblem(CheckCodes.UnknownPath, TemplateCheckSeverity.Error, $"A condition reads '{path}', which the data does not have.") { DataPath = path, Location = warning.Location }); + } + } + + foreach (string path in catalogue.FillMissing.Order(StringComparer.Ordinal)) + { + problems.Add(new TemplateCheckProblem(CheckCodes.UnknownPath, TemplateCheckSeverity.Error, $"The data has no '{path}'.") { DataPath = path }); + } + + if (catalogue.FillError is { } fillError) + { + problems.Add(new TemplateCheckProblem(CheckCodes.WrongKind, TemplateCheckSeverity.Error, fillError)); + } + + JudgeStamp(stamp, options, problems); + return new TemplateCheckResult(format, stamp, problems); + } + + /// + /// Checks a stored JSON definition against the current data: it must import with the catalogue (every data path + /// known and of the right kind) and, with , build. Registered components are used at their + /// current version, so a definition is never outdated by a component. + /// + /// The JSON definition. + /// The import options; is required. + /// The options to build with, to find what only the build checks; null to check the import only. + /// The identity the definition should have; null to leave it unjudged. + /// The status and the problems, located by JSON pointer. + /// The import options have no data catalogue. + public static TemplateCheckResult CheckDefinition(string json, Json.TemplateJsonImportOptions import, TemplateBuildOptions? build = null, TemplateIdentity? expected = null) + { + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(import); + if (import.Data is null) + { + throw new ArgumentException("Checking a definition needs the current data catalogue (TemplateJsonImportOptions.Data).", nameof(import)); + } + + List problems = new List(); + ITemplateDefinition definition; + try + { + definition = Json.TemplateJson.Import(json, import); + } + catch (TemplateBuildException exception) + { + problems.AddRange(exception.Errors.Select(AsProblem)); + return new TemplateCheckResult(TemplateFormat.Unknown, null, problems); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) + { + problems.Add(AsProblem(exception)); + return new TemplateCheckResult(TemplateFormat.Unknown, null, problems); + } + + if (build is not null) + { + try + { + TemplateBuilder.Build(definition, build); + } + catch (TemplateBuildException exception) + { + problems.AddRange(exception.Errors.Select(AsProblem)); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) + { + problems.Add(AsProblem(exception)); + } + } + + if (expected is not null && definition.Identity is { } identity) + { + JudgeIdentity(identity.Id, identity.Version, expected, problems); + } + + return new TemplateCheckResult(TemplateFormat.Unknown, null, problems); + } + + /// + /// An exception the reader or the build lets through for input it cannot take (an XML-invalid character in a text, + /// a lone surrogate), as a problem: checks report, they do not throw. + /// + internal static TemplateCheckProblem AsProblem(Exception exception) => + new TemplateCheckProblem(DiagnosticCodes.InvalidJsonValue, TemplateCheckSeverity.Error, exception.Message); + + internal static TemplateCheckProblem AsProblem(BuildDiagnostic error) => + new TemplateCheckProblem(error.Code, TemplateCheckSeverity.Error, error.Message) { Location = error.Location, DataPath = error.DataPath }; + + private static void JudgeIdentity(string id, int version, TemplateIdentity expected, List problems) + { + if (!string.Equals(id, expected.Id, StringComparison.Ordinal)) + { + problems.Add(new TemplateCheckProblem(CheckCodes.OtherTemplate, TemplateCheckSeverity.Warning, $"The template comes from '{id}', not from '{expected.Id}'.")); + } + else if (version < expected.Version) + { + problems.Add(new TemplateCheckProblem(CheckCodes.OlderVersion, TemplateCheckSeverity.Warning, $"The template comes from version {version} of '{expected.Id}'; the current version is {expected.Version}.")); + } + } + + private static void JudgeStamp(TemplateStamp? stamp, TemplateCheckOptions options, List problems) + { + if (stamp is null) + { + problems.Add(new TemplateCheckProblem(CheckCodes.NoStamp, TemplateCheckSeverity.Warning, "The template has no builder stamp: its origin is unknown (edited in an application that dropped it, or not built by the builder).")); + return; + } + + if (options.Expected is { } expected) + { + JudgeIdentity(stamp.TemplateId, stamp.Version, expected, problems); + } + + if (options.Components is { } components) + { + IReadOnlyDictionary current = components.Versions(); + foreach ((string name, int version) in stamp.Components) + { + if (!current.TryGetValue(name, out int now)) + { + problems.Add(new TemplateCheckProblem(CheckCodes.OlderComponent, TemplateCheckSeverity.Warning, $"The template was built with the component {name} (version {version}), which is no longer registered.")); + } + else if (version < now) + { + problems.Add(new TemplateCheckProblem(CheckCodes.OlderComponent, TemplateCheckSeverity.Warning, $"The template was built with version {version} of the component {name}; the current version is {now}.")); + } + } + } + } + + /// The builder's document properties of a package (name → value). + internal static Dictionary ReadProperties(byte[] bytes, TemplateFormat format) + { + Dictionary properties = new Dictionary(StringComparer.Ordinal); + try + { + if (format == TemplateFormat.Docx) + { + using MemoryStream stream = new MemoryStream(bytes, writable: false); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + foreach (CustomDocumentProperty property in document.CustomFilePropertiesPart?.Properties?.Elements() ?? []) + { + if (property.Name?.Value is { } name && name.StartsWith(TemplateStamp.PropertyPrefix, StringComparison.Ordinal)) + { + properties[name] = property.InnerText; + } + } + } + else if (format == TemplateFormat.Odt) + { + XNamespace meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; + using MemoryStream stream = new MemoryStream(bytes, writable: false); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + if (archive.GetEntry("meta.xml") is { } entry) + { + using Stream metaStream = entry.Open(); + foreach (XElement property in XDocument.Load(metaStream).Descendants(meta + "user-defined")) + { + if ((string?)property.Attribute(meta + "name") is { } name && name.StartsWith(TemplateStamp.PropertyPrefix, StringComparison.Ordinal)) + { + properties[name] = property.Value; + } + } + } + } + } + catch (Exception exception) when (exception is InvalidDataException or System.Xml.XmlException or OpenXmlPackageException or IOException) + { + // A damaged package has no readable stamp; Check reports its syntax through the engine. + } + + return properties; + } + + private static TemplateStamp? ReadStamp(byte[] bytes, TemplateFormat format) => + format == TemplateFormat.Unknown ? null : TemplateStamp.FromProperties(ReadProperties(bytes, format)); + + private static TemplateFormat DetectFormat(byte[] bytes) + { + using MemoryStream stream = new MemoryStream(bytes, writable: false); + return TemplateProcessor.DetectFormat(stream); + } + + private static byte[] ReadAll(Stream stream) + { + using MemoryStream buffer = new MemoryStream(); + stream.CopyTo(buffer); + return buffer.ToArray(); + } +} diff --git a/src/TriasDev.Templify.Builder/TemplatePath.cs b/src/TriasDev.Templify.Builder/TemplatePath.cs new file mode 100644 index 00000000..6b699d87 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplatePath.cs @@ -0,0 +1,292 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder; + +/// +/// A path into the data a template is filled with, for example customer.address.city. Paths are values: +/// they are built and checked in code and written into the template as Templify placeholders. +/// +/// +/// Start from (or ) and append segments with the indexer: +/// template.Data["customer"]["address.city"]. Each segment consists of letters, digits and _, as +/// Templify's placeholder grammar requires, optionally with one list index from 0 to 999: items[0].name. An invalid segment throws where the path is +/// written, so the stack trace points at the line in the definition. +/// +public readonly partial struct TemplatePath : IEquatable, IFormattable +{ + private readonly string? _value; + + private TemplatePath(string value, LoopScope? scope = null, bool isMetadata = false) + { + _value = value; + Scope = scope; + IsMetadata = isMetadata; + } + + /// Gets a value indicating whether this is the empty path (the root of the data). + internal bool IsRoot => _value is null; + + /// Gets the loop whose iteration variable this path starts from; null for a path from the data's root. + internal LoopScope? Scope { get; } + + /// Gets a value indicating whether this is loop metadata (@index, @first, …) of . + internal bool IsMetadata { get; } + + /// The path of a loop's iteration variable, for example line. + internal static TemplatePath ForItem(LoopScope scope) => new TemplatePath(scope.ItemName, scope); + + /// A loop metadata path, for example @index, of the innermost loop . + internal static TemplatePath ForMetadata(LoopScope scope, string name) => new TemplatePath("@" + name, scope, isMetadata: true); + + /// + /// Appends one or more dot-separated segments, for example path["address.city"]. + /// + /// The segments to append, separated by dots. + /// A segment is empty, contains characters other than letters, digits and _, or has an index other than one [0] … [999]. + public TemplatePath this[string relative] + { + get + { + ArgumentNullException.ThrowIfNull(relative); + if (IsMetadata) + { + throw new InvalidOperationException($"Loop metadata ({_value}) has no properties."); + } + + string[] segments = relative.Split('.'); + foreach (string segment in segments) + { + ValidateSegment(segment, relative); + } + + if (_value is null && string.Equals(segments[0], "this", StringComparison.Ordinal)) + { + throw new ArgumentException( + "'this' cannot start a data path: Templify reads {{this}} as the current loop item.", + nameof(relative)); + } + + return new TemplatePath(_value is null ? relative : _value + "." + relative, Scope); + } + } + + /// + /// Creates a path from the root of the data, for example TemplatePath.Root("customer.name"). + /// + /// The dot-separated segments of the path. + /// The path. + public static TemplatePath Root(string path) => default(TemplatePath)[path]; + + /// Gets a condition that holds when the path exists in the data: path exists. + public Condition Exists => new PostfixCondition(ForCondition(), "exists"); + + /// Gets a condition that holds when the value is missing, null, an empty text or an empty collection: path is empty. + public Condition IsEmpty => new PostfixCondition(ForCondition(), "is empty"); + + /// Gets a condition that holds when the value is not empty: path is not empty. + public Condition IsNotEmpty => new PostfixCondition(ForCondition(), "is not empty"); + + /// The value equals a text: path = "value" (ordinal, case-sensitive). + /// The text. + /// The condition. + public Condition Eq(string value) => Compare("=", ConditionText.String(value, nameof(value))); + + /// The value equals a number: path = 3 (numeric across number types). + /// The number. + /// The condition. + public Condition Eq(double value) => Compare("=", ConditionText.Number(value, nameof(value))); + + /// The value differs from a text: path != "value". + /// The text. + /// The condition. + public Condition NotEq(string value) => Compare("!=", ConditionText.String(value, nameof(value))); + + /// The value differs from a number: path != 3. + /// The number. + /// The condition. + public Condition NotEq(double value) => Compare("!=", ConditionText.Number(value, nameof(value))); + + /// The value is greater than a number: path > 3. + /// The number. + /// The condition. + public Condition Gt(double value) => Compare(">", ConditionText.Number(value, nameof(value))); + + /// The value is greater than or equal to a number: path >= 3. + /// The number. + /// The condition. + public Condition Ge(double value) => Compare(">=", ConditionText.Number(value, nameof(value))); + + /// The value is less than a number: path < 3. + /// The number. + /// The condition. + public Condition Lt(double value) => Compare("<", ConditionText.Number(value, nameof(value))); + + /// The value is less than or equal to a number: path <= 3. + /// The number. + /// The condition. + public Condition Le(double value) => Compare("<=", ConditionText.Number(value, nameof(value))); + + /// The value is one of several texts: path in ("a", "b"). + /// The texts; at least one. + /// The condition. + public Condition In(params string[] values) + { + ArgumentNullException.ThrowIfNull(values); + if (values.Length == 0) + { + throw new ArgumentException("In needs at least one value.", nameof(values)); + } + + return new InCondition(ForCondition(), values.Select(v => ConditionText.String(v, nameof(values))).ToArray()); + } + + /// The text contains a text, or the collection contains an item: path contains "x" (ordinal). + /// The text to look for. + /// The condition. + public Condition Contains(string value) => Compare("contains", ConditionText.String(value, nameof(value))); + + /// The text starts with a text: path startswith "x" (ordinal). + /// The prefix. + /// The condition. + public Condition StartsWith(string value) => Compare("startswith", ConditionText.String(value, nameof(value))); + + /// The text ends with a text: path endswith "x" (ordinal). + /// The suffix. + /// The condition. + public Condition EndsWith(string value) => Compare("endswith", ConditionText.String(value, nameof(value))); + + /// The value equals another value: a = b (numeric when both are numbers, else ordinal text). Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Eq(TemplatePath other) => ComparePath("=", other); + + /// The value differs from another value: a != b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition NotEq(TemplatePath other) => ComparePath("!=", other); + + /// The value is greater than another value: a > b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Gt(TemplatePath other) => ComparePath(">", other); + + /// The value is at least another value: a >= b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Ge(TemplatePath other) => ComparePath(">=", other); + + /// The value is less than another value: a < b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Lt(TemplatePath other) => ComparePath("<", other); + + /// The value is at most another value: a <= b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Le(TemplatePath other) => ComparePath("<=", other); + + /// The value contains another value, or the collection contains it: a contains b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition Contains(TemplatePath other) => ComparePath("contains", other); + + /// The value starts with another value: a startswith b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition StartsWith(TemplatePath other) => ComparePath("startswith", other); + + /// The value ends with another value: a endswith b. Both paths go into the data contract. + /// The path of the other value. + /// The condition. + public Condition EndsWith(TemplatePath other) => ComparePath("endswith", other); + + /// + /// The value is truthy: not null, not false, not an empty or blank text, not zero, not an empty + /// collection ({{#if path}}). + /// + /// The path. + public static implicit operator Condition(TemplatePath path) => new TruthCondition(path.ForCondition()); + + /// The value is not truthy: not path. + /// The path. + /// The condition. + public static Condition operator !(TemplatePath path) => !(Condition)path; + + /// Both values are truthy: a and b. (Mixed with a , its operator applies.) + /// The first path. + /// The second path. + /// The condition. + public static Condition operator &(TemplatePath left, TemplatePath right) => (Condition)left & (Condition)right; + + /// At least one value is truthy: a or b. + /// The first path. + /// The second path. + /// The condition. + public static Condition operator |(TemplatePath left, TemplatePath right) => (Condition)left | (Condition)right; + + /// Returns the path as Templify writes it, for example customer.address.city. + /// The dotted path; empty for the root. + public override string ToString() => _value ?? string.Empty; + + /// Gets the dotted path, for messages built by interpolation (where the path itself formats as its placeholder). + internal string Text => ToString(); + + /// + /// A path in an interpolated string ($"Report {path}") is written as its placeholder, {{report.number}}, + /// so the literal-text check (TB1002) reports it instead of the document printing the path's name. + /// + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => "{{" + ToString() + "}}"; + + /// + public bool Equals(TemplatePath other) => string.Equals(_value, other._value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is TemplatePath other && Equals(other); + + /// + public override int GetHashCode() => _value is null ? 0 : StringComparer.Ordinal.GetHashCode(_value); + + /// Compares two paths. + /// The first path. + /// The second path. + /// when both paths are equal. + public static bool operator ==(TemplatePath left, TemplatePath right) => left.Equals(right); + + /// Compares two paths. + /// The first path. + /// The second path. + /// when the paths differ. + public static bool operator !=(TemplatePath left, TemplatePath right) => !left.Equals(right); + + private Condition Compare(string op, string literal) => new ComparisonCondition(ForCondition(), op, literal); + + private Condition ComparePath(string op, TemplatePath other) => new PathComparisonCondition(ForCondition(), op, other.ForCondition()); + + private TemplatePath ForCondition() + { + if (IsRoot) + { + throw new InvalidOperationException("A condition needs a data path; the root of the data (template.Data) cannot be tested."); + } + + ConditionText.CheckPath(this, "path"); + return this; + } + + private static void ValidateSegment(string segment, string relative) + { + if (!SegmentPattern().IsMatch(segment)) + { + throw new ArgumentException( + $"'{relative}' is not a valid data path: each dot-separated segment must consist of letters, digits and '_', optionally with one list index from 0 to 999 such as items[0] (offending segment: '{segment}').", + nameof(relative)); + } + } + + // Templify's placeholder grammar (PlaceholderScanner) accepts \w characters in names. + [GeneratedRegex(@"^\w+(\[[0-9]{1,3}\])?$", RegexOptions.CultureInvariant)] + private static partial Regex SegmentPattern(); +} diff --git a/src/TriasDev.Templify.Builder/TemplateStamp.cs b/src/TriasDev.Templify.Builder/TemplateStamp.cs new file mode 100644 index 00000000..c96e072c --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateStamp.cs @@ -0,0 +1,142 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Reflection; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// +/// Where a template came from: written into every generated template's document properties (DOCX custom +/// properties, ODT meta:user-defined) and read back by . +/// +/// The definition's . +/// The definition's . +/// The of the build. +/// The document language, for example de-DE. +/// The version of TriasDev.Templify.Builder that built the template. +/// The version of TriasDev.Templify the builder was built against; fill with this or later. +/// +/// The stamp tells where a copy came from; it does not decide whether the copy is usable. Other editors may drop +/// custom properties, so a missing stamp means "unknown origin". Filled documents keep the stamp; +/// removes it from documents that go to external recipients. +/// +public sealed record TemplateStamp( + string TemplateId, + int Version, + string ContractHash, + string Language, + string BuilderVersion, + string MinimumEngineVersion) +{ + /// The prefix of the builder's document property names. + internal const string PropertyPrefix = "Templify."; + + private const string TemplateIdName = PropertyPrefix + "TemplateId"; + private const string VersionName = PropertyPrefix + "TemplateVersion"; + private const string ContractHashName = PropertyPrefix + "ContractHash"; + private const string LanguageName = PropertyPrefix + "Language"; + private const string BuilderVersionName = PropertyPrefix + "BuilderVersion"; + private const string EngineVersionName = PropertyPrefix + "MinimumEngineVersion"; + private const string ComponentsName = PropertyPrefix + "Components"; + + private static readonly IReadOnlyDictionary _noComponents = new SortedDictionary(StringComparer.Ordinal); + + /// + /// Gets the versioned components the template was built from (; by type + /// name without a generic suffix) and their versions; empty when it has none or the stamp predates component versions. + /// + public IReadOnlyDictionary Components { get; init; } = _noComponents; + + /// The stamp of a build. + internal static TemplateStamp For(TemplateIdentity identity, DataContract contract, CultureInfo language, IReadOnlyDictionary components) => + new TemplateStamp( + identity.Id, + identity.Version, + contract.Hash, + language.Name, + VersionOf(typeof(TemplateBuilder).Assembly), + VersionOf(typeof(TemplateProcessor).Assembly)) + { + Components = components, + }; + + /// The stamp as document properties (name, value), in a fixed order. + internal IEnumerable<(string Name, string Value)> ToProperties() + { + yield return (TemplateIdName, TemplateId); + yield return (VersionName, Version.ToString(CultureInfo.InvariantCulture)); + yield return (ContractHashName, ContractHash); + yield return (LanguageName, Language); + yield return (BuilderVersionName, BuilderVersion); + yield return (EngineVersionName, MinimumEngineVersion); + if (Components.Count > 0) + { + yield return (ComponentsName, string.Join(';', Components.OrderBy(c => c.Key, StringComparer.Ordinal).Select(c => c.Key + "=" + c.Value.ToString(CultureInfo.InvariantCulture)))); + } + } + + /// Reads a stamp from document properties; null unless every stamp property is present and valid. + internal static TemplateStamp? FromProperties(IReadOnlyDictionary properties) + { + if (properties.TryGetValue(TemplateIdName, out string? id) + && properties.TryGetValue(VersionName, out string? versionText) + && int.TryParse(versionText, NumberStyles.Integer, CultureInfo.InvariantCulture, out int version) + && properties.TryGetValue(ContractHashName, out string? hash) + && properties.TryGetValue(LanguageName, out string? language) + && properties.TryGetValue(BuilderVersionName, out string? builderVersion) + && properties.TryGetValue(EngineVersionName, out string? engineVersion)) + { + return new TemplateStamp(id, version, hash, language, builderVersion, engineVersion) + { + Components = properties.TryGetValue(ComponentsName, out string? components) ? ParseComponents(components) : _noComponents, + }; + } + + return null; + } + + /// + public bool Equals(TemplateStamp? other) => + other is not null + && TemplateId == other.TemplateId && Version == other.Version && ContractHash == other.ContractHash && Language == other.Language + && BuilderVersion == other.BuilderVersion && MinimumEngineVersion == other.MinimumEngineVersion + && Components.Count == other.Components.Count + && Components.All(c => other.Components.TryGetValue(c.Key, out int version) && version == c.Value); + + /// + public override int GetHashCode() => HashCode.Combine(TemplateId, Version, ContractHash, Language, BuilderVersion, MinimumEngineVersion, Components.Count); + + /// Reads Name=version;…; anything malformed gives no components (the stamp stays usable). + private static IReadOnlyDictionary ParseComponents(string text) + { + SortedDictionary result = new SortedDictionary(StringComparer.Ordinal); + foreach (string pair in text.Split(';', StringSplitOptions.RemoveEmptyEntries)) + { + string[] parts = pair.Split('='); + if (parts.Length != 2 || parts[0].Length == 0 + || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out int version) || version < 1 + || !result.TryAdd(parts[0], version)) + { + return _noComponents; + } + } + + return result; + } + + /// The informational version without build metadata (0.1.0+abc → 0.1.0). + private static string VersionOf(Assembly assembly) + { + string? version = assembly.GetCustomAttribute()?.InformationalVersion + ?? assembly.GetName().Version?.ToString(); + if (version == null) + { + return "0.0.0"; + } + + int plus = version.IndexOf('+', StringComparison.Ordinal); + return plus < 0 ? version : version[..plus]; + } +} diff --git a/src/TriasDev.Templify.Builder/TemplateStampRemover.cs b/src/TriasDev.Templify.Builder/TemplateStampRemover.cs new file mode 100644 index 00000000..8d562d16 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateStampRemover.cs @@ -0,0 +1,134 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.IO.Compression; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using DocumentFormat.OpenXml.CustomProperties; +using DocumentFormat.OpenXml.Packaging; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// +/// Removes the builder's stamp from a document, typically a filled document that goes to an external recipient who +/// should not see internal template ids. Other document properties stay. +/// +public static class TemplateStampRemover +{ + /// Removes the stamp properties (names starting with Templify.) from a DOCX or ODT document, in place. + /// The document; readable, writable and seekable. It is rewritten from position 0. + /// when the document had stamp properties and was rewritten. + /// The stream is not readable, writable and seekable. + public static bool Remove(Stream document) + { + ArgumentNullException.ThrowIfNull(document); + if (!document.CanRead || !document.CanWrite || !document.CanSeek) + { + throw new ArgumentException("The document stream must be readable, writable and seekable.", nameof(document)); + } + + document.Position = 0; + using MemoryStream original = new MemoryStream(); + document.CopyTo(original); + byte[] bytes = original.ToArray(); + + TemplateFormat format; + using (MemoryStream detect = new MemoryStream(bytes, writable: false)) + { + format = TemplateProcessor.DetectFormat(detect); + } + + if (TemplateInspector.ReadProperties(bytes, format).Count == 0) + { + return false; + } + + byte[] rewritten = format == TemplateFormat.Docx ? RemoveFromDocx(bytes) : RemoveFromOdt(bytes); + document.Position = 0; + document.SetLength(0); + document.Write(rewritten); + document.Position = 0; + return true; + } + + private static byte[] RemoveFromDocx(byte[] bytes) + { + using MemoryStream stream = new MemoryStream(); + stream.Write(bytes); + using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true)) + { + CustomFilePropertiesPart part = document.CustomFilePropertiesPart!; + List stamp = part.Properties!.Elements() + .Where(p => p.Name?.Value?.StartsWith(TemplateStamp.PropertyPrefix, StringComparison.Ordinal) == true) + .ToList(); + stamp.ForEach(p => p.Remove()); + + if (!part.Properties.Elements().Any()) + { + document.DeletePart(part); + } + else + { + part.Properties.Save(); + } + } + + return stream.ToArray(); + } + + /// Rewrites the package with the stamp removed from meta.xml; the mimetype entry stays first and stored. + private static byte[] RemoveFromOdt(byte[] bytes) + { + XNamespace meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; + List<(string Name, byte[] Data, DateTimeOffset Time)> entries = new List<(string, byte[], DateTimeOffset)>(); + using (MemoryStream input = new MemoryStream(bytes, writable: false)) + using (ZipArchive archive = new ZipArchive(input, ZipArchiveMode.Read)) + { + foreach (ZipArchiveEntry entry in archive.Entries) + { + using Stream entryStream = entry.Open(); + using MemoryStream data = new MemoryStream(); + entryStream.CopyTo(data); + byte[] content = data.ToArray(); + + if (entry.FullName == "meta.xml") + { + XDocument xml = XDocument.Parse(Encoding.UTF8.GetString(content), LoadOptions.PreserveWhitespace); + xml.Descendants(meta + "user-defined") + .Where(e => ((string?)e.Attribute(meta + "name"))?.StartsWith(TemplateStamp.PropertyPrefix, StringComparison.Ordinal) == true) + .ToList() + .ForEach(e => e.Remove()); + using MemoryStream serialized = new MemoryStream(); + using (XmlWriter writer = XmlWriter.Create(serialized, new XmlWriterSettings { Encoding = new UTF8Encoding(false) })) + { + xml.Save(writer); + } + + content = serialized.ToArray(); + } + + entries.Add((entry.FullName, content, entry.LastWriteTime)); + } + } + + using MemoryStream output = new MemoryStream(); + using (ZipArchive archive = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach ((string name, byte[] data, DateTimeOffset time) in entries.OrderBy(e => e.Name == "mimetype" ? 0 : 1)) + { + ZipArchiveEntry entry = archive.CreateEntry(name, name == "mimetype" ? CompressionLevel.NoCompression : CompressionLevel.Optimal); + if (time.Year >= 1980) + { + entry.LastWriteTime = time; + } + + using Stream entryStream = entry.Open(); + entryStream.Write(data); + } + } + + return output.ToArray(); + } +} diff --git a/src/TriasDev.Templify.Builder/TemplateSyntax.cs b/src/TriasDev.Templify.Builder/TemplateSyntax.cs new file mode 100644 index 00000000..66067c40 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TemplateSyntax.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder; + +/// +/// The one place that writes Templify syntax. Writers ask it for the text of placeholders and markers and only +/// decide where that text goes. +/// +internal static class TemplateSyntax +{ + /// The placeholder for a value, for example {{customer.name}} or {{order.date:date:yyyy-MM-dd}}. + /// A non-empty data path. + /// The format specifier, or null. + public static string Placeholder(TemplatePath path, ValueFormat? format = null) => + format is null ? "{{" + path + "}}" : "{{" + path + ":" + format.Specifier + "}}"; + + /// The else marker. + public const string Else = "{{#else}}"; + + /// The end marker of a conditional. + public const string EndIf = "{{/if}}"; + + /// The start marker of a conditional, for example {{#if order.total > 100}}. + public static string If(Condition condition) => "{{#if " + condition + "}}"; + + /// An inline expression, for example {{(order.isPaid and order.total > 0):yesno}}. + public static string Expression(Condition condition, ValueFormat? format) => + "{{(" + condition + ")" + (format is null ? string.Empty : ":" + format.Specifier) + "}}"; + + /// The end marker of a loop. + public const string EndForEach = "{{/foreach}}"; + + /// The start marker of a loop with a named iteration variable, for example {{#foreach line in order.lines}}. + public static string ForEach(string itemName, TemplatePath collection) => "{{#foreach " + itemName + " in " + collection + "}}"; + + /// An elseif marker. + public static string ElseIf(Condition condition) => "{{#elseif " + condition + "}}"; +} diff --git a/src/TriasDev.Templify.Builder/TextCatalog.cs b/src/TriasDev.Templify.Builder/TextCatalog.cs new file mode 100644 index 00000000..4c854520 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TextCatalog.cs @@ -0,0 +1,245 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Resources; + +namespace TriasDev.Templify.Builder; + +/// +/// The literal texts of templates in several languages: one definition, a text per key and language. Missing +/// translations are build errors, never silent fallbacks. +/// +public interface ITextCatalog +{ + /// Looks up a text. + /// The text's key. + /// The document language. + /// The text, when found. + /// when the catalog has the key for the language. + bool TryGet(string key, CultureInfo language, out string text); +} + +/// Creates and combines s. +/// +/// Lookups go from the specific to the neutral culture (de-AT, then de) but never to the invariant +/// culture: a missing German text must fail the build, not print the default language's text. +/// +public static class TextCatalog +{ + /// Gets a catalog without texts. + public static ITextCatalog Empty { get; } = new DictionaryCatalog(new Dictionary>()); + + /// + /// A catalog from a dictionary of key → (language → text), for example + /// ["invoiceTitle"] = { ["en"] = "Invoice", ["de"] = "Rechnung" }. Language names compare case-insensitively. + /// + /// The texts. + /// The catalog. + public static ITextCatalog FromDictionary(IReadOnlyDictionary> texts) + { + ArgumentNullException.ThrowIfNull(texts); + return new DictionaryCatalog(texts); + } + + /// A catalog over .resx resources. + /// The resource manager. + /// + /// The language of the neutral (default) resources, for example English when Texts.resx is English and + /// Texts.de.resx German. The neutral resources answer only for this language (and its specific cultures); + /// null to never use them. + /// + /// The catalog. + public static ITextCatalog FromResourceManager(ResourceManager resources, CultureInfo? neutralLanguage = null) + { + ArgumentNullException.ThrowIfNull(resources); + return new ResourceCatalog(resources, neutralLanguage); + } + + /// Combines catalogs; a later catalog overrides the texts of earlier ones (a base plus overrides). + /// The catalogs, in order of increasing priority. + /// The combined catalog. + public static ITextCatalog Combine(params ITextCatalog[] catalogs) + { + ArgumentNullException.ThrowIfNull(catalogs); + if (catalogs.Any(c => c is null)) + { + throw new ArgumentException("A catalog is null.", nameof(catalogs)); + } + + return new CombinedCatalog(catalogs.ToArray()); + } + + /// The culture and its parents, specific to neutral, without the invariant culture. + internal static IEnumerable Chain(CultureInfo language) + { + for (CultureInfo culture = language; !string.IsNullOrEmpty(culture.Name); culture = culture.Parent) + { + yield return culture; + } + } + + private sealed class DictionaryCatalog(IReadOnlyDictionary> texts) : ITextCatalog + { + public bool TryGet(string key, CultureInfo language, out string text) + { + text = string.Empty; + if (!texts.TryGetValue(key, out IReadOnlyDictionary? translations) || translations is null) + { + return false; + } + + foreach (CultureInfo culture in Chain(language)) + { + foreach (KeyValuePair translation in translations) + { + if (string.Equals(translation.Key, culture.Name, StringComparison.OrdinalIgnoreCase) && translation.Value is not null) + { + text = translation.Value; + return true; + } + } + } + + return false; + } + } + + private sealed class ResourceCatalog(ResourceManager resources, CultureInfo? neutralLanguage) : ITextCatalog + { + public bool TryGet(string key, CultureInfo language, out string text) + { + text = string.Empty; + List chain = Chain(language).ToList(); + foreach (CultureInfo culture in chain) + { + if (Find(culture, key) is { } found) + { + text = found; + return true; + } + } + + if (neutralLanguage != null && chain.Any(c => string.Equals(c.Name, neutralLanguage.Name, StringComparison.OrdinalIgnoreCase)) + && Find(CultureInfo.InvariantCulture, key) is { } neutral) + { + text = neutral; + return true; + } + + return false; + } + + private string? Find(CultureInfo culture, string key) + { + try + { + return resources.GetResourceSet(culture, createIfNotExists: true, tryParents: false)?.GetString(key); + } + catch (MissingManifestResourceException) + { + return null; + } + } + } + + private sealed class CombinedCatalog(ITextCatalog[] catalogs) : ITextCatalog + { + public bool TryGet(string key, CultureInfo language, out string text) + { + for (int i = catalogs.Length - 1; i >= 0; i--) + { + if (catalogs[i].TryGet(key, language, out text)) + { + return true; + } + } + + text = string.Empty; + return false; + } + } +} + +/// +/// The texts of the build's language, from : template.Texts["invoiceTitle"]. +/// +public sealed class TemplateTexts +{ + private readonly BuildContext _context; + private readonly ITextCatalog _catalog; + private readonly HashSet _reported; + private readonly ITextCatalog? _preferred; + + internal TemplateTexts(BuildContext context, ITextCatalog catalog, CultureInfo language, bool writesKeys = false) + : this(context, catalog, language, writesKeys, null, new HashSet(StringComparer.Ordinal)) + { + } + + private TemplateTexts(BuildContext context, ITextCatalog catalog, CultureInfo language, bool writesKeys, ITextCatalog? preferred, HashSet reported) + { + _context = context; + _catalog = catalog; + Language = language; + WritesKeys = writesKeys; + _preferred = preferred; + _reported = reported; + } + + /// Whether the texts are key markers instead of translations (composing for the JSON export). + internal bool WritesKeys { get; } + + /// Gets the document language of the build. + public CultureInfo Language { get; } + + /// + /// Gets the text of a key in the build's language. A missing text is reported when the build ends, together + /// with every other missing key; until then a marker stands in for it. + /// + /// The text's key. + public string this[string key] + { + get + { + ArgumentNullException.ThrowIfNull(key); + return Resolve(key, _preferred); + } + } + + /// + /// The text of a key: a key marker while exporting; else from (a JSON definition's own + /// texts), then from the catalog; a missing text is reported. + /// + /// + /// These texts, looked up first in : what the components of a JSON definition see, so + /// the JSON's own texts win over the catalog for them too. + /// + internal TemplateTexts Preferring(ITextCatalog preferred) => new TemplateTexts(_context, _catalog, Language, WritesKeys, preferred, _reported); + + internal string Resolve(string key, ITextCatalog? preferred) + { + if (WritesKeys) + { + return Json.TextKeys.Marker(key); + } + + if (preferred != null && preferred.TryGet(key, Language, out string own)) + { + return own; + } + + if (_catalog.TryGet(key, Language, out string text)) + { + return text; + } + + if (_reported.Add(key)) + { + _context.Error( + DiagnosticCodes.MissingText, + $"The text '{key}' has no translation for {Language.Name} ({Language.EnglishName})."); + } + + return "[" + key + "]"; + } +} diff --git a/src/TriasDev.Templify.Builder/TriasDev.Templify.Builder.csproj b/src/TriasDev.Templify.Builder/TriasDev.Templify.Builder.csproj new file mode 100644 index 00000000..3986a2a6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/TriasDev.Templify.Builder.csproj @@ -0,0 +1,44 @@ + + + + + net11.0;net10.0 + + + TriasDev.Templify.Builder + + $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)version.txt').Trim()) + Code-first template builder for TriasDev.Templify: describe Word (.docx) and OpenDocument Text (.odt) templates in C# — styles, placeholders, conditionals and loops — and generate them at runtime. Templify fills the generated templates. + word;docx;odt;opendocument;libreoffice;template;templify;document-generation;templating;builder;fluent + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs new file mode 100644 index 00000000..b9b0c9f5 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs @@ -0,0 +1,390 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder; + +/// What a path of the data is. +public enum DataKind +{ + /// A value printed or compared (text, number, date, boolean, enum). + Value, + + /// An object with properties. + Object, + + /// A collection to loop over; its items are listed under path[]. + Collection, + + /// A shape the type does not fix (a dictionary, , ): any path below is accepted. + Open, +} + +/// One path of a data catalogue. +/// The path in the data contract's form, for example order.lines[].description. +/// What the path is. +/// The C# type of the value. +public sealed record DataCatalogEntry(string Path, DataKind Kind, Type ClrType); + +/// +/// Every data path a C# type offers, named as its JSON (camelCase by default, +/// wins, hides). An import checks a definition's paths against it; a template's data +/// contract should be inside it. +/// +public sealed partial class DataCatalog +{ + private const int MaximumDepth = 16; + private const int JsonVersion = 1; + private const int MaximumItems = 1000; + private const int MaximumPasses = 24; + + private readonly HashSet _paths; + private readonly List _open; + + private DataCatalog(List entries) + { + Entries = entries; + _paths = entries.Select(e => e.Path).ToHashSet(StringComparer.Ordinal); + _open = entries.Where(e => e.Kind == DataKind.Open).Select(e => e.Path).ToList(); + } + + /// Gets the paths, in property order, parents before children. + public IReadOnlyList Entries { get; } + + /// The catalogue of a type. + /// The data's type. + /// How property names become data names; null for camelCase. + /// The catalogue. + public static DataCatalog From(JsonNamingPolicy? naming = null) => ForType(typeof(T), naming); + + /// The catalogue of a type. + /// The data's type. + /// How property names become data names; null for camelCase. + /// The catalogue. + public static DataCatalog ForType(Type type, JsonNamingPolicy? naming = null) + { + ArgumentNullException.ThrowIfNull(type); + List entries = new List(); + Properties(type, string.Empty, naming ?? JsonNamingPolicy.CamelCase, new List { type }, entries, 0); + return new DataCatalog(entries); + } + + /// Whether the data has this path (canonical form); any path below an open shape counts. + /// The path, for example order.lines[].description. + /// Whether it exists. + public bool Contains(string path) + { + ArgumentNullException.ThrowIfNull(path); + return _paths.Contains(path) + || _open.Any(open => path.StartsWith(open, StringComparison.Ordinal) && path.Length > open.Length && path[open.Length] is '.' or '['); + } + + /// + /// Writes the catalogue as JSON, for agents and for hosts that keep a snapshot: a version and the paths in + /// order, each with its kind (value, object, collection, open) and + /// its C# type name. + /// + /// The JSON, indented. + public string ToJson() + { + JsonObject root = new JsonObject + { + ["version"] = JsonVersion, + ["paths"] = new JsonArray(Entries + .Select(e => (JsonNode)new JsonObject + { + ["path"] = e.Path, + ["kind"] = e.Kind.ToString().ToLowerInvariant(), + ["type"] = TypeName(e.ClrType), + }) + .ToArray()), + }; + return root.ToJsonString(new JsonSerializerOptions { WriteIndented = true }); + } + + /// + /// Builds data in which every path of the catalogue exists: values are the text "x", collections hold + /// items, and an open shape is an with the given names. + /// + /// The names an open shape has (at any depth below it); null for none. + /// How many items every collection holds (an index [n] needs n + 1). + internal IReadOnlyDictionary CreateWitness(IEnumerable? openNames = null, int items = 1) + { + OpenWitness open = new OpenWitness(openNames ?? []); + Dictionary byPath = new Dictionary(StringComparer.Ordinal); + foreach (DataCatalogEntry entry in Entries) + { + // A property hidden with `new` lists its path twice; the first entry wins. + byPath.TryAdd(entry.Path, entry); + } + + ILookup children = byPath.Values + .Where(e => !e.Path.EndsWith("[]", StringComparison.Ordinal)) + .ToLookup(e => e.Path.LastIndexOf('.') is var dot and >= 0 ? e.Path[..dot] : string.Empty, StringComparer.Ordinal); + return ObjectWitness(string.Empty); + + object? Witness(DataCatalogEntry entry) + { + switch (entry.Kind) + { + case DataKind.Value: + return "x"; + case DataKind.Open: + return open; + case DataKind.Collection: + object? item = byPath.TryGetValue(entry.Path + "[]", out DataCatalogEntry? itemEntry) ? Witness(itemEntry) : "x"; + return Enumerable.Repeat(item, items).ToList(); + default: + return ObjectWitness(entry.Path); + } + } + + Dictionary ObjectWitness(string path) + { + Dictionary result = new Dictionary(StringComparer.Ordinal); + foreach (DataCatalogEntry child in children[path]) + { + result.TryAdd(path.Length == 0 ? child.Path : child.Path[(path.Length + 1)..], Witness(child)); + } + + return result; + } + } + + /// Validates a template against witness data of the catalogue (see ). + internal ValidationResult ValidateTemplate(byte[] template) => CheckTemplate(template).Validation; + + /// + /// Validates a template against witness data of the catalogue and fills it once with that data. The engine's + /// validation checks every branch but, inside loops, only the first segment of an item's path; the fill checks + /// whole paths in the branches the witness takes. Names below open shapes and indexes cannot be known in advance: + /// they start from the template's placeholders, and every name or index a pass misses is added (to the open shapes, + /// or as more collection items) until nothing changes. A name that stays missing is not in the data; paths below + /// closed types never gain names this way. + /// + /// The template package. + /// The last validation, the names only the fill missed, and the fill's error. + internal CatalogueCheck CheckTemplate(byte[] template) + { + HashSet names = new HashSet(StringComparer.Ordinal); + int items = 1; + bool open = Entries.Any(e => e.Kind == DataKind.Open); + + // An open loop item with a root name (order) would resolve order.… through the item inside the loop. + HashSet roots = Entries.Select(e => e.Path.Split('.', '[')[0]).ToHashSet(StringComparer.Ordinal); + for (int pass = 0; ; pass++) + { + IReadOnlyDictionary witness = CreateWitness(names, items); + ValidationResult validation; + using (MemoryStream stream = new MemoryStream(template, writable: false)) + { + validation = new TemplateProcessor().ValidateTemplate(stream, witness); + } + + ProcessingResult? fill = validation.Errors.All(e => e.Type == ValidationErrorType.MissingVariable) ? Fill(template, witness) : null; + List missing = MissingNames(validation).Concat(fill?.MissingVariables ?? []).ToList(); + + int namesBefore = names.Count; + int itemsBefore = items; + foreach (string name in missing) + { + foreach (Match index in IndexPattern().Matches(name)) + { + items = Math.Min(MaximumItems, Math.Max(items, int.Parse(index.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) + 1)); + } + } + + if (open) + { + foreach (string name in validation.AllPlaceholders.Concat(missing)) + { + names.UnionWith(name.Split('.', '[', ']', ':', '(', ')', ' ').Where(n => n.Length > 0 && !n.StartsWith('@') && !roots.Contains(n))); + } + } + + if ((names.Count == namesBefore && items == itemsBefore) || pass >= MaximumPasses) + { + HashSet reported = MissingNames(validation).ToHashSet(StringComparer.Ordinal); + return new CatalogueCheck( + validation, + (fill?.MissingVariables ?? []).Where(reported.Add).ToList(), + fill is { IsSuccess: false } ? fill.ErrorMessage ?? "Filling the template failed." : null); + } + } + } + + /// The variables a validation reports missing: values and loops, and variables of conditions. + internal static IEnumerable MissingNames(ValidationResult result) => + result.MissingVariables.Concat(result.Warnings + .Where(w => w.Type == ValidationWarningType.MissingConditionVariable) + .Select(w => ConditionVariable().Match(w.Message)) + .Where(m => m.Success) + .Select(m => m.Groups[1].Value)); + + private static ProcessingResult Fill(byte[] template, IReadOnlyDictionary witness) + { + using MemoryStream input = new MemoryStream(template, writable: false); + using MemoryStream output = new MemoryStream(); + return new TemplateProcessor().ProcessTemplate(input, output, witness); + } + + /// The kind of a path: its entry's kind, below an open shape, or null. + internal DataKind? KindOf(string path) + { + // items[0].name reads an item like items[].name. + path = System.Text.RegularExpressions.Regex.Replace(path, @"\[[0-9]+\]", "[]"); + DataCatalogEntry? entry = Entries.FirstOrDefault(e => e.Path == path); + if (entry != null) + { + return entry.Kind; + } + + return Contains(path) ? DataKind.Open : null; + } + + /// The kind a value of a C# type has (for typed component parameters). + internal static DataKind KindOfType(Type type) + { + Type bare = Nullable.GetUnderlyingType(type) ?? type; + return IsValue(bare) ? DataKind.Value : IsOpen(bare) ? DataKind.Open : ItemType(bare) is not null ? DataKind.Collection : DataKind.Object; + } + + private static void Properties(Type type, string prefix, JsonNamingPolicy naming, List branch, List entries, int depth) + { + foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetIndexParameters().Length > 0 || !property.CanRead + || property.GetCustomAttribute() is { Condition: JsonIgnoreCondition.Always }) + { + continue; + } + + string name = property.GetCustomAttribute()?.Name ?? naming.ConvertName(property.Name); + Add(property.PropertyType, prefix.Length == 0 ? name : prefix + "." + name, naming, branch, entries, depth + 1); + } + } + + private static void Add(Type type, string path, JsonNamingPolicy naming, List branch, List entries, int depth) + { + Type bare = Nullable.GetUnderlyingType(type) ?? type; + if (IsValue(bare)) + { + entries.Add(new DataCatalogEntry(path, DataKind.Value, type)); + return; + } + + if (IsOpen(bare)) + { + entries.Add(new DataCatalogEntry(path, DataKind.Open, type)); + return; + } + + if (ItemType(bare) is { } item) + { + entries.Add(new DataCatalogEntry(path, DataKind.Collection, type)); + Add(item, path + "[]", naming, branch, entries, depth); + return; + } + + entries.Add(new DataCatalogEntry(path, DataKind.Object, type)); + + // A recursive type is expanded once more (children[].name), then cut; the depth cap is a second guard. + if (depth >= MaximumDepth || branch.Count(t => t == bare) >= 2) + { + return; + } + + branch.Add(bare); + Properties(bare, path, naming, branch, entries, depth); + branch.RemoveAt(branch.Count - 1); + } + + private static bool IsValue(Type type) => + type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) + || type == typeof(DateOnly) || type == typeof(TimeOnly) || type == typeof(TimeSpan) || type == typeof(Guid); + + private static bool IsOpen(Type type) => + type == typeof(object) || type == typeof(JsonElement) || typeof(JsonNode).IsAssignableFrom(type) || type == typeof(System.Dynamic.ExpandoObject) + || typeof(System.Collections.IDictionary).IsAssignableFrom(type) + || type.GetInterfaces().Append(type).Any(IsDictionaryInterface); + + private static bool IsDictionaryInterface(Type type) => + type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IDictionary<,>) || type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>)); + + /// A readable C# type name: decimal, int?, IReadOnlyList<Line>. + private static string TypeName(Type type) + { + if (Nullable.GetUnderlyingType(type) is { } underlying) + { + return TypeName(underlying) + "?"; + } + + if (type.IsArray) + { + return TypeName(type.GetElementType()!) + "[]"; + } + + if (type.IsGenericType && type.Name.Contains('`', StringComparison.Ordinal)) + { + string name = type.Name[..type.Name.IndexOf('`', StringComparison.Ordinal)]; + return name + "<" + string.Join(", ", type.GetGenericArguments().Select(TypeName)) + ">"; + } + + return type == typeof(string) ? "string" : type == typeof(int) ? "int" : type == typeof(long) ? "long" + : type == typeof(bool) ? "bool" : type == typeof(decimal) ? "decimal" : type == typeof(double) ? "double" + : type == typeof(float) ? "float" : type == typeof(object) ? "object" : type.Name; + } + + // Until the engine exposes the variable of a MissingConditionVariable warning (TriasDev/templify#275), its name is + // read from the message; a test fails if the wording changes. + [GeneratedRegex(@"uses variable '([^']+)'", RegexOptions.CultureInvariant)] + private static partial Regex ConditionVariable(); + + [GeneratedRegex(@"\[([0-9]{1,3})\]", RegexOptions.CultureInvariant)] + private static partial Regex IndexPattern(); + + private static Type? ItemType(Type type) + { + if (type.IsArray) + { + return type.GetElementType(); + } + + Type? enumerable = type.GetInterfaces().Append(type).FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); + return enumerable?.GetGenericArguments()[0]; + } +} + +/// +/// Witness data below an open shape: every given name exists and is the witness again; it prints as x, and as +/// a collection it holds one item (itself). +/// +internal sealed class OpenWitness : Dictionary, System.Collections.IEnumerable +{ + public OpenWitness(IEnumerable names) + : base(StringComparer.Ordinal) + { + foreach (string name in names) + { + this[name] = this; + } + } + + // A loop enumerates without the generic interface: one item, which has the same names. + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => new object?[] { this }.GetEnumerator(); + + public override string ToString() => "x"; +} + +/// What found. +/// The last validation against the witness. +/// The names only the trial fill found missing (whole paths of loop items). +/// The trial fill's error (for example a loop over a value); null when it succeeded or did not run. +internal sealed record CatalogueCheck(ValidationResult Validation, IReadOnlyList FillMissing, string? FillError); + diff --git a/src/TriasDev.Templify.Builder/Typed/PathExpression.cs b/src/TriasDev.Templify.Builder/Typed/PathExpression.cs new file mode 100644 index 00000000..75b180d1 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Typed/PathExpression.cs @@ -0,0 +1,94 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace TriasDev.Templify.Builder; + +/// Turns a member expression (o => o.Order.Customer.Name) into a relative data path. +internal static class PathExpression +{ + /// The dotted path the expression reads, named as the data is (JSON names); empty for o => o. + /// The expression is not a chain of properties and constant dictionary keys. + public static string Relative(LambdaExpression lambda, JsonNamingPolicy? naming) + { + ArgumentNullException.ThrowIfNull(lambda); + JsonNamingPolicy policy = naming ?? JsonNamingPolicy.CamelCase; + List segments = new List(); + string index = string.Empty; + Expression expression = lambda.Body; + while (true) + { + switch (expression) + { + case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert: + expression = convert.Operand; + continue; + + case MemberExpression { Expression: not null, Member: PropertyInfo { Name: "Value" } } nullable + when nullable.Member.DeclaringType is { IsGenericType: true } declaring && declaring.GetGenericTypeDefinition() == typeof(Nullable<>): + // o.Discount.Value reads the same data as o.Discount. + expression = nullable.Expression; + continue; + + case MemberExpression { Expression: not null, Member: PropertyInfo or FieldInfo } member: + if (member.Member.DeclaringType?.Namespace is { } ns && (ns == "System" || ns.StartsWith("System.", StringComparison.Ordinal))) + { + throw Unsupported(lambda, $"'{member.Member.Name}' is computed by {member.Member.DeclaringType.Name}, not a value in the data"); + } + + segments.Add((member.Member.GetCustomAttribute()?.Name ?? policy.ConvertName(member.Member.Name)) + index); + index = string.Empty; + expression = member.Expression; + continue; + + case MethodCallExpression { Method.Name: "get_Item", Object: not null, Arguments.Count: 1 } indexer: + if (indexer.Arguments[0] is ConstantExpression { Value: string key }) + { + if (key.Length == 0 || !key.All(c => char.IsAsciiLetterOrDigit(c) || c == '_')) + { + throw Unsupported(lambda, $"the dictionary key '{key}' is not one path segment (letters, digits and '_')"); + } + + segments.Add(key + index); + index = string.Empty; + expression = indexer.Object; + continue; + } + + if (indexer.Arguments[0] is ConstantExpression { Value: int position } && index.Length == 0) + { + // o.Items[1].Name: the index belongs to the segment of the list, which comes next. + index = "[" + position.ToString(System.Globalization.CultureInfo.InvariantCulture) + "]"; + expression = indexer.Object; + continue; + } + + throw Unsupported(lambda, indexer.Arguments[0].Type == typeof(string) ? "a dictionary key must be a constant string" : "a list index must be a constant number, and only one per list"); + + case BinaryExpression { NodeType: ExpressionType.ArrayIndex } array: + if (array.Right is ConstantExpression { Value: int arrayPosition } && index.Length == 0) + { + index = "[" + arrayPosition.ToString(System.Globalization.CultureInfo.InvariantCulture) + "]"; + expression = array.Left; + continue; + } + + throw Unsupported(lambda, "a list index must be a constant number, and only one per list"); + + case ParameterExpression parameter when parameter == lambda.Parameters[0] && index.Length == 0: + segments.Reverse(); + return string.Join(".", segments); + + default: + throw Unsupported(lambda, $"'{expression}' is not a property"); + } + } + } + + private static ArgumentException Unsupported(LambdaExpression lambda, string reason) => + new ArgumentException($"The expression '{lambda}' cannot be turned into a data path: {reason}. Use a chain of properties (o => o.Order.Customer.Name)."); +} diff --git a/src/TriasDev.Templify.Builder/Typed/TemplatePathOfT.cs b/src/TriasDev.Templify.Builder/Typed/TemplatePathOfT.cs new file mode 100644 index 00000000..833e9d37 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Typed/TemplatePathOfT.cs @@ -0,0 +1,255 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Linq.Expressions; +using System.Text.Json; + +namespace TriasDev.Templify.Builder; + +/// +/// A data path that knows the C# type of the value it reads, so the next level is chosen with the compiler's help: +/// order.Path(o => o.Customer.Name). It is the same path value as the string API produces and converts to +/// and wherever those are expected. +/// +/// The type of the value at this path. +public readonly struct TemplatePath : IEquatable>, IFormattable +{ + private readonly JsonNamingPolicy? _naming; + + internal TemplatePath(TemplatePath path, JsonNamingPolicy? naming) + { + Untyped = path; + _naming = naming; + } + + /// Gets the path as a plain . + public TemplatePath Untyped { get; } + + /// How C# names become data names below this path (null: camelCase). + internal JsonNamingPolicy? Naming => _naming; + + /// A value below this one: a chain of properties and constant dictionary keys. + /// The type of the value. + /// The member chain, for example o => o.Customer.Name. + /// The path. + /// The expression is not a chain of properties and constant dictionary keys. + public TemplatePath Path(Expression> member) + { + string relative = PathExpression.Relative(member, _naming); + return new TemplatePath(relative.Length == 0 ? Untyped : Untyped[relative], _naming); + } + + /// A collection below this value, to loop over. + /// The item type. + /// The member chain, for example o => o.Lines. + /// The collection. + public TemplateCollection Items(Expression>> member) + { + string relative = PathExpression.Relative(member, _naming); + return new TemplateCollection(relative.Length == 0 ? Untyped : Untyped[relative], _naming); + } + + /// The value equals a string: path = "value". + public Condition Eq(string value) => Untyped.Eq(value); + + /// The value equals a number. + public Condition Eq(double value) => Untyped.Eq(value); + + /// The value differs from a string. + public Condition NotEq(string value) => Untyped.NotEq(value); + + /// The value differs from a number. + public Condition NotEq(double value) => Untyped.NotEq(value); + + /// The value is greater than a number. + public Condition Gt(double value) => Untyped.Gt(value); + + /// The value is at least a number. + public Condition Ge(double value) => Untyped.Ge(value); + + /// The value is less than a number. + public Condition Lt(double value) => Untyped.Lt(value); + + /// The value is at most a number. + public Condition Le(double value) => Untyped.Le(value); + + /// The value is one of the strings. + public Condition In(params string[] values) => Untyped.In(values); + + /// The value contains a string (or a collection contains it). + public Condition Contains(string value) => Untyped.Contains(value); + + /// The value starts with a string. + public Condition StartsWith(string value) => Untyped.StartsWith(value); + + /// The value ends with a string. + public Condition EndsWith(string value) => Untyped.EndsWith(value); + + /// The value equals another value: a = b (numeric when both are numbers, else ordinal text). + public Condition Eq(TemplatePath other) => Untyped.Eq(other); + + /// The value differs from another value: a != b. + public Condition NotEq(TemplatePath other) => Untyped.NotEq(other); + + /// The value is greater than another value: a > b. + public Condition Gt(TemplatePath other) => Untyped.Gt(other); + + /// The value is at least another value: a >= b. + public Condition Ge(TemplatePath other) => Untyped.Ge(other); + + /// The value is less than another value: a < b. + public Condition Lt(TemplatePath other) => Untyped.Lt(other); + + /// The value is at most another value: a <= b. + public Condition Le(TemplatePath other) => Untyped.Le(other); + + /// The value contains another value, or the collection contains it: a contains b. + public Condition Contains(TemplatePath other) => Untyped.Contains(other); + + /// The value starts with another value: a startswith b. + public Condition StartsWith(TemplatePath other) => Untyped.StartsWith(other); + + /// The value ends with another value: a endswith b. + public Condition EndsWith(TemplatePath other) => Untyped.EndsWith(other); + + /// Gets the condition that the value exists. + public Condition Exists => Untyped.Exists; + + /// Gets the condition that the value is empty. + public Condition IsEmpty => Untyped.IsEmpty; + + /// Gets the condition that the value is not empty. + public Condition IsNotEmpty => Untyped.IsNotEmpty; + + /// The plain path. + /// The typed path. + public static implicit operator TemplatePath(TemplatePath path) => path.Untyped; + + /// The value is truthy. + /// The typed path. + public static implicit operator Condition(TemplatePath path) => path.Untyped; + + /// The value is not truthy. + /// The typed path. + /// The condition. + public static Condition operator !(TemplatePath path) => !path.Untyped; + + /// Both are true. + /// The typed path. + /// The other condition (a typed path converts). + /// The condition. + public static Condition operator &(TemplatePath left, Condition right) => (Condition)left.Untyped & right; + + /// At least one is true. + /// The typed path. + /// The other condition (a typed path converts). + /// The condition. + public static Condition operator |(TemplatePath left, Condition right) => (Condition)left.Untyped | right; + + /// Compares two paths. + public static bool operator ==(TemplatePath left, TemplatePath right) => left.Equals(right); + + /// Compares two paths. + public static bool operator !=(TemplatePath left, TemplatePath right) => !left.Equals(right); + + /// + public bool Equals(TemplatePath other) => Untyped.Equals(other.Untyped); + + /// + public override bool Equals(object? obj) => obj is TemplatePath other && Equals(other); + + /// + public override int GetHashCode() => Untyped.GetHashCode(); + + /// Returns the path as Templify writes it. + /// The dotted path. + public override string ToString() => Untyped.ToString(); + + /// In an interpolated string the path is its placeholder, so the literal-text check (TB1002) reports it. + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ((IFormattable)Untyped).ToString(format, formatProvider); +} + +/// A collection in the data, typed by its items, for ForEach. +/// The item type. +public readonly struct TemplateCollection : IEquatable> +{ + internal TemplateCollection(TemplatePath path, JsonNamingPolicy? naming) + { + Untyped = path; + Naming = naming; + } + + /// Gets the path as a plain . + public TemplatePath Untyped { get; } + + internal JsonNamingPolicy? Naming { get; } + + /// Gets the condition that the collection exists. + public Condition Exists => Untyped.Exists; + + /// Gets the condition that the collection is empty. + public Condition IsEmpty => Untyped.IsEmpty; + + /// Gets the condition that the collection is not empty. + public Condition IsNotEmpty => Untyped.IsNotEmpty; + + /// The plain path. + /// The collection. + public static implicit operator TemplatePath(TemplateCollection collection) => collection.Untyped; + + /// The collection is truthy (exists and is not empty). + /// The collection. + public static implicit operator Condition(TemplateCollection collection) => collection.Untyped; + + /// Compares two collections. + public static bool operator ==(TemplateCollection left, TemplateCollection right) => left.Equals(right); + + /// Compares two collections. + public static bool operator !=(TemplateCollection left, TemplateCollection right) => !left.Equals(right); + + /// + public bool Equals(TemplateCollection other) => Untyped.Equals(other.Untyped); + + /// + public override bool Equals(object? obj) => obj is TemplateCollection other && Equals(other); + + /// + public override int GetHashCode() => Untyped.GetHashCode(); + + /// + public override string ToString() => Untyped.ToString(); +} + +/// The current item of a typed loop. +/// The item type. +public sealed class LoopItem +{ + private readonly JsonNamingPolicy? _naming; + + internal LoopItem(LoopItem item, JsonNamingPolicy? naming) + { + Item = item; + _naming = naming; + } + + /// Gets the untyped loop item. + public LoopItem Item { get; } + + /// Gets the item itself. + public TemplatePath Self => new TemplatePath(Item.Self, _naming); + + /// Gets the loop's metadata: line.Loop.Number is {{@number}}; data properties named Number or Count stay data. + public LoopInfo Loop => Item.Loop; + + /// A value of the item. + /// The type of the value. + /// The member chain, for example l => l.Description. + /// The path. + public TemplatePath Path(Expression> member) => Self.Path(member); + + /// A collection of the item, to loop over. + /// The item type. + /// The member chain. + /// The collection. + public TemplateCollection Items(Expression>> member) => Self.Items(member); +} diff --git a/src/TriasDev.Templify.Builder/ValueFormat.cs b/src/TriasDev.Templify.Builder/ValueFormat.cs new file mode 100644 index 00000000..23a46f15 --- /dev/null +++ b/src/TriasDev.Templify.Builder/ValueFormat.cs @@ -0,0 +1,157 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder; + +/// +/// How Templify formats a value: the format specifier of a placeholder, for example {{order.date:date:yyyy-MM-dd}}. +/// +/// +/// A closed set that mirrors the engine's specifiers, so a template can only carry formats the engine understands. +/// is the escape hatch for a specifier the set does not model, such as a boolean formatter a +/// product registered in BooleanFormatterRegistry. +/// +public sealed partial class ValueFormat +{ + private ValueFormat(string specifier) + { + Specifier = specifier; + } + + /// Gets the specifier as written after the path's colon, for example date:yyyy-MM-dd. + public string Specifier { get; } + + /// Gets the currency format of the fill culture: :currency. + public static ValueFormat Currency { get; } = new ValueFormat("currency"); + + /// Gets upper-case text: :uppercase. + public static ValueFormat Uppercase { get; } = new ValueFormat("uppercase"); + + /// Gets lower-case text: :lowercase. + public static ValueFormat Lowercase { get; } = new ValueFormat("lowercase"); + + /// Gets the value as is, without markdown: :raw. + public static ValueFormat Raw { get; } = new ValueFormat("raw"); + + /// Gets yes / no in the fill culture's language: :yesno. + public static ValueFormat YesNo { get; } = new ValueFormat("yesno"); + + /// Gets true / false in the fill culture's language: :truefalse. + public static ValueFormat TrueFalse { get; } = new ValueFormat("truefalse"); + + /// Gets on / off in the fill culture's language: :onoff. + public static ValueFormat OnOff { get; } = new ValueFormat("onoff"); + + /// Gets enabled / disabled in the fill culture's language: :enabled. + public static ValueFormat Enabled { get; } = new ValueFormat("enabled"); + + /// Gets active / inactive in the fill culture's language: :active. + public static ValueFormat Active { get; } = new ValueFormat("active"); + + /// Gets ☑ / ☐: :checkbox. + public static ValueFormat Checkbox { get; } = new ValueFormat("checkbox"); + + /// Gets ✓ / ✗: :checkmark. + public static ValueFormat Checkmark { get; } = new ValueFormat("checkmark"); + + /// A date in a .NET date pattern: :date:yyyy-MM-dd. + /// The pattern, for example yyyy-MM-dd or MMMM d, yyyy. + /// The format. + public static ValueFormat Date(string pattern) => new ValueFormat("date:" + Argument(pattern, nameof(pattern))); + + /// A number in a .NET numeric pattern: :number:N2. + /// The pattern, for example N2, F3 or P. + /// The format. + public static ValueFormat Number(string pattern) => new ValueFormat("number:" + Argument(pattern, nameof(pattern))); + + /// + /// A collection as one text: :join, :join:Name, :join:Name:"; ". Null and empty items are skipped. + /// + /// The property of each item to join, for example Name; null to join the items themselves. + /// The separator; null for the engine's default ", ". + /// The format. + public static ValueFormat Join(string? itemPath = null, string? separator = null) + { + StringBuilder specifier = new StringBuilder("join"); + if (itemPath != null) + { + if (!ItemPathPattern().IsMatch(itemPath)) + { + throw new ArgumentException( + $"'{itemPath}' is not a valid item path: use dot-separated segments of letters, digits and '_'.", + nameof(itemPath)); + } + + specifier.Append(':').Append(itemPath); + } + + if (separator != null) + { + Argument(separator, nameof(separator), allowEmpty: true); + if (separator.Any(c => c is '“' or '”' or '„' or '‟' or '″')) + { + throw new ArgumentException("The separator must not contain typographic quotes: Templify reads them as '\"'.", nameof(separator)); + } + + specifier.Append(":\"").Append(separator.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal)).Append('"'); + } + + return new ValueFormat(specifier.ToString()); + } + + /// + /// A specifier this set does not model, written as is, for example the name of a boolean formatter registered in + /// BooleanFormatterRegistry. + /// + /// A name of letters, digits and _, optionally followed by : and an argument. + /// The format. + public static ValueFormat Custom(string specifier) + { + ArgumentNullException.ThrowIfNull(specifier); + int colon = specifier.IndexOf(':', StringComparison.Ordinal); + string name = colon < 0 ? specifier : specifier[..colon]; + if (!NamePattern().IsMatch(name)) + { + throw new ArgumentException($"'{specifier}' is not a format specifier: it must start with a name of letters, digits and '_'.", nameof(specifier)); + } + + if (colon >= 0) + { + Argument(specifier[(colon + 1)..], nameof(specifier)); + } + + return new ValueFormat(specifier); + } + + /// Returns the specifier. + /// The specifier, for example date:yyyy-MM-dd. + public override string ToString() => Specifier; + + /// + /// Checks a format argument against the placeholder grammar: the engine reads everything up to the first }. + /// + private static string Argument(string value, string parameterName, bool allowEmpty = false) + { + ArgumentNullException.ThrowIfNull(value, parameterName); + if (!allowEmpty && value.Length == 0) + { + throw new ArgumentException("The format argument must not be empty.", parameterName); + } + + if (value.Contains('}', StringComparison.Ordinal) || value.Contains("{{", StringComparison.Ordinal) || value.Any(char.IsControl)) + { + throw new ArgumentException($"'{value}' cannot be a format argument: it must not contain '}}', '{{{{' or control characters.", parameterName); + } + + return value; + } + + [GeneratedRegex(@"^\w+$", RegexOptions.CultureInvariant)] + private static partial Regex NamePattern(); + + [GeneratedRegex(@"^\w+(\.\w+)*$", RegexOptions.CultureInvariant)] + private static partial Regex ItemPathPattern(); +} diff --git a/src/TriasDev.Templify.Builder/Writers/DeterministicZip.cs b/src/TriasDev.Templify.Builder/Writers/DeterministicZip.cs new file mode 100644 index 00000000..4c1e04e6 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/DeterministicZip.cs @@ -0,0 +1,46 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.IO.Compression; + +namespace TriasDev.Templify.Builder.Writers; + +/// One entry of a package. +/// The entry name. +/// The entry bytes. +/// Whether the entry is stored uncompressed (the ODF mimetype entry). +internal sealed record PackagePart(string Name, byte[] Content, bool Stored = false); + +/// +/// Writes a ZIP package whose bytes depend only on its parts: entries in the given order, a fixed timestamp and +/// fixed attributes. +/// +/// +/// The bytes are reproducible for the same runtime and operating system family. records the +/// host platform in the "version made by" field, so the same template is not byte-identical across Windows and Unix. +/// +internal static class DeterministicZip +{ + /// The timestamp of every entry: 2000-01-01 00:00 (DOS time has no time zone). + private static readonly DateTimeOffset _entryTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static byte[] Create(IEnumerable parts) + { + using MemoryStream buffer = new MemoryStream(); + using (ZipArchive archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (PackagePart part in parts) + { + ZipArchiveEntry entry = archive.CreateEntry( + part.Name, + part.Stored ? CompressionLevel.NoCompression : CompressionLevel.Optimal); + entry.LastWriteTime = _entryTime; + entry.ExternalAttributes = 0; + using Stream stream = entry.Open(); + stream.Write(part.Content); + } + } + + return buffer.ToArray(); + } +} diff --git a/src/TriasDev.Templify.Builder/Writers/DocxWriter.cs b/src/TriasDev.Templify.Builder/Writers/DocxWriter.cs new file mode 100644 index 00000000..db4df21d --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/DocxWriter.cs @@ -0,0 +1,1230 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Security; +using System.Text; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Wordprocessing; +using TriasDev.Templify.Builder.Model; +using A = DocumentFormat.OpenXml.Drawing; +using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; +using PIC = DocumentFormat.OpenXml.Drawing.Pictures; +using ParagraphProperties = DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties; +using Styles = DocumentFormat.OpenXml.Wordprocessing.Styles; + +namespace TriasDev.Templify.Builder.Writers; + +/// +/// Writes a as a WordprocessingML package (.docx). +/// +/// +/// The OpenXML SDK's typed elements build the XML parts; children are appended in the schema's order. The package +/// itself is written here rather than by the SDK's packaging: that would give every build random relationship ids, a +/// random core-properties part name and the current time on every entry. +/// +internal static class DocxWriter +{ + private const string XmlDeclaration = ""; + private const string MainContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"; + private const string StylesContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"; + private const string CorePropertiesContentType = "application/vnd.openxmlformats-package.core-properties+xml"; + private const string OfficeDocumentRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; + private const string StylesRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; + private const string CorePropertiesRelationship = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; + private const string CustomPropertiesContentType = "application/vnd.openxmlformats-officedocument.custom-properties+xml"; + private const string CustomPropertiesRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"; + + /// The format id every custom document property carries (FMTID_UserDefinedProperties). + private const string UserDefinedPropertiesFormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; + + /// Word's default paragraph style; the builder reserves the id. + private const string NormalStyleId = "Normal"; + + /// Word's default character style; the builder reserves the id. + private const string DefaultParagraphFontStyleId = "DefaultParagraphFont"; + + public static byte[] Write(DocumentModel model) + { + List parts = HeaderFooterParts(model.Page); + MediaStore media = new MediaStore(); + + // Lists: one numbering instance per list style used, in order of first use. + Dictionary numbering = BlockTree.Paragraphs(model.Body.Concat(model.Page.AllBlocks)) + .Select(p => p.List?.Style).OfType().Distinct() + .Select((style, index) => (style, index)).ToDictionary(e => e.style, e => e.index + 1); + string numberingRelationship = "rId" + (parts.Count + 2).ToString(CultureInfo.InvariantCulture); + + // The body's image relationships follow styles (rId1), the header/footer parts and the numbering part. + BlockWriter bodyWriter = new BlockWriter(model, media, parts.Count + 2 + (numbering.Count > 0 ? 1 : 0), numbering); + string document = XmlDeclaration + MainDocument(model, parts, bodyWriter).OuterXml; + + List partFiles = new List(); + foreach (HeaderFooterPart part in parts) + { + BlockWriter writer = new BlockWriter(model, media, 1, numbering); + OpenXmlCompositeElement root = part.IsHeader ? new Header() : new Footer(); + root.Append(EndWithParagraph(writer.WritePartBlocks(part.Blocks, model.Page.FrameWidth))); + partFiles.Add(new PackagePart("word/" + part.FileName, Utf8(XmlDeclaration + root.OuterXml))); + if (writer.Images.Count > 0) + { + partFiles.Add(new PackagePart($"word/_rels/{part.FileName}.rels", Utf8(Relationships(writer.Images.Select(i => (i.Id, ImageRelationship, i.Target)))))); + } + } + + List package = new List + { + new PackagePart("[Content_Types].xml", Utf8(ContentTypes(parts, media, numbering.Count > 0, model.Styles.EmbeddedFonts.Count > 0))), + new PackagePart("_rels/.rels", Utf8(PackageRelationships())), + new PackagePart("docProps/core.xml", Utf8(CoreProperties(model))), + new PackagePart("docProps/custom.xml", Utf8(CustomProperties(model))), + new PackagePart("word/document.xml", Utf8(document)), + new PackagePart("word/_rels/document.xml.rels", Utf8(DocumentRelationships(parts, bodyWriter.Images, numbering.Count > 0 ? numberingRelationship : null, model.Styles.EmbeddedFonts.Count > 0))), + new PackagePart("word/styles.xml", Utf8(XmlDeclaration + StylesPart(model).OuterXml)), + }; + if (numbering.Count > 0) + { + package.Add(new PackagePart("word/numbering.xml", Utf8(XmlDeclaration + NumberingPart(model, numbering).OuterXml))); + } + + // Embedded fonts (ECMA-376 part 1, 17.8): obfuscated parts, related from the font table, and the settings + // flag that tells Word to keep them. Without embedded fonts neither part is written. + IReadOnlyList fonts = model.Styles.EmbeddedFonts; + if (fonts.Count > 0) + { + package.Add(new PackagePart("word/settings.xml", Utf8(XmlDeclaration + ""))); + package.Add(new PackagePart("word/fontTable.xml", Utf8(FontTable(fonts)))); + package.Add(new PackagePart( + "word/_rels/fontTable.xml.rels", + Utf8(Relationships(fonts.Select((f, i) => (FontRelationshipId(i), FontRelationship, FontTarget(i))))))); + package.AddRange(fonts.Select((f, i) => new PackagePart("word/" + FontTarget(i), f.Embedding!.ObfuscatedForDocx()))); + } + + package.AddRange(partFiles); + package.AddRange(media.Files.Select(f => new PackagePart("word/" + f.Target, f.Data))); + return DeterministicZip.Create(package); + } + + private const string ImageRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; + private const string FontRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/font"; + + // Named ids, so the numbered ids of styles, parts and images do not shift when fonts are embedded. + private const string FontTableRelationshipId = "rIdFontTable"; + private const string SettingsRelationshipId = "rIdSettings"; + + private static string FontRelationshipId(int index) => "rIdFont" + (index + 1).ToString(CultureInfo.InvariantCulture); + + private static string FontTarget(int index) => "fonts/font" + (index + 1).ToString(CultureInfo.InvariantCulture) + ".odttf"; + + /// fontTable.xml: a w:font per embedded family with its regular face and obfuscation key. + private static string FontTable(IReadOnlyList fonts) + { + StringBuilder xml = new StringBuilder(XmlDeclaration).Append( + ""); + for (int i = 0; i < fonts.Count; i++) + { + xml.Append("") + .Append("") + .Append(""); + } + + return xml.Append("").ToString(); + } + + /// The images of a document: each distinct image once in word/media, and drawing ids unique across all parts. + private sealed class MediaStore + { + private readonly Dictionary _targets = new Dictionary(StringComparer.Ordinal); + + public List<(string Target, byte[] Data, string Extension)> Files { get; } = new List<(string, byte[], string)>(); + + public uint NextDrawingId { get; set; } = 1; + + public string Target(ImageSource image) + { + if (!_targets.TryGetValue(image.Hash, out string? target)) + { + target = $"media/image{(Files.Count + 1).ToString(CultureInfo.InvariantCulture)}.{image.Extension}"; + _targets[image.Hash] = target; + Files.Add((target, image.Data, image.Extension)); + } + + return target; + } + } + + private static string Relationships(IEnumerable<(string Id, string Type, string Target)> relationships) + { + StringBuilder xml = new StringBuilder(XmlDeclaration).Append(""); + foreach ((string id, string type, string target) in relationships) + { + xml.Append($""); + } + + return xml.Append("").ToString(); + } + + /// A header or footer part: what it holds and how the section refers to it. + private sealed record HeaderFooterPart(bool IsHeader, HeaderFooterValues Type, string FileName, string RelationshipId, List Blocks); + + /// + /// The header and footer parts of the page setup. With a distinct first page, the first page always gets its own + /// parts (empty ones for "none"), so no application falls back to the default header there. + /// + private static List HeaderFooterParts(PageSetup page) + { + List<(bool IsHeader, HeaderFooterValues Type, List Blocks)> wanted = new List<(bool, HeaderFooterValues, List)>(); + if (page.Header is { } header) + { + wanted.Add((true, HeaderFooterValues.Default, header)); + } + + if (page.DistinctFirstPage) + { + wanted.Add((true, HeaderFooterValues.First, page.FirstHeader ?? new List())); + } + + if (page.Footer is { } footer) + { + wanted.Add((false, HeaderFooterValues.Default, footer)); + } + + if (page.DistinctFirstPage) + { + wanted.Add((false, HeaderFooterValues.First, page.FirstFooter ?? new List())); + } + + List parts = new List(); + int headers = 0; + int footers = 0; + for (int i = 0; i < wanted.Count; i++) + { + (bool isHeader, HeaderFooterValues type, List blocks) = wanted[i]; + string fileName = isHeader ? $"header{++headers}.xml" : $"footer{++footers}.xml"; + parts.Add(new HeaderFooterPart(isHeader, type, fileName, "rId" + (i + 2).ToString(CultureInfo.InvariantCulture), blocks)); + } + + return parts; + } + + private static string ContentTypes(List parts, MediaStore media, bool hasNumbering, bool hasFonts) + { + StringBuilder xml = new StringBuilder(XmlDeclaration) + .Append("") + .Append("") + .Append(""); + foreach (string extension in media.Files.Select(f => f.Extension).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)) + { + xml.Append($""); + } + + if (hasFonts) + { + xml.Append(""); + } + + xml.Append($"") + .Append($""); + if (hasFonts) + { + xml.Append("") + .Append(""); + } + if (hasNumbering) + { + xml.Append(""); + } + + foreach (HeaderFooterPart part in parts) + { + string type = part.IsHeader ? "header" : "footer"; + xml.Append($""); + } + + return xml + .Append($"") + .Append($"") + .Append("") + .ToString(); + } + + private static string PackageRelationships() => + XmlDeclaration + + "" + + $"" + + $"" + + $"" + + ""; + + private static string DocumentRelationships(List parts, IReadOnlyList<(string Id, string Target)> images, string? numberingRelationship, bool hasFonts) => + Relationships( + new[] { ("rId1", StylesRelationship, "styles.xml") } + .Concat(parts.Select(p => (p.RelationshipId, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/" + (p.IsHeader ? "header" : "footer"), p.FileName))) + .Concat(numberingRelationship is null ? [] : new[] { (numberingRelationship, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", "numbering.xml") }) + .Concat(images.Select(i => (i.Id, ImageRelationship, i.Target))) + .Concat(hasFonts + ? new[] + { + (SettingsRelationshipId, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", "settings.xml"), + (FontTableRelationshipId, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", "fontTable.xml"), + } + : [])); + + /// numbering.xml: an abstract numbering (bullet levels) and an instance per list style used. + private static Numbering NumberingPart(DocumentModel model, Dictionary numbering) + { + Numbering result = new Numbering(); + foreach ((ListStyleKey key, int id) in numbering) + { + AbstractNum abstractNum = new AbstractNum(new MultiLevelType { Val = MultiLevelValues.HybridMultilevel }) { AbstractNumberId = id - 1 }; + foreach ((int level, ListLevel definition) in model.Styles.Find(key)?.Levels ?? new SortedDictionary()) + { + // CT_Lvl order: start, numFmt, lvlText, lvlJc, pPr. + abstractNum.Append(new Level( + new StartNumberingValue { Val = 1 }, + new NumberingFormat { Val = NumberFormatValues.Bullet }, + new LevelText { Val = definition.Bullet }, + new LevelJustification { Val = LevelJustificationValues.Left }, + new PreviousParagraphProperties(new Indentation { Left = Twips(definition.Indent), Hanging = Twips(definition.Hanging) })) + { LevelIndex = level }); + } + + result.Append(abstractNum); + } + + foreach (int id in numbering.Values) + { + result.Append(new NumberingInstance(new AbstractNumId { Val = id - 1 }) { NumberID = id }); + } + + return result; + } + + private static string CoreProperties(DocumentModel model) + { + StringBuilder xml = new StringBuilder(XmlDeclaration) + .Append(""); + AppendElement(xml, "dc:title", model.Info.Title); + AppendElement(xml, "dc:subject", model.Info.Subject); + AppendElement(xml, "dc:creator", model.Info.Author); + AppendElement(xml, "dc:language", model.Language.Name); + return xml.Append("").ToString(); + } + + private static string CustomProperties(DocumentModel model) + { + StringBuilder xml = new StringBuilder(XmlDeclaration) + .Append(""); + int pid = 2; + foreach ((string name, string value) in model.Stamp.ToProperties()) + { + xml.Append("") + .Append("").Append(SecurityElement.Escape(value)).Append(""); + } + + return xml.Append("").ToString(); + } + + private static void AppendElement(StringBuilder xml, string name, string? value) + { + if (value != null) + { + xml.Append('<').Append(name).Append('>').Append(SecurityElement.Escape(value)).Append("'); + } + } + + // ── styles.xml ─────────────────────────────────────────────────────────────── + + private static Styles StylesPart(DocumentModel model) + { + StyleSheet sheet = model.Styles; + + RunPropertiesBaseStyle defaultRun = new RunPropertiesBaseStyle(); + defaultRun.Append(RunPropertyElements(sheet.Defaults)); + defaultRun.Append(new Languages { Val = model.Language.Name }); + + Styles styles = new Styles( + new DocDefaults( + new RunPropertiesDefault(defaultRun), + new ParagraphPropertiesDefault(new ParagraphPropertiesBaseStyle(new WidowControl())))); + + Style normal = new Style { Type = StyleValues.Paragraph, StyleId = NormalStyleId, Default = true }; + normal.Append(new StyleName { Val = "Normal" }, new PrimaryStyle()); + styles.Append(normal); + + Style defaultFont = new Style { Type = StyleValues.Character, StyleId = DefaultParagraphFontStyleId, Default = true }; + defaultFont.Append( + new StyleName { Val = "Default Paragraph Font" }, + new UIPriority { Val = 1 }, + new SemiHidden(), + new UnhideWhenUsed()); + styles.Append(defaultFont); + + foreach (ParagraphStyleDefinition definition in sheet.ParagraphStyles) + { + Style style = new Style { Type = StyleValues.Paragraph, StyleId = definition.Key.Id, CustomStyle = true }; + style.Append(new StyleName { Val = definition.Key.DisplayName }); + style.Append(new BasedOn { Val = definition.BasedOn?.Id ?? NormalStyleId }); + if (definition.Next is { } next) + { + style.Append(new NextParagraphStyle { Val = next.Id }); + } + + style.Append(new PrimaryStyle()); + + StyleParagraphProperties paragraph = new StyleParagraphProperties(); + paragraph.Append(ParagraphPropertyElements(definition.Paragraph)); + if (paragraph.HasChildren) + { + style.Append(paragraph); + } + + StyleRunProperties run = new StyleRunProperties(); + run.Append(RunPropertyElements(definition.Text)); + if (run.HasChildren) + { + style.Append(run); + } + + styles.Append(style); + } + + // Word (and LibreOffice, which maps "toc N" to its "Contents N") styles table-of-contents entries with the built-in + // "toc 1" … "toc 9": they are written based on the entry styles the definition chose, so they look the same. + foreach ((int level, ParagraphStyleKey entry) in TocEntries.Of(model.Body.Concat(model.Page.AllBlocks))) + { + Style style = new Style { Type = StyleValues.Paragraph, StyleId = "TOC" + level.ToString(CultureInfo.InvariantCulture) }; + style.Append( + new StyleName { Val = "toc " + level.ToString(CultureInfo.InvariantCulture) }, + new BasedOn { Val = entry.Id }, + new NextParagraphStyle { Val = NormalStyleId }, + new UIPriority { Val = 39 }, + new UnhideWhenUsed()); + styles.Append(style); + } + + foreach (CharacterStyleDefinition definition in sheet.CharacterStyles) + { + Style style = new Style { Type = StyleValues.Character, StyleId = definition.Key.Id, CustomStyle = true }; + style.Append(new StyleName { Val = definition.Key.DisplayName }); + style.Append(new BasedOn { Val = definition.BasedOn?.Id ?? DefaultParagraphFontStyleId }); + style.Append(new PrimaryStyle()); + + StyleRunProperties run = new StyleRunProperties(); + run.Append(RunPropertyElements(definition.Text)); + if (run.HasChildren) + { + style.Append(run); + } + + styles.Append(style); + } + + return styles; + } + + /// Run properties in the order of CT_RPr: rFonts, b, bCs, i, iCs, color, sz, szCs. + private static IEnumerable RunPropertyElements(Model.TextProperties text) + { + if (text.Font is { } font) + { + yield return new RunFonts { Ascii = font.Family, HighAnsi = font.Family, ComplexScript = font.Family, EastAsia = font.Family }; + } + + if (text.Bold is bool bold) + { + yield return bold ? new Bold() : new Bold { Val = false }; + yield return bold ? new BoldComplexScript() : new BoldComplexScript { Val = false }; + } + + if (text.Italic is bool italic) + { + yield return italic ? new Italic() : new Italic { Val = false }; + yield return italic ? new ItalicComplexScript() : new ItalicComplexScript { Val = false }; + } + + if (text.Color is { } color) + { + yield return new DocumentFormat.OpenXml.Wordprocessing.Color { Val = color.Hex }; + } + + if (text.Size is { } size) + { + string halfPoints = size.HalfPoints.ToString(CultureInfo.InvariantCulture); + yield return new FontSize { Val = halfPoints }; + yield return new FontSizeComplexScript { Val = halfPoints }; + } + } + + /// Paragraph properties in the order of CT_PPrBase: keepNext, keepLines, spacing, ind, jc, outlineLvl. + private static IEnumerable ParagraphPropertyElements(Model.ParagraphProperties paragraph) + { + if (paragraph.KeepWithNext is bool keepNext) + { + yield return keepNext ? new KeepNext() : new KeepNext { Val = false }; + } + + if (paragraph.KeepLinesTogether is bool keepLines) + { + yield return keepLines ? new KeepLines() : new KeepLines { Val = false }; + } + + if (paragraph.BorderBottom is { } bottom) + { + // CT_PPrBase: pBdr after keepLines, before spacing; w:space is in points. + yield return new ParagraphBorders(new BottomBorder + { + Val = BorderValues.Single, + Size = (uint)Math.Clamp((int)Math.Round(bottom.Width.Points * 8, MidpointRounding.AwayFromZero), 2, 96), + Space = (uint)Math.Round((paragraph.BorderBottomSpace ?? Length.Zero).Points, MidpointRounding.AwayFromZero), + Color = bottom.Color.Hex, + }); + } + + if (paragraph.SpaceBefore != null || paragraph.SpaceAfter != null || paragraph.LineHeight != null) + { + SpacingBetweenLines spacing = new SpacingBetweenLines(); + if (paragraph.SpaceBefore is { } before) + { + spacing.Before = Twips(before); + } + + if (paragraph.SpaceAfter is { } after) + { + spacing.After = Twips(after); + } + + if (paragraph.LineHeight is { } line) + { + switch (line.Rule) + { + case LineHeightRule.Proportional: + spacing.Line = ((int)Math.Round(line.Multiple * 240, MidpointRounding.AwayFromZero)).ToString(CultureInfo.InvariantCulture); + spacing.LineRule = LineSpacingRuleValues.Auto; + break; + case LineHeightRule.Exact: + spacing.Line = Twips(line.Height); + spacing.LineRule = LineSpacingRuleValues.Exact; + break; + default: + spacing.Line = Twips(line.Height); + spacing.LineRule = LineSpacingRuleValues.AtLeast; + break; + } + } + + yield return spacing; + } + + if (paragraph.IndentStart != null || paragraph.IndentEnd != null || paragraph.FirstLineIndent != null) + { + Indentation indentation = new Indentation(); + if (paragraph.IndentStart is { } start) + { + indentation.Left = Twips(start); + } + + if (paragraph.IndentEnd is { } end) + { + indentation.Right = Twips(end); + } + + if (paragraph.FirstLineIndent is { } first) + { + if (first < Length.Zero) + { + indentation.Hanging = Twips(-first); + } + else + { + indentation.FirstLine = Twips(first); + } + } + + yield return indentation; + } + + if (paragraph.Alignment is { } alignment) + { + yield return new Justification + { + Val = alignment switch + { + TextAlignment.Center => JustificationValues.Center, + TextAlignment.End => JustificationValues.Right, + TextAlignment.Justify => JustificationValues.Both, + _ => JustificationValues.Left, + }, + }; + } + + if (paragraph.OutlineLevel is int level) + { + yield return new OutlineLevel { Val = level - 1 }; + } + } + + private static string Twips(Length length) => length.Twips.ToString(CultureInfo.InvariantCulture); + + // ── document.xml ───────────────────────────────────────────────────────────── + + private static Document MainDocument(DocumentModel model, List parts, BlockWriter writer) + { + Body body = new Body(); + body.Append(EndWithParagraph(writer.WritePartBlocks(model.Body, model.Page.FrameWidth))); + body.Append(SectionProperties(model.Page, parts)); + return new Document(body); + } + + /// + /// The body, a header and a footer end with a paragraph, as Word keeps them: a part that ends with a table makes + /// LibreOffice's text export loop forever (measured with LibreOffice 26.8 in #279), and Word adds the paragraph on + /// open anyway. An empty part gets one empty paragraph. + /// + private static List EndWithParagraph(List elements) + { + if (elements.Count == 0 || elements[^1] is not Paragraph) + { + elements.Add(new Paragraph()); + } + + return elements; + } + + /// The section properties in the order of CT_SectPr: references, pgSz, pgMar, titlePg. + private static SectionProperties SectionProperties(PageSetup page, List parts) + { + SectionProperties section = new SectionProperties(); + foreach (HeaderFooterPart part in parts) + { + section.Append(part.IsHeader + ? new HeaderReference { Type = part.Type, Id = part.RelationshipId } + : new FooterReference { Type = part.Type, Id = part.RelationshipId }); + } + + section.Append(new DocumentFormat.OpenXml.Wordprocessing.PageSize { Width = (uint)page.Size.Width.Twips, Height = (uint)page.Size.Height.Twips }); + section.Append(new PageMargin + { + Top = page.Top.Twips, + Right = (uint)page.Right.Twips, + Bottom = page.Bottom.Twips, + Left = (uint)page.Left.Twips, + Header = (uint)page.HeaderDistance.Twips, + Footer = (uint)page.FooterDistance.Twips, + Gutter = 0, + }); + if (page.DistinctFirstPage) + { + section.Append(new TitlePage()); + } + + return section; + } + + /// Writes blocks of the body, a header or a footer. + private sealed class BlockWriter(DocumentModel model, MediaStore media, int firstRelationship, Dictionary numbering) + { + private readonly Dictionary _imageIds = new Dictionary(StringComparer.Ordinal); + + // Each raw block is rendered once (its callbacks see the frame of its container); spacer decisions read its root. + private readonly Dictionary _raw = new Dictionary(ReferenceEqualityComparer.Instance); + + /// Gets the image relationships of this part (id, target relative to word/). + public List<(string Id, string Target)> Images { get; } = new List<(string, string)>(); + + /// Writes blocks in a container whose text frame is wide. + public List WriteBlocks(IEnumerable blocks, Length frame) + { + List elements = new List(); + List flattened = BlockFlattener.Flatten(blocks).ToList(); + for (int i = 0; i < flattened.Count; i++) + { + List written = WriteBlock(flattened[i], frame).ToList(); + + // Word merges two tables that touch; a paragraph keeps them apart. + if (written.Count > 0 && written[0] is Table && elements.Count > 0 && elements[^1] is Table) + { + elements.Add(new Paragraph()); + } + + elements.AddRange(written); + if (Spacers.After(flattened[i], i + 1 < flattened.Count ? flattened[i + 1] : null, raw => RawIsParagraph(raw, frame))) + { + elements.Add(WriteParagraph(Spacers.Paragraph, frame)); + } + } + + return elements; + } + + /// + /// Writes the blocks of the body, a header or a footer. A part needs no spacer of its own at the end: a table + /// that a marker follows already has one after it. + /// + public List WritePartBlocks(IReadOnlyList blocks, Length frame) + { + return WriteBlocks(blocks, frame); + } + + /// Writes the blocks of a table cell; it ends with a paragraph also once Templify removed the markers. + public List WriteCellBlocks(IReadOnlyList blocks, Length frame) + { + List elements = WriteBlocks(blocks, frame); + if (Spacers.AtCellEnd(blocks, raw => RawIsParagraph(raw, frame))) + { + elements.Add(WriteParagraph(Spacers.Paragraph, frame)); + } + + return elements; + } + + private IEnumerable WriteBlock(Block block, Length frame) => block switch + { + ParagraphBlock paragraph => [WriteParagraph(paragraph, frame)], + // A paragraph of its own carries the break, so it survives when the engine removes the paragraphs around it. + PageBreakBlock => [new Paragraph(new Run(new Break { Type = BreakValues.Page }))], + // A marker is a paragraph of its own with one run, which is what the engine's block detection reads. + MarkerBlock marker => [MarkerParagraph(marker.Text)], + TableBlock table => WriteTable(table, frame), + RuleBlock rule => [RuleParagraph(rule, frame)], + SpacerBlock spacer => [SpacerParagraph(spacer)], + TocBlock toc => TocParagraphs(toc), + RawXmlBlock raw => [RawElement(RawXml(raw, frame))], + _ => throw new NotSupportedException($"Block {block.GetType().Name} is not supported by the DOCX writer."), + }; + + /// A raw block as a typed paragraph or table, so the writer's own checks (tables that touch, the + /// closing paragraph) see what it is. + private System.Xml.Linq.XElement RawXml(RawXmlBlock raw, Length frame) + { + if (!_raw.TryGetValue(raw, out System.Xml.Linq.XElement? element)) + { + element = RawContext.Check(raw.Raw.Docx(new RawContext(raw.Raw, frame)), RawContext.DocxRoots, "DOCX"); + _raw[raw] = element; + } + + return element; + } + + private bool RawIsParagraph(RawXmlBlock raw, Length frame) => RawXml(raw, frame).Name.LocalName != "tbl"; + + private static OpenXmlElement RawElement(System.Xml.Linq.XElement element) + { + string xml = element.ToString(System.Xml.Linq.SaveOptions.DisableFormatting); + return element.Name.LocalName == "tbl" ? new Table(xml) : new Paragraph(xml); + } + + /// A spacer: an empty unstyled paragraph whose line is exactly the height, without space around it. + private static Paragraph SpacerParagraph(SpacerBlock spacer) => new Paragraph(new ParagraphProperties( + new SpacingBetweenLines + { + Before = "0", + After = "0", + Line = spacer.Height.Twips.ToString(CultureInfo.InvariantCulture), + LineRule = LineSpacingRuleValues.Exact, + })); + + /// A rule: an empty 1 pt paragraph whose top border is the line (CT_PPrBase order: pBdr, spacing). + /// A shorter rule ends early: the paragraph's end indent is the rest of the frame. + private static Paragraph RuleParagraph(RuleBlock rule, Length frame) + { + ParagraphProperties properties = new ParagraphProperties( + new ParagraphBorders(Border(rule.Line)), + new SpacingBetweenLines + { + Before = rule.SpaceBefore.Twips.ToString(CultureInfo.InvariantCulture), + After = rule.SpaceAfter.Twips.ToString(CultureInfo.InvariantCulture), + Line = "20", + LineRule = LineSpacingRuleValues.Exact, + }); + if (rule.Width is { } width) + { + properties.Append(new Indentation { Right = (frame - width).Twips.ToString(CultureInfo.InvariantCulture) }); + } + + return new Paragraph(properties); + } + + /// + /// A table of contents as a TOC field marked dirty, without a cached result: Word and LibreOffice build it. The + /// switches use outline levels (\u) and never name the styles (\t): with \t LibreOffice lists every heading twice. + /// + /// + /// The field ends in a paragraph of its own, as Word writes a built contents: LibreOffice imports a TOC field whose + /// empty result sits in one paragraph as plain text, so converters that refresh indexes on load (Stirling-PDF) + /// would have no index to build (#295). + /// + private static Paragraph[] TocParagraphs(TocBlock toc) => + [ + new Paragraph( + new Run(new FieldChar { FieldCharType = FieldCharValues.Begin, Dirty = true }), + new Run(new FieldCode($" TOC \\o \"1-{toc.MaxLevel.ToString(CultureInfo.InvariantCulture)}\" \\h \\z \\u ") { Space = SpaceProcessingModeValues.Preserve }), + new Run(new FieldChar { FieldCharType = FieldCharValues.Separate })), + new Paragraph(new Run(new FieldChar { FieldCharType = FieldCharValues.End })), + ]; + + private static Paragraph MarkerParagraph(string text) => new Paragraph( + new ParagraphProperties(new ParagraphStyleId { Val = BuilderStyles.TemplateMarker.Id }), + new Run(new Text(text) { Space = SpaceProcessingModeValues.Preserve })); + + // ── tables ─────────────────────────────────────────────────────────────── + + private IEnumerable WriteTable(TableBlock table, Length frame) + { + TableStyleDefinition? style = model.Styles.Resolve(table); + Length[] widths = TableLayout.Resolve(table.Columns, table.ColumnFrame(frame)); + Insets padding = style?.Padding ?? TableStyleDefinition.DefaultPadding; + + // CT_TblPr order: tblW, tblBorders, tblLayout, tblCellMar, tblLook. + TableProperties properties = new TableProperties( + new TableWidth { Width = widths.Sum(w => w.Twips).ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }); + if (table.Indent is { } indent) + { + // CT_TblPr: tblInd after tblW (and jc), before tblBorders. Without a compatibility mode in settings.xml + // (Word's legacy layout, which LibreOffice follows) tblInd places the first cell's text, not the table's + // edge: the edge is tblInd minus the left cell margin, so the margin is added back. + properties.Append(new TableIndentation { Width = (indent + padding.Left).Twips, Type = TableWidthUnitValues.Dxa }); + } + if (style != null && (!style.Outer.IsEmpty || style.RowRule != null || style.ColumnRule != null)) + { + properties.Append(new TableBorders( + Border(style.Outer.Top), + Border(style.Outer.Left), + Border(style.Outer.Bottom), + Border(style.Outer.Right), + Border(style.RowRule), + Border(style.ColumnRule))); + } + + properties.Append(new DocumentFormat.OpenXml.Wordprocessing.TableLayout { Type = TableLayoutValues.Fixed }); + properties.Append(new TableCellMarginDefault( + new TopMargin { Width = padding.Top.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }, + new TableCellLeftMargin { Width = (short)padding.Left.Twips, Type = TableWidthValues.Dxa }, + new BottomMargin { Width = padding.Bottom.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }, + new TableCellRightMargin { Width = (short)padding.Right.Twips, Type = TableWidthValues.Dxa })); + + Table result = new Table(properties, new TableGrid(widths.Select(w => new GridColumn { Width = w.Twips.ToString(CultureInfo.InvariantCulture) }))); + foreach (TableRowItem item in table.Rows) + { + result.Append(WriteRowItem(item, widths, style)); + } + + List elements = []; + if (table.SpaceBefore is { } before && before > Length.Zero) + { + // Word tables have no space before: a 1 pt paragraph with the space carries it (as for the space after). + elements.Add(new Paragraph(new ParagraphProperties(new SpacingBetweenLines + { + Before = before.Twips.ToString(CultureInfo.InvariantCulture), + After = "0", + Line = "20", + LineRule = LineSpacingRuleValues.Exact, + }))); + } + + elements.Add(result); + if (model.Styles.SpaceAfterOf(table) is { } space && space > Length.Zero) + { + // Word tables have no space after: a 1 pt paragraph with the space carries it. + elements.Add(new Paragraph(new ParagraphProperties(new SpacingBetweenLines + { + Before = "0", + After = space.Twips.ToString(CultureInfo.InvariantCulture), + Line = "20", + LineRule = LineSpacingRuleValues.Exact, + }))); + } + + return elements; + } + + private IEnumerable WriteRowItem(TableRowItem item, Length[] widths, TableStyleDefinition? style) + { + switch (item) + { + case TableRowModel row: + yield return WriteRow(row, widths, style); + break; + + case TableRowLoop loop: + yield return MarkerRow(TemplateSyntax.ForEach(loop.ItemName, loop.Collection), widths); + foreach (OpenXmlElement row in loop.Rows.SelectMany(r => WriteRowItem(r, widths, style))) + { + yield return row; + } + + yield return MarkerRow(TemplateSyntax.EndForEach, widths); + break; + + case TableRowConditional conditional: + for (int i = 0; i < conditional.Branches.Count; i++) + { + (Condition condition, List rows) = conditional.Branches[i]; + yield return MarkerRow(i == 0 ? TemplateSyntax.If(condition) : TemplateSyntax.ElseIf(condition), widths); + foreach (OpenXmlElement row in rows.SelectMany(r => WriteRowItem(r, widths, style))) + { + yield return row; + } + } + + if (conditional.Else is { } otherwise) + { + yield return MarkerRow(TemplateSyntax.Else, widths); + foreach (OpenXmlElement row in otherwise.SelectMany(r => WriteRowItem(r, widths, style))) + { + yield return row; + } + } + + yield return MarkerRow(TemplateSyntax.EndIf, widths); + break; + + default: + throw new NotSupportedException($"Row item {item.GetType().Name} is not supported by the DOCX writer."); + } + } + + /// A marker row: one cell over the whole grid holding the marker paragraph; Templify removes it when filling. + private static TableRow MarkerRow(string marker, Length[] widths) + { + TableCellProperties properties = new TableCellProperties( + new TableCellWidth { Width = widths.Sum(w => w.Twips).ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }); + if (widths.Length > 1) + { + properties.Append(new GridSpan { Val = widths.Length }); + } + + return new TableRow(new TableCell(properties, MarkerParagraph(marker))); + } + + private TableRow WriteRow(TableRowModel row, Length[] widths, TableStyleDefinition? style) + { + TableRow result = new TableRow(); + TableRowProperties properties = new TableRowProperties(); + if (!row.AllowSplit) + { + properties.Append(new CantSplit()); + } + + if (row.IsHeader) + { + properties.Append(new TableHeader()); + } + + if (properties.HasChildren) + { + result.Append(properties); + } + + int column = 0; + foreach (TableCellModel cell in row.Cells) + { + // The cell width is the sum of its grid columns as written (each rounded once), so tcW and tblGrid agree. + int twips = widths.Skip(column).Take(cell.Span).Sum(w => w.Twips); + result.Append(WriteCell(cell, row.IsHeader, twips, TableLayout.CellFrame(widths, column, cell.Span, TableLayout.PaddingOf(cell, style)), style)); + column += cell.Span; + } + + return result; + } + + private TableCell WriteCell(TableCellModel cell, bool isHeader, int widthTwips, Length contentFrame, TableStyleDefinition? style) + { + // CT_TcPr order: tcW, gridSpan, tcBorders, shd, vAlign. + TableCellProperties properties = new TableCellProperties( + new TableCellWidth { Width = widthTwips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }); + if (cell.Span > 1) + { + properties.Append(new GridSpan { Val = cell.Span }); + } + + // The cell's own lines replace the table's on their sides; a header cell's bottom is the header rule. + Edges lines = cell.Borders ?? Edges.None; + BorderLine? bottom = lines.Bottom ?? (isHeader ? style?.HeaderRule : null); + if (!lines.IsEmpty || bottom != null) + { + // CT_TcBorders order: top, left, bottom, right. + TableCellBorders borders = new TableCellBorders(); + if (lines.Top is { } top) + { + borders.Append(Border(top)); + } + + if (lines.Left is { } left) + { + borders.Append(Border(left)); + } + + if (bottom is { } line) + { + borders.Append(Border(line)); + } + + if (lines.Right is { } right) + { + borders.Append(Border(right)); + } + + properties.Append(borders); + } + + Color? background = cell.Background ?? (isHeader ? style?.HeaderBackground : style?.BodyBackground); + if (background is { } fill) + { + properties.Append(new Shading { Val = ShadingPatternValues.Clear, Color = "auto", Fill = fill.Hex }); + } + + if (cell.Padding is { } own) + { + // CT_TcPr: tcMar after shd, before vAlign. + properties.Append(new TableCellMargin( + new TopMargin { Width = own.Top.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }, + new LeftMargin { Width = own.Left.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }, + new BottomMargin { Width = own.Bottom.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa }, + new RightMargin { Width = own.Right.Twips.ToString(CultureInfo.InvariantCulture), Type = TableWidthUnitValues.Dxa })); + } + + if (cell.VerticalAlignment is { } alignment) + { + properties.Append(new TableCellVerticalAlignment + { + Val = alignment switch + { + CellVerticalAlignment.Center => TableVerticalAlignmentValues.Center, + CellVerticalAlignment.Bottom => TableVerticalAlignmentValues.Bottom, + _ => TableVerticalAlignmentValues.Top, + }, + }); + } + + TableCell result = new TableCell(properties); + result.Append(WriteCellBlocks(cell.Content, contentFrame)); + + // A cell ends with a paragraph (schema and Word); an empty cell has one. + if (result.LastChild is not Paragraph) + { + result.Append(new Paragraph()); + } + + return result; + } + + private static T Border(BorderLine? line) + where T : BorderType, new() + { + return line is null + ? new T { Val = BorderValues.Nil } + : new T + { + Val = BorderValues.Single, + Size = (uint)Math.Clamp((int)Math.Round(line.Width.Points * 8, MidpointRounding.AwayFromZero), 2, 96), + Space = 0, + Color = line.Color.Hex, + }; + } + + private Paragraph WriteParagraph(ParagraphBlock block, Length frame) + { + Paragraph paragraph = new Paragraph(); + bool rightTab = block.Inlines.OfType().Any(); + ParagraphStyleKey? paragraphStyle = block.Style ?? (block.List is { } listItem ? model.Styles.Find(listItem.Style)?.ItemStyle : null); + ParagraphOverrides? options = block.Options; + if (paragraphStyle != null || rightTab || block.List != null || options != null) + { + // CT_PPrBase order: pStyle, keepNext, keepLines, …, numPr, …, tabs, …, spacing. + ParagraphProperties properties = new ParagraphProperties(); + if (paragraphStyle is { } style) + { + properties.Append(new ParagraphStyleId { Val = style.Id }); + } + + if (options?.KeepWithNext is { } keepNext) + { + properties.Append(keepNext ? new KeepNext() : new KeepNext { Val = false }); + } + + if (options?.KeepLinesTogether is { } keepLines) + { + properties.Append(keepLines ? new KeepLines() : new KeepLines { Val = false }); + } + + if (block.List is { } item && numbering.TryGetValue(item.Style, out int numId)) + { + properties.Append(new NumberingProperties(new NumberingLevelReference { Val = item.Level }, new NumberingId { Val = numId })); + } + + if (rightTab) + { + // Word measures tab stops from the text frame's start, whatever the indent. + properties.Append(new Tabs(new TabStop { Val = TabStopValues.Right, Position = frame.Twips })); + } + + if (options is { SpaceBefore: not null } or { SpaceAfter: not null }) + { + // Only the attributes set: Word takes the others from the style. + SpacingBetweenLines spacing = new SpacingBetweenLines(); + if (options.SpaceBefore is { } before) + { + spacing.Before = before.Twips.ToString(CultureInfo.InvariantCulture); + } + + if (options.SpaceAfter is { } after) + { + spacing.After = after.Twips.ToString(CultureInfo.InvariantCulture); + } + + properties.Append(spacing); + } + + paragraph.Append(properties); + } + + foreach (Inline inline in block.Inlines) + { + paragraph.Append(WriteInline(inline)); + } + + return paragraph; + } + + private IEnumerable WriteInline(Inline inline) + { + switch (inline) + { + case TextInline text: + Run textRun = NewRun(inline.Style); + foreach ((TextPieceKind kind, string piece) in TextPieces.Split(text.Text)) + { + textRun.Append(kind switch + { + TextPieceKind.Tab => new TabChar(), + TextPieceKind.LineBreak => new Break(), + _ => new Text(piece) { Space = SpaceProcessingModeValues.Preserve }, + }); + } + + return [textRun]; + + case ValueInline value: + // One run per placeholder: the engine then never has to join a placeholder across runs, and the + // value takes this run's formatting. + Run valueRun = NewRun(inline.Style); + valueRun.Append(new Text(TemplateSyntax.Placeholder(value.Path, value.Format)) { Space = SpaceProcessingModeValues.Preserve }); + return [valueRun]; + + case RightTabInline: + Run tabRun = NewRun(null); + tabRun.Append(new TabChar()); + return [tabRun]; + + case ImageInline image: + Run imageRun = NewRun(null); + imageRun.Append(Drawing(image)); + return [imageRun]; + + case InlineConditional conditional: + // Markers and content stay in their own runs; the engine resolves the conditional inside the paragraph. + List runs = new List(); + for (int i = 0; i < conditional.Branches.Count; i++) + { + runs.Add(MarkerRun(i == 0 ? TemplateSyntax.If(conditional.Branches[i].Condition) : TemplateSyntax.ElseIf(conditional.Branches[i].Condition))); + runs.AddRange(conditional.Branches[i].Inlines.SelectMany(WriteInline)); + } + + if (conditional.Else is { } otherwise) + { + runs.Add(MarkerRun(TemplateSyntax.Else)); + runs.AddRange(otherwise.SelectMany(WriteInline)); + } + + runs.Add(MarkerRun(TemplateSyntax.EndIf)); + return runs; + + case ExpressionInline expression: + return [MarkerRun(TemplateSyntax.Expression(expression.Condition, expression.Format))]; + + case PageFieldInline field: + // A complex field with a cached result; Word and LibreOffice compute the value when they lay out. + string instruction = field.Field == PageField.Number ? " PAGE " : " NUMPAGES "; + return + [ + FieldRun(field.Style, new FieldChar { FieldCharType = FieldCharValues.Begin }), + FieldRun(field.Style, new FieldCode(instruction) { Space = SpaceProcessingModeValues.Preserve }), + FieldRun(field.Style, new FieldChar { FieldCharType = FieldCharValues.Separate }), + FieldRun(field.Style, new Text("1")), + FieldRun(field.Style, new FieldChar { FieldCharType = FieldCharValues.End }), + ]; + + default: + throw new NotSupportedException($"Inline {inline.GetType().Name} is not supported by the DOCX writer."); + } + } + + /// An inline picture: DrawingML with the relationship of this part and a document-wide unique id. + private Drawing Drawing(ImageInline image) + { + string target = media.Target(image.Image); + if (!_imageIds.TryGetValue(target, out string? relationship)) + { + relationship = "rId" + (firstRelationship + Images.Count).ToString(CultureInfo.InvariantCulture); + _imageIds[target] = relationship; + Images.Add((relationship, target)); + } + + uint id = media.NextDrawingId++; + long cx = Emu(image.Width); + long cy = Emu(image.Height); + string name = "Picture " + id.ToString(CultureInfo.InvariantCulture); + return new Drawing(new DW.Inline( + new DW.Extent { Cx = cx, Cy = cy }, + new DW.EffectExtent { LeftEdge = 0, TopEdge = 0, RightEdge = 0, BottomEdge = 0 }, + new DW.DocProperties { Id = id, Name = name, Description = image.AltText }, + new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks { NoChangeAspect = true }), + new A.Graphic(new A.GraphicData( + new PIC.Picture( + new PIC.NonVisualPictureProperties( + new PIC.NonVisualDrawingProperties { Id = 0U, Name = name, Description = image.AltText }, + new PIC.NonVisualPictureDrawingProperties()), + new PIC.BlipFill(new A.Blip { Embed = relationship }, new A.Stretch(new A.FillRectangle())), + new PIC.ShapeProperties( + new A.Transform2D(new A.Offset { X = 0L, Y = 0L }, new A.Extents { Cx = cx, Cy = cy }), + new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }))) + { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })) + { + DistanceFromTop = 0U, + DistanceFromBottom = 0U, + DistanceFromLeft = 0U, + DistanceFromRight = 0U, + }); + } + + /// English metric units: 12 700 per point. + private static long Emu(Length length) => (long)Math.Round(length.Points * 12700, MidpointRounding.AwayFromZero); + + private static Run MarkerRun(string text) => new Run(new Text(text) { Space = SpaceProcessingModeValues.Preserve }); + + private static Run FieldRun(CharacterStyleKey? style, OpenXmlElement content) + { + Run run = NewRun(style); + run.Append(content); + return run; + } + + private static Run NewRun(CharacterStyleKey? style) + { + Run run = new Run(); + if (style != null) + { + run.Append(new RunProperties(new RunStyle { Val = style.Id })); + } + + return run; + } + } + + private static byte[] Utf8(string xml) => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(xml); +} diff --git a/src/TriasDev.Templify.Builder/Writers/OdtWriter.cs b/src/TriasDev.Templify.Builder/Writers/OdtWriter.cs new file mode 100644 index 00000000..fc0850a4 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/OdtWriter.cs @@ -0,0 +1,1311 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Writers; + +/// +/// Writes a as an OpenDocument Text package (.odt, ODF 1.3). +/// +internal static class OdtWriter +{ + private const string MediaType = "application/vnd.oasis.opendocument.text"; + private const string OdfVersion = "1.3"; + + /// LibreOffice's default paragraph style ("Default Paragraph Style"); the builder reserves the name. + private const string StandardStyleName = "Standard"; + + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _svg = "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"; + private static readonly XNamespace _xlink = "http://www.w3.org/1999/xlink"; + private static readonly XNamespace _meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; + private static readonly XNamespace _dc = "http://purl.org/dc/elements/1.1/"; + private static readonly XNamespace _manifest = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; + + public static byte[] Write(DocumentModel model) + { + PictureStore pictures = new PictureStore(); + byte[] content = Serialize(Content(model, pictures)); + byte[] styles = Serialize(Styles(model, pictures)); + List parts = new List + { + // ODF 1.3 part 2, 3.3: the first entry, stored, without an extra field. + new PackagePart("mimetype", Encoding.ASCII.GetBytes(MediaType), Stored: true), + new PackagePart("content.xml", content), + new PackagePart("styles.xml", styles), + new PackagePart("meta.xml", Serialize(Meta(model))), + }; + parts.AddRange(pictures.Files.Select(f => new PackagePart(f.Path, f.Image.Data))); + List fonts = model.Styles.EmbeddedFonts.Select(f => f.Embedding!).DistinctBy(f => f.Hash).ToList(); + parts.AddRange(fonts.Select(f => new PackagePart(FontPath(f), f.Data))); + parts.Add(new PackagePart("META-INF/manifest.xml", Serialize(Manifest(pictures, fonts)))); + return DeterministicZip.Create(parts); + } + + /// The pictures of a package: each distinct image once in Pictures/, named by its content. + private sealed class PictureStore + { + private readonly Dictionary _paths = new Dictionary(StringComparer.Ordinal); + + public List<(string Path, ImageSource Image)> Files { get; } = new List<(string, ImageSource)>(); + + public string Path(ImageSource image) + { + if (!_paths.TryGetValue(image.Hash, out string? path)) + { + path = $"Pictures/{image.Hash[..32]}.{image.Extension}"; + _paths[image.Hash] = path; + Files.Add((path, image)); + } + + return path; + } + } + + // ── content.xml ────────────────────────────────────────────────────────────── + + private static XElement Content(DocumentModel model, PictureStore pictures) + { + BlockWriter writer = new BlockWriter(model, "Templify", pictures); + XElement text = new XElement(_office + "text", writer.WritePartBlocks(model.Body, model.Page.FrameWidth)); + + return new XElement( + _office + "document-content", + Namespaces(_office, _text, _style, _fo, _svg, _table, _draw, _xlink), + new XAttribute(_office + "version", OdfVersion), + new XElement(_office + "automatic-styles", writer.AutomaticStyles), + new XElement(_office + "body", text)); + } + + /// + /// Writes blocks of the body (content.xml) or of headers and footers (styles.xml) and collects the automatic + /// styles they need; each part gets its own name prefix. + /// + private sealed class BlockWriter(DocumentModel model, string prefix, PictureStore pictures) + { + private int _images; + + private readonly Dictionary _paragraphStyles = new Dictionary(StringComparer.Ordinal); + private bool _pageBreakStyle; + + public List AutomaticStyles { get; } = new List(); + + private readonly Dictionary _cellStyles = new Dictionary(StringComparer.Ordinal); + + // Each raw block is rendered once (its callbacks see the frame of its container); spacer decisions read its root. + private readonly Dictionary _raw = new Dictionary(ReferenceEqualityComparer.Instance); + private int _tables; + private bool _rowKeepStyle; + + /// Gets the width of the page's text frame. + public Length PageFrame => model.Page.FrameWidth; + + /// Writes blocks in a container whose text frame is wide. + public List WriteBlocks(IEnumerable blocks, Length frame) + { + List flattened = BlockFlattener.Flatten(blocks).ToList(); + List elements = new List(); + for (int i = 0; i < flattened.Count; i++) + { + elements.Add(WriteBlock(flattened[i], frame)); + if (Spacers.After(flattened[i], i + 1 < flattened.Count ? flattened[i + 1] : null, raw => RawIsParagraph(raw, frame))) + { + elements.Add(WriteParagraph(Spacers.Paragraph, frame)); + } + } + + return elements; + } + + /// + /// Writes the blocks of the body, a header or a footer. A part needs no spacer of its own at the end: a table + /// that a marker follows already has one after it. + /// + public List WritePartBlocks(IReadOnlyList blocks, Length frame) + { + return WriteBlocks(TopOfPage.Apply(blocks), frame); + } + + private XElement WriteBlock(Block block, Length frame) => block switch + { + ParagraphBlock { List: { } item } paragraph => WrapInList(WriteParagraph(paragraph, frame), item), + ParagraphBlock paragraph => WriteParagraph(paragraph, frame), + TableBlock table => WriteTable(table, frame), + RuleBlock rule => new XElement(_text + "p", new XAttribute(_text + "style-name", RuleStyle(rule, frame))), + SpacerBlock spacer => new XElement(_text + "p", new XAttribute(_text + "style-name", SpacerStyle(spacer))), + TocBlock toc => TableOfContents(toc), + RawXmlBlock raw => new XElement(RawXml(raw, frame)), + // An empty paragraph of its own carries the break (break-after: no empty line on the new page), so it + // survives when the engine removes the paragraphs around it. + PageBreakBlock => new XElement(_text + "p", new XAttribute(_text + "style-name", PageBreakStyle())), + MarkerBlock marker => WriteMarker(marker), + _ => throw new NotSupportedException($"Block {block.GetType().Name} is not supported by the ODT writer."), + }; + + private XElement RawXml(RawXmlBlock raw, Length frame) + { + if (!_raw.TryGetValue(raw, out XElement? element)) + { + element = RawContext.Check(raw.Raw.Odt(new RawContext(raw.Raw, frame)), RawContext.OdtRoots, "ODT"); + _raw[raw] = element; + } + + return element; + } + + private bool RawIsParagraph(RawXmlBlock raw, Length frame) => RawXml(raw, frame).Name.LocalName != "table"; + + private string PageBreakStyle() + { + string name = prefix + "PageBreak"; + if (!_pageBreakStyle) + { + _pageBreakStyle = true; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "parent-style-name", StandardStyleName), + new XElement(_style + "paragraph-properties", new XAttribute(_fo + "break-after", "page")))); + } + + return name; + } + + /// + /// An automatic paragraph style on top of a named one: a right tab stop at the end of the frame and the + /// paragraph's own options. ODF measures tab stops from the paragraph's indent, so the style's start indent is + /// subtracted. LibreOffice reads the top and bottom margin as one item, so when either is set both are written, + /// the other resolved through the style chain. Equal combinations share one style. + /// + private string AutomaticParagraphStyle(ParagraphStyleKey? parent, Length? rightTabFrame, ParagraphOverrides? options) + { + string parentName = parent?.Id ?? StandardStyleName; + XElement properties = new XElement(_style + "paragraph-properties"); + if (options is { SpaceBefore: not null } or { SpaceAfter: not null }) + { + properties.Add( + new XAttribute(_fo + "margin-top", (options.SpaceBefore ?? model.Styles.SpaceBeforeOf(parent)).ToString()), + new XAttribute(_fo + "margin-bottom", (options.SpaceAfter ?? model.Styles.SpaceAfterOf(parent)).ToString())); + } + + if (options?.KeepLinesTogether is { } keepLines) + { + properties.Add(new XAttribute(_fo + "keep-together", keepLines ? "always" : "auto")); + } + + if (options?.KeepWithNext is { } keepNext) + { + properties.Add(new XAttribute(_fo + "keep-with-next", keepNext ? "always" : "auto")); + } + + if (rightTabFrame is { } frame) + { + properties.Add(new XElement( + _style + "tab-stops", + new XElement( + _style + "tab-stop", + new XAttribute(_style + "position", (frame - model.Styles.IndentStartOf(parent)).ToString()), + new XAttribute(_style + "type", "right")))); + } + + string signature = parentName + "|" + properties.ToString(SaveOptions.DisableFormatting); + if (!_paragraphStyles.TryGetValue(signature, out string? name)) + { + // Tab-only styles keep their earlier names (Tab1, Tab2, …), so templates without options are unchanged; + // any style with options (also a right tab) is a Para style. + string kind = prefix + (options is null ? "Tab" : "Para"); + name = kind + (_paragraphStyles.Values.Count(v => v.StartsWith(kind, StringComparison.Ordinal)) + 1).ToString(CultureInfo.InvariantCulture); + _paragraphStyles[signature] = name; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "parent-style-name", parentName), + properties)); + } + + return name; + } + + // ── tables ─────────────────────────────────────────────────────────────── + + private XElement WriteTable(TableBlock table, Length frame) + { + TableStyleDefinition? style = model.Styles.Resolve(table); + Length[] widths = TableLayout.Resolve(table.Columns, table.ColumnFrame(frame)); + string name = prefix + "Table" + (++_tables).ToString(CultureInfo.InvariantCulture); + + XElement tableProperties = new XElement( + _style + "table-properties", + new XAttribute(_style + "width", widths.Aggregate(Length.Zero, (a, b) => a + b).ToString()), + new XAttribute(_table + "align", "left"), + new XAttribute(_table + "border-model", "collapsing")); + if (table.Indent is { } indent) + { + tableProperties.Add(new XAttribute(_fo + "margin-left", indent.ToString())); + } + + if (table.SpaceBefore is { } before) + { + tableProperties.Add(new XAttribute(_fo + "margin-top", before.ToString())); + } + + if (model.Styles.SpaceAfterOf(table) is { } space) + { + tableProperties.Add(new XAttribute(_fo + "margin-bottom", space.ToString())); + } + + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "table"), + tableProperties)); + + XElement result = new XElement(_table + "table", new XAttribute(_table + "name", name), new XAttribute(_table + "style-name", name)); + for (int i = 0; i < widths.Length; i++) + { + string columnStyle = $"{name}.C{(i + 1).ToString(CultureInfo.InvariantCulture)}"; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", columnStyle), + new XAttribute(_style + "family", "table-column"), + new XElement(_style + "table-column-properties", new XAttribute(_style + "column-width", widths[i].ToString())))); + result.Add(new XElement(_table + "table-column", new XAttribute(_table + "style-name", columnStyle))); + } + + // Collapsed borders: every cell carries the lines of its edges. Only a plain row at the template's edge carries + // the outer line there: a loop's row is cloned (every clone would keep it) and a conditional row may be removed + // (taking it along). Such an edge gets a 1 pt row of its own that carries the outer line instead. + TableEdges edges = new TableEdges(table.Rows.FirstOrDefault() as TableRowModel, table.Rows.LastOrDefault() as TableRowModel); + if (table.Rows.Count > 0 && edges.First is null && style?.Outer.Top is { } outerTop) + { + result.Add(EdgeRow(widths.Length, top: null, bottom: outerTop)); + } + + XElement? headerRows = null; + foreach (TableRowItem item in table.Rows) + { + foreach (XElement row in WriteRowItem(item, edges, widths, style)) + { + if (item is TableRowModel { IsHeader: true }) + { + headerRows ??= new XElement(_table + "table-header-rows"); + headerRows.Add(row); + if (headerRows.Parent is null) + { + result.Add(headerRows); + } + } + else + { + result.Add(row); + } + } + } + + if (table.Rows.Count > 0 && edges.Last is null && style?.Outer.Bottom is { } outerBottom) + { + result.Add(EdgeRow(widths.Length, top: outerBottom, bottom: null)); + } + + return result; + } + + /// The plain rows at the template's top and bottom edge; null where a loop or conditional is. + private sealed record TableEdges(TableRowModel? First, TableRowModel? Last); + + /// A 1 pt row over all columns that carries an outer line of the table (no side lines, no padding). + private XElement EdgeRow(int columns, BorderLine? top, BorderLine? bottom) + { + XElement cell = new XElement( + _table + "table-cell", + new XAttribute(_table + "style-name", CellStyle(top, bottom, null, null, null, null, Insets.Of(Length.Zero, Length.Zero))), + new XAttribute(_office + "value-type", "string"), + WriteBlock(new SpacerBlock(1.Pt()), Length.Zero)); + if (columns > 1) + { + cell.Add(new XAttribute(_table + "number-columns-spanned", columns)); + } + + XElement row = new XElement(_table + "table-row", cell); + for (int i = 1; i < columns; i++) + { + row.Add(new XElement(_table + "covered-table-cell")); + } + + return row; + } + + private IEnumerable WriteRowItem(TableRowItem item, TableEdges edges, Length[] widths, TableStyleDefinition? style) + { + switch (item) + { + case TableRowModel row: + yield return WriteRow(row, edges, widths, style); + break; + + case TableRowLoop loop: + yield return MarkerRow(TemplateSyntax.ForEach(loop.ItemName, loop.Collection), widths.Length); + foreach (XElement row in loop.Rows.SelectMany(r => WriteRowItem(r, edges, widths, style))) + { + yield return row; + } + + yield return MarkerRow(TemplateSyntax.EndForEach, widths.Length); + break; + + case TableRowConditional conditional: + for (int i = 0; i < conditional.Branches.Count; i++) + { + (Condition condition, List branchRows) = conditional.Branches[i]; + yield return MarkerRow(i == 0 ? TemplateSyntax.If(condition) : TemplateSyntax.ElseIf(condition), widths.Length); + foreach (XElement row in branchRows.SelectMany(r => WriteRowItem(r, edges, widths, style))) + { + yield return row; + } + } + + if (conditional.Else is { } otherwise) + { + yield return MarkerRow(TemplateSyntax.Else, widths.Length); + foreach (XElement row in otherwise.SelectMany(r => WriteRowItem(r, edges, widths, style))) + { + yield return row; + } + } + + yield return MarkerRow(TemplateSyntax.EndIf, widths.Length); + break; + + default: + throw new NotSupportedException($"Row item {item.GetType().Name} is not supported by the ODT writer."); + } + } + + /// A marker row: one cell spanning every column with the marker paragraph; Templify removes it when filling. + private XElement MarkerRow(string marker, int columns) + { + XElement cell = new XElement( + _table + "table-cell", + new XAttribute(_table + "style-name", CellStyle(null, null, null, null, null, null, Insets.Of(Length.Zero, Length.Zero))), + new XAttribute(_office + "value-type", "string"), + WriteMarker(new MarkerBlock(marker))); + if (columns > 1) + { + cell.Add(new XAttribute(_table + "number-columns-spanned", columns)); + } + + XElement row = new XElement(_table + "table-row", cell); + for (int i = 1; i < columns; i++) + { + row.Add(new XElement(_table + "covered-table-cell")); + } + + return row; + } + + private XElement WriteRow(TableRowModel row, TableEdges edges, Length[] widths, TableStyleDefinition? style) + { + XElement result = new XElement(_table + "table-row"); + if (!row.AllowSplit) + { + result.Add(new XAttribute(_table + "style-name", RowKeepStyle())); + } + + bool first = ReferenceEquals(row, edges.First); + bool last = ReferenceEquals(row, edges.Last); + int column = 0; + foreach (TableCellModel cell in row.Cells) + { + // Every body row's top is the row rule, also directly under the header: the collapsing model draws the + // wider of the header's bottom (the header rule) and this top. A row loop clones the row, so its top must + // be what goes between two items — the clones then keep their row rules even when the loop's row is the + // table's last row (whose bottom is the outer border). + // The cell's own lines replace these on their sides. + Edges own = cell.Borders ?? Edges.None; + BorderLine? top = own.Top ?? (first ? style?.Outer.Top : style?.RowRule); + BorderLine? bottom = own.Bottom ?? (row.IsHeader && style?.HeaderRule is { } rule ? rule : last ? style?.Outer.Bottom : style?.RowRule); + BorderLine? left = own.Left ?? (column == 0 ? style?.Outer.Left : style?.ColumnRule); + BorderLine? right = own.Right ?? (column + cell.Span >= widths.Length ? style?.Outer.Right : style?.ColumnRule); + Color? background = cell.Background ?? (row.IsHeader ? style?.HeaderBackground : style?.BodyBackground); + + XElement element = new XElement( + _table + "table-cell", + new XAttribute(_table + "style-name", CellStyle(top, bottom, left, right, background, cell.VerticalAlignment, TableLayout.PaddingOf(cell, style))), + new XAttribute(_office + "value-type", "string")); + if (cell.Span > 1) + { + element.Add(new XAttribute(_table + "number-columns-spanned", cell.Span)); + } + + Length cellFrame = TableLayout.CellFrame(widths, column, cell.Span, TableLayout.PaddingOf(cell, style)); + List content = WriteBlocks(cell.Content, cellFrame); + if (Spacers.AtCellEnd(cell.Content, raw => RawIsParagraph(raw, cellFrame))) + { + // Also once Templify removed the markers, the cell ends with a paragraph. + content.Add(WriteParagraph(Spacers.Paragraph, cellFrame)); + } + + element.Add(content.Count > 0 + ? content + : content.Append(new XElement(_text + "p", new XAttribute(_text + "style-name", StandardStyleName)))); + result.Add(element); + for (int i = 1; i < cell.Span; i++) + { + result.Add(new XElement(_table + "covered-table-cell")); + } + + column += cell.Span; + } + + return result; + } + + private readonly Dictionary _ruleStyles = new Dictionary(StringComparer.Ordinal); + private int _tocs; + + // Document-wide, as in DOCX: a table of contents without entry styles uses those of the others. + private readonly Lazy> _tocEntries = new Lazy>(() => TocEntries.Of(model.Body.Concat(model.Page.AllBlocks))); + + /// A table of contents over the outline levels, with an empty index body (filled when a user updates it). + private XElement TableOfContents(TocBlock toc) + { + XElement source = new XElement( + _text + "table-of-content-source", + new XAttribute(_text + "outline-level", toc.MaxLevel), + new XAttribute(_text + "use-index-marks", "false"), + new XElement(_text + "index-title-template")); + for (int level = 1; level <= toc.MaxLevel; level++) + { + source.Add(new XElement( + _text + "table-of-content-entry-template", + new XAttribute(_text + "outline-level", level), + new XAttribute(_text + "style-name", _tocEntries.Value.GetValueOrDefault(level)?.Id ?? "Contents_20_" + level.ToString(CultureInfo.InvariantCulture)), + new XElement(_text + "index-entry-link-start"), + new XElement(_text + "index-entry-text"), + new XElement(_text + "index-entry-tab-stop", new XAttribute(_style + "type", "right"), new XAttribute(_style + "leader-char", ".")), + new XElement(_text + "index-entry-page-number"), + new XElement(_text + "index-entry-link-end"))); + } + + return new XElement( + _text + "table-of-content", + new XAttribute(_text + "protected", "false"), + new XAttribute(_text + "name", prefix + "Toc" + (++_tocs).ToString(CultureInfo.InvariantCulture)), + source, + new XElement(_text + "index-body")); + } + + /// An automatic paragraph style for a spacer: no margins and a fixed line height; equal heights share one. + private string SpacerStyle(SpacerBlock spacer) + { + string height = spacer.Height.ToString(); + if (!_spacerStyles.TryGetValue(height, out string? name)) + { + name = prefix + "Gap" + (_spacerStyles.Count + 1).ToString(CultureInfo.InvariantCulture); + _spacerStyles[height] = name; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "parent-style-name", StandardStyleName), + new XElement( + _style + "paragraph-properties", + new XAttribute(_fo + "margin-top", "0pt"), + new XAttribute(_fo + "margin-bottom", "0pt"), + new XAttribute(_fo + "line-height", height)))); + } + + return name; + } + + private readonly Dictionary _spacerStyles = new Dictionary(StringComparer.Ordinal); + + /// An automatic paragraph style for a rule: a 1 pt line height and the line as the top border. + private string RuleStyle(RuleBlock rule, Length frame) + { + XElement properties = new XElement( + _style + "paragraph-properties", + new XAttribute(_fo + "margin-top", rule.SpaceBefore.ToString()), + new XAttribute(_fo + "margin-bottom", rule.SpaceAfter.ToString()), + new XAttribute(_fo + "line-height", "1pt"), + new XAttribute(_fo + "border-top", Border(rule.Line)), + new XAttribute(_fo + "border-bottom", "none"), + new XAttribute(_fo + "border-left", "none"), + new XAttribute(_fo + "border-right", "none"), + new XAttribute(_fo + "padding", "0pt")); + if (rule.Width is { } width) + { + // A shorter rule ends early: the paragraph's end margin is the rest of the frame. + properties.Add(new XAttribute(_fo + "margin-right", (frame - width).ToString())); + } + + string signature = properties.ToString(SaveOptions.DisableFormatting); + if (!_ruleStyles.TryGetValue(signature, out string? name)) + { + name = prefix + "Rule" + (_ruleStyles.Count + 1).ToString(CultureInfo.InvariantCulture); + _ruleStyles[signature] = name; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "parent-style-name", StandardStyleName), + properties, + new XElement(_style + "text-properties", new XAttribute(_fo + "font-size", "1pt")))); + } + + return name; + } + + private string RowKeepStyle() + { + string name = prefix + "RowKeep"; + if (!_rowKeepStyle) + { + _rowKeepStyle = true; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "table-row"), + new XElement(_style + "table-row-properties", new XAttribute(_fo + "keep-together", "always")))); + } + + return name; + } + + /// A cell style for a set of borders, background, alignment and padding; equal cells share one. + private string CellStyle(BorderLine? top, BorderLine? bottom, BorderLine? left, BorderLine? right, Color? background, CellVerticalAlignment? alignment, Insets padding) + { + XElement properties = new XElement( + _style + "table-cell-properties", + new XAttribute(_fo + "padding-top", padding.Top.ToString()), + new XAttribute(_fo + "padding-bottom", padding.Bottom.ToString()), + new XAttribute(_fo + "padding-left", padding.Left.ToString()), + new XAttribute(_fo + "padding-right", padding.Right.ToString()), + new XAttribute(_fo + "border-top", Border(top)), + new XAttribute(_fo + "border-bottom", Border(bottom)), + new XAttribute(_fo + "border-left", Border(left)), + new XAttribute(_fo + "border-right", Border(right))); + if (background is { } fill) + { + properties.Add(new XAttribute(_fo + "background-color", "#" + fill.Hex.ToLowerInvariant())); + } + + if (alignment is { } vertical) + { + properties.Add(new XAttribute(_style + "vertical-align", vertical switch + { + CellVerticalAlignment.Center => "middle", + CellVerticalAlignment.Bottom => "bottom", + _ => "top", + })); + } + + string signature = properties.ToString(SaveOptions.DisableFormatting); + if (!_cellStyles.TryGetValue(signature, out string? name)) + { + name = prefix + "Cell" + (_cellStyles.Count + 1).ToString(CultureInfo.InvariantCulture); + _cellStyles[signature] = name; + AutomaticStyles.Add(new XElement( + _style + "style", + new XAttribute(_style + "name", name), + new XAttribute(_style + "family", "table-cell"), + properties)); + } + + return name; + } + + private static string Border(BorderLine? line) => + line is null ? "none" : $"{line.Width} solid #{line.Color.Hex.ToLowerInvariant()}"; + + /// An image as a character: draw:frame with the picture, its title and description (alternative text). + private XElement Frame(ImageInline image) => + new XElement( + _draw + "frame", + new XAttribute(_draw + "name", prefix + "Image" + (++_images).ToString(CultureInfo.InvariantCulture)), + new XAttribute(_text + "anchor-type", "as-char"), + new XAttribute(_svg + "width", image.Width.ToString()), + new XAttribute(_svg + "height", image.Height.ToString()), + new XAttribute(_draw + "z-index", 0), + new XElement( + _draw + "image", + new XAttribute(_xlink + "href", pictures.Path(image.Image)), + new XAttribute(_xlink + "type", "simple"), + new XAttribute(_xlink + "show", "embed"), + new XAttribute(_xlink + "actuate", "onLoad")), + new XElement(_svg + "title", image.AltText), + new XElement(_svg + "desc", image.AltText)); + + private void WriteInlines(WhitespaceEncoder encoder, IEnumerable inlines) + { + foreach (Inline inline in inlines) + { + if (inline.Style is { } characterStyle) + { + encoder.BeginSpan(new XElement(_text + "span", new XAttribute(_text + "style-name", characterStyle.Id))); + } + + switch (inline) + { + case TextInline text: + foreach ((TextPieceKind kind, string piece) in TextPieces.Split(text.Text)) + { + switch (kind) + { + case TextPieceKind.Tab: + encoder.Element(new XElement(_text + "tab")); + break; + case TextPieceKind.LineBreak: + encoder.Element(new XElement(_text + "line-break")); + break; + default: + encoder.Text(piece); + break; + } + } + + break; + + case ValueInline value: + encoder.Text(TemplateSyntax.Placeholder(value.Path, value.Format)); + break; + + case RightTabInline: + encoder.Element(new XElement(_text + "tab")); + break; + + case ImageInline image: + encoder.Element(Frame(image)); + break; + + case InlineConditional conditional: + for (int i = 0; i < conditional.Branches.Count; i++) + { + encoder.Text(i == 0 ? TemplateSyntax.If(conditional.Branches[i].Condition) : TemplateSyntax.ElseIf(conditional.Branches[i].Condition)); + WriteInlines(encoder, conditional.Branches[i].Inlines); + } + + if (conditional.Else is { } otherwise) + { + encoder.Text(TemplateSyntax.Else); + WriteInlines(encoder, otherwise); + } + + encoder.Text(TemplateSyntax.EndIf); + break; + + case ExpressionInline expression: + encoder.Text(TemplateSyntax.Expression(expression.Condition, expression.Format)); + break; + + case PageFieldInline field: + encoder.Element(field.Field == PageField.Number + ? new XElement(_text + "page-number", new XAttribute(_text + "select-page", "current"), "1") + : new XElement(_text + "page-count", "1")); + break; + + default: + throw new NotSupportedException($"Inline {inline.GetType().Name} is not supported by the ODT writer."); + } + + if (inline.Style is not null) + { + encoder.EndSpan(); + } + } + } + + /// + /// A list item as a list of its own, nested to its level. Consecutive lists of one style read as one list, and + /// loop and conditional markers stay plain paragraphs between them. + /// + private static XElement WrapInList(XElement paragraph, ListItemInfo item) + { + XElement content = paragraph; + for (int level = item.Level; level >= 0; level--) + { + content = new XElement( + _text + "list", + level == 0 ? new XAttribute(_text + "style-name", item.Style.Id) : null, + new XElement(_text + "list-item", content)); + } + + return content; + } + + private static XElement WriteMarker(MarkerBlock marker) + { + XElement paragraph = new XElement(_text + "p", new XAttribute(_text + "style-name", BuilderStyles.TemplateMarker.Id)); + WhitespaceEncoder encoder = new WhitespaceEncoder(paragraph); + encoder.Text(marker.Text); + encoder.Finish(); + return paragraph; + } + + private XElement WriteParagraph(ParagraphBlock block, Length frame) + { + ParagraphStyleKey? paragraphStyle = block.Style ?? (block.List is { } listItem ? model.Styles.Find(listItem.Style)?.ItemStyle : null); + int? outlineLevel = paragraphStyle is { } key ? model.Styles.OutlineLevelOf(key) : null; + bool rightTab = block.Inlines.OfType().Any(); + string styleName = rightTab || block.Options != null + ? AutomaticParagraphStyle(paragraphStyle, rightTab ? frame : null, block.Options) + : paragraphStyle?.Id ?? StandardStyleName; + XAttribute styleAttribute = new XAttribute(_text + "style-name", styleName); + XElement paragraph = outlineLevel is int level + ? new XElement(_text + "h", styleAttribute, new XAttribute(_text + "outline-level", level)) + : new XElement(_text + "p", styleAttribute); + + WhitespaceEncoder encoder = new WhitespaceEncoder(paragraph); + WriteInlines(encoder, block.Inlines); + encoder.Finish(); + return paragraph; + } + } + + // ── styles.xml ─────────────────────────────────────────────────────────────── + + private static XElement Styles(DocumentModel model, PictureStore pictures) + { + StyleSheet sheet = model.Styles; + + XElement defaultText = TextProperties(sheet.Defaults); + (string language, string? country) = LanguageAndCountry(model.Language); + defaultText.Add(new XAttribute(_fo + "language", language)); + if (country != null) + { + defaultText.Add(new XAttribute(_fo + "country", country)); + } + + XElement styles = new XElement( + _office + "styles", + new XElement( + _style + "default-style", + new XAttribute(_style + "family", "paragraph"), + // Word turns widow control on by default; this is the same rule. + new XElement(_style + "paragraph-properties", new XAttribute(_fo + "orphans", 2), new XAttribute(_fo + "widows", 2)), + defaultText), + new XElement( + _style + "style", + new XAttribute(_style + "name", StandardStyleName), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "class", "text"))); + + foreach (ParagraphStyleDefinition definition in sheet.ParagraphStyles) + { + XElement style = new XElement( + _style + "style", + new XAttribute(_style + "name", definition.Key.Id), + new XAttribute(_style + "display-name", definition.Key.DisplayName), + new XAttribute(_style + "family", "paragraph"), + new XAttribute(_style + "parent-style-name", definition.BasedOn?.Id ?? StandardStyleName)); + if (definition.Next is { } next) + { + style.Add(new XAttribute(_style + "next-style-name", next.Id)); + } + + if (definition.Paragraph.OutlineLevel is int level) + { + style.Add(new XAttribute(_style + "default-outline-level", level)); + } + + style.Add(new XAttribute(_style + "class", "text")); + // LibreOffice reads a style's top and bottom margin as one item: a derived style that sets one would lose the + // inherited other (#298 F10), so it is restated from the parent chain. + Model.ParagraphProperties own = definition.Paragraph; + bool restate = definition.BasedOn is not null && (own.SpaceBefore is null) != (own.SpaceAfter is null); + AddIfNotEmpty(style, ParagraphProperties( + own, + own.SpaceBefore ?? (restate ? sheet.SpaceBeforeOf(definition.BasedOn) : null), + own.SpaceAfter ?? (restate ? sheet.SpaceAfterOf(definition.BasedOn) : null))); + AddIfNotEmpty(style, TextProperties(definition.Text)); + styles.Add(style); + } + + foreach (ListStyleDefinition definition in sheet.ListStyles) + { + XElement listStyle = new XElement(_text + "list-style", new XAttribute(_style + "name", definition.Key.Id)); + foreach ((int level, ListLevel bullet) in definition.Levels) + { + listStyle.Add(new XElement( + _text + "list-level-style-bullet", + new XAttribute(_text + "level", level + 1), + new XAttribute(_text + "bullet-char", bullet.Bullet), + new XElement( + _style + "list-level-properties", + new XAttribute(_text + "list-level-position-and-space-mode", "label-alignment"), + new XElement( + _style + "list-level-label-alignment", + new XAttribute(_text + "label-followed-by", "listtab"), + new XAttribute(_text + "list-tab-stop-position", bullet.Indent.ToString()), + new XAttribute(_fo + "text-indent", (-bullet.Hanging).ToString()), + new XAttribute(_fo + "margin-left", bullet.Indent.ToString()))))); + } + + styles.Add(listStyle); + } + + foreach (CharacterStyleDefinition definition in sheet.CharacterStyles) + { + XElement style = new XElement( + _style + "style", + new XAttribute(_style + "name", definition.Key.Id), + new XAttribute(_style + "display-name", definition.Key.DisplayName), + new XAttribute(_style + "family", "text")); + if (definition.BasedOn is { } basedOn) + { + style.Add(new XAttribute(_style + "parent-style-name", basedOn.Id)); + } + + AddIfNotEmpty(style, TextProperties(definition.Text)); + styles.Add(style); + } + + BlockWriter headerFooter = new BlockWriter(model, "TemplifyHf", pictures); + XElement masterPage = MasterPage(model.Page, headerFooter); + return new XElement( + _office + "document-styles", + Namespaces(_office, _text, _style, _fo, _svg, _table, _draw, _xlink), + new XAttribute(_office + "version", OdfVersion), + FontFaceDeclarations(sheet), + styles, + new XElement(_office + "automatic-styles", PageLayout(model.Page), headerFooter.AutomaticStyles), + new XElement(_office + "master-styles", masterPage)); + } + + private const string PageLayoutName = "TemplifyPageLayout"; + + private static bool HasHeader(PageSetup page) => page.Header != null || (page.DistinctFirstPage && page.FirstHeader is { Count: > 0 }); + + private static bool HasFooter(PageSetup page) => page.Footer != null || (page.DistinctFirstPage && page.FirstFooter is { Count: > 0 }); + + /// + /// The page layout. ODF measures the top margin to the header, Word to the body text: with a header, the page + /// margin is the header distance and the header is at least (top margin − header distance) high, so the body starts + /// where Word starts it. The footer mirrors this. + /// + private static XElement PageLayout(PageSetup page) + { + bool header = HasHeader(page); + bool footer = HasFooter(page); + XElement layout = new XElement( + _style + "page-layout", + new XAttribute(_style + "name", PageLayoutName), + new XElement( + _style + "page-layout-properties", + new XAttribute(_fo + "page-width", page.Size.Width.ToString()), + new XAttribute(_fo + "page-height", page.Size.Height.ToString()), + new XAttribute(_style + "print-orientation", "portrait"), + new XAttribute(_fo + "margin-top", (header ? page.HeaderDistance : page.Top).ToString()), + new XAttribute(_fo + "margin-bottom", (footer ? page.FooterDistance : page.Bottom).ToString()), + new XAttribute(_fo + "margin-left", page.Left.ToString()), + new XAttribute(_fo + "margin-right", page.Right.ToString()))); + + layout.Add(new XElement( + _style + "header-style", + header ? HeaderFooterProperties(page.Top - page.HeaderDistance, "margin-bottom") : null)); + layout.Add(new XElement( + _style + "footer-style", + footer ? HeaderFooterProperties(page.Bottom - page.FooterDistance, "margin-top") : null)); + return layout; + } + + private static XElement HeaderFooterProperties(Length minHeight, string spacing) => + new XElement( + _style + "header-footer-properties", + new XAttribute(_fo + "min-height", minHeight.ToString()), + new XAttribute(_fo + "margin-left", "0pt"), + new XAttribute(_fo + "margin-right", "0pt"), + new XAttribute(_fo + spacing, "0pt")); + + /// The master page "Standard" with the headers and footers (ODF 1.3 header-first / footer-first for the first page). + private static XElement MasterPage(PageSetup page, BlockWriter writer) + { + XElement master = new XElement( + _style + "master-page", + new XAttribute(_style + "name", StandardStyleName), + new XAttribute(_style + "page-layout-name", PageLayoutName)); + + if (HasHeader(page)) + { + master.Add(Region("header", page.Header, writer)); + if (page.DistinctFirstPage) + { + master.Add(Region("header-first", page.FirstHeader, writer)); + } + } + + if (HasFooter(page)) + { + master.Add(Region("footer", page.Footer, writer)); + if (page.DistinctFirstPage) + { + master.Add(Region("footer-first", page.FirstFooter, writer)); + } + } + + return master; + } + + private static XElement Region(string name, List? blocks, BlockWriter writer) + { + List content = blocks is null ? new List() : writer.WritePartBlocks(blocks, writer.PageFrame); + return new XElement(_style + name, content.Count > 0 ? content : new XElement(_text + "p", new XAttribute(_text + "style-name", StandardStyleName))); + } + + /// The package path of an embedded font file (named by content, so equal files are stored once). + private static string FontPath(FontFile file) => "Fonts/" + file.Hash[..16] + ".ttf"; + + /// One style:font-face per family the styles use, in first-use order. + private static XElement FontFaceDeclarations(StyleSheet sheet) + { + XElement declarations = new XElement(_office + "font-face-decls"); + foreach (string family in sheet.Fonts.Select(f => f.Family).Distinct(StringComparer.Ordinal)) + { + XElement face = new XElement( + _style + "font-face", + new XAttribute(_style + "name", family), + new XAttribute(_svg + "font-family", family.Contains(' ', StringComparison.Ordinal) ? "'" + family + "'" : family)); + if (sheet.EmbeddedFonts.FirstOrDefault(f => f.Family == family)?.Embedding is { } file) + { + // ODF 1.3 part 3, 16.23: the embedded file, which LibreOffice loads for the document. + face.Add(new XElement( + _svg + "font-face-src", + new XElement( + _svg + "font-face-uri", + new XAttribute(_xlink + "href", FontPath(file)), + new XAttribute(_xlink + "type", "simple"), + new XElement(_svg + "font-face-format", new XAttribute(_svg + "string", "truetype"))))); + } + + declarations.Add(face); + } + + return declarations; + } + + private static XElement TextProperties(Model.TextProperties text) + { + XElement properties = new XElement(_style + "text-properties"); + if (text.Font is { } font) + { + properties.Add(new XAttribute(_style + "font-name", font.Family)); + } + + if (text.Size is { } size) + { + properties.Add(new XAttribute(_fo + "font-size", size.ToString())); + } + + if (text.Color is { } color) + { + properties.Add(new XAttribute(_fo + "color", "#" + color.Hex.ToLowerInvariant())); + } + + if (text.Bold is bool bold) + { + properties.Add(new XAttribute(_fo + "font-weight", bold ? "bold" : "normal")); + } + + if (text.Italic is bool italic) + { + properties.Add(new XAttribute(_fo + "font-style", italic ? "italic" : "normal")); + } + + return properties; + } + + private static XElement ParagraphProperties(Model.ParagraphProperties paragraph, Length? spaceBefore, Length? spaceAfter) + { + XElement properties = new XElement(_style + "paragraph-properties"); + if (spaceBefore is { } before) + { + properties.Add(new XAttribute(_fo + "margin-top", before.ToString())); + } + + if (spaceAfter is { } after) + { + properties.Add(new XAttribute(_fo + "margin-bottom", after.ToString())); + } + + if (paragraph.LineHeight is { } line) + { + properties.Add(line.Rule switch + { + LineHeightRule.Proportional => new XAttribute(_fo + "line-height", (line.Multiple * 100).ToString("0.#", CultureInfo.InvariantCulture) + "%"), + LineHeightRule.Exact => new XAttribute(_fo + "line-height", line.Height.ToString()), + _ => new XAttribute(_style + "line-height-at-least", line.Height.ToString()), + }); + } + + if (paragraph.Alignment is { } alignment) + { + properties.Add(new XAttribute(_fo + "text-align", alignment switch + { + TextAlignment.Center => "center", + TextAlignment.End => "end", + TextAlignment.Justify => "justify", + _ => "start", + })); + } + + if (paragraph.IndentStart is { } start) + { + properties.Add(new XAttribute(_fo + "margin-left", start.ToString())); + } + + if (paragraph.IndentEnd is { } end) + { + properties.Add(new XAttribute(_fo + "margin-right", end.ToString())); + } + + if (paragraph.FirstLineIndent is { } first) + { + properties.Add(new XAttribute(_fo + "text-indent", first.ToString())); + } + + if (paragraph.KeepWithNext is bool keepNext) + { + properties.Add(new XAttribute(_fo + "keep-with-next", keepNext ? "always" : "auto")); + } + + if (paragraph.KeepLinesTogether is bool keepTogether) + { + properties.Add(new XAttribute(_fo + "keep-together", keepTogether ? "always" : "auto")); + } + + if (paragraph.BorderBottom is { } bottom) + { + properties.Add( + new XAttribute(_fo + "border-bottom", $"{bottom.Width} solid #{bottom.Color.Hex.ToLowerInvariant()}"), + new XAttribute(_fo + "padding-bottom", (paragraph.BorderBottomSpace ?? Length.Zero).ToString())); + } + + return properties; + } + + private static void AddIfNotEmpty(XElement style, XElement properties) + { + if (properties.HasAttributes) + { + style.Add(properties); + } + } + + /// The ODF language and country of a culture: de-DE → (de, DE), en → (en, none). + private static (string Language, string? Country) LanguageAndCountry(CultureInfo culture) + { + string[] parts = culture.Name.Split('-'); + string? country = parts.Length > 1 && parts[^1].Length == 2 && parts[^1].All(char.IsAsciiLetterUpper) ? parts[^1] : null; + return (parts[0], country); + } + + // ── meta.xml and the manifest ──────────────────────────────────────────────── + + private static XElement Meta(DocumentModel model) + { + XElement meta = new XElement(_office + "meta"); + if (model.Info.Title is { } title) + { + meta.Add(new XElement(_dc + "title", title)); + } + + if (model.Info.Subject is { } subject) + { + meta.Add(new XElement(_dc + "subject", subject)); + } + + if (model.Info.Author is { } author) + { + meta.Add(new XElement(_meta + "initial-creator", author), new XElement(_dc + "creator", author)); + } + + meta.Add(new XElement(_dc + "language", model.Language.Name)); + foreach ((string name, string value) in model.Stamp.ToProperties()) + { + meta.Add(new XElement(_meta + "user-defined", new XAttribute(_meta + "name", name), value)); + } + + return new XElement( + _office + "document-meta", + Namespaces(_office, _meta, _dc), + new XAttribute(_office + "version", OdfVersion), + meta); + } + + private static XElement Manifest(PictureStore pictures, List fonts) => + new XElement( + _manifest + "manifest", + new XAttribute(XNamespace.Xmlns + "manifest", _manifest.NamespaceName), + new XAttribute(_manifest + "version", OdfVersion), + FileEntry("/", MediaType, version: true), + FileEntry("content.xml", "text/xml"), + FileEntry("styles.xml", "text/xml"), + FileEntry("meta.xml", "text/xml"), + pictures.Files.Select(f => FileEntry(f.Path, f.Image.MediaType)), + fonts.Select(f => FileEntry(FontPath(f), "application/x-font-ttf"))); + + private static XElement FileEntry(string path, string mediaType, bool version = false) => + new XElement( + _manifest + "file-entry", + new XAttribute(_manifest + "full-path", path), + version ? new XAttribute(_manifest + "version", OdfVersion) : null, + new XAttribute(_manifest + "media-type", mediaType)); + + private static IEnumerable Namespaces(params XNamespace[] namespaces) + { + foreach (XNamespace ns in namespaces) + { + string prefix = ns == _office ? "office" + : ns == _text ? "text" + : ns == _style ? "style" + : ns == _fo ? "fo" + : ns == _svg ? "svg" + : ns == _table ? "table" + : ns == _draw ? "draw" + : ns == _xlink ? "xlink" + : ns == _meta ? "meta" + : ns == _dc ? "dc" + : throw new ArgumentOutOfRangeException(nameof(namespaces), ns.NamespaceName, "Unknown namespace."); + yield return new XAttribute(XNamespace.Xmlns + prefix, ns.NamespaceName); + } + } + + private static byte[] Serialize(XElement root) + { + XmlWriterSettings settings = new XmlWriterSettings + { + Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + Indent = false, + NewLineHandling = NewLineHandling.Entitize, + }; + + using MemoryStream buffer = new MemoryStream(); + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + new XDocument(new XDeclaration("1.0", "UTF-8", null), root).Save(writer); + } + + return buffer.ToArray(); + } + + /// + /// Writes text so that it renders exactly under ODF white-space rules: literal white space collapses and is + /// dropped at the start of a paragraph, so every space that would be lost becomes text:s. + /// + /// + /// The rule is conservative: after the paragraph start, a tab or a line break, and after a literal space, every + /// space is written as text:s, which always renders. A trailing literal space becomes text:s too. + /// + private sealed class WhitespaceEncoder + { + private readonly XElement _paragraph; + private readonly StringBuilder _pending = new StringBuilder(); + private XElement _target; + private bool _collapsible = true; + + public WhitespaceEncoder(XElement paragraph) + { + _paragraph = paragraph; + _target = paragraph; + } + + public void Text(string text) + { + int i = 0; + while (i < text.Length) + { + if (text[i] != ' ') + { + _pending.Append(text[i]); + _collapsible = false; + i++; + continue; + } + + int count = 0; + while (i < text.Length && text[i] == ' ') + { + count++; + i++; + } + + if (!_collapsible) + { + _pending.Append(' '); + count--; + } + + if (count > 0) + { + FlushText(); + _target.Add(Spaces(count)); + } + + _collapsible = true; + } + } + + public void Element(XElement element) + { + FlushText(); + _target.Add(element); + _collapsible = true; + } + + /// Continues inside a span; white-space state carries over, because spans do not reset it. + public void BeginSpan(XElement span) + { + FlushText(); + _target.Add(span); + _target = span; + } + + public void EndSpan() + { + FlushText(); + _target = _paragraph; + } + + public void Finish() + { + FlushText(); + + // A trailing literal space, possibly inside the last span, becomes text:s. + if (_paragraph.DescendantNodes().LastOrDefault() is XText last && last.Value.EndsWith(' ')) + { + last.Value = last.Value[..^1]; + last.AddAfterSelf(Spaces(1)); + if (last.Value.Length == 0) + { + last.Remove(); + } + } + } + + private void FlushText() + { + if (_pending.Length > 0) + { + _target.Add(new XText(_pending.ToString())); + _pending.Clear(); + } + } + + private static XElement Spaces(int count) => + count == 1 + ? new XElement(_text + "s") + : new XElement(_text + "s", new XAttribute(_text + "c", count)); + } +} diff --git a/src/TriasDev.Templify.Builder/Writers/Spacers.cs b/src/TriasDev.Templify.Builder/Writers/Spacers.cs new file mode 100644 index 00000000..e9ab9426 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/Spacers.cs @@ -0,0 +1,80 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Writers; + +/// +/// Spacer paragraphs (style "Template Spacer", 1 pt) keep containers well-formed once Templify removes the marker +/// paragraphs: a table cell must still end with a paragraph — LibreOffice drops the borders and padding of a table whose +/// cell ends with a table — and a table must not touch the next one, which Word and LibreOffice would merge. A writer +/// detail: spacers are not in the model, so definitions, JSON and the data contract do not see them. +/// +internal static class Spacers +{ + /// The spacer paragraph. + public static ParagraphBlock Paragraph { get; } = new ParagraphBlock([], BuilderStyles.TemplateSpacer); + + /// After a table (or raw block) that a marker follows: once the marker is gone, the next table would touch it. + public static bool After(Block current, Block? next, Func rawIsParagraph) => + (current is TableBlock || (current is RawXmlBlock raw && !rawIsParagraph(raw))) && next is MarkerBlock; + + /// + /// At the end of a cell that could otherwise end with a table or be empty once Templify removed markers and branches. + /// A table that a marker follows already has a spacer after it (), so the cell can end with a + /// table only when one is written last; a second spacer would stack on the first (#296 F13). + /// + public static bool AtCellEnd(IReadOnlyList blocks, Func rawIsParagraph) => + blocks.Count > 0 && (BlockFlattener.Flatten(blocks).LastOrDefault() is { } last && IsTable(last, rawIsParagraph) || MayBeEmpty(blocks)); + + /// + /// Whether filling may remove everything: every block is a loop (it may be empty), a conditional that may keep + /// nothing, or a component or list made of such blocks. + /// + public static bool MayBeEmpty(IReadOnlyList blocks) => blocks.All(block => block switch + { + LoopBlock => true, + ConditionalBlock conditional => conditional.Else is not { } otherwise + || MayBeEmpty(otherwise) + || conditional.Branches.Any(b => MayBeEmpty(b.Body)), + ComponentBlock component => MayBeEmpty(component.Body), + ListBlock list => MayBeEmpty(list.Items), + _ => false, + }); + + /// A table, or a raw block that is one (only its writer knows: it renders it once). + private static bool IsTable(Block block, Func rawIsParagraph) => + block is TableBlock || (block is RawXmlBlock raw && !rawIsParagraph(raw)); + + /// Without a writer a raw block may be a table: the conservative answer (used to decide on the style). + private static bool MayBeTable(RawXmlBlock raw) => false; + + /// Whether any spacer is written for these parts: the style sheet then needs the spacer style. + public static bool Used(IEnumerable> parts) + { + foreach (IReadOnlyList part in parts) + { + if (Touches(part)) + { + return true; + } + + foreach (TableBlock table in BlockTree.All(part).OfType()) + { + if (table.AllRows().SelectMany(r => r.Cells).Any(cell => AtCellEnd(cell.Content, MayBeTable) || Touches(cell.Content))) + { + return true; + } + } + } + + return false; + } + + private static bool Touches(IReadOnlyList blocks) + { + List flattened = BlockFlattener.Flatten(blocks).ToList(); + return flattened.Where((block, i) => After(block, i + 1 < flattened.Count ? flattened[i + 1] : null, MayBeTable)).Any(); + } +} diff --git a/src/TriasDev.Templify.Builder/Writers/TextPieces.cs b/src/TriasDev.Templify.Builder/Writers/TextPieces.cs new file mode 100644 index 00000000..9ebf2aa8 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/TextPieces.cs @@ -0,0 +1,58 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Writers; + +/// The kinds of piece literal text splits into. +internal enum TextPieceKind +{ + Text, + Tab, + LineBreak, +} + +/// +/// Splits literal text into runs of characters, tabs and line breaks; each writer writes them as the format's +/// own elements. \r\n and a lone \r count as one line break. +/// +internal static class TextPieces +{ + public static IEnumerable<(TextPieceKind Kind, string Text)> Split(string text) + { + int start = 0; + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (c is not ('\t' or '\n' or '\r')) + { + continue; + } + + if (i > start) + { + yield return (TextPieceKind.Text, text.Substring(start, i - start)); + } + + if (c == '\t') + { + yield return (TextPieceKind.Tab, string.Empty); + } + else + { + if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + } + + yield return (TextPieceKind.LineBreak, string.Empty); + } + + start = i + 1; + } + + if (start < text.Length) + { + yield return (TextPieceKind.Text, text.Substring(start)); + } + } +} diff --git a/src/TriasDev.Templify.Builder/Writers/TopOfPage.cs b/src/TriasDev.Templify.Builder/Writers/TopOfPage.cs new file mode 100644 index 00000000..3796118b --- /dev/null +++ b/src/TriasDev.Templify.Builder/Writers/TopOfPage.cs @@ -0,0 +1,79 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Writers; + +/// +/// No space before the content that starts a page after a page break, in ODT (#298 F11). LibreOffice's DOCX import writes +/// a top margin of 0 on the paragraph after a page break (in the body and in headers, not in table cells, where it +/// ignores the break); for an ODT it keeps the space. The ODT writer applies the same rule to the template, before +/// conditionals and loops are flattened: the first paragraph, table or rule after a break, and the first one of every +/// branch of a conditional there. A loop is left alone, since every copy of its body would lose its space; content +/// that only becomes first because filling removed what was before it keeps its space. The model is not changed. +/// +internal static class TopOfPage +{ + /// The blocks of the body or a header/footer with the content after each page break at the top of its page. + public static List Apply(IReadOnlyList blocks) + { + // Inside conditionals, components and lists a break can be followed by content as well. + List result = blocks.Select(Nested).ToList(); + for (int i = 0; i + 1 < result.Count; i++) + { + if (result[i] is PageBreakBlock && First(result[i + 1]) is { } first) + { + result[i + 1] = first; + } + } + + return result; + } + + /// A block whose first content sits at the top of a page; null when nothing changes. + private static Block? First(Block block) => block switch + { + ParagraphBlock paragraph => paragraph with + { + Options = (paragraph.Options ?? new ParagraphOverrides(null, null, null, null)) with { SpaceBefore = Length.Zero }, + }, + TableBlock { SpaceBefore: not null } table => table with { SpaceBefore = null }, + RuleBlock rule when rule.SpaceBefore != Length.Zero => rule with { SpaceBefore = Length.Zero }, + ConditionalBlock conditional => Branches(conditional, FirstOfAll), + ComponentBlock component => component with { Body = FirstOfAll(component.Body) }, + ListBlock list => list with { Items = FirstOfAll(list.Items) }, + _ => null, + }; + + /// The blocks with their first block at the top of a page. + private static List FirstOfAll(List blocks) + { + if (blocks.Count == 0 || First(blocks[0]) is not { } first) + { + return blocks; + } + + List copy = blocks.ToList(); + copy[0] = first; + return copy; + } + + /// Page breaks inside conditionals, components and lists (not loops, not table cells). + private static Block Nested(Block block) => block switch + { + ConditionalBlock conditional => Branches(conditional, Apply), + ComponentBlock component => component with { Body = Apply(component.Body) }, + ListBlock list => list with { Items = Apply(list.Items) }, + _ => block, + }; + + /// A copy of a conditional with every branch and the else part changed (its lists are not shared). + private static ConditionalBlock Branches(ConditionalBlock conditional, Func, List> change) + { + ConditionalBlock copy = new ConditionalBlock(); + copy.Branches.AddRange(conditional.Branches.Select(b => new ConditionalBranch(b.Condition, change(b.Body)))); + copy.Else = conditional.Else is { } otherwise ? change(otherwise) : null; + return copy; + } +} diff --git a/src/TriasDev.Templify.Builder/packages.lock.json b/src/TriasDev.Templify.Builder/packages.lock.json new file mode 100644 index 00000000..83ec44b7 --- /dev/null +++ b/src/TriasDev.Templify.Builder/packages.lock.json @@ -0,0 +1,77 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "DocumentFormat.OpenXml": { + "type": "Direct", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + }, + "Microsoft.CodeAnalysis.PublicApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "W4kJGezNIKLzo0Ak5FAQDFvkMf2U7DtGL4THmHyRSApfKsKt5V+eX/bU0ZLKAt/uf9Bb2o1bi0YDKj/GRB/vYQ==" + }, + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + } + }, + "net11.0": { + "DocumentFormat.OpenXml": { + "type": "Direct", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + }, + "Microsoft.CodeAnalysis.PublicApiAnalyzers": { + "type": "Direct", + "requested": "[5.6.0, )", + "resolved": "5.6.0", + "contentHash": "W4kJGezNIKLzo0Ak5FAQDFvkMf2U7DtGL4THmHyRSApfKsKt5V+eX/bU0ZLKAt/uf9Bb2o1bi0YDKj/GRB/vYQ==" + }, + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + } + } + } +} \ No newline at end of file diff --git a/src/TriasDev.Templify.Builder/version.txt b/src/TriasDev.Templify.Builder/version.txt new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/src/TriasDev.Templify.Builder/version.txt @@ -0,0 +1 @@ +0.1.0 diff --git a/templify.slnx b/templify.slnx index d9e3ce59..d3802863 100644 --- a/templify.slnx +++ b/templify.slnx @@ -3,12 +3,17 @@ + + + + + diff --git a/tests/TriasDev.Templify.Builder.Tests/BorderTests.cs b/tests/TriasDev.Templify.Builder.Tests/BorderTests.cs new file mode 100644 index 00000000..a410a3c5 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/BorderTests.cs @@ -0,0 +1,226 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F2: borders per side — the outer edges of a table style, and one cell's own lines. +public sealed class BorderTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + + private static readonly TableStyleKey _marked = new TableStyleKey("Marked"); + private static readonly Color _line = Color.FromHex("1F3864"); + private static readonly Color _tone = Color.FromHex("C00000"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action style, Action table) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Table(_marked, style))); + t.Content(c => c.Table(tb => + { + tb.Style(_marked); + table(tb); + })); + }); + + private static void ThreeByTwo(TableComposer t, Action? middle = null) + { + t.Columns(cols => cols.Relative(1).Relative(1).Relative(1)); + t.Row(r => r.Cell("a1").Cell(c => + { + middle?.Invoke(c); + c.Paragraph("b1"); + }).Cell("c1")); + t.Row(r => r.Cell("a2").Cell("b2").Cell("c2")); + } + + [Theory] + [MemberData(nameof(Formats))] + public void TableTopRuleOnly(TemplateFormat format) + { + TestDefinition definition = Define(s => s.OuterBorder(Sides.Top, 0.75.Pt(), _line).RowRule(0.5.Pt(), Color.FromHex("D0D0D0")), t => ThreeByTwo(t)); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement borders = Docx(template).Descendants(_w + "tblBorders").Single(); + Assert.Equal("single", Val(borders, "top")); + Assert.Equal(("nil", "nil", "nil"), (Val(borders, "left"), Val(borders, "bottom"), Val(borders, "right"))); + Assert.Equal("single", Val(borders, "insideH")); + } + else + { + List> cells = OdtCells(template); + Assert.All(cells[0], c => Assert.Equal("0.75pt solid #1f3864", c.Attribute(_fo + "border-top")!.Value)); + Assert.All(cells[1], c => Assert.Equal("none", c.Attribute(_fo + "border-bottom")!.Value)); + Assert.All(cells.SelectMany(r => r), c => Assert.Equal("none", c.Attribute(_fo + "border-left")!.Value)); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void CellLeftBorder(TemplateFormat format) + { + TestDefinition definition = Define(s => s.RowRule(0.5.Pt(), Color.FromHex("D0D0D0")), t => ThreeByTwo(t, c => c.Border(Sides.Left, 0.75.Pt(), _line))); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + List cells = Docx(template).Descendants(_w + "tc").ToList(); + XElement own = cells[1].Element(_w + "tcPr")!.Element(_w + "tcBorders")!; + Assert.Equal(new[] { "left" }, own.Elements().Select(e => e.Name.LocalName)); + Assert.Equal(("single", "6", "1F3864"), (Val(own, "left"), own.Element(_w + "left")!.Attribute(_w + "sz")!.Value, own.Element(_w + "left")!.Attribute(_w + "color")!.Value)); + Assert.All(cells.Where((_, i) => i != 1), c => Assert.Null(c.Element(_w + "tcPr")!.Element(_w + "tcBorders"))); + } + else + { + List> cells = OdtCells(template); + Assert.Equal("0.75pt solid #1f3864", cells[0][1].Attribute(_fo + "border-left")!.Value); + Assert.Equal("none", cells[0][0].Attribute(_fo + "border-left")!.Value); + Assert.Equal("none", cells[1][1].Attribute(_fo + "border-left")!.Value); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void CellFrameOfItsOwn(TemplateFormat format) + { + TestDefinition definition = Define(s => s.RowRule(0.5.Pt(), Color.FromHex("D0D0D0")), t => ThreeByTwo(t, c => c.Border(Sides.All, 1.Pt(), _tone))); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement own = Docx(template).Descendants(_w + "tc").ElementAt(1).Element(_w + "tcPr")!.Element(_w + "tcBorders")!; + Assert.Equal(new[] { "top", "left", "bottom", "right" }, own.Elements().Select(e => e.Name.LocalName)); + Assert.All(own.Elements(), e => Assert.Equal("C00000", e.Attribute(_w + "color")!.Value)); + } + else + { + XElement middle = OdtCells(template)[0][1]; + Assert.All(new[] { "border-top", "border-right", "border-bottom", "border-left" }, side => Assert.Equal("1pt solid #c00000", middle.Attribute(_fo + side)!.Value)); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void HeaderCellOwnBottom_WinsOverHeaderRule(TemplateFormat format) + { + TestDefinition definition = Define(s => s.HeaderRule(0.5.Pt(), Color.FromHex("808080")), t => + { + t.Columns(cols => cols.Relative(1).Relative(1)); + t.HeaderRow(r => r.Cell(c => c.Border(Sides.Bottom, 2.Pt(), _tone).Paragraph("H1")).Cell("H2")); + t.Row(r => r.Cell("a").Cell("b")); + }); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + List header = Docx(template).Descendants(_w + "tr").First().Elements(_w + "tc").ToList(); + Assert.Equal("C00000", header[0].Descendants(_w + "bottom").Single().Attribute(_w + "color")!.Value); + Assert.Equal("808080", header[1].Descendants(_w + "bottom").Single().Attribute(_w + "color")!.Value); + } + else + { + List> cells = OdtCells(template); + Assert.Equal("2pt solid #c00000", cells[0][0].Attribute(_fo + "border-bottom")!.Value); + Assert.Equal("0.5pt solid #808080", cells[0][1].Attribute(_fo + "border-bottom")!.Value); + } + } + + [Fact] + public void CellBorder_InRowLoop_IsKeptOnClones() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.ForEachRow(t.Data["items"], "item", (item, rows) => rows.Row(r => r.Cell(cell => cell.Border(Sides.Left, 0.75.Pt(), _line).Paragraph(item.Self)))); + }))); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, TemplateFormat.Docx, """{ "items": [ "one", "two", "three" ] }"""); + List cells = BuilderHarness.ReadXml(filled, "word/document.xml").Descendants(_w + "tc").ToList(); + Assert.Equal(3, cells.Count); + Assert.All(cells, cell => Assert.Equal("single", Val(cell.Element(_w + "tcPr")!.Element(_w + "tcBorders")!, "left"))); + } + + [Theory] + [InlineData("\"0.75pt #1F3864\"", "\"outerBorder\": \"0.75pt #1F3864\"")] + [InlineData("{ \"top\": \"0.75pt #1F3864\", \"bottom\": \"0.5pt #D0D0D0\" }", "\"bottom\": \"0.5pt #D0D0D0\"")] + public void Json_Borders_RoundTrip(string outer, string expected) + { + string json = $$""" + { + "templifyDefinition": 1, + "identity": { "id": "borders", "version": 1 }, + "styles": { "table": { "Marked": { "outerBorder": {{outer}} } } }, + "content": [ + { "style": "Marked", "columns": [ 1, 1 ], "table": [ { "row": [ { "border": { "left": "0.75pt #1F3864" }, "content": "a" }, { "border": "1pt #C00000", "content": "b" } ] } ] } + ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + foreach (TemplateFormat format in BuilderHarness.Formats) + { + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + } + + string exported = Json.TemplateJson.Export(imported, BuilderHarness.Options(TemplateFormat.Docx)).Json; + Assert.Contains(expected, exported, StringComparison.Ordinal); + Assert.Contains("\"border\": \"1pt #C00000\"", exported, StringComparison.Ordinal); + Assert.Contains("\"left\": \"0.75pt #1F3864\"", exported, StringComparison.Ordinal); + } + + [Fact] + public void Sides_None_Throws() + { + Assert.Throws(() => BuilderHarness.Build(Define(s => s.OuterBorder(Sides.None, 1.Pt(), _line), t => ThreeByTwo(t)), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(Define(s => { }, t => ThreeByTwo(t, c => c.Border(Sides.None, 1.Pt(), _line))), TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_CellBorderIsDrawn(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Fixed(60.Mm()).Relative(1)); + tb.Row(r => r.Cell("Left").Cell(cell => cell.Border(Sides.Left, 1.5.Pt(), Color.FromHex("000000")).Paragraph("Right"))); + }))); + byte[] pdf = PdfLayout.Pdf(definition, format); + PdfLayout.Ink ink = PdfLayout.Pixels(pdf); + double row = PdfLayout.Words(pdf).Find("Right").YMin; + + // The line is at the second cell's left edge: frame start (25 mm) + 60 mm = 85 mm = 240.9 pt. + int x = ink.Pixel(240.9); + bool drawn = Enumerable.Range(x - ink.Pixel(1.5), ink.Pixel(3)).Any(px => ink.IsInk(px, ink.Pixel(row + 3))); + Assert.True(drawn, "no vertical line at the second cell's left edge"); + } + + private static XDocument Docx(GeneratedTemplate template) => BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml"); + + private static string Val(XElement borders, string side) => borders.Element(_w + side)!.Attribute(_w + "val")!.Value; + + /// The cell properties of the body table, by row. + private static List> OdtCells(GeneratedTemplate template) + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + XElement Properties(XElement cell) + { + string name = cell.Attribute(_table + "style-name")!.Value; + return content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name).Element(_style + "table-cell-properties")!; + } + + return content.Descendants(_table + "table-row").Select(r => r.Elements(_table + "table-cell").Select(Properties).ToList()).ToList(); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/BoxRuleTests.cs b/tests/TriasDev.Templify.Builder.Tests/BoxRuleTests.cs new file mode 100644 index 00000000..1c5403fe --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/BoxRuleTests.cs @@ -0,0 +1,260 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Globalization; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed partial class BoxRuleTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly BoxStyleKey _success = new BoxStyleKey("Success"); + private static readonly BoxStyleKey _danger = new BoxStyleKey("Danger"); + private static readonly BoxStyleKey _neutral = new BoxStyleKey("Neutral"); + + private static StyleSheet Sheet() => StyleSheet.Create(s => + { + s.Box(_success, b => b.Border(1.Pt(), Color.FromHex("96C6A8")).Background(Color.FromHex("EFF6F1")).Padding(8.Pt()).SpaceAfter(6.Pt())); + s.Box(_danger, b => b.Border(1.Pt(), Color.FromHex("E09999")).Background(Color.FromHex("F8E8E8")).Padding(8.Pt())); + s.Box(_neutral, b => b.Border(0.75.Pt(), Color.FromHex("C0C0C0")).Padding(4.Pt(), 10.Pt())); + }); + + private sealed class Verdict(TemplatePath control) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Switch(control["answer"], s => + { + s.Case(new[] { "yes", "yesCertificate" }, b => Body(b, _success, "Met")); + s.Case("no", b => Body(b, _danger, "Not met")); + s.Default(b => Body(b, _neutral, "Not assessed")); + }); + + private void Body(BlockComposer c, BoxStyleKey style, string verdict) => c.Box(style, b => + { + b.Paragraph(x => + { + x.Text(verdict + ": "); + x.Value(control["title"]); + }); + b.If(control["comment"], k => k.Paragraph(control["comment"])); + b.ForEach(control["evidence"], "e", (e, eb) => eb.Paragraph(x => + { + x.Text("- "); + x.Value(e.Self); + })); + b.Table(t => + { + t.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + t.Row(r => + { + r.Cell("Owner"); + r.Cell(control["owner"]); + }); + }); + }); + } + + private static TestDefinition Controls() => new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => + { + c.Paragraph("Controls"); + c.Rule(0.5.Pt(), Color.FromHex("D4D4D4"), 4.Pt(), 8.Pt()); + c.ForEach(t.Data["controls"], "control", (control, b) => b.Component(new Verdict(control.Self))); + }); + }); + + private const string Json = """ + { + "controls": [ + { "answer": "yes", "title": "Encryption", "comment": "AES-256", "evidence": [ "Policy", "Audit" ], "owner": "IT" }, + { "answer": "no", "title": "Backups", "comment": "", "evidence": [], "owner": "Ops" }, + { "answer": "later", "title": "Training", "comment": "", "evidence": [ "Plan" ], "owner": "HR" } + ] + } + """; + + [Theory] + [MemberData(nameof(Formats))] + public void VerdictBoxes_ChooseTheirStyleByData(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Controls(), format); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + // Empty evidence lists are expected here: no warning for them. + ProcessingResult result = new TemplateProcessor(new PlaceholderReplacementOptions { WarnOnEmptyLoopCollections = false, Culture = CultureInfo.InvariantCulture }) + .ProcessTemplate(input, output, Json); + Assert.True(result.IsSuccess, result.ErrorMessage); + BuilderHarness.AssertPackage(format, output.ToArray()); + + List boxes = Boxes(format, output.ToArray()); + Assert.Equal(3, boxes.Count); + Assert.Equal(new[] { "Met: Encryption", "AES-256", "- Policy", "- Audit", "Owner | IT", string.Empty }, boxes[0]); + Assert.Equal(new[] { "Not met: Backups", "Owner | Ops", string.Empty }, boxes[1]); + Assert.Equal(new[] { "Not assessed: Training", "- Plan", "Owner | HR", string.Empty }, boxes[2]); + } + + [Fact] + public void Docx_Box_IsAOneCellTableWithBorderBackgroundAndPadding() + { + byte[] package = BuilderHarness.Build(Controls(), TemplateFormat.Docx).Content.ToArray(); + XElement body = BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!; + XElement box = body.Descendants(_w + "tbl").First(); + + XElement properties = box.Element(_w + "tblPr")!; + Assert.Equal("9071", properties.Element(_w + "tblW")!.Attribute(_w + "w")!.Value); + Assert.Equal(new[] { "8", "8", "8", "8" }, new[] { "top", "left", "bottom", "right" }.Select(e => properties.Element(_w + "tblBorders")!.Element(_w + e)!.Attribute(_w + "sz")!.Value)); + Assert.Equal("96C6A8", properties.Element(_w + "tblBorders")!.Element(_w + "top")!.Attribute(_w + "color")!.Value); + Assert.Equal("160", properties.Element(_w + "tblCellMar")!.Element(_w + "left")!.Attribute(_w + "w")!.Value); + Assert.Equal("EFF6F1", box.Descendants(_w + "shd").First().Attribute(_w + "fill")!.Value); + Assert.Null(box.Element(_w + "tr")!.Element(_w + "trPr")?.Element(_w + "cantSplit")); + + // The nested two-column table shares the box's inner width: 453.544 − 2 × 8 pt. + XElement nested = box.Descendants(_w + "tbl").First(); + Assert.Equal(new[] { "4375", "4375" }, nested.Element(_w + "tblGrid")!.Elements(_w + "gridCol").Select(g => g.Attribute(_w + "w")!.Value)); + + XElement rule = body.Elements(_w + "p").ElementAt(1); + Assert.Equal("4", rule.Descendants(_w + "top").Single().Attribute(_w + "sz")!.Value); + Assert.Equal("80", rule.Descendants(_w + "spacing").Single().Attribute(_w + "before")!.Value); + Assert.Equal("160", rule.Descendants(_w + "spacing").Single().Attribute(_w + "after")!.Value); + } + + [Fact] + public void Odt_Box_And_Rule_Styles() + { + byte[] package = BuilderHarness.Build(Controls(), TemplateFormat.Odt).Content.ToArray(); + XDocument content = BuilderHarness.ReadXml(package, "content.xml"); + Dictionary styles = content.Root!.Element(_office + "automatic-styles")!.Elements(_style + "style") + .ToDictionary(s => s.Attribute(_style + "name")!.Value); + + XElement boxCell = content.Descendants(_table + "table").First().Descendants(_table + "table-cell").First(); + XElement cellProperties = styles[boxCell.Attribute(_table + "style-name")!.Value].Element(_style + "table-cell-properties")!; + Assert.Equal("#eff6f1", cellProperties.Attribute(_fo + "background-color")!.Value); + Assert.Equal(new[] { "1pt solid #96c6a8", "1pt solid #96c6a8", "1pt solid #96c6a8", "1pt solid #96c6a8" }, + new[] { "border-top", "border-bottom", "border-left", "border-right" }.Select(a => cellProperties.Attribute(_fo + a)!.Value)); + Assert.Equal("8pt", cellProperties.Attribute(_fo + "padding-left")!.Value); + Assert.Equal("6pt", styles[content.Descendants(_table + "table").First().Attribute(_table + "style-name")!.Value].Element(_style + "table-properties")!.Attribute(_fo + "margin-bottom")!.Value); + + XElement rule = content.Descendants(_text + "p").ElementAt(1); + XElement ruleProperties = styles[rule.Attribute(_text + "style-name")!.Value].Element(_style + "paragraph-properties")!; + Assert.Equal("0.5pt solid #d4d4d4", ruleProperties.Attribute(_fo + "border-top")!.Value); + Assert.Equal("4pt", ruleProperties.Attribute(_fo + "margin-top")!.Value); + Assert.Equal("1pt", ruleProperties.Attribute(_fo + "line-height")!.Value); + } + + [Fact] + public void Errors_AreReported() + { + TestDefinition undefined = new TestDefinition(t => t.Content(c => c.Box(_success, b => b.Paragraph("x")))); + Assert.Equal("TB2010", Assert.Single(Assert.Throws(() => BuilderHarness.Build(undefined, TemplateFormat.Docx)).Errors).Code); + + TestDefinition duplicate = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Box(_success, b => b.Padding(1.Pt())); + s.Table(new TableStyleKey("Success"), tb => tb.CellPadding(1.Pt(), 1.Pt())); + })); + t.Content(c => c.Paragraph("x")); + }); + Assert.Equal("TB2001", Assert.Single(Assert.Throws(() => BuilderHarness.Build(duplicate, TemplateFormat.Docx)).Errors).Code); + + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Rule(Length.Zero, Color.FromHex("000000")))), TemplateFormat.Docx)); + Assert.Throws(() => StyleSheet.Create(s => s.Box(_success, b => b.Border(7.Pt(), Color.FromHex("000000"))))); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_IndentsBoxTextByThePadding(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + GeneratedTemplate template = BuilderHarness.Build(Controls(), format); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + new TemplateProcessor(new PlaceholderReplacementOptions { WarnOnEmptyLoopCollections = false }).ProcessTemplate(input, output, Json); + byte[] pdf = LibreOfficeRunner.Convert(output.ToArray(), template.FileExtension.TrimStart('.'), "pdf", "pdf"); + + // Frame starts at 70.866 pt; the success and danger boxes pad 8 pt inside a 1 pt border. The text starts after + // the padding; LibreOffice adds (part of) the border width, which differs by format (DOCX measures the padding + // from the border's inner edge, ODT centres collapsed borders on the edge): within 2.5 pt. + Dictionary starts = WordStarts(pdf); + Assert.InRange(starts["Met:"], 70.866 + 8 - 0.5, 70.866 + 8 + 2.5); + Assert.InRange(starts["Not"], 70.866 + 8 - 0.5, 70.866 + 8 + 2.5); + } + + private static List Boxes(TemplateFormat format, byte[] package) + { + if (format == TemplateFormat.Docx) + { + return BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!.Elements(_w + "tbl") + .Select(t => t.Element(_w + "tr")!.Element(_w + "tc")!.Elements() + .Where(e => e.Name == _w + "p" || e.Name == _w + "tbl") + .Select(e => e.Name == _w + "tbl" + ? string.Join(" | ", e.Descendants(_w + "tc").Select(c => string.Concat(c.Descendants(_w + "t").Select(x => x.Value)))) + : string.Concat(e.Descendants(_w + "t").Select(x => x.Value))) + .ToArray()) + .ToList(); + } + + return BuilderHarness.ReadXml(package, "content.xml").Descendants(_office + "text").First().Elements(_table + "table") + .Select(t => t.Element(_table + "table-row")!.Element(_table + "table-cell")!.Elements() + .Select(e => e.Name == _table + "table" + ? string.Join(" | ", e.Descendants(_table + "table-cell").Select(c => string.Concat(c.Elements(_text + "p").Select(OdtDocumentVerifier.RenderText)))) + : OdtDocumentVerifier.RenderText(e)) + .ToArray()) + .ToList(); + } + + private static Dictionary WordStarts(byte[] pdf) + { + string? executable = new[] { "/opt/homebrew/bin/pdftotext", "/usr/local/bin/pdftotext", "/usr/bin/pdftotext" }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, "pdftotext (poppler) is not installed."); + string file = Path.Combine(Path.GetTempPath(), "templify-box-" + Guid.NewGuid().ToString("N") + ".pdf"); + File.WriteAllBytes(file, pdf); + try + { + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + foreach (string argument in new[] { "-bbox", file, "-" }) + { + start.ArgumentList.Add(argument); + } + + using Process process = Process.Start(start)!; + string html = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + Dictionary starts = new Dictionary(StringComparer.Ordinal); + foreach (Match match in WordBox().Matches(html)) + { + starts.TryAdd(match.Groups[2].Value, double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture)); + } + + return starts; + } + finally + { + File.Delete(file); + } + } + + [GeneratedRegex("xMin=\"([0-9.]+)\"[^>]*>([^<]+)")] + private static partial Regex WordBox(); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/BuilderHarness.cs b/tests/TriasDev.Templify.Builder.Tests/BuilderHarness.cs new file mode 100644 index 00000000..999d2ef2 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/BuilderHarness.cs @@ -0,0 +1,207 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Validation; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; + +namespace TriasDev.Templify.Builder.Tests; + +/// +/// Builds definitions and checks the invariants every builder test holds (design spec, section 5). +/// +internal static class BuilderHarness +{ + public static readonly TemplateFormat[] Formats = { TemplateFormat.Docx, TemplateFormat.Odt }; + + public static TemplateBuildOptions Options(TemplateFormat format, string language = "en-US", ITextCatalog? texts = null) => + new TemplateBuildOptions { Format = format, Language = CultureInfo.GetCultureInfo(language), Texts = texts ?? TextCatalog.Empty }; + + public static GeneratedTemplate Build(ITemplateDefinition definition, TemplateFormat format) => + TemplateBuilder.Build(definition, Options(format)); + + /// + /// Builds the definition, checks the invariants and fills it with . + /// + /// The built template and the filled document. + public static (GeneratedTemplate Template, byte[] Filled) BuildAndFill(ITemplateDefinition definition, TemplateFormat format, string json) => + BuildAndFill(definition, Options(format), (processor, input, output) => processor.ProcessTemplate(input, output, json)); + + /// As , with explicit build options (language, texts). + public static (GeneratedTemplate Template, byte[] Filled) BuildAndFill(ITemplateDefinition definition, TemplateBuildOptions options, string json) => + BuildAndFill(definition, options, (processor, input, output) => processor.ProcessTemplate(input, output, json)); + + /// As , with data as a dictionary. + public static (GeneratedTemplate Template, byte[] Filled) BuildAndFill(ITemplateDefinition definition, TemplateFormat format, Dictionary data) => + BuildAndFill(definition, Options(format), (processor, input, output) => processor.ProcessTemplate(input, output, data)); + + /// As , with read-only data (a contract's witness). + public static (GeneratedTemplate Template, byte[] Filled) BuildAndFill(ITemplateDefinition definition, TemplateFormat format, IReadOnlyDictionary data) => + BuildAndFill(definition, Options(format), (processor, input, output) => processor.ProcessTemplate(input, output, data)); + + /// The options every fill uses: missing variables throw, invariant culture. + public static PlaceholderReplacementOptions FillOptions => new PlaceholderReplacementOptions + { + MissingVariableBehavior = MissingVariableBehavior.ThrowException, + Culture = CultureInfo.InvariantCulture, + }; + + private static (GeneratedTemplate Template, byte[] Filled) BuildAndFill( + ITemplateDefinition definition, + TemplateBuildOptions options, + Func fill) + { + TemplateFormat format = options.Format; + GeneratedTemplate template = TemplateBuilder.Build(definition, options); + AssertInvariants(definition, template, options); + + TemplateProcessor processor = new TemplateProcessor(FillOptions); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + ProcessingResult result = fill(processor, input, output); + Assert.True(result.IsSuccess, result.ErrorMessage); + Assert.False(result.HasWarnings, string.Join("; ", result.Warnings.Select(w => w.Message))); + + byte[] filled = output.ToArray(); + AssertPackage(format, filled); + return (template, filled); + } + + /// + /// The invariants of a built template, checked by the test kit (): + /// syntax, a complete contract (the witness fills it without missing variables or warnings), the package; plus + /// byte determinism. + /// + public static void AssertInvariants(ITemplateDefinition definition, GeneratedTemplate template, TemplateBuildOptions? options = null) + { + IReadOnlyList problems = Testing.TemplateVerifier.CheckTemplate(template); + Assert.True(problems.Count == 0, string.Join(Environment.NewLine, problems)); + + GeneratedTemplate again = TemplateBuilder.Build(definition, options ?? Options(template.Format)); + Assert.Equal(template.ContentHash, again.ContentHash); + AssertJsonRoundTrip(definition, template, options ?? Options(template.Format)); + } + + /// + /// Phase 3 (#274): exporting the definition to JSON and importing it builds the same bytes, and the import exports + /// to the same JSON. + /// + public static void AssertJsonRoundTrip(ITemplateDefinition definition, GeneratedTemplate template, TemplateBuildOptions options) + { + Json.TemplateJsonDocument exported = Json.TemplateJson.Export(definition, options); + ITemplateDefinition imported = Json.TemplateJson.Import(exported.Json, new Json.TemplateJsonImportOptions { Assets = exported.Assets, AllowRawXml = true }); + Assert.Equal(template.ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + Assert.Equal(exported.Json, Json.TemplateJson.Export(imported, options).Json); + } + + /// DOCX: OOXML schema validation. ODT: package structure (mimetype first, stored, no extra field; manifest). + public static void AssertPackage(TemplateFormat format, byte[] package) + { + IReadOnlyList problems = Testing.TemplateVerifier.CheckPackage(format, package); + Assert.True(problems.Count == 0, string.Join(Environment.NewLine, problems)); + } + + /// + /// Edits one entry of a package as text, the way a hand edit changes a document; the entry order is kept and the + /// ODF mimetype stays stored. + /// + public static byte[] EditEntry(byte[] package, string entryName, Func edit) + { + List<(string Name, byte[] Data)> entries = new List<(string, byte[])>(); + using (MemoryStream input = new MemoryStream(package)) + using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(input, System.IO.Compression.ZipArchiveMode.Read)) + { + foreach (System.IO.Compression.ZipArchiveEntry entry in archive.Entries) + { + using Stream entryStream = entry.Open(); + using MemoryStream data = new MemoryStream(); + entryStream.CopyTo(data); + byte[] content = data.ToArray(); + if (entry.FullName == entryName) + { + content = System.Text.Encoding.UTF8.GetBytes(edit(System.Text.Encoding.UTF8.GetString(content))); + } + + entries.Add((entry.FullName, content)); + } + } + + using MemoryStream output = new MemoryStream(); + using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(output, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true)) + { + foreach ((string name, byte[] data) in entries) + { + System.IO.Compression.ZipArchiveEntry entry = archive.CreateEntry( + name, + name == "mimetype" ? System.IO.Compression.CompressionLevel.NoCompression : System.IO.Compression.CompressionLevel.Optimal); + using Stream entryStream = entry.Open(); + entryStream.Write(data); + } + } + + return output.ToArray(); + } + + /// The main XML part of a template: word/document.xml or content.xml. + public static string MainPart(TemplateFormat format) => format == TemplateFormat.Docx ? "word/document.xml" : "content.xml"; + + /// Reads one entry of a package as XML. + public static System.Xml.Linq.XDocument ReadXml(byte[] package, string entryName) + { + using MemoryStream stream = new MemoryStream(package); + using System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Read); + System.IO.Compression.ZipArchiveEntry entry = archive.GetEntry(entryName) + ?? throw new InvalidOperationException($"The package has no entry '{entryName}'."); + using Stream entryStream = entry.Open(); + return System.Xml.Linq.XDocument.Load(entryStream); + } + + /// The rendered text of the body's paragraphs. + public static List ParagraphTexts(TemplateFormat format, byte[] package) + { + if (format == TemplateFormat.Odt) + { + return new OdtDocumentVerifier(package).GetParagraphTexts(); + } + + using MemoryStream stream = new MemoryStream(package); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + return document.MainDocumentPart!.Document!.Body! + .Elements() + .Select(DocxText) + .ToList(); + } + + private static string DocxText(DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph) + { + System.Text.StringBuilder text = new System.Text.StringBuilder(); + foreach (DocumentFormat.OpenXml.OpenXmlElement element in paragraph.Descendants()) + { + switch (element) + { + case DocumentFormat.OpenXml.Wordprocessing.Text t: + text.Append(t.Text); + break; + case DocumentFormat.OpenXml.Wordprocessing.TabChar: + text.Append('\t'); + break; + case DocumentFormat.OpenXml.Wordprocessing.Break br + when br.Type is null || br.Type.Value == DocumentFormat.OpenXml.Wordprocessing.BreakValues.TextWrapping: + text.Append('\n'); + break; + } + } + + return text.ToString(); + } +} + +/// A definition written as a lambda, for tests. +internal sealed class TestDefinition(Action compose, TemplateIdentity? identity = null) : ITemplateDefinition +{ + public TemplateIdentity Identity { get; } = identity ?? new TemplateIdentity("test", 1); + + public void Compose(TemplateComposer template) => compose(template); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ChainingTests.cs b/tests/TriasDev.Templify.Builder.Tests/ChainingTests.cs new file mode 100644 index 00000000..33e6a24b --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ChainingTests.cs @@ -0,0 +1,107 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Content-adding methods return their composer, and styles come first (#293). +public sealed class ChainingTests +{ + private static readonly CharacterStyleKey _strong = new CharacterStyleKey("Strong", "Strong Text"); + private static readonly ListStyleKey _bullets = new ListStyleKey("Bullets"); + + private static void Styles(TemplateComposer t) => t.Styles(StyleSheet.Create(s => + { + s.Character(_strong, c => c.Bold()); + s.List(_bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm()).Level(1, "–", 12.Mm(), 4.Mm())); + })); + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Chained_BuildsLikeStatements(TemplateFormat format) + { + TestDefinition chained = new TestDefinition(t => + { + Styles(t); + t.Content(c => c + .Paragraph("Title") + .Paragraph(x => x.Text("Dear ").Value(_strong, t.Data["name"]).Text(_strong, "!").Tab().Value(t.Data["total"], ValueFormat.Currency)) + .List(_bullets, l => l.Item("one").Item(1, "two").ForEach(t.Data["tags"], "tag", (tag, i) => i.Item(tag.Self))) + .Table(table => table + .Columns(k => k.Relative(1).Relative(1)) + .HeaderRow(r => r.Cell("A").Cell("B")) + .Row(r => r.Cell("1").Cell(c => c.Paragraph("2").Paragraph("3"))) + .ForEachRow(t.Data["lines"], "line", (line, rows) => rows.Row(r => r.Cell(line["name"]).Cell(line["qty"])))) + .Switch(t.Data["status"], s => s.Case("paid", b => b.Paragraph("Paid").Paragraph("Thanks")).Default(b => b.Paragraph("Open"))) + .PageBreak() + .Paragraph("End")); + }); + TestDefinition statements = new TestDefinition(t => + { + Styles(t); + t.Content(c => + { + c.Paragraph("Title"); + c.Paragraph(x => + { + x.Text("Dear "); + x.Value(_strong, t.Data["name"]); + x.Text(_strong, "!"); + x.Tab(); + x.Value(t.Data["total"], ValueFormat.Currency); + }); + c.List(_bullets, l => + { + l.Item("one"); + l.Item(1, "two"); + l.ForEach(t.Data["tags"], "tag", (tag, i) => i.Item(tag.Self)); + }); + c.Table(table => + { + table.Columns(k => + { + k.Relative(1); + k.Relative(1); + }); + table.HeaderRow(r => + { + r.Cell("A"); + r.Cell("B"); + }); + table.Row(r => + { + r.Cell("1"); + r.Cell(c => + { + c.Paragraph("2"); + c.Paragraph("3"); + }); + }); + table.ForEachRow(t.Data["lines"], "line", (line, rows) => rows.Row(r => + { + r.Cell(line["name"]); + r.Cell(line["qty"]); + })); + }); + c.Switch(t.Data["status"], s => + { + s.Case("paid", b => + { + b.Paragraph("Paid"); + b.Paragraph("Thanks"); + }); + s.Default(b => b.Paragraph("Open")); + }); + c.PageBreak(); + c.Paragraph("End"); + }); + }); + + GeneratedTemplate template = BuilderHarness.Build(chained, format); + + Assert.Equal(BuilderHarness.Build(statements, format).ContentHash, template.ContentHash); + BuilderHarness.AssertInvariants(chained, template); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ComponentCatalogTests.cs b/tests/TriasDev.Templify.Builder.Tests/ComponentCatalogTests.cs new file mode 100644 index 00000000..66749a1a --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ComponentCatalogTests.cs @@ -0,0 +1,160 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Registered components export as references (#274, hybrid). +public sealed class ComponentCatalogTests +{ + private static readonly ParagraphStyleKey _strong = new ParagraphStyleKey("Strong", "Strong Body"); + + public sealed record Address(string Street, string City); + + public sealed record AddressBlock(TemplatePath Address) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(x => + { + x.Value(Address["street"]); + x.Text(", "); + x.Value(Address["city"]); + }); + } + + public sealed record AddressBlockV2(TemplatePath Address) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(x => + { + x.Text("City: "); + x.Value(Address["city"]); + }); + } + + public enum Tone + { + Plain, + LoudVoice, + } + + public sealed record Badge(string Label, Tone Tone, int Repeat, decimal Threshold, ParagraphStyleKey Style, Length Gap, Color? Ink, IReadOnlyList Tags, TemplatePath
Where) : ITemplateComponent + { + public void Compose(BlockComposer content) + { + for (int i = 0; i < Repeat; i++) + { + content.Paragraph(Style, x => + { + x.Text(Label + " " + Tone + " " + Threshold.ToString(System.Globalization.CultureInfo.InvariantCulture) + " " + string.Join("/", Tags) + " " + Gap + " " + Ink + " "); + x.Value(Where.Path(a => a.City)); + }); + } + } + } + + public sealed class ThemeBlock(BrandTheme theme) : ITemplateComponent + { + public BrandTheme Theme { get; } = theme; + + public void Compose(BlockComposer content) => content.Paragraph("x"); + } + + public sealed record BrandTheme(string Name); + + private static ComponentCatalog Catalog() => new ComponentCatalog().Register("address").Register("badge"); + + private static TestDefinition Definition() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(_strong, p => p.Bold()))); + t.Content(c => + { + c.Component(new AddressBlock(t.Data["order"]["customer"]["address"])); + c.ForEach(t.Data["branches"], "branch", (branch, b) => + b.Component(new AddressBlock(branch["address"]))); + c.Component(new Badge("Hi", Tone.LoudVoice, 2, 0.5m, _strong, 3.Mm(), Color.FromHex("1F4E79"), new[] { "a", "b" }, t.DataAs().Path(r => r.Office))); + }); + }); + + public sealed record Root(Address Office); + + [Fact] + public void Register_RejectsUnserializableParameters() + { + ArgumentException exception = Assert.Throws(() => new ComponentCatalog().Register("theme")); + + Assert.Contains("theme", exception.Message, StringComparison.Ordinal); + Assert.Contains("BrandTheme", exception.Message, StringComparison.Ordinal); + Assert.Throws(() => new ComponentCatalog().Register("Address-Block")); + Assert.Throws(() => new ComponentCatalog().Register("address").Register("address")); + } + + [Fact] + public void Export_RegisteredComponent_IsAReference() + { + string json = TemplateJson.Export(Definition(), BuilderHarness.Options(TemplateFormat.Docx), Catalog()).Json; + + Assert.Contains("\"component\": \"address\"", json, StringComparison.Ordinal); + Assert.Contains("\"address\": \"order.customer.address\"", json, StringComparison.Ordinal); + Assert.Contains("\"address\": \"branch.address\"", json, StringComparison.Ordinal); + Assert.Contains("\"tone\": \"loudVoice\"", json, StringComparison.Ordinal); + Assert.Contains("\"gap\": \"3mm\"", json, StringComparison.Ordinal); + Assert.Contains("\"where\": \"office\"", json, StringComparison.Ordinal); + Assert.DoesNotContain("\"section\"", json, StringComparison.Ordinal); + + string unregistered = TemplateJson.Export(Definition(), BuilderHarness.Options(TemplateFormat.Docx)).Json; + Assert.Contains("\"section\": \"AddressBlock\"", unregistered, StringComparison.Ordinal); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void RoundTrip_WithCatalog_IsByteIdentical(TemplateFormat format) + { + TemplateBuildOptions options = BuilderHarness.Options(format); + TemplateJsonDocument exported = TemplateJson.Export(Definition(), options, Catalog()); + + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Components = Catalog() }); + + Assert.Equal(TemplateBuilder.Build(Definition(), options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + Assert.Equal(exported.Json, TemplateJson.Export(imported, options, Catalog()).Json); + } + + [Fact] + public void Import_ComponentReference_UsesCurrentComponentCode() + { + string json = TemplateJson.Export(Definition(), BuilderHarness.Options(TemplateFormat.Docx), Catalog()).Json; + ComponentCatalog updated = new ComponentCatalog().Register("address").Register("badge"); + + ITemplateDefinition imported = TemplateJson.Import(json, new TemplateJsonImportOptions { Components = updated }); + (_, byte[] filled) = BuilderHarness.BuildAndFill( + imported, + TemplateFormat.Docx, + """{ "order": { "customer": { "address": { "street": "S", "city": "Munich" } } }, "branches": [], "office": { "city": "Berlin" } }"""); + + Assert.Equal("City: Munich", BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)[0]); + } + + [Fact] + public void Import_UnknownComponent_IsTB9200() + { + string json = TemplateJson.Export(Definition(), BuilderHarness.Options(TemplateFormat.Docx), Catalog()).Json; + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(json, new TemplateJsonImportOptions { Components = new ComponentCatalog() })); + + Assert.All(exception.Errors, e => Assert.Equal("TB9200", e.Code)); + Assert.Contains(exception.Errors, e => e.Location == "/content/0" && e.Message.Contains("'address'", StringComparison.Ordinal)); + } + + [Fact] + public void Import_ReferenceWithoutParams_ForAComponentWithParameters_NamesTheMissingParameter() + { + string json = """{"templifyDefinition": 1, "identity": {"id": "test", "version": 1}, "content": [{"component": "address"}]}"""; + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(json, new TemplateJsonImportOptions { Components = Catalog() })); + + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("/content/0/params", error.Location); + Assert.Contains("address", error.Message, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ComponentVersionTests.cs b/tests/TriasDev.Templify.Builder.Tests/ComponentVersionTests.cs new file mode 100644 index 00000000..f65d0f32 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ComponentVersionTests.cs @@ -0,0 +1,144 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using DocumentFormat.OpenXml.CustomProperties; +using DocumentFormat.OpenXml.Packaging; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Component versions in the template stamp (#294). +public sealed class ComponentVersionTests +{ + [ComponentVersion(2)] + public sealed record Terms : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph("Terms"); + } + + public sealed record Card(string Title) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(Title); + } + + [ComponentVersion(3)] + public sealed record Box(string Title) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(Title); + } + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition WithComponents() => new TestDefinition(t => t.Content(c => c + .Component(new Terms()) + .Component(new Card("a")) + .Component(new Card("b")) + .Component(new Box("box")) + .Section("intro", s => s.Paragraph("Intro")))); + + [Theory] + [MemberData(nameof(Formats))] + public void Stamp_RecordsComponentsAndVersions(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(WithComponents(), format); + + Assert.Equal( + [new KeyValuePair("Box", 3), new KeyValuePair("Terms", 2)], + template.Stamp.Components.OrderBy(c => c.Key, StringComparer.Ordinal)); + TemplateStamp? read = TemplateInspector.Inspect(template.OpenRead()).Stamp; + Assert.Equal(template.Stamp, read); + } + + [Fact] + public void Stamp_UnversionedComponentsAndSections_AreNotRecorded() + { + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Component(new Card("a")).Section("intro", s => s.Paragraph("Intro")))), TemplateFormat.Docx); + + Assert.Empty(template.Stamp.Components); + Assert.DoesNotContain("Templify.Components", PropertyNames(template.Content.ToArray())); + } + + [Fact] + public void Stamp_WithoutComponentProperty_StillReads() + { + GeneratedTemplate template = BuilderHarness.Build(WithComponents(), TemplateFormat.Docx); + byte[] without = RemoveProperty(template.Content.ToArray(), "Templify.Components"); + + TemplateStamp? read = TemplateInspector.Inspect(new MemoryStream(without)).Stamp; + + Assert.NotNull(read); + Assert.Empty(read.Components); + Assert.Equal(template.Stamp.TemplateId, read.TemplateId); + } + + [Fact] + public void Stamp_ComponentProperty_IsSortedPairs() + { + GeneratedTemplate template = BuilderHarness.Build(WithComponents(), TemplateFormat.Docx); + + Assert.Equal("Box=3;Terms=2", PropertyValue(template.Content.ToArray(), "Templify.Components")); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_RegisteredVersionedComponent_KeepsTheStamp(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Component(new Terms()).Component(new Card("a")))); + ComponentCatalog components = new ComponentCatalog().Register("terms"); + TemplateBuildOptions options = BuilderHarness.Options(format, "de-DE"); + + string json = TemplateJson.Export(definition, options, components).Json; + GeneratedTemplate fromJson = TemplateBuilder.Build(TemplateJson.Import(json, new TemplateJsonImportOptions { Components = components }), options); + + Assert.Equal(TemplateBuilder.Build(definition, options).Content.ToArray(), fromJson.Content.ToArray()); + Assert.Equal(2, fromJson.Stamp.Components["Terms"]); + } + + [Fact] + public void Json_UnregisteredVersionedComponent_IsNotExportable() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Component(new Terms()))); + + TemplateBuildException error = Assert.Throws(() => TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx, "de-DE"))); + + BuildDiagnostic problem = Assert.Single(error.Errors); + Assert.Equal("TB9204", problem.Code); + Assert.Contains("Terms", problem.Message, StringComparison.Ordinal); + Assert.Contains("register", problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void ComponentVersion_MustBePositive() + { + Assert.Throws(() => new ComponentVersionAttribute(0)); + } + + private static List PropertyNames(byte[] docx) + { + using MemoryStream stream = new MemoryStream(docx); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + return document.CustomFilePropertiesPart!.Properties!.Elements().Select(p => p.Name!.Value!).ToList(); + } + + private static string? PropertyValue(byte[] docx, string name) + { + using MemoryStream stream = new MemoryStream(docx); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + return document.CustomFilePropertiesPart!.Properties!.Elements().FirstOrDefault(p => p.Name!.Value == name)?.InnerText; + } + + private static byte[] RemoveProperty(byte[] docx, string name) + { + using MemoryStream stream = new MemoryStream(); + stream.Write(docx); + using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true)) + { + Properties properties = document.CustomFilePropertiesPart!.Properties!; + properties.Elements().Single(p => p.Name!.Value == name).Remove(); + properties.Save(); + } + + return stream.ToArray(); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ConditionParserTests.cs b/tests/TriasDev.Templify.Builder.Tests/ConditionParserTests.cs new file mode 100644 index 00000000..44987ed5 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ConditionParserTests.cs @@ -0,0 +1,103 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; + +namespace TriasDev.Templify.Builder.Tests; + +/// Reading conditions back from their Templify text (#274). +public sealed class ConditionParserTests +{ + private static TemplatePath P(string path) => TemplatePath.Root(path); + + private static Condition Parse(string text) => ConditionParser.Parse(text, TemplatePath.Root); + + public static TheoryData Conditions => new TheoryData + { + (Condition)P("order.isPaid"), + P("order.status").Eq("paid"), + P("order.status").NotEq("open"), + P("order.total").Gt(1000), + P("order.total").Ge(0.5), + P("order.total").Lt(-2.5), + P("order.total").Le(3), + P("order.total").NotEq(0), + P("role").In("Admin", "Owner"), + P("name").Contains("a\"b\\c"), + P("name").StartsWith("Dr. "), + P("name").EndsWith("GmbH"), + P("notes").Exists, + P("notes").IsEmpty, + P("notes").IsNotEmpty, + !P("order.isPaid"), + !P("order.total").Gt(1), + P("a") & P("b") | P("c"), + P("a") & (P("b") | P("c")), + P("a") & P("b") & P("c"), + P("a") & (P("b") & P("c")), + !(P("a") | P("b")), + (Condition)P("exists"), + P("in").Eq("x"), + P("lines.amount").Gt(-2.5), + }; + + [Theory] + [MemberData(nameof(Conditions))] + public void Parse_ReadsWhatTheEmitterWrites(Condition condition) + { + string text = condition.ToString(); + + Condition parsed = Parse(text); + + Assert.Equal(text, parsed.ToString()); + } + + [Fact] + public void Parse_ResolvesPathsThroughTheResolver() + { + List seen = new List(); + + Condition parsed = ConditionParser.Parse("line.amount > 0 and [exists]", p => + { + seen.Add(p); + return TemplatePath.Root(p); + }); + + Assert.Equal(new[] { "line.amount", "exists" }, seen); + Assert.Equal("line.amount > 0 and [exists]", parsed.ToString()); + } + + [Fact] + public void Parse_AcceptsExtraSpacesAndParentheses() + { + Assert.Equal("a and b", Parse(" ( a ) and (b)").ToString()); + } + + [Theory] + [InlineData("a >", 3)] + [InlineData("(a", 2)] + [InlineData("a and", 5)] + [InlineData("", 0)] + [InlineData("a b", 2)] + [InlineData("a in (\"x\"", 9)] + public void Parse_Malformed_ReportsTheColumn(string text, int column) + { + FormatException exception = Assert.Throws(() => Parse(text)); + + Assert.Contains($"column {column}", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_BareWordLiteral_AsksForQuotes() + { + FormatException exception = Assert.Throws(() => Parse("status = paid")); + + Assert.Contains("quote", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_UnterminatedString() + { + Assert.Throws(() => Parse("a = \"x")); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ConditionalTests.cs b/tests/TriasDev.Templify.Builder.Tests/ConditionalTests.cs new file mode 100644 index 00000000..cf6e43d5 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ConditionalTests.cs @@ -0,0 +1,374 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TriasDev.Templify.Conditionals; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class ConditionalTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly TemplatePath _order = TemplatePath.Root("order"); + private static readonly TemplatePath _a = TemplatePath.Root("a"); + private static readonly TemplatePath _b = TemplatePath.Root("b"); + private static readonly TemplatePath _c = TemplatePath.Root("c"); + + // ── The emitter ───────────────────────────────────────────────────────────── + + public static TheoryData Emitted => new TheoryData + { + { "order.isPaid", _order["isPaid"] }, + { "order.status = \"paid\"", _order["status"].Eq("paid") }, + { "name = \"say \\\"hi\\\" \\\\ ok\"", TemplatePath.Root("name").Eq("say \"hi\" \\ ok") }, + { "total = 1.5", TemplatePath.Root("total").Eq(1.5) }, + { "total != 3", TemplatePath.Root("total").NotEq(3) }, + { "total > -5", TemplatePath.Root("total").Gt(-5) }, + { "total >= 100000000000000000000", TemplatePath.Root("total").Ge(1e20) }, + { "total < 0.25", TemplatePath.Root("total").Lt(0.25) }, + { "total <= 10", TemplatePath.Root("total").Le(10) }, + { "status != \"open\"", TemplatePath.Root("status").NotEq("open") }, + { "role in (\"admin\", \"owner\")", TemplatePath.Root("role").In("admin", "owner") }, + { "tags contains \"x\"", TemplatePath.Root("tags").Contains("x") }, + { "name startswith \"Ac\"", TemplatePath.Root("name").StartsWith("Ac") }, + { "name endswith \"Ltd\"", TemplatePath.Root("name").EndsWith("Ltd") }, + { "note exists", TemplatePath.Root("note").Exists }, + { "note is empty", TemplatePath.Root("note").IsEmpty }, + { "note is not empty", TemplatePath.Root("note").IsNotEmpty }, + { "[in]", TemplatePath.Root("in") }, + { "[Empty] = \"x\"", TemplatePath.Root("Empty").Eq("x") }, + { "order.in", _order["in"] }, + { "not a", !_a }, + { "not (a = \"x\")", !_a.Eq("x") }, + { "not (a and b)", !(_a & _b) }, + { "a or b and c", _a | (_b & _c) }, + { "(a or b) and c", (_a | _b) & _c }, + { "a and b and c", (_a & _b) & _c }, + { "a and (b and c)", _a & (_b & _c) }, + { "a or b or c", (_a | _b) | _c }, + { "not a and b", !_a & _b }, + { "Count > 0 and IsActive", Condition.Raw("Count > 0 and IsActive", TemplatePath.Root("Count"), TemplatePath.Root("IsActive")) }, + { "(Count > 0 and IsActive) or a", Condition.Raw("Count > 0 and IsActive") | _a }, + { "not (Count > 0)", !Condition.Raw("Count > 0") }, + }; + + [Theory] + [MemberData(nameof(Emitted))] + public void Emitter_WritesTemplifyConditionText(string expected, Condition condition) + { + Assert.Equal(expected, condition.ToString()); + ConditionValidationResult validation = new ConditionEvaluator().Validate(condition.ToString()); + Assert.True(validation.IsValid, string.Join("; ", validation.Issues.Select(i => i.Message))); + } + + [Fact] + public void Emitter_RejectsWhatCannotBeWritten() + { + Assert.Throws(() => default(TemplatePath).Eq("x")); + Assert.Throws(() => _ = (Condition)default(TemplatePath)); + Assert.Throws(() => TemplatePath.Root("1.5").Eq("x")); + Assert.Throws(() => _a.Eq("a }} b")); + Assert.Throws(() => _a.Eq("{{x")); + Assert.Throws(() => _a.Eq("“quoted”")); + Assert.Throws(() => _a.In()); + Assert.Throws(() => _a.Gt(double.NaN)); + Assert.Throws(() => _a.Gt(1e30)); + Assert.Throws(() => Condition.Raw("Count >")); + Assert.Throws(() => Condition.Raw("a }} b")); + } + + // ── The engine evaluates what the builder writes ─────────────────────────── + + private const string OrderJson = """ + { + "order": { "status": "paid", "total": 1500, "isVip": false, "tags": ["a", "b"], "note": "", + "role": "owner", "name": "Acme Ltd" }, + "in": "keyword" + } + """; + + private static readonly (Condition Condition, bool Expected)[] _cases = + { + (_order["status"].Eq("paid"), true), + (_order["status"].Eq("open"), false), + (_order["total"].Gt(1000), true), + (_order["total"].Le(1000), false), + (_order["total"].Eq(1500), true), + (!_order["isVip"], true), + (_order["status"].In("paid", "settled"), true), + (_order["tags"].Contains("b"), true), + (_order["name"].StartsWith("Acme"), true), + (_order["name"].EndsWith("GmbH"), false), + (_order["note"].IsEmpty, true), + (_order["note"].IsNotEmpty, false), + (_order["status"].Eq("paid") | (_order["total"].Lt(0) & _order["isVip"]), true), + ((_order["status"].Eq("open") | _order["total"].Gt(1000)) & !_order["isVip"], true), + (!_order["status"].Eq("paid"), false), + (TemplatePath.Root("in"), true), + (Condition.Raw("order.total > 100 and order.status = \"paid\"", _order["total"], _order["status"]), true), + (_order["isVip"], false), + }; + + [Theory] + [MemberData(nameof(Formats))] + public void Conditions_AreEvaluatedByTheEngineAsWritten(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + for (int i = 0; i < _cases.Length; i++) + { + int n = i; + c.If(_cases[n].Condition, b => b.Paragraph($"T{n}")).Else(b => b.Paragraph($"F{n}")); + } + })); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, OrderJson); + + Assert.Equal(_cases.Select((c, i) => (c.Expected ? "T" : "F") + i), BuilderHarness.ParagraphTexts(format, filled)); + } + + private static TestDefinition Chain() => new TestDefinition(template => + { + TemplatePath status = template.Data["order"]["status"]; + template.Content(c => + { + c.Paragraph("before"); + c.If(status.Eq("open"), b => b.Paragraph("open")) + .ElseIf(status.Eq("paid"), b => + { + b.Paragraph("paid"); + b.If(template.Data["order"]["total"].Gt(1000), inner => inner.Paragraph("large")); + }) + .ElseIf(status.Eq("overdue"), b => b.Paragraph("overdue")) + .Else(b => b.Paragraph("other")); + c.Paragraph("after"); + }); + }); + + [Theory] + [InlineData(TemplateFormat.Docx, "open", 5, "before|open|after")] + [InlineData(TemplateFormat.Docx, "paid", 5000, "before|paid|large|after")] + [InlineData(TemplateFormat.Docx, "paid", 5, "before|paid|after")] + [InlineData(TemplateFormat.Docx, "overdue", 5, "before|overdue|after")] + [InlineData(TemplateFormat.Docx, "draft", 5, "before|other|after")] + [InlineData(TemplateFormat.Odt, "open", 5, "before|open|after")] + [InlineData(TemplateFormat.Odt, "paid", 5000, "before|paid|large|after")] + [InlineData(TemplateFormat.Odt, "paid", 5, "before|paid|after")] + [InlineData(TemplateFormat.Odt, "overdue", 5, "before|overdue|after")] + [InlineData(TemplateFormat.Odt, "draft", 5, "before|other|after")] + public void ElseIfChain_AndNesting_ChooseOneBranch(TemplateFormat format, string status, int total, string expected) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Chain(), format, $$"""{ "order": { "status": "{{status}}", "total": {{total}} } }"""); + + Assert.Equal(expected.Split('|'), BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Markers_AreParagraphsOfTheirOwnInTheMarkerStyle(TemplateFormat format) + { + byte[] template = BuilderHarness.Build(Chain(), format).Content.ToArray(); + + string[] expected = + { + "before", "{{#if order.status = \"open\"}}", "open", "{{#elseif order.status = \"paid\"}}", "paid", + "{{#if order.total > 1000}}", "large", "{{/if}}", "{{#elseif order.status = \"overdue\"}}", "overdue", + "{{#else}}", "other", "{{/if}}", "after", + }; + Assert.Equal(expected, BuilderHarness.ParagraphTexts(format, template)); + + if (format == TemplateFormat.Docx) + { + XElement body = BuilderHarness.ReadXml(template, "word/document.xml").Root!.Element(_w + "body")!; + List markers = body.Elements(_w + "p").Where(p => p.Value.StartsWith("{{#", StringComparison.Ordinal) || p.Value.StartsWith("{{/", StringComparison.Ordinal)).ToList(); + Assert.Equal(7, markers.Count); + Assert.All(markers, m => + { + Assert.Equal("TemplifyMarker", m.Element(_w + "pPr")!.Element(_w + "pStyle")!.Attribute(_w + "val")!.Value); + Assert.Single(m.Elements(_w + "r")); + }); + XElement style = BuilderHarness.ReadXml(template, "word/styles.xml").Root!.Elements(_w + "style") + .Single(s => (string?)s.Attribute(_w + "styleId") == "TemplifyMarker"); + Assert.Equal("Template Marker", style.Element(_w + "name")!.Attribute(_w + "val")!.Value); + Assert.Equal("16", style.Element(_w + "rPr")!.Element(_w + "sz")!.Attribute(_w + "val")!.Value); + } + else + { + List markers = BuilderHarness.ReadXml(template, "content.xml").Descendants(_text + "p") + .Where(p => (string?)p.Attribute(_text + "style-name") == "TemplifyMarker").ToList(); + Assert.Equal(7, markers.Count); + XElement style = BuilderHarness.ReadXml(template, "styles.xml").Descendants(_style + "style") + .Single(s => (string?)s.Attribute(_style + "name") == "TemplifyMarker"); + Assert.Equal("Template Marker", style.Attribute(_style + "display-name")!.Value); + Assert.Equal("8pt", style.Element(_style + "text-properties")!.Attribute(_fo + "font-size")!.Value); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void MarkerStyle_CanBeRedefinedByTheStyleSheet(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => + { + template.Styles(StyleSheet.Create(s => s.Paragraph(BuilderStyles.TemplateMarker, p => p.Size(6.Pt()).Color(Color.FromHex("FF0000"))))); + template.Content(c => c.If(template.Data["x"], b => b.Paragraph("x"))); + }); + + byte[] template = BuilderHarness.Build(definition, format).Content.ToArray(); + + if (format == TemplateFormat.Docx) + { + List styles = BuilderHarness.ReadXml(template, "word/styles.xml").Root!.Elements(_w + "style") + .Where(s => (string?)s.Attribute(_w + "styleId") == "TemplifyMarker").ToList(); + Assert.Equal("12", Assert.Single(styles).Element(_w + "rPr")!.Element(_w + "sz")!.Attribute(_w + "val")!.Value); + } + else + { + List styles = BuilderHarness.ReadXml(template, "styles.xml").Descendants(_style + "style") + .Where(s => (string?)s.Attribute(_style + "name") == "TemplifyMarker").ToList(); + Assert.Equal("6pt", Assert.Single(styles).Element(_style + "text-properties")!.Attribute(_fo + "font-size")!.Value); + } + } + + [Fact] + public void WithoutConditionals_NoMarkerStyleIsWritten() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph("x"))); + + XDocument styles = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Docx).Content.ToArray(), "word/styles.xml"); + + Assert.DoesNotContain(styles.Root!.Elements(_w + "style"), s => (string?)s.Attribute(_w + "styleId") == "TemplifyMarker"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void PageBreak_InsideAFalseConditional_IsRemoved(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + c.Paragraph("one"); + c.If(template.Data["breakPage"], b => b.PageBreak()); + c.Paragraph("two"); + })); + + (_, byte[] kept) = BuilderHarness.BuildAndFill(definition, format, """{ "breakPage": true }"""); + (_, byte[] removed) = BuilderHarness.BuildAndFill(definition, format, """{ "breakPage": false }"""); + + Assert.Equal(new[] { "one", string.Empty, "two" }, BuilderHarness.ParagraphTexts(format, kept)); + Assert.Equal(new[] { "one", "two" }, BuilderHarness.ParagraphTexts(format, removed)); + } + + // ── Switch ────────────────────────────────────────────────────────────────── + + private static TestDefinition StatusSwitch() => new TestDefinition(template => template.Content(c => + c.Switch(template.Data["status"], s => + { + s.Case("paid", b => b.Paragraph("Paid")); + s.Case(new[] { "settled", "closed" }, b => b.Paragraph("Settled")); + s.Default(b => b.Paragraph("Open")); + }))); + + [Theory] + [InlineData(TemplateFormat.Docx, "paid", "Paid")] + [InlineData(TemplateFormat.Docx, "closed", "Settled")] + [InlineData(TemplateFormat.Docx, "settled", "Settled")] + [InlineData(TemplateFormat.Docx, "unknown-later-value", "Open")] + [InlineData(TemplateFormat.Odt, "paid", "Paid")] + [InlineData(TemplateFormat.Odt, "closed", "Settled")] + [InlineData(TemplateFormat.Odt, "unknown-later-value", "Open")] + public void Switch_ChoosesTheCaseOrTheDefault(TemplateFormat format, string status, string expected) + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(StatusSwitch(), format, $$"""{ "status": "{{status}}" }"""); + + Assert.Equal(new[] { expected }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Equal( + new[] { "{{#if status = \"paid\"}}", "Paid", "{{#elseif status in (\"settled\", \"closed\")}}", "Settled", "{{#else}}", "Open", "{{/if}}" }, + BuilderHarness.ParagraphTexts(format, template.Content.ToArray())); + } + + [Fact] + public void Switch_WithoutCases_WritesTheDefaultUnconditionally() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.Switch(template.Data["status"], s => s.Default(b => b.Paragraph("Always"))))); + + Assert.Equal(new[] { "Always" }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, BuilderHarness.Build(definition, TemplateFormat.Docx).Content.ToArray())); + } + + [Fact] + public void Switch_WithoutDefault_OrWithDuplicateCases_IsAnError() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + c.Switch(template.Data["status"], s => s.Case("paid", b => b.Paragraph("x"))); + c.Switch(template.Data["kind"], s => + { + s.Case("a", b => b.Paragraph("a")); + s.Case(new[] { "b", "a" }, b => b.Paragraph("b")); + s.Default(b => b.Paragraph("d")); + }); + })); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + + Assert.Equal(new[] { "TB3001", "TB3002" }, exception.Errors.Select(e => e.Code)); + Assert.Contains("'status'", exception.Errors[0].Message, StringComparison.Ordinal); + } + + [Fact] + public void Switch_DefaultTwice_Throws() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.Switch(template.Data["status"], s => + { + s.Default(b => b.Paragraph("a")); + s.Default(b => b.Paragraph("b")); + }))); + + Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + } + + [Fact] + public void IfChain_MisuseThrows() + { + IfChain? kept = null; + TestDefinition afterElse = new TestDefinition(template => template.Content(c => + { + IfChain chain = c.If(template.Data["a"], b => b.Paragraph("a")); + chain.Else(b => b.Paragraph("b")); + chain.ElseIf(template.Data["c"], b => b.Paragraph("c")); + })); + TestDefinition outside = new TestDefinition(template => template.Content(c => kept = c.If(template.Data["a"], b => b.Paragraph("a")))); + + Assert.Throws(() => TemplateBuilder.Build(afterElse, BuilderHarness.Options(TemplateFormat.Docx))); + TemplateBuilder.Build(outside, BuilderHarness.Options(TemplateFormat.Docx)); + Assert.Throws(() => kept!.Else(b => b.Paragraph("late"))); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersTheChosenBranchesOnly(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Chain(), format, """{ "order": { "status": "paid", "total": 5000 } }"""); + string extension = template.FileExtension.TrimStart('.'); + + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, extension, "txt:Text (encoded):UTF8", "txt")).TrimStart(''); + Assert.Equal(new[] { "before", "paid", "large", "after" }, text.Replace("\r\n", "\n", StringComparison.Ordinal).TrimEnd('\n').Split('\n')); + + string templateText = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(template.Content.ToArray(), extension, "txt:Text (encoded):UTF8", "txt")); + Assert.Contains("{{#elseif order.status = \"overdue\"}}", templateText, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/DataCatalogEvolutionTests.cs b/tests/TriasDev.Templify.Builder.Tests/DataCatalogEvolutionTests.cs new file mode 100644 index 00000000..ade0922f --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/DataCatalogEvolutionTests.cs @@ -0,0 +1,124 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json.Nodes; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// The data catalogue as JSON and as witness data for checking stored templates (#294). +public sealed class DataCatalogEvolutionTests +{ + public sealed record OrderData(Order Order); + + public sealed record Order(string Number, bool IsExpress, Customer Customer, IReadOnlyList Lines, Dictionary Extra); + + public sealed record Customer(string Name, string Contact); + + public sealed record Line(string Description, decimal Amount); + + [Fact] + public void ToJson_ListsEveryPath_WithKindAndType() + { + DataCatalog catalog = DataCatalog.From(); + + JsonNode root = JsonNode.Parse(catalog.ToJson())!; + + Assert.Equal(1, root["version"]!.GetValue()); + JsonArray paths = root["paths"]!.AsArray(); + Assert.Equal(catalog.Entries.Count, paths.Count); + Assert.Equal(catalog.Entries.Select(e => e.Path), paths.Select(p => p!["path"]!.GetValue())); + JsonNode lines = paths.Single(p => p!["path"]!.GetValue() == "order.lines")!; + Assert.Equal("collection", lines["kind"]!.GetValue()); + JsonNode amount = paths.Single(p => p!["path"]!.GetValue() == "order.lines[].amount")!; + Assert.Equal("value", amount["kind"]!.GetValue()); + Assert.Equal("decimal", amount["type"]!.GetValue()); + Assert.Equal("open", paths.Single(p => p!["path"]!.GetValue() == "order.extra")!["kind"]!.GetValue()); + Assert.Contains("\n", catalog.ToJson(), StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Witness_ValidatesTemplateReadingAnyCataloguePath(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build( + new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.Paragraph(order["customer"]["name"]); + c.If(order["isExpress"], b => b.Paragraph("Express")); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(line["description"])); + }); + }), + format); + + ValidationResult result = DataCatalog.From().ValidateTemplate(template.Content.ToArray()); + + Assert.True(result.IsValid); + Assert.Empty(result.MissingVariables); + Assert.DoesNotContain(result.Warnings, w => w.Type == ValidationWarningType.MissingConditionVariable); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Witness_AcceptsAnyPathBelowAnOpenShape(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build( + new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.Paragraph(order["extra"]["anything"]["deep"]); + c.If(order["extra"]["flag"], b => b.Paragraph("Flag")); + c.ForEach(order["extra"]["items"], "item", (item, b) => b.Paragraph(item["name"])); + }); + }), + format); + + ValidationResult result = DataCatalog.From().ValidateTemplate(template.Content.ToArray()); + + Assert.True(result.IsValid); + Assert.Empty(result.MissingVariables); + Assert.DoesNotContain(result.Warnings, w => w.Type == ValidationWarningType.MissingConditionVariable); + } + + [Fact] + public void Witness_LacksPathsTheCatalogueDoesNotHave() + { + GeneratedTemplate template = BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["order"]["customer"]["fax"]))), + TemplateFormat.Docx); + + ValidationResult result = DataCatalog.From().ValidateTemplate(template.Content.ToArray()); + + Assert.Equal(["order.customer.fax"], result.MissingVariables); + } + + [Fact] + public void Witness_OpenShapeNames_DoNotReachClosedTypes() + { + GeneratedTemplate template = BuilderHarness.Build( + new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.Paragraph(order["extra"]["fax"]); + c.Paragraph(order["customer"]["fax"]); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(line["fax"])); + c.If(order["customer"]["vip"], b => b.Paragraph("VIP")); + }); + }), + TemplateFormat.Docx); + + ValidationResult result = DataCatalog.From().ValidateTemplate(template.Content.ToArray()); + + Assert.Equal(["line.fax", "order.customer.fax"], result.MissingVariables.Order(StringComparer.Ordinal)); + Assert.Contains(DataCatalog.MissingNames(result), n => n == "order.customer.vip"); + } + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/DataCatalogTests.cs b/tests/TriasDev.Templify.Builder.Tests/DataCatalogTests.cs new file mode 100644 index 00000000..2320f442 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/DataCatalogTests.cs @@ -0,0 +1,129 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// The data catalogue of a C# type, and the import check against it (#274). +public sealed class DataCatalogTests +{ + public sealed record OrderData(Order Order); + + public sealed record Order(string Number, DateTime Date, decimal? Total, bool IsExpress, Customer Customer, IReadOnlyList Lines, string[] Tags); + + public sealed record Customer(string Name, Address Address); + + public sealed record Address(string Street, string City); + + public sealed record Line(string Description, int Quantity); + + public sealed record Renamed([property: JsonPropertyName("cust")] Customer Customer, bool IsExpress, [property: JsonIgnore] string Secret); + + public sealed record Node(string Name, IReadOnlyList Children, Node? Parent); + + public sealed record WithOpen(Dictionary Extra, JsonElement Raw, object Anything); + + [Fact] + public void From_ListsPathsWithKinds() + { + DataCatalog catalog = DataCatalog.From(); + + Assert.Contains(new DataCatalogEntry("order.number", DataKind.Value, typeof(string)), catalog.Entries); + Assert.Contains(new DataCatalogEntry("order.total", DataKind.Value, typeof(decimal?)), catalog.Entries); + Assert.Contains(new DataCatalogEntry("order.customer", DataKind.Object, typeof(Customer)), catalog.Entries); + Assert.Contains(new DataCatalogEntry("order.lines", DataKind.Collection, typeof(IReadOnlyList)), catalog.Entries); + Assert.Contains(new DataCatalogEntry("order.lines[]", DataKind.Object, typeof(Line)), catalog.Entries); + Assert.Contains(new DataCatalogEntry("order.tags[]", DataKind.Value, typeof(string)), catalog.Entries); + Assert.True(catalog.Contains("order.lines[].description")); + Assert.True(catalog.Contains("order.customer.address.city")); + Assert.False(catalog.Contains("order.customer.address.zip")); + Assert.False(catalog.Contains("order.number.length")); + } + + [Fact] + public void From_HonoursNaming() + { + Assert.True(DataCatalog.From().Contains("cust.name")); + Assert.False(DataCatalog.From().Contains("secret")); + Assert.True(DataCatalog.From(JsonNamingPolicy.SnakeCaseLower).Contains("is_express")); + Assert.False(DataCatalog.From(JsonNamingPolicy.SnakeCaseLower).Contains("isExpress")); + } + + [Fact] + public void From_RecursiveType_Terminates() + { + DataCatalog catalog = DataCatalog.From(); + + Assert.True(catalog.Contains("children[].name")); + Assert.True(catalog.Contains("parent")); + Assert.DoesNotContain(catalog.Entries, e => e.Path.Count(c => c == '.') > 16); + } + + [Fact] + public void From_OpenShapes_AcceptAnythingBelow() + { + DataCatalog catalog = DataCatalog.From(); + + Assert.Contains(catalog.Entries, e => e.Path == "extra" && e.Kind == DataKind.Open); + Assert.True(catalog.Contains("extra.anything.deep")); + Assert.True(catalog.Contains("raw.x")); + Assert.True(catalog.Contains("anything[].y")); + } + + [Fact] + public void Import_PathOutsideCatalog_IsTB9203() + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "c", "version": 1 }, + "content": [ + { "paragraph": "{{order.nummer}}" }, + { "if": "order.totl > 1", "then": [ { "paragraph": "x" } ] }, + { "forEach": "order.lines", "as": "line", "body": [ "{{line.descr}}{{@number}}" ] } + ] + } + """; + + TemplateBuildException exception = Assert.Throws(() => + TemplateJson.Import(json, new TemplateJsonImportOptions { Data = DataCatalog.From() })); + + Assert.All(exception.Errors, e => Assert.Equal("TB9203", e.Code)); + Assert.Equal( + new[] { "/content/0/paragraph", "/content/1/if", "/content/2/body/0" }, + exception.Errors.Select(e => e.Location)); + Assert.Contains("order.lines[].descr", exception.Errors[2].Message, StringComparison.Ordinal); + + TemplateJson.Import(json.Replace("nummer", "number", StringComparison.Ordinal).Replace("totl", "total", StringComparison.Ordinal).Replace("line.descr}", "line.description}", StringComparison.Ordinal), new TemplateJsonImportOptions { Data = DataCatalog.From() }); + } + + [Fact] + public void Sample_ContractIsInsideTheCatalogue() + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = CultureInfo.GetCultureInfo("en-GB"), Texts = SampleTexts.Catalog }; + GeneratedTemplate template = TemplateBuilder.Build(new OrderConfirmation(BrandTheme.CreateDefault()), options); + DataCatalog catalog = DataCatalog.From(); + + Assert.All(template.Contract.Entries, e => Assert.True(catalog.Contains(e.Path), e.Path)); + } + + public sealed record SampleOrderData(SampleOrder Order); + + public sealed record SampleOrder( + string Number, DateTime Date, string Status, bool IsExpress, decimal Total, decimal Discount, string Notes, + SampleCustomer Customer, IReadOnlyList Lines, IReadOnlyList Checks); + + public sealed record SampleCustomer(string Name, string Contact, bool IsNew, SampleAddress Address); + + public sealed record SampleAddress(string Street, string PostalCode, string City, string Country); + + public sealed record SampleLine(string Description, int Quantity, decimal Amount, bool InStock, IReadOnlyList Tags); + + public sealed record SampleCheck(string Title, bool Passed, string? Note); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs new file mode 100644 index 00000000..3aef90cf --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class DataContractTests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private sealed class Address(TemplatePath address) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(x => + { + x.Value(address["street"]); + x.Text(" "); + x.Value(address["city"]); + }); + } + + private static TestDefinition Order() => new TestDefinition(template => + { + TemplatePath order = template.Data["order"]; + template.Content(c => + { + c.Paragraph(order["number"]); + c.Component(new Address(order["customer.address"])); + c.If(order["isPaid"] & order["total"].Gt(100), b => b.Paragraph("paid")); + c.Switch(order["status"], s => + { + s.Case("open", b => b.Paragraph("open")); + s.Default(b => b.Paragraph("other")); + }); + c.ForEach(order["lines"], "line", (line, b) => + { + b.If(!line.Loop.IsFirst, r => r.Paragraph("---")); + b.Paragraph(x => + { + x.Value(line.Loop.Number); + x.Value(line["description"]); + x.Value(order["currency"]); + }); + b.ForEach(line["tags"], "tag", (tag, tb) => tb.Paragraph(tag.Self)); + b.If(Condition.Raw("line.amount > 10", line["amount"]), r => r.Paragraph("big")); + }); + }); + }); + + [Fact] + public void Contract_ListsEveryPathInCanonicalForm() + { + DataContract contract = BuilderHarness.Build(Order(), TemplateFormat.Docx).Contract; + + Assert.Equal( + new[] + { + new ContractEntry("order.currency", ContractUsage.Value), + new ContractEntry("order.customer.address.city", ContractUsage.Value), + new ContractEntry("order.customer.address.street", ContractUsage.Value), + new ContractEntry("order.isPaid", ContractUsage.Condition), + new ContractEntry("order.lines", ContractUsage.Collection), + new ContractEntry("order.lines[].amount", ContractUsage.Condition), + new ContractEntry("order.lines[].description", ContractUsage.Value), + new ContractEntry("order.lines[].tags", ContractUsage.Collection), + new ContractEntry("order.lines[].tags[]", ContractUsage.Value), + new ContractEntry("order.number", ContractUsage.Value), + new ContractEntry("order.status", ContractUsage.Condition), + new ContractEntry("order.total", ContractUsage.Condition), + }, + contract.Entries); + Assert.Equal(64, contract.Hash.Length); + } + + [Fact] + public void Hash_IsTheSameForEveryFormatAndLanguage() + { + string[] hashes = new[] { "en-US", "de-DE", "fr" } + .SelectMany(language => BuilderHarness.Formats.Select(format => + TemplateBuilder.Build(Order(), BuilderHarness.Options(format, language)).Contract.Hash)) + .Distinct() + .ToArray(); + + Assert.Single(hashes); + } + + [Fact] + public void Hash_ChangesWithThePaths() + { + TestDefinition one = new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["a"]))); + TestDefinition other = new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["b"]))); + TestDefinition asCondition = new TestDefinition(t => t.Content(c => c.If(t.Data["a"], b => b.Paragraph("x")))); + + string[] hashes = + { + BuilderHarness.Build(one, TemplateFormat.Docx).Contract.Hash, + BuilderHarness.Build(other, TemplateFormat.Docx).Contract.Hash, + BuilderHarness.Build(asCondition, TemplateFormat.Docx).Contract.Hash, + }; + + Assert.Equal(3, hashes.Distinct().Count()); + } + + [Fact] + public void Witness_HasEveryPathWithOneItemPerCollection() + { + IReadOnlyDictionary witness = BuilderHarness.Build(Order(), TemplateFormat.Odt).Contract.CreateWitness(); + + Dictionary order = Assert.IsType>(witness["order"]); + Assert.Equal("x", order["number"]); + Dictionary line = Assert.IsType>(Assert.Single(Assert.IsType>(order["lines"]))); + Assert.Equal("x", line["description"]); + Assert.Equal("x", Assert.Single(Assert.IsType>(line["tags"]))); + Assert.Equal("x", ((Dictionary)((Dictionary)order["customer"]!)["address"]!)["city"]); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Witness_FillsTheTemplateWithoutAnyMissingVariable(TemplateFormat format) + { + GeneratedTemplate built = BuilderHarness.Build(Order(), format); + + using (Stream stream = built.OpenRead()) + { + ValidationResult validation = new TemplateProcessor().ValidateTemplate(stream, built.Contract.CreateWitness()); + Assert.Empty(validation.MissingVariables); + Assert.DoesNotContain(validation.Warnings, w => w.Type == ValidationWarningType.MissingConditionVariable); + } + + // Fills with MissingVariableBehavior.ThrowException and no warnings (the harness asserts both). + BuilderHarness.BuildAndFill(Order(), format, built.Contract.CreateWitness()); + } + + [Fact] + public void Json_RoundTrips() + { + DataContract contract = BuilderHarness.Build(Order(), TemplateFormat.Docx).Contract; + + string json = contract.ToJson(); + DataContract read = DataContract.FromJson(json); + + Assert.Equal(contract.Entries, read.Entries); + Assert.Equal(contract.Hash, read.Hash); + Assert.Contains("\"usage\": \"collection\"", json, StringComparison.Ordinal); + Assert.Contains($"\"hash\": \"{contract.Hash}\"", json, StringComparison.Ordinal); + } + + [Theory] + [InlineData("")] + [InlineData("[]")] + [InlineData("""{ "version": 2, "entries": [] }""")] + [InlineData("""{ "version": 1 }""")] + [InlineData("""{ "version": 1, "entries": [ { "path": "a", "usage": "unknown" } ] }""")] + [InlineData("""{ "version": 1, "entries": [ { "path": "", "usage": "value" } ] }""")] + [InlineData("""{ "version": 1, "entries": [ { "usage": "value" } ] }""")] + public void Json_Invalid_Throws(string json) + { + Assert.Throws(() => DataContract.FromJson(json)); + } + + [Fact] + public void EmptyDefinition_HasAnEmptyContractAndWitness() + { + DataContract contract = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("static"))), TemplateFormat.Docx).Contract; + + Assert.Empty(contract.Entries); + Assert.Empty(contract.CreateWitness()); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/DefinitionErrorTests.cs b/tests/TriasDev.Templify.Builder.Tests/DefinitionErrorTests.cs new file mode 100644 index 00000000..def6b3b2 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/DefinitionErrorTests.cs @@ -0,0 +1,138 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class DefinitionErrorTests +{ + [Theory] + [InlineData("")] + [InlineData("customer.")] + [InlineData(".name")] + [InlineData("customer name")] + [InlineData("customer-name")] + [InlineData("{{name}}")] + [InlineData("@index")] + [InlineData("items[0][1]")] + public void Path_InvalidSegment_ThrowsWhereItIsWritten(string relative) + { + ArgumentException exception = Assert.Throws(() => TemplatePath.Root("order")[relative]); + Assert.Contains("not a valid data path", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Path_ThisAtTheRoot_Throws() + { + Assert.Throws(() => TemplatePath.Root("this.name")); + } + + [Fact] + public void Path_IsBuiltFromSegments() + { + TemplatePath path = TemplatePath.Root("order")["customer.address"]["city"]; + + Assert.Equal("order.customer.address.city", path.ToString()); + Assert.Equal(TemplatePath.Root("order.customer.address.city"), path); + Assert.True(path == TemplatePath.Root("order.customer.address.city")); + Assert.True(path != TemplatePath.Root("order")); + Assert.Equal("Straße_1", TemplatePath.Root("Straße_1").ToString()); + } + + [Fact] + public void Build_ValueWithTheRootPath_FailsWithAllErrors() + { + TestDefinition definition = new TestDefinition( + template => template.Content(c => + { + c.Paragraph(template.Data); + c.Paragraph(x => x.Value(default)); + }), + new TemplateIdentity(" ", 1)); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Equal(new[] { "TB0002", "TB1001", "TB1001" }, exception.Errors.Select(e => e.Code)); + Assert.Contains("3 errors", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Build_WithoutIdentity_Fails() + { + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(new NoIdentity(), BuilderHarness.Options(TemplateFormat.Odt))); + + Assert.Equal("TB0001", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void Build_UnknownFormat_Throws() + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Unknown, Language = CultureInfo.GetCultureInfo("en") }; + + Assert.Throws(() => TemplateBuilder.Build(new TestDefinition(_ => { }), options)); + } + + [Fact] + public void Build_InvariantLanguage_Throws() + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = CultureInfo.InvariantCulture }; + + Assert.Throws(() => TemplateBuilder.Build(new TestDefinition(_ => { }), options)); + } + + [Fact] + public void Composers_UsedAfterTheirLambda_Throw() + { + TemplateComposer? capturedTemplate = null; + BlockComposer? capturedBlock = null; + InlineComposer? capturedInline = null; + TestDefinition definition = new TestDefinition(template => + { + capturedTemplate = template; + template.Content(c => + { + capturedBlock = c; + c.Paragraph(x => capturedInline = x); + }); + }); + + TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx)); + + Assert.Throws(() => capturedTemplate!.Content(_ => { })); + Assert.Throws(() => capturedBlock!.Paragraph("late")); + Assert.Throws(() => capturedInline!.Text("late")); + } + + [Fact] + public void Build_EmptyDefinition_IsAValidEmptyDocument() + { + foreach (TemplateFormat format in BuilderHarness.Formats) + { + TestDefinition definition = new TestDefinition(_ => { }); + BuilderHarness.AssertInvariants(definition, BuilderHarness.Build(definition, format)); + } + } + + private sealed class NoIdentity : ITemplateDefinition + { + public TemplateIdentity Identity => null!; + + public void Compose(TemplateComposer template) + { + } + } + + [Fact] + public void Diagnostic_LocationIsNullForCSharp() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(new ParagraphStyleKey("Missing", "Missing"), "x"))); + + TemplateBuildException exception = Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.All(exception.Errors, e => Assert.Null(e.Location)); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ExperimentalTests.cs b/tests/TriasDev.Templify.Builder.Tests/ExperimentalTests.cs new file mode 100644 index 00000000..9b29af10 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ExperimentalTests.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace TriasDev.Templify.Builder.Tests; + +/// The builder packages are a preview: using their API reports TPLB001 until the consumer opts in. +public sealed class ExperimentalTests +{ + [Theory] + [InlineData(typeof(TemplateBuilder))] + [InlineData(typeof(Testing.TemplateVerifier))] + public void Assembly_IsExperimental(Type type) + { + ExperimentalAttribute attribute = Assert.Single(type.Assembly.GetCustomAttributes()); + Assert.Equal("TPLB001", attribute.DiagnosticId); + Assert.EndsWith("template-builder.md#preview-status", attribute.UrlFormat, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/Fixtures/OFL.txt b/tests/TriasDev.Templify.Builder.Tests/Fixtures/OFL.txt new file mode 100644 index 00000000..677d181a --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/Fixtures/OFL.txt @@ -0,0 +1,65 @@ +Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic with Reserved Font Name "Carlito". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL Open Font License Version 1.1 – 26 February 2007 + +PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font +projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not +sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold +with any software provided that the font names of derivative works are changed. The fonts and derivatives, however, +cannot be released under any other type of license. The requirement for fonts to remain under this license does not +apply to any document created using the fonts or their derivatives. + +DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license +and clearly marked as such. This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the copyright statement(s). + +"Original Version" refers to the collection of Font Software components as distributed by the Copyright +Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, or substituting – in part or in whole +-- any of the components of the Original Version, by changing formats or by porting the Font Software to a new +environment. + +"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the +Font Software. + +PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the +Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of +the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold +by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any +software, provided that each copy contains the above copyright notice and this license. These can be included +either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields +within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission +is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, +endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and +the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this +license, and must not be distributed under any other license. The requirement for fonts to remain under this +license does not apply to any document created using the Font Software. + +TERMINATION This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR +FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/tests/TriasDev.Templify.Builder.Tests/Fixtures/README.md b/tests/TriasDev.Templify.Builder.Tests/Fixtures/README.md new file mode 100644 index 00000000..328ec574 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/Fixtures/README.md @@ -0,0 +1,10 @@ +# Test fixtures + +`TemplifyEmbedTest-Regular.ttf` is a modified version of **Carlito Regular** (tyPoland Lukasz Dziedzic, SIL Open Font +License 1.1, see `OFL.txt`), used only by the font-embedding tests: + +- subset to Basic Latin (U+0020–U+007E), without hinting and layout features; +- renamed to the family "Templify Embed Test", because "Carlito" is a Reserved Font Name and because the tests need a + family that no machine has installed (LibreOffice ships Carlito itself). + +The copyright and licence entries of the font's name table are kept. diff --git a/tests/TriasDev.Templify.Builder.Tests/Fixtures/TemplifyEmbedTest-Regular.ttf b/tests/TriasDev.Templify.Builder.Tests/Fixtures/TemplifyEmbedTest-Regular.ttf new file mode 100644 index 00000000..9614db20 Binary files /dev/null and b/tests/TriasDev.Templify.Builder.Tests/Fixtures/TemplifyEmbedTest-Regular.ttf differ diff --git a/tests/TriasDev.Templify.Builder.Tests/FontEmbeddingTests.cs b/tests/TriasDev.Templify.Builder.Tests/FontEmbeddingTests.cs new file mode 100644 index 00000000..653b1f88 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/FontEmbeddingTests.cs @@ -0,0 +1,301 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Diagnostics; +using System.IO.Compression; +using System.Xml.Linq; +using TriasDev.Templify.Builder.Testing; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Font embedding (#288). +public sealed class FontEmbeddingTests +{ + private const string Family = "Templify Embed Test"; + + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _svg = "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"; + private static readonly XNamespace _xlink = "http://www.w3.org/1999/xlink"; + private static readonly XNamespace _manifest = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; + + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("BodyCopy", "Body Copy"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("SectionHeading", "Section Heading"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static byte[] FontBytes() + { + using Stream stream = typeof(FontEmbeddingTests).Assembly.GetManifestResourceStream("TemplifyEmbedTest-Regular.ttf")!; + using MemoryStream copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + /// The font with a different fsType (OS/2 offset 8); checksums are not checked by the reader. + private static byte[] WithFsType(ushort fsType) + { + byte[] font = FontBytes(); + int tables = BinaryPrimitives.ReadUInt16BigEndian(font.AsSpan(4)); + for (int i = 0; i < tables; i++) + { + int record = 12 + (i * 16); + if (System.Text.Encoding.ASCII.GetString(font, record, 4) == "OS/2") + { + int offset = (int)BinaryPrimitives.ReadUInt32BigEndian(font.AsSpan(record + 8)); + BinaryPrimitives.WriteUInt16BigEndian(font.AsSpan(offset + 8), fsType); + return font; + } + } + + throw new InvalidOperationException("The test font has no OS/2 table."); + } + + private static TestDefinition Document(FontFace font, FontFace? headingFont = null) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.Font(font).Size(12.Pt())); + s.Paragraph(_body, p => p.SpaceAfter(6.Pt())); + s.Paragraph(_heading, p => p.BasedOn(_body).Font(headingFont ?? font).Size(16.Pt())); + })); + t.Content(c => + { + c.Paragraph(_heading, "Embedded font"); + c.Paragraph(_body, x => + { + x.Text("Hello "); + x.Value(t.Data["name"]); + }); + }); + }); + + [Fact] + public void Embedded_ReadsTheFamilyFromTheFile() + { + FontFace font = FontFace.Embedded(FontBytes()); + + Assert.Equal(Family, font.Family); + Assert.True(font.IsEmbedded); + Assert.False(new FontFace(Family).IsEmbedded); + } + + [Fact] + public void Embedded_WithAFamily_MustBeOneTheFileDeclares() + { + Assert.Equal(Family, FontFace.Embedded(Family, FontBytes()).Family); + + ArgumentException exception = Assert.Throws(() => FontFace.Embedded("Other Family", FontBytes())); + Assert.Contains("'Templify Embed Test'", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Equality_IsFamilyAndFile() + { + FontFace embedded = FontFace.Embedded(FontBytes()); + + Assert.Equal(embedded, FontFace.Embedded(FontBytes())); + Assert.Equal(embedded.GetHashCode(), FontFace.Embedded(FontBytes()).GetHashCode()); + Assert.NotEqual(embedded, new FontFace(Family)); + Assert.NotEqual(embedded, FontFace.Embedded(WithFsType(0x0008))); + Assert.Equal(new FontFace(Family), new FontFace(Family)); + } + + [Fact] + public void Embedded_CopiesTheBytes() + { + byte[] bytes = FontBytes(); + FontFace font = FontFace.Embedded(bytes); + bytes[100] ^= 0xFF; + + Assert.Equal(FontFace.Embedded(FontBytes()), font); + } + + [Theory] + [InlineData((ushort)0x0000)] + [InlineData((ushort)0x0008)] + [InlineData((ushort)0x000C)] + [InlineData((ushort)0x0108)] + public void Embedded_AllowsInstallableAndEditableFonts(ushort fsType) + { + Assert.True(FontFace.Embedded(WithFsType(fsType)).IsEmbedded); + } + + [Theory] + [InlineData((ushort)0x0002, "restricted")] + [InlineData((ushort)0x0004, "preview and print only")] + [InlineData((ushort)0x0208, "bitmaps only")] + public void Embedded_RefusesFontsWhoseLicenceForbidsIt(ushort fsType, string reason) + { + ArgumentException exception = Assert.Throws(() => FontFace.Embedded(WithFsType(fsType))); + + Assert.Contains(reason, exception.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("OTTO", "PostScript (CFF)")] + [InlineData("ttcf", "collection")] + [InlineData("wOFF", "WOFF")] + [InlineData("\u0089PNG", "not a TrueType font")] + public void Embedded_RefusesOtherFileTypes(string signature, string reason) + { + byte[] bytes = FontBytes(); + System.Text.Encoding.Latin1.GetBytes(signature).CopyTo(bytes, 0); + + ArgumentException exception = Assert.Throws(() => FontFace.Embedded(bytes)); + + Assert.Contains(reason, exception.Message, StringComparison.Ordinal); + Assert.Throws(() => FontFace.Embedded(new byte[] { 0, 1 })); + Assert.Throws(() => FontFace.Embedded(null!)); + } + + [Fact] + public void Docx_EmbedsTheObfuscatedFont() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Document(FontFace.Embedded(FontBytes())), TemplateFormat.Docx, """{ "name": "Ada" }"""); + + BuilderHarness.AssertInvariants(Document(FontFace.Embedded(FontBytes())), template); + foreach (byte[] package in new[] { template.Content.ToArray(), filled }) + { + XElement font = Assert.Single(BuilderHarness.ReadXml(package, "word/fontTable.xml").Root!.Elements(_w + "font")); + Assert.Equal(Family, (string?)font.Attribute(_w + "name")); + XElement embed = font.Element(_w + "embedRegular")!; + string key = (string)embed.Attribute(_w + "fontKey")!; + Assert.Matches("^\\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\\}$", key); + + XElement relationship = BuilderHarness.ReadXml(package, "word/_rels/fontTable.xml.rels").Root!.Elements() + .Single(r => (string?)r.Attribute("Id") == (string?)embed.Attribute(_r + "id")); + Assert.Equal("http://schemas.openxmlformats.org/officeDocument/2006/relationships/font", (string?)relationship.Attribute("Type")); + Assert.Equal(FontBytes(), Deobfuscate(Entry(package, "word/" + (string)relationship.Attribute("Target")!), key)); + Assert.NotNull(BuilderHarness.ReadXml(package, "word/settings.xml").Root!.Element(_w + "embedTrueTypeFonts")); + } + } + + [Fact] + public void Odt_EmbedsTheFontFile() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Document(FontFace.Embedded(FontBytes())), TemplateFormat.Odt, """{ "name": "Ada" }"""); + + foreach (byte[] package in new[] { template.Content.ToArray(), filled }) + { + XElement face = BuilderHarness.ReadXml(package, "styles.xml").Descendants(_style + "font-face").Single(f => (string?)f.Attribute(_style + "name") == Family); + XElement uri = face.Element(_svg + "font-face-src")!.Element(_svg + "font-face-uri")!; + string path = (string)uri.Attribute(_xlink + "href")!; + Assert.StartsWith("Fonts/", path, StringComparison.Ordinal); + Assert.Equal("truetype", (string?)uri.Element(_svg + "font-face-format")!.Attribute(_svg + "string")); + Assert.Equal(FontBytes(), Entry(package, path)); + + XElement entry = BuilderHarness.ReadXml(package, "META-INF/manifest.xml").Root!.Elements(_manifest + "file-entry") + .Single(e => (string?)e.Attribute(_manifest + "full-path") == path); + Assert.Equal("application/x-font-ttf", (string?)entry.Attribute(_manifest + "media-type")); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void AFontUsedByManyStyles_IsEmbeddedOnce(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Document(FontFace.Embedded(FontBytes()), FontFace.Embedded(FontBytes())), format); + + string folder = format == TemplateFormat.Docx ? "word/fonts/" : "Fonts/"; + Assert.Single(EntryNames(template.Content.ToArray()), n => n.StartsWith(folder, StringComparison.Ordinal)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void WithoutEmbeddedFonts_NothingIsAdded(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Document(new FontFace(Family)), format); + + List names = EntryNames(template.Content.ToArray()); + Assert.DoesNotContain(names, n => n.Contains("font", StringComparison.OrdinalIgnoreCase) || n == "word/settings.xml"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void OneFamilyWithTwoFiles_IsABuildError(TemplateFormat format) + { + TestDefinition definition = Document(FontFace.Embedded(FontBytes()), FontFace.Embedded(WithFsType(0x0008))); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, format)); + + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB2011", error.Code); + Assert.Contains(Family, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Verifier_PassesForEmbeddedFonts() + { + TemplateVerifier.VerifyAll( + () => Document(FontFace.Embedded(FontBytes())), + new TemplateVerificationOptions { SampleData = ["""{ "name": "Ada" }"""] }); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersWithTheEmbeddedFont(TemplateFormat format) + { + Assert.SkipUnless(LibreOfficeConverter.IsAvailable, "LibreOffice (soffice) is not installed; set TEMPLIFY_SOFFICE to run round-trip tests."); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Document(FontFace.Embedded(FontBytes())), format, """{ "name": "Ada" }"""); + + // The family is installed nowhere: the PDF can only use it if LibreOffice loaded it from the document. + Assert.Contains("TemplifyEmbedTest", PdfFonts(LibreOfficeConverter.ToPdf(filled, template.FileExtension)), StringComparison.Ordinal); + Assert.DoesNotContain("TemplifyEmbedTest", PdfFonts(LibreOfficeConverter.ToPdf(BuilderHarness.Build(Document(new FontFace(Family)), format))), StringComparison.Ordinal); + } + + /// The obfuscation as LibreOffice undoes it: key bytes from the GUID's hex pairs, last pair first. + private static byte[] Deobfuscate(byte[] data, string key) + { + int[] positions = { 35, 33, 31, 29, 27, 25, 22, 20, 17, 15, 12, 10, 7, 5, 3, 1 }; + byte[] bytes = positions.Select(p => Convert.ToByte(key.Substring(p, 2), 16)).ToArray(); + byte[] result = (byte[])data.Clone(); + for (int i = 0; i < 16; i++) + { + result[i] ^= bytes[i]; + result[i + 16] ^= bytes[i]; + } + + return result; + } + + private static byte[] Entry(byte[] package, string name) + { + using ZipArchive archive = new ZipArchive(new MemoryStream(package), ZipArchiveMode.Read); + using Stream stream = archive.GetEntry(name)!.Open(); + using MemoryStream copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + private static List EntryNames(byte[] package) + { + using ZipArchive archive = new ZipArchive(new MemoryStream(package), ZipArchiveMode.Read); + return archive.Entries.Select(e => e.FullName).ToList(); + } + + private static string PdfFonts(byte[] pdf) + { + string? executable = new[] { "/opt/homebrew/bin/pdffonts", "/usr/local/bin/pdffonts", "/usr/bin/pdffonts" }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, "pdffonts (poppler) is not installed."); + string file = Path.Combine(Path.GetTempPath(), "templify-fonts-" + Guid.NewGuid().ToString("N") + ".pdf"); + File.WriteAllBytes(file, pdf); + try + { + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + start.ArgumentList.Add(file); + using Process process = Process.Start(start)!; + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + return output; + } + finally + { + File.Delete(file); + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/GeneratedPathTests.cs b/tests/TriasDev.Templify.Builder.Tests/GeneratedPathTests.cs new file mode 100644 index 00000000..861dfa06 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/GeneratedPathTests.cs @@ -0,0 +1,79 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Serialization; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +internal sealed record GeneratedData(GeneratedOrder Order); + +internal sealed record GeneratedOrder([property: JsonPropertyName("no")] string Number, IReadOnlyList Lines, GeneratedCustomer CustomerInfo, bool IsExpress); + +internal sealed record GeneratedLine(decimal UnitPrice, IReadOnlyList Parts); + +internal sealed record GeneratedCustomer(string FirstName); + +/// The generated typed paths (this project runs the generator): the same paths as the lambda API. +public sealed class GeneratedPathTests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + [Fact] + public void GeneratedPaths_AreTheLambdaPaths() + { + List<(string Generated, string Lambda)> pairs = new List<(string, string)>(); + BuilderHarness.Build(new TestDefinition(t => + { + TemplatePath data = t.DataAs(); + TemplatePath snake = t.DataAs(JsonNamingPolicy.SnakeCaseLower); + pairs.Add((data.Order.Number.ToString(), data.Path(d => d.Order.Number).ToString())); + pairs.Add((data.Order.CustomerInfo.FirstName.ToString(), data.Path(d => d.Order.CustomerInfo.FirstName).ToString())); + pairs.Add((snake.Order.CustomerInfo.FirstName.ToString(), snake.Path(d => d.Order.CustomerInfo.FirstName).ToString())); + pairs.Add((((TemplatePath)data.Order.Lines).ToString(), ((TemplatePath)data.Items(d => d.Order.Lines)).ToString())); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + + Assert.Equal( + new[] { "order.no", "order.customerInfo.firstName", "order.customer_info.first_name", "order.lines" }, + pairs.Select(p => p.Generated)); + Assert.All(pairs, p => Assert.Equal(p.Lambda, p.Generated)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void GeneratedLoops_BuildTheLambdaTemplate(TemplateFormat format) + { + TestDefinition generated = new TestDefinition(t => + { + TemplatePath order = t.DataAs().Order; + t.Content(c => + { + c.If(order.IsExpress, b => b.Paragraph(order.Number)); + c.ForEach(order.Lines, "line", (line, b) => + { + b.Paragraph(line.UnitPrice); + b.ForEach(line.Parts, "part", (part, inner) => inner.Paragraph(part.UnitPrice)); + }); + }); + }); + TestDefinition lambdas = new TestDefinition(t => + { + TemplatePath order = t.DataAs().Path(d => d.Order); + t.Content(c => + { + c.If(order.Path(o => o.IsExpress), b => b.Paragraph(order.Path(o => o.Number))); + c.ForEach(order.Items(o => o.Lines), "line", (line, b) => + { + b.Paragraph(line.Path(l => l.UnitPrice)); + b.ForEach(line.Items(l => l.Parts), "part", (part, inner) => inner.Paragraph(part.Path(p => p.UnitPrice))); + }); + }); + }); + + GeneratedTemplate template = BuilderHarness.Build(generated, format); + BuilderHarness.AssertInvariants(generated, template); + Assert.Equal(BuilderHarness.Build(lambdas, format).ContentHash, template.ContentHash); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/GeneratorTests.cs b/tests/TriasDev.Templify.Builder.Tests/GeneratorTests.cs new file mode 100644 index 00000000..5525abf6 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/GeneratorTests.cs @@ -0,0 +1,329 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using TriasDev.Templify.Builder.Generators; + +namespace TriasDev.Templify.Builder.Tests; + +/// The typed path source generator, run on client code through the Roslyn generator driver. +public sealed class GeneratorTests +{ + private const string Client = """ + using System.Collections.Generic; + using System.Text.Json.Serialization; + using TriasDev.Templify.Builder; + + namespace Client; + + public sealed record OrderData(Order Order); + + public class Base + { + public string Id { get; init; } = ""; + } + + public sealed class Order : Base + { + public string Number { get; init; } = ""; + public decimal? Discount { get; init; } + public Customer Customer { get; init; } = new(); + public List Lines { get; init; } = []; + public string[] Tags { get; init; } = []; + public Dictionary Extra { get; init; } = []; + [JsonIgnore] public string Secret { get; init; } = ""; + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Note { get; init; } + public string @class { get; init; } = ""; + public string Exists { get; init; } = ""; + public static string Shared { get; } = ""; + } + + public sealed class Customer + { + public string Name { get; init; } = ""; + public Customer? Parent { get; init; } + } + + public sealed class Line + { + public int Number { get; init; } + public decimal Quantity { get; init; } + } + + public sealed class Definition : ITemplateDefinition + { + public TemplateIdentity Identity { get; } = new("client", 1); + + public void Compose(TemplateComposer template) + { + TemplatePath order = template.DataAs().Order; + template.Content(c => + { + c.Paragraph(order.Number); + c.Paragraph(order.Customer.Parent.Name); + c.ForEach(order.Lines, "line", (line, body) => body.Paragraph(line.Quantity)); + c.If(order.Discount.Gt(0), b => b.Paragraph("discount")); + }); + _ = template.DataAs(); + } + + private sealed record Hidden(string Secret); + } + """; + + private static readonly MetadataReference[] _references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Append(typeof(TemplateComposer).Assembly.Location) + .Append(typeof(TriasDev.Templify.Core.TemplateFormat).Assembly.Location) + .DistinctBy(Path.GetFileName) + .Select(path => (MetadataReference)MetadataReference.CreateFromFile(path)) + .ToArray(); + + private static (string? Source, ImmutableArray Generator, ImmutableArray Compiler) Run(LanguageVersion language, params string[] sources) => + Run(language, optedIn: true, sources); + + private static (string? Source, ImmutableArray Generator, ImmutableArray Compiler) Run(LanguageVersion language, bool optedIn, params string[] sources) + { + CSharpParseOptions parse = new CSharpParseOptions(language); + CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable); + CSharpCompilation compilation = CSharpCompilation.Create( + "Client", + sources.Select(s => CSharpSyntaxTree.ParseText(s, parse)), + _references, + optedIn ? Consumer(options) : options); + GeneratorDriver driver = CSharpGeneratorDriver.Create([new TypedPathGenerator().AsSourceGenerator()], parseOptions: parse); + driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation output, out ImmutableArray generator, TestContext.Current.CancellationToken); + string? source = output.SyntaxTrees.FirstOrDefault(t => t.FilePath.EndsWith("TemplifyDataPaths.g.cs", StringComparison.Ordinal))?.ToString(); + return (source, generator, output.GetDiagnostics(TestContext.Current.CancellationToken)); + } + + private static string Block(string source, string receiver) + { + int start = source.IndexOf("extension(global::TriasDev.Templify.Builder." + receiver + " ", StringComparison.Ordinal); + Assert.True(start >= 0, "no block for " + receiver); + return source[start..source.IndexOf(" }", start, StringComparison.Ordinal)]; + } + + /// A consumer project that opted in to the experimental builder API (NoWarn TPLB001). + private static CSharpCompilationOptions Consumer(CSharpCompilationOptions options) => + options.WithSpecificDiagnosticOptions([new KeyValuePair("TPLB001", ReportDiagnostic.Suppress)]); + + [Fact] + public void Generates_PathsForEveryReachableType() + { + (string? source, _, _) = Run(LanguageVersion.CSharp14, Client); + + Assert.NotNull(source); + string order = Block(source, "TemplatePath"); + Assert.Contains("public global::TriasDev.Templify.Builder.TemplatePath Number => __templifyPath.Path(__x => __x.Number);", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath Discount", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath Customer", order, StringComparison.Ordinal); + Assert.Contains("public global::TriasDev.Templify.Builder.TemplateCollection Lines => __templifyPath.Items(__x => __x.Lines);", order, StringComparison.Ordinal); + Assert.Contains("TemplateCollection Tags", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath> Extra", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath Id", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath Note", order, StringComparison.Ordinal); + Assert.Contains("TemplatePath @class => __templifyPath.Path(__x => __x.@class);", order, StringComparison.Ordinal); + Assert.DoesNotContain("Secret", order, StringComparison.Ordinal); + Assert.DoesNotContain("Shared", order, StringComparison.Ordinal); + + Assert.Contains("TemplatePath Parent", Block(source, "TemplatePath"), StringComparison.Ordinal); + Assert.Contains("TemplatePath Order", Block(source, "TemplatePath"), StringComparison.Ordinal); + Assert.Contains("TemplatePath Number", Block(source, "TemplatePath"), StringComparison.Ordinal); + Assert.Contains("TemplatePath Quantity => __templifyItem.Path(__x => __x.Quantity);", Block(source, "LoopItem"), StringComparison.Ordinal); + Assert.DoesNotContain("Hidden", source, StringComparison.Ordinal); + } + + [Fact] + public void Collisions_AreSkippedWithTBG001() + { + (string? source, ImmutableArray generator, _) = Run(LanguageVersion.CSharp14, Client); + + // Loop metadata lives under line.Loop, so a data property Number is generated on the item (it was {{@number}}). + Assert.Contains(" Number ", Block(source!, "LoopItem"), StringComparison.Ordinal); + Assert.DoesNotContain(" Exists ", Block(source!, "TemplatePath"), StringComparison.Ordinal); + Assert.DoesNotContain("LoopItem", source!, StringComparison.Ordinal); + Assert.Equal( + new[] { "'Order.Exists' is not generated for TemplatePath" }, + generator.Where(d => d.Id == "TBG001").Select(d => d.GetMessage(System.Globalization.CultureInfo.InvariantCulture)[..d.GetMessage(System.Globalization.CultureInfo.InvariantCulture).IndexOf(':', StringComparison.Ordinal)]).Order(StringComparer.Ordinal)); + Assert.All(generator, d => Assert.Equal("TBG001", d.Id)); + // The location is the data property's declaration (a file location: generators keep no syntax trees between runs). + Assert.All(generator, d => Assert.True(d.Location.GetLineSpan().StartLinePosition.Line > 0)); + } + + [Fact] + public void GeneratedCode_ReportsNoTPLB001_WhenTheConsumerDidNotOptIn() + { + // The consumer's own use of the builder reports TPLB001 (experimental); the generated code does not add to it. + (_, _, ImmutableArray compiler) = Run(LanguageVersion.CSharp14, optedIn: false, Client); + + Assert.Contains(compiler, d => d.Id == "TPLB001"); + Assert.DoesNotContain(compiler, d => d.Id == "TPLB001" && d.Location.SourceTree?.FilePath.EndsWith("TemplifyDataPaths.g.cs", StringComparison.Ordinal) == true); + } + + [Fact] + public void GeneratedCode_CompilesWithoutAnyWarning() + { + (_, _, ImmutableArray compiler) = Run(LanguageVersion.CSharp14, Client); + + Assert.Empty(compiler.Where(d => d.Severity >= DiagnosticSeverity.Warning)); + } + + [Fact] + public void BelowCSharp14_IsTBG002_AndNothingIsGenerated() + { + (string? source, ImmutableArray generator, _) = Run(LanguageVersion.CSharp13, Client); + + Assert.Null(source); + Assert.Equal("TBG002", Assert.Single(generator).Id); + } + + [Fact] + public void AssemblyAttribute_AddsARoot() + { + (string? source, _, ImmutableArray compiler) = Run(LanguageVersion.CSharp14, """ + using TriasDev.Templify.Builder; + + [assembly: TemplateData(typeof(Lib.Address))] + + namespace Lib; + + public sealed record Address(string Street, string City); + + public static class Use + { + public static TriasDev.Templify.Builder.TemplatePath City(TriasDev.Templify.Builder.TemplatePath
address) => address.City; + } + """); + + Assert.Contains("TemplatePath Street", Block(source!, "TemplatePath"), StringComparison.Ordinal); + Assert.Empty(compiler.Where(d => d.Severity >= DiagnosticSeverity.Warning)); + } + + [Fact] + public void NoRoots_NoSource() + { + (string? source, ImmutableArray generator, _) = Run(LanguageVersion.CSharp14, "namespace Empty; public sealed class Nothing { }"); + + Assert.Null(source); + Assert.Empty(generator); + } + + // ── final review fixes ─────────────────────────────────────────────────── + + [Fact] + public void ProjectWithInternalsVisibleTo_DoesNotGenerateTwice() + { + const string app = """ + using System.Runtime.CompilerServices; + using TriasDev.Templify.Builder; + + [assembly: InternalsVisibleTo("Client")] + + namespace App; + + public sealed record Order(string Number, string Name); + + public static class AppUse + { + public static void Compose(TemplateComposer t) => t.Content(c => c.Paragraph(t.DataAs().Name)); + } + """; + CSharpParseOptions parse = new CSharpParseOptions(LanguageVersion.CSharp14); + CSharpCompilation appCompilation = CSharpCompilation.Create("App", [CSharpSyntaxTree.ParseText(app, parse, cancellationToken: TestContext.Current.CancellationToken)], _references, Consumer(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))); + CSharpGeneratorDriver.Create([new TypedPathGenerator().AsSourceGenerator()], parseOptions: parse) + .RunGeneratorsAndUpdateCompilation(appCompilation, out Compilation appOutput, out _, TestContext.Current.CancellationToken); + Assert.Empty(appOutput.GetDiagnostics(TestContext.Current.CancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error)); + + const string client = """ + using TriasDev.Templify.Builder; + + namespace Client; + + public static class ClientUse + { + public static TemplatePath Number(TemplateComposer t) => t.DataAs().Number; + } + """; + CSharpCompilation clientCompilation = CSharpCompilation.Create("Client", [CSharpSyntaxTree.ParseText(client, parse, cancellationToken: TestContext.Current.CancellationToken)], _references.Append(appOutput.ToMetadataReference()), Consumer(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))); + CSharpGeneratorDriver.Create([new TypedPathGenerator().AsSourceGenerator()], parseOptions: parse) + .RunGeneratorsAndUpdateCompilation(clientCompilation, out Compilation clientOutput, out _, TestContext.Current.CancellationToken); + + Assert.Empty(clientOutput.GetDiagnostics(TestContext.Current.CancellationToken).Where(d => d.Severity >= DiagnosticSeverity.Warning)); + } + + [Fact] + public void ShapesTheGeneratedCodeCannotHold_AreSkipped() + { + (string? source, _, ImmutableArray compiler) = Run(LanguageVersion.CSharp14, """ + using System; + using System.Collections.Generic; + using TriasDev.Templify.Builder; + + namespace Shapes; + + public interface IA { string Name { get; } } + public interface IB { string Name { get; } } + public interface IBoth : IA, IB { string Code { get; } } + + public sealed class Data + { + private int _value; + public ReadOnlyMemory Bytes { get; init; } + public ref int Ref => ref _value; + public IBoth Both { get; init; } = null!; + public Uri Link { get; init; } = null!; + public Exception Error { get; init; } = null!; + public List Versions { get; init; } = []; + public int? Maybe { get; init; } + public Money? Price { get; init; } + [Obsolete("Use Code.")] public string Old { get; init; } = ""; + public string Code { get; init; } = ""; + } + + public struct Money { public decimal Amount { get; init; } } + + file sealed class Local { public string Text { get; init; } = ""; } + + public static class Use + { + public static void Compose(TemplateComposer t) + { + TemplatePath data = t.DataAs(); + t.Content(c => c.Paragraph(data.Code)); + _ = t.DataAs(); + } + } + """); + + Assert.Empty(compiler.Where(d => d.Severity >= DiagnosticSeverity.Warning)); + Assert.DoesNotContain(" Ref ", source!, StringComparison.Ordinal); + Assert.DoesNotContain(" Span ", source!, StringComparison.Ordinal); + Assert.DoesNotContain("Local", source!, StringComparison.Ordinal); + Assert.Contains("TemplatePath Code", Block(source!, "TemplatePath"), StringComparison.Ordinal); + Assert.DoesNotContain(" Name ", Block(source!, "TemplatePath"), StringComparison.Ordinal); + Assert.Contains("TemplatePath Link", source!, StringComparison.Ordinal); + Assert.DoesNotContain("extension(global::TriasDev.Templify.Builder.TemplatePath generator, _) = Run(LanguageVersion.CSharp14, Client); + + Assert.NotEmpty(generator); + Assert.All(generator, d => Assert.Equal(DiagnosticSeverity.Warning, d.Severity)); + } + + [Fact] + public void Output_IsDeterministic() + { + Assert.Equal(Run(LanguageVersion.CSharp14, Client).Source, Run(LanguageVersion.CSharp14, Client).Source); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/IdentityTests.cs b/tests/TriasDev.Templify.Builder.Tests/IdentityTests.cs new file mode 100644 index 00000000..fb2e59e5 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/IdentityTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using DocumentFormat.OpenXml.CustomProperties; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.VariantTypes; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class IdentityTests +{ + private static readonly XNamespace _meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + internal static readonly TemplateIdentity InvoiceIdentity = new TemplateIdentity("invoice", 1); + + /// Version 1 of an invoice template. adds fields that version 2 dropped. + internal static TestDefinition Invoice(int version, bool withOldFields = false) => new TestDefinition( + template => + { + TemplatePath order = template.Data["order"]; + template.Content(c => + { + c.Paragraph(x => + { + x.Text("Invoice "); + x.Value(order["number"]); + }); + c.If(order["isPaid"], b => b.Paragraph("Paid")); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(x => + { + x.Value(line["description"]); + x.Text(": "); + x.Value(line["amount"]); + })); + if (version >= 2) + { + c.Paragraph(order["dueDate"]); + } + + if (withOldFields) + { + c.Paragraph(order["fax"]); + c.If(order["archived"], b => b.Paragraph("archived")); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(line["discount"])); + } + }); + }, + InvoiceIdentity with { Version = version }); + + [Theory] + [MemberData(nameof(Formats))] + public void Stamp_IsWrittenAndReadBack(TemplateFormat format) + { + GeneratedTemplate template = TemplateBuilder.Build(Invoice(2), BuilderHarness.Options(format, "de-DE")); + + TemplateInspection inspection = TemplateInspector.Inspect(template.OpenRead()); + + Assert.Equal(format, inspection.Format); + Assert.Equal(template.Stamp, inspection.Stamp); + Assert.Equal("invoice", template.Stamp.TemplateId); + Assert.Equal(2, template.Stamp.Version); + Assert.Equal(template.Contract.Hash, template.Stamp.ContractHash); + Assert.Equal("de-DE", template.Stamp.Language); + Assert.Matches(@"^\d+\.\d+\.\d+", template.Stamp.BuilderVersion); + Assert.DoesNotContain("+", template.Stamp.BuilderVersion, StringComparison.Ordinal); + Assert.Matches(@"^\d+\.\d+\.\d+", template.Stamp.MinimumEngineVersion); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Stamp_SurvivesFilling_AndCanBeRemoved(TemplateFormat format) + { + string json = """{ "order": { "number": "7", "isPaid": true, "lines": [ { "description": "Pen", "amount": 2 } ], "dueDate": "soon" } }"""; + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Invoice(2), format, json); + Assert.Equal(template.Stamp, TemplateInspector.Inspect(new MemoryStream(filled)).Stamp); + + byte[] withOther = AddOtherProperty(filled, format); + using MemoryStream document = new MemoryStream(); + document.Write(withOther); + + Assert.True(TemplateStampRemover.Remove(document)); + + byte[] cleaned = document.ToArray(); + Assert.Null(TemplateInspector.Inspect(new MemoryStream(cleaned)).Stamp); + Assert.Equal("kept", ReadOtherProperty(cleaned, format)); + BuilderHarness.AssertPackage(format, cleaned); + Assert.Equal(BuilderHarness.ParagraphTexts(format, filled), BuilderHarness.ParagraphTexts(format, cleaned)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Remover_WithoutStamp_ChangesNothing(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Invoice(1), format); + using MemoryStream document = new MemoryStream(); + template.WriteTo(document); + Assert.True(TemplateStampRemover.Remove(document)); + byte[] once = document.ToArray(); + + Assert.False(TemplateStampRemover.Remove(document)); + Assert.Equal(once, document.ToArray()); + } + + [Fact] + public void Remover_NeedsAWritableSeekableStream() + { + GeneratedTemplate template = BuilderHarness.Build(Invoice(1), TemplateFormat.Docx); + + Assert.Throws(() => TemplateStampRemover.Remove(template.OpenRead())); + } + + internal static string RemoveParagraphsContaining(string xml, TemplateFormat format, params string[] texts) + { + XDocument document = XDocument.Parse(xml); + XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + XNamespace text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + IEnumerable paragraphs = format == TemplateFormat.Docx ? document.Descendants(w + "p") : document.Descendants(text + "p"); + paragraphs.Where(p => texts.Contains(p.Value)).ToList().ForEach(p => p.Remove()); + return document.ToString(SaveOptions.DisableFormatting); + } + + private static byte[] AddOtherProperty(byte[] package, TemplateFormat format) + { + if (format == TemplateFormat.Odt) + { + return BuilderHarness.EditEntry(package, "meta.xml", xml => + { + XDocument meta = XDocument.Parse(xml); + meta.Root!.Element(_office + "meta")!.Add(new XElement(_meta + "user-defined", new XAttribute(_meta + "name", "Department"), "kept")); + return meta.ToString(SaveOptions.DisableFormatting); + }); + } + + using MemoryStream stream = new MemoryStream(); + stream.Write(package); + using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true)) + { + Properties properties = document.CustomFilePropertiesPart!.Properties!; + properties.Append(new CustomDocumentProperty(new VTLPWSTR("kept")) + { + FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", + PropertyId = 99, + Name = "Department", + }); + properties.Save(); + } + + return stream.ToArray(); + } + + private static string? ReadOtherProperty(byte[] package, TemplateFormat format) + { + if (format == TemplateFormat.Odt) + { + return BuilderHarness.ReadXml(package, "meta.xml").Descendants(_meta + "user-defined") + .SingleOrDefault(e => (string?)e.Attribute(_meta + "name") == "Department")?.Value; + } + + using MemoryStream stream = new MemoryStream(package); + using WordprocessingDocument document = WordprocessingDocument.Open(stream, false); + return document.CustomFilePropertiesPart?.Properties?.Elements() + .SingleOrDefault(p => p.Name?.Value == "Department")?.InnerText; + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ImageTests.cs b/tests/TriasDev.Templify.Builder.Tests/ImageTests.cs new file mode 100644 index 00000000..a37ae6cd --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ImageTests.cs @@ -0,0 +1,235 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.IO.Compression; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class ImageTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"; + private static readonly XNamespace _draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"; + private static readonly XNamespace _svg = "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"; + private static readonly XNamespace _xlink = "http://www.w3.org/1999/xlink"; + private static readonly XNamespace _manifest = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + /// 40 × 20 px PNG, no resolution (96 dpi). + internal static readonly byte[] Png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAIAAABwJOjsAAAAJElEQVR42mOQ96scEMQwavGoxaMWj1o8avGoxaMWj1o8ciwGAO6wzt9DGVp0AAAAAElFTkSuQmCC"); + + /// 40 × 20 px PNG at 192 dpi (pHYs). + private static readonly byte[] _hiDpiPng = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAIAAABwJOjsAAAACXBIWXMAAB2HAAAdhwGP5fFlAAAAJElEQVR42mM4ISc3IIhh1OJRi0ctHrV41OJRi0ctHrV45FgMAFLhLK5O4QWwAAAAAElFTkSuQmCC"); + + /// 40 × 20 px JPEG, JFIF without units (96 dpi). + private static readonly byte[] _jpeg = Convert.FromBase64String( + "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAKKADAAQAAAABAAAAFAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAFAAoAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICAwICAwUDAwMFBgUFBQUGCAYGBgYGCAoICAgICAgKCgoKCgoKCgwMDAwMDA4ODg4ODw8PDw8PDw8PD//bAEMBAgICBAQEBwQEBxALCQsQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEP/dAAQAA//aAAwDAQACEQMRAD8A+E6KKK/dD8TCiiigAooooA//0PhOiiiv3Q/EwooooAKKKKAP/9k="); + + [Fact] + public void ImageSource_ReadsSizeAndResolution() + { + ImageSource png = ImageSource.Png(Png); + Assert.Equal((40, 20), (png.PixelWidth, png.PixelHeight)); + Assert.Equal((30.Pt(), 15.Pt()), (png.NaturalWidth, png.NaturalHeight)); + + ImageSource hiDpi = ImageSource.FromBytes(_hiDpiPng); + Assert.Equal(15, hiDpi.NaturalWidth.Points, 2); + + ImageSource jpeg = ImageSource.Jpeg(_jpeg); + Assert.Equal((40, 20), (jpeg.PixelWidth, jpeg.PixelHeight)); + Assert.Equal(30.Pt(), jpeg.NaturalWidth); + Assert.Equal(20, ImageSource.FromBytes(_jpeg).PixelHeight); + + Assert.Throws(() => ImageSource.Png(_jpeg)); + Assert.Throws(() => ImageSource.Jpeg(Png)); + Assert.Throws(() => ImageSource.FromBytes(new byte[] { 1, 2, 3, 4, 5 })); + } + + [Fact] + public void ImageFit_KeepsTheAspectRatio() + { + ImageSource png = ImageSource.Png(Png); + Assert.Equal((60.Pt(), 30.Pt()), ImageFit.Width(60.Pt()).Resolve(png)); + Assert.Equal((20.Pt(), 10.Pt()), ImageFit.Height(10.Pt()).Resolve(png)); + Assert.Equal((40.Pt(), 20.Pt()), ImageFit.Within(100.Pt(), 20.Pt()).Resolve(png)); + Assert.Equal((20.Pt(), 10.Pt()), ImageFit.Within(20.Pt(), 100.Pt()).Resolve(png)); + Assert.Equal((30.Pt(), 15.Pt()), ImageFit.Natural.Resolve(png)); + } + + private static TestDefinition Document() => new TestDefinition(t => + { + ImageSource logo = ImageSource.Png(Png); + ImageSource photo = ImageSource.Jpeg(_jpeg); + t.Page(p => p.Header(h => h.Paragraph(x => + { + x.Text("Company"); + x.TabRight(); + x.Image(logo, "Company logo", ImageFit.Within(30.Mm(), 10.Mm())); + }))); + t.Content(c => + { + c.Paragraph(x => + { + x.Text("Signed "); + x.Image(logo, "Signature", ImageFit.Height(12.Pt())); + x.Text(" by "); + x.Value(t.Data["signer"]); + }); + c.Image(photo, "Product photo", ImageFit.Width(80.Mm())); + c.Table(tb => + { + tb.Columns(cols => + { + cols.Fixed(20.Mm()); + cols.Relative(1); + }); + tb.ForEachRow(t.Data["items"], "item", (item, rows) => rows.Row(r => + { + r.Cell(cell => cell.Image(logo, "Item icon", ImageFit.Height(10.Pt()))); + r.Cell(item["name"]); + })); + }); + }); + }); + + private const string Json = """{ "signer": "Alice", "items": [ { "name": "one" }, { "name": "two" }, { "name": "three" } ] }"""; + + [Fact] + public void Docx_StoresEachImageOnce_WithPerPartRelationships() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Document(), TemplateFormat.Docx, Json); + byte[] package = template.Content.ToArray(); + + Assert.Equal(new[] { "word/media/image1.png", "word/media/image2.jpeg" }, Entries(package).Where(e => e.StartsWith("word/media/", StringComparison.Ordinal))); + string contentTypes = Entry(package, "[Content_Types].xml"); + Assert.Contains("Extension=\"png\" ContentType=\"image/png\"", contentTypes, StringComparison.Ordinal); + Assert.Contains("Extension=\"jpeg\" ContentType=\"image/jpeg\"", contentTypes, StringComparison.Ordinal); + Assert.Contains("Target=\"media/image1.png\"", Entry(package, "word/_rels/header1.xml.rels"), StringComparison.Ordinal); + Assert.Contains("Target=\"media/image2.jpeg\"", Entry(package, "word/_rels/document.xml.rels"), StringComparison.Ordinal); + + List docPr = BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_wp + "docPr").ToList(); + Assert.Equal(new[] { "Signature", "Product photo", "Item icon" }, docPr.Select(d => d.Attribute("descr")!.Value)); + XElement headerDocPr = BuilderHarness.ReadXml(package, "word/header1.xml").Descendants(_wp + "docPr").Single(); + Assert.Equal(4, docPr.Select(d => d.Attribute("id")!.Value).Append(headerDocPr.Attribute("id")!.Value).Distinct().Count()); + + // 80 mm wide photo: 226.772 pt → 2 880 000 EMU; height half. + XElement extent = BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_wp + "extent").ElementAt(1); + Assert.Equal("2880004", extent.Attribute("cx")!.Value); + + // The engine cloned the row's image three times with unique ids (schema validation ran in the harness). + List filledIds = BuilderHarness.ReadXml(filled, "word/document.xml").Descendants(_wp + "docPr").Select(d => d.Attribute("id")!.Value).ToList(); + Assert.Equal(5, filledIds.Count); + Assert.Equal(filledIds.Count, filledIds.Distinct().Count()); + } + + [Fact] + public void Odt_StoresPicturesWithManifestEntries_AndFramesWithAltText() + { + (GeneratedTemplate template, _) = BuilderHarness.BuildAndFill(Document(), TemplateFormat.Odt, Json); + byte[] package = template.Content.ToArray(); + + List pictures = Entries(package).Where(e => e.StartsWith("Pictures/", StringComparison.Ordinal)).ToList(); + Assert.Equal(2, pictures.Count); + XDocument manifest = BuilderHarness.ReadXml(package, "META-INF/manifest.xml"); + Assert.All(pictures, p => Assert.Contains(manifest.Descendants(_manifest + "file-entry"), e => (string?)e.Attribute(_manifest + "full-path") == p)); + + List frames = BuilderHarness.ReadXml(package, "content.xml").Descendants(_draw + "frame").ToList(); + Assert.Equal(new[] { "Signature", "Product photo", "Item icon" }, frames.Select(f => f.Element(_svg + "title")!.Value)); + Assert.Equal(new[] { "TemplifyImage1", "TemplifyImage2", "TemplifyImage3" }, frames.Select(f => f.Attribute(_draw + "name")!.Value)); + Assert.Equal("226.772pt", frames[1].Attribute(_svg + "width")!.Value); + Assert.Equal(frames[0].Element(_draw + "image")!.Attribute(_xlink + "href")!.Value, frames[2].Element(_draw + "image")!.Attribute(_xlink + "href")!.Value); + + XElement logo = BuilderHarness.ReadXml(package, "styles.xml").Descendants(_draw + "frame").Single(); + Assert.Equal("TemplifyHfImage1", logo.Attribute(_draw + "name")!.Value); + Assert.Equal("Company logo", logo.Element(_svg + "desc")!.Value); + } + + [Fact] + public void AltText_IsRequired() + { + ImageSource png = ImageSource.Png(Png); + + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Image(png, " "))), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(x => x.Image(png, string.Empty)))), TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersEveryImage(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Document(), format, Json); + byte[] pdf = LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "pdf", "pdf"); + + // Header logo, signature, photo and three row icons. + Assert.Equal(6, PdfImageCount(pdf)); + } + + private static int PdfImageCount(byte[] pdf) + { + string? executable = new[] { "/opt/homebrew/bin/pdfimages", "/usr/local/bin/pdfimages", "/usr/bin/pdfimages" }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, "pdfimages (poppler) is not installed."); + string file = Path.Combine(Path.GetTempPath(), "templify-images-" + Guid.NewGuid().ToString("N") + ".pdf"); + File.WriteAllBytes(file, pdf); + try + { + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + start.ArgumentList.Add("-list"); + start.ArgumentList.Add(file); + using Process process = Process.Start(start)!; + string[] lines = process.StandardOutput.ReadToEnd().Split('\n', StringSplitOptions.RemoveEmptyEntries); + process.WaitForExit(); + + // Two header lines; one line per image ("smask" lines are the alpha channel of the image before them). + return lines.Skip(2).Count(l => !l.Contains(" smask ", StringComparison.Ordinal)); + } + finally + { + File.Delete(file); + } + } + + private static List Entries(byte[] package) + { + using ZipArchive archive = new ZipArchive(new MemoryStream(package), ZipArchiveMode.Read); + return archive.Entries.Select(e => e.FullName).ToList(); + } + + private static string Entry(byte[] package, string name) + { + using ZipArchive archive = new ZipArchive(new MemoryStream(package), ZipArchiveMode.Read); + using StreamReader reader = new StreamReader(archive.GetEntry(name)!.Open()); + return reader.ReadToEnd(); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Exact_DrawsAtThatSize(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Image(ImageSource.Png(Png), "a", ImageFit.Exact(30.Pt(), 10.Pt())))); + + GeneratedTemplate template = BuilderHarness.Build(definition, format); + + string xml = BuilderHarness.ReadXml(template.Content.ToArray(), BuilderHarness.MainPart(format)).ToString(System.Xml.Linq.SaveOptions.DisableFormatting); + if (format == TemplateFormat.Docx) + { + Assert.Contains("cx=\"381000\" cy=\"127000\"", xml, StringComparison.Ordinal); + } + else + { + Assert.Contains("svg:width=\"30pt\"", xml.Replace("xmlns:svg", "x", StringComparison.Ordinal), StringComparison.Ordinal); + } + } + + [Fact] + public void Exact_RequiresPositiveSizes() + { + Assert.Throws(() => ImageFit.Exact(0.Pt(), 1.Pt())); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/IndexedPathTests.cs b/tests/TriasDev.Templify.Builder.Tests/IndexedPathTests.cs new file mode 100644 index 00000000..0437aa7a --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/IndexedPathTests.cs @@ -0,0 +1,202 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Indexed path segments, items[0] (#290). +public sealed class IndexedPathTests +{ + private const string Data = """ + { + "order": { + "items": [ { "name": "first", "ok": false, "parts": [ { "name": "p0" } ] }, { "name": "second", "ok": true, "parts": [ { "name": "q0" }, { "name": "q1" } ] } ], + "lines": [ { "parts": [ { "name": "a" }, { "name": "b" } ] } ] + } + } + """; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private sealed record Part(string Name); + + private sealed record Item(string Name, bool Ok, List Parts); + + private sealed record Order(List Items, Item[] Array); + + private sealed record Root(Order Order); + + [Theory] + [MemberData(nameof(Formats))] + public void StringPaths_ReadTheItemAtTheIndex(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.Paragraph(x => + { + x.Text("1: "); + x.Value(order["items[1].name"]); + x.Text(", 0: "); + x.Value(order["items[0]"]["name"]); + }); + c.If(order["items[1].ok"], b => b.Paragraph("second ok")); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(x => x.Value(line["parts[1].name"]))); + }); + }); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, Data); + + Assert.Equal(new[] { "1: second, 0: first", "second ok", "b" }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Contains(new ContractEntry("order.items[1].name", ContractUsage.Value), template.Contract.Entries); + Assert.Contains(new ContractEntry("order.lines[].parts[1].name", ContractUsage.Value), template.Contract.Entries); + } + + [Fact] + public void TypedPaths_MapAConstantIndex() + { + List paths = new List(); + BuilderHarness.Build(new TestDefinition(t => + { + TemplatePath root = t.DataAs(); + paths.Add(root.Path(r => r.Order.Items[1].Name).ToString()); + paths.Add(root.Path(r => r.Order.Array[2].Parts[0].Name).ToString()); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + + Assert.Equal(new[] { "order.items[1].name", "order.array[2].parts[0].name" }, paths); + } + + [Fact] + public void TypedPaths_RejectAComputedIndex() + { + int index = 1; + TemplatePath root = default; + ArgumentException exception = Assert.Throws(() => root.Path(r => r.Order.Items[index].Name)); + Assert.Contains("constant", exception.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("items[1000]")] + [InlineData("items[x]")] + [InlineData("items[0][1]")] + [InlineData("items[-1]")] + [InlineData("[0]")] + public void InvalidIndexes_AreRejected(string path) + { + Assert.Throws(() => TemplatePath.Root(path)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_TextAndConditionsUseIndexes(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(""" + { + "templifyDefinition": 1, + "identity": { "id": "indexed", "version": 1 }, + "content": [ + "{{order.items[1].name}} / {{order.items[0].parts[0].name}}", + { "if": "order.items[1].ok and not order.items[0].ok", "then": [ "conditions read indexes" ] } + ] + } + """); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, Data); + + Assert.Equal(new[] { "second / p0", "conditions read indexes" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Witness_SatisfiesLoopsAndIndexesOnOneCollection(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.ForEach(order["items"], "item", (item, b) => b.Paragraph(x => x.Value(item["name"]))); + c.Paragraph(x => x.Value(order["items[2].parts[1].name"])); + }); + }); + GeneratedTemplate built = BuilderHarness.Build(definition, format); + + using (Stream stream = built.OpenRead()) + { + ValidationResult validation = new TemplateProcessor().ValidateTemplate(stream, built.Contract.CreateWitness()); + Assert.Empty(validation.MissingVariables); + } + + BuilderHarness.BuildAndFill(definition, format, built.Contract.CreateWitness()); + } + + [Fact] + public void LoopOverAnIndexedPath_IsRejected() + { + // Templify's loop markers take a path of letters, digits, '_' and '.': {{#foreach l in groups[1].lines}} would stay text. + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["groups[1].lines"], "l", (l, b) => b.Paragraph(l["name"])))), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => + c.ForEach(t.DataAs().Items(r => r.Order.Items[0].Parts), "p", (p, b) => b.Paragraph(p.Path(x => x.Name))))), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.ForEachRow(t.Data["matrix[1]"], "cell", (cell, rows) => rows.Row(r => r.Cell(cell.Self))); + }))), TemplateFormat.Docx)); + + ITemplateDefinition imported = TemplateJson.Import(""" + { "templifyDefinition": 1, "identity": { "id": "c", "version": 1 }, "content": [ { "forEach": "order.items[0].parts", "as": "p", "body": [ "{{p.name}}" ] } ] } + """); + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build(imported, TemplateFormat.Docx)).Errors); + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/0", error.Location); + } + + [Fact] + public void NonAsciiDigits_AreNotAnIndex() + { + Assert.Throws(() => TemplatePath.Root("items[\u0663].name")); + } + + [Theory] + [MemberData(nameof(Formats))] + public void IndexInsideNestedLoops(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["order.groups"], "g", (g, outer) => + outer.ForEach(g["lines"], "line", (line, inner) => inner.Paragraph(x => + { + x.Value(line["parts[1].name"]); + x.Text("/"); + x.Value(g["lines[0].parts[0].name"]); + }))))); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """ + { "order": { "groups": [ { "lines": [ { "parts": [ { "name": "a0" }, { "name": "a1" } ] }, { "parts": [ { "name": "b0" }, { "name": "b1" } ] } ] } ] } } + """); + + Assert.Equal(new[] { "a1/a0", "b1/a0" }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Contains(new ContractEntry("order.groups[].lines[].parts[1].name", ContractUsage.Value), template.Contract.Entries); + Assert.Contains(new ContractEntry("order.groups[].lines[0].parts[0].name", ContractUsage.Value), template.Contract.Entries); + BuilderHarness.BuildAndFill(definition, format, template.Contract.CreateWitness()); + } + + [Fact] + public void Catalogue_AcceptsIndexedPaths() + { + TemplateJsonImportOptions options = new TemplateJsonImportOptions { Data = DataCatalog.From() }; + + TemplateJson.Import(""" + { "templifyDefinition": 1, "identity": { "id": "c", "version": 1 }, "content": [ "{{order.items[0].name}}", "{{order.array[1].parts[0].name}}" ] } + """, options); + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(""" + { "templifyDefinition": 1, "identity": { "id": "c", "version": 1 }, "content": [ "{{order.items[0].nmae}}" ] } + """, options)); + Assert.Equal("TB9203", Assert.Single(exception.Errors).Code); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/InlineConditionalTests.cs b/tests/TriasDev.Templify.Builder.Tests/InlineConditionalTests.cs new file mode 100644 index 00000000..fd4cf572 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/InlineConditionalTests.cs @@ -0,0 +1,156 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class InlineConditionalTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly CharacterStyleKey _strong = new CharacterStyleKey("Strong", "Strong Text"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Letter() => new TestDefinition(t => + { + TemplatePath a = t.Data["address"]; + TemplatePath order = t.Data["order"]; + t.Styles(StyleSheet.Create(s => s.Character(_strong, c => c.Bold()))); + t.Content(c => + { + // The separator sits inside the guard of the piece it precedes. + c.Paragraph(x => + { + x.Value(a["street"]); + x.If(a["postalCode"], y => y.Text(", ").Value(a["postalCode"])); + x.If(a["city"], y => y.Text(" ").Value(a["city"])); + }); + c.Paragraph(x => + { + x.Text("Status: "); + x.If(order["status"].Eq("paid"), y => y.Text(_strong, "paid")) + .ElseIf(order["status"].Eq("overdue"), y => y.Text("overdue").If(order["reminded"], z => z.Text(" (reminded)"))) + .Else(y => y.Text("open")); + }); + c.Paragraph(x => + { + x.Text("Paid and positive: "); + x.Expression(order["isPaid"] & order["total"].Gt(0), ValueFormat.YesNo); + x.Text(" "); + x.Expression(order["isPaid"], ValueFormat.Checkbox); + }); + c.Paragraph(x => x.If(order["note"], y => y.Value(order["note"]))); + c.Paragraph("end"); + }); + }); + + public static TheoryData Cases => new TheoryData + { + { + TemplateFormat.Docx, + """{ "address": { "street": "Main St 1", "postalCode": "80331", "city": "Munich" }, "order": { "status": "paid", "reminded": false, "isPaid": true, "total": 10, "note": "fragile" } }""", + ["Main St 1, 80331 Munich", "Status: paid", "Paid and positive: Yes ☑", "fragile", "end"] + }, + { + TemplateFormat.Odt, + """{ "address": { "street": "Main St 1", "postalCode": "", "city": "Munich" }, "order": { "status": "overdue", "reminded": true, "isPaid": false, "total": 10, "note": "" } }""", + ["Main St 1 Munich", "Status: overdue (reminded)", "Paid and positive: No ☐", "", "end"] + }, + { + TemplateFormat.Docx, + """{ "address": { "street": "Main St 1", "postalCode": "", "city": "" }, "order": { "status": "draft", "reminded": false, "isPaid": "x", "total": 0, "note": "" } }""", + ["Main St 1", "Status: open", "Paid and positive: No ☐", "", "end"] + }, + { + TemplateFormat.Odt, + """{ "address": { "street": "Main St 1", "postalCode": "80331", "city": "" }, "order": { "status": "overdue", "reminded": false, "isPaid": true, "total": 5, "note": "x" } }""", + ["Main St 1, 80331", "Status: overdue", "Paid and positive: Yes ☑", "x", "end"] + }, + }; + + [Theory] + [MemberData(nameof(Cases))] + public void InlineConditionalsAndExpressions_AreResolvedInsideTheParagraph(TemplateFormat format, string json, string[] expected) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), format, json); + + Assert.Equal(expected, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Template_HoldsTheMarkersInsideTheParagraphs(TemplateFormat format) + { + List texts = BuilderHarness.ParagraphTexts(format, BuilderHarness.Build(Letter(), format).Content.ToArray()); + + Assert.Equal("{{address.street}}{{#if address.postalCode}}, {{address.postalCode}}{{/if}}{{#if address.city}} {{address.city}}{{/if}}", texts[0]); + Assert.Equal("Status: {{#if order.status = \"paid\"}}paid{{#elseif order.status = \"overdue\"}}overdue{{#if order.reminded}} (reminded){{/if}}{{#else}}open{{/if}}", texts[1]); + Assert.Equal("Paid and positive: {{(order.isPaid and order.total > 0):yesno}} {{(order.isPaid):checkbox}}", texts[2]); + } + + [Fact] + public void StyledTextInABranch_KeepsItsStyle() + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), TemplateFormat.Docx, + """{ "address": { "street": "S", "postalCode": "", "city": "" }, "order": { "status": "paid", "reminded": false, "isPaid": true, "total": 1, "note": "" } }"""); + + XElement paid = BuilderHarness.ReadXml(filled, "word/document.xml").Descendants(_w + "r").Single(r => r.Value == "paid"); + Assert.Equal("Strong", paid.Element(_w + "rPr")!.Element(_w + "rStyle")!.Attribute(_w + "val")!.Value); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Contract_IncludesConditionAndExpressionPaths(TemplateFormat format) + { + Assert.Equal( + new[] + { + "address.city (Value)", "address.city (Condition)", "address.postalCode (Value)", "address.postalCode (Condition)", + "address.street (Value)", "order.isPaid (Condition)", "order.note (Value)", "order.note (Condition)", + "order.reminded (Condition)", "order.status (Condition)", "order.total (Condition)", + }, + BuilderHarness.Build(Letter(), format).Contract.Entries.Select(e => $"{e.Path} ({e.Usage})")); + } + + [Fact] + public void Errors_AreReported() + { + Assert.Throws(() => BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Paragraph(x => x.If(t.Data["a"], y => y.Text("tab\there"))))), TemplateFormat.Docx)); + + TemplateBuildException braces = Assert.Throws(() => BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Paragraph(x => x.If(t.Data["a"], y => y.Text("{{oops"))))), TemplateFormat.Docx)); + Assert.Equal("TB1002", Assert.Single(braces.Errors).Code); + + InlineIfChain? kept = null; + BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(x => kept = x.If(t.Data["a"], y => y.Text("a"))))), TemplateFormat.Docx); + Assert.Throws(() => kept!.Else(y => y.Text("late"))); + + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + InlineIfChain chain = x.If(t.Data["a"], y => y.Text("a")); + chain.Else(y => y.Text("b")); + chain.ElseIf(t.Data["c"], y => y.Text("c")); + }))), TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ShowsTheResolvedText(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), format, + """{ "address": { "street": "Main St 1", "postalCode": "80331", "city": "Munich" }, "order": { "status": "overdue", "reminded": true, "isPaid": true, "total": 10, "note": "" } }"""); + + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + + Assert.Contains("Main St 1, 80331 Munich", text, StringComparison.Ordinal); + Assert.Contains("Status: overdue (reminded)", text, StringComparison.Ordinal); + Assert.Contains("Paid and positive: Yes ☑", text, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/InlineContentTests.cs b/tests/TriasDev.Templify.Builder.Tests/InlineContentTests.cs new file mode 100644 index 00000000..56db8c48 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/InlineContentTests.cs @@ -0,0 +1,337 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed partial class InlineContentTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + private static readonly CharacterStyleKey _strong = new CharacterStyleKey("Strong", "Strong Text"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly (string Name, ValueFormat Format, string Path)[] _formats = + { + ("date", ValueFormat.Date("yyyy-MM-dd"), "date"), + ("date with spaces and colon", ValueFormat.Date("MMMM d, yyyy HH:mm"), "date"), + ("number", ValueFormat.Number("N2"), "amount"), + ("currency", ValueFormat.Currency, "amount"), + ("uppercase", ValueFormat.Uppercase, "name"), + ("lowercase", ValueFormat.Lowercase, "name"), + ("raw", ValueFormat.Raw, "markdown"), + ("yesno", ValueFormat.YesNo, "flag"), + ("truefalse", ValueFormat.TrueFalse, "flag"), + ("onoff", ValueFormat.OnOff, "flag"), + ("enabled", ValueFormat.Enabled, "flag"), + ("active", ValueFormat.Active, "flag"), + ("checkbox", ValueFormat.Checkbox, "flag"), + ("checkmark", ValueFormat.Checkmark, "flag"), + ("join", ValueFormat.Join(), "tags"), + ("join with separator", ValueFormat.Join(separator: " | "), "tags"), + ("join item path", ValueFormat.Join("owner.name"), "assets"), + ("join item path and quoted separator", ValueFormat.Join("owner.name", "\"; \\"), "assets"), + ("join without separator", ValueFormat.Join(separator: ""), "tags"), + ("custom", ValueFormat.Custom("yesno"), "flag"), + }; + + private static Dictionary FormatData() => new Dictionary + { + ["date"] = new DateTime(2026, 11, 25, 14, 30, 0), + ["amount"] = 1234.5m, + ["name"] = "Alice Example", + ["markdown"] = "**not bold**", + ["flag"] = true, + ["tags"] = new List { "alpha", null, "", "beta" }, + ["assets"] = new List + { + new Dictionary { ["owner"] = new Dictionary { ["name"] = "Ann" } }, + new Dictionary { ["owner"] = new Dictionary { ["name"] = "Bob" } }, + }, + }; + + [Theory] + [MemberData(nameof(Formats))] + public void ValueFormats_RenderAsTheEngineDefinesThem(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + foreach ((string _, ValueFormat valueFormat, string path) in _formats) + { + c.Paragraph(x => x.Value(template.Data[path], valueFormat)); + } + })); + + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, FormatData()); + + TextTemplateProcessor oracle = new TextTemplateProcessor(BuilderHarness.FillOptions); + List expected = _formats + .Select(f => oracle.ProcessTemplate($"{{{{{f.Path}:{f.Format.Specifier}}}}}", FormatData()).ProcessedText) + .ToList(); + List actual = BuilderHarness.ParagraphTexts(format, filled); + + Assert.Equal(_formats.Select(f => $"{{{{{f.Path}:{f.Format.Specifier}}}}}"), BuilderHarness.ParagraphTexts(format, built.Content.ToArray())); + for (int i = 0; i < _formats.Length; i++) + { + Assert.True(expected[i] == actual[i], $"{_formats[i].Name}: expected '{expected[i]}', got '{actual[i]}'"); + } + + // Spot checks, so the oracle cannot drift silently. + Assert.Equal("2026-11-25", actual[0]); + Assert.Equal("1,234.50", actual[2]); + Assert.Equal("ALICE EXAMPLE", actual[4]); + Assert.Equal("**not bold**", actual[6]); + Assert.Equal("☑", actual[12]); + Assert.Equal("alpha, beta", actual[14]); + Assert.Equal("alpha | beta", actual[15]); + Assert.Equal("Ann, Bob", actual[16]); + Assert.Equal("Ann\"; \\Bob", actual[17]); + Assert.Equal("alphabeta", actual[18]); + } + + [Fact] + public void ValueFormat_Specifiers() + { + Assert.Equal("date:yyyy-MM-dd", ValueFormat.Date("yyyy-MM-dd").Specifier); + Assert.Equal("number:N2", ValueFormat.Number("N2").ToString()); + Assert.Equal("join", ValueFormat.Join().Specifier); + Assert.Equal("join:owner.name", ValueFormat.Join("owner.name").Specifier); + Assert.Equal("join:\"; \"", ValueFormat.Join(separator: "; ").Specifier); + Assert.Equal("join:a:\"\\\"\"", ValueFormat.Join("a", "\"").Specifier); + Assert.Equal("mine:arg", ValueFormat.Custom("mine:arg").Specifier); + } + + [Theory] + [InlineData("")] + [InlineData("a}b")] + [InlineData("a{{b")] + [InlineData("tab\there")] + public void ValueFormat_InvalidPattern_Throws(string pattern) + { + Assert.Throws(() => ValueFormat.Date(pattern)); + Assert.Throws(() => ValueFormat.Number(pattern)); + } + + [Fact] + public void ValueFormat_InvalidJoinOrCustom_Throws() + { + Assert.Throws(() => ValueFormat.Join("owner name")); + Assert.Throws(() => ValueFormat.Join("owner.")); + Assert.Throws(() => ValueFormat.Join("items[0]")); + Assert.Throws(() => ValueFormat.Join(separator: "a}")); + Assert.Throws(() => ValueFormat.Join(separator: "\u201C")); + Assert.Throws(() => ValueFormat.Custom("")); + Assert.Throws(() => ValueFormat.Custom("my-format")); + Assert.Throws(() => ValueFormat.Custom("mine:a}")); + } + + private static TestDefinition StyledText() => new TestDefinition(template => + { + template.Styles(StyleSheet.Create(s => s.Character(_strong, c => c.Bold()))); + TemplatePath customer = template.Data["customer"]; + template.Content(c => c.Paragraph(x => + { + x.Text("Dear "); + x.Value(_strong, customer["name"]); + x.Text(", total "); + x.Value(_strong, customer["total"], ValueFormat.Number("F2")); + x.Text(_strong, " ok "); + x.Tab(); + x.Text("end"); + x.LineBreak(); + x.Text("next line "); + })); + }); + + private const string CustomerJson = """{ "customer": { "name": "Alice", "total": 12.5 } }"""; + + [Fact] + public void CharacterStyles_Docx_AreRunStylesAndSurviveFilling() + { + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(StyledText(), TemplateFormat.Docx, CustomerJson); + + Assert.Equal(new[] { "Dear Alice, total 12.50 ok \tend\nnext line " }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)); + + List runs = BuilderHarness.ReadXml(built.Content.ToArray(), "word/document.xml").Descendants(_w + "r").ToList(); + Assert.Equal( + new string?[] { null, "Strong", null, "Strong", "Strong", null, null, null, null }, + runs.Select(r => (string?)r.Element(_w + "rPr")?.Element(_w + "rStyle")?.Attribute(_w + "val"))); + + List filledRuns = BuilderHarness.ReadXml(filled, "word/document.xml").Descendants(_w + "r").ToList(); + XElement alice = filledRuns.Single(r => r.Value == "Alice"); + Assert.Equal("Strong", alice.Element(_w + "rPr")!.Element(_w + "rStyle")!.Attribute(_w + "val")!.Value); + } + + [Fact] + public void CharacterStyles_Odt_AreSpansAndSurviveFilling() + { + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(StyledText(), TemplateFormat.Odt, CustomerJson); + + Assert.Equal(new[] { "Dear Alice, total 12.50 ok \tend\nnext line " }, BuilderHarness.ParagraphTexts(TemplateFormat.Odt, filled)); + + XElement paragraph = BuilderHarness.ReadXml(built.Content.ToArray(), "content.xml").Descendants(_text + "p").Single(); + List spans = paragraph.Elements(_text + "span").ToList(); + Assert.Equal(new[] { "Strong", "Strong", "Strong" }, spans.Select(s => (string?)s.Attribute(_text + "style-name"))); + + XElement filledParagraph = BuilderHarness.ReadXml(filled, "content.xml").Descendants(_text + "p").Single(); + Assert.Contains(filledParagraph.Elements(_text + "span"), s => s.Value == "Alice" && (string?)s.Attribute(_text + "style-name") == "Strong"); + } + + [Fact] + public void CharacterStyle_NotDefined_IsAnError() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph(x => x.Text(_strong, "x")))); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + + Assert.Equal("TB2010", Assert.Single(exception.Errors).Code); + Assert.Contains("character style 'Strong'", exception.Errors[0].Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("a {{ b")] + [InlineData("{{name}}")] + public void LiteralText_WithOpenBraces_IsAnError(string text) + { + TestDefinition asParagraph = new TestDefinition(template => template.Content(c => c.Paragraph(text))); + TestDefinition asInline = new TestDefinition(template => template.Content(c => c.Paragraph(x => x.Text(text)))); + + foreach (TestDefinition definition in new[] { asParagraph, asInline }) + { + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + Assert.Equal("TB1002", Assert.Single(exception.Errors).Code); + } + } + + [Fact] + public void LiteralText_OpenBracesAcrossPieces_IsAnError() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph(x => + { + x.Text("a {"); + x.Text(_strong, "{ b"); + }))); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Contains(exception.Errors, e => e.Code == "TB1002"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void LiteralText_SingleBracesAndClosingBraces_AreFine(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + c.Paragraph("a { b } c }} d"); + c.Paragraph(x => + { + x.Text("{"); + x.Value(template.Data["v"]); + x.Text("}"); + }); + })); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "v": "x" }"""); + + Assert.Equal(new[] { "a { b } c }} d", "{x}" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void ReservedStylePrefix_Throws() + { + Assert.Throws(() => new ParagraphStyleKey("TemplifyPageBreak", "Mine")); + Assert.Throws(() => new CharacterStyleKey("templifyAnything", "Mine")); + } + + private static TestDefinition TwoPages() => new TestDefinition(template => template.Content(c => + { + c.Paragraph("first page"); + c.PageBreak(); + c.Paragraph(template.Data["v"]); + })); + + [Theory] + [MemberData(nameof(Formats))] + public void PageBreak_IsAParagraphOfItsOwn(TemplateFormat format) + { + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(TwoPages(), format, """{ "v": "second page" }"""); + byte[] template = built.Content.ToArray(); + + if (format == TemplateFormat.Docx) + { + List paragraphs = BuilderHarness.ReadXml(template, "word/document.xml").Descendants(_w + "p").ToList(); + Assert.Equal(3, paragraphs.Count); + Assert.Equal("page", paragraphs[1].Descendants(_w + "br").Single().Attribute(_w + "type")!.Value); + } + else + { + XDocument content = BuilderHarness.ReadXml(template, "content.xml"); + List paragraphs = content.Descendants(_text + "p").ToList(); + Assert.Equal(3, paragraphs.Count); + Assert.Equal("TemplifyPageBreak", paragraphs[1].Attribute(_text + "style-name")!.Value); + // Since #298 the paragraph after the break has an automatic style too (no space before at the page top). + XElement style = content.Root!.Element(_office + "automatic-styles")!.Elements(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == "TemplifyPageBreak"); + Assert.Equal("page", style.Element(_style + "paragraph-properties")!.Attribute(_fo + "break-after")!.Value); + } + + Assert.Equal(new[] { "first page", string.Empty, "second page" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void PageBreak_Odt_WritesTheAutomaticStyleOnlyWhenUsed() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph("x"))); + + XDocument content = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Odt).Content.ToArray(), "content.xml"); + + Assert.Empty(content.Root!.Element(_office + "automatic-styles")!.Elements()); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_PageBreakStartsANewPage(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(TwoPages(), format, """{ "v": "second page" }"""); + string extension = built.FileExtension.TrimStart('.'); + + Assert.Equal(2, PdfPageCount(LibreOfficeRunner.Convert(filled, extension, "pdf", "pdf"))); + Assert.Equal(1, PdfPageCount(LibreOfficeRunner.Convert( + BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("one"))), format).Content.ToArray(), extension, "pdf", "pdf"))); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersStyledInlineContent(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate built, byte[] filled) = BuilderHarness.BuildAndFill(StyledText(), format, CustomerJson); + string extension = built.FileExtension.TrimStart('.'); + + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, extension, "txt:Text (encoded):UTF8", "txt")).TrimStart('\uFEFF'); + + Assert.StartsWith("Dear Alice, total 12.50 ok \tend", text, StringComparison.Ordinal); + Assert.Contains("next line", text, StringComparison.Ordinal); + } + + private static int PdfPageCount(byte[] pdf) => PageObject().Matches(Encoding.Latin1.GetString(pdf)).Count; + + [GeneratedRegex(@"/Type\s*/Page(?![a-zA-Z])")] + private static partial Regex PageObject(); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonAssetTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonAssetTests.cs new file mode 100644 index 00000000..78d5de41 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonAssetTests.cs @@ -0,0 +1,71 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Named assets and images with one size (#293, style review A6). +public sealed class JsonAssetTests +{ + // 40 × 20 pixels: the height is half the width. + private static readonly byte[] _png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAIAAABwJOjsAAAACXBIWXMAAB2HAAAdhwGP5fFlAAAAJElEQVR42mM4ISc3IIhh1OJRi0ctHrV41OJRi0ctHrV45FgMAFLhLK5O4QWwAAAAAElFTkSuQmCC"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Pictures() => new TestDefinition(t => t.Content(c => + { + c.Image(ImageSource.Png(_png).WithName("logo"), "Logo", ImageFit.Height(12.Pt())); + c.Image(ImageSource.Png(_png), "Unnamed", ImageFit.Width(30.Pt())); + c.Image(ImageSource.Png(_png), "Squeezed", ImageFit.Exact(30.Pt(), 30.Pt())); + })); + + private static JsonElement Root(string json) => JsonDocument.Parse(json).RootElement; + + [Fact] + public void Export_NamesAssets_AndWritesOneSizeWhenTheOtherFollows() + { + TemplateJsonDocument exported = TemplateJson.Export(Pictures(), BuilderHarness.Options(TemplateFormat.Docx)); + JsonElement root = Root(exported.Json); + + JsonElement assets = root.GetProperty("assets"); + Assert.Equal(new[] { "logo", "image-1" }, assets.EnumerateObject().Select(p => p.Name)); + Assert.StartsWith("sha256:", assets.GetProperty("logo").GetString(), StringComparison.Ordinal); + Assert.Equal(new[] { "templifyDefinition", "identity", "assets" }, root.EnumerateObject().Select(p => p.Name).Take(3)); + + List images = root.GetProperty("content").EnumerateArray().Select(b => b.GetProperty("paragraph")[0]).ToList(); + Assert.Equal("""{"image":"logo","alt":"Logo","height":"12pt"}""", JsonSerializer.Serialize(images[0])); + // Width 30 pt gives height 15 pt; the export writes the height when the width follows from it. + Assert.Equal("""{"image":"image-1","alt":"Unnamed","height":"15pt"}""", JsonSerializer.Serialize(images[1])); + Assert.Equal("""{"image":"image-1","alt":"Squeezed","width":"30pt","height":"30pt"}""", JsonSerializer.Serialize(images[2])); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Import_ResolvesNamesAndTheMissingSize(TemplateFormat format) + { + TemplateJsonDocument exported = TemplateJson.Export(Pictures(), BuilderHarness.Options(format)); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets }); + + Assert.Equal(BuilderHarness.Build(Pictures(), format).ContentHash, BuilderHarness.Build(imported, format).ContentHash); + Assert.Equal(exported.Json, TemplateJson.Export(imported, BuilderHarness.Options(format)).Json); + } + + [Theory] + [InlineData("""{ "logo": "sha256:missing" }""", """[ { "paragraph": [ { "image": "logo", "alt": "a", "height": "10pt" } ] } ]""", "/assets/logo")] + [InlineData("""{}""", """[ { "paragraph": [ { "image": "logo", "alt": "a", "height": "10pt" } ] } ]""", "/content/0/paragraph/0/image")] + [InlineData("""{ "bad name": "sha256:x" }""", """[ "x" ]""", "/assets/bad name")] + public void AssetErrors(string assets, string content, string location) + { + string json = $$""" + { "templifyDefinition": 1, "identity": { "id": "a", "version": 1 }, "assets": {{assets}}, "content": {{content}} } + """; + + IReadOnlyList errors = Assert.Throws(() => TemplateJson.Import(json)).Errors; + + Assert.All(errors, e => Assert.Equal("TB9200", e.Code)); + Assert.Contains(errors, e => e.Location == location); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonDiagnosticsTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonDiagnosticsTests.cs new file mode 100644 index 00000000..60508a5e --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonDiagnosticsTests.cs @@ -0,0 +1,130 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Import diagnostics with JSON pointers (#274). +public sealed class JsonDiagnosticsTests +{ + private static string Definition(string content, string styles = "{}") => $$""" + { + "templifyDefinition": 1, + "identity": { "id": "diag", "version": 1 }, + "styles": {{styles}}, + "content": {{content}} + } + """; + + private static IReadOnlyList ImportErrors(string json, TemplateJsonImportOptions? options = null) => + Assert.Throws(() => TemplateJson.Import(json, options)).Errors; + + private static IReadOnlyList BuildErrors(string json) => + Assert.Throws(() => TemplateBuilder.Build(TemplateJson.Import(json), BuilderHarness.Options(TemplateFormat.Docx))).Errors; + + [Fact] + public void Import_ReportsEveryStructuralProblemAtOnce() + { + string json = Definition(""" + [ + { "paragraph": "ok" }, + { "paragrahp": "typo" }, + { "style": 5, "paragraph": "x" }, + { "paragraph": "x", "colour": "red" }, + { "paragraph": [ { "image": "missing", "alt": "a", "width": "10pt", "height": "10pt" } ] } + ] + """); + + IReadOnlyList errors = ImportErrors(json); + + Assert.All(errors, e => Assert.Equal("TB9200", e.Code)); + Assert.Equal( + new[] { "/content/1", "/content/2/style", "/content/3/colour", "/content/4/paragraph/0/image" }, + errors.Select(e => e.Location)); + } + + [Fact] + public void Build_ComposerArgumentErrors_BecomeTB9201_AndTheRestIsStillChecked() + { + string json = Definition( + """ + [ + { "style": "Bullets", "list": [ { "level": 12, "item": "deep" } ] }, + { "rule": { "line": "0pt #000000" } }, + { "style": "Missing", "paragraph": "x" } + ] + """, + """{ "list": { "Bullets": { "levels": [ { "level": 0, "bullet": "•", "indent": "6mm", "hanging": "4mm" } ] } } }"""); + + IReadOnlyList errors = BuildErrors(json); + + Assert.Contains(errors, e => e.Code == "TB9201" && e.Location == "/content/0/list/0"); + Assert.Contains(errors, e => e.Code == "TB9201" && e.Location == "/content/1"); + Assert.Contains(errors, e => e.Code == "TB2010" && e.Location == "/content/2"); + } + + [Fact] + public void Build_ScopeErrorsCarryTheirLocation() + { + string json = Definition(""" + [ + { "paragraph": [ "{{@index}}" ] } + ] + """); + + BuildDiagnostic error = Assert.Single(BuildErrors(json)); + + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/0/paragraph/0", error.Location); + Assert.Contains("@index", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Import_RawXml_RefusedByDefault() + { + string json = Definition(""" + [ { "raw": { "docx": "

", "odt": "

", "uses": [] } } ] + """); + + BuildDiagnostic error = Assert.Single(ImportErrors(json)); + + Assert.Equal("TB9202", error.Code); + Assert.Equal("/content/0/raw", error.Location); + BuilderHarness.Build(TemplateJson.Import(json, new TemplateJsonImportOptions { AllowRawXml = true }), TemplateFormat.Docx); + } + + [Fact] + public void Import_InvalidJsonText() + { + BuildDiagnostic error = Assert.Single(ImportErrors("{")); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(string.Empty, error.Location); + Assert.Contains("LineNumber", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Import_UnknownVersion() + { + BuildDiagnostic error = Assert.Single(ImportErrors(Definition("[]").Replace("\"templifyDefinition\": 1", "\"templifyDefinition\": 2", StringComparison.Ordinal))); + + Assert.Equal("TB9200", error.Code); + Assert.Equal("/templifyDefinition", error.Location); + } + + [Fact] + public void Import_UnknownTopLevelKeyAndBadCondition() + { + string json = Definition(""" + [ { "if": "status = paid", "then": [ { "paragraph": "x" } ] } ] + """).Replace("\"identity\"", "\"extra\": 1, \"identity\"", StringComparison.Ordinal); + + IReadOnlyList errors = ImportErrors(json); + + Assert.Contains(errors, e => e.Location == "/extra"); + BuildDiagnostic condition = Assert.Single(errors, e => e.Location == "/content/0/if"); + Assert.Contains("quote", condition.Message, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonExportTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonExportTests.cs new file mode 100644 index 00000000..cc6a3fcb --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonExportTests.cs @@ -0,0 +1,137 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.Json; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +///

Exporting definitions to JSON (#274). +public sealed class JsonExportTests +{ + private static TemplateBuildOptions Options(TemplateFormat format, string language = "en-GB") => new TemplateBuildOptions + { + Format = format, + Language = CultureInfo.GetCultureInfo(language), + Texts = SampleTexts.Catalog, + }; + + [Fact] + public void Export_WalkingSkeleton_IsThisJson() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Text("Hello "); + x.Value(t.Data["name"]); + }))); + + TemplateJsonDocument document = TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)); + + Assert.Equal( + "{\"templifyDefinition\": 1, \"identity\": {\"id\": \"test\", \"version\": 1}, \"content\": [\"Hello {{name}}\"]}\n", + document.Json); + Assert.Empty(document.Assets); + } + + [Fact] + public void Export_WithoutIndentation_IsOneLine_AndImportsToTheSameTemplate() + { + BrandTheme theme = BrandTheme.CreateDefault(); + TemplateBuildOptions options = Options(TemplateFormat.Docx); + TemplateJsonDocument indented = TemplateJson.Export(new OrderConfirmation(theme), options, SampleRunner.Components); + + TemplateJsonDocument compact = TemplateJson.Export(new OrderConfirmation(theme), options, new TemplateJsonExportOptions { Indented = false, Components = SampleRunner.Components }); + + Assert.DoesNotContain('\n', compact.Json); + Assert.Equal(JsonSerializer.Serialize(JsonDocument.Parse(compact.Json).RootElement, new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }), compact.Json); + Assert.Equal(JsonLayout.Format(compact.Json), indented.Json); + ITemplateDefinition imported = TemplateJson.Import(compact.Json, new TemplateJsonImportOptions { Assets = compact.Assets, AllowRawXml = true, Components = SampleRunner.Components, Shared = [theme] }); + Assert.Equal(TemplateBuilder.Build(new OrderConfirmation(theme), options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + Assert.Equal(indented.Json, TemplateJson.Export(imported, options, SampleRunner.Components).Json); + } + + [Fact] + public void Export_IsDeterministic_AndDoesNotDependOnTheFormat() + { + BrandTheme theme = BrandTheme.CreateDefault(); + string docx = TemplateJson.Export(new OrderConfirmation(theme), Options(TemplateFormat.Docx), SampleRunner.Components).Json; + + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR"); + Assert.Equal(docx, TemplateJson.Export(new OrderConfirmation(theme), Options(TemplateFormat.Docx), SampleRunner.Components).Json); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ar-SA"); + Assert.Equal(docx, TemplateJson.Export(new OrderConfirmation(theme), Options(TemplateFormat.Odt), SampleRunner.Components).Json); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [Fact] + public void Export_CoversEveryBlock() + { + BrandTheme theme = BrandTheme.CreateDefault(); + + TemplateJsonDocument document = TemplateJson.Export(new OrderConfirmation(theme), Options(TemplateFormat.Docx), SampleRunner.Components); + + HashSet keys = new HashSet(StringComparer.Ordinal); + using (JsonDocument json = JsonDocument.Parse(document.Json)) + { + Collect(json.RootElement, keys); + } + + foreach (string key in new[] + { + "styles", "page", "properties", "paragraph", "if", "elseIf", "else", "table", "forEachRow", "rowsIf", "box", "list", + "forEach", "image", "toc", "raw", "tabRight", "pageNumber", "pageCount", "section", "component", + }) + { + Assert.True(keys.Contains(key), $"The export has no '{key}'."); + } + + Assert.Contains("{{(order.isExpress and order.total > 1000):yesno}}", document.Json, StringComparison.Ordinal); + Assert.Contains("{{line.amount:currency}}", document.Json, StringComparison.Ordinal); + string logo = Assert.Single(document.Assets.Keys); + Assert.StartsWith("sha256:", logo, StringComparison.Ordinal); + Assert.Contains("\"" + logo + "\"", document.Json, StringComparison.Ordinal); + Assert.Contains("[[title]]", TemplateJson.Export(new OrderConfirmation(theme), Options(TemplateFormat.Docx, "de-DE"), SampleRunner.Components).Json, StringComparison.Ordinal); + } + + [Fact] + public void Export_FailingDefinition_Throws() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(new ParagraphStyleKey("Missing", "Missing"), "x"))); + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Contains(exception.Errors, e => e.Code == "TB2010"); + } + + private static void Collect(JsonElement element, HashSet keys) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + foreach (JsonProperty property in element.EnumerateObject()) + { + keys.Add(property.Name); + Collect(property.Value, keys); + } + + break; + case JsonValueKind.Array: + foreach (JsonElement item in element.EnumerateArray()) + { + Collect(item, keys); + } + + break; + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonImportTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonImportTests.cs new file mode 100644 index 00000000..150e4355 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonImportTests.cs @@ -0,0 +1,96 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Importing JSON definitions (#274). +public sealed class JsonImportTests +{ + public static TheoryData FormatsAndLanguages => new TheoryData + { + { TemplateFormat.Docx, "de-DE" }, { TemplateFormat.Odt, "de-DE" }, { TemplateFormat.Docx, "en-GB" }, { TemplateFormat.Odt, "en-GB" }, + }; + + [Theory] + [MemberData(nameof(FormatsAndLanguages))] + public void Import_RoundTripsTheSample(TemplateFormat format, string language) + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = format, Language = CultureInfo.GetCultureInfo(language), Texts = SampleTexts.Catalog }; + BrandTheme theme = BrandTheme.CreateDefault(); + OrderConfirmation definition = new OrderConfirmation(theme); + TemplateJsonDocument exported = TemplateJson.Export(definition, options, SampleRunner.Components); + + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets, AllowRawXml = true, Components = SampleRunner.Components, Shared = [theme] }); + + Assert.Equal(definition.Identity, imported.Identity); + Assert.Equal(TemplateBuilder.Build(definition, options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + Assert.Equal(exported.Json, TemplateJson.Export(imported, options, SampleRunner.Components).Json); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Import_AcceptsShorthandsAndAlternativeForms(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "short", "version": 1 }, + "styles": { "paragraph": { "Body": { "name": "Body Copy", "spaceAfter": "70.866pt", "color": "#1f4e79", "indentStart": "25mm" } } }, + "content": [ + { "paragraph": "Hi" }, + "Hi", + { "style": "Body", "paragraph": "a\t{{name}}" } + ] + } + """; + + ITemplateDefinition imported = TemplateJson.Import(json); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, """{ "name": "Ada" }"""); + + Assert.Equal(new[] { "Hi", "Hi", "a\tAda" }, BuilderHarness.ParagraphTexts(format, filled)); + string normalised = TemplateJson.Export(imported, BuilderHarness.Options(format)).Json; + using (System.Text.Json.JsonDocument document = System.Text.Json.JsonDocument.Parse(normalised)) + { + Assert.Equal("Hi", document.RootElement.GetProperty("content")[0].GetString()); + } + + Assert.Contains("\"spaceAfter\": \"25mm\"", normalised, StringComparison.Ordinal); + Assert.Contains("\"color\": \"#1F4E79\"", normalised, StringComparison.Ordinal); + Assert.DoesNotContain("70.866pt", normalised, StringComparison.Ordinal); + Assert.NotNull(template); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Import_ResolvesLoopItemsLikeTheFluentApi(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "loops", "version": 1 }, + "content": [ + { "forEach": "order.lines", "as": "line", "body": [ + "{{@number}} {{line.description}}" ] }, + "{{line.description}}" + ] + } + """; + + ITemplateDefinition imported = TemplateJson.Import(json); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill( + imported, + format, + """{ "order": { "lines": [ { "description": "A" } ] }, "line": { "description": "root" } }"""); + + Assert.Equal(new[] { "1 A", "root" }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Contains(new ContractEntry("order.lines[].description", ContractUsage.Value), template.Contract.Entries); + Assert.Contains(new ContractEntry("line.description", ContractUsage.Value), template.Contract.Entries); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonLayoutTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonLayoutTests.cs new file mode 100644 index 00000000..c7f433a7 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonLayoutTests.cs @@ -0,0 +1,82 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; + +namespace TriasDev.Templify.Builder.Tests; + +/// The width-based layout of exported JSON definitions. +public sealed class JsonLayoutTests +{ + [Fact] + public void FitsOnOneLine_WhenItFits() + { + Assert.Equal("{\"a\": 1, \"b\": [\"x\", \"y\"]}\n", JsonLayout.Format("""{"a":1,"b":["x","y"]}""")); + } + + [Fact] + public void Width_CountsTheKey_NotTheIndentation() + { + // The member's key "\"k\": " is 5 characters; a 95-character value makes 100 exactly. The indentation (2 or 4 + // spaces) does not count, so a member reads the same at every depth. + string fits = "[\"" + new string('x', 91) + "\"]"; + Assert.Equal(95, fits.Length); + string tooLong = "[\"" + new string('x', 92) + "\"]"; + string Wrap(string value) => "{\"k\":" + value + ",\"other\":" + new string('1', 95) + "}"; + string Nested(string value) => "{\"a\":" + Wrap(value) + "}"; + + Assert.Contains(" \"k\": " + fits + ",\n", JsonLayout.Format(Wrap(fits)), StringComparison.Ordinal); + Assert.Contains(" \"k\": " + fits + ",\n", JsonLayout.Format(Nested(fits)), StringComparison.Ordinal); + Assert.Contains(" \"k\": [\n \"" + new string('x', 92) + "\"\n ],\n", JsonLayout.Format(Wrap(tooLong)), StringComparison.Ordinal); + } + + [Fact] + public void Width_ArrayItems_CountOnlyThemselves() + { + string fits = "{\"p\":\"" + new string('y', 91) + "\"}"; + Assert.Equal(100, "{\"p\": \"".Length + 91 + 2); + string json = "[[" + fits + ",\"" + new string('z', 100) + "\"]]"; + + Assert.Contains(" {\"p\": \"" + new string('y', 91) + "\"},\n", JsonLayout.Format(json), StringComparison.Ordinal); + } + + [Fact] + public void Nested_OuterBreaks_InnerFits() + { + string json = "{\"content\":[{\"style\":\"Heading\",\"paragraph\":\"Title\"},\"" + new string('t', 100) + "\"]}"; + + Assert.Equal( + "{\n \"content\": [\n {\"style\": \"Heading\", \"paragraph\": \"Title\"},\n \"" + new string('t', 100) + "\"\n ]\n}\n", + JsonLayout.Format(json)); + } + + [Fact] + public void LongStrings_AreNotWrapped_EscapingIsKept() + { + string json = "{\"a\":\"" + new string('a', 120) + "\",\"q\":\"say \\\"ü\\\" \\\\ {{x}}\"}"; + + string formatted = JsonLayout.Format(json); + + Assert.Contains(" \"a\": \"" + new string('a', 120) + "\",\n", formatted, StringComparison.Ordinal); + Assert.Contains(" \"q\": \"say \\\"ü\\\" \\\\ {{x}}\"\n", formatted, StringComparison.Ordinal); + } + + [Fact] + public void EmptyContainers_AreInline() + { + string json = "{\"a\":[],\"b\":{},\"c\":\"" + new string('c', 100) + "\"}"; + + Assert.Equal("{\n \"a\": [],\n \"b\": {},\n \"c\": \"" + new string('c', 100) + "\"\n}\n", JsonLayout.Format(json)); + } + + [Fact] + public void Format_IsIdempotent() + { + string json = "{\"content\":[{\"if\":\"a\",\"then\":[\"" + new string('x', 120) + "\"]},\"short\"],\"n\":1.5,\"t\":true,\"z\":null}"; + + string once = JsonLayout.Format(json); + + Assert.Equal(once, JsonLayout.Format(once)); + Assert.Equal(once, JsonLayout.Format(json)); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonOutlineTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonOutlineTests.cs new file mode 100644 index 00000000..01754a32 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonOutlineTests.cs @@ -0,0 +1,83 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #274: an agent finds its way around a definition (Outline) and reads one part of it (Read). +public sealed class JsonOutlineTests +{ + private static string Sample() => + TemplateJson.Export(new OrderConfirmation(BrandTheme.CreateDefault()), BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog), SampleRunner.Components).Json; + + [Fact] + public void Outline_ListsBlocksWithPointersKindsAndLabels() + { + IReadOnlyList outline = TemplateJson.Outline(Sample()); + + Assert.Contains(outline, n => n.Pointer == "/content/0" && n.Kind == "paragraph" && n.Label == "DocTitle: [[title]]" && n.Depth == 0); + Assert.Contains(outline, n => n.Pointer == "/content/3" && n.Kind == "section" && n.Label == "customer" && n.Depth == 0); + Assert.Contains(outline, n => n.Pointer == "/content/3/blocks/0" && n.Kind == "paragraph" && n.Label == "SectionHeading: [[customer]]" && n.Depth == 1); + Assert.Contains(outline, n => n.Pointer == "/content/3/blocks/2" && n.Kind == "if" && n.Label == "order.customer.contact is not empty" && n.Depth == 1); + Assert.Contains(outline, n => n.Pointer == "/content/3/blocks/3" && n.Kind == "component" && n.Label == "address" && n.Depth == 1); + Assert.Contains(outline, n => n.Pointer == "/content/4/blocks/1" && n.Kind == "table"); + Assert.Contains(outline, n => n.Pointer == "/content/4/blocks/1/table/1" && n.Kind == "forEachRow" && n.Label == "order.lines as line" && n.Depth == 2); + Assert.Contains(outline, n => n.Pointer == "/content/5/blocks/0/elseIf/0" && n.Kind == "elseIf" && n.Label == "order.status in (\"overdue\", \"reminded\")"); + Assert.Contains(outline, n => n.Pointer == "/content/5/blocks/0/else/0" && n.Kind == "paragraph"); + Assert.Contains(outline, n => n.Pointer == "/page/footer/0" && n.Kind == "paragraph"); + Assert.Contains(outline, n => n.Pointer == "/content/6/blocks/0/then/1/list/0" && n.Kind == "forEach"); + + // Document order: a parent comes before its children. + Assert.True(outline.ToList().FindIndex(n => n.Pointer == "/content/3") < outline.ToList().FindIndex(n => n.Pointer == "/content/3/blocks/0")); + } + + [Fact] + public void Outline_RowLabelStartsWithTheColumnsItCovers() + { + // The agent trial: adding a column means every row must cover one more; spans count. + IReadOnlyList rows = TemplateJson.Outline(Sample()).Where(n => n.Kind is "row" or "headerRow").ToList(); + Assert.NotEmpty(rows); + Assert.All(rows.Where(r => r.Pointer.StartsWith("/content/4/blocks/1/", StringComparison.Ordinal)), r => Assert.StartsWith("4 columns: ", r.Label, StringComparison.Ordinal)); + } + + [Fact] + public void Outline_LongTextIsShortened() + { + string json = """{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, "content": [ "This paragraph is much longer than forty characters, so it is cut." ] }"""; + TemplateJsonNode node = Assert.Single(TemplateJson.Outline(json)); + Assert.Equal("This paragraph is much longer than forty…", node.Label); + } + + [Fact] + public void Read_ReturnsTheSubtree() + { + JsonNode part = JsonNode.Parse(TemplateJson.Read(Sample(), "/content/3/blocks/3"))!; + Assert.Equal("address", (string?)part["component"]); + Assert.Equal("order.customer.address", (string?)part["params"]!["address"]); + } + + [Fact] + public void Read_EscapedPointer() + { + string json = """{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, "texts": { "a/b": { "en": "slash" }, "c~d": { "en": "tilde" } }, "content": [] }"""; + Assert.Contains("slash", TemplateJson.Read(json, "/texts/a~1b"), StringComparison.Ordinal); + Assert.Contains("tilde", TemplateJson.Read(json, "/texts/c~0d"), StringComparison.Ordinal); + } + + [Fact] + public void Read_Root() => Assert.Contains("templifyDefinition", TemplateJson.Read(Sample(), string.Empty), StringComparison.Ordinal); + + [Theory] + [InlineData("/content/99")] + [InlineData("/nothing")] + [InlineData("content/0")] + [InlineData("/content/01")] + [InlineData("/content/-")] + [InlineData("/content/0/paragraph/x")] + public void Read_MissingOrMalformed_Throws(string pointer) => + Assert.Throws(() => TemplateJson.Read(Sample(), pointer)); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonPatchTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonPatchTests.cs new file mode 100644 index 00000000..1f6e7542 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonPatchTests.cs @@ -0,0 +1,151 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #274: an agent changes a definition in small steps (JSON Patch) and gets the check of the result. +public sealed class JsonPatchTests +{ + private static readonly TemplateBuildOptions _build = BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog); + + private static TemplateJsonDocument Export() => TemplateJson.Export(new OrderConfirmation(BrandTheme.CreateDefault()), _build, SampleRunner.Components); + + private static TemplateJsonImportOptions Import(TemplateJsonDocument document) => new TemplateJsonImportOptions + { + Assets = document.Assets, + Components = SampleRunner.Components, + Shared = [BrandTheme.CreateDefault()], + Data = DataCatalog.From(), + AllowRawXml = true, + }; + + private static TemplatePatchResult Patch(string patch) + { + TemplateJsonDocument document = Export(); + return TemplateJson.Patch(document.Json, patch, Import(document), _build); + } + + private static int SectionIndex(string json, string name) => + TemplateJson.Outline(json).Where(n => n.Depth == 0 && n.Pointer.StartsWith("/content/", StringComparison.Ordinal)).ToList().FindIndex(n => n.Kind == "section" && n.Label == name); + + [Fact] + public void Add_AppendsABlock() + { + TemplatePatchResult result = Patch("""[ { "op": "add", "path": "/content/-", "value": "Thank you for your order." } ]"""); + Assert.True(result.Applied); + Assert.Equal(TemplateCheckStatus.Ok, result.Check.Status); + Assert.Equal("Thank you for your order.", (string?)JsonNode.Parse(result.Json)!["content"]!.AsArray()[^1]); + } + + [Fact] + public void Remove_ASection() + { + string json = Export().Json; + int notes = SectionIndex(json, "notes"); + TemplatePatchResult result = Patch($$"""[ { "op": "remove", "path": "/content/{{notes}}" } ]"""); + Assert.Equal(TemplateCheckStatus.Ok, result.Check.Status); + Assert.Equal(-1, SectionIndex(result.Json, "notes")); + } + + [Fact] + public void Replace_AParagraph() + { + TemplatePatchResult result = Patch("""[ { "op": "replace", "path": "/content/0/paragraph", "value": "Confirmation {{order.number}}" } ]"""); + Assert.Equal(TemplateCheckStatus.Ok, result.Check.Status); + Assert.Equal("Confirmation {{order.number}}", (string?)JsonNode.Parse(result.Json)!["content"]![0]!["paragraph"]); + } + + [Fact] + public void Move_ASection() + { + string json = Export().Json; + int notes = SectionIndex(json, "notes"); + int customer = SectionIndex(json, "customer"); + TemplatePatchResult result = Patch($$"""[ { "op": "move", "from": "/content/{{notes}}", "path": "/content/{{customer}}" } ]"""); + Assert.Equal(TemplateCheckStatus.Ok, result.Check.Status); + Assert.Equal(customer, SectionIndex(result.Json, "notes")); + Assert.Equal(customer + 1, SectionIndex(result.Json, "customer")); + } + + [Fact] + public void Copy_ABlock() + { + TemplatePatchResult result = Patch("""[ { "op": "copy", "from": "/content/0", "path": "/content/-" } ]"""); + JsonArray content = JsonNode.Parse(result.Json)!["content"]!.AsArray(); + Assert.True(JsonNode.DeepEquals(content[0], content[^1])); + Assert.Equal(TemplateCheckStatus.Ok, result.Check.Status); + } + + [Fact] + public void Test_GuardsTheEdit() + { + string json = Export().Json; + int customer = SectionIndex(json, "customer"); + Assert.True(Patch($$"""[ { "op": "test", "path": "/content/{{customer}}/section", "value": "customer" }, { "op": "remove", "path": "/content/{{customer}}" } ]""").Applied); + + TemplatePatchResult failed = Patch($$"""[ { "op": "test", "path": "/content/{{customer}}/section", "value": "items" }, { "op": "remove", "path": "/content/{{customer}}" } ]"""); + Assert.False(failed.Applied); + Assert.Equal(("TB9207", "/0"), (failed.Check.Problems.Single().Code, failed.Check.Problems.Single().Location)); + } + + [Fact] + public void FailingOp_LeavesTheInputUnchanged() + { + TemplateJsonDocument document = Export(); + TemplatePatchResult result = TemplateJson.Patch( + document.Json, + """[ { "op": "replace", "path": "/content/0/paragraph", "value": "x" }, { "op": "remove", "path": "/content/99" }, { "op": "add", "path": "/content/-", "value": "y" } ]""", + Import(document), + _build); + Assert.False(result.Applied); + Assert.Equal(document.Json, result.Json); + Assert.Equal(TemplateCheckStatus.Broken, result.Check.Status); + TemplateCheckProblem problem = Assert.Single(result.Check.Problems); + Assert.Equal(("TB9207", "/1"), (problem.Code, problem.Location)); + Assert.Contains("/content/99", problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void MoveIntoItsOwnChild_Fails() + { + string json = Export().Json; + int customer = SectionIndex(json, "customer"); + Assert.False(Patch($$"""[ { "op": "move", "from": "/content/{{customer}}", "path": "/content/{{customer}}/blocks/0" } ]""").Applied); + } + + [Theory] + [InlineData("nope")] + [InlineData("""{ "op": "remove", "path": "/content/0" }""")] + [InlineData("""[ { "op": "rename", "path": "/content/0" } ]""")] + [InlineData("""[ { "op": "add", "path": "/content/-" } ]""")] + [InlineData("""[ { "op": "move", "path": "/content/0" } ]""")] + public void MalformedPatch_Fails(string patch) + { + TemplatePatchResult result = Patch(patch); + Assert.False(result.Applied); + Assert.Equal("TB9207", result.Check.Problems.Single().Code); + } + + [Fact] + public void PatchedButBroken_ReportsTheProblemAtItsPointer() + { + TemplatePatchResult result = Patch("""[ { "op": "add", "path": "/content/-", "value": "Shipped to {{order.shipTo}}" } ]"""); + Assert.True(result.Applied); + Assert.Equal(TemplateCheckStatus.Broken, result.Check.Status); + TemplateCheckProblem problem = Assert.Single(result.Check.Problems); + Assert.Equal("order.shipTo", problem.DataPath); + Assert.StartsWith("/content/", problem.Location, StringComparison.Ordinal); + } + + [Fact] + public void WithoutDataCatalog_Throws() + { + TemplateJsonDocument document = Export(); + Assert.Throws(() => TemplateJson.Patch(document.Json, "[]", new TemplateJsonImportOptions(), _build)); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonPreviewTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonPreviewTests.cs new file mode 100644 index 00000000..94925311 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonPreviewTests.cs @@ -0,0 +1,92 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #274: an agent sees what a definition makes (Preview): the filled document and its text. +public sealed class JsonPreviewTests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TemplateJsonDocument Export() => + TemplateJson.Export(new OrderConfirmation(BrandTheme.CreateDefault()), BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog), SampleRunner.Components); + + private static TemplateJsonImportOptions Import(TemplateJsonDocument document) => new TemplateJsonImportOptions + { + Assets = document.Assets, + Components = SampleRunner.Components, + Shared = [BrandTheme.CreateDefault()], + AllowRawXml = true, + }; + + [Theory] + [MemberData(nameof(Formats))] + public void Preview_FillsWithData(TemplateFormat format) + { + TemplateJsonDocument document = Export(); + TemplatePreview preview = TemplateJson.Preview(document.Json, Import(document), BuilderHarness.Options(format, "en-GB", SampleTexts.Catalog), SampleResources.SampleData); + + Assert.Equal(TemplateCheckStatus.Ok, preview.Check.Status); + Assert.NotNull(preview.Document); + BuilderHarness.AssertPackage(format, preview.Document!); + Assert.Contains("Order confirmation", preview.Text, StringComparison.Ordinal); + Assert.Contains("Example Trading GmbH", preview.Text, StringComparison.Ordinal); + Assert.DoesNotContain("{{", preview.Text, StringComparison.Ordinal); + } + + [Fact] + public void Preview_WithoutData_UsesTheWitness() + { + TemplateJsonDocument document = Export(); + TemplatePreview preview = TemplateJson.Preview(document.Json, Import(document), BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog)); + Assert.Equal(TemplateCheckStatus.Ok, preview.Check.Status); + Assert.NotNull(preview.Text); + Assert.DoesNotContain("{{", preview.Text, StringComparison.Ordinal); + } + + [Fact] + public void Preview_BrokenDefinition_ReturnsProblems_NoDocument() + { + TemplateJsonDocument document = Export(); + string broken = TemplateJson.Patch(document.Json, """[ { "op": "replace", "path": "/content/0/style", "value": "Nope" } ]""", + new TemplateJsonImportOptions { Data = DataCatalog.From() }).Json; + TemplatePreview preview = TemplateJson.Preview(broken, Import(document), BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog)); + Assert.Equal(TemplateCheckStatus.Broken, preview.Check.Status); + Assert.Null(preview.Document); + Assert.Null(preview.Text); + Assert.Contains(preview.Check.Problems, p => p.Code == "TB2010"); + } + + [Fact] + public void Preview_FillFailure_IsAProblem() + { + string json = """{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, "content": [ { "forEach": "items", "as": "item", "body": [ "{{item}}" ] } ] }"""; + TemplatePreview preview = TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(TemplateFormat.Docx), """{ "items": "not a list" }"""); + Assert.Equal(TemplateCheckStatus.Broken, preview.Check.Status); + Assert.Null(preview.Document); + Assert.Contains(preview.Check.Problems, p => p.Code == "TB9302"); + } + + [Fact] + public void Preview_MissingValue_IsAWarning() + { + string json = """{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, "content": [ "Hello {{name}} {{surname}}" ] }"""; + TemplatePreview preview = TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(TemplateFormat.Odt), """{ "name": "Ada" }"""); + Assert.Equal(TemplateCheckStatus.Warning, preview.Check.Status); + Assert.Equal("surname", Assert.Single(preview.Check.Problems).DataPath); + Assert.Contains("Hello Ada", preview.Text, StringComparison.Ordinal); + } + + [Fact] + public void Preview_BadDataJson_IsAProblem() + { + string json = """{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, "content": [ "Hello" ] }"""; + TemplatePreview preview = TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(TemplateFormat.Docx), "{ nope"); + Assert.Equal(TemplateCheckStatus.Broken, preview.Check.Status); + Assert.Null(preview.Document); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonSchemaTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonSchemaTests.cs new file mode 100644 index 00000000..fce2728a --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonSchemaTests.cs @@ -0,0 +1,81 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #274: the JSON Schema of the definition format accepts what the reader accepts and rejects unknown keys. +public sealed class JsonSchemaTests +{ + public static TheoryData Constructs => new TheoryData(JsonVocabulary.All.Select(c => c.Name)); + + private sealed record Results(List Errors) + { + public bool IsValid => Errors.Count == 0; + } + + private static Results Evaluate(string schema, string instance) => new Results(new SchemaValidator(schema).Validate(instance)); + + private static string Errors(Results results) => string.Join(Environment.NewLine, results.Errors.Take(20)); + + private static string SampleExport() => + TemplateJson.Export(new OrderConfirmation(BrandTheme.CreateDefault()), BuilderHarness.Options(TemplateFormat.Docx, "en-GB", SampleTexts.Catalog), SampleRunner.Components).Json; + + [Fact] + public void Schema_AcceptsTheSampleExport() + { + Results results = Evaluate(TemplateJson.Schema(SampleRunner.Components), SampleExport()); + Assert.True(results.IsValid, Errors(results)); + } + + [Theory] + [MemberData(nameof(Constructs))] + public void Schema_AcceptsEveryVocabularyExample(string name) + { + Construct construct = JsonVocabulary.All.Single(c => c.Name == name); + Results results = Evaluate(TemplateJson.Schema(SampleRunner.Components), JsonVocabularyTests.Place(construct, JsonNode.Parse(construct.Example)!)); + Assert.True(results.IsValid, Errors(results)); + } + + [Fact] + public void Schema_RejectsAnUnknownKey() + { + JsonObject definition = JsonNode.Parse(SampleExport())!.AsObject(); + definition["content"]![0]!.AsObject()["colour"] = "red"; + Assert.False(Evaluate(TemplateJson.Schema(SampleRunner.Components), definition.ToJsonString()).IsValid); + } + + [Fact] + public void Schema_RejectsABadLength() + { + JsonObject definition = JsonNode.Parse(SampleExport())!.AsObject(); + definition["page"]!["margins"] = "25"; + Assert.False(Evaluate(TemplateJson.Schema(), definition.ToJsonString()).IsValid); + } + + [Fact] + public void Schema_RejectsAnUnknownComponent_WhenComponentsGiven() + { + JsonObject definition = JsonNode.Parse(SampleExport())!.AsObject(); + definition["content"]!.AsArray().Add(JsonNode.Parse("""{ "component": "nope" }""")); + Assert.False(Evaluate(TemplateJson.Schema(SampleRunner.Components), definition.ToJsonString()).IsValid); + Assert.True(Evaluate(TemplateJson.Schema(), definition.ToJsonString()).IsValid); + } + + [Fact] + public void Schema_ChecksComponentParameters_WhenComponentsGiven() + { + JsonObject definition = JsonNode.Parse(SampleExport())!.AsObject(); + definition["content"]!.AsArray().Add(JsonNode.Parse("""{ "component": "address", "params": { "adress": "order.customer.address" } }""")); + Assert.False(Evaluate(TemplateJson.Schema(SampleRunner.Components), definition.ToJsonString()).IsValid); + } + + [Fact] + public void Schema_IsDeterministic() => + Assert.Equal(TemplateJson.Schema(SampleRunner.Components), TemplateJson.Schema(SampleRunner.Components)); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonShortFormTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonShortFormTests.cs new file mode 100644 index 00000000..aa031c4b --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonShortFormTests.cs @@ -0,0 +1,534 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// The compact JSON forms: text with placeholders, short blocks, inherited styles (#274). +public sealed class JsonShortFormTests +{ + private static readonly CharacterStyleKey _strong = new CharacterStyleKey("Strong", "Strong Text"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static string Definition(string content, string styles = "{ \"character\": { \"Strong\": { \"name\": \"Strong Text\", \"bold\": true } } }") => $$""" + { + "templifyDefinition": 1, + "identity": { "id": "short", "version": 1 }, + "styles": {{styles}}, + "content": {{content}} + } + """; + + private sealed record Order(string Number); + + private sealed record Data(Order Order); + + // ── text with placeholders ─────────────────────────────────────────────── + + [Theory] + [MemberData(nameof(Formats))] + public void Import_StringWithPlaceholders(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ { "paragraph": "Order {{order.number}} of {{order.date:date:yyyy}}" } ]""")); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, """{ "order": { "number": "42", "date": "2026-11-26" } }"""); + + Assert.Equal(new[] { "Order 42 of 2026" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Import_StyledTextWithValue(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ { "paragraph": [ "No. ", { "text": "{{order.number}}", "style": "Strong" } ] } ]""")); + TestDefinition expected = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Character(_strong, c => c.Bold()))); + t.Content(c => c.Paragraph(x => + { + x.Text("No. "); + x.Value(_strong, t.Data["order"]["number"]); + })); + }, new TemplateIdentity("short", 1)); + + Assert.Equal(BuilderHarness.Build(expected, format).ContentHash, BuilderHarness.Build(imported, format).ContentHash); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Import_Expression(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ { "paragraph": "Free: {{(a and b):yesno}}" } ]""")); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, """{ "a": true, "b": false }"""); + + Assert.Equal(new[] { "Free: No" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [InlineData("""[ { "paragraph": "x {{order.number" } ]""", "/content/0/paragraph")] + [InlineData("""[ { "paragraph": [ "ok", "x {{}}" ] } ]""", "/content/0/paragraph/1")] + [InlineData("""[ { "paragraph": "{{(a and b)}}" } ]""", "/content/0/paragraph")] + [InlineData("""[ { "paragraph": [ { "text": "{{(a):yesno}}", "style": "Strong" } ] } ]""", "/content/0/paragraph/0")] + [InlineData("""[ { "paragraph": [ { "if": "a", "then": "{{(b):yesno}}" } ] } ]""", "/content/0/paragraph/0/then")] + [InlineData("""[ { "paragraph": [ { "if": "a", "then": [ { "text": "{{v:number:F2}}", "style": "Strong" } ] } ] } ]""", "/content/0/paragraph/0/then/0")] + [InlineData("""[ { "paragraph": [ { "value": "a" } ] } ]""", "/content/0/paragraph/0")] + [InlineData("""[ { "paragraph": [ { "expression": "a", "format": "yesno" } ] } ]""", "/content/0/paragraph/0/expression")] + public void Import_Errors(string content, string location) + { + IReadOnlyList errors = Assert.Throws(() => TemplateJson.Import(Definition(content))).Errors; + + BuildDiagnostic error = Assert.Single(errors); + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + [Fact] + public void Import_UnknownPathInString_IsTB9203() + { + TemplateJsonImportOptions options = new TemplateJsonImportOptions { Data = DataCatalog.From() }; + + IReadOnlyList errors = Assert.Throws(() => + TemplateJson.Import(Definition("""[ { "paragraph": "{{order.number}} {{order.nmber}}" } ]"""), options)).Errors; + + BuildDiagnostic error = Assert.Single(errors); + Assert.Equal("TB9203", error.Code); + Assert.Equal("/content/0/paragraph", error.Location); + Assert.Contains("order.nmber", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Export_MergesValuesIntoText() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Text("Order "); + x.Value(t.Data["order"]["number"]); + x.Text(" of "); + x.Value(t.Data["order"]["date"], ValueFormat.Date("yyyy")); + }))); + + Assert.Equal("Order {{order.number}} of {{order.date:date:yyyy}}", ContentOf(definition).GetString()); + } + + [Fact] + public void Export_KeepsAdjacentTextsApart() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Text("a"); + x.Text("b"); + x.Value(t.Data["v"]); + x.Tab(); + x.Text("c"); + }))); + + // A tab or line break is part of the string ("\t", "\n"); two plain texts still never join. + Assert.Equal("""["a","b{{v}}\tc"]""", Compact(ContentOf(definition))); + AssertRoundTrip(definition); + } + + [Fact] + public void Export_DoesNotMergeABraceIntoAPlaceholder() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Text("set {"); + x.Value(t.Data["v"]); + x.Text("}"); + }))); + + Assert.Equal("""["set {","{{v}}}"]""", Compact(ContentOf(definition))); + AssertRoundTrip(definition); + } + + [Fact] + public void Export_StyledRun() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Character(_strong, c => c.Bold()))); + t.Content(c => c.Paragraph(x => + { + x.Text(_strong, "x"); + x.Value(_strong, t.Data["p"]); + x.Value(t.Data["q"]); + })); + }); + + Assert.Equal("""[{"text":"x{{p}}","style":"Strong"},"{{q}}"]""", Compact(ContentOf(definition))); + AssertRoundTrip(definition); + } + + [Fact] + public void Export_InlineConditionBranchesAreText() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Value(t.Data["name"]); + x.If(t.Data["isNew"], b => b.Text(" (new, ").Value(t.Data["since"]).Text(")")).Else(b => b.Text("")); + }))); + + Assert.Equal("""["{{name}}",{"if":"isNew","then":" (new, {{since}})","else":[]}]""", Compact(ContentOf(definition))); + AssertRoundTrip(definition); + } + + // ── block short forms ──────────────────────────────────────────────────── + + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body Text Style"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading", "Heading Style"); + private static readonly ParagraphStyleKey _cell = new ParagraphStyleKey("CellText", "Cell Text"); + private static readonly ParagraphStyleKey _head = new ParagraphStyleKey("HeadText", "Head Text"); + private static readonly ParagraphStyleKey _total = new ParagraphStyleKey("TotalText", "Total Text"); + private static readonly ParagraphStyleKey _item = new ParagraphStyleKey("ItemText", "Item Text"); + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + private static readonly BoxStyleKey _success = new BoxStyleKey("SuccessBox"); + private static readonly ListStyleKey _bullets = new ListStyleKey("Bullets"); + + private const string ShortStyles = """ + { + "defaults": { "paragraphStyle": "Body" }, + "paragraph": { + "Body": { "name": "Body Text Style" }, "Heading": { "name": "Heading Style" }, "CellText": { "name": "Cell Text" }, + "HeadText": { "name": "Head Text" }, "TotalText": { "name": "Total Text" }, "ItemText": { "name": "Item Text" } + }, + "table": { "Grid": { "rowRule": "0.5pt #D4D4D4", "paragraphStyle": "CellText", "headerParagraphStyle": "HeadText" } }, + "box": { "SuccessBox": { "background": "#EFF6F1" } }, + "list": { "Bullets": { "itemStyle": "ItemText", "levels": [ { "level": 0, "bullet": "•", "indent": "6mm", "hanging": "4mm" }, { "level": 1, "bullet": "–", "indent": "12mm", "hanging": "4mm" } ] } } + } + """; + + private const string ShortContent = """ + [ + "Plain block {{name}}", + { "style": "Heading", "paragraph": "Title" }, + { "style": "SuccessBox", "box": [ "Paid" ] }, + { "style": "Bullets", "list": [ "first", { "level": 1, "item": "second {{name}}" } ] }, + { "style": "Grid", "columns": [ "20mm", 1 ], "table": [ + { "header": true, "row": [ "#", "Item" ] }, + { "row": [ "1", { "content": [ "a", { "style": "Heading", "paragraph": "b" } ] } ] }, + { "paragraphStyle": "TotalText", "row": [ { "span": 2, "content": "Total {{total}}" } ] } + ] } + ] + """; + + private static TestDefinition ShortFormsInCSharp() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.ParagraphStyle(_body)); + s.Paragraph(_body, p => { }); + s.Paragraph(_heading, p => { }); + s.Paragraph(_cell, p => { }); + s.Paragraph(_head, p => { }); + s.Paragraph(_total, p => { }); + s.Paragraph(_item, p => { }); + s.Table(_grid, g => g.RowRule(0.5.Pt(), Color.FromHex("D4D4D4")).ParagraphStyle(_cell).HeaderParagraphStyle(_head)); + s.Box(_success, b => b.Background(Color.FromHex("EFF6F1"))); + s.List(_bullets, l => l.ItemStyle(_item).Level(0, "•", 6.Mm(), 4.Mm()).Level(1, "–", 12.Mm(), 4.Mm())); + })); + t.Content(c => + { + c.Paragraph(x => + { + x.Text("Plain block "); + x.Value(t.Data["name"]); + }); + c.Paragraph(_heading, "Title"); + c.Box(_success, b => b.Paragraph("Paid")); + c.List(_bullets, l => + { + l.Item("first"); + l.Item(1, x => + { + x.Text("second "); + x.Value(t.Data["name"]); + }); + }); + c.Table(tb => + { + tb.Style(_grid).Columns(cols => + { + cols.Fixed(20.Mm()); + cols.Relative(1); + }); + tb.HeaderRow(r => + { + r.Cell("#"); + r.Cell("Item"); + }); + tb.Row(r => + { + r.Cell("1"); + r.Cell(cell => + { + cell.Paragraph("a"); + cell.Paragraph(_heading, "b"); + }); + }); + tb.Row(r => + { + r.ParagraphStyle(_total); + r.Cell(cell => cell.ColumnSpan(2).Paragraph(x => + { + x.Text("Total "); + x.Value(t.Data["total"]); + })); + }); + }); + }); + }, new TemplateIdentity("short", 1)); + + [Theory] + [MemberData(nameof(Formats))] + public void Import_ShortForms(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition(ShortContent, ShortStyles)); + + Assert.Equal(BuilderHarness.Build(ShortFormsInCSharp(), format).ContentHash, BuilderHarness.Build(imported, format).ContentHash); + } + + [Fact] + public void Export_ShortForms() + { + string json = TemplateJson.Export(ShortFormsInCSharp(), BuilderHarness.Options(TemplateFormat.Docx)).Json; + using JsonDocument document = JsonDocument.Parse(json); + using JsonDocument expected = JsonDocument.Parse(ShortContent); + + Assert.Equal(Compact(expected.RootElement), Compact(document.RootElement.GetProperty("content"))); + AssertRoundTrip(ShortFormsInCSharp()); + } + + [Fact] + public void Export_OmitsInheritedStyle_KeepsOthers() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.ParagraphStyle(_body)); + s.Paragraph(_body, p => { }); + s.Paragraph(_heading, p => { }); + })); + t.Content(c => + { + c.Paragraph(_body, "explicit body"); + c.Paragraph(_heading, "heading"); + }); + }); + + string json = TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)).Json; + using JsonDocument document = JsonDocument.Parse(json); + + Assert.Equal("""["explicit body",{"style":"Heading","paragraph":"heading"}]""", Compact(document.RootElement.GetProperty("content"))); + AssertRoundTrip(definition); + } + + [Fact] + public void Export_ExplicitInheritedStyleInNestedCell_RoundTrips() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.ParagraphStyle(_body)); + s.Paragraph(_body, p => { }); + s.Paragraph(_cell, p => { }); + s.Table(_grid, g => g.ParagraphStyle(_cell)); + s.Box(_success, b => b.Background(Color.FromHex("EFF6F1"))); + })); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => + { + cell.Paragraph(_cell, "explicit cell style"); + cell.If(t.Data["flag"], b => b.Box(_success, box => box.Paragraph(_body, "explicit body in box"))); + cell.Table(inner => + { + inner.Columns(cols => cols.Relative(1)); + inner.Row(ir => ir.Cell(_cell, "unstyled table, explicit cell style")); + }); + })); + })); + }); + + string json = TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)).Json; + Assert.DoesNotContain("\"style\": \"Body\"", json, StringComparison.Ordinal); + Assert.Contains("unstyled table, explicit cell style", json, StringComparison.Ordinal); + AssertRoundTrip(definition); + } + + [Fact] + public void Import_OldShape_IsRejected() + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => + TemplateJson.Import(Definition("""[ { "paragraph": { "style": "Body", "content": "x" } } ]"""))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal("/content/0/paragraph", error.Location); + } + + [Fact] + public void Import_CellOptionsWithoutContent_IsTB9200() + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => + TemplateJson.Import(Definition("""[ { "columns": [ 1 ], "table": [ { "row": [ { "span": 1 } ] } ] } ]"""))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal("/content/0/table/0/row/0", error.Location); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Conditionals_AlwaysUseThen_AndElseIfUsesIf(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition(""" + [ + { "style": "Bullets", "list": [ { "if": "a", "then": [ "list a" ], "elseIf": [ { "if": "b", "then": [ "list b" ] } ] } ] }, + { "if": "a", "then": [ "block a" ], "elseIf": [ { "if": "b", "then": [ "block b" ] } ], "else": [ "block c" ] } + ] + """, ShortStyles)); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, """{ "a": false, "b": true }"""); + + Assert.Equal(new[] { "list b", "block b" }, BuilderHarness.ParagraphTexts(format, filled)); + string json = TemplateJson.Export(imported, BuilderHarness.Options(format)).Json; + Assert.DoesNotContain("\"when\"", json, StringComparison.Ordinal); + } + + // ── sections ───────────────────────────────────────────────────────────── + + private sealed class Banner : ITemplateComponent + { + public void Compose(BlockComposer c) => c.Paragraph("banner"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Sections_AreNamedAndTransparent(TemplateFormat format) + { + TestDefinition sectioned = new TestDefinition(t => t.Content(c => + { + c.Section("intro", b => b.Paragraph("Hello")); + c.Component(new Banner()); + c.Component(new Banner()); + })); + TestDefinition plain = new TestDefinition(t => t.Content(c => + { + c.Paragraph("Hello"); + c.Paragraph("banner"); + c.Paragraph("banner"); + })); + + Assert.Equal(BuilderHarness.Build(plain, format).ContentHash, BuilderHarness.Build(sectioned, format).ContentHash); + string json = TemplateJson.Export(sectioned, BuilderHarness.Options(format)).Json; + using JsonDocument document = JsonDocument.Parse(json); + Assert.Equal( + """[{"section":"intro","blocks":["Hello"]},{"section":"Banner","blocks":["banner"]},{"section":"Banner-2","blocks":["banner"]}]""", + Compact(document.RootElement.GetProperty("content"))); + AssertRoundTrip(sectioned); + } + + [Theory] + [InlineData("""[ { "section": "a", "blocks": [ "x" ] }, { "section": "a", "blocks": [ "y" ] } ]""", "/content/1/section")] + [InlineData("""[ { "section": "has space", "blocks": [ "x" ] } ]""", "/content/0/section")] + [InlineData("""[ { "group": [ "x" ] } ]""", "/content/0")] + public void SectionErrors(string content, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(Definition(content))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + // ── cells and control characters ───────────────────────────────────────── + + [Fact] + public void Cell_WithAStyledParagraph_IsStyleAndContent() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_heading, p => { }); + s.Paragraph(_cell, p => { }); + s.Table(_grid, g => g.ParagraphStyle(_cell)); + })); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.Row(r => + { + r.Cell(_heading, "styled"); + r.Cell(cell => cell.ColumnSpan(1).Background(Color.FromHex("EEEEEE")).Paragraph(_heading, "both")); + }); + })); + }); + + string json = TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)).Json; + using JsonDocument document = JsonDocument.Parse(json); + Assert.Equal( + """[{"style":"Heading","content":"styled"},{"background":"#EEEEEE","style":"Heading","content":"both"}]""", + Compact(document.RootElement.GetProperty("content")[0].GetProperty("table")[0].GetProperty("row"))); + AssertRoundTrip(definition); + } + + [Theory] + [InlineData("""[ { "columns": [ 1 ], "table": [ { "row": [ [ "a" ] ] } ] } ]""", "/content/0/table/0/row/0")] + [InlineData("""[ { "columns": [ 1 ], "table": [ { "row": [ { "style": "Heading", "content": [ "a" ] } ] } ] } ]""", "/content/0/table/0/row/0/content")] + [InlineData("""[ { "paragraph": [ "a", { "tab": true } ] } ]""", "/content/0/paragraph/1")] + [InlineData("""[ { "paragraph": [ "a", { "lineBreak": true } ] } ]""", "/content/0/paragraph/1")] + public void RemovedForms_AreErrors(string content, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(Definition(content, ShortStyles))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + [Theory] + [MemberData(nameof(Formats))] + public void TabsAndLineBreaks_AreInTheString(TemplateFormat format) + { + TestDefinition fromCSharp = new TestDefinition(t => t.Content(c => c.Paragraph(x => + { + x.Text("a\tb"); + x.LineBreak(); + x.Text("c"); + x.Tab(); + x.Value(t.Data["v"]); + })), new TemplateIdentity("short", 1)); + + Assert.Equal("a\tb\nc\t{{v}}", ContentOf(fromCSharp).GetString()); + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ "a\tb\nc\t{{v}}" ]""", "{}")); + Assert.Equal(BuilderHarness.Build(fromCSharp, format).ContentHash, BuilderHarness.Build(imported, format).ContentHash); + } + + private static JsonElement ContentOf(ITemplateDefinition definition) + { + string json = TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)).Json; + using JsonDocument document = JsonDocument.Parse(json); + JsonElement block = document.RootElement.GetProperty("content")[0]; + return (block.ValueKind == JsonValueKind.String ? block : block.GetProperty("paragraph")).Clone(); + } + + private static string Compact(JsonElement element) => + JsonSerializer.Serialize(element, new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + + private static void AssertRoundTrip(ITemplateDefinition definition) + { + foreach (TemplateFormat format in BuilderHarness.Formats) + { + BuilderHarness.AssertJsonRoundTrip(definition, BuilderHarness.Build(definition, format), BuilderHarness.Options(format)); + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonStrictTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonStrictTests.cs new file mode 100644 index 00000000..d40bd4a7 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonStrictTests.cs @@ -0,0 +1,156 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// The reader refuses what it used to accept silently (#293, style review A1). +public sealed class JsonStrictTests +{ + private static string Definition(string content, string extra = "") => $$""" + { + "templifyDefinition": 1, + "identity": { "id": "strict", "version": 1 },{{extra}} + "content": {{content}} + } + """; + + [Theory] + [InlineData("""[ "{{order.total:N2}}" ]""", "/content/0")] + [InlineData("""[ "{{order.total:currency:EUR}}" ]""", "/content/0")] + [InlineData("""[ "{{order.date:date}}" ]""", "/content/0")] + [InlineData("""[ "{{order.total:number}}" ]""", "/content/0")] + [InlineData("""[ "{{(order.paid):janein}}" ]""", "/content/0")] + [InlineData("""[ { "paragraph": [ { "text": "{{order.total:money}}", "style": "Strong" } ] } ]""", "/content/0/paragraph/0")] + public void UnknownValueFormats_AreErrors(string content, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => + TemplateJson.Import(Definition(content, """ "styles": { "character": { "Strong": { "name": "Strong Text", "bold": true } } },"""))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + Assert.Contains("format", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("{{order.total:currency}}")] + [InlineData("{{order.total:number:N2}}")] + [InlineData("{{order.date:date:d. MMMM yyyy}}")] + [InlineData("{{order.tags:join}}")] + [InlineData("{{order.tags:join:\\\" · \\\"}}")] + [InlineData("{{order.lines:join:name:\\\"; \\\"}}")] + [InlineData("{{order.paid:yesno}} {{order.paid:checkbox}} {{order.paid:check}} {{order.name:uppercase}} {{order.note:raw}}")] + [InlineData("{{(order.paid):truefalse}}")] + public void KnownValueFormats_AreAccepted(string text) + { + TemplateJson.Import(Definition("[ \"" + text + "\" ]")); + } + + [Fact] + public void HostFormats_CanBeAdded() + { + TemplateJson.Import(Definition("""[ "{{order.paid:janein}}" ]"""), new TemplateJsonImportOptions { ValueFormats = ["janein"] }); + } + + [Fact] + public void PaddingWithFiveValues_IsAnError() + { + // Since #296 one to four values (CSS order) are padding per side; five are not padding. + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(Definition( + """[ "x" ]""", + """ "styles": { "box": { "Panel": { "padding": "1pt 2pt 30pt 40pt 5pt" } } },"""))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal("/styles/box/Panel/padding", error.Location); + } + + [Fact] + public void LoopVariableShadowingItsOwnRoot_IsAnError() + { + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["order"]["lines"], "order", (item, b) => b.Paragraph(item["name"])))), TemplateFormat.Docx)); + + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ { "forEach": "order.lines", "as": "order", "body": [ "{{order.name}}" ] } ]""")); + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build(imported, TemplateFormat.Docx)).Errors); + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/0", error.Location); + } + + [Theory] + [MemberData(nameof(Formats))] + public void DoubleEquals_IsEquals(TemplateFormat format) + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ { "if": "order.status == \"paid\"", "then": [ "paid" ] } ]""")); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, """{ "order": { "status": "paid" } }"""); + + Assert.Equal(new[] { "paid" }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Contains("\"order.status = \\\"paid\\\"\"", TemplateJson.Export(imported, BuilderHarness.Options(format)).Json, StringComparison.Ordinal); + } + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + [Fact] + public void SchemaKey_IsIgnored_ComponentsKey_IsReserved() + { + TemplateJson.Import(Definition("""[ "x" ]""", """ "$schema": "https://example.invalid/templify-definition.json",""")); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => + TemplateJson.Import(Definition("""[ "x" ]""", """ "components": {},"""))).Errors); + Assert.Equal("TB9200", error.Code); + Assert.Equal("/components", error.Location); + Assert.Contains("reserved", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void ExportSelfCheck_NamesTheFirstDifference() + { + ITextCatalog catalog = TextCatalog.FromDictionary(new Dictionary> + { + ["pages"] = new Dictionary { ["en"] = "Page {0}" }, + }); + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(string.Format(System.Globalization.CultureInfo.InvariantCulture, t.Texts["pages"], 5)))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => + TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx) with { Texts = catalog })).Errors); + + Assert.Equal("TB9204", error.Code); + Assert.Contains("Page 5", error.Message, StringComparison.Ordinal); + Assert.Contains("Page {0}", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TextsKey_MissingALanguageTheOthersHave_IsAnError() + { + string json = Definition( + """[ "[[title]] [[note]]" ]""", + """ "texts": { "title": { "de": "Titel", "en": "Title" }, "note": { "de": "Hinweis" } },"""); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal("/texts/note", error.Location); + Assert.Contains("'en'", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TextsKey_WithoutARegionalVariant_IsCoveredByItsParent_ButNotTheOtherWayRound() + { + string covered = Definition("""[ "[[a]] [[b]]" ]""", """ "texts": { "a": { "de": "A", "de-CH": "A!" }, "b": { "de": "B" } },"""); + string notCovered = Definition("""[ "[[a]] [[b]]" ]""", """ "texts": { "a": { "de": "A" }, "b": { "de-CH": "B" } },"""); + + Assert.NotNull(TemplateJson.Import(covered)); + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(notCovered)).Errors); + Assert.Equal("/texts/b", error.Location); + } + + [Fact] + public void Texts_AllInOneLanguage_AreAccepted() + { + string json = Definition("""[ "[[title]]" ]""", """ "texts": { "title": { "de": "Titel" } },"""); + + Assert.NotNull(TemplateJson.Import(json)); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonTextKeyTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonTextKeyTests.cs new file mode 100644 index 00000000..f2544c40 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonTextKeyTests.cs @@ -0,0 +1,301 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.Json; +using System.Xml.Linq; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Text keys in JSON definitions: one JSON for every language (#274). +public sealed class JsonTextKeyTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + + public static TheoryData FormatsAndLanguages => new TheoryData + { + { TemplateFormat.Docx, "de-DE" }, { TemplateFormat.Odt, "de-DE" }, { TemplateFormat.Docx, "en-GB" }, { TemplateFormat.Odt, "en-GB" }, + }; + + private static ITextCatalog Catalog { get; } = TextCatalog.FromDictionary(new Dictionary> + { + ["hello"] = new Dictionary { ["de"] = "Hallo", ["en"] = "Hello" }, + ["fmt"] = new Dictionary { ["de"] = "d. MMMM yyyy", ["en"] = "d MMMM yyyy" }, + ["title"] = new Dictionary { ["de"] = "Titel", ["en"] = "Title" }, + ["logo"] = new Dictionary { ["de"] = "Firmenlogo", ["en"] = "Company logo" }, + ["printed"] = new Dictionary { ["de"] = "Gedruckt", ["en"] = "Printed" }, + ["braces"] = new Dictionary { ["de"] = "a {{x}}", ["en"] = "a {{x}}" }, + }); + + private static TemplateBuildOptions Options(TemplateFormat format, string language, ITextCatalog? texts = null) => + new TemplateBuildOptions { Format = format, Language = CultureInfo.GetCultureInfo(language), Texts = texts ?? Catalog }; + + private static byte[] Png() => Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="); + + private static TestDefinition Translated() => new TestDefinition(t => + { + TemplateTexts texts = t.Texts; + t.Properties(p => p.Title(texts["title"])); + t.Content(c => + { + c.Paragraph(x => + { + x.Text(texts["hello"] + " "); + x.Value(t.Data["date"], ValueFormat.Date(texts["fmt"])); + }); + c.Image(ImageSource.Png(Png()), texts["logo"], ImageFit.Exact(10.Pt(), 10.Pt())); + c.Raw(new RawBlock + { + Docx = _ => new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", texts["printed"]))), + Odt = _ => new XElement(_text + "p", texts["printed"]), + }); + }); + }); + + private static JsonElement Root(string json) => JsonDocument.Parse(json).RootElement; + + [Fact] + public void Export_WritesKeys_AndNoLanguage() + { + TemplateJsonDocument de = TemplateJson.Export(Translated(), Options(TemplateFormat.Docx, "de-DE")); + TemplateJsonDocument en = TemplateJson.Export(Translated(), Options(TemplateFormat.Odt, "en-GB")); + + Assert.Equal(de.Json, en.Json); + JsonElement root = Root(de.Json); + Assert.False(root.TryGetProperty("language", out _)); + Assert.Equal("[[title]]", root.GetProperty("properties").GetProperty("title").GetString()); + Assert.Contains("\"[[hello]] {{date:date:[[fmt]]}}\"", de.Json, StringComparison.Ordinal); + Assert.Contains("\"alt\": \"[[logo]]\"", de.Json, StringComparison.Ordinal); + Assert.Contains("[[printed]]", root.GetProperty("content")[2].GetProperty("raw").GetProperty("docx").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Hallo", de.Json, StringComparison.Ordinal); + Assert.DoesNotContain("", de.Json, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(FormatsAndLanguages))] + public void Import_TranslatesFromTheCatalog_SameBytesAsCSharp(TemplateFormat format, string language) + { + TemplateJsonDocument exported = TemplateJson.Export(Translated(), Options(TemplateFormat.Docx, "en-US")); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets, AllowRawXml = true }); + + Assert.Equal(TemplateBuilder.Build(Translated(), Options(format, language)).ContentHash, TemplateBuilder.Build(imported, Options(format, language)).ContentHash); + Assert.Equal(exported.Json, TemplateJson.Export(imported, Options(format, language)).Json); + } + + [Fact] + public void Import_MissingTranslation_IsTB5001() + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ "[[hello]] [[nope]]" ]""")); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateBuilder.Build(imported, Options(TemplateFormat.Docx, "de-DE"))).Errors); + Assert.Equal("TB5001", error.Code); + Assert.Contains("nope", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("""[ "a [[bad key]]" ]""", "/content/0")] + [InlineData("""[ { "paragraph": [ "ok", "[[unclosed" ] } ]""", "/content/0/paragraph/1")] + public void Import_MalformedKey_IsTB9200(string content, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(Definition(content))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + [Fact] + public void Import_LoneClosingBrackets_AreText() + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ "a ]] b" ]""")); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, TemplateFormat.Docx, "{}"); + Assert.Equal(new[] { "a ]] b" }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)); + } + + [Fact] + public void Import_TranslationWithBraces_IsRejectedAtTheString() + { + ITemplateDefinition imported = TemplateJson.Import(Definition("""[ "ok", "[[braces]]" ]""")); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateBuilder.Build(imported, Options(TemplateFormat.Docx, "de-DE"))).Errors); + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/1", error.Location); + } + + [Fact] + public void Export_LiteralBrackets_IsTB9204() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Paragraph("fine"); + c.Paragraph("a [[b"); + })); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export(definition, Options(TemplateFormat.Docx, "en-US"))).Errors); + Assert.Equal("TB9204", error.Code); + Assert.Equal("/content/1", error.Location); + } + + [Fact] + public void Export_KeyOutsideTheSyntax_IsTB9204() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(t.Texts["two words"]))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export(definition, Options(TemplateFormat.Docx, "en-US"))).Errors); + Assert.Equal("TB9204", error.Code); + Assert.Contains("two words", error.Message, StringComparison.Ordinal); + } + + // ── embedded texts ─────────────────────────────────────────────────────── + + private static readonly TemplateJsonExportOptions _bothLanguages = new TemplateJsonExportOptions + { + TextLanguages = [CultureInfo.GetCultureInfo("de"), CultureInfo.GetCultureInfo("en")], + }; + + [Fact] + public void Export_WithTextLanguages_WritesTextsInFirstUseOrder() + { + TemplateJsonDocument exported = TemplateJson.Export(Translated(), Options(TemplateFormat.Docx, "en-US"), _bothLanguages); + JsonElement texts = Root(exported.Json).GetProperty("texts"); + + // Key first: one wording change is one edit at /texts/ (style review A8). + Assert.Equal(new[] { "title", "hello", "fmt", "logo", "printed" }, texts.EnumerateObject().Select(p => p.Name)); + Assert.Equal(new[] { "de", "en" }, texts.GetProperty("hello").EnumerateObject().Select(p => p.Name)); + Assert.Equal("Hallo", texts.GetProperty("hello").GetProperty("de").GetString()); + Assert.Equal("Company logo", texts.GetProperty("logo").GetProperty("en").GetString()); + Assert.Equal(new[] { "templifyDefinition", "identity", "texts" }, Root(exported.Json).EnumerateObject().Select(p => p.Name).Take(3)); + } + + [Theory] + [MemberData(nameof(FormatsAndLanguages))] + public void Import_WithEmbeddedTexts_NeedsNoCatalog(TemplateFormat format, string language) + { + TemplateJsonDocument exported = TemplateJson.Export(Translated(), Options(TemplateFormat.Docx, "en-US"), _bothLanguages); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets, AllowRawXml = true }); + + Assert.Equal( + TemplateBuilder.Build(Translated(), Options(format, language)).ContentHash, + TemplateBuilder.Build(imported, Options(format, language, TextCatalog.Empty)).ContentHash); + } + + [Fact] + public void EmbeddedTexts_WinOverTheCatalog_WhichFillsGaps() + { + ITemplateDefinition imported = TemplateJson.Import(""" + { + "templifyDefinition": 1, + "identity": { "id": "keys", "version": 1 }, + "texts": { "hello": { "de": "Servus" } }, + "content": [ "[[hello]], [[title]]" ] + } + """); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, Options(TemplateFormat.Docx, "de-DE"), "{}"); + Assert.Equal(new[] { "Servus, Titel" }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)); + } + + [Fact] + public void ReExport_KeepsTheTexts() + { + TemplateJsonDocument exported = TemplateJson.Export(Translated(), Options(TemplateFormat.Docx, "en-US"), _bothLanguages); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets, AllowRawXml = true }); + + Assert.Equal(exported.Json, TemplateJson.Export(imported, Options(TemplateFormat.Odt, "de-DE", TextCatalog.Empty)).Json); + } + + [Theory] + [InlineData("""{ "a": { "de": 1 } }""", "/texts/a/de")] + [InlineData("""{ "a": [ "de" ] }""", "/texts/a")] + [InlineData("""[ "de" ]""", "/texts")] + public void MalformedTexts_AreTB9200(string texts, string location) + { + string json = Definition("""[ "x" ]""").Replace("\"content\"", "\"texts\": " + texts + ", \"content\"", StringComparison.Ordinal); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors); + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + // ── final review fixes ─────────────────────────────────────────────────── + + private static ITextCatalog Tricky { get; } = TextCatalog.FromDictionary(new Dictionary> + { + ["a"] = new Dictionary { ["de"] = "A", ["en"] = "A" }, + ["amp"] = new Dictionary { ["de"] = "Lieferung & Montage <", ["en"] = "Delivery & assembly" }, + ["quote"] = new Dictionary { ["de"] = "say \"hi\"", ["en"] = "say \"hi\"" }, + ["pages"] = new Dictionary { ["de"] = "Seite {0}", ["en"] = "Page {0}" }, + }); + + [Fact] + public void Export_BracketBeforeAKey_IsTB9204() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph("[" + t.Texts["a"] + "]"))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export(definition, Options(TemplateFormat.Docx, "de-DE", Tricky))).Errors); + Assert.Equal("TB9204", error.Code); + } + + [Theory] + [MemberData(nameof(FormatsAndLanguages))] + public void RawXml_TranslationWithXmlCharacters_RoundTrips(TemplateFormat format, string language) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(new RawBlock + { + Docx = _ => new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", t.Texts["amp"]))), + Odt = _ => new XElement(_text + "p", new XAttribute(_text + "style-name", t.Texts["amp"]), t.Texts["amp"]), + }))); + TemplateJsonDocument exported = TemplateJson.Export(definition, Options(format, language, Tricky)); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { AllowRawXml = true }); + + Assert.Equal(TemplateBuilder.Build(definition, Options(format, language, Tricky)).ContentHash, TemplateBuilder.Build(imported, Options(format, language, Tricky)).ContentHash); + } + + [Fact] + public void Export_TextChangedByCode_IsTB9204() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(string.Format(CultureInfo.InvariantCulture, t.Texts["pages"], 5)))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export(definition, Options(TemplateFormat.Docx, "de-DE", Tricky))).Errors); + Assert.Equal("TB9204", error.Code); + Assert.Contains("de-DE", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Export_TranslationThatChangesAQuotedValue_IsTB9204() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => x.Value(t.Data["tags"], ValueFormat.Join(separator: t.Texts["quote"]))))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export(definition, Options(TemplateFormat.Docx, "de-DE", Tricky))).Errors); + Assert.Equal("TB9204", error.Code); + } + + [Fact] + public void ReExport_WithoutTextLanguages_KeepsTheSectionAsImported() + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "keys", "version": 1 }, + "texts": { "hello": { "de": "Servus", "de-CH": "Grüezi" }, "unused": { "de": "U" } }, + "content": [ "[[hello]] [[title]]" ] + } + """; + ITemplateDefinition imported = TemplateJson.Import(json); + + JsonElement texts = Root(TemplateJson.Export(imported, Options(TemplateFormat.Docx, "de-DE")).Json).GetProperty("texts"); + + Assert.Equal("""{"hello":{"de":"Servus","de-CH":"Grüezi"},"unused":{"de":"U"}}""", JsonSerializer.Serialize(texts, new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })); + } + + private static string Definition(string content) => $$""" + { + "templifyDefinition": 1, + "identity": { "id": "keys", "version": 1 }, + "content": {{content}} + } + """; +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonThemeTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonThemeTests.cs new file mode 100644 index 00000000..5053da44 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonThemeTests.cs @@ -0,0 +1,160 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Theme tokens and the context components see (#293, style review A5; port finding F5). +public sealed class JsonThemeTests +{ + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading", "Heading Style"); + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + private static readonly Color _accent = Color.Token("accent", Color.FromHex("1F4E79")); + private static readonly Color _line = Color.Token("line", Color.FromHex("D4D4D4")); + private static readonly FontFace _headingFont = FontFace.Token("heading", new FontFace("Liberation Serif")); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Themed() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_heading, p => p.Font(_headingFont).Color(_accent)); + s.Table(_grid, g => g.HeaderRule(1.Pt(), _accent).RowRule(0.5.Pt(), _line)); + })); + t.Content(c => + { + c.Paragraph(_heading, "Title"); + c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => cell.Background(_line).Paragraph("x"))); + }); + c.Rule(0.5.Pt(), _line); + }); + }); + + private static JsonElement Root(string json) => JsonDocument.Parse(json).RootElement; + + private static string Compact(JsonElement element) => JsonSerializer.Serialize(element); + + [Fact] + public void Export_WritesTokens_AndATheme() + { + string json = TemplateJson.Export(Themed(), BuilderHarness.Options(TemplateFormat.Docx)).Json; + JsonElement root = Root(json); + + Assert.Equal("""{"colors":{"accent":"#1F4E79","line":"#D4D4D4"},"fonts":{"heading":"Liberation Serif"}}""", Compact(root.GetProperty("theme"))); + JsonElement heading = root.GetProperty("styles").GetProperty("paragraph").GetProperty("Heading"); + Assert.Equal("$heading", heading.GetProperty("font").GetString()); + Assert.Equal("$accent", heading.GetProperty("color").GetString()); + JsonElement grid = root.GetProperty("styles").GetProperty("table").GetProperty("Grid"); + Assert.Equal("1pt $accent", grid.GetProperty("headerRule").GetString()); + Assert.Contains("\"background\": \"$line\"", json, StringComparison.Ordinal); + Assert.Contains("\"line\": \"0.5pt $line\"", json, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Import_ResolvesTokens_SameBytes(TemplateFormat format) + { + TemplateJsonDocument exported = TemplateJson.Export(Themed(), BuilderHarness.Options(format)); + ITemplateDefinition imported = TemplateJson.Import(exported.Json); + + Assert.Equal(BuilderHarness.Build(Themed(), format).ContentHash, BuilderHarness.Build(imported, format).ContentHash); + Assert.Equal(exported.Json, TemplateJson.Export(imported, BuilderHarness.Options(format)).Json); + } + + [Fact] + public void HostTheme_OverridesTheFile() + { + string json = TemplateJson.Export(Themed(), BuilderHarness.Options(TemplateFormat.Docx)).Json; + ITemplateDefinition imported = TemplateJson.Import(json, new TemplateJsonImportOptions + { + Theme = new Dictionary { ["accent"] = "#00A000", ["heading"] = "Liberation Sans" }, + }); + + GeneratedTemplate template = BuilderHarness.Build(imported, TemplateFormat.Docx); + string styles = BuilderHarness.ReadXml(template.Content.ToArray(), "word/styles.xml").ToString(); + Assert.Contains("00A000", styles, StringComparison.Ordinal); + Assert.DoesNotContain("1F4E79", styles, StringComparison.Ordinal); + Assert.Contains("Liberation Sans", styles, StringComparison.Ordinal); + } + + [Theory] + [InlineData("""{ "styles": { "paragraph": { "H": { "name": "H", "color": "$nope" } } } }""", "/styles/paragraph/H/color")] + [InlineData("""{ "theme": { "colors": { "a": "blue" } } }""", "/theme/colors/a")] + [InlineData("""{ "theme": { "colors": { "1a": "#000000" } } }""", "/theme/colors/1a")] + public void ThemeErrors(string extra, string location) + { + string body = extra.Trim()[1..^1]; + string json = $$"""{ "templifyDefinition": 1, "identity": { "id": "t", "version": 1 }, {{body}}, "content": [ "x" ] }"""; + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors); + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + [Fact] + public void Token_RejectsBadNames() + { + Assert.Throws(() => Color.Token("has space", Color.FromHex("000000"))); + Assert.Throws(() => FontFace.Token("", new FontFace("Arial"))); + } + + // ── component context ──────────────────────────────────────────────────── + + private sealed record Brand(string Greeting); + + private sealed class Greeting : ITemplateComponent + { + public void Compose(BlockComposer c) => c.Paragraph(c.Shared().Greeting + " " + c.Texts["name"]); + } + + [Fact] + public void Components_SeeTheTextsAndSharedObjects() + { + ITextCatalog catalog = TextCatalog.FromDictionary(new Dictionary> + { + ["name"] = new Dictionary { ["en"] = "World" }, + }); + TestDefinition definition = new TestDefinition(t => + { + t.Share(new Brand("Hello")); + t.Content(c => c.Component(new Greeting())); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, BuilderHarness.Options(TemplateFormat.Docx) with { Texts = catalog }, "{}"); + + Assert.Equal(new[] { "Hello World" }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Component(new Greeting()))), TemplateFormat.Docx)); + } + + [Fact] + public void RegisteredComponent_ReadingSharedObjects_Exports_AndImportsWithTheHostsObjects() + { + ITextCatalog catalog = TextCatalog.FromDictionary(new Dictionary> + { + ["name"] = new Dictionary { ["en"] = "World" }, + }); + TestDefinition definition = new TestDefinition(t => + { + t.Share(new Brand("Hello")); + t.Content(c => c.Component(new Greeting())); + }); + ComponentCatalog components = new ComponentCatalog().Register("greeting"); + TemplateBuildOptions options = BuilderHarness.Options(TemplateFormat.Docx) with { Texts = catalog }; + + TemplateJsonDocument exported = TemplateJson.Export(definition, options, new TemplateJsonExportOptions { Components = components, TextLanguages = [CultureInfo.GetCultureInfo("en")] }); + + // The component's own text is in the JSON's texts, so the JSON builds without the host's catalog. + Assert.Contains("\"component\": \"greeting\"", exported.Json, StringComparison.Ordinal); + Assert.Contains("\"texts\": {\"name\": {\"en\": \"World\"}}", exported.Json, StringComparison.Ordinal); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Components = components, Shared = [new Brand("Hello")] }); + Assert.Equal(TemplateBuilder.Build(definition, options).ContentHash, TemplateBuilder.Build(imported, options with { Texts = TextCatalog.Empty }).ContentHash); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonValuesTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonValuesTests.cs new file mode 100644 index 00000000..758b2600 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonValuesTests.cs @@ -0,0 +1,119 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Model; + +namespace TriasDev.Templify.Builder.Tests; + +/// How values are written in JSON definitions (#274). +public sealed class JsonValuesTests +{ + public static TheoryData Lengths => new TheoryData + { + { 10.Pt(), "10pt" }, + { 10.5.Pt(), "10.5pt" }, + { 0.Pt(), "0pt" }, + { (-6).Mm(), "-6mm" }, + { 25.Mm(), "25mm" }, + { 12.5.Mm(), "12.5mm" }, + { Length.FromPoints(10.123), "10.123pt" }, + }; + + [Theory] + [MemberData(nameof(Lengths))] + public void Length_IsWrittenInTheShortestExactForm(Length value, string text) + { + Assert.Equal(text, JsonValues.Length(value)); + Assert.True(JsonValues.TryLength(text, out Length back)); + Assert.Equal(value, back); + } + + [Theory] + [InlineData("1in", 72.0)] + [InlineData("1cm", 28.346)] + [InlineData("2.5pt", 2.5)] + public void Length_ReadsOtherUnits(string text, double points) + { + Assert.True(JsonValues.TryLength(text, out Length value)); + Assert.Equal(points, value.Points, 3); + } + + [Theory] + [InlineData("12")] + [InlineData("pt")] + [InlineData("1,5pt")] + [InlineData("10 pt")] + [InlineData("")] + public void Length_RejectsMalformedText(string text) + { + Assert.False(JsonValues.TryLength(text, out _)); + } + + [Fact] + public void Color_IsUpperCaseHex_AndReadsEitherCase() + { + Assert.Equal("#1F4E79", JsonValues.Color(Color.FromHex("1f4e79"))); + Assert.True(JsonValues.TryColor("#abcdef", out Color color)); + Assert.Equal(Color.FromHex("ABCDEF"), color); + Assert.False(JsonValues.TryColor("#12345", out _)); + Assert.False(JsonValues.TryColor("123456", out _)); + } + + [Fact] + public void PageSize_ByName() + { + Assert.Equal("A4", JsonValues.PageSizeName(PageSize.A4)); + Assert.Equal("Letter", JsonValues.PageSizeName(PageSize.Letter)); + Assert.Null(JsonValues.PageSizeName(new PageSize(100.Mm(), 100.Mm()))); + Assert.True(JsonValues.TryPageSize("A5", out PageSize? size)); + Assert.Equal(PageSize.A5, size); + Assert.False(JsonValues.TryPageSize("A3", out _)); + } + + [Fact] + public void Border_IsWidthAndColour() + { + BorderLine line = new BorderLine(0.5.Pt(), Color.FromHex("D4D4D4")); + + Assert.Equal("0.5pt #D4D4D4", JsonValues.Border(line)); + Assert.True(JsonValues.TryBorder("0.5pt #d4d4d4", out BorderLine? back)); + Assert.Equal(line, back); + Assert.False(JsonValues.TryBorder("0.5pt", out _)); + } + + [Theory] + [InlineData(3, 3, 3, 3, "3pt")] + [InlineData(3, 5, 3, 5, "3pt 5pt")] + [InlineData(1, 2, 3, 4, "1pt 2pt 3pt 4pt")] + public void Box_IsShortest(double top, double right, double bottom, double left, string text) + { + Assert.Equal(text, JsonValues.Box(top.Pt(), right.Pt(), bottom.Pt(), left.Pt())); + Assert.True(JsonValues.TryBox(text, out (Length Top, Length Right, Length Bottom, Length Left) box)); + Assert.Equal((top.Pt(), right.Pt(), bottom.Pt(), left.Pt()), box); + Assert.True(JsonValues.TryBox("1pt 2pt 3pt", out (Length Top, Length Right, Length Bottom, Length Left) three)); + Assert.Equal((1.Pt(), 2.Pt(), 3.Pt(), 2.Pt()), three); + Assert.False(JsonValues.TryBox("1pt 2pt 3pt 4pt 5pt", out _)); + } + + [Fact] + public void Values_DoNotDependOnTheCurrentCulture() + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + foreach (string culture in new[] { "tr-TR", "ar-SA", "de-DE" }) + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + Assert.Equal("10.5pt", JsonValues.Length(10.5.Pt())); + Assert.True(JsonValues.TryLength("12.5mm", out Length value)); + Assert.Equal(12.5.Mm(), value); + } + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/JsonVocabularyTests.cs b/tests/TriasDev.Templify.Builder.Tests/JsonVocabularyTests.cs new file mode 100644 index 00000000..3980fd38 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/JsonVocabularyTests.cs @@ -0,0 +1,223 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #274: the vocabulary an agent reads (Describe) matches what the JSON reader accepts. +public sealed class JsonVocabularyTests +{ + private const string AssetKey = "sha256:test-logo"; + private const string FontKey = "sha256:test-font"; + + public static TheoryData Constructs => new TheoryData(JsonVocabulary.All.Select(c => c.Name)); + + internal static TemplateJsonImportOptions ImportOptions => new TemplateJsonImportOptions + { + Assets = new Dictionary { [AssetKey] = ImageTests.Png, [FontKey] = FontBytes() }, + AllowRawXml = true, + Components = SampleRunner.Components, + Shared = [BrandTheme.CreateDefault()], + }; + + private static byte[] FontBytes() + { + using Stream stream = typeof(JsonVocabularyTests).Assembly.GetManifestResourceStream("TemplifyEmbedTest-Regular.ttf")!; + using MemoryStream copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + /// A definition with the construct's example (or ) placed where it is written. + internal static string Place(Construct construct, JsonNode value) + { + if (construct.Name == "definition") + { + return value.ToJsonString(); + } + + JsonObject root = JsonNode.Parse($$""" + { + "templifyDefinition": 1, + "identity": { "id": "vocabulary", "version": 1 }, + "assets": { "logo": "{{AssetKey}}", "bodyFont": "{{FontKey}}" }, + "texts": { "title": { "en": "Title" }, "customer": { "en": "Customer" }, "footer": { "en": "Footer" } }, + "theme": { "colors": { "accent": "#1F4E79" }, "fonts": { "body": "Liberation Sans" } }, + "styles": { + "paragraph": { + "Body": { "name": "Body Copy" }, + "Heading": { "name": "Heading Line", "outlineLevel": 1 }, + "TocPart": { "name": "Contents Part" } + }, + "character": { "Strong": { "name": "Strong Text", "bold": true } }, + "table": { "Grid": { "rowRule": "0.5pt #D4D4D4" } }, + "box": { "Panel": { "border": "1pt #C0C0C0" } }, + "list": { "Bullets": { "itemStyle": "Body", "levels": [ + { "level": 0, "bullet": "•", "indent": "6mm", "hanging": "4mm" }, + { "level": 1, "bullet": "–", "indent": "12mm", "hanging": "4mm" } ] } } + }, + "content": [] + } + """)!.AsObject(); + JsonObject styles = root["styles"]!.AsObject(); + JsonArray content = root["content"]!.AsArray(); + JsonNode Wrap(string json) => JsonNode.Parse(json.Replace("@", value.ToJsonString(), StringComparison.Ordinal))!; + switch (construct.Name) + { + case "properties": + root["properties"] = value; + break; + case "theme": + root["theme"] = value; + break; + case "font": + styles["defaults"] = Wrap("""{ "font": @ }"""); + break; + case "styles": + root["styles"] = value; + break; + case "defaults": + styles["defaults"] = value; + break; + case "paragraphStyle": + styles["paragraph"]!["Placed"] = value; + break; + case "characterStyle": + styles["character"]!["Placed"] = value; + break; + case "tableStyle": + styles["table"]!["Placed"] = value; + break; + case "boxStyle": + styles["box"]!["Placed"] = value; + break; + case "listStyle": + styles["list"]!["Placed"] = value; + break; + case "listLevel": + styles["list"]!["Placed"] = Wrap("""{ "levels": [ @ ] }"""); + break; + case "edges": + styles["table"]!["Placed"] = Wrap("""{ "outerBorder": @ }"""); + break; + case "page": + root["page"] = value; + break; + case "pageSize": + root["page"] = Wrap("""{ "size": @ }"""); + break; + case "firstPage": + root["page"] = Wrap("""{ "firstPage": @ }"""); + break; + case "branch": + content.Add(Wrap("""{ "if": "flag", "then": [ "x" ], "elseIf": [ @ ] }""")); + break; + case "ruleLine": + content.Add(Wrap("""{ "rule": @ }""")); + break; + case "tocOptions": + content.Add(Wrap("""{ "toc": @ }""")); + break; + case "rawXml": + content.Add(Wrap("""{ "raw": @ }""")); + break; + case "rawCondition": + content.Add(Wrap("""{ "if": @, "then": [ "x" ] }""")); + break; + default: + content.Add(construct.Group switch + { + "block" => value, + "item" => Wrap("""{ "style": "Bullets", "list": [ @ ] }"""), + "row" => Wrap("""{ "columns": [ 1, 1 ], "table": [ @ ] }"""), + "cell" => Wrap("""{ "columns": [ 1, 1 ], "table": [ { "row": [ @ ] } ] }"""), + "inline" => Wrap("""{ "paragraph": [ @ ] }"""), + _ => throw new InvalidOperationException($"No place for {construct.Name}."), + }); + break; + } + + return root.ToJsonString(); + } + + private static Construct Find(string name) => JsonVocabulary.All.Single(c => c.Name == name); + + [Theory] + [MemberData(nameof(Constructs))] + public void EveryConstruct_ExampleImportsAndBuilds(string name) + { + Construct construct = Find(name); + ITemplateDefinition definition = TemplateJson.Import(Place(construct, JsonNode.Parse(construct.Example)!), ImportOptions); + TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Constructs))] + public void EveryConstruct_KeysMatchTheReader(string name) + { + Construct construct = Find(name); + JsonObject example = JsonNode.Parse(construct.Example)!.AsObject(); + example["zzzUnknown"] = 1; + TemplateBuildException error = Assert.Throws(() => TemplateJson.Import(Place(construct, example), ImportOptions)); + string message = Assert.Single(error.Errors, e => e.Message.Contains("'zzzUnknown'", StringComparison.Ordinal)).Message; + string allowed = message[(message.IndexOf("allowed here: ", StringComparison.Ordinal) + "allowed here: ".Length)..].TrimEnd('.'); + Assert.Equal(allowed.Split(", ").Order(StringComparer.Ordinal), construct.Keys.Select(k => k.Name).Order(StringComparer.Ordinal)); + } + + [Fact] + public void ConstructNames_AreUnique() => + Assert.Equal(JsonVocabulary.All.Count, JsonVocabulary.All.Select(c => c.Name).Distinct().Count()); + + [Fact] + public void Describe_ListsConstructsAndValues() + { + using JsonDocument description = JsonDocument.Parse(TemplateJson.Describe()); + JsonElement root = description.RootElement; + Assert.Equal(1, root.GetProperty("formatVersion").GetInt32()); + JsonElement table = root.GetProperty("constructs").EnumerateArray().Single(c => c.GetProperty("name").GetString() == "table"); + Assert.Equal("block", table.GetProperty("in").GetString()); + Assert.Equal("table", table.GetProperty("key").GetString()); + Assert.Contains(table.GetProperty("keys").EnumerateArray(), k => k.GetProperty("name").GetString() == "columns" && k.GetProperty("required").GetBoolean()); + Assert.Equal(JsonValueKind.Object, table.GetProperty("example").ValueKind); + Assert.True(root.GetProperty("values").TryGetProperty("condition", out _)); + Assert.False(root.TryGetProperty("components", out _)); + Assert.False(root.TryGetProperty("data", out _)); + } + + [Fact] + public void Describe_StartsWithAnIndexOfConstructsByGroup() + { + using JsonDocument description = JsonDocument.Parse(TemplateJson.Describe()); + JsonElement index = description.RootElement.GetProperty("index"); + Assert.Contains("table", index.GetProperty("block").EnumerateArray().Select(e => e.GetString())); + Assert.Contains("forEachRow", index.GetProperty("row").EnumerateArray().Select(e => e.GetString())); + Assert.Equal(JsonVocabulary.All.Count, index.EnumerateObject().Sum(g => g.Value.GetArrayLength())); + } + + [Fact] + public void Describe_ListsRegisteredComponents() + { + using JsonDocument description = JsonDocument.Parse(TemplateJson.Describe(new TemplateJsonDescribeOptions { Components = SampleRunner.Components })); + JsonElement[] components = description.RootElement.GetProperty("components").EnumerateArray().ToArray(); + Assert.Equal(new[] { "address", "terms" }, components.Select(c => c.GetProperty("name").GetString())); + JsonElement parameter = Assert.Single(components[0].GetProperty("parameters").EnumerateArray()); + Assert.Equal(("address", "path"), (parameter.GetProperty("name").GetString(), parameter.GetProperty("type").GetString())); + Assert.Empty(components[1].GetProperty("parameters").EnumerateArray()); + } + + [Fact] + public void Describe_IncludesDataWhenGiven() + { + using JsonDocument description = JsonDocument.Parse(TemplateJson.Describe(new TemplateJsonDescribeOptions { Data = DataCatalog.From() })); + Assert.Contains(description.RootElement.GetProperty("data").GetProperty("paths").EnumerateArray(), p => p.GetProperty("path").GetString() == "order.customer.name"); + } + + [Fact] + public void Describe_IsDeterministic() => + Assert.Equal(TemplateJson.Describe(new TemplateJsonDescribeOptions { Components = SampleRunner.Components }), TemplateJson.Describe(new TemplateJsonDescribeOptions { Components = SampleRunner.Components })); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ListTests.cs b/tests/TriasDev.Templify.Builder.Tests/ListTests.cs new file mode 100644 index 00000000..0053a3b3 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ListTests.cs @@ -0,0 +1,222 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed partial class ListTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly ListStyleKey _bullets = new ListStyleKey("Bullets"); + private static readonly ParagraphStyleKey _item = new ParagraphStyleKey("ListItem", "List Item"); + + private static TestDefinition Measures() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_item, p => p.SpaceAfter(2.Pt())); + s.List(_bullets, l => l + .Level(0, "•", 6.Mm(), 4.Mm()) + .Level(1, "–", 12.Mm(), 4.Mm()) + .ItemStyle(_item)); + })); + t.Content(c => + { + c.Paragraph("Measures"); + c.List(_bullets, l => + { + l.Item("General"); + l.ForEach(t.Data["measures"], "measure", (measure, ml) => + { + ml.Item(measure["title"]); + ml.ForEach(measure["requirements"], "req", (req, rl) => rl.Item(1, x => + { + x.Value(req.Self); + x.Text(" ("); + x.Value(measure["title"]); + x.Text(")"); + })); + ml.If(measure["optional"], o => o.Item(1, "optional")).Else(o => o.Item(1, "mandatory")); + }); + }); + c.Paragraph("after"); + }); + }); + + private const string Json = """ + { + "measures": [ + { "title": "Encryption", "requirements": [ "at rest", "in transit" ], "optional": false }, + { "title": "Training", "requirements": [ "yearly" ], "optional": true } + ] + } + """; + + private static readonly string[] _expected = + { + "Measures", "General", "Encryption", "at rest (Encryption)", "in transit (Encryption)", "mandatory", + "Training", "yearly (Training)", "optional", "after", + }; + + [Theory] + [MemberData(nameof(Formats))] + public void List_WithLoopsAndConditions_IsFilled(TemplateFormat format) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Measures(), format, Json); + + Assert.Equal(_expected, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void Docx_UsesNumberingWithBulletLevels() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Measures(), TemplateFormat.Docx, Json); + byte[] package = template.Content.ToArray(); + + XElement numbering = BuilderHarness.ReadXml(package, "word/numbering.xml").Root!; + List levels = numbering.Descendants(_w + "lvl").ToList(); + Assert.Equal(new[] { "•", "–" }, levels.Select(l => l.Element(_w + "lvlText")!.Attribute(_w + "val")!.Value)); + Assert.Equal(new[] { "340", "680" }, levels.Select(l => l.Descendants(_w + "ind").Single().Attribute(_w + "left")!.Value)); + Assert.Equal("1", numbering.Element(_w + "num")!.Attribute(_w + "numId")!.Value); + + List paragraphs = BuilderHarness.ReadXml(filled, "word/document.xml").Descendants(_w + "p").ToList(); + XElement general = paragraphs.Single(p => p.Value == "General"); + Assert.Equal("ListItem", general.Element(_w + "pPr")!.Element(_w + "pStyle")!.Attribute(_w + "val")!.Value); + Assert.Equal("0", general.Descendants(_w + "ilvl").Single().Attribute(_w + "val")!.Value); + Assert.Equal("1", paragraphs.Single(p => p.Value == "yearly (Training)").Descendants(_w + "ilvl").Single().Attribute(_w + "val")!.Value); + Assert.Null(paragraphs.Single(p => p.Value == "after").Element(_w + "pPr")); + } + + [Fact] + public void Odt_UsesAListStyleAndNestedLists() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Measures(), TemplateFormat.Odt, Json); + + XElement listStyle = BuilderHarness.ReadXml(template.Content.ToArray(), "styles.xml").Descendants(_text + "list-style").Single(); + Assert.Equal("Bullets", listStyle.Attribute(_style + "name")!.Value); + List levels = listStyle.Elements(_text + "list-level-style-bullet").ToList(); + Assert.Equal(new[] { "1", "2" }, levels.Select(l => l.Attribute(_text + "level")!.Value)); + Assert.Equal("-11.339pt", levels[0].Descendants(_style + "list-level-label-alignment").Single().Attribute(_fo + "text-indent")!.Value); + + XElement body = BuilderHarness.ReadXml(filled, "content.xml").Descendants(_office + "text").First(); + XElement nested = body.Descendants(_text + "p").Single(p => OdtDocumentVerifier.RenderText(p) == "yearly (Training)"); + Assert.Equal(2, nested.Ancestors(_text + "list").Count()); + Assert.Equal("Bullets", nested.Ancestors(_text + "list").Last().Attribute(_text + "style-name")!.Value); + Assert.Equal("ListItem", nested.Attribute(_text + "style-name")!.Value); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Contract_IncludesListLoops(TemplateFormat format) + { + Assert.Equal( + new[] { "measures (Collection)", "measures[].optional (Condition)", "measures[].requirements (Collection)", "measures[].requirements[] (Value)", "measures[].title (Value)" }, + BuilderHarness.Build(Measures(), format).Contract.Entries.Select(e => $"{e.Path} ({e.Usage})")); + } + + [Fact] + public void Errors_AreReported() + { + TestDefinition undefined = new TestDefinition(t => t.Content(c => c.List(_bullets, l => l.Item("x")))); + TestDefinition level = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.List(_bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm())))); + t.Content(c => c.List(_bullets, l => l.Item(2, "too deep"))); + }); + + Assert.Equal("TB2010", Assert.Single(Assert.Throws(() => BuilderHarness.Build(undefined, TemplateFormat.Docx)).Errors).Code); + Assert.Equal("TB8001", Assert.Single(Assert.Throws(() => BuilderHarness.Build(level, TemplateFormat.Odt)).Errors).Code); + Assert.Throws(() => StyleSheet.Create(s => s.List(_bullets, l => l.Level(0, "•", 2.Mm(), 4.Mm())))); + Assert.Throws(() => StyleSheet.Create(s => s.List(_bullets, l => l.Level(9, "•", 6.Mm(), 4.Mm())))); + Assert.Throws(() => StyleSheet.Create(s => s.List(_bullets, l => l.Level(0, string.Empty, 6.Mm(), 4.Mm())))); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_PlacesBulletsAndText(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Measures(), format, Json); + string extension = template.FileExtension.TrimStart('.'); + + // LibreOffice's text export draws its own bullets per level (•, ◦, …); the PDF shows the list style's. + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, extension, "txt:Text (encoded):UTF8", "txt")); + Assert.Contains("• General", text, StringComparison.Ordinal); + + // Level 0: bullet at 6 − 4 = 2 mm, text at 6 mm; level 1: bullet "–" at 8 mm, text at 12 mm (from 70.866 pt). + Dictionary starts = WordStarts(LibreOfficeRunner.Convert(filled, extension, "pdf", "pdf")); + Assert.InRange(starts["General"], 70.866 + 17.008 - 1, 70.866 + 17.008 + 1); + Assert.InRange(starts["at"], 70.866 + 34.016 - 1, 70.866 + 34.016 + 1); + Assert.InRange(starts["•"], 70.866 + 5.669 - 1, 70.866 + 5.669 + 1); + Assert.InRange(starts["–"], 70.866 + 22.677 - 1, 70.866 + 22.677 + 1); + } + + private static Dictionary WordStarts(byte[] pdf) + { + string? executable = new[] { "/opt/homebrew/bin/pdftotext", "/usr/local/bin/pdftotext", "/usr/bin/pdftotext" }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, "pdftotext (poppler) is not installed."); + string file = Path.Combine(Path.GetTempPath(), "templify-list-" + Guid.NewGuid().ToString("N") + ".pdf"); + File.WriteAllBytes(file, pdf); + try + { + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + foreach (string argument in new[] { "-bbox", file, "-" }) + { + start.ArgumentList.Add(argument); + } + + using Process process = Process.Start(start)!; + string html = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + Dictionary starts = new Dictionary(StringComparer.Ordinal); + foreach (Match match in WordBox().Matches(html)) + { + starts.TryAdd(match.Groups[2].Value, double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture)); + } + + return starts; + } + finally + { + File.Delete(file); + } + } + + [GeneratedRegex("xMin=\"([0-9.]+)\"[^>]*>([^<]+)")] + private static partial Regex WordBox(); + + [Fact] + public void List_IsOneBlockInTheModel() + { + List body = new List(); + BlockComposer composer = new BlockComposer(new BuildContext(), body, null); + + composer.List(_bullets, l => + { + l.Item("a"); + l.ForEach(TemplatePath.Root("items"), "x", (x, items) => items.Item(x.Self)); + }); + + Model.ListBlock list = Assert.IsType(Assert.Single(body)); + Assert.Equal(_bullets, list.Style); + Assert.Equal(2, list.Items.Count); + Assert.IsType(list.Items[0]); + Assert.IsType(list.Items[1]); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/LocalisationTests.cs b/tests/TriasDev.Templify.Builder.Tests/LocalisationTests.cs new file mode 100644 index 00000000..a109c535 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/LocalisationTests.cs @@ -0,0 +1,183 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Collections; +using System.Globalization; +using System.Resources; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class LocalisationTests +{ + private static IReadOnlyDictionary> Texts(params (string Key, string Language, string Text)[] entries) => + entries.GroupBy(e => e.Key) + .ToDictionary( + g => g.Key, + g => (IReadOnlyDictionary)g.ToDictionary(e => e.Language, e => e.Text)); + + private static readonly ITextCatalog _invoiceTexts = TextCatalog.FromDictionary(Texts( + ("title", "en", "Invoice"), + ("title", "de", "Rechnung"), + ("customer", "en", "Customer"), + ("customer", "de", "Kunde"), + ("paid", "en", "Paid"), + ("paid", "de", "Bezahlt"))); + + private static TestDefinition Invoice() => new TestDefinition(template => + { + var t = template.Texts; + template.Properties(p => p.Title(t["title"])); + template.Content(c => + { + c.Paragraph(t["title"]); + c.Paragraph(x => + { + x.Text(t["customer"] + ": "); + x.Value(template.Data["customer"]); + }); + c.If(template.Data["isPaid"], b => b.Paragraph(t["paid"])); + }); + }); + + private static GeneratedTemplate Build(TemplateFormat format, string language, ITextCatalog texts, ITemplateDefinition? definition = null) => + TemplateBuilder.Build(definition ?? Invoice(), new TemplateBuildOptions { Format = format, Language = CultureInfo.GetCultureInfo(language), Texts = texts }); + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void OneDefinition_BuildsEveryLanguage_WithTheSameContract(TemplateFormat format) + { + GeneratedTemplate english = Build(format, "en-GB", _invoiceTexts); + GeneratedTemplate german = Build(format, "de-DE", _invoiceTexts); + + Assert.Equal(new[] { "Invoice", "Customer: {{customer}}", "{{#if isPaid}}", "Paid", "{{/if}}" }, BuilderHarness.ParagraphTexts(format, english.Content.ToArray())); + Assert.Equal(new[] { "Rechnung", "Kunde: {{customer}}", "{{#if isPaid}}", "Bezahlt", "{{/if}}" }, BuilderHarness.ParagraphTexts(format, german.Content.ToArray())); + Assert.Equal(english.Contract.Hash, german.Contract.Hash); + Assert.Equal("de-DE", german.Stamp.Language); + + (_, byte[] filled) = BuilderHarness.BuildAndFill( + Invoice(), BuilderHarness.Options(format, "de-DE", _invoiceTexts), """{ "customer": "Alice", "isPaid": true }"""); + Assert.Equal(new[] { "Rechnung", "Kunde: Alice", "Bezahlt" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void MissingTranslations_AreReportedTogether_OncePerKey() + { + ITextCatalog incomplete = TextCatalog.FromDictionary(Texts( + ("title", "en", "Invoice"), + ("title", "de", "Rechnung"), + ("customer", "en", "Customer"))); + TestDefinition definition = new TestDefinition(template => + { + var t = template.Texts; + template.Content(c => + { + c.Paragraph(t["title"]); + c.Paragraph(t["customer"]); + c.Paragraph(t["customer"]); + c.Paragraph(t["paid"]); + }); + }); + + TemplateBuildException exception = Assert.Throws(() => Build(TemplateFormat.Odt, "de-DE", incomplete, definition)); + + Assert.Equal(new[] { "TB5001", "TB5001" }, exception.Errors.Select(e => e.Code)); + Assert.Contains("'customer'", exception.Errors[0].Message, StringComparison.Ordinal); + Assert.Contains("de-DE", exception.Errors[0].Message, StringComparison.Ordinal); + Assert.Contains("'paid'", exception.Errors[1].Message, StringComparison.Ordinal); + Build(TemplateFormat.Odt, "en-US", TextCatalog.FromDictionary(Texts(("title", "en", "x"), ("customer", "en", "x"), ("paid", "en", "x"))), definition); + } + + [Theory] + [InlineData("de-AT", "de", true)] // specific → neutral + [InlineData("de", "de-DE", false)] // a neutral language does not borrow a specific one + [InlineData("fr-FR", "en", false)] // never the default language instead of a missing one + [InlineData("de-CH", "DE-ch", true)] // language names compare case-insensitively + public void Dictionary_FallsBackFromSpecificToNeutralOnly(string language, string available, bool found) + { + ITextCatalog catalog = TextCatalog.FromDictionary(Texts(("k", available, "text"))); + + Assert.Equal(found, catalog.TryGet("k", CultureInfo.GetCultureInfo(language), out string text)); + Assert.Equal(found ? "text" : string.Empty, text); + } + + [Fact] + public void Combine_LetsLaterCatalogsOverride() + { + ITextCatalog product = TextCatalog.FromDictionary(Texts(("title", "en", "Invoice"), ("footer", "en", "Thank you"))); + ITextCatalog customer = TextCatalog.FromDictionary(Texts(("title", "en", "Bill"))); + + ITextCatalog combined = TextCatalog.Combine(product, customer); + + Assert.True(combined.TryGet("title", CultureInfo.GetCultureInfo("en"), out string title)); + Assert.Equal("Bill", title); + Assert.True(combined.TryGet("footer", CultureInfo.GetCultureInfo("en"), out string footer)); + Assert.Equal("Thank you", footer); + Assert.False(TextCatalog.Empty.TryGet("title", CultureInfo.GetCultureInfo("en"), out _)); + Assert.Throws(() => TextCatalog.Combine(product, null!)); + } + + [Theory] + [InlineData("de-DE", null, "Rechnung")] + [InlineData("de", null, "Rechnung")] + [InlineData("en-US", "en", "Invoice")] // the neutral resources are English + [InlineData("en-US", null, null)] // without a neutral language they never answer + [InlineData("fr", "en", null)] // French is missing, not English + public void ResourceManager_UsesSatellitesAndTheDeclaredNeutralLanguage(string language, string? neutral, string? expected) + { + ResourceManager resources = new InMemoryResourceManager(new Dictionary> + { + [string.Empty] = new Dictionary { ["title"] = "Invoice" }, + ["de"] = new Dictionary { ["title"] = "Rechnung" }, + }); + ITextCatalog catalog = TextCatalog.FromResourceManager(resources, neutral is null ? null : CultureInfo.GetCultureInfo(neutral)); + + bool found = catalog.TryGet("title", CultureInfo.GetCultureInfo(language), out string text); + + Assert.Equal(expected != null, found); + Assert.Equal(expected ?? string.Empty, text); + } + + [Fact] + public void TextWithOpenBraces_IsCaughtLikeAnyLiteral() + { + ITextCatalog catalog = TextCatalog.FromDictionary(Texts(("title", "en", "Hello {{name}}"))); + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(t.Texts["title"]))); + + TemplateBuildException exception = Assert.Throws(() => Build(TemplateFormat.Docx, "en", catalog, definition)); + + Assert.Equal("TB1002", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void Texts_KnowTheLanguage() + { + CultureInfo? seen = null; + Build(TemplateFormat.Docx, "de-DE", TextCatalog.Empty, new TestDefinition(t => seen = t.Texts.Language)); + + Assert.Equal("de-DE", seen!.Name); + } + + /// A resource manager over in-memory resource sets, keyed by culture name ("" for the neutral resources). + private sealed class InMemoryResourceManager(Dictionary> sets) : ResourceManager + { + protected override ResourceSet? InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) => + sets.TryGetValue(culture.Name, out Dictionary? texts) ? new ResourceSet(new Reader(texts)) : null; + + private sealed class Reader(Dictionary texts) : IResourceReader + { + public void Close() + { + } + + public void Dispose() + { + } + + public IDictionaryEnumerator GetEnumerator() => new Hashtable(texts).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/LoopTests.cs b/tests/TriasDev.Templify.Builder.Tests/LoopTests.cs new file mode 100644 index 00000000..6e27ac1b --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/LoopTests.cs @@ -0,0 +1,298 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class LoopTests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private const string OrderJson = """ + { + "order": { + "number": "A-17", + "lines": [ + { "description": "Pen", "amount": 2.5, "tags": [ { "name": "office" }, { "name": "cheap" } ] }, + { "description": "Desk", "amount": 300, "tags": [ { "name": "furniture" } ] } + ] + } + } + """; + + private static TestDefinition Order() => new TestDefinition(template => + { + TemplatePath order = template.Data["order"]; + template.Content(c => + { + c.Paragraph(x => + { + x.Text("Order "); + x.Value(order["number"]); + }); + c.ForEach(order["lines"], "line", (line, b) => + { + b.If(!line.Loop.IsFirst, r => r.Paragraph("---")); + b.Paragraph(x => + { + x.Value(line.Loop.Number); + x.Text(". "); + x.Value(line["description"]); + x.Text(": "); + x.Value(line["amount"], ValueFormat.Number("F2")); + }); + b.ForEach(line["tags"], "tag", (tag, tb) => tb.Paragraph(x => + { + x.Text(" #"); + x.Value(tag["name"]); + x.Text(" of "); + x.Value(line["description"]); + x.Text(" in "); + x.Value(order["number"]); + x.Text(" ("); + x.Value(tag.Loop.Number); + x.Text("/"); + x.Value(tag.Loop.Count); + x.Text(")"); + })); + b.If(line.Loop.IsLast, r => r.Paragraph("end of lines")); + }); + }); + }); + + private static readonly string[] _expectedOrder = + { + "Order A-17", + "1. Pen: 2.50", + " #office of Pen in A-17 (1/2)", + " #cheap of Pen in A-17 (2/2)", + "---", + "2. Desk: 300.00", + " #furniture of Desk in A-17 (1/1)", + "end of lines", + }; + + [Theory] + [MemberData(nameof(Formats))] + public void NestedLoops_WithOuterAccessAndMetadata_AreFilledByTheEngine(TemplateFormat format) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Order(), format, OrderJson); + + Assert.Equal(_expectedOrder, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Loops_AreWrittenAsNamedForeachMarkers(TemplateFormat format) + { + List texts = BuilderHarness.ParagraphTexts(format, BuilderHarness.Build(Order(), format).Content.ToArray()); + + Assert.Equal( + new[] + { + "Order {{order.number}}", + "{{#foreach line in order.lines}}", + "{{#if not @first}}", "---", "{{/if}}", + "{{@number}}. {{line.description}}: {{line.amount:number:F2}}", + "{{#foreach tag in line.tags}}", + " #{{tag.name}} of {{line.description}} in {{order.number}} ({{@number}}/{{@count}})", + "{{/foreach}}", + "{{#if @last}}", "end of lines", "{{/if}}", + "{{/foreach}}", + }, + texts); + } + + [Theory] + [MemberData(nameof(Formats))] + public void LoopInsideConditional_AndConditionalOnItem(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.If(template.Data["showLines"], b => b.ForEach(template.Data["lines"], "line", (line, lb) => + lb.If(line["amount"].Gt(10), big => big.Paragraph(line["name"])) + .Else(small => small.Paragraph(x => + { + x.Text("small: "); + x.Value(line["name"]); + })))))); + string json = """{ "showLines": true, "lines": [ { "name": "a", "amount": 5 }, { "name": "b", "amount": 50 } ] }"""; + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, json); + + Assert.Equal(new[] { "small: a", "b" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void LoopOverScalars_UsesTheItemItself(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.ForEach(template.Data["tags"], "tag", (tag, b) => b.Paragraph(x => + { + x.Text("- "); + x.Value(tag.Self, ValueFormat.Uppercase); + })))); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "tags": [ "red", "green" ] }"""); + + Assert.Equal(new[] { "- RED", "- GREEN" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [InlineData("in")] + [InlineData("IN")] + [InlineData("this")] + [InlineData("and")] + [InlineData("empty")] + [InlineData("1x")] + [InlineData("a-b")] + [InlineData("a.b")] + [InlineData("@index")] + [InlineData("")] + public void ItemName_Invalid_ThrowsWhereWritten(string itemName) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.ForEach(template.Data["items"], itemName, (_, b) => b.Paragraph("x")))); + + Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + } + + [Fact] + public void ItemName_UsedByAnEnclosingLoop_Throws() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.ForEach(template.Data["groups"], "item", (group, b) => + b.ForEach(group["items"], "item", (_, ib) => ib.Paragraph("x"))))); + + ArgumentException exception = Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + Assert.Contains("enclosing loop", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Collection_RootOrMetadata_Throws() + { + TestDefinition fromRoot = new TestDefinition(template => template.Content(c => c.ForEach(template.Data, "x", (_, b) => b.Paragraph("x")))); + TestDefinition fromMetadata = new TestDefinition(template => template.Content(c => + c.ForEach(template.Data["items"], "item", (item, b) => b.ForEach(item.Loop.Index, "x", (_, ib) => ib.Paragraph("x"))))); + + Assert.Throws(() => TemplateBuilder.Build(fromRoot, BuilderHarness.Options(TemplateFormat.Docx))); + Assert.Throws(() => TemplateBuilder.Build(fromMetadata, BuilderHarness.Options(TemplateFormat.Docx))); + } + + [Fact] + public void Metadata_HasNoProperties() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + c.ForEach(template.Data["items"], "item", (item, b) => b.Paragraph(item.Loop.Index["x"])))); + + Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + } + + [Fact] + public void ScopeErrors_AreReportedTogether() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + LoopItem? escaped = null; + c.ForEach(template.Data["lines"], "line", (line, b) => + { + escaped = line; + b.ForEach(line["tags"], "tag", (tag, tb) => + { + tb.Paragraph(x => x.Value(line.Loop.Number)); // outer metadata in the inner loop + tb.If(line.Loop.IsFirst, f => f.Paragraph("first")); // the same, in a condition + tb.Paragraph(tag["name"]); // fine + }); + }); + c.Paragraph(escaped!["description"]); // the variable outside its loop + c.ForEach(template.Data["orders"], "order", (order, b) => + b.Paragraph(template.Data["order"]["number"])); // a root path hidden by the variable + })); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Equal(new[] { "TB4002", "TB4002", "TB4001", "TB4003" }, exception.Errors.Select(e => e.Code)); + Assert.Contains("innermost loop", exception.Errors[0].Message, StringComparison.Ordinal); + Assert.Contains("'line.description'", exception.Errors[2].Message, StringComparison.Ordinal); + } + + // ── Components ────────────────────────────────────────────────────────────── + + private sealed class AddressBlock(TemplatePath address) : ITemplateComponent + { + public void Compose(BlockComposer content) + { + content.Paragraph(x => + { + x.Value(address["street"]); + x.Text(", "); + x.Value(address["city"]); + }); + content.If(address["country"].NotEq("DE"), b => b.Paragraph(address["country"])); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Component_IsUsedAtTheRootAndInsideALoop(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + c.Paragraph("Customer"); + c.Component(new AddressBlock(template.Data["customer"]["address"])); + c.ForEach(template.Data["branches"], "branch", (branch, b) => + { + b.Paragraph(branch["name"]); + b.Component(new AddressBlock(branch["address"])); + }); + })); + string json = """ + { + "customer": { "address": { "street": "Main St 1", "city": "Berlin", "country": "DE" } }, + "branches": [ + { "name": "North", "address": { "street": "Harbour 2", "city": "Hamburg", "country": "DE" } }, + { "name": "Abroad", "address": { "street": "Rue 3", "city": "Paris", "country": "FR" } } + ] + } + """; + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, json); + + Assert.Equal( + new[] { "Customer", "Main St 1, Berlin", "North", "Harbour 2, Hamburg", "Abroad", "Rue 3, Paris", "FR" }, + BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void Component_KeepsTheLoopScopeOfItsCaller() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + LoopItem? escaped = null; + c.ForEach(template.Data["branches"], "branch", (branch, b) => escaped = branch); + c.Component(new AddressBlock(escaped!["address"])); + })); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + + Assert.All(exception.Errors, e => Assert.Equal("TB4001", e.Code)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersNestedLoops(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Order(), format, OrderJson); + + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + + Assert.Equal(_expectedOrder, text.TrimStart('').Replace("\r\n", "\n", StringComparison.Ordinal).TrimEnd('\n').Split('\n')); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/OdtParityTests.cs b/tests/TriasDev.Templify.Builder.Tests/OdtParityTests.cs new file mode 100644 index 00000000..ba7181ad --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/OdtParityTests.cs @@ -0,0 +1,211 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; + +namespace TriasDev.Templify.Builder.Tests; + +/// #298: ODT lays out like DOCX in LibreOffice — inherited spacing (F10), space after a page break (F11). +public sealed class OdtParityTests +{ + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body Copy"); + private static readonly ParagraphStyleKey _label = new ParagraphStyleKey("Label", "Label Line"); + private static readonly ParagraphStyleKey _note = new ParagraphStyleKey("Note", "Note Line"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Head", "Head Line"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action content) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_body, p => p.Size(10.Pt()).SpaceBefore(4.Pt()).SpaceAfter(10.Pt())); + s.Paragraph(_label, p => p.BasedOn(_body).SpaceBefore(2.Pt())); + s.Paragraph(_note, p => p.Size(9.Pt()).SpaceAfter(3.Pt())); + s.Paragraph(_heading, p => p.BasedOn(_body).Size(16.Pt()).SpaceBefore(28.Pt())); + })); + t.Content(c => content(t, c)); + }); + + [Fact] + public void DerivedStyle_SettingOneSpacing_RestatesTheOther() + { + XDocument styles = BuilderHarness.ReadXml(BuilderHarness.Build(Define((_, c) => c.Paragraph(_label, "x")), TemplateFormat.Odt).Content.ToArray(), "styles.xml"); + XElement label = Properties(styles, "Label"); + Assert.Equal(("2pt", "10pt"), (label.Attribute(_fo + "margin-top")!.Value, label.Attribute(_fo + "margin-bottom")!.Value)); + + // A style without a parent of its own inherits zero from Standard: nothing to restate. + Assert.Null(Properties(styles, "Note").Attribute(_fo + "margin-top")); + } + + [Fact] + public void ParagraphAfterPageBreak_HasNoSpaceBefore() + { + TestDefinition definition = Define((_, c) => c.Paragraph(_body, "Alpha").PageBreak().Paragraph(_heading, "Echo").Paragraph(_body, "Foxtrot")); + GeneratedTemplate template = BuilderHarness.Build(definition, TemplateFormat.Odt); + BuilderHarness.AssertInvariants(definition, template); + + XElement echo = ParagraphStyle(template, "Echo"); + Assert.Equal("Head", echo.Attribute(_style + "parent-style-name")!.Value); + XElement properties = echo.Element(_style + "paragraph-properties")!; + Assert.Equal(("0pt", "10pt"), (properties.Attribute(_fo + "margin-top")!.Value, properties.Attribute(_fo + "margin-bottom")!.Value)); + Assert.Equal("Body", ParagraphStyleName(template, "Foxtrot")); + } + + [Fact] + public void ParagraphAfterPageBreak_KeepsItsOtherOptions() + { + TestDefinition definition = Define((_, c) => c.PageBreak().Paragraph(_heading, "Echo", p => p.SpaceBefore(9.Pt()).KeepWithNext())); + XElement properties = ParagraphStyle(BuilderHarness.Build(definition, TemplateFormat.Odt), "Echo").Element(_style + "paragraph-properties")!; + Assert.Equal("0pt", properties.Attribute(_fo + "margin-top")!.Value); + Assert.Equal("always", properties.Attribute(_fo + "keep-with-next")!.Value); + } + + [Fact] + public void ParagraphAfterPageBreakAndMarker_HasNoSpaceBefore() + { + TestDefinition definition = Define((t, c) => c.PageBreak().If(t.Data["show"], b => b.Paragraph(_heading, "Echo"))); + XElement properties = ParagraphStyle(BuilderHarness.Build(definition, TemplateFormat.Odt), "Echo").Element(_style + "paragraph-properties")!; + Assert.Equal("0pt", properties.Attribute(_fo + "margin-top")!.Value); + } + + [Fact] + public void LoopAfterPageBreak_KeepsItsSpace() + { + // Every copy of a loop body would lose its space; LibreOffice's DOCX import zeroes only the first. + TestDefinition definition = Define((t, c) => c.PageBreak().ForEach(t.Data["items"], "i", (i, b) => b.Paragraph(_heading, "Echo"))); + Assert.Equal("Head", ParagraphStyleName(BuilderHarness.Build(definition, TemplateFormat.Odt), "Echo")); + } + + [Fact] + public void PageBreakInACell_KeepsTheSpace() + { + // LibreOffice ignores a page break in a table cell and keeps the space in DOCX too. + TestDefinition definition = Define((_, c) => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(x => x.Paragraph(_body, "One").PageBreak().Paragraph(_heading, "Echo"))); + })); + Assert.Equal("Head", ParagraphStyleName(BuilderHarness.Build(definition, TemplateFormat.Odt), "Echo")); + } + + [Fact] + public void TopOfPage_DoesNotChangeTheModel() + { + // The ODT writer works on copies: the DOCX and the JSON of the same definition stay as they were. + TestDefinition definition = Define((t, c) => c.PageBreak().If(t.Data["show"], b => b.Paragraph(_heading, "Echo")).Else(b => b.Paragraph(_heading, "Golf"))); + GeneratedTemplate odt = BuilderHarness.Build(definition, TemplateFormat.Odt); + BuilderHarness.AssertInvariants(definition, odt); + BuilderHarness.AssertInvariants(definition, BuilderHarness.Build(definition, TemplateFormat.Docx)); + } + + public static TheoryData TopOfPageCases => new TheoryData + { + { "else", "Golf" }, + { "table", "Tango" }, + { "rule", "Romeo" }, + { "list", "Lima" }, + }; + + [Theory] + [MemberData(nameof(TopOfPageCases))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ContentAfterPageBreakStartsLikeDocx(string kind, string word) + { + ListStyleKey bullets = new ListStyleKey("Bullets"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_body, p => p.Size(10.Pt()).SpaceBefore(4.Pt()).SpaceAfter(10.Pt())); + s.Paragraph(_heading, p => p.BasedOn(_body).Size(16.Pt()).SpaceBefore(28.Pt())); + s.List(bullets, l => l.ItemStyle(_heading).Level(0, "•", 6.Mm(), 4.Mm())); + })); + t.Content(c => + { + c.Paragraph(_body, "Alpha").PageBreak(); + switch (kind) + { + case "else": + c.If(t.Data["show"], b => b.Paragraph(_heading, "Hotel")).Else(b => b.Paragraph(_heading, word)); + break; + case "table": + c.Table(tb => + { + tb.SpaceBefore(20.Pt()); + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(word)); + }); + break; + case "rule": + c.Rule(1.Pt(), Color.FromHex("000000"), 20.Pt(), 5.Pt()).Paragraph(_body, word); + break; + default: + c.List(bullets, l => l.Item(word).Item("Mike")); + break; + } + }); + }); + const string data = """{ "show": false }"""; + double docx = PdfLayout.Words(PdfLayout.Pdf(definition, TemplateFormat.Docx, data), page: 2).Find(word).YMin; + double odt = PdfLayout.Words(PdfLayout.Pdf(definition, TemplateFormat.Odt, data), page: 2).Find(word).YMin; + // DOCX carries a table's space before on a 1 pt paragraph, which stays (a known 1 pt difference, #296). + double tolerance = kind == "table" ? 1.5 : 0.5; + Assert.InRange(odt, docx - tolerance, docx + tolerance); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_InheritedSpaceAfterIsKept(TemplateFormat format) + { + // DOCX in LibreOffice is the reference: Label keeps Body's 10 pt after. + List words = PdfLayout.Words(PdfLayout.Pdf(Define((_, c) => c.Paragraph(_label, "Bravo").Paragraph(_body, "Charlie")), format)); + double gap = words.Find("Charlie").YMin - words.Find("Bravo").YMin; + Assert.InRange(gap, Reference(format, "Bravo", "Charlie") - 0.5, Reference(format, "Bravo", "Charlie") + 0.5); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_HeadingAfterPageBreakStartsAtTheTop(TemplateFormat format) + { + TestDefinition definition = Define((t, c) => c.Paragraph(_body, "Alpha").PageBreak().If(t.Data["show"], b => b.Paragraph(_heading, "Echo"))); + double docx = PdfLayout.Words(PdfLayout.Pdf(definition, TemplateFormat.Docx, """{ "show": true }"""), page: 2).Find("Echo").YMin; + double actual = PdfLayout.Words(PdfLayout.Pdf(definition, format, """{ "show": true }"""), page: 2).Find("Echo").YMin; + Assert.InRange(actual, docx - 0.5, docx + 0.5); + } + + private static double Reference(TemplateFormat format, string first, string second) + { + if (format == TemplateFormat.Docx) + { + // Body's 10 pt after, 10 pt text: the DOCX gap is the reference the ODT must meet. + List words = PdfLayout.Words(PdfLayout.Pdf(Define((_, c) => c.Paragraph(_label, first).Paragraph(_body, second)), TemplateFormat.Docx)); + return words.Find(second).YMin - words.Find(first).YMin; + } + + return Reference(TemplateFormat.Docx, first, second); + } + + private static XElement Properties(XDocument styles, string name) => + styles.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")?.Value == name).Element(_style + "paragraph-properties")!; + + private static string ParagraphStyleName(GeneratedTemplate template, string text) => + BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml").Descendants(_office + "text").First().Descendants() + .First(e => (e.Name == _text + "p" || e.Name == _text + "h") && OdtDocumentVerifier.RenderText(e) == text) + .Attribute(_text + "style-name")!.Value; + + private static XElement ParagraphStyle(GeneratedTemplate template, string text) + { + string name = ParagraphStyleName(template, text); + return BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml").Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/PaddingTests.cs b/tests/TriasDev.Templify.Builder.Tests/PaddingTests.cs new file mode 100644 index 00000000..a6d3e72d --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/PaddingTests.cs @@ -0,0 +1,183 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F2: padding per side for table styles, box styles and one cell. +public sealed class PaddingTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + private static readonly BoxStyleKey _panel = new BoxStyleKey("Panel"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action content) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Table(_grid, g => g.CellPadding(8.Pt(), 6.Pt(), 9.Pt(), 6.Pt())); + s.Box(_panel, b => b.Border(1.Pt(), Color.FromHex("C0C0C0")).Padding(12.Pt(), 12.Pt(), 6.Pt(), 12.Pt())); + })); + t.Content(content); + }); + + private static TestDefinition Grid(Action? cell = null) => Define(c => c.Table(t => + { + t.Style(_grid); + t.Columns(cols => cols.Fixed(60.Mm()).Relative(1)); + t.Row(r => r.Cell(x => + { + cell?.Invoke(x); + x.Paragraph(p => p.Text("A").TabRight().Text("B")); + }).Cell("other")); + })); + + [Theory] + [MemberData(nameof(Formats))] + public void TableStylePadding_PerSide(TemplateFormat format) + { + TestDefinition definition = Grid(); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement margins = Docx(template).Descendants(_w + "tblCellMar").Single(); + Assert.Equal(("160", "120", "180", "120"), (Width(margins, "top"), Width(margins, "left"), Width(margins, "bottom"), Width(margins, "right"))); + } + else + { + Assert.All(OdtCellStyles(template), p => Assert.Equal(("8pt", "6pt", "9pt", "6pt"), Paddings(p))); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void CellPadding_OverridesTheTableStyle(TemplateFormat format) + { + TestDefinition definition = Grid(cell => cell.Padding(2.Pt(), 3.Pt(), 4.Pt(), 5.Pt())); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + List cells = Docx(template).Descendants(_w + "tc").ToList(); + XElement own = cells[0].Element(_w + "tcPr")!.Element(_w + "tcMar")!; + Assert.Equal(("40", "100", "80", "60"), (Width(own, "top"), Width(own, "left"), Width(own, "bottom"), Width(own, "right"))); + Assert.Null(cells[1].Element(_w + "tcPr")!.Element(_w + "tcMar")); + } + else + { + List styles = OdtCellStyles(template); + Assert.Equal(("2pt", "3pt", "4pt", "5pt"), Paddings(styles[0])); + Assert.Equal(("8pt", "6pt", "9pt", "6pt"), Paddings(styles[1])); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void BoxPadding_PerSide(TemplateFormat format) + { + TestDefinition definition = Define(c => c.Box(_panel, b => b.Paragraph("In the box"))); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement margins = Docx(template).Descendants(_w + "tblCellMar").Single(); + Assert.Equal(("240", "240", "120", "240"), (Width(margins, "top"), Width(margins, "left"), Width(margins, "bottom"), Width(margins, "right"))); + } + else + { + Assert.Equal(("12pt", "12pt", "6pt", "12pt"), Paddings(OdtCellStyles(template).Single())); + } + } + + [Fact] + public void CellFrame_UsesTheCellsOwnPadding() + { + TestDefinition definition = Grid(cell => cell.Padding(2.Pt(), 10.Pt(), 4.Pt(), 20.Pt())); + GeneratedTemplate template = BuilderHarness.Build(definition, TemplateFormat.Docx); + XElement tab = Docx(template).Descendants(_w + "tab").First(t => t.Parent!.Name == _w + "tabs"); + Assert.Equal((60.Mm() - 20.Pt() - 10.Pt()).Twips.ToString(System.Globalization.CultureInfo.InvariantCulture), tab.Attribute(_w + "pos")!.Value); + } + + [Fact] + public void CellPadding_WiderThanColumn_IsABuildError() + { + TestDefinition definition = Grid(cell => cell.Padding(2.Pt(), 90.Pt(), 2.Pt(), 90.Pt())); + TemplateBuildException error = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + Assert.Contains("padding", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("8pt 6pt 9pt", "8pt 6pt 9pt 6pt")] + [InlineData("8pt 6pt 9pt 6pt", "8pt 6pt 9pt 6pt")] + [InlineData("8pt 6pt", "8pt 6pt")] + public void Json_Padding_RoundTrip(string given, string exported) + { + string json = $$""" + { + "templifyDefinition": 1, + "identity": { "id": "padding", "version": 1 }, + "styles": { + "table": { "Grid": { "cellPadding": "{{given}}" } }, + "box": { "Panel": { "padding": "{{given}}" } } + }, + "content": [ + { "table": [ { "row": [ { "padding": "{{given}}", "content": "cell" } ] } ], "columns": [ 1 ], "style": "Grid" }, + { "box": [ "boxed" ], "style": "Panel" } + ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, TemplateFormat.Docx); + BuilderHarness.AssertInvariants(imported, template); + string text = Json.TemplateJson.Export(imported, BuilderHarness.Options(TemplateFormat.Docx)).Json; + Assert.Equal(3, text.Split("\"" + exported + "\"").Length - 1); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_PaddingTopAndBottomDiffer(TemplateFormat format) + { + double TextTop(Length top, Length bottom) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Box(_panel, b => b.Border(1.Pt(), Color.FromHex("C0C0C0")).Padding(top, 6.Pt(), bottom, 6.Pt())))); + t.Content(c => c.Paragraph("Before").Box(_panel, b => b.Paragraph("Inside"))); + }); + List words = PdfLayout.Words(PdfLayout.Pdf(definition, format)); + return words.Find("Inside").YMin - words.Find("Before").YMin; + } + + Assert.InRange(TextTop(12.Pt(), 6.Pt()) - TextTop(6.Pt(), 12.Pt()), 5, 7); + } + + private static XDocument Docx(GeneratedTemplate template) => BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml"); + + private static string Width(XElement margins, string side) => margins.Element(_w + side)!.Attribute(_w + "w")!.Value; + + /// The cell styles of the body's cells, in document order. + private static List OdtCellStyles(GeneratedTemplate template) + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + return content.Descendants(_table + "table-cell") + .Select(c => c.Attribute(_table + "style-name")!.Value) + .Select(name => content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name).Element(_style + "table-cell-properties")!) + .ToList(); + } + + private static (string Top, string Right, string Bottom, string Left) Paddings(XElement properties) => + (properties.Attribute(_fo + "padding-top")!.Value, properties.Attribute(_fo + "padding-right")!.Value, properties.Attribute(_fo + "padding-bottom")!.Value, properties.Attribute(_fo + "padding-left")!.Value); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/PageTests.cs b/tests/TriasDev.Templify.Builder.Tests/PageTests.cs new file mode 100644 index 00000000..0bdc41f2 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/PageTests.cs @@ -0,0 +1,295 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Globalization; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class PageTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly ParagraphStyleKey _indented = new ParagraphStyleKey("Indented", "Indented"); + + [Fact] + public void DefaultPage_IsA4WithEqualMargins() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph("x"))); + + XElement section = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Docx).Content.ToArray(), "word/document.xml") + .Descendants(_w + "sectPr").Single(); + Assert.Equal("11906", section.Element(_w + "pgSz")!.Attribute(_w + "w")!.Value); + Assert.Equal("16838", section.Element(_w + "pgSz")!.Attribute(_w + "h")!.Value); + Assert.Equal("1417", section.Element(_w + "pgMar")!.Attribute(_w + "top")!.Value); + Assert.Equal("1417", section.Element(_w + "pgMar")!.Attribute(_w + "left")!.Value); + Assert.Null(section.Element(_w + "titlePg")); + + XElement layout = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Odt).Content.ToArray(), "styles.xml") + .Descendants(_style + "page-layout-properties").Single(); + Assert.Equal("595.276pt", layout.Attribute(_fo + "page-width")!.Value); + Assert.Equal("841.89pt", layout.Attribute(_fo + "page-height")!.Value); + Assert.Equal("70.866pt", layout.Attribute(_fo + "margin-top")!.Value); + } + + [Fact] + public void CustomPage_SizeAndMargins() + { + TestDefinition definition = new TestDefinition(t => + { + t.Page(p => p.Size(PageSize.Letter).Margins(top: 20.Mm(), right: 15.Mm(), bottom: 18.Mm(), left: 30.Mm()).HeaderFooterDistance(8.Mm(), 6.Mm())); + t.Content(c => c.Paragraph("x")); + }); + + XElement margins = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Docx).Content.ToArray(), "word/document.xml") + .Descendants(_w + "pgMar").Single(); + Assert.Equal(new[] { "1134", "850", "1020", "1701", "454", "340" }, + new[] { "top", "right", "bottom", "left", "header", "footer" }.Select(a => margins.Attribute(_w + a)!.Value)); + + XElement layout = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Odt).Content.ToArray(), "styles.xml") + .Descendants(_style + "page-layout-properties").Single(); + Assert.Equal("612pt", layout.Attribute(_fo + "page-width")!.Value); + Assert.Equal("85.039pt", layout.Attribute(_fo + "margin-left")!.Value); + } + + private static TestDefinition Letter() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(_indented, p => p.IndentStart(10.Mm())))); + t.Page(p => p + .Header(h => + { + h.Paragraph(x => + { + x.Value(t.Data["company"]); + x.TabRight(); + x.Text("Confidential"); + }); + h.If(t.Data["draft"], d => d.Paragraph("DRAFT")); + }) + .Footer(f => f.Paragraph(x => + { + x.Text("Page "); + x.PageNumber(); + x.Text(" of "); + x.PageCount(); + })) + .FirstPage(first => + { + first.NoHeader(); + first.Footer(f => f.Paragraph(x => + { + x.Text("Cover of "); + x.Value(t.Data["company"]); + })); + })); + t.Content(c => + { + c.Paragraph("Cover"); + c.PageBreak(); + c.Paragraph(x => + { + x.Text("Body"); + x.TabRight(); + x.Text("right"); + }); + c.Paragraph(_indented, x => + { + x.Text("Indented"); + x.TabRight(); + x.Text("end"); + }); + c.PageBreak(); + c.Paragraph("Last"); + }); + }); + + private const string LetterJson = """{ "company": "Acme Ltd", "draft": true }"""; + + [Fact] + public void Docx_WritesHeaderAndFooterParts_WithAFirstPage() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), TemplateFormat.Docx, LetterJson); + byte[] built = template.Content.ToArray(); + + XElement section = BuilderHarness.ReadXml(built, "word/document.xml").Descendants(_w + "sectPr").Single(); + Assert.NotNull(section.Element(_w + "titlePg")); + Assert.Equal( + new[] { "headerReference default rId2", "headerReference first rId3", "footerReference default rId4", "footerReference first rId5" }, + section.Elements().Where(e => e.Name.LocalName.EndsWith("Reference", StringComparison.Ordinal)) + .Select(e => $"{e.Name.LocalName} {e.Attribute(_w + "type")!.Value} {e.Attribute(_r + "id")!.Value}")); + + Assert.Equal(new[] { "Acme Ltd\tConfidential", "DRAFT" }, PartTexts(filled, "word/header1.xml")); + Assert.Equal(new[] { string.Empty }, PartTexts(filled, "word/header2.xml")); + Assert.Equal(new[] { "Cover of Acme Ltd" }, PartTexts(filled, "word/footer2.xml")); + + XElement footer = BuilderHarness.ReadXml(filled, "word/footer1.xml").Root!; + Assert.Equal(new[] { " PAGE ", " NUMPAGES " }, footer.Descendants(_w + "instrText").Select(i => i.Value)); + + XElement tab = BuilderHarness.ReadXml(built, "word/document.xml").Descendants(_w + "tab").First(e => e.Parent!.Name == _w + "tabs"); + Assert.Equal("right", tab.Attribute(_w + "val")!.Value); + Assert.Equal("9071", tab.Attribute(_w + "pos")!.Value); + } + + [Fact] + public void Odt_WritesTheMasterPage_WithAFirstPage() + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), TemplateFormat.Odt, LetterJson); + + XElement master = BuilderHarness.ReadXml(filled, "styles.xml").Descendants(_style + "master-page").Single(); + Assert.Equal("Standard", master.Attribute(_style + "name")!.Value); + Assert.Equal(new[] { "header", "header-first", "footer", "footer-first" }, master.Elements().Select(e => e.Name.LocalName)); + Assert.Equal(new[] { "Acme Ltd\tConfidential", "DRAFT" }, master.Element(_style + "header")!.Elements(_text + "p").Select(OdtDocumentVerifier.RenderText)); + Assert.Equal(new[] { "Cover of Acme Ltd" }, master.Element(_style + "footer-first")!.Elements(_text + "p").Select(OdtDocumentVerifier.RenderText)); + Assert.NotNull(master.Element(_style + "footer")!.Descendants(_text + "page-number").SingleOrDefault()); + Assert.NotNull(master.Element(_style + "footer")!.Descendants(_text + "page-count").SingleOrDefault()); + + XDocument styles = BuilderHarness.ReadXml(template.Content.ToArray(), "styles.xml"); + XElement layout = styles.Descendants(_style + "page-layout").Single(); + Assert.Equal("35.433pt", layout.Element(_style + "page-layout-properties")!.Attribute(_fo + "margin-top")!.Value); + Assert.Equal("35.433pt", layout.Element(_style + "header-style")!.Element(_style + "header-footer-properties")!.Attribute(_fo + "min-height")!.Value); + + // Right tab stops: from the frame's start in the header and body (453.544pt), from the indent for the indented style. + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + Dictionary tabs = content.Root!.Element(_office + "automatic-styles")!.Elements(_style + "style") + .Where(s => s.Descendants(_style + "tab-stop").Any()) + .ToDictionary(s => s.Attribute(_style + "parent-style-name")!.Value, s => s.Descendants(_style + "tab-stop").Single().Attribute(_style + "position")!.Value); + Assert.Equal("453.544pt", tabs["Standard"]); + Assert.Equal("425.198pt", tabs["Indented"]); + Assert.Contains(styles.Descendants(_style + "style"), s => (string?)s.Attribute(_style + "name") == "TemplifyHfTab1"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Contract_IncludesHeaderAndFooterPaths(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Letter(), format); + + Assert.Equal(new[] { "company", "draft" }, template.Contract.Entries.Select(e => e.Path)); + } + + [Fact] + public void Errors_AreReported() + { + TestDefinition twice = new TestDefinition(t => + { + t.Page(p => p.Size(PageSize.A5)); + t.Page(p => p.Size(PageSize.A4)); + }); + TestDefinition noFrame = new TestDefinition(t => t.Page(p => p.Size(PageSize.A5).Margins(100.Mm()))); + TestDefinition undefinedStyle = new TestDefinition(t => t.Page(p => p.Header(h => h.Paragraph(_indented, "x")))); + + Assert.Equal("TB6001", Assert.Single(Assert.Throws(() => BuilderHarness.Build(twice, TemplateFormat.Docx)).Errors).Code); + Assert.Equal("TB6002", Assert.Single(Assert.Throws(() => BuilderHarness.Build(noFrame, TemplateFormat.Docx)).Errors).Code); + Assert.Equal("TB2010", Assert.Single(Assert.Throws(() => BuilderHarness.Build(undefinedStyle, TemplateFormat.Odt)).Errors).Code); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Page(p => p.Margins(-1.Mm()))), TemplateFormat.Docx)); + Assert.Throws(() => new PageSize(Length.Zero, 10.Mm())); + + PageComposer? kept = null; + BuilderHarness.Build(new TestDefinition(t => t.Page(p => kept = p)), TemplateFormat.Docx); + Assert.Throws(() => kept!.Size(PageSize.A4)); + } + + // ── LibreOffice: what a reader sees ───────────────────────────────────────── + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ShowsTheHeadersFootersAndPageNumbersPerPage(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), format, LetterJson); + byte[] pdf = LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "pdf", "pdf"); + + string[] pages = Enumerable.Range(1, 3).Select(n => PdfText(pdf, n)).ToArray(); + + Assert.DoesNotContain("Acme Ltd", pages[0].Split("Cover of")[0], StringComparison.Ordinal); + Assert.Contains("Cover of Acme Ltd", pages[0], StringComparison.Ordinal); + Assert.DoesNotContain("Page 1 of", pages[0], StringComparison.Ordinal); + Assert.Contains("Acme Ltd", pages[1], StringComparison.Ordinal); + Assert.Contains("DRAFT", pages[1], StringComparison.Ordinal); + Assert.Contains("Page 2 of 3", pages[1], StringComparison.Ordinal); + Assert.Contains("Page 3 of 3", pages[2], StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RightTabEndsAtTheRightMargin(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Letter(), format, LetterJson); + byte[] pdf = LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "pdf", "pdf"); + + // A4, 25 mm margins: the frame ends at 595.276 − 70.866 = 524.41 pt. + Dictionary wordEnds = PdfWordEnds(pdf, 2); + Assert.InRange(wordEnds["right"], 523.0, 525.0); + Assert.InRange(wordEnds["end"], 523.0, 525.0); + Assert.InRange(wordEnds["Confidential"], 523.0, 525.0); + } + + private static List PartTexts(byte[] package, string part) + { + return BuilderHarness.ReadXml(package, part).Root!.Elements(_w + "p").Select(p => + string.Concat(p.Descendants().Select(e => + e.Name == _w + "t" ? e.Value + : e.Name == _w + "tab" && e.Parent!.Name == _w + "r" ? "\t" + : string.Empty))) + .ToList(); + } + + private static string PdfText(byte[] pdf, int page) => RunPdfTool("pdftotext", pdf, "-f", page.ToString(CultureInfo.InvariantCulture), "-l", page.ToString(CultureInfo.InvariantCulture), "-layout"); + + /// The right edge (xMax) of each word on a page, from pdftotext's bounding-box output. + private static Dictionary PdfWordEnds(byte[] pdf, int page) + { + string html = RunPdfTool("pdftotext", pdf, "-f", page.ToString(CultureInfo.InvariantCulture), "-l", page.ToString(CultureInfo.InvariantCulture), "-bbox"); + Dictionary ends = new Dictionary(StringComparer.Ordinal); + foreach (System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(html, "xMax=\"([0-9.]+)\"[^>]*>([^<]+)")) + { + ends[match.Groups[2].Value] = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + } + + return ends; + } + + private static string RunPdfTool(string tool, byte[] pdf, params string[] arguments) + { + string? executable = new[] { "/opt/homebrew/bin/" + tool, "/usr/local/bin/" + tool, "/usr/bin/" + tool }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, $"{tool} (poppler) is not installed."); + + string directory = Path.Combine(Path.GetTempPath(), "templify-pdf-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string input = Path.Combine(directory, "document.pdf"); + File.WriteAllBytes(input, pdf); + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + foreach (string argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.ArgumentList.Add(input); + start.ArgumentList.Add("-"); + using Process process = Process.Start(start)!; + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + return output; + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ParagraphOptionsTests.cs b/tests/TriasDev.Templify.Builder.Tests/ParagraphOptionsTests.cs new file mode 100644 index 00000000..7d54cf19 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ParagraphOptionsTests.cs @@ -0,0 +1,192 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F3: space before/after and keep options on one paragraph, without a style of their own. +public sealed class ParagraphOptionsTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + private static readonly ParagraphStyleKey _label = new ParagraphStyleKey("Label", "Label"); + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body"); + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static StyleSheet Sheet() => StyleSheet.Create(s => + { + s.Paragraph(_body, p => p.Size(10.Pt()).SpaceAfter(6.Pt())); + s.Paragraph(_label, p => p.BasedOn(_body).SpaceAfter(4.Pt())); + s.Table(_grid, t => t.ParagraphStyle(_label)); + }); + + private static TestDefinition Define(Action content) => new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(content); + }); + + [Theory] + [MemberData(nameof(Formats))] + public void Options_AreWrittenAsDirectParagraphProperties(TemplateFormat format) + { + TestDefinition definition = Define(c => c.Paragraph(_label, "Label", p => p.SpaceBefore(7.Pt()).KeepWithNext())); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement properties = DocxParagraph(template, "Label").Element(_w + "pPr")!; + Assert.Equal(new[] { "pStyle", "keepNext", "spacing" }, properties.Elements().Select(e => e.Name.LocalName)); + Assert.Equal("Label", properties.Element(_w + "pStyle")!.Attribute(_w + "val")!.Value); + XElement spacing = properties.Element(_w + "spacing")!; + Assert.Equal("140", spacing.Attribute(_w + "before")!.Value); + Assert.Null(spacing.Attribute(_w + "after")); + } + else + { + XElement style = OdtParagraphStyle(template, "Label"); + Assert.Equal("Label", style.Attribute(_style + "parent-style-name")!.Value); + XElement properties = style.Element(_style + "paragraph-properties")!; + Assert.Equal("always", properties.Attribute(_fo + "keep-with-next")!.Value); + Assert.Equal("7pt", properties.Attribute(_fo + "margin-top")!.Value); + + // LibreOffice reads top and bottom margin as one item: the other one is restated from the style. + Assert.Equal("4pt", properties.Attribute(_fo + "margin-bottom")!.Value); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Options_SurviveStyleInheritance(TemplateFormat format) + { + TestDefinition definition = Define(c => c.Table(t => + { + t.Style(_grid); + t.Columns(cols => cols.Relative(1)); + t.Row(r => r.Cell(cell => cell.Paragraph(null, "Inherited", p => p.KeepLinesTogether().SpaceAfter(2.Pt())))); + })); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement properties = DocxParagraph(template, "Inherited").Element(_w + "pPr")!; + Assert.Equal("Label", properties.Element(_w + "pStyle")!.Attribute(_w + "val")!.Value); + Assert.NotNull(properties.Element(_w + "keepLines")); + Assert.Equal("40", properties.Element(_w + "spacing")!.Attribute(_w + "after")!.Value); + } + else + { + XElement style = OdtParagraphStyle(template, "Inherited"); + Assert.Equal("Label", style.Attribute(_style + "parent-style-name")!.Value); + XElement properties = style.Element(_style + "paragraph-properties")!; + Assert.Equal("always", properties.Attribute(_fo + "keep-together")!.Value); + Assert.Equal("2pt", properties.Attribute(_fo + "margin-bottom")!.Value); + Assert.Equal("0pt", properties.Attribute(_fo + "margin-top")!.Value); + } + } + + [Fact] + public void Odt_RightTabAndOptions_ShareOneAutomaticStyle() + { + TestDefinition definition = Define(c => c.Paragraph(_label, x => x.Text("Left").TabRight().Text("Right"), p => p.KeepWithNext())); + GeneratedTemplate template = BuilderHarness.Build(definition, TemplateFormat.Odt); + BuilderHarness.AssertInvariants(definition, template); + + XElement properties = OdtParagraphStyle(template, "Left").Element(_style + "paragraph-properties")!; + Assert.Equal("always", properties.Attribute(_fo + "keep-with-next")!.Value); + Assert.Equal("right", properties.Element(_style + "tab-stops")!.Element(_style + "tab-stop")!.Attribute(_style + "type")!.Value); + } + + [Theory] + [MemberData(nameof(Formats))] + public void EmptyOptions_BuildLikeNoOptions(TemplateFormat format) + { + GeneratedTemplate with = BuilderHarness.Build(Define(c => c.Paragraph(_label, "Text", p => { })), format); + GeneratedTemplate without = BuilderHarness.Build(Define(c => c.Paragraph(_label, "Text")), format); + Assert.Equal(without.ContentHash, with.ContentHash); + } + + [Fact] + public void NegativeSpace_Throws() + { + TestDefinition before = Define(c => c.Paragraph(_label, "x", p => p.SpaceBefore(-1.Pt()))); + TestDefinition after = Define(c => c.Paragraph(_label, "x", p => p.SpaceAfter(-1.Pt()))); + Assert.Throws(() => BuilderHarness.Build(before, TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(after, TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_ParagraphOptions_RoundTrip(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "options", "version": 1 }, + "styles": { "paragraph": { "Label": { "size": "10pt", "spaceAfter": "4pt" } } }, + "content": [ + { "style": "Label", "paragraph": "Label", "spaceBefore": "7pt", "spaceAfter": "3pt", "keepWithNext": true, "keepLinesTogether": true }, + { "paragraph": "Plain", "keepWithNext": true } + ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + + string exported = Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json; + Assert.Contains("\"spaceBefore\": \"7pt\"", exported, StringComparison.Ordinal); + Assert.Contains("\"keepLinesTogether\": true", exported, StringComparison.Ordinal); + Assert.Contains("\"paragraph\": \"Plain\"", exported, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_SpaceBeforeMovesTheParagraph(TemplateFormat format) + { + double Gap(Action? options) + { + TestDefinition definition = Define(c => + { + c.Paragraph(_body, "First"); + if (options is null) + { + c.Paragraph(_body, "Second"); + } + else + { + c.Paragraph(_body, "Second", options); + } + }); + List words = PdfLayout.Words(PdfLayout.Pdf(definition, format)); + return words.Find("Second").YMin - words.Find("First").YMin; + } + + Assert.InRange(Gap(p => p.SpaceBefore(20.Pt())) - Gap(null), 19, 21); + } + + private static XElement DocxParagraph(GeneratedTemplate template, string text) => + BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml").Descendants(_w + "p") + .First(p => string.Concat(p.Descendants(_w + "t").Select(t => t.Value)).StartsWith(text, StringComparison.Ordinal)); + + private static XElement OdtParagraphStyle(GeneratedTemplate template, string text) + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + XElement paragraph = content.Descendants(_office + "text").First().Descendants() + .First(e => (e.Name == _text + "p" || e.Name == _text + "h") && OdtDocumentVerifier.RenderText(e).StartsWith(text, StringComparison.Ordinal)); + string name = paragraph.Attribute(_text + "style-name")!.Value; + return content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/PathComparisonTests.cs b/tests/TriasDev.Templify.Builder.Tests/PathComparisonTests.cs new file mode 100644 index 00000000..79708f8e --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/PathComparisonTests.cs @@ -0,0 +1,183 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Conditionals; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #297: a path compared with another path, without a raw condition. +public sealed class PathComparisonTests +{ + private static readonly TemplatePath _a = TemplatePath.Root("a")["id"]; + private static readonly TemplatePath _b = TemplatePath.Root("b")["id"]; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + public static TheoryData Written => new TheoryData + { + { "a.id = b.id", _a.Eq(_b) }, + { "a.id != b.id", _a.NotEq(_b) }, + { "a.id > b.id", _a.Gt(_b) }, + { "a.id >= b.id", _a.Ge(_b) }, + { "a.id < b.id", _a.Lt(_b) }, + { "a.id <= b.id", _a.Le(_b) }, + { "a.id contains b.id", _a.Contains(_b) }, + { "a.id startswith b.id", _a.StartsWith(_b) }, + { "a.id endswith b.id", _a.EndsWith(_b) }, + { "a.id = b.id and not (a.id > b.id)", _a.Eq(_b) & !_a.Gt(_b) }, + { "a.id = [in]", _a.Eq(TemplatePath.Root("in")) }, + { "a.id > [limit]", _a.Gt(TemplatePath.Root("limit")) }, + { "limit = a.id", TemplatePath.Root("limit").Eq(_a) }, + { "a.id = items[0].id", _a.Eq(TemplatePath.Root("items[0]")["id"]) }, + }; + + [Theory] + [MemberData(nameof(Written))] + public void PathComparison_IsWrittenWithBothPaths(string expected, Condition condition) + { + Assert.Equal(expected, condition.ToString()); + Assert.True(new ConditionEvaluator().Validate(condition.ToString()).IsValid); + } + + [Fact] + public void PathComparison_ReadsBothPaths() => + Assert.Equal(new[] { _a, _b }, _a.Eq(_b).Paths); + + [Fact] + public void RootAsOperand_Throws() => + Assert.Throws(() => _a.Eq(default(TemplatePath))); + + private static TestDefinition Owners() => new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["owners"], "owner", (owner, b) => + { + b.Paragraph(owner["name"]); + b.ForEach(t.Data["entries"], "entry", (entry, e) => + e.If(entry["ownerId"].Eq(owner["id"]), x => x.Paragraph(entry["text"]))); + }))); + + private const string OwnersData = """ + { + "owners": [ { "id": 1, "name": "Ada" }, { "id": 2, "name": "Bo" } ], + "entries": [ { "ownerId": 2, "text": "second" }, { "ownerId": 1, "text": "first" }, { "ownerId": 1, "text": "third" } ] + } + """; + + [Theory] + [MemberData(nameof(Formats))] + public void Fill_ComparesTheTwoValues(TemplateFormat format) + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Owners(), format, OwnersData); + Assert.Equal(new[] { "Ada", "first", "third", "Bo", "second" }, BuilderHarness.ParagraphTexts(format, filled).Where(p => p.Length > 0)); + Assert.Contains("entries[].ownerId", template.Contract.Entries.Select(e => e.Path)); + Assert.Contains("owners[].id", template.Contract.Entries.Select(e => e.Path)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Fill_ComparesNumbersNumerically(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.If(t.Data["total"].Gt(t.Data["limit"]), b => b.Paragraph("over")).Else(b => b.Paragraph("within")))); + (_, byte[] over) = BuilderHarness.BuildAndFill(definition, format, """{ "total": 10, "limit": 9.5 }"""); + (_, byte[] within) = BuilderHarness.BuildAndFill(definition, format, """{ "total": 10, "limit": 10.0 }"""); + Assert.Contains("over", BuilderHarness.ParagraphTexts(format, over)); + Assert.Contains("within", BuilderHarness.ParagraphTexts(format, within)); + } + + [Fact] + public void RightOperandOutsideItsLoop_IsAnError() + { + LoopItem? escaped = null; + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.ForEach(t.Data["owners"], "owner", (owner, b) => + { + escaped = owner; + b.Paragraph(owner["name"]); + }); + c.If(t.Data["id"].Eq(escaped!["id"]), b => b.Paragraph("x")); + })); + Assert.ThrowsAny(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_PathComparison_RoundTrips(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "compare", "version": 1 }, + "content": [ + { "forEach": "owners", "as": "owner", "body": [ + "{{owner.name}}", + { "forEach": "entries", "as": "entry", "body": [ + { "if": "entry.ownerId = owner.id and entry.text != owner.name", "then": [ "{{entry.text}}" ] } + ] } + ] } + ] + } + """; + Builder.ITemplateDefinition imported = Json.TemplateJson.Import(json); + (_, byte[] filled) = BuilderHarness.BuildAndFill(imported, format, OwnersData); + Assert.Equal(new[] { "Ada", "first", "third", "Bo", "second" }, BuilderHarness.ParagraphTexts(format, filled).Where(p => p.Length > 0)); + Assert.Contains("\"if\": \"entry.ownerId = owner.id and entry.text != owner.name\"", Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json, StringComparison.Ordinal); + } + + [Fact] + public void Json_EscapedWordAfterAnOperatorIsAPath() + { + // A plain word stays an error (a forgotten quote, ConditionParserTests); [expected] is the top-level value. + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "compare", "version": 1 }, + "content": [ { "if": "status = [expected]", "then": [ "match" ] } ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, TemplateFormat.Docx); + BuilderHarness.AssertInvariants(imported, template); + Assert.Contains("expected", template.Contract.Entries.Select(e => e.Path)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void LoopMetadataAsOperand_RoundTrips(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["lines"], "line", (line, b) => b.If(line["position"].Eq(line.Loop.Index), x => x.Paragraph(line["name"]))))); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "lines": [ { "position": 0, "name": "kept" }, { "position": 5, "name": "dropped" } ] }"""); + Assert.Contains("kept", BuilderHarness.ParagraphTexts(format, filled)); + Assert.DoesNotContain("dropped", BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void LoopItemAsOperand_RoundTrips(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["tags"], "tag", (tag, b) => b.If(t.Data["chosen"].Contains(tag.Self), x => x.Paragraph(tag.Self))))); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "tags": [ "red", "blue" ], "chosen": [ "blue" ] }"""); + Assert.Contains("blue", BuilderHarness.ParagraphTexts(format, filled)); + Assert.DoesNotContain("red", BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void Typed_PathComparison() + { + string? written = null; + BuilderHarness.Build(new TestDefinition(t => + { + TemplatePath root = t.DataAs(); + written = root.Path(p => p.Owner.Id).Eq(root.Path(p => p.Other.Id)).ToString(); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + Assert.Equal("owner.id = other.id", written); + } + + private sealed record Owner(int Id, string Name); + + private sealed record Pair(Owner Owner, Owner Other); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/PdfLayout.cs b/tests/TriasDev.Templify.Builder.Tests/PdfLayout.cs new file mode 100644 index 00000000..f19c9e77 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/PdfLayout.cs @@ -0,0 +1,171 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Globalization; +using System.Text.RegularExpressions; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +/// +/// Measures what LibreOffice lays out: the first page of a built and filled template as a PDF, its words with their +/// boxes (poppler's pdftotext) and its ink as pixels (pdftoppm). Positions are in points from the page's top left. +/// +internal static partial class PdfLayout +{ + /// A word on the first page: its text and box. + public sealed record Word(string Text, double XMin, double YMin, double XMax, double YMax); + + /// The first page rendered in grey: tells dark pixels, converts. + public sealed class Ink(int width, int height, byte[] pixels, int dpi) + { + public int Width { get; } = width; + + public int Height { get; } = height; + + public double Points(int pixel) => pixel * 72.0 / dpi; + + public int Pixel(double points) => (int)Math.Round(points * dpi / 72.0, MidpointRounding.AwayFromZero); + + public bool IsInk(int x, int y) => pixels[(y * Width) + x] < 160; + + /// The runs of ink in a row: (first, last) pixel, inclusive. + public List<(int First, int Last)> Runs(int y) + { + List<(int, int)> runs = new List<(int, int)>(); + int start = -1; + for (int x = 0; x <= Width; x++) + { + bool ink = x < Width && IsInk(x, y); + if (ink && start < 0) + { + start = x; + } + else if (!ink && start >= 0) + { + runs.Add((start, x - 1)); + start = -1; + } + } + + return runs; + } + + /// The runs of ink in a column: (first, last) pixel, inclusive. + public List<(int First, int Last)> ColumnRuns(int x) + { + List<(int, int)> runs = new List<(int, int)>(); + int start = -1; + for (int y = 0; y <= Height; y++) + { + bool ink = y < Height && IsInk(x, y); + if (ink && start < 0) + { + start = y; + } + else if (!ink && start >= 0) + { + runs.Add((start, y - 1)); + start = -1; + } + } + + return runs; + } + } + + /// Builds, fills (checking the invariants) and converts to PDF with LibreOffice. + public static byte[] Pdf(ITemplateDefinition definition, TemplateFormat format, string json = "{}") + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, json); + return LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "pdf", "pdf"); + } + + /// The words of a page (the first by default) in reading order. + public static List Words(byte[] pdf, int page = 1) + { + string number = page.ToString(CultureInfo.InvariantCulture); + string html = Run(Tool("pdftotext"), pdf, "pdf", (file, _) => ["-bbox", "-f", number, "-l", number, file, "-"], output: null); + return WordBox().Matches(html).Select(m => new Word( + System.Net.WebUtility.HtmlDecode(m.Groups[5].Value), + Number(m.Groups[1].Value), + Number(m.Groups[2].Value), + Number(m.Groups[3].Value), + Number(m.Groups[4].Value))).ToList(); + } + + /// The first word with this text. + public static Word Find(this List words, string text) => + words.FirstOrDefault(w => w.Text == text) ?? throw new InvalidOperationException($"No word '{text}' in [{string.Join(" ", words.Select(w => w.Text))}]."); + + /// The first page as grey pixels at . + public static Ink Pixels(byte[] pdf, int dpi = 288) + { + byte[] pgm = File.ReadAllBytes(Run(Tool("pdftoppm"), pdf, "pdf", (file, output) => ["-gray", "-r", dpi.ToString(CultureInfo.InvariantCulture), "-f", "1", "-l", "1", "-singlefile", file, output!], output: ".pgm")); + int position = 0; + string Token() + { + while (char.IsWhiteSpace((char)pgm[position])) + { + position++; + } + + int start = position; + while (!char.IsWhiteSpace((char)pgm[position])) + { + position++; + } + + return System.Text.Encoding.ASCII.GetString(pgm, start, position - start); + } + + Assert.Equal("P5", Token()); + int width = int.Parse(Token(), CultureInfo.InvariantCulture); + int height = int.Parse(Token(), CultureInfo.InvariantCulture); + _ = Token(); + position++; + return new Ink(width, height, pgm[position..(position + (width * height))], dpi); + } + + private static string Tool(string name) + { + string? executable = new[] { "/opt/homebrew/bin/", "/usr/local/bin/", "/usr/bin/" }.Select(d => d + name).FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, name + " (poppler) is not installed."); + return executable!; + } + + /// Runs a tool on the PDF; returns its standard output, or the path of the output file when one is named. + private static string Run(string executable, byte[] pdf, string extension, Func arguments, string? output) + { + string directory = Path.Combine(Path.GetTempPath(), "templify-pdf-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + string file = Path.Combine(directory, "in." + extension); + File.WriteAllBytes(file, pdf); + string? outputRoot = output is null ? null : Path.Combine(directory, "out"); + ProcessStartInfo start = new ProcessStartInfo(executable) { RedirectStandardOutput = true, UseShellExecute = false }; + foreach (string argument in arguments(file, outputRoot)) + { + start.ArgumentList.Add(argument); + } + + using Process process = Process.Start(start)!; + string text = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + if (output is null) + { + Directory.Delete(directory, recursive: true); + return text; + } + + // The caller reads the file; the temporary directory is left for the OS (one small file per test). + return outputRoot + output; + } + + private static double Number(string text) => double.Parse(text, CultureInfo.InvariantCulture); + + [GeneratedRegex("([^<]+)")] + private static partial Regex WordBox(); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/Phase3ReviewTests.cs b/tests/TriasDev.Templify.Builder.Tests/Phase3ReviewTests.cs new file mode 100644 index 00000000..84332337 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/Phase3ReviewTests.cs @@ -0,0 +1,268 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.Json; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the phase 3 branch review (#274), each pinned by a test. +public sealed class Phase3ReviewTests +{ + private static string Definition(string content) => $$""" + { + "templifyDefinition": 1, + "identity": { "id": "review", "version": 1 }, + "content": {{content}} + } + """; + + // ── C1: deep conditions must not overflow the stack ─────────────────────── + + [Fact] + public void C1_DeeplyNestedCondition_IsADiagnostic() + { + string condition = new string('(', 20_000) + "a" + new string(')', 20_000); + string json = Definition($$"""[ { "if": "{{condition}}", "then": [ { "paragraph": "x" } ] } ]"""); + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(json)); + + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("/content/0/if", error.Location); + Assert.Contains("nested", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void C1_ManyNots_IsADiagnostic() + { + string condition = string.Concat(Enumerable.Repeat("not ", 200_000)) + "a"; + string json = Definition($$"""[ { "if": "{{condition}}", "then": [ { "paragraph": "x" } ] } ]"""); + + Assert.Equal("/content/0/if", Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors).Location); + } + + [Fact] + public void C1_DeeplyNestedRawCondition_IsADiagnostic() + { + string condition = new string('(', 50_000) + "a" + new string(')', 50_000); + string json = Definition($$"""[ { "if": { "raw": "{{condition}}", "uses": [ "a" ] }, "then": [ { "paragraph": "x" } ] } ]"""); + + Assert.Equal("/content/0/if", Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors).Location); + } + + // ── C2: an imported definition can be built concurrently ────────────────── + + [Fact] + public void C2_ImportedDefinition_BuildsConcurrently() + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = CultureInfo.GetCultureInfo("en-GB"), Texts = SampleTexts.Catalog }; + OrderConfirmation definition = new OrderConfirmation(BrandTheme.CreateDefault()); + TemplateJsonDocument exported = TemplateJson.Export(definition, options, SampleRunner.Components); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { Assets = exported.Assets, Components = SampleRunner.Components, Shared = [BrandTheme.CreateDefault()], AllowRawXml = true }); + string expected = TemplateBuilder.Build(definition, options).ContentHash; + + string[] hashes = new string[200]; + Parallel.For(0, hashes.Length, new ParallelOptions { MaxDegreeOfParallelism = 8 }, i => hashes[i] = TemplateBuilder.Build(imported, options).ContentHash); + + Assert.All(hashes, h => Assert.Equal(expected, h)); + } + + // ── I1: every problem is a TemplateBuildException ───────────────────────── + + public sealed record Validating(string Label) : ITemplateComponent + { + public string Label { get; } = Label.Length > 0 ? Label : throw new ArgumentException("A label is required.", nameof(Label)); + + public void Compose(BlockComposer content) => content.Paragraph(Label); + } + + public sealed record Crashing(string Label) : ITemplateComponent + { + public string Label { get; } = Label == "boom" ? throw new InvalidOperationException("boom") : Label; + + public void Compose(BlockComposer content) => content.Paragraph(Label); + } + + [Fact] + public void I1_HeaderRowAfterBodyRow_IsTB9201() + { + string json = Definition(""" + [ { "columns": [ 1 ], "table": [ { "row": [ "a" ] }, { "header": true, "row": [ "h" ] } ] } ] + """); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build(TemplateJson.Import(json), TemplateFormat.Docx)).Errors); + + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/0/table/1", error.Location); + } + + [Theory] + [InlineData("")] + [InlineData("boom")] + public void I1_ComponentConstructorThrowing_IsTB9201(string label) + { + ComponentCatalog catalog = new ComponentCatalog().Register("validating").Register("crashing"); + string name = label.Length == 0 ? "validating" : "crashing"; + string json = Definition($$"""[ { "component": "{{name}}", "params": { "label": "{{label}}" } } ]"""); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build(TemplateJson.Import(json, new TemplateJsonImportOptions { Components = catalog }), TemplateFormat.Docx)).Errors); + + Assert.Equal("TB9201", error.Code); + Assert.Equal("/content/0", error.Location); + } + + [Theory] + [InlineData("\"templifyDefinition\": 1.5", "/templifyDefinition")] + [InlineData("\"identity\": \"x\"", "/identity")] + [InlineData("\"identity\": { \"id\": \"x\", \"version\": 1.5 }", "/identity/version")] + public void I1_MalformedHeader_IsTB9200(string header, string location) + { + string json = Definition("[]").Replace("\"templifyDefinition\": 1", "\"templifyDefinition\": 1, \"__\": 0", StringComparison.Ordinal); + json = header.StartsWith("\"templifyDefinition\"", StringComparison.Ordinal) + ? json.Replace("\"templifyDefinition\": 1, \"__\": 0", header, StringComparison.Ordinal) + : json.Replace("\"identity\": { \"id\": \"review\", \"version\": 1 }", header, StringComparison.Ordinal).Replace(", \"__\": 0", string.Empty, StringComparison.Ordinal); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } + + // ── I2: typed component parameters keep the data's naming ───────────────── + + public sealed record SnakeData(SnakeCustomer Customer); + + public sealed record SnakeCustomer(SnakeAddress HomeAddress); + + public sealed record SnakeAddress(string PostalCode); + + public sealed record SnakeBlock(TemplatePath Address) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(Address.Path(a => a.PostalCode)); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void I2_TypedComponentParameters_RoundTripWithTheCatalogsNaming(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.Component(new SnakeBlock(t.DataAs(JsonNamingPolicy.SnakeCaseLower).Path(d => d.Customer.HomeAddress))))); + ComponentCatalog catalog = new ComponentCatalog { DataNaming = JsonNamingPolicy.SnakeCaseLower }.Register("snake"); + TemplateBuildOptions options = BuilderHarness.Options(format); + + string json = TemplateJson.Export(definition, options, catalog).Json; + GeneratedTemplate imported = TemplateBuilder.Build(TemplateJson.Import(json, new TemplateJsonImportOptions { Components = catalog }), options); + + Assert.Equal(TemplateBuilder.Build(definition, options).ContentHash, imported.ContentHash); + Assert.Contains(new ContractEntry("customer.home_address.postal_code", ContractUsage.Value), imported.Contract.Entries); + } + + [Fact] + public void I2_ParameterNamingDifferentFromTheCatalog_IsAnExportError() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.Component(new SnakeBlock(t.DataAs(JsonNamingPolicy.SnakeCaseLower).Path(d => d.Customer.HomeAddress))))); + + ArgumentException exception = Assert.Throws(() => + TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx), new ComponentCatalog().Register("snake"))); + + Assert.Contains("DataNaming", exception.Message, StringComparison.Ordinal); + } + + // ── I3: computed members are not data paths ─────────────────────────────── + + public sealed record Computed(decimal? Discount, List Lines, string Name, DateTime When, Dictionary Map); + + [Theory] + [InlineData("count")] + [InlineData("length")] + [InlineData("year")] + [InlineData("dotted")] + public void I3_ComputedMembersAndDottedKeys_Throw(string kind) + { + TemplatePath d = default(TemplateComposerProbe).Root; + + Assert.Throws(() => kind switch + { + "count" => d.Path(o => o.Lines.Count).ToString(), + "length" => d.Path(o => o.Name.Length).ToString(), + "year" => d.Path(o => o.When.Year).ToString(), + _ => d.Path(o => o.Map["a.b"]).ToString(), + }); + } + + [Fact] + public void I3_NullableValue_IsTheValueItself() + { + TemplatePath d = default(TemplateComposerProbe).Root; + + Assert.Equal("discount", d.Path(o => o.Discount!.Value).ToString()); + } + + /// A typed root without building a template. + private readonly struct TemplateComposerProbe + { + public TemplatePath Root + { + get + { + TemplatePath? root = null; + BuilderHarness.Build(new TestDefinition(t => + { + root = t.DataAs(); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + return root!.Value; + } + } + } + + // ── I4: with a data catalogue, the kind of a path must fit ──────────────── + + public sealed record KindData(string Title, IReadOnlyList Tags, KindAddress Address); + + public sealed record KindAddress(string City); + + public sealed record KindBlock(TemplatePath Where) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(Where.Path(a => a.City)); + } + + [Fact] + public void I4_CatalogueChecksThatTheKindFits() + { + ComponentCatalog catalog = new ComponentCatalog().Register("where"); + string json = Definition(""" + [ + { "forEach": "title", "as": "t", "body": [ { "paragraph": "x" } ] }, + { "paragraph": "{{address}}" }, + { "component": "where", "params": { "where": "title" } }, + { "forEach": "tags", "as": "tag", "body": [ { "paragraph": "{{tag}}" } ] }, + { "component": "where", "params": { "where": "address" } } + ] + """); + + TemplateBuildException exception = Assert.Throws(() => + TemplateJson.Import(json, new TemplateJsonImportOptions { Components = catalog, Data = DataCatalog.From() })); + + Assert.All(exception.Errors, e => Assert.Equal("TB9203", e.Code)); + Assert.Equal(new[] { "/content/0/forEach", "/content/1/paragraph", "/content/2/params" }, exception.Errors.Select(e => e.Location)); + } + + // ── Re-graded minor: flags must be true ─────────────────────────────────── + + [Theory] + [InlineData("""{ "pageBreak": false }""", "/content/0/pageBreak")] + [InlineData("""{ "paragraph": [ { "tabRight": false } ] }""", "/content/0/paragraph/0/tabRight")] + public void Flags_MustBeTrue(string block, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(Definition("[" + block + "]"))).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/RawTests.cs b/tests/TriasDev.Templify.Builder.Tests/RawTests.cs new file mode 100644 index 00000000..8ae003b1 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/RawTests.cs @@ -0,0 +1,304 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class RawTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private const string Json = """{ "customer": { "name": "Acme GmbH" }, "lines": [ { "code": "A-1" }, { "code": "B-2" } ] }"""; + + /// A paragraph with a document field (the author) and a placeholder, written as format XML. + private static RawBlock AuthorLine(TemplatePath name) => new RawBlock + { + Uses = [name], + Docx = ctx => new XElement(_w + "p", + new XElement(_w + "r", new XElement(_w + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), "Prepared for ")), + new XElement(_w + "r", new XElement(_w + "t", ctx.Placeholder(name))), + new XElement(_w + "r", new XElement(_w + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), " by ")), + new XElement(_w + "fldSimple", new XAttribute(_w + "instr", " AUTHOR "), + new XElement(_w + "r", new XElement(_w + "t", "Author")))), + Odt = ctx => new XElement(_text + "p", + "Prepared for ", + new XElement(_text + "span", ctx.Placeholder(name)), + " by ", + new XElement(_text + "initial-creator", "Author")), + }; + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_BuildsFillsAndValidates(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Paragraph("Before"); + c.Raw(AuthorLine(t.Data["customer"]["name"])); + c.Paragraph("After"); + })); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, Json); + + BuilderHarness.AssertInvariants(definition, template); + List texts = BuilderHarness.ParagraphTexts(format, filled); + Assert.Equal("Before", texts[0]); + // The harness reads plain text only; the ODT field element is checked in Raw_ElementIsWrittenAsGiven. + Assert.StartsWith("Prepared for Acme GmbH by ", texts[1], StringComparison.Ordinal); + Assert.Equal("After", texts[2]); + Assert.Contains(new ContractEntry("customer.name", ContractUsage.Value), template.Contract.Entries); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_ElementIsWrittenAsGiven(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(AuthorLine(t.Data["customer"]["name"])))); + + GeneratedTemplate template = BuilderHarness.Build(definition, format); + + XDocument main = BuilderHarness.ReadXml(template.Content.ToArray(), BuilderHarness.MainPart(format)); + if (format == TemplateFormat.Docx) + { + XElement field = Assert.Single(main.Descendants(_w + "fldSimple")); + Assert.Equal(" AUTHOR ", (string?)field.Attribute(_w + "instr")); + } + else + { + Assert.Single(main.Descendants(_text + "initial-creator")); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_InALoop_ReadsTheItem(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.ForEach(t.Data["lines"], "line", (line, b) => + { + TemplatePath code = line["code"]; + b.Raw(new RawBlock + { + Uses = [code], + Docx = ctx => new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", ctx.Placeholder(code)))), + Odt = ctx => new XElement(_text + "p", ctx.Placeholder(code)), + }); + }))); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, Json); + + BuilderHarness.AssertInvariants(definition, template); + Assert.Equal(new[] { "A-1", "B-2" }, BuilderHarness.ParagraphTexts(format, filled)); + Assert.Contains(new ContractEntry("lines[].code", ContractUsage.Value), template.Contract.Entries); + } + + [Fact] + public void Raw_UsesOutsideItsLoop_IsAScopeError() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + LoopItem? escaped = null; + c.ForEach(t.Data["lines"], "line", (line, b) => escaped = line); + TemplatePath code = escaped!["code"]; + c.Raw(new RawBlock + { + Uses = [code], + Docx = ctx => new XElement(_w + "p"), + Odt = ctx => new XElement(_text + "p"), + }); + })); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Equal("TB4001", Assert.Single(exception.Errors).Code); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_PlaceholderOfAnUndeclaredPath_IsAnError(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + TemplatePath name = t.Data["customer"]["name"]; + c.Raw(new RawBlock + { + Docx = ctx => new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", ctx.Placeholder(name)))), + Odt = ctx => new XElement(_text + "p", ctx.Placeholder(name)), + }); + })); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(format))); + + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB9102", error.Code); + Assert.Contains("customer.name", error.Message, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_ElementThatCannotStandAtBlockLevel_IsAnError(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(new RawBlock + { + Docx = ctx => new XElement(_w + "r", new XElement(_w + "t", "run")), + Odt = ctx => new XElement(_text + "span", "span"), + }))); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(format))); + + Assert.Equal("TB9101", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void Raw_ElementInTheWrongNamespace_IsAnError() + { + // A text:p handed to the DOCX side is the typical copy-paste mistake. + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(new RawBlock + { + Docx = ctx => new XElement(_text + "p", "odt"), + Odt = ctx => new XElement(_text + "p", "odt"), + }))); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Equal("TB9101", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void Raw_NullFactories_AreRejected() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(new RawBlock { Docx = null!, Odt = ctx => new XElement(_text + "p") }))); + + Assert.Throws(() => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_FrameIsTheWidthOfItsContainer(TemplateFormat format) + { + List frames = new List(); + RawBlock Probe() => new RawBlock + { + Docx = ctx => + { + frames.Add(ctx.Frame.Points); + return new XElement(_w + "p"); + }, + Odt = ctx => + { + frames.Add(ctx.Frame.Points); + return new XElement(_text + "p"); + }, + }; + + TestDefinition definition = new TestDefinition(t => + { + t.Page(p => p.Size(PageSize.A4).Margins(20.Mm())); + t.Content(c => + { + c.Raw(Probe()); + c.Table(tb => + { + tb.Columns(cols => + { + cols.Fixed(50.Mm()); + cols.Relative(1); + }); + tb.Row(r => + { + r.Cell(cell => cell.Raw(Probe())); + r.Cell("x"); + }); + }); + }); + }); + + BuilderHarness.Build(definition, format); + + Assert.Equal(2, frames.Count); + Assert.Equal(170.Mm().Points, frames[0], 3); + Assert.True(frames[1] < 50.Mm().Points && frames[1] > 40.Mm().Points, $"cell frame {frames[1]}"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_Table_IsATableToTheWriter(TemplateFormat format) + { + // A raw table that ends the body and touches a builder table: DOCX keeps them apart and ends the body with a + // paragraph, which both need the writer to see a table. + RawBlock table = new RawBlock + { + Docx = ctx => new XElement(_w + "tbl", + new XElement(_w + "tblPr", new XElement(_w + "tblW", new XAttribute(_w + "w", "0"), new XAttribute(_w + "type", "auto"))), + new XElement(_w + "tblGrid", new XElement(_w + "gridCol", new XAttribute(_w + "w", "2000"))), + new XElement(_w + "tr", new XElement(_w + "tc", new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", "raw cell")))))), + Odt = ctx => new XElement(_table + "table", new XAttribute(_table + "name", "RawTable"), + new XElement(_table + "table-column"), + new XElement(_table + "table-row", new XElement(_table + "table-cell", new XElement(_text + "p", "raw cell")))), + }; + + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("builder cell")); + }); + c.Raw(table); + })); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, "{}"); + + BuilderHarness.AssertInvariants(definition, template); + if (format == TemplateFormat.Docx) + { + XElement body = BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml").Descendants(_w + "body").Single(); + Assert.Equal(new[] { "tbl", "p", "tbl", "p", "sectPr" }, body.Elements().Select(e => e.Name.LocalName)); + } + + Assert.Contains("raw cell", BuilderHarness.ReadXml(filled, BuilderHarness.MainPart(format)).ToString(SaveOptions.DisableFormatting), StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Raw_InHeader_IsWritten(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Page(p => p.Header(h => h.Raw(AuthorLine(t.Data["customer"]["name"])))); + t.Content(c => c.Paragraph("Body")); + }); + + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, Json); + + BuilderHarness.AssertInvariants(definition, template); + Assert.Contains(new ContractEntry("customer.name", ContractUsage.Value), template.Contract.Entries); + string part = format == TemplateFormat.Docx ? "word/header1.xml" : "styles.xml"; + Assert.Contains(">Acme GmbH<", BuilderHarness.ReadXml(filled, part).ToString(SaveOptions.DisableFormatting), StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersARawBlock(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Raw(AuthorLine(t.Data["customer"]["name"])))); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, Json); + + string text = System.Text.Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + + Assert.Contains("Prepared for Acme GmbH by", text, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/RenderSafetyTests.cs b/tests/TriasDev.Templify.Builder.Tests/RenderSafetyTests.cs new file mode 100644 index 00000000..7be2f9af --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/RenderSafetyTests.cs @@ -0,0 +1,228 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// +/// Containers stay well-formed once Templify removes the markers (#291): a cell or box still ends with a paragraph, +/// and a table never touches the next one. +/// +public sealed class RenderSafetyTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly BoxStyleKey _box = new BoxStyleKey("Framed"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static StyleSheet Sheet() => StyleSheet.Create(s => s.Box(_box, b => b.Border(1.Pt(), Color.FromHex("000000")))); + + private static void Inner(BlockComposer c) => c.Table(t => + { + t.Columns(cols => cols.Relative(1)); + t.Row(r => r.Cell("inner")); + }); + + private static XElement Body(TemplateFormat format, byte[] package) => + format == TemplateFormat.Docx + ? BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_w + "body").Single() + : BuilderHarness.ReadXml(package, "content.xml").Descendants(_office + "text").Single(); + + private static XName TableName(TemplateFormat format) => format == TemplateFormat.Docx ? _w + "tbl" : _table + "table"; + + private static XName ParagraphName(TemplateFormat format) => format == TemplateFormat.Docx ? _w + "p" : _text + "p"; + + private static XElement FirstCell(TemplateFormat format, XElement table) => + format == TemplateFormat.Docx ? table.Descendants(_w + "tc").First() : table.Descendants(_table + "table-cell").First(); + + /// The last content element of a cell (DOCX: not the cell properties). + private static XElement LastContent(XElement cell) => cell.Elements().Last(e => e.Name.LocalName is not "tcPr"); + + [Theory] + [MemberData(nameof(Formats))] + public void CellEndingWithAConditional_StillEndsWithAParagraph(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => + { + Inner(cell); + cell.If(t.Data["flag"], b => b.Paragraph("only when flagged")); + })); + }))); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "flag": false }"""); + + XElement outer = Body(format, filled).Elements(TableName(format)).Single(); + Assert.Equal(ParagraphName(format), LastContent(FirstCell(format, outer)).Name); + } + + [Theory] + [MemberData(nameof(Formats))] + public void BoxEndingWithAnEmptyLoop_StillEndsWithAParagraph(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Box(_box, b => + { + Inner(b); + b.ForEach(t.Data["items"], "item", (item, body) => body.Paragraph(item["name"])); + })); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "items": [] }"""); + + XElement box = Body(format, filled).Elements(TableName(format)).Single(); + Assert.Equal(ParagraphName(format), LastContent(FirstCell(format, box)).Name); + } + + [Theory] + [MemberData(nameof(Formats))] + public void TablesAroundARemovedConditional_StayApart(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + Inner(c); + c.If(t.Data["flag"], b => b.Paragraph("between")); + Inner(c); + })); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "flag": false }"""); + + List children = Body(format, filled).Elements().Where(e => e.Name == TableName(format) || e.Name == ParagraphName(format)).ToList(); + int first = children.FindIndex(e => e.Name == TableName(format)); + Assert.Equal(ParagraphName(format), children[first + 1].Name); + Assert.Equal(TableName(format), children[first + 2].Name); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NoSpacer_WhenNothingNeedsOne(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => cell.If(t.Data["flag"], b => b.Paragraph("x")).Else(b => b.Paragraph("y")))); + }); + c.Paragraph("after"); + })); + + GeneratedTemplate template = BuilderHarness.Build(definition, format); + string styles = BuilderHarness.ReadXml(template.Content.ToArray(), format == TemplateFormat.Docx ? "word/styles.xml" : "styles.xml").ToString(); + string withSpacer = BuilderHarness.ReadXml(BuilderHarness.Build(new TestDefinition(t => t.Content(c => + { + Inner(c); + c.If(t.Data["flag"], b => b.Paragraph("x")); + })), format).Content.ToArray(), format == TemplateFormat.Docx ? "word/styles.xml" : "styles.xml").ToString(); + + Assert.Contains("TemplifyMarker", styles, StringComparison.Ordinal); + Assert.DoesNotContain("TemplifySpacer", styles, StringComparison.Ordinal); + Assert.Contains("TemplifySpacer", withSpacer, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void RawBlocks_CountByTheirRoot(TemplateFormat format) + { + RawBlock paragraph = new RawBlock + { + Docx = _ => new XElement(_w + "p", new XElement(_w + "r", new XElement(_w + "t", "raw paragraph"))), + Odt = _ => new XElement(_text + "p", "raw paragraph"), + }; + RawBlock table = new RawBlock + { + Docx = ctx => new XElement(_w + "tbl", new XElement(_w + "tblGrid", new XElement(_w + "gridCol", new XAttribute(_w + "w", "2000"))), new XElement(_w + "tr", new XElement(_w + "tc", new XElement(_w + "p")))), + Odt = _ => new XElement(_table + "table", new XElement(_table + "table-column"), new XElement(_table + "table-row", new XElement(_table + "table-cell", new XElement(_text + "p")))), + }; + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.Row(r => + { + r.Cell(cell => cell.Raw(paragraph)); + r.Cell(cell => cell.Raw(table)); + }); + }))); + + GeneratedTemplate template = BuilderHarness.Build(definition, format); + + XElement outer = Body(format, template.Content.ToArray()).Elements(TableName(format)).Single(); + List cells = (format == TemplateFormat.Docx ? outer.Elements(_w + "tr").Single().Elements(_w + "tc") : outer.Elements(_table + "table-row").Single().Elements(_table + "table-cell")).ToList(); + Assert.Single(cells[0].Elements(ParagraphName(format))); + Assert.Equal(ParagraphName(format), LastContent(cells[1]).Name); + Assert.Contains("TemplifySpacer", LastContent(cells[1]).ToString(), StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NestedBoxEndingWithAConditional_BothCellsEndWithAParagraph(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Box(_box, outer => outer.Box(_box, inner => + { + Inner(inner); + inner.If(t.Data["flag"], b => b.Paragraph("x")); + }))); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "flag": false }"""); + + XElement outerBox = Body(format, filled).Elements(TableName(format)).Single(); + XElement outerCell = FirstCell(format, outerBox); + XElement innerBox = outerCell.Elements(TableName(format)).Single(); + Assert.Equal(ParagraphName(format), LastContent(outerCell).Name); + Assert.Equal(ParagraphName(format), LastContent(FirstCell(format, innerBox)).Name); + } + + [Fact] + public void HeaderWithTablesAroundAConditional_StaysApartAndEndsWithAParagraph() + { + TestDefinition definition = new TestDefinition(t => + { + t.Page(p => p.Header(h => + { + Inner(h); + h.If(t.Data["flag"], b => b.Paragraph("between")); + Inner(h); + h.If(t.Data["flag"], b => b.Paragraph("after")); + })); + t.Content(c => c.Paragraph("body")); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, TemplateFormat.Docx, """{ "flag": false }"""); + + List header = BuilderHarness.ReadXml(filled, "word/header1.xml").Root!.Elements().ToList(); + Assert.Equal(ParagraphName(TemplateFormat.Docx), header[^1].Name); + Assert.DoesNotContain(header.Zip(header.Skip(1)), pair => pair.First.Name == _w + "tbl" && pair.Second.Name == _w + "tbl"); + } + + [Fact] + public void CommaInAStyleName_IsTB2006() + { + ParagraphStyleKey key = new ParagraphStyleKey("Body", "Body, main"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(key, p => p.Bold()))); + t.Content(c => c.Paragraph(key, "x")); + }); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)).Errors); + Assert.Equal("TB2006", error.Code); + Assert.Contains("Body, main", error.Message, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ReviewFixes274Tests.cs b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes274Tests.cs new file mode 100644 index 00000000..d3ccbb53 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes274Tests.cs @@ -0,0 +1,158 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json.Nodes; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the final review of #274. +public sealed class ReviewFixes274Tests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static string Definition(string content, string extra = "") => + $$"""{ "templifyDefinition": 1, "identity": { "id": "x", "version": 1 }, {{extra}} "content": {{content}} }"""; + + // ── 1: Preview and Patch report, they do not throw ────────────────────── + + public static TheoryData PreviewInputs => new TheoryData + { + { Definition("""[ "Hello" ]"""), "" }, + { Definition("""[ "Hello" ]"""), " " }, + { Definition("""[ "a\u0001b" ]"""), null }, + { Definition("""[ "a\uD800b" ]"""), null }, + { Definition("""[ "x" ]""", """ "styles": { "paragraph": { "P": { "name": "N\u0001" } } }, """), null }, + }; + + [Theory] + [MemberData(nameof(PreviewInputs))] + public void Preview_NeverThrows(string json, string? data) + { + foreach (TemplateFormat format in BuilderHarness.Formats) + { + TemplatePreview preview = TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(format), data); + Assert.Equal(TemplateCheckStatus.Broken, preview.Check.Status); + Assert.Null(preview.Document); + } + } + + [Fact] + public void Patch_WithBuild_ReportsAnInvalidCharacter() + { + TemplatePatchResult result = TemplateJson.Patch(Definition("""[ "Hello" ]"""), """[ { "op": "add", "path": "/content/-", "value": "a\u0001b" } ]""", + new TemplateJsonImportOptions { Data = DataCatalog.From() }, BuilderHarness.Options(TemplateFormat.Docx)); + Assert.True(result.Applied); + Assert.Equal(TemplateCheckStatus.Broken, result.Check.Status); + } + + // ── 2: Preview keeps the fill's warnings ───────────────────────────────── + + [Fact] + public void Preview_MissingLoopCollection_IsAWarning() + { + TemplatePreview preview = TemplateJson.Preview(Definition("""[ { "forEach": "items", "as": "item", "body": [ "{{item}}" ] } ]"""), + new TemplateJsonImportOptions(), BuilderHarness.Options(TemplateFormat.Docx), "{}"); + Assert.Equal(TemplateCheckStatus.Warning, preview.Check.Status); + Assert.Contains(preview.Check.Problems, p => p.DataPath == "items"); + } + + // ── 3: Preview text has headers, footers, tabs and line breaks ────────── + + [Theory] + [MemberData(nameof(Formats))] + public void PreviewText_HasPartsTabsAndBreaks(TemplateFormat format) + { + string json = Definition( + """[ "BODY\tTAB two spaces\nline2" ]""", + """ "page": { "header": [ "HEADERTEXT" ], "footer": [ "FOOTERTEXT" ] }, """); + TemplatePreview preview = TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(format), "{}"); + Assert.Contains("BODY\tTAB two spaces\nline2", preview.Text, StringComparison.Ordinal); + Assert.Contains("HEADERTEXT", preview.Text, StringComparison.Ordinal); + Assert.Contains("FOOTERTEXT", preview.Text, StringComparison.Ordinal); + } + + // ── 4: Outline reads any JSON object without throwing ─────────────────── + + [Theory] + [InlineData("""[ { "section": 5, "blocks": [] } ]""")] + [InlineData("""[ { "toc": "x" } ]""")] + [InlineData("""[ { "toc": { "maxLevel": "x" } } ]""")] + [InlineData("""[ { "rule": "x" } ]""")] + [InlineData("""[ { "if": "a", "then": [], "elseIf": [ "x" ] } ]""")] + [InlineData("""[ { "style": 5, "paragraph": "x" } ]""")] + [InlineData("""[ { "forEach": 5, "as": 1, "body": [] } ]""")] + [InlineData("""[ { "component": 5 } ]""")] + [InlineData("""[ { "spacer": 5 } ]""")] + [InlineData("""[ { "paragraph": [ { "text": 5 } ] } ]""")] + [InlineData("""[ { "columns": [1], "table": [ { "row": [ { "span": "x", "content": [ "a" ] } ] }, 5, { "forEachRow": 1, "as": 2, "rows": [] } ] } ]""")] + [InlineData("""[ { "style": "B", "list": [ 5, { "forEach": 1, "as": 2, "items": [] }, { "item": 3 } ] } ]""")] + public void Outline_WrongTypes_DoNotThrow(string content) => TemplateJson.Outline(Definition(content)); + + [Theory] + [InlineData("[]")] + [InlineData("5")] + public void Outline_NotAnObject_IsAnArgumentError(string json) => + Assert.Throws(() => TemplateJson.Outline(json)); + + // ── 5: required flags match the reader ─────────────────────────────────── + + public static TheoryData Constructs => new TheoryData(JsonVocabulary.All.Select(c => c.Name)); + + [Theory] + [MemberData(nameof(Constructs))] + public void RequiredKeys_MatchTheReader(string name) + { + // Every required key is in the example; dropping it fails the import, dropping an optional one does not. + Construct construct = JsonVocabulary.All.Single(c => c.Name == name); + JsonObject example = JsonNode.Parse(construct.Example)!.AsObject(); + foreach (VocabularyKey key in construct.Keys) + { + if (!example.ContainsKey(key.Name)) + { + Assert.False(key.Required, $"{name}.{key.Name} is required but not in the example."); + continue; + } + + // A component's params are needed when it has parameters (the example's has), not for one without. + if (name == "component" && key.Name == "params") + { + continue; + } + + JsonObject without = example.DeepClone().AsObject(); + without.Remove(key.Name); + string json = JsonVocabularyTests.Place(construct, without); + bool accepted = Imports(json) && (!key.Required || Builds(json)); + Assert.True(accepted != key.Required, $"{name}.{key.Name}: required {key.Required}, but the definition is {(accepted ? "accepted" : "rejected")} without it."); + } + } + + /// A required key the build checks (a table's columns) is required too. + private static bool Builds(string json) + { + try + { + TemplateBuilder.Build(TemplateJson.Import(json, JsonVocabularyTests.ImportOptions), BuilderHarness.Options(TemplateFormat.Docx)); + return true; + } + catch (TemplateBuildException) + { + return false; + } + } + + private static bool Imports(string json) + { + try + { + TemplateJson.Import(json, JsonVocabularyTests.ImportOptions); + return true; + } + catch (TemplateBuildException) + { + return false; + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ReviewFixes293Tests.cs b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes293Tests.cs new file mode 100644 index 00000000..506a7b67 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes293Tests.cs @@ -0,0 +1,184 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the final review of the JSON format round (#293). +public sealed class ReviewFixes293Tests +{ + private static readonly ListStyleKey _bullets = new ListStyleKey("Bullets"); + + // ── 1: line breaks and tabs, composed either way, export ───────────────── + + public static TheoryData BreakDefinitions => new() { "inline-break", "inline-tab", "paragraph-string", "cell", "list-item" }; + + private static TestDefinition Breaks(string kind) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.List(_bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm())))); + t.Content(c => + { + _ = kind switch + { + "inline-break" => c.Paragraph(x => x.Text("a").LineBreak().Text("b")), + "inline-tab" => c.Paragraph(x => x.Text("a").Tab().Text("b")), + "paragraph-string" => c.Paragraph("a\nb\tc"), + "cell" => c.Table(table => table.Columns(k => k.Relative(1)).Row(r => r.Cell("a\nb"))), + _ => c.List(_bullets, l => l.Item("a\tb")), + }; + }); + }); + + [Theory] + [MemberData(nameof(BreakDefinitions))] + public void LineBreaksAndTabs_RoundTripThroughJson(string kind) + { + foreach (TemplateFormat format in new[] { TemplateFormat.Docx, TemplateFormat.Odt }) + { + TestDefinition definition = Breaks(kind); + BuilderHarness.AssertInvariants(definition, BuilderHarness.Build(definition, format)); + } + } + + [Fact] + public void ParagraphString_WithABreak_BuildsLikeTheInlineForm() + { + TestDefinition text = new TestDefinition(t => t.Content(c => c.Paragraph("a\nb"))); + TestDefinition inline = new TestDefinition(t => t.Content(c => c.Paragraph(x => x.Text("a").LineBreak().Text("b")))); + + Assert.Equal(BuilderHarness.Build(inline, TemplateFormat.Docx).ContentHash, BuilderHarness.Build(text, TemplateFormat.Docx).ContentHash); + } + + // ── 2: a host value format exports; the import still asks for it ───────── + + [Fact] + public void CustomValueFormat_Exports_AndTheImportNeedsItListed() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(x => x.Value(t.Data["ok"], ValueFormat.Custom("janein"))))); + TemplateBuildOptions options = BuilderHarness.Options(TemplateFormat.Docx); + + TemplateJsonDocument exported = TemplateJson.Export(definition, options); + + Assert.Contains("{{ok:janein}}", exported.Json, StringComparison.Ordinal); + Assert.Equal("TB9200", Assert.Single(Assert.Throws(() => TemplateJson.Import(exported.Json)).Errors).Code); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions { ValueFormats = ["janein"] }); + Assert.Equal(TemplateBuilder.Build(definition, options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + } + + // ── 3: a requested language a text does not have is named at export ────── + + [Fact] + public void Export_TextLanguages_TextWithoutOneOfThem_IsAClearError() + { + ITextCatalog catalog = TextCatalog.FromDictionary(new Dictionary> + { + ["a"] = new Dictionary { ["en"] = "A", ["de"] = "A" }, + ["b"] = new Dictionary { ["en"] = "B" }, + }); + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Paragraph(t.Texts["a"]).Paragraph(t.Texts["b"]))); + + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Export( + definition, + BuilderHarness.Options(TemplateFormat.Docx) with { Texts = catalog }, + new TemplateJsonExportOptions { TextLanguages = [CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de")] })).Errors); + + Assert.Equal("TB9204", error.Code); + Assert.Contains("'b'", error.Message, StringComparison.Ordinal); + Assert.Contains("de", error.Message, StringComparison.Ordinal); + Assert.DoesNotContain("the same", error.Message, StringComparison.Ordinal); + } + + // ── 4: host theme values must fit the token ────────────────────────────── + + private const string ThemedJson = """ + {"templifyDefinition": 1, "identity": {"id": "t", "version": 1}, + "theme": {"colors": {"accent": "#1F4E79"}}, + "styles": {"paragraph": {"P": {"name": "P", "color": "$accent"}}}, + "content": [{"style": "P", "paragraph": "x"}]} + """; + + [Fact] + public void HostTheme_NonColourForAColourToken_IsAnError() + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => BuilderHarness.Build( + TemplateJson.Import(ThemedJson, new TemplateJsonImportOptions { Theme = new Dictionary { ["accent"] = "00A000" } }), + TemplateFormat.Docx)).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Contains("accent", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void HostTheme_TokenTheDefinitionDoesNotHave_IsAWarning() + { + GeneratedTemplate template = BuilderHarness.Build( + TemplateJson.Import(ThemedJson, new TemplateJsonImportOptions { Theme = new Dictionary { ["acent"] = "#00A000" } }), + TemplateFormat.Docx); + + BuildDiagnostic warning = Assert.Single(template.Warnings, w => w.Code == "TB9205"); + Assert.Contains("acent", warning.Message, StringComparison.Ordinal); + } + + // ── 5: theme tokens in registered component parameters ─────────────────── + + public sealed record Bar(Color Colour) : ITemplateComponent + { + public void Compose(BlockComposer c) => c.Rule(1.Pt(), Colour); + } + + private static TestDefinition Barred(Color accent) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(new ParagraphStyleKey("P", "P"), p => p.Color(accent)))); + t.Content(c => c.Paragraph(new ParagraphStyleKey("P", "P"), "x").Component(new Bar(accent))); + }); + + [Fact] + public void ComponentParameter_ThemeColour_IsWrittenAsToken_AndFollowsTheHostTheme() + { + ComponentCatalog components = new ComponentCatalog().Register("bar"); + TemplateBuildOptions options = BuilderHarness.Options(TemplateFormat.Docx); + + TemplateJsonDocument exported = TemplateJson.Export(Barred(Color.Token("accent", Color.FromHex("1F4E79"))), options, components); + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions + { + Components = components, + Theme = new Dictionary { ["accent"] = "#FF0000" }, + }); + + Assert.Contains("\"colour\": \"$accent\"", exported.Json, StringComparison.Ordinal); + Assert.Equal(TemplateBuilder.Build(Barred(Color.Token("accent", Color.FromHex("FF0000"))), options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + } + + // ── 6: a generic component's section name ──────────────────────────────── + + private sealed class Card : ITemplateComponent + { + public void Compose(BlockComposer c) => c.Paragraph(typeof(T).Name); + } + + [Fact] + public void UnregisteredGenericComponent_Exports() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Component(new Card()).Component(new Card()))); + + BuilderHarness.AssertInvariants(definition, BuilderHarness.Build(definition, TemplateFormat.Docx)); + Assert.Contains("\"section\": \"Card\"", TemplateJson.Export(definition, BuilderHarness.Options(TemplateFormat.Docx)).Json, StringComparison.Ordinal); + } + + // ── 7, 8: malformed input is a TemplateBuildException ──────────────────── + + [Theory] + [InlineData("""{"templifyDefinition": 1, "identity": {"id": "t", "version": 1}, "texts": {"a": {"de": "x", "DE": "y"}}, "content": ["[[a]]"]}""", "/texts/a")] + [InlineData("""{"templifyDefinition": 1, "identity": {"id": "t", "version": "1"}, "content": []}""", "/identity/version")] + [InlineData("""{"templifyDefinition": "1", "identity": {"id": "t", "version": 1}, "content": []}""", "/templifyDefinition")] + public void MalformedInput_IsTB9200(string json, string location) + { + BuildDiagnostic error = Assert.Single(Assert.Throws(() => TemplateJson.Import(json)).Errors); + + Assert.Equal("TB9200", error.Code); + Assert.Equal(location, error.Location); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ReviewFixes294Tests.cs b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes294Tests.cs new file mode 100644 index 00000000..26a1daef --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes294Tests.cs @@ -0,0 +1,199 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the final review of the stored-template check (#294). +public sealed class ReviewFixes294Tests +{ + public sealed record Data(Ord Order); + + public sealed record Ord(string Number, IReadOnlyList Lines, Customer Customer, Dictionary Extra, List> Rows); + + public sealed record Ln(string Description, Product Product); + + public sealed record Product(string Name); + + public sealed record Customer(string Name); + + public class Base + { + public int Name { get; set; } + } + + public sealed class Derived : Base + { + public new string Name { get; set; } = string.Empty; + } + + public sealed record DuplicateData(Derived Item); + + public static class Env + { + public sealed record Meta(T Value, string Label); + } + + public sealed record NestedGenericData(Env.Meta Meta); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly DataCatalog _catalog = DataCatalog.From(); + + private static TemplateCheckResult Check(GeneratedTemplate template, DataCatalog? catalog = null) => + TemplateInspector.Check(template.OpenRead(), new TemplateCheckOptions { Data = catalog ?? _catalog }); + + private static TemplateCheckResult Check(byte[] template) => + TemplateInspector.Check(new MemoryStream(template), new TemplateCheckOptions { Data = _catalog }); + + private static GeneratedTemplate Build(Action content, TemplateFormat format = TemplateFormat.Docx) => + BuilderHarness.Build(new TestDefinition(t => t.Content(c => content(t.Data["order"], c))), format); + + private static IEnumerable Unknown(TemplateCheckResult result) => + result.Problems.Where(p => p.Code == "TB9301").Select(p => p.DataPath).Order(StringComparer.Ordinal); + + [Theory] + [MemberData(nameof(Formats))] + public void C1_RemovedNestedFieldOfALoopItem_IsBroken(TemplateFormat format) + { + GeneratedTemplate copy = Build((order, c) => c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(line["product"]["removed"])), format); + + TemplateCheckResult result = Check(copy); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Equal(["line.product.removed"], Unknown(result)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void C1_RemovedNestedField_ImplicitLoopName_IsBroken(TemplateFormat format) + { + byte[] bytes = Build((order, c) => c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(line["product"]["removed"])), format).Content.ToArray(); + byte[] implicitName = BuilderHarness.EditEntry(bytes, BuilderHarness.MainPart(format), xml => xml + .Replace("foreach line in order.lines", "foreach order.lines", StringComparison.Ordinal) + .Replace("line.product.removed", "product.removed", StringComparison.Ordinal)); + + TemplateCheckResult result = Check(implicitName); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Contains(result.Problems, p => p.Code == "TB9301" && p.DataPath == "product.removed"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void RemovedNestedFieldInACondition_IsFound_Since299(TemplateFormat format) + { + // Until core #299 the engine's validation checked only the first segment of a loop item's path, and the trial + // fill does not report condition variables: this was a documented limit of the check. + GeneratedTemplate copy = Build((order, c) => c.ForEach(order["lines"], "line", (line, b) => b.If(line["product"]["removed"], x => x.Paragraph("x"))), format); + + TemplateCheckResult result = Check(copy); + + Assert.Contains(result.Problems, p => p.DataPath == "line.product.removed"); + Assert.NotEqual(TemplateCheckStatus.Ok, result.Status); + } + + [Theory] + [MemberData(nameof(Formats))] + public void RemovedNestedFieldInAnUntakenBranch_IsFound_Since299(TemplateFormat format) + { + // The witness's values are the text "x", so the branch is not taken in the trial fill; validation checks it. + GeneratedTemplate copy = Build( + (order, c) => c.If(order["number"].Eq("never"), b => b.ForEach(order["lines"], "line", (line, x) => x.Paragraph(line["product"]["removed"]))), + format); + + TemplateCheckResult result = Check(copy); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Contains("line.product.removed", Unknown(result)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void C1_ExistingNestedFieldOfALoopItem_IsOk(TemplateFormat format) + { + GeneratedTemplate copy = Build( + (order, c) => c.ForEach(order["lines"], "line", (line, b) => + { + b.Paragraph(line["product"]["name"]); + b.If(line["product"]["name"], x => x.Paragraph("named")); + }), + format); + + Assert.Equal(TemplateCheckStatus.Ok, Check(copy).Status); + } + + [Theory] + [MemberData(nameof(Formats))] + public void I1_ClosedTypoInsideALoopOverAnOpenShape_IsBroken(TemplateFormat format) + { + GeneratedTemplate copy = Build( + (order, c) => + { + c.ForEach(order["extra"]["items"], "e", (e, b) => b.Paragraph(x => x.Value(e["name"]).Value(order["customer"]["typo"]))); + c.ForEach(order["rows"], "r", (r, b) => b.Paragraph(x => x.Value(r["anything"]).Value(order["customer"]["other"]))); + }, + format); + + TemplateCheckResult result = Check(copy); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Equal(["order.customer.other", "order.customer.typo"], Unknown(result)); + } + + [Fact] + public void I1_LoopOverAnOpenShape_WithKnownPaths_IsOk() + { + GeneratedTemplate copy = Build((order, c) => c.ForEach(order["extra"]["items"], "e", (e, b) => + { + b.Paragraph(x => x.Value(e["name"]).Value(order["customer"]["name"])); + b.ForEach(e["children"], "child", (child, d) => d.If(child["flag"], y => y.Paragraph(child["label"]))); + })); + + Assert.DoesNotContain(Check(copy).Problems, p => p.Severity == TemplateCheckSeverity.Error); + } + + [Theory] + [MemberData(nameof(Formats))] + public void I3_IndexedPaths_AreOk(TemplateFormat format) + { + GeneratedTemplate copy = Build( + (order, c) => + { + c.Paragraph(order["lines[1].description"]); + c.Paragraph(order["lines[2].product.name"]); + c.Paragraph(order["extra.items[0].name"]); + c.Paragraph(order["extra[3]"]); + }, + format); + + Assert.DoesNotContain(Check(copy).Problems, p => p.Severity == TemplateCheckSeverity.Error); + } + + [Fact] + public void I3_IndexedPathToARemovedField_IsBroken() + { + GeneratedTemplate copy = Build((order, c) => c.Paragraph(order["lines[2].removed"])); + + Assert.Equal(["order.lines[2].removed"], Unknown(Check(copy))); + } + + [Fact] + public void I4_CatalogueWithAHiddenProperty_DoesNotThrow() + { + GeneratedTemplate copy = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["item"]["name"]))), TemplateFormat.Docx); + + TemplateCheckResult result = Check(copy, DataCatalog.From()); + + Assert.DoesNotContain(result.Problems, p => p.Severity == TemplateCheckSeverity.Error); + } + + [Fact] + public void M1_ToJson_TypeNestedInAGenericType_DoesNotThrow() + { + string json = DataCatalog.From().ToJson(); + + Assert.Contains("Meta", json, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ReviewFixes296Tests.cs b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes296Tests.cs new file mode 100644 index 00000000..cfcf661f --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ReviewFixes296Tests.cs @@ -0,0 +1,55 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the final review of #296. +public sealed class ReviewFixes296Tests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + [Theory] + [MemberData(nameof(Formats))] + public void NarrowGutterColumn_WithDefaultPadding_StillBuilds(TemplateFormat format) + { + // Before #296 a gutter column narrower than Word's default cell margins built; it must still. + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1).Fixed(8.Pt()).Relative(1)); + tb.Row(r => r.Cell("left").Cell(string.Empty).Cell("right")); + }))); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + } + + [Fact] + public void BorderBottomSpace_AboveWhatDocxHolds_Throws() + { + // DOCX holds a border space of 0 to 31 pt (ST_PointMeasure); more would be an invalid document. + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(new ParagraphStyleKey("Head", "Head"), p => p.BorderBottom(0.75.Pt(), Color.FromHex("C8C8C8"), 32.Pt())))); + t.Content(c => c.Paragraph("x")); + }); + Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ZeroIndent_BuildsLikeNoIndent(TemplateFormat format) + { + TestDefinition Define(bool indent) => new TestDefinition(t => t.Content(c => c.Table(tb => + { + if (indent) + { + tb.Indent(Length.Zero); + } + + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("x")); + }))); + Assert.Equal(BuilderHarness.Build(Define(indent: false), format).ContentHash, BuilderHarness.Build(Define(indent: true), format).ContentHash); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/ReviewFixesFinalTests.cs b/tests/TriasDev.Templify.Builder.Tests/ReviewFixesFinalTests.cs new file mode 100644 index 00000000..a010052c --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/ReviewFixesFinalTests.cs @@ -0,0 +1,182 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TriasDev.Templify.Builder.Tests; + +/// Findings of the final review before the merge into main (2026-12-01). +public sealed class ReviewFixesFinalTests +{ + private static readonly TemplatePath _total = TemplatePath.Root("total"); + + [Theory] + [InlineData(19.99, "total > 19.99")] + [InlineData(0.1, "total > 0.1")] + [InlineData(-2.5, "total > -2.5")] + [InlineData(1234567.125, "total > 1234567.125")] + [InlineData(1e20, "total > 100000000000000000000")] + [InlineData(0.0000001, "total > 0.0000001")] + [InlineData(3, "total > 3")] + public void NumberInACondition_IsItsShortestDecimalText(double value, string expected) + { + // .NET 11 converts double to decimal exactly (19.99 → 19.989999999999998436805981328), .NET 10 rounded: the + // condition text, and so the template's bytes and the exported JSON, differed by runtime. + Assert.Equal(expected, _total.Gt(value).ToString()); + } +} + +/// Final review I1: ODT table edges when a row loop or row conditional is the first or last row. +public sealed class OdtTableEdgeTests +{ + private static readonly System.Xml.Linq.XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly System.Xml.Linq.XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly System.Xml.Linq.XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly TableStyleKey _boxed = new TableStyleKey("Boxed"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + public static TheoryData Shapes => new TheoryData("loop only", "header and loop", "last row conditional", "first row conditional"); + + private static TestDefinition Define(string shape) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Table(_boxed, g => g.OuterBorder(3.Pt(), Color.FromHex("000000")).RowRule(0.25.Pt(), Color.FromHex("BBBBBB"))))); + t.Content(c => c.Table(tb => + { + tb.Style(_boxed); + tb.Columns(cols => cols.Relative(1)); + if (shape == "first row conditional") + { + tb.RowsIf(t.Data["show"], rows => rows.Row(r => r.Cell("shown"))); + } + + if (shape == "header and loop") + { + tb.HeaderRow(r => r.Cell("Head")); + } + + if (shape is "loop only" or "header and loop") + { + tb.ForEachRow(t.Data["lines"], "line", (line, rows) => rows.Row(r => r.Cell(line.Self))); + } + else + { + tb.Row(r => r.Cell("a")); + tb.Row(r => r.Cell("b")); + } + + if (shape == "last row conditional") + { + tb.RowsIf(t.Data["show"], rows => rows.Row(r => r.Cell("shown"))); + } + })); + }); + + private const string Data = """{ "lines": [ "one", "two", "three", "four" ], "show": false }"""; + + [Fact] + public void LoopRows_CarryOnlyRowRules_AndAnEdgeRowCarriesTheOuterLine() + { + GeneratedTemplate template = BuilderHarness.Build(Define("loop only"), Core.TemplateFormat.Odt); + System.Xml.Linq.XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + string Style(System.Xml.Linq.XElement cell, string side) => content.Descendants(_style + "style") + .Single(s => s.Attribute(_style + "name")!.Value == cell.Attribute(_table + "style-name")!.Value) + .Element(_style + "table-cell-properties")!.Attribute(_fo + "border-" + side)!.Value; + + List rows = content.Descendants(_table + "table").Single().Elements(_table + "table-row").ToList(); + System.Xml.Linq.XElement loopRow = rows.Single(r => OdtText(r) == "{{line}}"); + Assert.StartsWith("0.25pt", Style(loopRow.Element(_table + "table-cell")!, "top"), StringComparison.Ordinal); + Assert.StartsWith("0.25pt", Style(loopRow.Element(_table + "table-cell")!, "bottom"), StringComparison.Ordinal); + Assert.StartsWith("3pt", Style(rows[0].Element(_table + "table-cell")!, "bottom"), StringComparison.Ordinal); + Assert.StartsWith("3pt", Style(rows[^1].Element(_table + "table-cell")!, "top"), StringComparison.Ordinal); + } + + [Fact] + public void PlainEdges_AddNoRow() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Table(_boxed, g => g.OuterBorder(3.Pt(), Color.FromHex("000000"))))); + t.Content(c => c.Table(tb => + { + tb.Style(_boxed); + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("a")); + tb.Row(r => r.Cell("b")); + })); + }); + System.Xml.Linq.XDocument content = BuilderHarness.ReadXml(BuilderHarness.Build(definition, Core.TemplateFormat.Odt).Content.ToArray(), "content.xml"); + Assert.Equal(2, content.Descendants(_table + "table-row").Count()); + } + + [Theory] + [MemberData(nameof(Shapes))] + public void Edges_AreValidAndFill(string shape) + { + foreach (Core.TemplateFormat format in BuilderHarness.Formats) + { + BuilderHarness.BuildAndFill(Define(shape), format, Data); + } + } + + [Theory] + [MemberData(nameof(Shapes))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_OnlyTheTwoOuterLinesAreThick(string shape) + { + foreach (Core.TemplateFormat format in BuilderHarness.Formats) + { + PdfLayout.Ink ink = PdfLayout.Pixels(PdfLayout.Pdf(Define(shape), format, Data)); + + // A column 3 pt inside the table's left edge (25 mm frame start): past the outer vertical line, before the + // cell text (5.4 pt padding); only the horizontal lines cross it. + int x = ink.Pixel((25 * 72 / 25.4) + 3); + List lines = ink.ColumnRuns(x).Select(r => ink.Points(r.Last - r.First + 1)).ToList(); + Assert.True(lines.Count(l => l >= 2) == 2, $"{format} {shape}: thick lines {string.Join(", ", lines.Select(l => l.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture)))}"); + } + } + + private static string OdtText(System.Xml.Linq.XElement element) => string.Concat(element.Descendants().Where(e => e.Name.LocalName == "p").Select(e => e.Value)); +} + +/// A path interpolated into literal text is reported, not printed as its name (API review I2). +public sealed class InterpolatedPathTests +{ + [Fact] + public void InterpolatedPath_InLiteralText_IsTB1002() + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath number = t.Data["report"]["number"]; + t.Content(c => c.Paragraph($"Report {number}")); + }); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(Core.TemplateFormat.Docx))); + + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB1002", error.Code); + Assert.Contains("Report {{report.number}}", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void InterpolatedTypedPath_InLiteralText_IsTB1002() + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath number = t.DataAs().Path(o => o.Order.Number); + t.Content(c => c.Paragraph(x => x.Text($"Order {number}"))); + }); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(Core.TemplateFormat.Docx))); + + Assert.Equal("TB1002", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void PathToString_IsStillTheDottedPath() + { + TemplatePath number = TemplatePath.Root("report")["number"]; + + Assert.Equal("report.number", number.ToString()); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/RowLoopTests.cs b/tests/TriasDev.Templify.Builder.Tests/RowLoopTests.cs new file mode 100644 index 00000000..ce424ea7 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/RowLoopTests.cs @@ -0,0 +1,303 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class RowLoopTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Invoice() => new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => c.Table(tb => + { + tb.Columns(cols => + { + cols.Relative(3); + cols.Relative(1); + }); + tb.HeaderRow(r => + { + r.Cell("Item"); + r.Cell("Amount"); + }); + tb.ForEachRow(order["lines"], "line", (line, rows) => + { + rows.Row(r => + { + r.Cell(cell => + { + cell.Paragraph(x => + { + x.Value(line.Loop.Number); + x.Text(". "); + x.Value(line["description"]); + }); + cell.ForEach(line["tags"], "tag", (tag, tb2) => tb2.Paragraph(x => + { + x.Text("#"); + x.Value(tag.Self); + })); + }); + r.Cell(line["amount"]); + }); + rows.RowsIf(line["discount"], d => d.Row(r => + { + r.Cell(" discount"); + r.Cell(line["discount"]); + })); + }); + tb.RowsIf(order["vat"].Gt(0), v => v.Row(r => + { + r.Cell("VAT"); + r.Cell(order["vat"]); + })).Else(e => e.Row(r => + { + r.Cell("no VAT"); + r.Cell("–"); + })); + tb.Row(r => + { + r.Cell("Total"); + r.Cell(order["total"]); + }); + })); + }); + + private const string OrderJson = """ + { + "order": { + "lines": [ + { "description": "Laptop", "amount": "1499", "tags": [ "hw", "3y" ], "discount": "-50" }, + { "description": "Dock", "amount": "175", "tags": [ "acc" ], "discount": "" } + ], + "vat": 0, + "total": "1624" + } + } + """; + + [Theory] + [MemberData(nameof(Formats))] + public void RowLoop_WithConditionalRowsAndCellLoops_IsFilled(TemplateFormat format) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Invoice(), format, OrderJson); + + Assert.Equal( + new[] + { + "Item | Amount", + "1. Laptop\n#hw\n#3y | 1499", + " discount | -50", + "2. Dock\n#acc | 175", + "no VAT | –", + "Total | 1624", + }, + Rows(format, filled)); + } + + [Fact] + public void Odt_RowLoopUnderAHeader_DoesNotRepeatTheHeaderRule() + { + XNamespace style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + XNamespace fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + TableStyleKey grid = new TableStyleKey("Grid"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Table(grid, g => g.HeaderRule(1.5.Pt(), Color.FromHex("1F4E79")).RowRule(0.5.Pt(), Color.FromHex("D4D4D4"))))); + t.Content(c => c.Table(tb => + { + tb.Style(grid); + tb.Columns(cols => cols.Relative(1)); + tb.HeaderRow(r => r.Cell("Item")); + tb.ForEachRow(t.Data["lines"], "line", (line, rows) => rows.Row(r => r.Cell(line["name"]))); + })); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, TemplateFormat.Odt, """{ "lines": [ { "name": "a" }, { "name": "b" }, { "name": "c" } ] }"""); + + XDocument content = BuilderHarness.ReadXml(filled, "content.xml"); + Dictionary styles = content.Descendants(style + "style").ToDictionary(e => e.Attribute(style + "name")!.Value); + string? Border(XElement cell, string side) => + styles[cell.Attribute(_table + "style-name")!.Value].Element(style + "table-cell-properties")?.Attribute(fo + "border-" + side)?.Value; + + XElement header = content.Descendants(_table + "table-header-rows").Single().Descendants(_table + "table-cell").Single(); + Assert.Equal("1.5pt solid #1f4e79", Border(header, "bottom")); + XElement[] body = content.Descendants(_table + "table").Single().Elements(_table + "table-row").Select(r => r.Elements(_table + "table-cell").Single()).ToArray(); + Assert.Equal(3, body.Length); + // Every clone's top is the row rule; the header's wider bottom wins the first edge (collapsing model). + Assert.All(body, cell => Assert.Equal("0.5pt solid #d4d4d4", Border(cell, "top"))); + } + + [Theory] + [MemberData(nameof(Formats))] + public void RowLoop_EmptyCollection_LeavesNoRows(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Invoice(), format); + using Stream input = template.OpenRead(); + using MemoryStream output = new MemoryStream(); + ProcessingResult result = new TemplateProcessor(new PlaceholderReplacementOptions { WarnOnEmptyLoopCollections = false }) + .ProcessTemplate(input, output, """{ "order": { "lines": [], "vat": 19, "total": "0" } }"""); + + Assert.True(result.IsSuccess, result.ErrorMessage); + Assert.Equal(new[] { "Item | Amount", "VAT | 19", "Total | 0" }, Rows(format, output.ToArray())); + } + + [Theory] + [MemberData(nameof(Formats))] + public void MarkerRows_SpanTheWholeGrid(TemplateFormat format) + { + byte[] package = BuilderHarness.Build(Invoice(), format).Content.ToArray(); + + List rows = Rows(format, package); + Assert.Contains("{{#foreach line in order.lines}}", rows); + Assert.Contains("{{#if line.discount}}", rows); + Assert.Contains("{{#if order.vat > 0}}", rows); + Assert.Contains("{{#else}}", rows); + Assert.Equal(2, rows.Count(r => r == "{{/if}}")); + + if (format == TemplateFormat.Docx) + { + XElement marker = BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_w + "tr") + .First(r => r.Value == "{{#foreach line in order.lines}}"); + Assert.Equal("2", marker.Descendants(_w + "gridSpan").Single().Attribute(_w + "val")!.Value); + } + else + { + XElement marker = BuilderHarness.ReadXml(package, "content.xml").Descendants(_table + "table-row") + .First(r => r.Value == "{{#foreach line in order.lines}}"); + Assert.Equal("2", marker.Element(_table + "table-cell")!.Attribute(_table + "number-columns-spanned")!.Value); + Assert.Single(marker.Elements(_table + "covered-table-cell")); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void NestedRowLoops_AndTablesInsideParagraphLoops(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Table(tb => + { + tb.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.ForEachRow(t.Data["groups"], "group", (group, rows) => + { + rows.Row(r => r.Cell(cell => cell.ColumnSpan(2).Paragraph(group["name"]))); + rows.ForEachRow(group["items"], "item", (item, inner) => inner.Row(r => + { + r.Cell(item["name"]); + r.Cell(group["name"]); + })); + }); + }); + c.ForEach(t.Data["groups"], "g", (g, b) => + { + b.Paragraph(g["name"]); + b.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.ForEachRow(g["items"], "it", (it, rows) => rows.Row(r => r.Cell(it["name"]))); + }); + }); + })); + string json = """{ "groups": [ { "name": "A", "items": [ { "name": "a1" }, { "name": "a2" } ] }, { "name": "B", "items": [ { "name": "b1" } ] } ] }"""; + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, json); + + List rows = Rows(format, filled); + Assert.Equal(new[] { "A", "a1 | A", "a2 | A", "B", "b1 | B", "a1", "a2", "b1" }, rows); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Contract_IncludesRowLoopsAndRowConditions(TemplateFormat format) + { + Assert.Equal( + new[] + { + "order.lines (Collection)", "order.lines[].amount (Value)", "order.lines[].description (Value)", + "order.lines[].discount (Value)", "order.lines[].discount (Condition)", "order.lines[].tags (Collection)", + "order.lines[].tags[] (Value)", "order.total (Value)", "order.vat (Value)", "order.vat (Condition)", + }, + BuilderHarness.Build(Invoice(), format).Contract.Entries.Select(e => $"{e.Path} ({e.Usage})")); + } + + [Fact] + public void Scope_And_CellCount_AreChecked() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + LoopItem? escaped = null; + tb.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.ForEachRow(t.Data["lines"], "line", (line, rows) => + { + escaped = line; + rows.Row(r => r.Cell("only one cell")); + }); + tb.Row(r => + { + r.Cell(escaped!["name"]); + r.Cell("x"); + }); + }))); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + + Assert.Equal(new[] { "TB4001", "TB7003" }, exception.Errors.Select(e => e.Code)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RendersTheFilledRows(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Invoice(), format, OrderJson); + + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + + foreach (string expected in new[] { "1. Laptop", "#3y", "discount", "2. Dock", "no VAT", "Total" }) + { + Assert.Contains(expected, text, StringComparison.Ordinal); + } + + Assert.DoesNotContain("{{", text, StringComparison.Ordinal); + } + + /// Every table row of the body (nested tables' rows included in order), cells joined with " | ". + private static List Rows(TemplateFormat format, byte[] package) + { + if (format == TemplateFormat.Docx) + { + return BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_w + "tr") + .Select(r => string.Join(" | ", r.Elements(_w + "tc").Select(c => + string.Join("\n", c.Elements(_w + "p").Select(p => string.Concat(p.Descendants(_w + "t").Select(x => x.Value))))))) + .ToList(); + } + + return BuilderHarness.ReadXml(package, "content.xml").Descendants(_office + "text").First().Descendants(_table + "table-row") + .Select(r => string.Join(" | ", r.Elements(_table + "table-cell").Select(c => + string.Join("\n", c.Elements(_text + "p").Select(OdtDocumentVerifier.RenderText))))) + .ToList(); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/RuleBorderTests.cs b/tests/TriasDev.Templify.Builder.Tests/RuleBorderTests.cs new file mode 100644 index 00000000..29a2aa8c --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/RuleBorderTests.cs @@ -0,0 +1,141 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F8: a rule shorter than its frame; a bottom border on a paragraph style. +public sealed class RuleBorderTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + private static readonly Color _ink = Color.FromHex("1A1A1A"); + private static readonly ParagraphStyleKey _runHead = new ParagraphStyleKey("RunHead", "Running Head"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition ShortRule(Length width) => new TestDefinition(t => t.Content(c => c + .Paragraph("Title") + .Rule(1.5.Pt(), _ink, Length.Zero, 14.Pt(), width))); + + [Theory] + [MemberData(nameof(Formats))] + public void ShortRule_IndentsTheEnd(TemplateFormat format) + { + TestDefinition definition = ShortRule(12.Mm()); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + Length end = new PageSetupProbe().FrameWidth - 12.Mm(); + + if (format == TemplateFormat.Docx) + { + XElement rule = BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml").Root!.Element(_w + "body")!.Elements(_w + "p").ElementAt(1); + Assert.Equal(end.Twips.ToString(System.Globalization.CultureInfo.InvariantCulture), rule.Element(_w + "pPr")!.Element(_w + "ind")!.Attribute(_w + "right")!.Value); + } + else + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + XElement rule = content.Descendants(_office + "text").First().Elements(_text + "p").ElementAt(1); + string name = rule.Attribute(_text + "style-name")!.Value; + XElement properties = content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name).Element(_style + "paragraph-properties")!; + Assert.Equal(end.ToString(), properties.Attribute(_fo + "margin-right")!.Value); + } + } + + [Fact] + public void ShortRule_WiderThanFrame_IsABuildError() + { + TemplateBuildException error = Assert.Throws(() => BuilderHarness.Build(ShortRule(200.Mm()), TemplateFormat.Docx)); + Assert.Contains("rule", error.Message, StringComparison.Ordinal); + Assert.Contains("TB", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void ShortRule_InACell_IsCheckedAgainstTheCell() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Fixed(30.Mm()).Relative(1)); + tb.Row(r => r.Cell(cell => cell.Rule(1.Pt(), _ink, Length.Zero, Length.Zero, 40.Mm())).Cell("x")); + }))); + Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + } + + [Fact] + public void ShortRule_BadWidth_Throws() => + Assert.Throws(() => BuilderHarness.Build(ShortRule(Length.Zero), TemplateFormat.Docx)); + + [Theory] + [MemberData(nameof(Formats))] + public void StyleBorderBottom_IsWritten(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(_runHead, p => p.Size(8.Pt()).BorderBottom(0.75.Pt(), Color.FromHex("C8C8C8"), 3.Pt())))); + t.Content(c => c.Paragraph(_runHead, "Head")); + }); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement style = BuilderHarness.ReadXml(template.Content.ToArray(), "word/styles.xml").Descendants(_w + "style").Single(s => s.Attribute(_w + "styleId")?.Value == "RunHead"); + XElement bottom = style.Element(_w + "pPr")!.Element(_w + "pBdr")!.Element(_w + "bottom")!; + Assert.Equal(("single", "6", "3", "C8C8C8"), (bottom.Attribute(_w + "val")!.Value, bottom.Attribute(_w + "sz")!.Value, bottom.Attribute(_w + "space")!.Value, bottom.Attribute(_w + "color")!.Value)); + } + else + { + XElement style = BuilderHarness.ReadXml(template.Content.ToArray(), "styles.xml").Descendants(_style + "style").Single(s => s.Attribute(_style + "name")?.Value == "RunHead"); + XElement properties = style.Element(_style + "paragraph-properties")!; + Assert.Equal("0.75pt solid #c8c8c8", properties.Attribute(_fo + "border-bottom")!.Value); + Assert.Equal("3pt", properties.Attribute(_fo + "padding-bottom")!.Value); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_RuleWidthAndBorderBottom_RoundTrip(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "rules", "version": 1 }, + "styles": { "paragraph": { "RunHead": { "name": "Running Head", "borderBottom": "0.75pt #C8C8C8", "borderBottomSpace": "3pt" } } }, + "content": [ + { "style": "RunHead", "paragraph": "Head" }, + { "rule": { "line": "1.5pt #1A1A1A", "spaceAbove": "0pt", "spaceBelow": "14pt", "width": "12mm" } } + ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + string exported = Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json; + Assert.Contains("\"borderBottomSpace\": \"3pt\"", exported, StringComparison.Ordinal); + Assert.Contains("\"width\": \"12mm\"", exported, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ShortRuleEndsAtItsWidth(TemplateFormat format) + { + PdfLayout.Ink ink = PdfLayout.Pixels(PdfLayout.Pdf(ShortRule(12.Mm()), format)); + + // The longest horizontal run of ink on the page is the rule: 12 mm = 34.0 pt. + int longest = Enumerable.Range(0, ink.Height).SelectMany(ink.Runs).Max(r => r.Last - r.First + 1); + Assert.InRange(ink.Points(longest), 34.0 - 1.5, 34.0 + 1.5); + } + + /// The default page's frame: A4 minus the default side margins. + private sealed class PageSetupProbe + { + public Length FrameWidth => 210.Mm() - 25.Mm() - 25.Mm(); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/SampleTests.cs b/tests/TriasDev.Templify.Builder.Tests/SampleTests.cs new file mode 100644 index 00000000..e5c3de78 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/SampleTests.cs @@ -0,0 +1,131 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Builder.Sample; +using TriasDev.Templify.Builder.Testing; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Runs the sample (samples/TriasDev.Templify.Builder.Sample), so CI keeps it working (#287). +public sealed class SampleTests +{ + [Fact] + public void Sample_VerifiesBuildsAndFillsEveryLanguageAndFormat() + { + string directory = Path.Combine(Path.GetTempPath(), "templify-sample-" + Guid.NewGuid().ToString("N")); + try + { + StringWriter log = new StringWriter(); + + IReadOnlyList files = SampleRunner.Run(directory, log); + + Assert.Equal( + new[] + { + "order-confirmation.de-DE.template.docx", "order-confirmation.de-DE.filled.docx", + "order-confirmation.de-DE.template.odt", "order-confirmation.de-DE.filled.odt", + "order-confirmation.en-GB.template.docx", "order-confirmation.en-GB.filled.docx", + "order-confirmation.en-GB.template.odt", "order-confirmation.en-GB.filled.odt", + "data-contract.json", + }, + files.Select(Path.GetFileName)); + Assert.All(files, f => Assert.True(new FileInfo(f).Length > 0, f)); + Assert.Contains("Template verification passed (4 templates).", log.ToString(), StringComparison.Ordinal); + Assert.Contains("check of the unchanged template: Ok", log.ToString(), StringComparison.Ordinal); + + byte[] filled = File.ReadAllBytes(Path.Combine(directory, "order-confirmation.en-GB.filled.odt")); + string snapshot = TemplateSnapshot.Create(TemplateFormat.Odt, filled); + Assert.Contains("DocTitle | Order confirmation", snapshot, StringComparison.Ordinal); + Assert.Contains("TableText | Laptop 14\" — in stock", snapshot, StringComparison.Ordinal); + Assert.Contains("ListItem [list 1] | Credit limit: ✓", snapshot, StringComparison.Ordinal); + Assert.DoesNotContain("{{", snapshot, StringComparison.Ordinal); + } + finally + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + } + + [Fact] + public void Phase3_JsonRoundTripIsByteIdentical() + { + string directory = Path.Combine(Path.GetTempPath(), "templify-phase3-" + Guid.NewGuid().ToString("N")); + try + { + StringWriter log = new StringWriter(); + + IReadOnlyList files = SampleRunner.RunPhase3(directory, log); + + string json = Assert.Single(files, f => Path.GetExtension(f) == ".json"); + Assert.Equal("order-confirmation.json", Path.GetFileName(json)); + Assert.Contains("\"texts\"", File.ReadAllText(json), StringComparison.Ordinal); + foreach (string language in new[] { "de-DE", "en-GB" }) + { + foreach (string extension in new[] { "docx", "odt" }) + { + Assert.Contains(files, f => Path.GetFileName(f) == $"order-confirmation.{language}.from-json.{extension}"); + Assert.Contains(files, f => Path.GetFileName(f) == $"order-confirmation.{language}.from-json.filled.{extension}"); + } + } + + Assert.Contains(files, f => Path.GetFileName(Path.GetDirectoryName(f)) == "assets" && f.EndsWith(".png", StringComparison.Ordinal)); + Assert.Equal(4, System.Text.RegularExpressions.Regex.Matches(log.ToString(), "same bytes as C#").Count); + } + finally + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + } + + [Theory] + [InlineData(TemplateFormat.Docx, "de-DE")] + [InlineData(TemplateFormat.Odt, "de-DE")] + [InlineData(TemplateFormat.Docx, "en-GB")] + [InlineData(TemplateFormat.Odt, "en-GB")] + public void Typed_SampleProducesTheSameBytes(TemplateFormat format, string language) + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = format, Language = CultureInfo.GetCultureInfo(language), Texts = SampleTexts.Catalog }; + BrandTheme theme = BrandTheme.CreateDefault(); + + Assert.Equal(TemplateBuilder.Build(new OrderConfirmation(theme), options).ContentHash, TemplateBuilder.Build(new TypedOrderConfirmation(theme), options).ContentHash); + } + + [Fact] + public void Typed_SampleVerifies() + { + BrandTheme theme = BrandTheme.CreateDefault(); + + TemplateVerifier.VerifyAll( + () => new TypedOrderConfirmation(theme), + new TemplateVerificationOptions { Languages = SampleRunner.Languages, Texts = _ => SampleTexts.Catalog, SampleData = [SampleResources.SampleData] }); + } + + [Fact] + public void Phase3_ImportCheckedAgainstTheDataCatalogue() + { + TemplateBuildOptions options = new TemplateBuildOptions { Format = TemplateFormat.Docx, Language = CultureInfo.GetCultureInfo("en-GB"), Texts = SampleTexts.Catalog }; + TemplateJsonDocument exported = TemplateJson.Export(new OrderConfirmation(BrandTheme.CreateDefault()), options, SampleRunner.Components); + + ITemplateDefinition imported = TemplateJson.Import(exported.Json, new TemplateJsonImportOptions + { + Assets = exported.Assets, + Components = SampleRunner.Components, + Data = DataCatalog.From(), + Shared = [BrandTheme.CreateDefault()], + AllowRawXml = true, + }); + + Assert.Contains("\"component\": \"address\"", exported.Json, StringComparison.Ordinal); + Assert.Contains("{\"component\": \"terms\"}", exported.Json, StringComparison.Ordinal); + Assert.Equal(TemplateBuilder.Build(new OrderConfirmation(BrandTheme.CreateDefault()), options).ContentHash, TemplateBuilder.Build(imported, options).ContentHash); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/SchemaValidator.cs b/tests/TriasDev.Templify.Builder.Tests/SchemaValidator.cs new file mode 100644 index 00000000..f9a9dc27 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/SchemaValidator.cs @@ -0,0 +1,176 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace TriasDev.Templify.Builder.Tests; + +/// +/// A JSON Schema (draft 2020-12) validator for the keywords TemplateJson.Schema writes: $ref into +/// $defs, type, properties, required, additionalProperties, items, oneOf, +/// const, enum and pattern. Any other keyword is an error, so the tests notice when the schema +/// writer starts using one. (A test-only replacement for a validator package with a commercial licence.) +/// +internal sealed class SchemaValidator +{ + private static readonly HashSet _annotations = new HashSet(StringComparer.Ordinal) { "$schema", "title", "description", "$defs" }; + + private readonly JsonElement _root; + + public SchemaValidator(string schema) + { + _root = JsonDocument.Parse(schema).RootElement.Clone(); + } + + /// The problems of an instance, as "pointer: message"; empty when it is valid. + public List Validate(string instance) + { + using JsonDocument document = JsonDocument.Parse(instance); + List errors = new List(); + Validate(_root, document.RootElement, string.Empty, errors); + return errors; + } + + private void Validate(JsonElement schema, JsonElement value, string at, List errors) + { + if (schema.ValueKind == JsonValueKind.False) + { + errors.Add($"{at}: not allowed"); + return; + } + + if (schema.ValueKind == JsonValueKind.True) + { + return; + } + + foreach (JsonProperty keyword in schema.EnumerateObject()) + { + switch (keyword.Name) + { + case "$ref": + Validate(Resolve(keyword.Value.GetString()!), value, at, errors); + break; + case "type": + if (!HasType(value, keyword.Value.GetString()!)) + { + errors.Add($"{at}: expected {keyword.Value.GetString()}, got {value.ValueKind}"); + } + + break; + case "const": + if (!JsonElement.DeepEquals(keyword.Value, value)) + { + errors.Add($"{at}: expected {keyword.Value.GetRawText()}"); + } + + break; + case "enum": + if (!keyword.Value.EnumerateArray().Any(option => JsonElement.DeepEquals(option, value))) + { + errors.Add($"{at}: not one of {keyword.Value.GetRawText()}"); + } + + break; + case "pattern": + if (value.ValueKind == JsonValueKind.String && !Regex.IsMatch(value.GetString()!, keyword.Value.GetString()!, RegexOptions.CultureInvariant)) + { + errors.Add($"{at}: '{value.GetString()}' does not match {keyword.Value.GetString()}"); + } + + break; + case "required": + if (value.ValueKind == JsonValueKind.Object) + { + foreach (JsonElement name in keyword.Value.EnumerateArray()) + { + if (!value.TryGetProperty(name.GetString()!, out _)) + { + errors.Add($"{at}: '{name.GetString()}' is required"); + } + } + } + + break; + case "properties": + if (value.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty member in value.EnumerateObject()) + { + if (keyword.Value.TryGetProperty(member.Name, out JsonElement memberSchema)) + { + Validate(memberSchema, member.Value, at + "/" + member.Name, errors); + } + } + } + + break; + case "additionalProperties": + if (value.ValueKind == JsonValueKind.Object) + { + JsonElement? properties = schema.TryGetProperty("properties", out JsonElement p) ? p : null; + foreach (JsonProperty member in value.EnumerateObject().Where(m => properties is not { } known || !known.TryGetProperty(m.Name, out _))) + { + Validate(keyword.Value, member.Value, at + "/" + member.Name, errors); + } + } + + break; + case "items": + if (value.ValueKind == JsonValueKind.Array) + { + int i = 0; + foreach (JsonElement item in value.EnumerateArray()) + { + Validate(keyword.Value, item, at + "/" + (i++).ToString(CultureInfo.InvariantCulture), errors); + } + } + + break; + case "oneOf": + List> results = keyword.Value.EnumerateArray().Select(option => + { + List optionErrors = new List(); + Validate(option, value, at, optionErrors); + return optionErrors; + }).ToList(); + int matches = results.Count(r => r.Count == 0); + if (matches != 1) + { + errors.Add($"{at}: matches {matches} of the oneOf options (exactly one expected); closest: {string.Join("; ", results.OrderBy(r => r.Count).First().Take(3))}"); + } + + break; + default: + if (!_annotations.Contains(keyword.Name)) + { + throw new NotSupportedException($"The schema uses '{keyword.Name}', which this test validator does not implement."); + } + + break; + } + } + } + + private JsonElement Resolve(string reference) + { + const string prefix = "#/$defs/"; + return reference.StartsWith(prefix, StringComparison.Ordinal) && _root.GetProperty("$defs").TryGetProperty(reference[prefix.Length..], out JsonElement target) + ? target + : reference == "#" ? _root : throw new NotSupportedException($"Unsupported $ref '{reference}'."); + } + + private static bool HasType(JsonElement value, string type) => type switch + { + "string" => value.ValueKind == JsonValueKind.String, + "boolean" => value.ValueKind is JsonValueKind.True or JsonValueKind.False, + "object" => value.ValueKind == JsonValueKind.Object, + "array" => value.ValueKind == JsonValueKind.Array, + "number" => value.ValueKind == JsonValueKind.Number, + "integer" => value.ValueKind == JsonValueKind.Number && value.TryGetDecimal(out decimal d) && d == decimal.Truncate(d), + "null" => value.ValueKind == JsonValueKind.Null, + _ => throw new NotSupportedException($"Unsupported type '{type}'."), + }; +} diff --git a/tests/TriasDev.Templify.Builder.Tests/SpacerStackingTests.cs b/tests/TriasDev.Templify.Builder.Tests/SpacerStackingTests.cs new file mode 100644 index 00000000..a7bb58fc --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/SpacerStackingTests.cs @@ -0,0 +1,140 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// +/// #296 F13: the 1 pt "Template Spacer" paragraphs that keep containers well-formed once the markers are gone must not +/// stack: one after a table that a marker follows, and one at a cell's end only when the cell may otherwise end with a +/// table or be empty. +/// +public sealed class SpacerStackingTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly BoxStyleKey _panel = new BoxStyleKey("Panel"); + private const string Spacer = "TemplifySpacer"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static void Inner(BlockComposer c) => c.Table(t => + { + t.Columns(cols => cols.Relative(1)); + t.Row(r => r.Cell("inner")); + }); + + private static TestDefinition Define(Action content) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Box(_panel, b => b.Border(1.Pt(), Color.FromHex("C0C0C0"))))); + t.Content(c => content(t, c)); + }); + + [Theory] + [MemberData(nameof(Formats))] + public void BoxEndingWithConditional_HasOneSpacerAfterFilling(TemplateFormat format) + { + TestDefinition definition = Define((t, c) => c.Box(_panel, b => + { + Inner(b); + b.If(t.Data["show"], x => x.Paragraph("shown")); + })); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "show": false }"""); + Assert.Equal(new[] { "table", Spacer }, OuterCell(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void PartEndingWithConditionalAfterTable_HasOneSpacer(TemplateFormat format) + { + TestDefinition definition = Define((t, c) => + { + Inner(c); + c.If(t.Data["show"], x => x.Paragraph("shown")); + }); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "show": false }"""); + Assert.Equal(1, Body(format, filled).Count(e => e == Spacer)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void CellOnlyConditional_StillEndsWithAParagraph(TemplateFormat format) + { + TestDefinition definition = Define((t, c) => c.Box(_panel, b => b.If(t.Data["show"], x => x.Paragraph("shown")))); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "show": false }"""); + Assert.NotEmpty(OuterCell(format, filled)); + Assert.NotEqual("table", OuterCell(format, filled)[^1]); + } + + [Theory] + [MemberData(nameof(Formats))] + public void CellEndingWithTable_StillGetsItsSpacer(TemplateFormat format) + { + TestDefinition definition = Define((t, c) => c.Box(_panel, b => + { + b.Paragraph("first"); + Inner(b); + })); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + Assert.Equal(new[] { "p", "table", Spacer }, OuterCell(format, template.Content.ToArray())); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_BoxHeightDoesNotGrowBySpacers(TemplateFormat format) + { + double After(bool conditional) + { + TestDefinition definition = Define((t, c) => + { + c.Paragraph("Before"); + c.Box(_panel, b => + { + Inner(b); + if (conditional) + { + b.If(t.Data["show"], x => x.Paragraph("shown")); + } + }); + c.Paragraph("After"); + }); + List words = PdfLayout.Words(PdfLayout.Pdf(definition, format, """{ "show": false }""")); + return words.Find("After").YMin - words.Find("Before").YMin; + } + + Assert.InRange(After(conditional: true) - After(conditional: false), -0.5, 0.5); + } + + /// The outer box cell's children: "table", "p", or the spacer style for a spacer paragraph. + private static List OuterCell(TemplateFormat format, byte[] package) + { + XDocument document = BuilderHarness.ReadXml(package, BuilderHarness.MainPart(format)); + if (format == TemplateFormat.Docx) + { + XElement cell = document.Root!.Element(_w + "body")!.Element(_w + "tbl")!.Element(_w + "tr")!.Element(_w + "tc")!; + return cell.Elements().Where(e => e.Name != _w + "tcPr").Select(e => e.Name == _w + "tbl" ? "table" : DocxStyle(e) ?? "p").ToList(); + } + + XElement odtCell = document.Descendants(_office + "text").First().Element(_table + "table")!.Descendants(_table + "table-cell").First(); + return odtCell.Elements().Select(e => e.Name == _table + "table" ? "table" : e.Attribute(_text + "style-name")?.Value == Spacer ? Spacer : "p").ToList(); + } + + /// The body's children: "table", "p", or the spacer style for a spacer paragraph. + private static List Body(TemplateFormat format, byte[] package) + { + XDocument document = BuilderHarness.ReadXml(package, BuilderHarness.MainPart(format)); + IEnumerable children = format == TemplateFormat.Docx + ? document.Root!.Element(_w + "body")!.Elements().Where(e => e.Name != _w + "sectPr") + : document.Descendants(_office + "text").First().Elements().Where(e => e.Name == _text + "p" || e.Name == _table + "table"); + return children.Select(e => e.Name.LocalName is "tbl" or "table" ? "table" + : (format == TemplateFormat.Docx ? DocxStyle(e) : e.Attribute(_text + "style-name")?.Value) == Spacer ? Spacer : "p").ToList(); + } + + private static string? DocxStyle(XElement paragraph) => paragraph.Element(_w + "pPr")?.Element(_w + "pStyle")?.Attribute(_w + "val")?.Value; +} diff --git a/tests/TriasDev.Templify.Builder.Tests/SpacerTests.cs b/tests/TriasDev.Templify.Builder.Tests/SpacerTests.cs new file mode 100644 index 00000000..8caacb40 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/SpacerTests.cs @@ -0,0 +1,116 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F3: vertical space of a given height without a style of its own. +public sealed class SpacerTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action content) => new TestDefinition(t => t.Content(content)); + + [Theory] + [MemberData(nameof(Formats))] + public void Spacer_IsAnEmptyParagraphOfExactHeight(TemplateFormat format) + { + TestDefinition definition = Define(c => c.Paragraph("Above").Spacer(14.Pt()).Paragraph("Below")); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement spacer = BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml").Root!.Element(_w + "body")!.Elements(_w + "p").ElementAt(1); + XElement properties = spacer.Element(_w + "pPr")!; + Assert.Null(properties.Element(_w + "pStyle")); + Assert.Empty(spacer.Elements(_w + "r")); + XElement spacing = properties.Element(_w + "spacing")!; + Assert.Equal(("0", "0", "280", "exact"), (spacing.Attribute(_w + "before")!.Value, spacing.Attribute(_w + "after")!.Value, spacing.Attribute(_w + "line")!.Value, spacing.Attribute(_w + "lineRule")!.Value)); + } + else + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + XElement spacer = content.Descendants(_office + "text").First().Elements(_text + "p").ElementAt(1); + Assert.Empty(spacer.Nodes()); + string name = spacer.Attribute(_text + "style-name")!.Value; + XElement properties = content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name).Element(_style + "paragraph-properties")!; + Assert.Equal(("0pt", "0pt", "14pt"), (properties.Attribute(_fo + "margin-top")!.Value, properties.Attribute(_fo + "margin-bottom")!.Value, properties.Attribute(_fo + "line-height")!.Value)); + } + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(73)] + public void Spacer_OutOfRange_Throws(double points) => + Assert.Throws(() => BuilderHarness.Build(Define(c => c.Spacer(points.Pt())), TemplateFormat.Docx)); + + [Theory] + [MemberData(nameof(Formats))] + public void Json_Spacer_RoundTrip(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "spacer", "version": 1 }, + "content": [ "Above", { "spacer": "14pt" }, "Below" ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + Assert.Contains("{\"spacer\": \"14pt\"}", Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Spacer_EndsACellAsAParagraph(TemplateFormat format) + { + TestDefinition definition = Define(c => c.Table(t => + { + t.Columns(cols => cols.Relative(1)); + t.Row(r => r.Cell(cell => cell.Table(inner => + { + inner.Columns(cols => cols.Relative(1)); + inner.Row(ir => ir.Cell("inner")); + }).Spacer(6.Pt()))); + })); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + string main = BuilderHarness.ReadXml(template.Content.ToArray(), BuilderHarness.MainPart(format)).ToString(); + Assert.DoesNotContain("TemplifySpacer", main, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_SpacerHeight(TemplateFormat format) + { + double Gap(bool spacer) + { + TestDefinition definition = Define(c => + { + c.Paragraph("Above"); + if (spacer) + { + c.Spacer(14.Pt()); + } + + c.Paragraph("Below"); + }); + List words = PdfLayout.Words(PdfLayout.Pdf(definition, format)); + return words.Find("Below").YMin - words.Find("Above").YMin; + } + + Assert.InRange(Gap(spacer: true) - Gap(spacer: false), 13, 15); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/StyleInheritanceTests.cs b/tests/TriasDev.Templify.Builder.Tests/StyleInheritanceTests.cs new file mode 100644 index 00000000..010634dc --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/StyleInheritanceTests.cs @@ -0,0 +1,365 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; +using TriasDev.Templify.Builder.Testing; + +namespace TriasDev.Templify.Builder.Tests; + +/// Inherited paragraph styles: the style sheet's default, table text styles and a row's text style. +public sealed class StyleInheritanceTests +{ + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body Text Style"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading", "Heading Style"); + private static readonly ParagraphStyleKey _cell = new ParagraphStyleKey("CellText", "Cell Text"); + private static readonly ParagraphStyleKey _head = new ParagraphStyleKey("HeadText", "Head Text"); + private static readonly ParagraphStyleKey _total = new ParagraphStyleKey("TotalText", "Total Text"); + private static readonly ParagraphStyleKey _other = new ParagraphStyleKey("OtherText", "Other Text"); + private static readonly ParagraphStyleKey _inner = new ParagraphStyleKey("InnerText", "Inner Text"); + private static readonly ParagraphStyleKey _item = new ParagraphStyleKey("ItemText", "Item Text"); + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + private static readonly TableStyleKey _innerGrid = new TableStyleKey("InnerGrid"); + private static readonly BoxStyleKey _note = new BoxStyleKey("Note"); + private static readonly ListStyleKey _bullets = new ListStyleKey("Bullets"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static StyleSheet Sheet(bool withDefault = true, bool withTableText = true) => StyleSheet.Create(s => + { + if (withDefault) + { + s.Defaults(d => d.ParagraphStyle(_body)); + } + + foreach (ParagraphStyleKey key in new[] { _body, _heading, _cell, _head, _total, _other, _inner, _item }) + { + s.Paragraph(key, p => p.SpaceAfter(1.Pt())); + } + + s.Table(_grid, t => + { + t.RowRule(0.5.Pt(), Color.FromHex("D4D4D4")); + if (withTableText) + { + t.ParagraphStyle(_cell).HeaderParagraphStyle(_head); + } + }); + s.Table(_innerGrid, t => t.ParagraphStyle(_inner)); + s.Box(_note, b => b.Background(Color.FromHex("EEEEEE"))); + s.List(_bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm()).ItemStyle(_item)); + }); + + private static string Snapshot(ITemplateDefinition definition, TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + return TemplateSnapshot.Create(template); + } + + [Theory] + [MemberData(nameof(Formats))] + public void UnstyledParagraph_GetsTheDefault(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Paragraph("plain")); + }), format); + + Assert.Contains("Body | plain", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ExplicitStyle_Wins(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Paragraph(_heading, "title")); + }), format); + + Assert.Contains("Heading | title", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NoDefault_StaysUnstyled(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(Sheet(withDefault: false)); + t.Content(c => c.Paragraph("plain")); + }); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + string part = BuilderHarness.ReadXml(template.Content.ToArray(), BuilderHarness.MainPart(format)).ToString(); + Assert.DoesNotContain("\"Body\"", part, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void TableCells_UseTextStyles(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.HeaderRow(r => + { + r.Cell("h1"); + r.Cell("h2"); + }); + tb.Row(r => + { + r.Cell("b1"); + r.Cell(_other, "b2"); + }); + tb.Row(r => + { + r.ParagraphStyle(_total); + r.Cell("t1"); + r.Cell("t2"); + }); + })); + }), format); + + Assert.Contains("HeadText | h1", snapshot, StringComparison.Ordinal); + Assert.Contains("CellText | b1", snapshot, StringComparison.Ordinal); + Assert.Contains("OtherText | b2", snapshot, StringComparison.Ordinal); + Assert.Contains("TotalText | t1", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NestedTable_UsesItsOwnStyle(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => + { + cell.Paragraph("outer"); + cell.Table(inner => + { + inner.Style(_innerGrid).Columns(cols => cols.Relative(1)); + inner.Row(ir => ir.Cell("nested")); + }); + })); + })); + }), format); + + Assert.Contains("CellText | outer", snapshot, StringComparison.Ordinal); + Assert.Contains("InnerText | nested", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void BoxInCell_GetsTheDocumentDefault(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => cell.Box(_note, b => b.Paragraph("boxed")))); + })); + }), format); + + Assert.Contains("Body | boxed", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ConditionalsAndLoops_Inherit(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Styles(Sheet()); + t.Content(c => + { + c.If(order["flag"], b => b.Paragraph("in if")); + c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => cell.If(order["flag"], b => b.Paragraph("in cell if")))); + }); + }); + }), format); + + Assert.Contains("Body | in if", snapshot, StringComparison.Ordinal); + Assert.Contains("CellText | in cell if", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ListItems_KeepTheirItemStyle(TemplateFormat format) + { + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.List(_bullets, l => l.Item("first"))); + }), format); + + Assert.Contains("ItemText [list 1] | first", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ListWithoutItemStyle_GetsTheInheritedStyle(TemplateFormat format) + { + ListStyleKey plain = new ListStyleKey("PlainBullets"); + string snapshot = Snapshot(new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.ParagraphStyle(_body)); + s.Paragraph(_body, p => p.SpaceAfter(1.Pt())); + s.Paragraph(_cell, p => p.SpaceAfter(1.Pt())); + s.Table(_grid, g => g.ParagraphStyle(_cell)); + s.List(plain, l => l.Level(0, "•", 6.Mm(), 4.Mm())); + })); + t.Content(c => + { + c.List(plain, l => l.Item("in body")); + c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell(cell => cell.List(plain, l => l.Item("in cell")))); + }); + }); + }), format); + + Assert.Contains("Body [list 1] | in body", snapshot, StringComparison.Ordinal); + Assert.Contains("CellText [list 1] | in cell", snapshot, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void HeaderAndFooter_GetTheDefault(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(Sheet()); + t.Page(p => p.Header(h => h.Paragraph("running head"))); + t.Content(c => c.Paragraph(_heading, "body")); + }); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + string part = format == TemplateFormat.Docx + ? BuilderHarness.ReadXml(template.Content.ToArray(), "word/header1.xml").ToString() + : BuilderHarness.ReadXml(template.Content.ToArray(), "styles.xml").ToString(); + Assert.Matches("(w:val|text:style-name)=\"Body\"[^<]*>(.|\\n)*running head", part); + } + + [Fact] + public void UndefinedDefault_IsTB2010() + { + ParagraphStyleKey missing = new ParagraphStyleKey("Missing", "Missing Style"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Defaults(d => d.ParagraphStyle(missing)); + s.Paragraph(_heading, p => p.Bold()); + })); + t.Content(c => c.Paragraph(_heading, "styled only")); + }); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB2010", error.Code); + Assert.Contains("Missing", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void UndefinedDefault_UsedByParagraphs_IsReportedOnce() + { + ParagraphStyleKey missing = new ParagraphStyleKey("Missing", "Missing Style"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Defaults(d => d.ParagraphStyle(missing)))); + t.Content(c => + { + c.Paragraph("a"); + c.Paragraph("b"); + }); + }); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + Assert.Equal("TB2010", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void UndefinedTableTextStyle_IsTB2010() + { + ParagraphStyleKey missing = new ParagraphStyleKey("Missing", "Missing Style"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Table(_grid, tb => tb.HeaderParagraphStyle(missing)))); + t.Content(c => c.Paragraph("no table at all")); + }); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB2010", error.Code); + Assert.Contains("Grid", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Json_CarriesTheInheritanceSettings() + { + TestDefinition definition = new TestDefinition(t => + { + t.Styles(Sheet()); + t.Content(c => c.Table(tb => + { + tb.Style(_grid).Columns(cols => cols.Relative(1)); + tb.Row(r => + { + r.ParagraphStyle(_total); + r.Cell("t"); + }); + })); + }); + TemplateBuildOptions options = BuilderHarness.Options(TemplateFormat.Docx); + + string json = TemplateJson.Export(definition, options).Json; + Assert.Contains("\"paragraphStyle\": \"Body\"", json, StringComparison.Ordinal); + Assert.Contains("\"paragraphStyle\": \"CellText\"", json, StringComparison.Ordinal); + Assert.Contains("\"headerParagraphStyle\": \"HeadText\"", json, StringComparison.Ordinal); + Assert.Contains("\"paragraphStyle\": \"TotalText\"", json, StringComparison.Ordinal); + BuilderHarness.AssertJsonRoundTrip(definition, TemplateBuilder.Build(definition, options), options); + } + + [Fact] + public void Json_UndefinedDefault_IsTB2010() + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "t", "version": 1 }, + "styles": { "defaults": { "paragraphStyle": "Nope" } }, + "content": [ "x" ] + } + """; + + TemplateBuildException exception = Assert.ThrowsAny(() => + TemplateBuilder.Build(TemplateJson.Import(json, new TemplateJsonImportOptions()), BuilderHarness.Options(TemplateFormat.Docx))); + Assert.Equal("TB2010", Assert.Single(exception.Errors).Code); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/StyleSheetTests.cs b/tests/TriasDev.Templify.Builder.Tests/StyleSheetTests.cs new file mode 100644 index 00000000..d04ed801 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/StyleSheetTests.cs @@ -0,0 +1,413 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class StyleSheetTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + private static readonly XNamespace _dc = "http://purl.org/dc/elements/1.1/"; + private static readonly XNamespace _meta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0"; + + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body Copy"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading1", "Heading One"); + private static readonly ParagraphStyleKey _subHeading = new ParagraphStyleKey("Heading2", "Heading Two"); + private static readonly ParagraphStyleKey _note = new ParagraphStyleKey("Note", "Note"); + private static readonly CharacterStyleKey _strong = new CharacterStyleKey("Strong", "Strong Text"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static StyleSheet Sheet() => StyleSheet.Create(s => + { + s.Defaults(d => d.Font(new FontFace("Liberation Sans")).Size(10.5.Pt()).Color(Color.FromHex("171717"))); + s.Paragraph(_body, p => p.SpaceAfter(8.Pt()).MinimumLineHeight(15.Pt())); + s.Paragraph(_heading, p => p.BasedOn(_body).Next(_body).Font(new FontFace("Liberation Serif")).Size(16.Pt()) + .Bold().Color(Color.FromHex("#1F4E79")).SpaceBefore(20.Pt()).KeepWithNext().KeepLinesTogether().OutlineLevel(1)); + // Inherits its outline level from nowhere: level 2 set here; the level 1 heading's other properties inherited. + s.Paragraph(_subHeading, p => p.BasedOn(_heading).Size(13.Pt()).OutlineLevel(2)); + s.Paragraph(_note, p => p.BasedOn(_body).Italic().Alignment(TextAlignment.Justify).IndentStart(10.Mm()) + .IndentEnd(5.Mm()).FirstLineIndent(-4.5.Mm()).LineSpacing(1.15)); + s.Character(_strong, c => c.Bold().Color(Color.FromRgb(0x15, 0x80, 0x3D))); + }); + + private static TestDefinition Document() => new TestDefinition(template => + { + template.Styles(Sheet()); + template.Properties(p => p.Title("Order confirmation").Author("Example Ltd").Subject("Orders")); + TemplatePath order = template.Data["order"]; + template.Content(c => + { + c.Paragraph(_heading, "Order"); + c.Paragraph(_subHeading, order["number"]); + c.Paragraph(_body, x => + { + x.Text("Customer: "); + x.Value(order["customer"]); + }); + c.Paragraph(_note, "All prices include VAT."); + c.Paragraph("Unstyled"); + }); + }); + + private const string OrderJson = """{ "order": { "number": "A-17", "customer": "Alice" } }"""; + + [Theory] + [MemberData(nameof(Formats))] + public void StyledDocument_IsFilledByTemplify(TemplateFormat format) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Document(), format, OrderJson); + + Assert.Equal(new[] { "Order", "A-17", "Customer: Alice", "All prices include VAT.", "Unstyled" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Fact] + public void Docx_WritesNamedStylesAndReferencesThem() + { + byte[] package = BuilderHarness.Build(Document(), TemplateFormat.Docx).Content.ToArray(); + XElement styles = BuilderHarness.ReadXml(package, "word/styles.xml").Root!; + XElement Style(string id) => styles.Elements(_w + "style").Single(s => (string?)s.Attribute(_w + "styleId") == id); + + Assert.Equal( + new[] { "Normal", "DefaultParagraphFont", "Body", "Heading1", "Heading2", "Note", "Strong" }, + styles.Elements(_w + "style").Select(s => (string?)s.Attribute(_w + "styleId"))); + Assert.Equal("Heading One", Style("Heading1").Element(_w + "name")!.Attribute(_w + "val")!.Value); + Assert.Equal("Body", Style("Heading1").Element(_w + "basedOn")!.Attribute(_w + "val")!.Value); + Assert.Equal("Body", Style("Heading1").Element(_w + "next")!.Attribute(_w + "val")!.Value); + Assert.Equal("Normal", Style("Body").Element(_w + "basedOn")!.Attribute(_w + "val")!.Value); + Assert.Equal("DefaultParagraphFont", Style("Strong").Element(_w + "basedOn")!.Attribute(_w + "val")!.Value); + + XElement heading = Style("Heading1"); + Assert.Equal("Liberation Serif", heading.Element(_w + "rPr")!.Element(_w + "rFonts")!.Attribute(_w + "ascii")!.Value); + Assert.Equal("32", heading.Element(_w + "rPr")!.Element(_w + "sz")!.Attribute(_w + "val")!.Value); + Assert.Equal("1F4E79", heading.Element(_w + "rPr")!.Element(_w + "color")!.Attribute(_w + "val")!.Value); + Assert.NotNull(heading.Element(_w + "rPr")!.Element(_w + "b")); + Assert.NotNull(heading.Element(_w + "pPr")!.Element(_w + "keepNext")); + Assert.NotNull(heading.Element(_w + "pPr")!.Element(_w + "keepLines")); + Assert.Equal("400", heading.Element(_w + "pPr")!.Element(_w + "spacing")!.Attribute(_w + "before")!.Value); + Assert.Equal("0", heading.Element(_w + "pPr")!.Element(_w + "outlineLvl")!.Attribute(_w + "val")!.Value); + + XElement body = Style("Body").Element(_w + "pPr")!.Element(_w + "spacing")!; + Assert.Equal("160", body.Attribute(_w + "after")!.Value); + Assert.Equal("300", body.Attribute(_w + "line")!.Value); + Assert.Equal("atLeast", body.Attribute(_w + "lineRule")!.Value); + + XElement note = Style("Note").Element(_w + "pPr")!; + Assert.Equal("276", note.Element(_w + "spacing")!.Attribute(_w + "line")!.Value); + Assert.Equal("auto", note.Element(_w + "spacing")!.Attribute(_w + "lineRule")!.Value); + Assert.Equal("567", note.Element(_w + "ind")!.Attribute(_w + "left")!.Value); + Assert.Equal("283", note.Element(_w + "ind")!.Attribute(_w + "right")!.Value); + Assert.Equal("255", note.Element(_w + "ind")!.Attribute(_w + "hanging")!.Value); + Assert.Equal("both", note.Element(_w + "jc")!.Attribute(_w + "val")!.Value); + + XElement defaults = styles.Element(_w + "docDefaults")!.Element(_w + "rPrDefault")!.Element(_w + "rPr")!; + Assert.Equal("Liberation Sans", defaults.Element(_w + "rFonts")!.Attribute(_w + "ascii")!.Value); + Assert.Equal("21", defaults.Element(_w + "sz")!.Attribute(_w + "val")!.Value); + Assert.Equal("en-US", defaults.Element(_w + "lang")!.Attribute(_w + "val")!.Value); + + XElement documentBody = BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!; + Assert.Equal( + new string?[] { "Heading1", "Heading2", "Body", "Note", null }, + documentBody.Elements(_w + "p").Select(p => (string?)p.Element(_w + "pPr")?.Element(_w + "pStyle")?.Attribute(_w + "val"))); + Assert.Empty(documentBody.Descendants(_w + "rPr")); + } + + [Fact] + public void Odt_WritesNamedStylesAndHeadings() + { + byte[] package = BuilderHarness.Build(Document(), TemplateFormat.Odt).Content.ToArray(); + XElement styles = BuilderHarness.ReadXml(package, "styles.xml").Root!.Element(_office + "styles")!; + XElement Style(string name) => styles.Elements(_style + "style").Single(s => (string?)s.Attribute(_style + "name") == name); + + Assert.Equal( + new[] { "Standard", "Body", "Heading1", "Heading2", "Note", "Strong" }, + styles.Elements(_style + "style").Select(s => (string?)s.Attribute(_style + "name"))); + Assert.Equal("Heading One", Style("Heading1").Attribute(_style + "display-name")!.Value); + Assert.Equal("Body", Style("Heading1").Attribute(_style + "parent-style-name")!.Value); + Assert.Equal("Body", Style("Heading1").Attribute(_style + "next-style-name")!.Value); + Assert.Equal("1", Style("Heading1").Attribute(_style + "default-outline-level")!.Value); + Assert.Equal("Standard", Style("Body").Attribute(_style + "parent-style-name")!.Value); + Assert.Equal("text", Style("Strong").Attribute(_style + "family")!.Value); + + XElement headingText = Style("Heading1").Element(_style + "text-properties")!; + Assert.Equal("Liberation Serif", headingText.Attribute(_style + "font-name")!.Value); + Assert.Equal("16pt", headingText.Attribute(_fo + "font-size")!.Value); + Assert.Equal("#1f4e79", headingText.Attribute(_fo + "color")!.Value); + Assert.Equal("bold", headingText.Attribute(_fo + "font-weight")!.Value); + XElement headingParagraph = Style("Heading1").Element(_style + "paragraph-properties")!; + Assert.Equal("20pt", headingParagraph.Attribute(_fo + "margin-top")!.Value); + Assert.Equal("always", headingParagraph.Attribute(_fo + "keep-with-next")!.Value); + Assert.Equal("always", headingParagraph.Attribute(_fo + "keep-together")!.Value); + + XElement bodyParagraph = Style("Body").Element(_style + "paragraph-properties")!; + Assert.Equal("8pt", bodyParagraph.Attribute(_fo + "margin-bottom")!.Value); + Assert.Equal("15pt", bodyParagraph.Attribute(_style + "line-height-at-least")!.Value); + + XElement noteParagraph = Style("Note").Element(_style + "paragraph-properties")!; + Assert.Equal("115%", noteParagraph.Attribute(_fo + "line-height")!.Value); + Assert.Equal("justify", noteParagraph.Attribute(_fo + "text-align")!.Value); + Assert.Equal("28.346pt", noteParagraph.Attribute(_fo + "margin-left")!.Value); + Assert.Equal("-12.756pt", noteParagraph.Attribute(_fo + "text-indent")!.Value); + + XElement defaults = styles.Element(_style + "default-style")!.Element(_style + "text-properties")!; + Assert.Equal("Liberation Sans", defaults.Attribute(_style + "font-name")!.Value); + Assert.Equal("10.5pt", defaults.Attribute(_fo + "font-size")!.Value); + Assert.Equal("en", defaults.Attribute(_fo + "language")!.Value); + Assert.Equal("US", defaults.Attribute(_fo + "country")!.Value); + + XElement fonts = BuilderHarness.ReadXml(package, "styles.xml").Root!.Element(_office + "font-face-decls")!; + Assert.Equal(new[] { "Liberation Sans", "Liberation Serif" }, fonts.Elements().Select(f => (string?)f.Attribute(_style + "name"))); + + XElement text = BuilderHarness.ReadXml(package, "content.xml").Root!.Element(_office + "body")!.Element(_office + "text")!; + List paragraphs = text.Elements().ToList(); + Assert.Equal(new[] { "h", "h", "p", "p", "p" }, paragraphs.Select(p => p.Name.LocalName)); + Assert.Equal(new[] { "Heading1", "Heading2", "Body", "Note", "Standard" }, paragraphs.Select(p => (string?)p.Attribute(_text + "style-name"))); + Assert.Equal(new[] { "1", "2" }, paragraphs.Take(2).Select(p => (string?)p.Attribute(_text + "outline-level"))); + } + + [Fact] + public void Odt_HeadingLevelIsInheritedThroughBasedOn() + { + ParagraphStyleKey parent = new ParagraphStyleKey("Parent", "Parent"); + ParagraphStyleKey child = new ParagraphStyleKey("Child", "Child"); + TestDefinition definition = new TestDefinition(template => + { + template.Styles(StyleSheet.Create(s => + { + s.Paragraph(parent, p => p.OutlineLevel(3)); + s.Paragraph(child, p => p.BasedOn(parent).Bold()); + })); + template.Content(c => c.Paragraph(child, "Inherited heading")); + }); + + byte[] package = BuilderHarness.Build(definition, TemplateFormat.Odt).Content.ToArray(); + XElement paragraph = BuilderHarness.ReadXml(package, "content.xml").Root!.Element(_office + "body")!.Element(_office + "text")!.Elements().Single(); + + Assert.Equal("h", paragraph.Name.LocalName); + Assert.Equal("3", paragraph.Attribute(_text + "outline-level")!.Value); + } + + [Theory] + [InlineData("de-DE", "de", "DE")] + [InlineData("en", "en", null)] + public void Language_IsWrittenInTheDefaults(string culture, string language, string? country) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph("x"))); + + byte[] docx = TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx, culture)).Content.ToArray(); + XElement docxDefaults = BuilderHarness.ReadXml(docx, "word/styles.xml").Root!.Element(_w + "docDefaults")!; + Assert.Equal(culture, docxDefaults.Descendants(_w + "lang").Single().Attribute(_w + "val")!.Value); + + byte[] odt = TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt, culture)).Content.ToArray(); + XElement odtDefaults = BuilderHarness.ReadXml(odt, "styles.xml").Root!.Element(_office + "styles")!.Element(_style + "default-style")!.Element(_style + "text-properties")!; + Assert.Equal(language, odtDefaults.Attribute(_fo + "language")!.Value); + Assert.Equal(country, (string?)odtDefaults.Attribute(_fo + "country")); + } + + [Fact] + public void DocumentProperties_AreWrittenInBothFormats() + { + byte[] docx = BuilderHarness.Build(Document(), TemplateFormat.Docx).Content.ToArray(); + XElement core = BuilderHarness.ReadXml(docx, "docProps/core.xml").Root!; + Assert.Equal("Order confirmation", core.Element(_dc + "title")!.Value); + Assert.Equal("Example Ltd", core.Element(_dc + "creator")!.Value); + Assert.Equal("Orders", core.Element(_dc + "subject")!.Value); + + byte[] odt = BuilderHarness.Build(Document(), TemplateFormat.Odt).Content.ToArray(); + XElement meta = BuilderHarness.ReadXml(odt, "meta.xml").Root!.Element(_office + "meta")!; + Assert.Equal("Order confirmation", meta.Element(_dc + "title")!.Value); + Assert.Equal("Example Ltd", meta.Element(_meta + "initial-creator")!.Value); + Assert.Equal("Orders", meta.Element(_dc + "subject")!.Value); + } + + [Fact] + public void Build_ReportsEveryStyleProblem() + { + ParagraphStyleKey a = new ParagraphStyleKey("A", "Alpha"); + ParagraphStyleKey b = new ParagraphStyleKey("B", "Beta"); + ParagraphStyleKey alsoAlpha = new ParagraphStyleKey("C", "Alpha"); + ParagraphStyleKey missing = new ParagraphStyleKey("Missing", "Missing"); + CharacterStyleKey clash = new CharacterStyleKey("A", "Clash"); + + TestDefinition definition = new TestDefinition(template => + { + template.Styles(StyleSheet.Create(s => + { + s.Paragraph(a, p => p.BasedOn(b)); + s.Paragraph(b, p => p.BasedOn(a).Next(missing)); + s.Paragraph(alsoAlpha, p => p.BasedOn(missing)); + s.Character(clash, c => c.Bold()); + })); + template.Styles(StyleSheet.Create(_ => { })); + template.Content(c => + { + c.Paragraph(missing, "uses an undefined style"); + c.Paragraph(missing, "reported once"); + }); + }); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Odt))); + + Assert.Equal( + new[] { "TB2000", "TB2001", "TB2002", "TB2003", "TB2004", "TB2005", "TB2010" }, + exception.Errors.Select(e => e.Code).Order(StringComparer.Ordinal)); + } + + [Fact] + public void Build_StyleWithoutStyleSheet_IsAnError() + { + TestDefinition definition = new TestDefinition(template => template.Content(c => c.Paragraph(_body, "x"))); + + TemplateBuildException exception = Assert.Throws( + () => TemplateBuilder.Build(definition, BuilderHarness.Options(TemplateFormat.Docx))); + + Assert.Contains("'Body'", Assert.Single(exception.Errors).Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("")] + [InlineData("1Heading")] + [InlineData("Heading 1")] + [InlineData("Ünicode")] + [InlineData("Normal")] + [InlineData("standard")] + [InlineData("DefaultParagraphFont")] + public void StyleKey_InvalidOrReservedId_Throws(string id) + { + Assert.Throws(() => new ParagraphStyleKey(id, "Name")); + Assert.Throws(() => new CharacterStyleKey(id, "Name")); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("Tab\tName")] + public void StyleKey_InvalidDisplayName_Throws(string displayName) + { + Assert.Throws(() => new ParagraphStyleKey("Valid_id-1", displayName)); + } + + [Fact] + public void StyleValues_OutOfRange_ThrowWhereWritten() + { + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.Size(0.Pt())))); + Assert.Throws(() => StyleSheet.Create(s => s.Defaults(d => d.Size(2000.Pt())))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.SpaceAfter(-1.Pt())))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.LineHeight(Length.Zero)))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.LineSpacing(0.1)))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.OutlineLevel(0)))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.OutlineLevel(10)))); + Assert.Throws(() => StyleSheet.Create(s => s.Paragraph(_body, p => p.Alignment((TextAlignment)42)))); + } + + [Fact] + public void StyleComposers_UsedAfterCreate_Throw() + { + StyleSheetComposer? sheet = null; + ParagraphStyleComposer? paragraph = null; + CharacterStyleComposer? character = null; + DefaultStyleComposer? defaults = null; + StyleSheet.Create(s => + { + sheet = s; + s.Defaults(d => defaults = d); + s.Paragraph(_body, p => paragraph = p); + s.Character(_strong, c => character = c); + }); + + Assert.Throws(() => sheet!.Paragraph(_note, _ => { })); + Assert.Throws(() => paragraph!.Bold()); + Assert.Throws(() => character!.Italic()); + Assert.Throws(() => defaults!.Size(12.Pt())); + } + + [Fact] + public void Units_ConvertAndRound() + { + Assert.Equal(Length.FromPoints(12), 12.Pt()); + Assert.Equal(72.Pt(), 25.4.Mm()); + Assert.Equal("10.5pt", 10.5.Pt().ToString()); + Assert.Equal("28.346pt", 10.Mm().ToString()); + Assert.Equal(12.5, (10.Pt() + 2.5.Pt()).Points); + Assert.Equal(-3.Pt(), -(3.Pt())); + Assert.True(1.Mm() > 2.Pt()); + Assert.Equal(25.4, 72.Pt().Millimeters, 6); + Assert.Throws(() => Length.FromPoints(double.NaN)); + } + + [Theory] + [InlineData("1F4E79")] + [InlineData("#1f4e79")] + public void Color_ParsesHex(string hex) + { + Color color = Color.FromHex(hex); + + Assert.Equal(Color.FromRgb(0x1F, 0x4E, 0x79), color); + Assert.Equal("#1F4E79", color.ToString()); + } + + [Theory] + [InlineData("")] + [InlineData("#12345")] + [InlineData("12345G")] + [InlineData("#1234567")] + public void Color_InvalidHex_Throws(string hex) + { + Assert.Throws(() => Color.FromHex(hex)); + } + + [Theory] + [InlineData("")] + [InlineData(" Padded")] + [InlineData("It's")] + public void FontFace_InvalidFamily_Throws(string family) + { + Assert.Throws(() => new FontFace(family)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_KeepsTheNamedStylesWhenConverting(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + byte[] template = BuilderHarness.Build(Document(), format).Content.ToArray(); + + if (format == TemplateFormat.Docx) + { + // DOCX → ODT: LibreOffice read our styles and writes them under their display names. + byte[] converted = LibreOfficeRunner.Convert(template, "docx", "odt", "odt"); + XElement styles = BuilderHarness.ReadXml(converted, "styles.xml").Root!.Element(_office + "styles")!; + List names = styles.Elements(_style + "style") + .Select(s => (string?)s.Attribute(_style + "display-name") ?? (string)s.Attribute(_style + "name")!) + .ToList(); + Assert.Contains("Heading One", names); + Assert.Contains("Body Copy", names); + Assert.Contains("Strong Text", names); + + XElement heading = styles.Elements(_style + "style").First(s => ((string?)s.Attribute(_style + "display-name") ?? (string?)s.Attribute(_style + "name")) == "Heading One"); + Assert.Equal("16pt", heading.Element(_style + "text-properties")!.Attribute(_fo + "font-size")!.Value); + } + else + { + // ODT → DOCX: Word sees the display names as style names. + byte[] converted = LibreOfficeRunner.Convert(template, "odt", "docx:MS Word 2007 XML", "docx"); + XElement styles = BuilderHarness.ReadXml(converted, "word/styles.xml").Root!; + List names = styles.Elements(_w + "style").Select(s => s.Element(_w + "name")!.Attribute(_w + "val")!.Value).ToList(); + Assert.Contains("Heading One", names); + Assert.Contains("Body Copy", names); + Assert.Contains("Strong Text", names); + } + + (_, byte[] filled) = BuilderHarness.BuildAndFill(Document(), format, OrderJson); + Assert.NotEmpty(LibreOfficeRunner.Convert(filled, format == TemplateFormat.Docx ? "docx" : "odt", "pdf", "pdf")); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TableIndentTests.cs b/tests/TriasDev.Templify.Builder.Tests/TableIndentTests.cs new file mode 100644 index 00000000..c95b46b9 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TableIndentTests.cs @@ -0,0 +1,152 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #296 F2/F3: a table stepped in from the start of its frame, and space before a table. +public sealed class TableIndentTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + + private static readonly Length _frame = 160.Mm(); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action options) => new TestDefinition(t => t.Content(c => c + .Paragraph("Before") + .Table(tb => + { + options(tb); + tb.Columns(cols => cols.Relative(1).Relative(1)); + tb.Row(r => r.Cell("Inside").Cell("other")); + }))); + + [Theory] + [MemberData(nameof(Formats))] + public void Indent_NarrowsTheColumns(TemplateFormat format) + { + TestDefinition definition = Define(t => t.Indent(6.Mm())); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XDocument document = Docx(template); + XElement indent = document.Descendants(_w + "tblInd").Single(); + // tblInd places the first cell's text (legacy layout): the indent plus the default left cell margin. + Assert.Equal(((6.Mm() + 5.4.Pt()).Twips.ToString(CultureInfo.InvariantCulture), "dxa"), (indent.Attribute(_w + "w")!.Value, indent.Attribute(_w + "type")!.Value)); + int sum = document.Descendants(_w + "gridCol").Sum(c => int.Parse(c.Attribute(_w + "w")!.Value, CultureInfo.InvariantCulture)); + Assert.InRange(sum, (_frame - 6.Mm()).Twips - 1, (_frame - 6.Mm()).Twips + 1); + } + else + { + XElement properties = OdtTableProperties(template); + Assert.Equal(6.Mm().ToString(), properties.Attribute(_fo + "margin-left")!.Value); + double width = double.Parse(properties.Attribute(_style + "width")!.Value.TrimEnd('p', 't'), CultureInfo.InvariantCulture); + Assert.InRange(width, (_frame - 6.Mm()).Points - 0.01, (_frame - 6.Mm()).Points + 0.01); + } + } + + [Fact] + public void Indent_NotSmallerThanFrame_IsABuildError() + { + TemplateBuildException error = Assert.Throws(() => BuilderHarness.Build(Define(t => t.Indent(_frame)), TemplateFormat.Docx)); + Assert.Contains("TB7002", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void Indent_Negative_Throws() => + Assert.Throws(() => BuilderHarness.Build(Define(t => t.Indent(-1.Mm())), TemplateFormat.Docx)); + + [Theory] + [MemberData(nameof(Formats))] + public void SpaceBefore_DocxParagraphBefore_OdtMarginTop(TemplateFormat format) + { + TestDefinition definition = Define(t => t.SpaceBefore(17.Pt())); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + BuilderHarness.AssertInvariants(definition, template); + + if (format == TemplateFormat.Docx) + { + XElement before = Docx(template).Descendants(_w + "tbl").Single().ElementsBeforeSelf(_w + "p").Last(); + Assert.Equal("340", before.Element(_w + "pPr")!.Element(_w + "spacing")!.Attribute(_w + "before")!.Value); + Assert.Empty(before.Elements(_w + "r")); + } + else + { + Assert.Equal("17pt", OdtTableProperties(template).Attribute(_fo + "margin-top")!.Value); + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_IndentSpaceBefore_RoundTrip(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "indent", "version": 1 }, + "content": [ "Before", { "columns": [ 1 ], "indent": "6mm", "spaceBefore": "17pt", "table": [ { "row": [ "cell" ] } ] } ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + string exported = Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json; + Assert.Contains("\"indent\": \"6mm\"", exported, StringComparison.Ordinal); + Assert.Contains("\"spaceBefore\": \"17pt\"", exported, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_IndentMovesTheText(TemplateFormat format) + { + double Start(Length? indent) => PdfLayout.Words(PdfLayout.Pdf(Define(t => + { + if (indent is { } value) + { + t.Indent(value); + } + }), format)).Find("Inside").XMin; + + Assert.InRange(Start(6.Mm()) - Start(null), 17.0 - 1.5, 17.0 + 1.5); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_SpaceBeforeMovesTheTable(TemplateFormat format) + { + double Gap(bool space) + { + List words = PdfLayout.Words(PdfLayout.Pdf(Define(t => + { + if (space) + { + t.SpaceBefore(17.Pt()); + } + }), format)); + return words.Find("Inside").YMin - words.Find("Before").YMin; + } + + // DOCX carries the space on a 1 pt paragraph, as it does the space after. + Assert.InRange(Gap(space: true) - Gap(space: false), 16, 19); + } + + private static XDocument Docx(GeneratedTemplate template) => BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml"); + + private static XElement OdtTableProperties(GeneratedTemplate template) + { + XDocument content = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml"); + string name = content.Descendants(_table + "table").Single().Attribute(_table + "style-name")!.Value; + return content.Descendants(_style + "style").Single(s => s.Attribute(_style + "name")!.Value == name).Element(_style + "table-properties")!; + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TableTests.cs b/tests/TriasDev.Templify.Builder.Tests/TableTests.cs new file mode 100644 index 00000000..c5809b42 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TableTests.cs @@ -0,0 +1,404 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using System.Globalization; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed partial class TableTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"; + private static readonly XNamespace _style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0"; + private static readonly XNamespace _fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + private static readonly XNamespace _office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly TableStyleKey _grid = new TableStyleKey("Grid"); + + private static StyleSheet Sheet() => StyleSheet.Create(s => s.Table(_grid, t => t + .OuterBorder(0.75.Pt(), Color.FromHex("404040")) + .RowRule(0.5.Pt(), Color.FromHex("D4D4D4")) + .ColumnRule(0.5.Pt(), Color.FromHex("D4D4D4")) + .HeaderRule(1.5.Pt(), Color.FromHex("1F4E79")) + .HeaderBackground(Color.FromHex("EEF3F8")) + .CellPadding(2.Pt(), 4.Pt()))); + + private static TestDefinition Invoice(int extraRows = 0) => new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Styles(Sheet()); + t.Content(c => + { + c.Table(tb => + { + tb.Style(_grid); + tb.Columns(cols => + { + cols.Fixed(15.Mm()); + cols.Relative(2); + cols.Relative(1); + }); + tb.SpaceAfter(6.Pt()); + tb.HeaderRow(r => + { + r.Cell("Pos."); + r.Cell("Description"); + r.Cell("Amount"); + }); + tb.Row(r => + { + r.Cell("1"); + r.Cell(cell => + { + cell.Paragraph(order["item"]); + cell.If(order["express"], b => b.Paragraph("express")); + }); + r.Cell(cell => cell.VerticalAlignment(CellVerticalAlignment.Bottom).Paragraph(x => x.Value(order["amount"], ValueFormat.Number("F2")))); + }); + for (int i = 0; i < extraRows; i++) + { + string n = (i + 2).ToString(CultureInfo.InvariantCulture); + tb.Row(r => + { + r.Cell(n); + r.Cell("Filler line " + n); + r.Cell("0.00"); + }); + } + + tb.Row(r => + { + r.Cell(cell => cell.ColumnSpan(2).Background(Color.FromHex("F5F5F5")).Paragraph("Total")); + r.Cell(order["total"]); + }); + }); + c.Paragraph("after"); + }); + }); + + private const string OrderJson = """{ "order": { "item": "Laptop", "express": true, "amount": 1499, "total": "1,499.00" } }"""; + + [Theory] + [MemberData(nameof(Formats))] + public void Table_IsFilledByTheEngine(TemplateFormat format) + { + (_, byte[] filled) = BuilderHarness.BuildAndFill(Invoice(), format, OrderJson); + + Assert.Equal( + new[] + { + new[] { "Pos.", "Description", "Amount" }, + new[] { "1", "Laptop\nexpress", "1499.00" }, + new[] { "Total", "1,499.00" }, + }, + TableTexts(format, filled).Single()); + } + + [Fact] + public void Docx_Table_HasTheGridBordersAndRowOptions() + { + byte[] package = BuilderHarness.Build(Invoice(), TemplateFormat.Docx).Content.ToArray(); + XElement table = BuilderHarness.ReadXml(package, "word/document.xml").Descendants(_w + "tbl").Single(); + + // Frame 160 mm = 453.544 pt; 15 mm fixed; the rest 2 : 1. + Assert.Equal(new[] { "850", "5480", "2740" }, table.Element(_w + "tblGrid")!.Elements(_w + "gridCol").Select(g => g.Attribute(_w + "w")!.Value)); + XElement properties = table.Element(_w + "tblPr")!; + Assert.Equal("fixed", properties.Element(_w + "tblLayout")!.Attribute(_w + "type")!.Value); + Assert.Equal("6", properties.Element(_w + "tblBorders")!.Element(_w + "top")!.Attribute(_w + "sz")!.Value); + Assert.Equal("D4D4D4", properties.Element(_w + "tblBorders")!.Element(_w + "insideH")!.Attribute(_w + "color")!.Value); + Assert.Equal("80", properties.Element(_w + "tblCellMar")!.Element(_w + "left")!.Attribute(_w + "w")!.Value); + + List rows = table.Elements(_w + "tr").ToList(); + Assert.NotNull(rows[0].Element(_w + "trPr")!.Element(_w + "tblHeader")); + Assert.All(rows, r => Assert.NotNull(r.Element(_w + "trPr")!.Element(_w + "cantSplit"))); + XElement headerCell = rows[0].Elements(_w + "tc").First().Element(_w + "tcPr")!; + Assert.Equal("EEF3F8", headerCell.Element(_w + "shd")!.Attribute(_w + "fill")!.Value); + Assert.Equal("12", headerCell.Element(_w + "tcBorders")!.Element(_w + "bottom")!.Attribute(_w + "sz")!.Value); + XElement totalCell = rows[2].Elements(_w + "tc").First().Element(_w + "tcPr")!; + Assert.Equal("2", totalCell.Element(_w + "gridSpan")!.Attribute(_w + "val")!.Value); + Assert.Equal("6330", totalCell.Element(_w + "tcW")!.Attribute(_w + "w")!.Value); + Assert.Equal("bottom", rows[1].Elements(_w + "tc").Last().Element(_w + "tcPr")!.Element(_w + "vAlign")!.Attribute(_w + "val")!.Value); + + // SpaceAfter: a 1 pt paragraph after the table. + XElement spacer = (XElement)table.NextNode!; + Assert.Equal("120", spacer.Descendants(_w + "spacing").Single().Attribute(_w + "after")!.Value); + } + + [Fact] + public void Odt_Table_HasColumnsHeaderRowsSpansAndCellStyles() + { + byte[] package = BuilderHarness.Build(Invoice(), TemplateFormat.Odt).Content.ToArray(); + XDocument content = BuilderHarness.ReadXml(package, "content.xml"); + XElement table = content.Descendants(_table + "table").Single(); + Dictionary styles = content.Root!.Element(_office + "automatic-styles")!.Elements(_style + "style") + .ToDictionary(s => s.Attribute(_style + "name")!.Value); + + Assert.Equal("TemplifyTable1", table.Attribute(_table + "name")!.Value); + Assert.Equal( + new[] { "42.52pt", "274.016pt", "137.008pt" }, + table.Elements(_table + "table-column").Select(c => styles[c.Attribute(_table + "style-name")!.Value].Descendants().Single().Attribute(_style + "column-width")!.Value)); + Assert.Single(table.Element(_table + "table-header-rows")!.Elements(_table + "table-row")); + Assert.Equal("6pt", styles["TemplifyTable1"].Element(_style + "table-properties")!.Attribute(_fo + "margin-bottom")!.Value); + + List bodyRows = table.Elements(_table + "table-row").ToList(); + XElement total = bodyRows[1]; + Assert.Equal("2", total.Elements(_table + "table-cell").First().Attribute(_table + "number-columns-spanned")!.Value); + Assert.Single(total.Elements(_table + "covered-table-cell")); + + XElement headerCell = table.Element(_table + "table-header-rows")!.Descendants(_table + "table-cell").First(); + XElement headerProps = styles[headerCell.Attribute(_table + "style-name")!.Value].Element(_style + "table-cell-properties")!; + Assert.Equal("#eef3f8", headerProps.Attribute(_fo + "background-color")!.Value); + Assert.Equal("1.5pt solid #1f4e79", headerProps.Attribute(_fo + "border-bottom")!.Value); + Assert.Equal("0.75pt solid #404040", headerProps.Attribute(_fo + "border-top")!.Value); + XElement firstBodyCell = bodyRows[0].Elements(_table + "table-cell").First(); + // The header's bottom border draws the rule; the row below has the row rule on top (the wider one wins), so a + // row loop does not repeat the header rule between its items. + Assert.Equal("0.5pt solid #d4d4d4", styles[firstBodyCell.Attribute(_table + "style-name")!.Value].Element(_style + "table-cell-properties")!.Attribute(_fo + "border-top")!.Value); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NestedTable_ResolvesItsColumnsAgainstTheCell(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + c.Table(outer => + { + outer.Columns(cols => + { + cols.Fixed(100.Mm()); + cols.Relative(1); + }); + outer.Row(r => + { + r.Cell(cell => cell.Table(inner => + { + inner.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + inner.Row(ir => + { + ir.Cell("a"); + ir.Cell("b"); + }); + })); + r.Cell("right"); + }); + }); + c.Table(second => + { + second.Columns(cols => cols.Relative(1)); + second.Row(r => r.Cell("second table")); + }); + })); + + (GeneratedTemplate template, _) = BuilderHarness.BuildAndFill(definition, format, "{}"); + byte[] package = template.Content.ToArray(); + + // 100 mm = 283.465 pt, minus 2 × 5.4 pt default padding = 272.665 pt, halved. + if (format == TemplateFormat.Docx) + { + XElement body = BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!; + XElement inner = body.Descendants(_w + "tbl").Skip(1).First(); + Assert.Equal(new[] { "2727", "2727" }, inner.Element(_w + "tblGrid")!.Elements(_w + "gridCol").Select(g => g.Attribute(_w + "w")!.Value)); + Assert.Equal(new[] { "tbl", "p", "tbl", "p", "sectPr" }, body.Elements().Select(e => e.Name.LocalName)); + } + else + { + XDocument content = BuilderHarness.ReadXml(package, "content.xml"); + Dictionary styles = content.Root!.Element(_office + "automatic-styles")!.Elements(_style + "style") + .ToDictionary(s => s.Attribute(_style + "name")!.Value); + XElement inner = content.Descendants(_table + "table").Skip(1).First(); + Assert.Equal( + new[] { "136.333pt", "136.332pt" }, + inner.Elements(_table + "table-column").Select(c => styles[c.Attribute(_table + "style-name")!.Value].Descendants().Single().Attribute(_style + "column-width")!.Value)); + } + } + + [Fact] + public void Docx_BodyAndHeaderEndWithAParagraph_AfterATable() + { + TestDefinition definition = new TestDefinition(t => + { + t.Page(p => p.Header(h => h.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("header table")); + }))); + t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("body table")); + })); + }); + + byte[] package = BuilderHarness.Build(definition, TemplateFormat.Docx).Content.ToArray(); + + Assert.Equal(new[] { "tbl", "p", "sectPr" }, BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!.Elements().Select(e => e.Name.LocalName)); + Assert.Equal(new[] { "tbl", "p" }, BuilderHarness.ReadXml(package, "word/header1.xml").Root!.Elements().Select(e => e.Name.LocalName)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ExportsATableAtTheEndAsText(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + TestDefinition definition = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("last block is a table")); + }))); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + + // Before #279 a DOCX ending with a table made LibreOffice's text export loop forever. + string text = System.Text.Encoding.UTF8.GetString(LibreOfficeRunner.Convert(template.Content.ToArray(), template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + Assert.Contains("last block is a table", text, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Contract_IncludesCellPaths(TemplateFormat format) + { + Assert.Equal( + new[] { "order.amount", "order.express", "order.item", "order.total" }, + BuilderHarness.Build(Invoice(), format).Contract.Entries.Select(e => e.Path)); + } + + [Fact] + public void Errors_AreReported() + { + TestDefinition noColumns = new TestDefinition(t => t.Content(c => c.Table(tb => tb.Row(r => r.Cell("x"))))); + TestDefinition tooWide = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => + { + cols.Fixed(100.Mm()); + cols.Fixed(100.Mm()); + }); + tb.Row(r => + { + r.Cell("a"); + r.Cell("b"); + }); + }))); + TestDefinition wrongCells = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Columns(cols => + { + cols.Relative(1); + cols.Relative(1); + }); + tb.Row(r => r.Cell("only one")); + }))); + TestDefinition undefinedStyle = new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Style(_grid); + tb.Columns(cols => cols.Relative(1)); + tb.Row(r => r.Cell("x")); + }))); + + Assert.Equal("TB7001", Single(noColumns)); + Assert.Equal("TB7002", Single(tooWide)); + Assert.Equal("TB7003", Single(wrongCells)); + Assert.Equal("TB2010", Single(undefinedStyle)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Table(tb => + { + tb.Row(r => r.Cell("x")); + tb.HeaderRow(r => r.Cell("late header")); + }))), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Table(tb => + tb.Row(r => r.Cell(cell => cell.ColumnSpan(0)))))), TemplateFormat.Docx)); + + static string Single(TestDefinition definition) => + Assert.Single(Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Odt)).Errors).Code; + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_RepeatsTheHeaderRowAndPlacesTheColumns(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Invoice(extraRows: 60), format, OrderJson); + byte[] pdf = LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "pdf", "pdf"); + + string page2 = Pdf(pdf, 2, "-layout"); + Assert.Contains("Description", page2, StringComparison.Ordinal); + + // Column starts: frame starts at 70.866 pt; column 2 at + 42.52 pt; column 3 at + 274.016 pt more; plus 4 pt padding. + Dictionary starts = WordStarts(Pdf(pdf, 1, "-bbox")); + Assert.InRange(starts["Description"], 70.866 + 42.52 + 4 - 1.5, 70.866 + 42.52 + 4 + 1.5); + Assert.InRange(starts["Amount"], 70.866 + 42.52 + 274.016 + 4 - 1.5, 70.866 + 42.52 + 274.016 + 4 + 1.5); + } + + /// Rows of every top-level table: cell texts, paragraphs joined with a newline. + private static List TableTexts(TemplateFormat format, byte[] package) + { + if (format == TemplateFormat.Docx) + { + return BuilderHarness.ReadXml(package, "word/document.xml").Root!.Element(_w + "body")!.Elements(_w + "tbl") + .Select(t => t.Elements(_w + "tr").Select(r => r.Elements(_w + "tc") + .Select(c => string.Join("\n", c.Elements(_w + "p").Select(p => string.Concat(p.Descendants(_w + "t").Select(x => x.Value))))).ToArray()).ToArray()) + .ToList(); + } + + XElement body = BuilderHarness.ReadXml(package, "content.xml").Descendants(_office + "text").First(); + return body.Elements(_table + "table") + .Select(t => t.Descendants(_table + "table-row").Select(r => r.Elements(_table + "table-cell") + .Select(c => string.Join("\n", c.Elements(_text + "p").Select(OdtDocumentVerifier.RenderText))).ToArray()).ToArray()) + .ToList(); + } + + private static Dictionary WordStarts(string bbox) + { + Dictionary starts = new Dictionary(StringComparer.Ordinal); + foreach (Match match in WordBox().Matches(bbox)) + { + starts.TryAdd(match.Groups[2].Value, double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture)); + } + + return starts; + } + + [GeneratedRegex("xMin=\"([0-9.]+)\"[^>]*>([^<]+)")] + private static partial Regex WordBox(); + + private static string Pdf(byte[] pdf, int page, string mode) + { + string? executable = new[] { "/opt/homebrew/bin/pdftotext", "/usr/local/bin/pdftotext", "/usr/bin/pdftotext" }.FirstOrDefault(File.Exists); + Assert.SkipWhen(executable == null, "pdftotext (poppler) is not installed."); + string directory = Path.Combine(Path.GetTempPath(), "templify-pdf-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + string input = Path.Combine(directory, "document.pdf"); + File.WriteAllBytes(input, pdf); + ProcessStartInfo start = new ProcessStartInfo(executable!) { RedirectStandardOutput = true, UseShellExecute = false }; + foreach (string argument in new[] { "-f", page.ToString(CultureInfo.InvariantCulture), "-l", page.ToString(CultureInfo.InvariantCulture), mode, input, "-" }) + { + start.ArgumentList.Add(argument); + } + + using Process process = Process.Start(start)!; + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + return output; + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TemplateCheckTests.cs b/tests/TriasDev.Templify.Builder.Tests/TemplateCheckTests.cs new file mode 100644 index 00000000..f718fc9f --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TemplateCheckTests.cs @@ -0,0 +1,322 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Checking stored templates against the current data catalogue (#294). +public sealed class TemplateCheckTests +{ + public sealed record InvoiceData(Order Order); + + public sealed record Order(string Number, bool IsPaid, IReadOnlyList Lines, string DueDate, string Reference, Dictionary Extra); + + public sealed record Line(string Description, decimal Amount); + + /// The data after a breaking change: number renamed to invoiceNumber. + public sealed record RenamedData(RenamedOrder Order); + + public sealed record RenamedOrder(string InvoiceNumber, bool IsPaid, IReadOnlyList Lines, string DueDate); + + /// The component as an older build knew it. + public static class Before + { + [ComponentVersion(1)] + public sealed record Terms : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph("Terms v1"); + } + } + + /// The same component today: its wording changed, its version went up. + public static class Now + { + [ComponentVersion(2)] + public sealed record Terms : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph("Terms v2"); + } + } + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly DataCatalog _catalog = DataCatalog.From(); + + private static TemplateCheckOptions Options(TemplateIdentity? expected = null) => + new TemplateCheckOptions { Data = _catalog, Expected = expected ?? IdentityTests.InvoiceIdentity with { Version = 2 } }; + + private static TemplateCheckResult Check(GeneratedTemplate template, TemplateCheckOptions? options = null) => + TemplateInspector.Check(template.OpenRead(), options ?? Options()); + + private static TemplateCheckResult Check(byte[] template, TemplateCheckOptions? options = null) => + TemplateInspector.Check(new MemoryStream(template), options ?? Options()); + + [Theory] + [MemberData(nameof(Formats))] + public void Check_UnchangedTemplate_IsOk(TemplateFormat format) + { + TemplateCheckResult result = Check(BuilderHarness.Build(IdentityTests.Invoice(2), format)); + + Assert.Equal(TemplateCheckStatus.Ok, result.Status); + Assert.Empty(result.Problems); + Assert.Equal(format, result.Format); + Assert.Equal("invoice", result.Stamp!.TemplateId); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_CopyReadingAnotherCatalogueField_IsOk(TemplateFormat format) + { + // The standard template does not read order.reference; a customer's copy may. + GeneratedTemplate copy = BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["order"]["reference"])), IdentityTests.InvoiceIdentity with { Version = 2 }), + format); + + Assert.Equal(TemplateCheckStatus.Ok, Check(copy).Status); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_RemovedField_IsBroken_WithPath(TemplateFormat format) + { + TemplateCheckResult result = Check( + BuilderHarness.Build(IdentityTests.Invoice(2), format), + new TemplateCheckOptions { Data = DataCatalog.From() }); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems, p => p.Severity == TemplateCheckSeverity.Error); + Assert.Equal("TB9301", problem.Code); + Assert.Equal("order.number", problem.DataPath); + Assert.Contains("order.number", problem.Message, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_PathsTheDataNoLongerHas_AreListed(TemplateFormat format) + { + TemplateCheckResult result = Check(BuilderHarness.Build(IdentityTests.Invoice(1, withOldFields: true), format)); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + // order.archived comes from a MissingConditionVariable warning, read from its message until #275. + Assert.Equal( + ["line.discount", "order.archived", "order.fax"], + result.Problems.Where(p => p.Code == "TB9301").Select(p => p.DataPath).Order(StringComparer.Ordinal)); + } + + [Fact] + public void Check_LoopOverValue_IsBroken() + { + GeneratedTemplate copy = BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.ForEach(t.Data["order"]["number"], "n", (n, b) => b.Paragraph(n.Self)))), + TemplateFormat.Docx); + + TemplateCheckResult result = Check(copy); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems, p => p.Severity == TemplateCheckSeverity.Error); + Assert.Equal("TB9302", problem.Code); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_HandEdits_AreJudgedByTheirPaths(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(IdentityTests.Invoice(2), format); + byte[] bytes = template.Content.ToArray(); + string part = BuilderHarness.MainPart(format); + + // A section deleted (the paid note and its markers), a loop variable renamed. + byte[] cutDown = BuilderHarness.EditEntry(bytes, part, xml => IdentityTests.RemoveParagraphsContaining(xml, format, "{{#if order.isPaid}}", "Paid", "{{/if}}")); + byte[] renamed = BuilderHarness.EditEntry(bytes, part, xml => xml.Replace("line.", "l.", StringComparison.Ordinal).Replace("foreach line in", "foreach l in", StringComparison.Ordinal)); + + Assert.Equal(TemplateCheckStatus.Ok, Check(cutDown).Status); + Assert.Equal(TemplateCheckStatus.Ok, Check(renamed).Status); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_SyntaxError_IsBroken(TemplateFormat format) + { + byte[] bytes = BuilderHarness.Build(IdentityTests.Invoice(2), format).Content.ToArray(); + byte[] broken = BuilderHarness.EditEntry(bytes, BuilderHarness.MainPart(format), xml => IdentityTests.RemoveParagraphsContaining(xml, format, "{{/foreach}}")); + + TemplateCheckResult result = Check(broken); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems, p => p.Code == "TB9300"); + Assert.Equal(TemplateCheckSeverity.Error, problem.Severity); + Assert.Contains("foreach", problem.Message, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(result.Problems, p => p.Code == "TB9302"); + } + + [Fact] + public void Check_NotATemplate_IsBroken() + { + TemplateCheckResult result = TemplateInspector.Check(new MemoryStream([1, 2, 3, 4]), Options()); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Equal(TemplateFormat.Unknown, result.Format); + Assert.Null(result.Stamp); + Assert.Contains(result.Problems, p => p.Code == "TB9300"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_NoStamp_IsWarning(TemplateFormat format) + { + using MemoryStream stripped = new MemoryStream(); + BuilderHarness.Build(IdentityTests.Invoice(2), format).WriteTo(stripped); + TemplateStampRemover.Remove(stripped); + + TemplateCheckResult result = TemplateInspector.Check(stripped, Options()); + + Assert.Equal(TemplateCheckStatus.Warning, result.Status); + Assert.Equal("TB9303", Assert.Single(result.Problems).Code); + } + + [Fact] + public void Check_OtherTemplate_IsWarning() + { + TemplateCheckResult result = Check(BuilderHarness.Build(IdentityTests.Invoice(2), TemplateFormat.Odt), Options(new TemplateIdentity("letter", 1))); + + Assert.Equal(TemplateCheckStatus.Warning, result.Status); + Assert.Equal("TB9304", Assert.Single(result.Problems).Code); + } + + [Fact] + public void Check_OlderVersion_IsWarning() + { + TemplateCheckResult result = Check(BuilderHarness.Build(IdentityTests.Invoice(1), TemplateFormat.Docx)); + + Assert.Equal(TemplateCheckStatus.Warning, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems); + Assert.Equal("TB9305", problem.Code); + Assert.Contains("1", problem.Message, StringComparison.Ordinal); + Assert.Contains("2", problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void Check_WithoutExpectedIdentity_DoesNotJudgeTheStamp() + { + TemplateCheckResult result = Check(BuilderHarness.Build(IdentityTests.Invoice(1), TemplateFormat.Docx), new TemplateCheckOptions { Data = _catalog }); + + Assert.Equal(TemplateCheckStatus.Ok, result.Status); + } + + [Fact] + public void Check_OlderComponent_IsWarning() + { + // The copy was built with Terms at version 1; the host now registers version 2 under the same type name. + GeneratedTemplate copy = BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Component(new Before.Terms())), IdentityTests.InvoiceIdentity with { Version = 2 }), + TemplateFormat.Docx); + TemplateCheckResult result = Check(copy, Options() with { Components = new ComponentCatalog().Register("terms") }); + + Assert.Equal(TemplateCheckStatus.Warning, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems); + Assert.Equal("TB9306", problem.Code); + Assert.Contains("Terms", problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void Check_CurrentComponent_IsOk() + { + GeneratedTemplate copy = BuilderHarness.Build( + new TestDefinition(t => t.Content(c => c.Component(new Now.Terms())), IdentityTests.InvoiceIdentity with { Version = 2 }), + TemplateFormat.Docx); + + TemplateCheckResult result = Check(copy, Options() with { Components = new ComponentCatalog().Register("terms") }); + + Assert.Equal(TemplateCheckStatus.Ok, result.Status); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Check_OpenShape_AcceptsAnyPath(TemplateFormat format) + { + GeneratedTemplate copy = BuilderHarness.Build( + new TestDefinition( + t => + { + TemplatePath extra = t.Data["order"]["extra"]; + t.Content(c => + { + c.Paragraph(extra["costCentre"]["code"]); + c.ForEach(extra["notes"], "note", (note, b) => b.Paragraph(note["text"])); + }); + }, + IdentityTests.InvoiceIdentity with { Version = 2 }), + format); + + Assert.Equal(TemplateCheckStatus.Ok, Check(copy).Status); + } + + private static string InvoiceJson(int version = 2) => + TemplateJson.Export(IdentityTests.Invoice(version), BuilderHarness.Options(TemplateFormat.Docx, "de-DE")).Json; + + private static TemplateJsonImportOptions Import(DataCatalog? data = null) => new TemplateJsonImportOptions { Data = data ?? _catalog }; + + [Fact] + public void CheckDefinition_Current_IsOk() + { + TemplateCheckResult result = TemplateInspector.CheckDefinition(InvoiceJson(), Import(), BuilderHarness.Options(TemplateFormat.Docx, "de-DE"), IdentityTests.InvoiceIdentity with { Version = 2 }); + + Assert.Equal(TemplateCheckStatus.Ok, result.Status); + Assert.Empty(result.Problems); + Assert.Equal(TemplateFormat.Unknown, result.Format); + Assert.Null(result.Stamp); + } + + [Fact] + public void CheckDefinition_RemovedField_IsBroken_AtPointer() + { + TemplateCheckResult result = TemplateInspector.CheckDefinition(InvoiceJson(), Import(DataCatalog.From())); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + TemplateCheckProblem problem = Assert.Single(result.Problems); + Assert.Equal("TB9203", problem.Code); + Assert.Equal("order.number", problem.DataPath); + Assert.StartsWith("/content/", problem.Location, StringComparison.Ordinal); + } + + [Fact] + public void CheckDefinition_NotJson_IsBroken() + { + TemplateCheckResult result = TemplateInspector.CheckDefinition("{ not json", Import()); + + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Equal("TB9200", Assert.Single(result.Problems).Code); + } + + [Fact] + public void CheckDefinition_BuildError_IsBroken() + { + // Imports, but the build rejects it: a paragraph style the style sheet does not define. + string json = InvoiceJson().Replace("\"content\": [", "\"content\": [ { \"paragraph\": \"x\", \"style\": \"Missing\" },", StringComparison.Ordinal); + Assert.NotNull(TemplateJson.Import(json, Import())); + + TemplateCheckResult withoutBuild = TemplateInspector.CheckDefinition(json, Import()); + TemplateCheckResult withBuild = TemplateInspector.CheckDefinition(json, Import(), BuilderHarness.Options(TemplateFormat.Docx, "de-DE")); + + Assert.Equal(TemplateCheckStatus.Ok, withoutBuild.Status); + Assert.Equal(TemplateCheckStatus.Broken, withBuild.Status); + Assert.All(withBuild.Problems, p => Assert.Equal(TemplateCheckSeverity.Error, p.Severity)); + } + + [Fact] + public void CheckDefinition_OlderVersion_IsWarning() + { + TemplateCheckResult result = TemplateInspector.CheckDefinition(InvoiceJson(version: 1), Import(), expected: IdentityTests.InvoiceIdentity with { Version = 2 }); + + Assert.Equal(TemplateCheckStatus.Warning, result.Status); + Assert.Equal("TB9305", Assert.Single(result.Problems).Code); + } + + [Fact] + public void CheckDefinition_NeedsADataCatalogue() + { + Assert.Throws(() => TemplateInspector.CheckDefinition(InvoiceJson(), new TemplateJsonImportOptions())); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TestKitTests.cs b/tests/TriasDev.Templify.Builder.Tests/TestKitTests.cs new file mode 100644 index 00000000..4d8e70b0 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TestKitTests.cs @@ -0,0 +1,399 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.IO.Compression; +using TriasDev.Templify.Builder.Testing; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// The consumer test kit (TriasDev.Templify.Builder.Testing, #286). +public sealed class TestKitTests +{ + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading1", "Heading 1"); + + private static readonly CultureInfo _de = CultureInfo.GetCultureInfo("de-DE"); + private static readonly CultureInfo _en = CultureInfo.GetCultureInfo("en-US"); + + private const string Sample = """ + { "order": { "number": "A-17", "isPaid": true, "total": 1234.5, + "lines": [ { "description": "Chair", "amount": 2 }, { "description": "Desk", "amount": 1 } ] } } + """; + + /// A definition with texts, a conditional, a loop and a table: what a consumer verifies. + private sealed class OrderTemplate : ITemplateDefinition + { + public TemplateIdentity Identity { get; } = new TemplateIdentity("order", 2); + + public void Compose(TemplateComposer template) + { + TemplatePath order = template.Data["order"]; + template.Styles(StyleSheet.Create(s => s.Paragraph(_heading, p => p.Size(16.Pt()).Bold().OutlineLevel(1)))); + template.Page(p => p.Header(h => h.Paragraph(x => + { + x.Text(template.Texts["order.title"] + " "); + x.Value(order["number"]); + }))); + template.Content(c => + { + c.Paragraph(_heading, x => + { + x.Text(template.Texts["order.title"] + " "); + x.Value(order["number"]); + }); + c.If(order["isPaid"], b => b.Paragraph(template.Texts["order.paid"])); + c.Table(t => + { + t.Columns(cols => + { + cols.Relative(3); + cols.Relative(1); + }); + t.ForEachRow(order["lines"], "line", (line, rows) => rows.Row(r => + { + r.Cell(line["description"]); + r.Cell(line["amount"]); + })); + }); + c.Paragraph(x => + { + x.Text(template.Texts["order.total"] + "\t"); + x.Value(order["total"], ValueFormat.Number("N2")); + }); + }); + } + } + + private static readonly ITextCatalog _catalog = TextCatalog.FromDictionary(new Dictionary> + { + ["order.title"] = new Dictionary { ["de"] = "Auftrag", ["en"] = "Order" }, + ["order.paid"] = new Dictionary { ["de"] = "Bezahlt.", ["en"] = "Paid." }, + ["order.total"] = new Dictionary { ["de"] = "Summe:", ["en"] = "Total:" }, + }); + + private static ITextCatalog Texts(CultureInfo language) => _catalog; + + private static TemplateVerificationOptions Options => new TemplateVerificationOptions + { + Languages = [_de, _en], + Texts = Texts, + SampleData = [Sample], + }; + + [Fact] + public void VerifyAll_PassesForAGoodDefinition() + { + TemplateVerificationReport report = TemplateVerifier.VerifyAll(() => new OrderTemplate(), Options); + + Assert.True(report.IsSuccess); + Assert.Equal(4, report.Templates.Count); + Assert.Equal( + new[] { "de-DE/Docx", "de-DE/Odt", "en-US/Docx", "en-US/Odt" }, + report.Templates.Select(t => t.Language.Name + "/" + t.Format)); + Assert.Single(report.Templates.Select(t => t.Template.Contract.Hash).Distinct()); + Assert.StartsWith("Template verification passed (4 templates)", report.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Verify_DefaultOptions_BuildBothFormatsInEnglish() + { + TemplateVerificationReport report = TemplateVerifier.Verify(() => new TestDefinition(t => t.Content(c => c.Paragraph("Hello")))); + + Assert.True(report.IsSuccess, report.ToString()); + Assert.Equal(new[] { TemplateFormat.Docx, TemplateFormat.Odt }, report.Templates.Select(t => t.Format)); + Assert.All(report.Templates, t => Assert.Equal("en-US", t.Language.Name)); + } + + [Fact] + public void Verify_ReportsBuildErrorsPerTarget() + { + TemplateVerificationReport report = TemplateVerifier.Verify( + () => new TestDefinition(t => t.Content(c => c.Paragraph(new ParagraphStyleKey("Undefined", "Undefined"), "x")))); + + Assert.False(report.IsSuccess); + Assert.Empty(report.Templates); + Assert.Equal(2, report.Failures.Count); + Assert.All(report.Failures, f => + { + Assert.Equal(VerificationCheck.Build, f.Check); + Assert.StartsWith("TB", f.Message, StringComparison.Ordinal); + }); + } + + [Fact] + public void VerifyAll_ThrowsWithEveryFailure() + { + TemplateVerificationException exception = Assert.Throws(() => TemplateVerifier.VerifyAll( + () => new OrderTemplate(), + new TemplateVerificationOptions { Texts = Texts, SampleData = ["""{ "order": { "number": "A-17" } }"""] })); + + // The sample lacks order.lines and order.total: the fill fails in both formats. + Assert.Equal(2, exception.Report.Failures.Count); + Assert.All(exception.Report.Failures, f => Assert.Equal(VerificationCheck.Fill, f.Check)); + Assert.Contains("[en-US/docx] Fill: sample data #1:", exception.Message, StringComparison.Ordinal); + Assert.Contains("[en-US/odt] Fill: sample data #1:", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Verify_FindsNonDeterministicDefinitions() + { + // A definition must not read the clock, random values or the current culture. + TemplateVerificationReport report = TemplateVerifier.Verify( + () => new TestDefinition(t => t.Content(c => c.Paragraph(Guid.NewGuid().ToString()))), + new TemplateVerificationOptions { Formats = [TemplateFormat.Odt] }); + + TemplateVerificationFailure[] failures = report.Failures.ToArray(); + Assert.Equal(2, failures.Length); + Assert.All(failures, f => Assert.Equal(VerificationCheck.Determinism, f.Check)); + Assert.Contains("tr-TR", failures[0].Message, StringComparison.Ordinal); + Assert.Contains("ar-SA", failures[1].Message, StringComparison.Ordinal); + } + + [Fact] + public void Verify_FindsContractsThatDifferAcrossLanguages() + { + // A definition whose data depends on something else than the texts: here a call counter, standing in for + // a definition that branches on the language outside the catalog. + int builds = 0; + TemplateVerificationReport report = TemplateVerifier.Verify( + () => + { + bool first = builds++ == 0; + return new TestDefinition(t => t.Content(c => c.Paragraph(first ? t.Data["a"] : t.Data["b"]))); + }, + new TemplateVerificationOptions { Formats = [TemplateFormat.Docx], Languages = [_de, _en], DeterminismCultures = [] }); + + TemplateVerificationFailure failure = Assert.Single(report.Failures); + Assert.Equal(VerificationCheck.ContractParity, failure.Check); + Assert.Null(failure.Language); + Assert.Equal("en-US/docx reads different data than de-DE/docx: -a (Value), +b (Value)", failure.Message); + } + + [Fact] + public void Verify_BuildWarnings_FailOnlyWhenAsked() + { + Func toc = () => new TestDefinition(t => t.Content(c => c.TableOfContents())); + + Assert.True(TemplateVerifier.Verify(toc).IsSuccess); + TemplateVerificationReport strict = TemplateVerifier.Verify(toc, new TemplateVerificationOptions { FailOnBuildWarnings = true }); + Assert.All(strict.Failures, f => Assert.Equal(VerificationCheck.BuildWarning, f.Check)); + Assert.Contains(strict.Failures, f => f.Message.StartsWith("TB9001", StringComparison.Ordinal)); + } + + [Fact] + public void Verify_RejectsEmptyTargets() + { + Assert.Throws(() => TemplateVerifier.Verify(() => new OrderTemplate(), new TemplateVerificationOptions { Languages = [] })); + Assert.Throws(() => TemplateVerifier.Verify(null!)); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void CheckTemplate_FindsPlaceholdersOutsideTheContract(TemplateFormat format) + { + // A hand-edited template that reads a path its contract does not declare. + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["name"]))), format); + byte[] edited = BuilderHarness.EditEntry( + template.Content.ToArray(), + BuilderHarness.MainPart(format), + xml => xml.Replace("{{name}}", "{{name}} {{extra}}", StringComparison.Ordinal)); + GeneratedTemplate tampered = Rewrap(template, edited); + + IReadOnlyList problems = TemplateVerifier.CheckTemplate(tampered); + + Assert.Contains(problems, p => p.StartsWith("Contract: 'extra' is read but not in the data contract.", StringComparison.Ordinal)); + } + + [Fact] + public void CheckFill_ReportsMissingVariablesAndAcceptsCompleteData() + { + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["name"]))), TemplateFormat.Docx); + + Assert.Empty(TemplateVerifier.CheckFill(template, """{ "name": "Ada" }""")); + Assert.Contains("name", Assert.Single(TemplateVerifier.CheckFill(template, "{}")), StringComparison.Ordinal); + } + + [Fact] + public void CheckPackage_FindsACompressedMimetype() + { + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("x"))), TemplateFormat.Odt); + byte[] broken = Repack(template.Content.ToArray(), compressMimetype: true); + + IReadOnlyList problems = TemplateVerifier.CheckPackage(TemplateFormat.Odt, broken); + + Assert.Contains("The mimetype entry is compressed; it must be stored.", problems); + } + + [Fact] + public void CheckPackage_FindsAManifestEntryWithoutAFile() + { + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("x"))), TemplateFormat.Odt); + byte[] broken = BuilderHarness.EditEntry( + template.Content.ToArray(), + "META-INF/manifest.xml", + xml => xml.Replace("", "", StringComparison.Ordinal)); + + Assert.Contains("The manifest lists 'Pictures/missing.png', which is not in the package.", TemplateVerifier.CheckPackage(TemplateFormat.Odt, broken)); + } + + [Fact] + public void CheckPackage_FindsDocxSchemaErrors() + { + GeneratedTemplate template = BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("x"))), TemplateFormat.Docx); + byte[] broken = BuilderHarness.EditEntry( + template.Content.ToArray(), + "word/document.xml", + xml => xml.Replace("", "", StringComparison.Ordinal)); + + Assert.NotEmpty(TemplateVerifier.CheckPackage(TemplateFormat.Docx, broken)); + Assert.Empty(TemplateVerifier.CheckPackage(TemplateFormat.Docx, template.Content)); + } + + [Fact] + public void CheckPackage_NotAPackage_IsAProblemNotAnException() + { + Assert.Single(TemplateVerifier.CheckPackage(TemplateFormat.Odt, new byte[] { 1, 2, 3 })); + Assert.Single(TemplateVerifier.CheckPackage(TemplateFormat.Docx, new byte[] { 1, 2, 3 })); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Snapshot_IsTheSameForBothFormats(TemplateFormat format) + { + GeneratedTemplate template = TemplateBuilder.Build( + new OrderTemplate(), + new TemplateBuildOptions { Format = format, Language = _en, Texts = Texts(_en) }); + + string snapshot = TemplateSnapshot.Create(template); + + Assert.Equal( + """ + == body + Heading1 | Order {{order.number}} + TemplifyMarker | {{#if order.isPaid}} + Normal | Paid. + TemplifyMarker | {{/if}} + table + row + cell + TemplifyMarker | {{#foreach line in order.lines}} + row + cell + Normal | {{line.description}} + cell + Normal | {{line.amount}} + row + cell + TemplifyMarker | {{/foreach}} + Normal | Total:→{{order.total:number:N2}} + == header + Normal | Order {{order.number}} + """.Replace("\r\n", "\n", StringComparison.Ordinal), + snapshot); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Snapshot_ShowsListsFieldsImagesAndBreaks(TemplateFormat format) + { + ListStyleKey bullets = new ListStyleKey("Bullets"); + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.List(bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm()).Level(1, "–", 12.Mm(), 4.Mm())))); + t.Page(p => p.Footer(f => f.Paragraph(x => + { + x.PageNumber(); + x.Text(" / "); + x.PageCount(); + }))); + t.Content(c => + { + c.List(bullets, l => + { + l.Item("one"); + l.Item("two"); + l.Item(1, "nested"); + }); + c.Paragraph(x => + { + x.Text("a"); + x.LineBreak(); + x.Text("b"); + x.Tab(); + x.Image(ImageSource.Png(ImageTests.Png), "logo"); + }); + }); + }); + + string snapshot = TemplateSnapshot.Create(BuilderHarness.Build(definition, format)); + + Assert.Equal( + """ + == body + Normal [list 1] | one + Normal [list 1] | two + Normal [list 2] | nested + Normal | a↵b→[image] + == footer + Normal | {PAGE} / {NUMPAGES} + """.Replace("\r\n", "\n", StringComparison.Ordinal), + snapshot); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + public void Snapshot_OfAFilledDocument(TemplateFormat format) + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill( + new TestDefinition(t => t.Content(c => c.If(t.Data["show"], b => b.Paragraph(t.Data["name"])))), + format, + """{ "show": true, "name": "Ada" }"""); + + Assert.Equal("== body\nNormal | Ada", TemplateSnapshot.Create(format, filled)); + Assert.Contains("{{#if show}}", TemplateSnapshot.Create(template), StringComparison.Ordinal); + } + + [Theory] + [InlineData(TemplateFormat.Docx)] + [InlineData(TemplateFormat.Odt)] + [Trait("Category", "LibreOffice")] + public void LibreOfficeConverter_ConvertsTemplatesAndFilledDocuments(TemplateFormat format) + { + Assert.SkipUnless(LibreOfficeConverter.IsAvailable, "LibreOffice (soffice) is not installed; set TEMPLIFY_SOFFICE to run round-trip tests."); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill( + new TestDefinition(t => t.Content(c => c.Paragraph(t.Data["name"]))), + format, + """{ "name": "Ada Lovelace" }"""); + + Assert.Equal("Ada Lovelace\n", LibreOfficeConverter.ToText(filled, template.FileExtension)); + byte[] pdf = LibreOfficeConverter.ToPdf(template); + Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(pdf, 0, 4)); + } + + private static GeneratedTemplate Rewrap(GeneratedTemplate template, byte[] content) => + new GeneratedTemplate(template.Format, content, template.Contract, template.Stamp, template.Warnings); + + private static byte[] Repack(byte[] package, bool compressMimetype) + { + using MemoryStream output = new MemoryStream(); + using (MemoryStream input = new MemoryStream(package)) + using (ZipArchive source = new ZipArchive(input, ZipArchiveMode.Read)) + using (ZipArchive target = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (ZipArchiveEntry entry in source.Entries) + { + CompressionLevel level = entry.FullName == "mimetype" && !compressMimetype ? CompressionLevel.NoCompression : CompressionLevel.Optimal; + using Stream from = entry.Open(); + using Stream to = target.CreateEntry(entry.FullName, level).Open(); + from.CopyTo(to); + } + } + + return output.ToArray(); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TextTemplateTests.cs b/tests/TriasDev.Templify.Builder.Tests/TextTemplateTests.cs new file mode 100644 index 00000000..cfe332f6 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TextTemplateTests.cs @@ -0,0 +1,73 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Builder.Json; + +namespace TriasDev.Templify.Builder.Tests; + +/// Strings with placeholders in JSON definitions: {{path}}, {{path:format}}, {{(condition):format}}. +public sealed class TextTemplateTests +{ + public static TheoryData Valid => new TheoryData + { + { + "Auftrag {{order.number}} · {{order.date:date:d. MMMM yyyy}}", + "L(Auftrag )¦V(order.number,-)¦L( · )¦V(order.date,date:d. MMMM yyyy)" + }, + { "{{a}}{{b}}", "V(a,-)¦V(b,-)" }, + { "plain", "L(plain)" }, + { "", "L()" }, + { "a }} b", "L(a }} b)" }, + { "a } { b", "L(a } { b)" }, + { "{{order.date:date:HH:mm}}", "V(order.date,date:HH:mm)" }, + { "{{line.tags:join:\" · \"}}", "V(line.tags,join:\" · \")" }, + { "x {{@number}}.", "L(x )¦V(@number,-)¦L(.)" }, + { + "Free: {{(order.isExpress and order.total > 1000):yesno}}", + "L(Free: )¦E(order.isExpress and order.total > 1000,yesno)" + }, + { "{{(a = \"x):y\"):yesno}}", "E(a = \"x):y\",yesno)" }, + { "{{(a = 'it''s')}}", "E(a = 'it''s',-)" }, + { "{{(a = \"q\\\")\"):yesno}}", "E(a = \"q\\\")\",yesno)" }, + { "{{((a or b) and c)}}", "E((a or b) and c,-)" }, + }; + + [Theory] + [MemberData(nameof(Valid))] + public void Parse_SplitsIntoPieces(string text, string expected) + { + Assert.Equal(expected, Describe(TextTemplate.Parse(text))); + } + + [Theory] + [MemberData(nameof(Valid))] + public void Write_IsTheInverseOfParse(string text, string pieces) + { + _ = pieces; + Assert.Equal(text, TextTemplate.Write(TextTemplate.Parse(text))); + } + + private static string Describe(IEnumerable pieces) => string.Join("¦", pieces.Select(p => p switch + { + TextPiece.Literal l => "L(" + l.Text + ")", + TextPiece.Value v => "V(" + v.Path + "," + (v.Format ?? "-") + ")", + TextPiece.Expression e => "E(" + e.Condition + "," + (e.Format ?? "-") + ")", + _ => "?", + })); + + [Theory] + [InlineData("{{", "{{")] + [InlineData("x {{a", "{{a")] + [InlineData("{{}}", "{{}}")] + [InlineData("{{:yesno}}", "{{:yesno}}")] + [InlineData("{{(a}}", "{{(a}}")] + [InlineData("{{(a) junk}}", "{{(a) junk}}")] + [InlineData("{{(a):}}", "{{(a):}}")] + [InlineData("{{a:}}", "{{a:}}")] + [InlineData("{{()}}", "{{()}}")] + public void Parse_RejectsMalformedPlaceholders(string text, string quoted) + { + FormatException exception = Assert.Throws(() => TextTemplate.Parse(text)); + Assert.Contains(quoted, exception.Message, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TocEntryStyleTests.cs b/tests/TriasDev.Templify.Builder.Tests/TocEntryStyleTests.cs new file mode 100644 index 00000000..f40bfc9d --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TocEntryStyleTests.cs @@ -0,0 +1,175 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #295 F9: the look of a table of contents' entries, a paragraph style per level. +public sealed class TocEntryStyleTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + + private static readonly ParagraphStyleKey _body = new ParagraphStyleKey("Body", "Body Copy"); + private static readonly ParagraphStyleKey _heading = new ParagraphStyleKey("Heading", "Section Heading"); + private static readonly ParagraphStyleKey _tocPart = new ParagraphStyleKey("TocPart", "Contents Part"); + private static readonly ParagraphStyleKey _tocSection = new ParagraphStyleKey("TocSection", "Contents Section"); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Define(Action content) => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_body, p => p.Size(10.Pt())); + s.Paragraph(_heading, p => p.BasedOn(_body).Bold().OutlineLevel(1)); + s.Paragraph(_tocPart, p => p.BasedOn(_body).Bold().SpaceBefore(6.Pt())); + s.Paragraph(_tocSection, p => p.BasedOn(_body).IndentStart(5.Mm())); + })); + t.Content(content); + }); + + private static TestDefinition Styled() => Define(c => c + .TableOfContents(3, toc => toc.Level(1, _tocPart).Level(2, _tocSection)) + .Paragraph(_heading, "Introduction") + .Paragraph(_body, "Text")); + + [Fact] + public void Docx_DefinesTocStylesBasedOnTheEntryStyles() + { + GeneratedTemplate template = BuilderHarness.Build(Styled(), TemplateFormat.Docx); + BuilderHarness.AssertInvariants(Styled(), template); + List styles = BuilderHarness.ReadXml(template.Content.ToArray(), "word/styles.xml").Descendants(_w + "style").ToList(); + + XElement toc1 = styles.Single(s => s.Attribute(_w + "styleId")?.Value == "TOC1"); + Assert.Equal(("toc 1", "TocPart"), (toc1.Element(_w + "name")!.Attribute(_w + "val")!.Value, toc1.Element(_w + "basedOn")!.Attribute(_w + "val")!.Value)); + Assert.Equal("TocSection", styles.Single(s => s.Attribute(_w + "styleId")?.Value == "TOC2").Element(_w + "basedOn")!.Attribute(_w + "val")!.Value); + Assert.DoesNotContain(styles, s => s.Attribute(_w + "styleId")?.Value == "TOC3"); + } + + [Fact] + public void Odt_EntryTemplatesUseTheEntryStyles() + { + GeneratedTemplate template = BuilderHarness.Build(Styled(), TemplateFormat.Odt); + BuilderHarness.AssertInvariants(Styled(), template); + List styles = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml").Descendants(_text + "table-of-content-entry-template") + .Select(e => e.Attribute(_text + "style-name")?.Value).ToList(); + Assert.Equal(new[] { "TocPart", "TocSection", "Contents_20_3" }, styles); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NoEntryStyles_BuildsAsBefore(TemplateFormat format) => + Assert.Equal( + BuilderHarness.Build(Define(c => c.TableOfContents(3)), format).ContentHash, + BuilderHarness.Build(Define(c => c.TableOfContents(3, toc => { })), format).ContentHash); + + [Fact] + public void LevelOutsideTheTable_Throws() => + Assert.Throws(() => BuilderHarness.Build(Define(c => c.TableOfContents(2, toc => toc.Level(3, _tocPart))), TemplateFormat.Docx)); + + [Theory] + [InlineData("undefined", "TB2010")] + [InlineData("heading", "TB8002")] + [InlineData("conflict", "TB8003")] + public void EntryStyleProblems_AreBuildErrors(string kind, string code) + { + TestDefinition definition = Define(c => + { + switch (kind) + { + case "undefined": + c.TableOfContents(2, toc => toc.Level(1, new ParagraphStyleKey("Missing", "Missing"))); + break; + case "heading": + c.TableOfContents(2, toc => toc.Level(1, _heading)); + break; + default: + c.TableOfContents(2, toc => toc.Level(1, _tocPart)).TableOfContents(2, toc => toc.Level(1, _tocSection)); + break; + } + }); + TemplateBuildException error = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + Assert.Contains(error.Errors, e => e.Code == code); + } + + [Theory] + [InlineData("TOC1", "My Toc", "TB2001")] + [InlineData("toc1", "My Toc", "TB2001")] + [InlineData("Mine", "toc 1", "TB2002")] + [InlineData("Other", "TOC 1", "TB2002")] + public void UserStyleTakingAGeneratedTocName_IsAnError(string id, string name, string code) + { + // DOCX writes "toc 1" (id TOC1) for a styled level 1: a user style with that id or name would be a duplicate. + TestDefinition definition = new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_body, p => p.Size(10.Pt())); + s.Paragraph(_tocPart, p => p.BasedOn(_body).Bold()); + s.Paragraph(new ParagraphStyleKey(id, name), p => p.BasedOn(_body)); + })); + t.Content(c => c.TableOfContents(2, toc => toc.Level(1, _tocPart))); + }); + TemplateBuildException error = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + Assert.Contains(error.Errors, e => e.Code == code); + } + + [Fact] + public void UserStyleNamedLikeTocWithoutEntryStyles_StillBuilds() => + BuilderHarness.Build(new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => s.Paragraph(new ParagraphStyleKey("TOC1", "toc 1"), p => p.Bold()))); + t.Content(c => c.TableOfContents(2)); + }), TemplateFormat.Docx); + + [Fact] + public void Odt_UnstyledTableOfContents_UsesTheDocumentsEntryStyles() + { + // DOCX entry styles are document-wide, so an unstyled table of contents gets them too; the ODT says the same. + TestDefinition definition = Define(c => c.TableOfContents(2, toc => toc.Level(1, _tocPart)).TableOfContents(2, toc => toc.Level(2, _tocSection)).TableOfContents(2)); + List styles = BuilderHarness.ReadXml(BuilderHarness.Build(definition, TemplateFormat.Odt).Content.ToArray(), "content.xml") + .Descendants(_text + "table-of-content-entry-template").Select(e => e.Attribute(_text + "style-name")?.Value).ToList(); + Assert.Equal(new[] { "TocPart", "TocSection", "TocPart", "TocSection", "TocPart", "TocSection" }, styles); + } + + [Theory] + [InlineData("[]")] + [InlineData("\"TocPart\"")] + [InlineData("null")] + public void Json_LevelsNotAnObject_IsAnError(string levels) + { + string json = $$""" + { + "templifyDefinition": 1, + "identity": { "id": "toc", "version": 1 }, + "content": [ { "toc": { "maxLevel": 2, "levels": {{levels}} } } ] + } + """; + TemplateBuildException error = Assert.Throws(() => Json.TemplateJson.Import(json)); + Assert.Contains(error.Errors, e => e.Location == "/content/0/toc/levels"); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Json_EntryStyles_RoundTrip(TemplateFormat format) + { + const string json = """ + { + "templifyDefinition": 1, + "identity": { "id": "toc", "version": 1 }, + "styles": { "paragraph": { + "Heading": { "name": "Section Heading", "outlineLevel": 1 }, + "TocPart": { "name": "Contents Part", "bold": true } + } }, + "content": [ { "toc": { "maxLevel": 2, "levels": { "1": "TocPart" } } }, { "style": "Heading", "paragraph": "Intro" } ] + } + """; + ITemplateDefinition imported = Json.TemplateJson.Import(json); + GeneratedTemplate template = BuilderHarness.Build(imported, format); + BuilderHarness.AssertInvariants(imported, template); + Assert.Contains("\"levels\": {\"1\": \"TocPart\"}", Json.TemplateJson.Export(imported, BuilderHarness.Options(format)).Json, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TocTests.cs b/tests/TriasDev.Templify.Builder.Tests/TocTests.cs new file mode 100644 index 00000000..e469f387 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TocTests.cs @@ -0,0 +1,112 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Xml.Linq; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class TocTests +{ + private static readonly XNamespace _w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static readonly XNamespace _text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static readonly ParagraphStyleKey _h1 = new ParagraphStyleKey("H1", "Heading Level One"); + private static readonly ParagraphStyleKey _h2 = new ParagraphStyleKey("H2", "Heading Level Two"); + + private static TestDefinition Report() => new TestDefinition(t => + { + t.Styles(StyleSheet.Create(s => + { + s.Paragraph(_h1, p => p.Size(16.Pt()).OutlineLevel(1)); + s.Paragraph(_h2, p => p.Size(13.Pt()).OutlineLevel(2)); + })); + t.Content(c => + { + c.Paragraph("Contents"); + c.TableOfContents(2); + c.PageBreak(); + c.Paragraph(_h1, x => + { + x.Text("Chapter "); + x.Value(t.Data["name"]); + }); + c.Paragraph(_h2, "Section"); + }); + }); + + [Fact] + public void Docx_TocIsADirtyFieldOverOutlineLevels() + { + GeneratedTemplate template = BuilderHarness.Build(Report(), TemplateFormat.Docx); + XElement body = BuilderHarness.ReadXml(template.Content.ToArray(), "word/document.xml").Root!.Element(_w + "body")!; + + // The field's end sits in a paragraph of its own: LibreOffice imports a field whose result is empty and in one + // paragraph as text, so a converter that refreshes indexes (Stirling-PDF) would leave the contents empty (#295). + XElement toc = body.Elements(_w + "p").ElementAt(1); + XElement end = body.Elements(_w + "p").ElementAt(2); + Assert.Equal(new[] { "begin", "separate" }, toc.Descendants(_w + "fldChar").Select(f => f.Attribute(_w + "fldCharType")!.Value)); + Assert.Equal(new[] { "end" }, end.Descendants(_w + "fldChar").Select(f => f.Attribute(_w + "fldCharType")!.Value)); + Assert.Equal("true", toc.Descendants(_w + "fldChar").First().Attribute(_w + "dirty")!.Value); + string instruction = toc.Descendants(_w + "instrText").Single().Value; + Assert.Equal(" TOC \\o \"1-2\" \\h \\z \\u ", instruction); + Assert.DoesNotContain("\\t", instruction, StringComparison.Ordinal); + + // Filled with UpdateFieldsOnOpen = Auto, the engine asks Word to update the fields on open. + GeneratedTemplate built = BuilderHarness.Build(Report(), TemplateFormat.Docx); + using Stream input = built.OpenRead(); + using MemoryStream output = new MemoryStream(); + new TemplateProcessor(new PlaceholderReplacementOptions { UpdateFieldsOnOpen = UpdateFieldsOnOpenMode.Auto }).ProcessTemplate(input, output, """{ "name": "Alpha" }"""); + Assert.Equal("true", BuilderHarness.ReadXml(output.ToArray(), "word/settings.xml").Descendants(_w + "updateFields").Single().Attribute(_w + "val")!.Value); + } + + [Fact] + public void Odt_TocIsAnIndexOverOutlineLevels() + { + GeneratedTemplate template = BuilderHarness.Build(Report(), TemplateFormat.Odt); + XElement toc = BuilderHarness.ReadXml(template.Content.ToArray(), "content.xml").Descendants(_text + "table-of-content").Single(); + + Assert.Equal("TemplifyToc1", toc.Attribute(_text + "name")!.Value); + XElement source = toc.Element(_text + "table-of-content-source")!; + Assert.Equal("2", source.Attribute(_text + "outline-level")!.Value); + Assert.Equal(new[] { "1", "2" }, source.Elements(_text + "table-of-content-entry-template").Select(e => e.Attribute(_text + "outline-level")!.Value)); + Assert.Empty(toc.Element(_text + "index-body")!.Elements()); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Toc_IsFilledAndWarnsThatOnlyWordBuildsIt(TemplateFormat format) + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Report(), format, """{ "name": "Alpha" }"""); + + BuildDiagnostic warning = Assert.Single(template.Warnings); + Assert.Equal("TB9001", warning.Code); + Assert.Contains("LibreOffice", warning.Message, StringComparison.Ordinal); + Assert.Contains("Chapter Alpha", BuilderHarness.ParagraphTexts(format, filled)); + Assert.Empty(BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph("x"))), format).Warnings); + } + + [Fact] + public void Toc_LevelIsChecked() + { + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.TableOfContents(0))), TemplateFormat.Docx)); + Assert.Throws(() => BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.TableOfContents(10))), TemplateFormat.Docx)); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_ConvertsADocumentWithAToc(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Report(), format, """{ "name": "Alpha" }"""); + + string text = System.Text.Encoding.UTF8.GetString(LibreOfficeRunner.Convert(filled, template.FileExtension.TrimStart('.'), "txt:Text (encoded):UTF8", "txt")); + + Assert.Contains("Chapter Alpha", text, StringComparison.Ordinal); + Assert.Contains("Section", text, StringComparison.Ordinal); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj b/tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj new file mode 100644 index 00000000..7f17bb76 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TriasDev.Templify.Builder.Tests.csproj @@ -0,0 +1,37 @@ + + + + + $(NoWarn);TPLB001 + net11.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/TriasDev.Templify.Builder.Tests/TypedPathTests.cs b/tests/TriasDev.Templify.Builder.Tests/TypedPathTests.cs new file mode 100644 index 00000000..829a4dc8 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/TypedPathTests.cs @@ -0,0 +1,218 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text.Json; +using System.Text.Json.Serialization; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// Data paths from C# types (#274, approach A with types all the way through). +public sealed class TypedPathTests +{ + public sealed record OrderData(Order Order); + + public sealed record Order(string Number, decimal Total, bool IsExpress, Customer Customer, List Lines, Dictionary Settings); + + public sealed record Customer(string Name, Address Address); + + public sealed record Address(string Street, string City); + + public sealed record Line(string Description, int Quantity); + + public sealed record Renamed([property: JsonPropertyName("cust")] Customer Customer, bool IsExpress); + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TemplatePath Root(Action>? use = null) + { + TemplatePath? root = null; + BuilderHarness.Build(new TestDefinition(t => + { + root = t.DataAs(); + use?.Invoke(root.Value); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + return root!.Value; + } + + [Fact] + public void Path_MapsMembersWithCamelCase() + { + Assert.Equal("order.customer.name", Root().Path(o => o.Order.Customer.Name).ToString()); + } + + [Fact] + public void Path_HonoursJsonPropertyNameAndPolicy() + { + string? renamed = null; + string? snake = null; + BuilderHarness.Build(new TestDefinition(t => + { + renamed = t.DataAs().Path(r => r.Customer.Name).ToString(); + snake = t.DataAs(JsonNamingPolicy.SnakeCaseLower).Path(r => r.IsExpress).ToString(); + t.Content(c => c.Paragraph("x")); + }), TemplateFormat.Docx); + + Assert.Equal("cust.name", renamed); + Assert.Equal("is_express", snake); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Path_FillsWithDataInThatShape(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath d = t.DataAs(JsonNamingPolicy.SnakeCaseLower); + t.Content(c => c.Paragraph(x => + { + x.Value(d.Path(r => r.Customer.Name)); + x.Text(" "); + x.Expression(d.Path(r => r.IsExpress), ValueFormat.YesNo); + })); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, """{ "cust": { "name": "Ada" }, "is_express": true }"""); + + Assert.Equal("Ada Yes", Assert.Single(BuilderHarness.ParagraphTexts(format, filled))); + } + + [Fact] + public void Path_DictionaryKey_IsASegment() + { + Assert.Equal("order.settings.Theme", Root().Path(o => o.Order.Settings["Theme"]).ToString()); + } + + [Theory] + [InlineData("first")] + [InlineData("method")] + [InlineData("captured")] + [InlineData("index")] + public void Path_UnsupportedExpressions_Throw(string kind) + { + int i = 0; + TemplatePath d = Root(); + + ArgumentException exception = Assert.Throws(() => kind switch + { + "first" => d.Path(o => o.Order.Lines.First().Description).ToString(), + "method" => d.Path(o => o.Order.Number.ToUpperInvariant()).ToString(), + "captured" => d.Path(o => o.Order.Settings[i.ToString(System.Globalization.CultureInfo.InvariantCulture)]).ToString(), + _ => d.Path(o => o.Order.Lines[i].Description).ToString(), + }); + + Assert.Contains("o => o.Order", exception.Message, StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void TypedLoop_ProducesTheSameBytesAsTheStringApi(TemplateFormat format) + { + TestDefinition typed = new TestDefinition(t => + { + TemplatePath d = t.DataAs(); + t.Content(c => + { + c.ForEach(d.Path(o => o.Order).Items(o => o.Lines), "line", (line, b) => b.Paragraph(x => + { + x.Value(line.Loop.Number); + x.Text(". "); + x.Value(line.Path(l => l.Description)); + })); + c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.ForEachRow(d.Items(o => o.Order.Lines), "row", (row, rows) => rows.Row(r => r.Cell(row.Path(l => l.Quantity)))); + }); + }); + }); + TestDefinition strings = new TestDefinition(t => + { + TemplatePath order = t.Data["order"]; + t.Content(c => + { + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(x => + { + x.Value(line.Loop.Number); + x.Text(". "); + x.Value(line["description"]); + })); + c.Table(tb => + { + tb.Columns(cols => cols.Relative(1)); + tb.ForEachRow(order["lines"], "row", (row, rows) => rows.Row(r => r.Cell(row["quantity"]))); + }); + }); + }); + + Assert.Equal(BuilderHarness.Build(strings, format).ContentHash, BuilderHarness.Build(typed, format).ContentHash); + } + + private sealed record AddressBlock(TemplatePath
Address) : ITemplateComponent + { + public void Compose(BlockComposer content) => content.Paragraph(x => + { + x.Value(Address.Path(a => a.Street)); + x.Text(", "); + x.Value(Address.Path(a => a.City)); + }); + } + + [Fact] + public void TypedComponentParameter() + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + c.Component(new AddressBlock(t.DataAs().Path(o => o.Order.Customer.Address))))); + + GeneratedTemplate template = BuilderHarness.Build(definition, TemplateFormat.Odt); + + Assert.Contains(new ContractEntry("order.customer.address.city", ContractUsage.Value), template.Contract.Entries); + Assert.Contains(new ContractEntry("order.customer.address.street", ContractUsage.Value), template.Contract.Entries); + } + + [Fact] + public void TypedConditions() + { + Condition? condition = null; + Root(d => condition = d.Path(o => o.Order.IsExpress) & d.Path(o => o.Order.Total).Gt(1000) | !d.Path(o => o.Order.Customer.Name).IsEmpty); + + Assert.Equal("order.isExpress and order.total > 1000 or not (order.customer.name is empty)", condition!.ToString()); + } + + [Fact] + public void TypedList_AndCollectionConditions() + { + ListStyleKey bullets = new ListStyleKey("Bullets"); + TestDefinition definition = new TestDefinition(t => + { + TemplatePath d = t.DataAs(); + t.Styles(StyleSheet.Create(s => s.List(bullets, l => l.Level(0, "•", 6.Mm(), 4.Mm())))); + t.Content(c => c.If(d.Items(o => o.Order.Lines).IsNotEmpty, b => b.List(bullets, l => + l.ForEach(d.Items(o => o.Order.Lines), "line", (line, items) => items.Item(line.Path(x => x.Description)))))); + }); + + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, TemplateFormat.Docx, """{ "order": { "lines": [ { "description": "A" }, { "description": "B" } ] } }"""); + + Assert.Equal(new[] { "A", "B" }, BuilderHarness.ParagraphTexts(TemplateFormat.Docx, filled)); + } + + [Fact] + public void TypedPaths_ScopeErrorsStillApply() + { + TestDefinition definition = new TestDefinition(t => + { + TemplatePath d = t.DataAs(); + t.Content(c => + { + LoopItem? escaped = null; + c.ForEach(d.Items(o => o.Order.Lines), "line", (line, b) => escaped = line); + c.Paragraph(escaped!.Path(l => l.Description)); + }); + }); + + TemplateBuildException exception = Assert.Throws(() => BuilderHarness.Build(definition, TemplateFormat.Docx)); + + Assert.Equal("TB4001", Assert.Single(exception.Errors).Code); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/WalkingSkeletonTests.cs b/tests/TriasDev.Templify.Builder.Tests/WalkingSkeletonTests.cs new file mode 100644 index 00000000..5c4e2d5f --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/WalkingSkeletonTests.cs @@ -0,0 +1,175 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.IO.Compression; +using System.Text; +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; +using TriasDev.Templify.Tests.Odt; + +namespace TriasDev.Templify.Builder.Tests; + +public sealed class WalkingSkeletonTests +{ + private const string GreetingJson = """{ "customer": { "name": "Alice" } }"""; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static TestDefinition Greeting() => new TestDefinition(template => + { + TemplatePath customer = template.Data["customer"]; + template.Content(c => + { + c.Paragraph("Greeting"); + c.Paragraph(x => + { + x.Text("Hello "); + x.Value(customer["name"]); + x.Text("!"); + }); + c.Paragraph(customer["name"]); + }); + }); + + [Theory] + [MemberData(nameof(Formats))] + public void Build_ParagraphWithPlaceholder_IsFilledByTemplify(TemplateFormat format) + { + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Greeting(), format, GreetingJson); + + Assert.Equal(new[] { "Greeting", "Hello {{customer.name}}!", "{{customer.name}}" }, BuilderHarness.ParagraphTexts(format, template.Content.ToArray())); + Assert.Equal(new[] { "Greeting", "Hello Alice!", "Alice" }, BuilderHarness.ParagraphTexts(format, filled)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Build_DescribesTheFormat(TemplateFormat format) + { + GeneratedTemplate template = BuilderHarness.Build(Greeting(), format); + + Assert.Equal(format, template.Format); + Assert.Equal(format == TemplateFormat.Docx ? ".docx" : ".odt", template.FileExtension); + Assert.Equal( + format == TemplateFormat.Docx + ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + : "application/vnd.oasis.opendocument.text", + template.MediaType); + Assert.Equal(64, template.ContentHash.Length); + Assert.Equal(template.ContentHash, template.ContentHash.ToLowerInvariant()); + + using (Stream stream = template.OpenRead()) + { + Assert.False(stream.CanWrite); + Assert.True(stream.CanSeek); + } + + using MemoryStream copy = new MemoryStream(); + template.WriteTo(copy); + Assert.Equal(template.Content.ToArray(), copy.ToArray()); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Build_IsDeterministic_AcrossBuildsAndCultures(TemplateFormat format) + { + byte[] reference = BuilderHarness.Build(Greeting(), format).Content.ToArray(); + + foreach (string culture in new[] { "tr-TR", "ar-SA", "de-DE" }) + { + CultureInfo previous = CultureInfo.CurrentCulture; + CultureInfo previousUi = CultureInfo.CurrentUICulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(culture); + Assert.Equal(reference, BuilderHarness.Build(Greeting(), format).Content.ToArray()); + } + finally + { + CultureInfo.CurrentCulture = previous; + CultureInfo.CurrentUICulture = previousUi; + } + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void Build_EntriesHaveAFixedTimestamp(TemplateFormat format) + { + using MemoryStream stream = new MemoryStream(BuilderHarness.Build(Greeting(), format).Content.ToArray()); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + + Assert.All(archive.Entries, e => Assert.Equal(new DateTime(2000, 1, 1), e.LastWriteTime.DateTime)); + } + + [Fact] + public void Build_Odt_StoresTheMimetypeFirstAndUncompressed() + { + using MemoryStream stream = new MemoryStream(BuilderHarness.Build(Greeting(), TemplateFormat.Odt).Content.ToArray()); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + + ZipArchiveEntry first = archive.Entries[0]; + Assert.Equal("mimetype", first.FullName); + Assert.Equal(first.Length, first.CompressedLength); + } + + [Theory] + [InlineData(TemplateFormat.Docx, "de-DE")] + [InlineData(TemplateFormat.Odt, "de-DE")] + [InlineData(TemplateFormat.Odt, "en")] + public void Build_WritesTheDocumentLanguage(TemplateFormat format, string language) + { + GeneratedTemplate template = TemplateBuilder.Build(Greeting(), BuilderHarness.Options(format, language)); + + string part = format == TemplateFormat.Docx ? "docProps/core.xml" : "meta.xml"; + using MemoryStream stream = new MemoryStream(template.Content.ToArray()); + using ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read); + using StreamReader reader = new StreamReader(archive.GetEntry(part)!.Open(), Encoding.UTF8); + Assert.Contains($"{language}", reader.ReadToEnd(), StringComparison.Ordinal); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Build_LiteralWhitespace_RendersExactly(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(template => template.Content(c => + { + c.Paragraph(" two leading, two inner, one trailing "); + c.Paragraph("tab\there"); + c.Paragraph("line\nbreak and\r\nwindows"); + c.Paragraph(x => + { + x.Text("a "); + x.Text(" b"); + }); + c.Paragraph(string.Empty); + })); + + (GeneratedTemplate template, _) = BuilderHarness.BuildAndFill(definition, format, "{}"); + + Assert.Equal( + new[] { " two leading, two inner, one trailing ", "tab\there", "line\nbreak and\nwindows", "a b", string.Empty }, + BuilderHarness.ParagraphTexts(format, template.Content.ToArray())); + } + + [Theory] + [MemberData(nameof(Formats))] + [Trait("Category", "LibreOffice")] + public void LibreOffice_OpensBuiltAndFilledDocuments(TemplateFormat format) + { + LibreOfficeRunner.RequireExecutable(); + (GeneratedTemplate template, byte[] filled) = BuilderHarness.BuildAndFill(Greeting(), format, GreetingJson); + string extension = template.FileExtension.TrimStart('.'); + + Assert.Equal(new[] { "Greeting", "Hello {{customer.name}}!", "{{customer.name}}" }, ToText(template.Content.ToArray(), extension)); + Assert.Equal(new[] { "Greeting", "Hello Alice!", "Alice" }, ToText(filled, extension)); + Assert.NotEmpty(LibreOfficeRunner.Convert(filled, extension, "pdf", "pdf")); + } + + private static string[] ToText(byte[] document, string extension) + { + string text = Encoding.UTF8.GetString(LibreOfficeRunner.Convert(document, extension, "txt:Text (encoded):UTF8", "txt")); + return text.TrimStart('').Replace("\r\n", "\n", StringComparison.Ordinal).TrimEnd('\n').Split('\n'); + } +} diff --git a/tests/TriasDev.Templify.Builder.Tests/packages.lock.json b/tests/TriasDev.Templify.Builder.Tests/packages.lock.json new file mode 100644 index 00000000..eb754df7 --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/packages.lock.json @@ -0,0 +1,202 @@ +{ + "version": 2, + "dependencies": { + "net11.0": { + "coverlet.collector": { + "type": "Direct", + "requested": "[10.1.0, )", + "resolved": "10.1.0", + "contentHash": "SlYCIHnBYxINSUpR75SiM5JEmnx11pqT+Ac/C/fUqTTA0dLPl9eYzmFXKKuxmQhL3ZdTQl4PBD3YdAxAauaKLQ==" + }, + "Microsoft.CodeAnalysis.CSharp": { + "type": "Direct", + "requested": "[5.0.0, )", + "resolved": "5.0.0", + "contentHash": "5DSyJ9bk+ATuDy7fp2Zt0mJStDVKbBoiz1DyfAwSa+k4H4IwykAUcV3URelw5b8/iVbfSaOwkwmPUZH6opZKCw==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.11.0", + "Microsoft.CodeAnalysis.Common": "[5.0.0]" + } + }, + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "MdVkskM2ZCKSlNts5DIbz9MZidX7SwcXKBoBqY4XT91b30hAwC8PkjWbdGKRak6BKAD1BQqaZnh/SD0AJGoDCQ==", + "dependencies": { + "Microsoft.CodeCoverage": "18.12.0", + "Microsoft.TestPlatform.TestHost": "18.12.0" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[4.0.1, )", + "resolved": "4.0.1", + "contentHash": "8CoAaZkniVekR1ycJyxn+hOz+6ZQCDPcoIsIs6ujd4WyFcBMlxGNU15Qb8Uxd4iO4UmOuETb0M6vzBbwX/mfLA==" + }, + "xunit.v3.mtp-off": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "/2DllJSdr4mnMdnY5gN5ndxGdTGwTX6brIpmZv2PEV7D2N1PwwdSW4t+3ARD/5JwYXFBl1XV+8ozwSTyq2wbEg==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-off": "[4.0.3]" + } + }, + "DocumentFormat.OpenXml.Framework": { + "type": "Transitive", + "resolved": "3.5.1", + "contentHash": "U5txtc3ORno73xQx9Lf2gWzfaSZnZwKHfLkTAslhlew9lxe5XbUiCt0dY1fHeAf8yRqszUAe5i/+xLC9R/Xfsw==", + "dependencies": { + "System.IO.Packaging": "10.0.2" + } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.CodeAnalysis.Analyzers": { + "type": "Transitive", + "resolved": "3.11.0", + "contentHash": "v/EW3UE8/lbEYHoC2Qq7AR/DnmvpgdtAMndfQNmpuIMx/Mto8L5JnuCfdBYtgvalQOtfNCnxFejxuRrryvUTsg==" + }, + "Microsoft.CodeAnalysis.Common": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "ZXRAdvH6GiDeHRyd3q/km8Z44RoM6FBWHd+gen/la81mVnAdHTEsEkO5J0TCNXBymAcx5UYKt5TvgKBhaLJEow==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.11.0" + } + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "OhOPSaCAQhBJgXF1OrX0uK3eTkwZ1XnM44iGLZplYgKrmgKzQUdv9xtGGaE568RuQ738TlrTJ3pm9aWL5FH7iw==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "ilT2o4v/c1joLgsfzS4dYQ71bWAy/RsA6fBY7f5OEUpUsUhwIzoliGeXdS3yctWuy4NZyuSVlO7dPX4ed7R06A==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "18.12.0", + "contentHash": "WTT912JUqmFa2BkCeXPkMCUpbYOqsbeRfRJdhaIQROx49iokgnGPAlKvXmHWKC9nJwWrHwSQfR+k+Qn7NCxfzw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.12.0" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "System.IO.Packaging": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "JTpM4z0wpoIHHDvlCU27HsXo+zVnpWib94HXQpzzr+jc/P9NYf4w353AK4MXyGq/grm1mbLi7eXsOsDU8sGmNg==" + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-off": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "zzd3noMJ7I6DnoXMfNv/skWlJx873Cj7PrraA+JTVFtBnoy9yJwGd5f9ovP2jBQxVYfyHUdiWAlE3plvJghy8Q==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "triasdev.templify": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )" + } + }, + "triasdev.templify.builder": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify": "[1.10.0, )" + } + }, + "triasdev.templify.builder.generators": { + "type": "Project" + }, + "triasdev.templify.builder.sample": { + "type": "Project", + "dependencies": { + "TriasDev.Templify.Builder": "[0.1.0, )", + "TriasDev.Templify.Builder.Testing": "[0.1.0, )" + } + }, + "triasdev.templify.builder.testing": { + "type": "Project", + "dependencies": { + "DocumentFormat.OpenXml": "[3.5.1, )", + "TriasDev.Templify.Builder": "[0.1.0, )" + } + }, + "DocumentFormat.OpenXml": { + "type": "CentralTransitive", + "requested": "[3.5.1, )", + "resolved": "3.5.1", + "contentHash": "zxdOf5VVCe/uNklbRhj8dVBzQGj3DoqkUuqOp9cAZVuN8mNYDjof1lvSQA2OQNr8Ptc9d7pbA7Azq/ReaI3FpA==", + "dependencies": { + "DocumentFormat.OpenXml.Framework": "3.5.1" + } + } + } + } +} \ No newline at end of file