From f48586033dcba9ab94f06575aa4b215778f98fc1 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Fri, 26 Dec 2025 15:07:48 -0800 Subject: [PATCH] feat(docgen): improve mdx output with linked defaults and markdown support - Add default value linking: when a default value refers to an enum variant, it now links to the type definition (e.g., "Monitor" links to CrossBoundaryBehaviour type) - Make mdx_escape code-block aware: braces inside fenced code blocks (```) and inline code (`) are no longer escaped, preserving proper JSON code block rendering in descriptions - Use raw markdown descriptions in MDX templates instead of converting to HTML then stripping tags, which was destroying code blocks - Skip redundant type badge for documented const variants in MDX output --- Cargo.lock | 20 +-- flake.nix | 1 + src/mdx_generator.rs | 123 +++++++++++++++- src/prepare.rs | 281 ++++++++++++++++++++++++++++++++++++ src/templates/macros.html | 4 +- src/templates/mdx_macros.md | 21 ++- 6 files changed, 429 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 52f9eba7..c64f7e94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,9 +182,9 @@ checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" [[package]] name = "cc" -version = "1.2.50" +version = "1.2.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f50d563227a1c37cc0a263f64eca3334388c01c5e4c4861a9def205c614383c" +checksum = "7a0aeaff4ff1a90589618835a598e545176939b97874f7abc7851caa0618f203" dependencies = [ "find-msvc-tools", "shlex", @@ -476,9 +476,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" +checksum = "645cbb3a84e60b7531617d5ae4e57f7e27308f6445f5abf653209ea76dec8dff" [[package]] name = "funty" @@ -1201,9 +1201,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9558e172d4e8533736ba97870c4b2cd63f84b382a3d6eb063da41b91cce17289" +checksum = "54e910108742c57a770f492731f99be216a52fadd361b06c8fb59d74ccc267d2" dependencies = [ "dyn-clone", "ref-cast", @@ -1232,9 +1232,9 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "301858a4023d78debd2353c7426dc486001bddc91ae31a76fb1f55132f7e2633" +checksum = "4908ad288c5035a8eb12cfdf0d49270def0a268ee162b75eeee0f85d155a7c45" dependencies = [ "proc-macro2", "quote", @@ -1739,6 +1739,6 @@ dependencies = [ [[package]] name = "zmij" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dccf46b25b205e4bebe1d5258a991df1cc17801017a845cb5b3fe0269781aa" +checksum = "d0095ecd462946aa3927d9297b63ef82fb9a5316d7a37d134eeb36e58228615a" diff --git a/flake.nix b/flake.nix index 0dadc72a..15efe8c1 100644 --- a/flake.nix +++ b/flake.nix @@ -68,6 +68,7 @@ (craneLib.filterCargoSources path type) || (builtins.match ".*\\.css$" path != null) || (builtins.match ".*\\.html$" path != null) + || (builtins.match ".*\\.md$" path != null) || (builtins.match ".*\\.json$" path != null); }; diff --git a/src/mdx_generator.rs b/src/mdx_generator.rs index 62af68dd..6eadc807 100644 --- a/src/mdx_generator.rs +++ b/src/mdx_generator.rs @@ -18,16 +18,82 @@ use tera::Tera; /// MDX interprets `{` and `}` as JSX expressions. This filter escapes them /// so they render as literal text, which is necessary for descriptions /// containing JSON code blocks. +/// +/// This filter is code-block aware: it will NOT escape braces inside fenced +/// code blocks (```) or inline code (`), preserving proper code formatting. fn mdx_escape(value: &Value, _args: &HashMap) -> tera::Result { match value { Value::String(s) => { - let escaped = s.replace('{', "\\{").replace('}', "\\}"); + let escaped = escape_braces_outside_code(s); Ok(Value::String(escaped)) } _ => Ok(value.clone()), } } +/// Escape `{` and `}` characters outside of code blocks and inline code. +/// +/// This preserves code block content while escaping braces in regular text +/// that would otherwise be interpreted as JSX expressions by MDX. +fn escape_braces_outside_code(text: &str) -> String { + let mut result = String::with_capacity(text.len()); + let chars: Vec = text.chars().collect(); + let len = chars.len(); + let mut i = 0; + + // Track whether we're inside a fenced code block + let mut in_fenced_block = false; + + while i < len { + // Check for fenced code block start/end (```) + if i + 2 < len && chars[i] == '`' && chars[i + 1] == '`' && chars[i + 2] == '`' { + // Toggle fenced block state + in_fenced_block = !in_fenced_block; + result.push('`'); + result.push('`'); + result.push('`'); + i += 3; + continue; + } + + // If we're in a fenced code block, pass through everything + if in_fenced_block { + result.push(chars[i]); + i += 1; + continue; + } + + // Check for inline code (single backtick, not part of ```) + if chars[i] == '`' { + result.push('`'); + i += 1; + // Find closing backtick and pass through content + while i < len && chars[i] != '`' { + result.push(chars[i]); + i += 1; + } + // Push closing backtick if found + if i < len { + result.push('`'); + i += 1; + } + continue; + } + + // Outside of any code: escape braces + if chars[i] == '{' { + result.push_str("\\{"); + } else if chars[i] == '}' { + result.push_str("\\}"); + } else { + result.push(chars[i]); + } + i += 1; + } + + result +} + /// MDX documentation generator for Astro Starlight pub struct MdxGenerator { tera: Tera, @@ -803,4 +869,59 @@ mod tests { "Should detect string enum pattern" ); } + + #[test] + fn test_escape_braces_outside_code_plain_text() { + // Plain text should have braces escaped + let result = escape_braces_outside_code("Use {foo} and {bar}"); + assert_eq!(result, "Use \\{foo\\} and \\{bar\\}"); + } + + #[test] + fn test_escape_braces_outside_code_inline_code() { + // Braces inside inline code should NOT be escaped + let result = escape_braces_outside_code("Use `{foo}` in your code"); + assert_eq!(result, "Use `{foo}` in your code"); + } + + #[test] + fn test_escape_braces_outside_code_fenced_block() { + // Braces inside fenced code blocks should NOT be escaped + let input = "Example:\n```json\n{\"key\": \"value\"}\n```\nEnd"; + let result = escape_braces_outside_code(input); + assert_eq!(result, "Example:\n```json\n{\"key\": \"value\"}\n```\nEnd"); + } + + #[test] + fn test_escape_braces_outside_code_mixed() { + // Mix of plain text and code - only plain text braces escaped + let input = "Set `{option}` to {value}"; + let result = escape_braces_outside_code(input); + assert_eq!(result, "Set `{option}` to \\{value\\}"); + } + + #[test] + fn test_escape_braces_outside_code_multiple_code_blocks() { + // Multiple fenced code blocks + let input = "First:\n```\n{a}\n```\nMiddle {b}\n```\n{c}\n```\nEnd"; + let result = escape_braces_outside_code(input); + assert_eq!( + result, + "First:\n```\n{a}\n```\nMiddle \\{b\\}\n```\n{c}\n```\nEnd" + ); + } + + #[test] + fn test_escape_braces_outside_code_no_braces() { + // No braces should pass through unchanged + let result = escape_braces_outside_code("Just plain text"); + assert_eq!(result, "Just plain text"); + } + + #[test] + fn test_escape_braces_outside_code_nested_inline() { + // Multiple inline code segments + let result = escape_braces_outside_code("`{a}` and `{b}` with {c}"); + assert_eq!(result, "`{a}` and `{b}` with \\{c\\}"); + } } diff --git a/src/prepare.rs b/src/prepare.rs index 3d1905f8..9bbbefaf 100644 --- a/src/prepare.rs +++ b/src/prepare.rs @@ -27,6 +27,7 @@ pub fn prepare_for_template(value: &Value) -> Value { normalize_refs(&mut prepared, &root_schema); detect_wrapper_types(&mut prepared); add_wrapper_display_names(&mut prepared); + annotate_defaults_with_refs(&mut prepared); prepared } @@ -57,6 +58,90 @@ fn add_wrapper_display_names(schema: &mut Value) { } } +/// Annotate default values with type references for linking +/// +/// When a property has a `default` value and references a type via `$ref` (directly or +/// through `anyOf`/`oneOf` for Option patterns), this adds a `_default_ref` field +/// with the referenced type name. This allows templates to render defaults as links +/// to the type definition. +/// +/// For example, if a property has: +/// - `"anyOf": [{"$ref": "#/$defs/MoveBehaviour"}, {"type": "null"}]` +/// - `"default": "Swap"` +/// +/// This adds `"_default_ref": "MoveBehaviour"` so the template can render: +/// `Default: [Swap](#movebehaviour)` +fn annotate_defaults_with_refs(schema: &mut Value) { + annotate_defaults_recursive(schema); +} + +fn annotate_defaults_recursive(value: &mut Value) { + match value { + Value::Object(map) => { + // Check if this object has a default value + if map.contains_key("default") { + // Try to find a $ref to a type definition + if let Some(ref_name) = extract_type_ref(map) { + map.insert("_default_ref".to_string(), Value::String(ref_name)); + } + } + + // Recurse into all nested values + for v in map.values_mut() { + annotate_defaults_recursive(v); + } + } + Value::Array(arr) => { + for v in arr.iter_mut() { + annotate_defaults_recursive(v); + } + } + _ => {} + } +} + +/// Extract the type name from a $ref, handling various patterns: +/// - Direct `$ref`: `{"$ref": "#/$defs/TypeName"}` +/// - Option via anyOf: `{"anyOf": [{"$ref": "#/$defs/TypeName"}, {"type": "null"}]}` +/// - Option via oneOf: `{"oneOf": [{"$ref": "#/$defs/TypeName"}, {"type": "null"}]}` +fn extract_type_ref(map: &Map) -> Option { + // Check for direct $ref + if let Some(ref_value) = map.get("$ref") + && let Some(ref_str) = ref_value.as_str() + && let Some(type_name) = ref_str.strip_prefix("#/$defs/") + { + return Some(type_name.to_string()); + } + + // Check for anyOf/oneOf Option pattern + for key in ["anyOf", "oneOf"] { + if let Some(variants) = map.get(key).and_then(|v| v.as_array()) { + // Look for the pattern: exactly 2 variants, one null and one $ref + if variants.len() == 2 { + let null_count = variants + .iter() + .filter(|v| v.get("type").and_then(|t| t.as_str()) == Some("null")) + .count(); + + if null_count == 1 { + // Find the non-null variant with a $ref + for variant in variants { + if variant.get("type").and_then(|t| t.as_str()) != Some("null") { + if let Some(ref_str) = variant.get("$ref").and_then(|v| v.as_str()) + && let Some(type_name) = ref_str.strip_prefix("#/$defs/") + { + return Some(type_name.to_string()); + } + } + } + } + } + } + } + + None +} + /// Embed usages directly into each $defs entry /// /// This avoids Tera template lookup issues with special characters in def names @@ -2449,4 +2534,200 @@ mod tests { "PerAnimationPrefixConfig3 should have digits stripped" ); } + + #[test] + fn test_default_with_direct_ref_gets_annotated() { + // When a property has a default and a direct $ref, it should get _default_ref + let schema = json!({ + "title": "Test", + "type": "object", + "$defs": { + "Layout": { + "type": "string", + "enum": ["horizontal", "vertical"] + } + }, + "properties": { + "layout": { + "$ref": "#/$defs/Layout", + "default": "horizontal" + } + } + }); + + let prepared = prepare_for_template(&schema); + let props = prepared.get("properties").unwrap().as_object().unwrap(); + let layout_prop = props.get("layout").unwrap(); + + assert_eq!( + layout_prop.get("_default_ref"), + Some(&json!("Layout")), + "Direct $ref with default should have _default_ref" + ); + } + + #[test] + fn test_default_with_anyof_option_pattern_gets_annotated() { + // When a property has a default and anyOf Option pattern, it should get _default_ref + let schema = json!({ + "title": "Test", + "type": "object", + "$defs": { + "MoveBehaviour": { + "oneOf": [ + { "type": "string", "const": "Swap" }, + { "type": "string", "const": "Insert" } + ] + } + }, + "properties": { + "move_behaviour": { + "anyOf": [ + { "$ref": "#/$defs/MoveBehaviour" }, + { "type": "null" } + ], + "default": "Swap" + } + } + }); + + let prepared = prepare_for_template(&schema); + let props = prepared.get("properties").unwrap().as_object().unwrap(); + let move_prop = props.get("move_behaviour").unwrap(); + + assert_eq!( + move_prop.get("_default_ref"), + Some(&json!("MoveBehaviour")), + "anyOf Option pattern with default should have _default_ref" + ); + } + + #[test] + fn test_default_with_oneof_option_pattern_gets_annotated() { + // When a property has a default and oneOf Option pattern, it should get _default_ref + let schema = json!({ + "title": "Test", + "type": "object", + "$defs": { + "BorderStyle": { + "type": "string", + "enum": ["solid", "dashed"] + } + }, + "properties": { + "border_style": { + "oneOf": [ + { "$ref": "#/$defs/BorderStyle" }, + { "type": "null" } + ], + "default": "solid" + } + } + }); + + let prepared = prepare_for_template(&schema); + let props = prepared.get("properties").unwrap().as_object().unwrap(); + let border_prop = props.get("border_style").unwrap(); + + assert_eq!( + border_prop.get("_default_ref"), + Some(&json!("BorderStyle")), + "oneOf Option pattern with default should have _default_ref" + ); + } + + #[test] + fn test_primitive_default_not_annotated() { + // Primitive defaults (boolean, integer, etc.) should NOT get _default_ref + let schema = json!({ + "title": "Test", + "type": "object", + "properties": { + "enabled": { + "type": ["boolean", "null"], + "default": true + }, + "count": { + "type": ["integer", "null"], + "default": 10 + } + } + }); + + let prepared = prepare_for_template(&schema); + let props = prepared.get("properties").unwrap().as_object().unwrap(); + + assert!( + props.get("enabled").unwrap().get("_default_ref").is_none(), + "Boolean default should not have _default_ref" + ); + assert!( + props.get("count").unwrap().get("_default_ref").is_none(), + "Integer default should not have _default_ref" + ); + } + + #[test] + fn test_default_without_ref_not_annotated() { + // Defaults on types without $ref should NOT get _default_ref + let schema = json!({ + "title": "Test", + "type": "object", + "properties": { + "name": { + "type": "string", + "default": "untitled" + } + } + }); + + let prepared = prepare_for_template(&schema); + let props = prepared.get("properties").unwrap().as_object().unwrap(); + + assert!( + props.get("name").unwrap().get("_default_ref").is_none(), + "String type without $ref should not have _default_ref" + ); + } + + #[test] + fn test_nested_defaults_annotated() { + // Defaults inside nested structures should also be annotated + let schema = json!({ + "title": "Test", + "type": "object", + "$defs": { + "AnimationStyle": { + "type": "string", + "enum": ["Linear", "EaseIn", "EaseOut"] + }, + "AnimationConfig": { + "type": "object", + "properties": { + "style": { + "anyOf": [ + { "$ref": "#/$defs/AnimationStyle" }, + { "type": "null" } + ], + "default": "Linear" + } + } + } + }, + "properties": { + "animation": { "$ref": "#/$defs/AnimationConfig" } + } + }); + + let prepared = prepare_for_template(&schema); + let defs = prepared.get("$defs").unwrap().as_object().unwrap(); + let anim_config = defs.get("AnimationConfig").unwrap(); + let style_prop = anim_config.get("properties").unwrap().get("style").unwrap(); + + assert_eq!( + style_prop.get("_default_ref"), + Some(&json!("AnimationStyle")), + "Nested default with $ref should have _default_ref" + ); + } } diff --git a/src/templates/macros.html b/src/templates/macros.html index 8b11cf7c..8f6f903c 100644 --- a/src/templates/macros.html +++ b/src/templates/macros.html @@ -33,7 +33,7 @@ {%- if node.description_html %}
{{ node.description_html | safe }}
{% endif -%} {{ self::render_constraints(node=node) }} - {%- if node.default %}
Default: {{ node.default | json_encode() }}
{% endif -%} + {%- if node.default %}
Default: {% if node._default_ref and schema["$defs"][node._default_ref] %}{{ node.default | json_encode() }}{% else %}{{ node.default | json_encode() }}{% endif %}
{% endif -%} {{ self::render_schema_body(node=node, depth=depth, path=path) }} {%- else -%} @@ -365,7 +365,7 @@
{{ self::render_type_badge(node=node) }}{%- if node.description_html %}
{{ node.description_html | safe }}
{% endif -%} {{ self::render_constraints(node=node) }} - {%- if node.default %}
Default: {{ node.default | json_encode() }}
{% endif -%} + {%- if node.default %}
Default: {% if node._default_ref and schema["$defs"][node._default_ref] %}{{ node.default | json_encode() }}{% else %}{{ node.default | json_encode() }}{% endif %}
{% endif -%} {{ self::render_schema_body(node=node, depth=depth, path=path) }}
{%- endif -%} diff --git a/src/templates/mdx_macros.md b/src/templates/mdx_macros.md index 3d103019..47032497 100644 --- a/src/templates/mdx_macros.md +++ b/src/templates/mdx_macros.md @@ -171,7 +171,7 @@ {% else -%} **Pattern:** `{{ pattern }}` **→** {{ self::render_type_badge(node=prop) }} {% endif %} -{% if prop.description_html %}{{ prop.description_html | striptags | mdx_escape }}{% endif %} +{% if prop.description %}{{ prop.description | mdx_escape }}{% endif %} {{ self::render_schema_body(node=prop, depth=depth + 1, path=path ~ ".[key]") }} {% endfor %} {%- elif node.items -%} @@ -291,11 +291,16 @@ {# Render a schema without property wrapper #} {% macro render_schema(node, depth, path) %} {%- if depth < 10 -%} -{{ self::render_type_badge(node=node) }}{% if node.description_html %} - {{ node.description_html | striptags | mdx_escape }}{% endif %} +{# Skip type badge for documented const variants - the value is shown below #} +{%- if node.const and node.description -%} +{{ node.description | mdx_escape }} +{%- else -%} +{{ self::render_type_badge(node=node) }}{% if node.description %} - {{ node.description | mdx_escape }}{% endif %} +{%- endif -%} {{ self::render_constraints(node=node) }} {%- if node.default %} -**Default:** `{{ node.default | json_encode() }}` +**Default:** {% if node._default_ref and schema["$defs"][node._default_ref] %}[`{{ node.default | json_encode() }}`](#{{ node._default_ref | lower }}){% else %}`{{ node.default | json_encode() }}`{% endif %} {% endif -%} {{ self::render_schema_body(node=node, depth=depth, path=path) }} {%- endif -%} @@ -309,11 +314,11 @@ {% if required %} {% endif %}{% if node.deprecated %} {% endif %}{{ self::render_type_badge(node=node) }} -{% if node.description_html %}{{ node.description_html | striptags | mdx_escape }}{% endif %} +{% if node.description %}{{ node.description | mdx_escape }}{% endif %} {{ self::render_constraints(node=node) }} {%- if node.default %} -**Default:** `{{ node.default | json_encode() }}` +**Default:** {% if node._default_ref and schema["$defs"][node._default_ref] %}[`{{ node.default | json_encode() }}`](#{{ node._default_ref | lower }}){% else %}`{{ node.default | json_encode() }}`{% endif %} {% endif -%} {{ self::render_schema_body(node=node, depth=depth, path=path) }} {%- endif -%} @@ -327,11 +332,11 @@ {% if required %} {% endif %}{% if node.deprecated %} {% endif %}{{ self::render_type_badge(node=node) }} -{% if node.description_html %}{{ node.description_html | striptags | mdx_escape }}{% endif %} +{% if node.description %}{{ node.description | mdx_escape }}{% endif %} {{ self::render_constraints(node=node) }} {%- if node.default %} -**Default:** `{{ node.default | json_encode() }}` +**Default:** {% if node._default_ref and schema["$defs"][node._default_ref] %}[`{{ node.default | json_encode() }}`](#{{ node._default_ref | lower }}){% else %}`{{ node.default | json_encode() }}`{% endif %} {% endif -%} {{ self::render_schema_body(node=node, depth=depth, path=path) }} @@ -367,7 +372,7 @@ {{ self::render_type_badge(node=def) }} -{% if def.description_html %}{{ def.description_html | striptags | mdx_escape }}{% endif %} +{% if def.description %}{{ def.description | mdx_escape }}{% endif %} {{ self::render_constraints(node=def) }} {{ self::render_schema_body(node=def, depth=0, path=def_name) }} {{ self::render_usages(def=def) }}