Repository navigation
feat(xuiper-ui): add DSL validation and HTML rendering tools - #486
Conversation
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.
WalkthroughThis 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
|
augment review |
There was a problem hiding this comment.
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:
parseContentBlockduplicates the logic ofparseChildren. 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
$namedirectly into HTML without escaping. For defensive coding, consider escaping HTML special characters:private fun String.escapeHtml() = this .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace("\"", """)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
📒 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 viaparseContentBlock- 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
*.htmlto 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
NanoUIRenderertoComposeNanoRendereraligns with the renderer renaming in ComposeNanoRenderer.kt. The functionality remains unchanged.xuiper-ui/build.gradle.kts (1)
110-120: LGTM!The
renderHtmltask 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
NanoUIRenderertoComposeNanoRendererbetter reflects the Compose-specific implementation and improves code clarity.
40-41: LGTM!The addition of
ConditionalandForLooprendering support extends the renderer's capabilities to handle these DSL constructs.
209-229: LGTM!The
RenderConditionalandRenderForLoopimplementations 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
printASTTreefunction 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
There was a problem hiding this comment.
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
IndentParserto handle empty property values and parsecontent:blocks with nested children correctly - Added
DslValidatortool for validating NanoDSL files with detailed AST output - Added
DslToHtmlRenderertool for rendering NanoDSL files to HTML with an index gallery - Renamed
NanoUIRenderertoComposeNanoRendererfor clarity and added rendering support forConditionalandForLoopnodes
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
RenderConditionalandRenderForLoopfunctions 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.
| // Skip empty property values | ||
| if (propValue.isEmpty()) { |
There was a problem hiding this comment.
[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.
| // 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()}'") |
| println("${indent}Card [${node.children.size} children]") | ||
| node.children.forEach { printASTTree(it, "$indent ") } | ||
| } | ||
| is NanoNode.Text -> println("${indent}Text(\"${node.content.take(30)}...\")") |
There was a problem hiding this comment.
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\")")| 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\")") | |
| } |
| fileNames.forEach { name -> | ||
| append(""" | ||
| <div class="card"> | ||
| <h3>$name</h3> | ||
| <a href="$name.html" target="_blank">View Preview →</a> | ||
| </div> | ||
| """.trimIndent()) |
There was a problem hiding this comment.
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("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
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.
| 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 | ||
| } |
There was a problem hiding this comment.
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).
| 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 |
There was a problem hiding this comment.
Code duplication: The parseContentBlock method (lines 373-397) has identical logic to the parseChildren method (lines 336-359). Both methods:
- Get the indent of the startIndex line
- Iterate through subsequent lines
- Skip blank lines
- Break when encountering a line with indent <= baseIndent
- 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.
| 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) |
Summary
Add tools for validating and rendering NanoDSL files, and fix parser issues with the
content:block syntax.Changes
New Files
Bug Fixes
IndentParserto properly handlecontent:block syntaxPROP_REGEXto match empty property values (e.g.,content:without inline value)parseContentBlockmethod for correct nested children parsingGradle Tasks
./gradlew :xuiper-ui:validateDsl- Validate DSL files./gradlew :xuiper-ui:validateDsl -Pverbose=true- With AST tree output./gradlew :xuiper-ui:renderHtml- Render to HTMLProblem Solved
Previously, the parser failed to parse
content:blocks correctly:This resulted in
Card [0 children]in the AST. Now it correctly producesCard [1 children]with the VStack and its children.Testing
Summary by CodeRabbit
Release Notes
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.