Skip to content

feat(xuiper-ui): add DSL validation and HTML rendering tools - #486

Merged
phodal merged 3 commits into
masterfrom
feat/xuiper-dsl-validation-tools
Dec 6, 2025
Merged

phodal merged 3 commits into
masterfrom
feat/xuiper-dsl-validation-tools

Conversation

@phodal

@phodal phodal commented Dec 6, 2025 •

Copy link
Copy Markdown
Owner

Summary

Add tools for validating and rendering NanoDSL files, and fix parser issues with the content: block syntax.

Changes

New Files

  • DslValidator.kt: Validates NanoDSL files with detailed AST tree output
  • DslToHtmlRenderer.kt: Renders DSL files to HTML with an index gallery

Bug Fixes

  • Fix IndentParser to properly handle content: block syntax
  • Fix PROP_REGEX to match empty property values (e.g., content: without inline value)
  • Add parseContentBlock method for correct nested children parsing

Gradle Tasks

  • ./gradlew :xuiper-ui:validateDsl - Validate DSL files
  • ./gradlew :xuiper-ui:validateDsl -Pverbose=true - With AST tree output
  • ./gradlew :xuiper-ui:renderHtml - Render to HTML

Problem Solved

Previously, the parser failed to parse content: blocks correctly:

Card:
    padding: "lg"
    content:
        VStack(spacing="md"):
            Text("Hello")

This resulted in Card [0 children] in the AST. Now it correctly produces Card [1 children] with the VStack and its children.

Testing

./gradlew :xuiper-ui:validateDsl -Pverbose=true
./gradlew :xuiper-ui:renderHtml

Summary by CodeRabbit

Release Notes

  • New Features

    • Added DSL validation task to check .nanodsl file syntax and generate reports
    • Added HTML rendering capability for .nanodsl files with automatic index gallery generation
  • Improvements

    • Enhanced support for conditional and loop rendering in UI components
    • Improved content block parsing in DSL parser for better handling of nested structures

✏️ Tip: You can customize this high-level summary in your review settings.

Implement composable functions to render Conditional and ForLoop IR nodes in the NanoUI renderer.
- Add DslValidator.kt for validating NanoDSL files with AST tree output
- Add DslToHtmlRenderer.kt for rendering DSL files to HTML with gallery
- Fix IndentParser to properly handle 'content:' block syntax
- Fix PROP_REGEX to match empty property values
- Add validateDsl and renderHtml Gradle tasks

The parser now correctly parses Card and other components that use
the 'content:' block syntax for nested children, which is commonly
generated by LLMs.
Renamed the renderer object for clarity and consistency with Compose UI naming conventions.
Copilot AI review requested due to automatic review settings December 6, 2025 13:50
@coderabbitai

coderabbitai Bot commented Dec 6, 2025 •

Copy link
Copy Markdown

Walkthrough

This pull request introduces rendering infrastructure updates and command-line tools for NanoDSL processing. It renames the Nano renderer object, adds conditional and loop rendering handlers, creates DSL validation and HTML rendering utilities with file I/O and error handling, enhances the parser to support inline and block-style content properties, and adds Gradle tasks and gitignore rules for build automation.

Changes

Cohort / File(s) Summary
Rendering Infrastructure
mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/ComposeNanoRenderer.kt, mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/NanoDSLDemo.kt
Renamed public object from NanoUIRenderer to ComposeNanoRenderer; added private composable functions RenderConditional and RenderForLoop to handle conditional and loop component types; updated demo to use new renderer.
Build Configuration
xuiper-ui/build.gradle.kts
Added two new Gradle JavaExec tasks: validateDsl (runs DSL validation with directory and verbose flag options) and renderHtml (renders NanoDSL files to HTML with input/output directory arguments).
DSL Processing Utilities
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslValidator.kt, xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslToHtmlRenderer.kt
New command-line utilities: DslValidator parses NanoDSL files, converts to IR, computes AST/IR statistics, and reports results with error aggregation; DslToHtmlRenderer renders NanoDSL files to HTML with per-file output and index.html gallery generation.
Parser Enhancement
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/parser/IndentParser.kt
Modified content property parsing to conditionally treat content as inline value (stored in props) or parse dedicated indented content block via new parseContentBlock helper; updated PROP_REGEX to accept empty inline values.
Configuration
xuiper-ui/testcases/.gitignore
Added \*.html ignore pattern for HTML files in testcases/actual directory.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • DslValidator.kt & DslToHtmlRenderer.kt: New utilities with file I/O, parsing pipelines, error handling, and gallery generation logic requiring careful verification of correctness and edge case handling.
  • IndentParser.kt: Parser logic modifications for content property handling; verify conditional logic between inline vs. block parsing and index tracking correctness.
  • Heterogeneous changes: Mix of renaming, new utilities, build configuration, and parser logic requires separate reasoning per file.

