Coverage for src/jsoncrack_for_sphinx/generators/html_generator.py: 100%
40 statements
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-24 22:26 +0000
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-24 22:26 +0000
1"""
2HTML generation for JSONCrack visualizations.
3"""
5import json
6from pathlib import Path
7from typing import Any, Optional
9from sphinx.util import logging
11from ..config.config_parser import JsonCrackConfig, get_config_values
12from ..config.config_utils import get_jsoncrack_config
14logger = logging.getLogger(__name__)
17def generate_schema_html(
18 schema_path: Path, file_type: str, app_config: Optional[Any] = None
19) -> str:
20 """Generate HTML representation of a JSON schema or JSON data for JSONCrack."""
21 logger.debug(f"Generating schema HTML for: {schema_path} (type: {file_type})")
23 try:
24 # Get configuration
25 config = get_jsoncrack_config(app_config) if app_config else JsonCrackConfig()
26 config_values = get_config_values(config)
27 logger.debug(f"Using config values: {config_values}")
29 # Read schema file
30 with open(schema_path, "r", encoding="utf-8") as f:
31 data = json.load(f)
32 logger.debug(f"Successfully loaded JSON data from {schema_path}")
34 # Process data based on file type
35 if file_type == "schema":
36 logger.debug("Processing as JSON schema, attempting to generate fake data")
37 # For .schema.json files, generate fake data using JSF
38 try:
39 from jsf import JSF
41 fake_data = JSF(data).generate()
42 json_data = fake_data
43 logger.debug("Successfully generated fake data using JSF")
44 except ImportError:
45 logger.warning("jsf library not available, using schema as-is")
46 json_data = data
47 except Exception as e:
48 logger.warning(
49 f"Error generating fake data with JSF: {e}, using schema as-is"
50 )
51 json_data = data
52 else:
53 logger.debug("Processing as JSON data file")
54 # For .json files, use data as-is
55 json_data = data
57 # Передаем JSON как строковый атрибут data-schema
58 # Используем html.escape для экранирования JSON в HTML-атрибуте
59 import html
61 schema_str = html.escape(json.dumps(json_data))
62 logger.debug(f"Escaped JSON data length: {len(schema_str)}")
64 # Create HTML for JSONCrack visualization
65 html_content = f"""
66 <div class="jsoncrack-container"
67 data-schema="{schema_str}"
68 data-render-mode="{config_values['render_mode']}"
69 data-theme="{config_values['theme'] or ''}"
70 data-direction="{config_values['direction']}"
71 data-height="{config_values['height']}"
72 data-width="{config_values['width']}"
73 data-onscreen-threshold="{config_values['onscreen_threshold']}"
74 data-onscreen-margin="{config_values['onscreen_margin']}">
75 </div>
76 """
78 logger.info(f"Successfully generated HTML for schema: {schema_path}")
79 return html_content
80 except Exception as e:
81 logger.error(f"Error generating schema HTML for {schema_path}: {e}")
82 return f"<div class='error'>Error processing schema file: {str(e)}</div>"