Poem

🐰 A renderer reborn, composable and bright,
New tools to validate and render just right,
Content blocks flow both inline and deep,
HTML galleries for files to keep—
The parser now dances where logic does creep! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.56% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main changes: adding DSL validation and HTML rendering tools. It directly reflects the primary features introduced in the PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/xuiper-dsl-validation-tools

Comment @coderabbitai help to get the list of available commands and usage tips.

@phodal

phodal commented Dec 6, 2025

Copy link
Copy Markdown
Owner Author

augment review

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review completed. No suggestions at this time.

Comment augment review to trigger a new review at any time.

@phodal
phodal merged commit bbb930c into master Dec 6, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/parser/IndentParser.kt (1)

361-397: Well-documented method that correctly parses content blocks.

The implementation properly handles the indentation-based hierarchy for content blocks. The logic mirrors parseChildren (lines 336-359) but with clearer naming and documentation for this specific use case.

Optional consideration: parseContentBlock duplicates the logic of parseChildren. While the current approach provides clarity through naming and documentation, you could consolidate these methods if desired:

private fun parseChildren(lines: List<String>, startIndex: Int): Pair<List<NanoNode>, Int> {
    return parseChildrenFromIndent(lines, startIndex)
}

private fun parseContentBlock(lines: List<String>, startIndex: Int): Pair<List<NanoNode>, Int> {
    return parseChildrenFromIndent(lines, startIndex)
}

private fun parseChildrenFromIndent(lines: List<String>, startIndex: Int): Pair<List<NanoNode>, Int> {
    // ... existing logic ...
}

However, the current implementation is perfectly acceptable and arguably more readable.

xuiper-ui/build.gradle.kts (1)

98-108: Consider a clearer verbose flag pattern.

The current approach passes an empty string when verbose is false, which works but isn't immediately clear. Consider building the args list conditionally:

-    val dslDir = project.findProperty("dslDir") as? String ?: "testcases/actual/integration"
-    val verbose = if (project.hasProperty("verbose")) "verbose" else ""
-    args = listOf(dslDir, verbose)
+    val dslDir = project.findProperty("dslDir") as? String ?: "testcases/actual/integration"
+    args = if (project.hasProperty("verbose")) {
+        listOf(dslDir, "verbose")
+    } else {
+        listOf(dslDir)
+    }

This makes the intent clearer and avoids passing empty strings as placeholder arguments.

xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslToHtmlRenderer.kt (1)

95-161: Consider HTML-escaping filenames for robustness.

While the risk is very low (filenames are from the local filesystem), line 146 embeds $name directly into HTML without escaping. For defensive coding, consider escaping HTML special characters:

private fun String.escapeHtml() = this
    .replace("&", "&amp;")
    .replace("<", "&lt;")
    .replace(">", "&gt;")
    .replace("\"", "&quot;")

Then use ${name.escapeHtml()} in the HTML template. This prevents potential issues if filenames somehow contain special characters.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9479e4b and 76f26e5.

📒 Files selected for processing (7)
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/ComposeNanoRenderer.kt (3 hunks)
  • mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/NanoDSLDemo.kt (1 hunks)
  • xuiper-ui/build.gradle.kts (1 hunks)
  • xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslToHtmlRenderer.kt (1 hunks)
  • xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslValidator.kt (1 hunks)
  • xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/parser/IndentParser.kt (3 hunks)
  • xuiper-ui/testcases/.gitignore (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Agent
  • GitHub Check: Test mpp-core (KMP)
  • GitHub Check: Build
🔇 Additional comments (13)
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/parser/IndentParser.kt (2)

42-42: LGTM! Regex change enables empty property values.

The change from .+ to .* correctly allows the regex to match properties with empty inline values (e.g., content:), which is essential for the block-style content parsing feature. Empty values are appropriately handled downstream at lines 312-316.


293-316: Correct implementation of content block parsing.

The logic correctly handles both inline and block-style content:

  • Empty content: lines trigger block parsing via parseContentBlock
  • Inline values (e.g., content: "text") are stored as properties
  • The continue statement at line 309 properly prevents fall-through
  • Index management is handled correctly in both branches
xuiper-ui/testcases/.gitignore (1)

4-4: LGTM!

The addition of *.html to gitignore is appropriate given the new HTML rendering functionality. This prevents generated HTML files from being committed to the repository.

mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/NanoDSLDemo.kt (1)

259-259: LGTM!

The update from NanoUIRenderer to ComposeNanoRenderer aligns with the renderer renaming in ComposeNanoRenderer.kt. The functionality remains unchanged.

xuiper-ui/build.gradle.kts (1)

110-120: LGTM!

The renderHtml task is well-structured with sensible defaults and clear argument passing. The default directories align well with the validation task.

mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/ComposeNanoRenderer.kt (3)

24-24: LGTM!

The rename from NanoUIRenderer to ComposeNanoRenderer better reflects the Compose-specific implementation and improves code clarity.


40-41: LGTM!

The addition of Conditional and ForLoop rendering support extends the renderer's capabilities to handle these DSL constructs.


209-229: LGTM!

The RenderConditional and RenderForLoop implementations are appropriate for static preview purposes. The comments clearly explain that these show all children for preview rather than implementing runtime conditional/loop logic.

xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslToHtmlRenderer.kt (2)

14-43: LGTM!

The setup and validation logic is robust:

  • Clear default arguments
  • Proper directory validation with early returns
  • Automatic output directory creation
  • Informative error messages and progress output

44-77: LGTM!

The rendering loop has appropriate error handling:

  • Try-catch around IR conversion and rendering
  • Proper ParseResult pattern matching
  • Clear per-file progress output with success/failure tracking
  • Detailed error messages for debugging
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslValidator.kt (3)

15-92: LGTM!

The validation logic is comprehensive and well-structured:

  • Proper directory validation with early returns
  • Two-phase validation: parse success and IR conversion success
  • Detailed error tracking and reporting
  • Optional verbose mode for AST inspection
  • Clear summary output with per-file results

94-150: LGTM!

The AST traversal and printing utilities are well-implemented:

  • Recursive traversal correctly handles all major node types
  • The printASTTree function provides clear hierarchical output with indentation
  • Fallback cases handle unknown node types gracefully

152-169: LGTM!

The IR statistics utilities are clean and effective:

  • Simple data class for returning structured statistics
  • Recursive traversal correctly handles the IR tree structure
  • Proper null-safety with children?.forEach

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds DSL validation and HTML rendering tools for NanoDSL files, and fixes a critical parser bug that prevented proper parsing of the content: block syntax. The changes enable developers to validate NanoDSL files and render them to HTML for preview purposes.

Key Changes:

  • Fixed IndentParser to handle empty property values and parse content: blocks with nested children correctly
  • Added DslValidator tool for validating NanoDSL files with detailed AST output
  • Added DslToHtmlRenderer tool for rendering NanoDSL files to HTML with an index gallery
  • Renamed NanoUIRenderer to ComposeNanoRenderer for clarity and added rendering support for Conditional and ForLoop nodes

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
xuiper-ui/testcases/.gitignore Added *.html pattern to ignore generated HTML files
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/parser/IndentParser.kt Fixed PROP_REGEX to match empty values; added special handling for content: block with parseContentBlock method
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslValidator.kt New validation tool that parses DSL files, validates them, and optionally prints AST trees
xuiper-ui/src/main/kotlin/cc/unitmesh/xuiper/eval/DslToHtmlRenderer.kt New HTML rendering tool that converts DSL files to HTML and generates an index gallery
xuiper-ui/build.gradle.kts Added validateDsl and renderHtml Gradle tasks for running the new tools
mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/NanoDSLDemo.kt Updated reference from NanoUIRenderer to ComposeNanoRenderer
mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/ComposeNanoRenderer.kt Renamed object from NanoUIRenderer to ComposeNanoRenderer; added RenderConditional and RenderForLoop methods
Comments suppressed due to low confidence (1)

mpp-ui/src/jvmMain/kotlin/cc/unitmesh/devins/ui/nano/ComposeNanoRenderer.kt:229

  • [nitpick] The RenderConditional and RenderForLoop functions provide a reasonable preview behavior by rendering children directly. However, the comments could be more specific about the implications.

For RenderConditional: Consider noting that only the "then" branch is shown in preview, and the condition itself is not displayed.

For RenderForLoop: Consider noting that only one iteration is shown, and the loop variable values are not available in the preview context.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +312 to +313
// Skip empty property values
if (propValue.isEmpty()) {

Copilot AI Dec 6, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The logic for handling empty property values appears after the special handling of the content: property. However, this could cause issues with other properties that might intentionally have empty values but are not special cases like content:.

Consider whether this is the intended behavior: should all properties with empty values be silently skipped, or should this only apply to specific properties? If properties with empty values are invalid, consider logging a warning or error instead of silently skipping them.

Suggested change
// Skip empty property values
if (propValue.isEmpty()) {
// Warn and skip empty property values (except for "content")
if (propValue.isEmpty()) {
println("Warning: Property '$propName' has an empty value and will be skipped at line ${index + 1}: '${line.trim()}'")

Copilot uses AI. Check for mistakes.
println("${indent}Card [${node.children.size} children]")
node.children.forEach { printASTTree(it, "$indent ") }
}
is NanoNode.Text -> println("${indent}Text(\"${node.content.take(30)}...\")")

Copilot AI Dec 6, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The take(30) call on node.content will always append "..." even if the content is shorter than 30 characters. This could result in misleading output like Text("Hello...") for short content.

Consider using a conditional append:

val displayContent = if (node.content.length > 30) node.content.take(30) + "..." else node.content
println("${indent}Text(\"$displayContent\")")
Suggested change
is NanoNode.Text -> println("${indent}Text(\"${node.content.take(30)}...\")")
is NanoNode.Text -> {
val displayContent = if (node.content.length > 30) node.content.take(30) + "..." else node.content
println("${indent}Text(\"$displayContent\")")
}

Copilot uses AI. Check for mistakes.
Comment on lines +143 to +149
fileNames.forEach { name ->
append("""
<div class="card">
<h3>$name</h3>
<a href="$name.html" target="_blank">View Preview →</a>
</div>
""".trimIndent())

Copilot AI Dec 6, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potential XSS vulnerability: File names are inserted directly into the HTML without proper HTML escaping on lines 146 and 147. If a file name contains special HTML characters like <, >, &, or quotes, it could break the HTML structure or potentially execute malicious code.

Consider using HTML escaping for the name variable:

val escapedName = name
    .replace("&", "&amp;")
    .replace("<", "&lt;")
    .replace(">", "&gt;")
    .replace("\"", "&quot;")
append("""
        <div class="card">
            <h3>$escapedName</h3>
            <a href="$name.html" target="_blank">View Preview →</a>
        </div>
""".trimIndent())

Note: The href attribute should also be properly URL-encoded if file names can contain special characters.

Copilot uses AI. Check for mistakes.
Comment on lines 298 to +310
if (propName == "content") {
val (contentChildren, newIndex) = parseChildren(lines, index)
children.addAll(contentChildren)
index = newIndex
// If content is empty or just whitespace, parse children from content block
if (propValue.isEmpty() || propValue.isBlank()) {
val (contentChildren, newIndex) = parseContentBlock(lines, index)
children.addAll(contentChildren)
index = newIndex
} else {
// Content has an inline value, treat as property
props[propName] = propValue.removeSurrounding("\"")
index++
}
continue
}

Copilot AI Dec 6, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing test coverage for the content: block parsing fix. The PR description specifically mentions fixing the parser to handle this pattern:

Card:
    padding: "lg"
    content:
        VStack(spacing="md"):
            Text("Hello")

Consider adding a test case in NanoDSLParserTest.kt to verify that the content: block is correctly parsed and that the Card node has the expected number of children (previously 0, now should be 1).

Copilot uses AI. Check for mistakes.
Comment on lines +374 to +396
val contentLineIndent = getIndent(lines[startIndex])
var index = startIndex + 1
val children = mutableListOf<NanoNode>()

while (index < lines.size) {
val line = lines[index]
if (line.isBlank()) {
index++
continue
}

val currentIndent = getIndent(line)
// Content block ends when we encounter a line with same or less indent than "content:" line
if (currentIndent <= contentLineIndent) break

val (node, newIndex) = parseNode(lines, index, currentIndent)
if (node != null) {
children.add(node)
}
index = newIndex
}

return children to index

Copilot AI Dec 6, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code duplication: The parseContentBlock method (lines 373-397) has identical logic to the parseChildren method (lines 336-359). Both methods:

  1. Get the indent of the startIndex line
  2. Iterate through subsequent lines
  3. Skip blank lines
  4. Break when encountering a line with indent <= baseIndent
  5. Parse nodes and add them to children

Consider refactoring to eliminate this duplication. Since they have the same behavior, you could simply call parseChildren(lines, index) instead of parseContentBlock(lines, index) on line 301, or rename parseChildren to something more generic if the current name is misleading.

Suggested change
val contentLineIndent = getIndent(lines[startIndex])
var index = startIndex + 1
val children = mutableListOf<NanoNode>()
while (index < lines.size) {
val line = lines[index]
if (line.isBlank()) {
index++
continue
}
val currentIndent = getIndent(line)
// Content block ends when we encounter a line with same or less indent than "content:" line
if (currentIndent <= contentLineIndent) break
val (node, newIndex) = parseNode(lines, index, currentIndent)
if (node != null) {
children.add(node)
}
index = newIndex
}
return children to index
// Delegates to parseChildren since logic is identical
return parseChildren(lines, startIndex)

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants