Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
html_builders.py · 11.3 KB · 343 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | DBBasic HTML Builders - Experiments in data-to-Bootstrap conversion |
| 4 | Let's try different approaches and see what feels most natural |
| 5 | """ |
| 6 | |
| 7 | import json |
| 8 | from typing import Dict, List, Any, Optional |
| 9 | |
| 10 | # ============================================ |
| 11 | # APPROACH 1: Simple dict-to-Bootstrap mapping |
| 12 | # ============================================ |
| 13 | |
| 14 | def dict_to_bootstrap(data: Dict[str, Any]) -> str: |
| 15 | """Convert a dict structure directly to Bootstrap HTML""" |
| 16 | component_type = data.get('type', 'div') |
| 17 | |
| 18 | if component_type == 'page': |
| 19 | return f"""<!DOCTYPE html> |
| 20 | <html> |
| 21 | <head> |
| 22 | <title>{data.get('title', 'DBBasic')}</title> |
| 23 | <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> |
| 24 | <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css"> |
| 25 | </head> |
| 26 | <body> |
| 27 | {dict_to_bootstrap(data.get('body', {}))} |
| 28 | <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> |
| 29 | </body> |
| 30 | </html>""" |
| 31 | |
| 32 | elif component_type == 'navbar': |
| 33 | items = ''.join([f'<a class="nav-link" href="{item["url"]}">{item["text"]}</a>' |
| 34 | for item in data.get('items', [])]) |
| 35 | return f"""<nav class="navbar navbar-expand-lg navbar-light bg-light"> |
| 36 | <div class="container-fluid"> |
| 37 | <a class="navbar-brand" href="#">{data.get('brand', 'DBBasic')}</a> |
| 38 | <div class="navbar-nav ms-auto">{items}</div> |
| 39 | </div> |
| 40 | </nav>""" |
| 41 | |
| 42 | elif component_type == 'card': |
| 43 | return f"""<div class="card"> |
| 44 | <div class="card-body"> |
| 45 | <h5 class="card-title">{data.get('title', '')}</h5> |
| 46 | <p class="card-text">{data.get('text', '')}</p> |
| 47 | {dict_to_bootstrap(data.get('footer', {})) if 'footer' in data else ''} |
| 48 | </div> |
| 49 | </div>""" |
| 50 | |
| 51 | elif component_type == 'button': |
| 52 | return f"""<button class="btn btn-{data.get('variant', 'primary')}" {data.get('attrs', '')}> |
| 53 | {data.get('text', 'Button')} |
| 54 | </button>""" |
| 55 | |
| 56 | elif component_type == 'grid': |
| 57 | cols = ''.join([f'<div class="col">{dict_to_bootstrap(col)}</div>' |
| 58 | for col in data.get('columns', [])]) |
| 59 | return f'<div class="row">{cols}</div>' |
| 60 | |
| 61 | elif component_type == 'container': |
| 62 | children = ''.join([dict_to_bootstrap(child) for child in data.get('children', [])]) |
| 63 | return f'<div class="container">{children}</div>' |
| 64 | |
| 65 | else: |
| 66 | # Default div with optional content |
| 67 | return f'<div>{data.get("content", "")}</div>' |
| 68 | |
| 69 | |
| 70 | # ============================================ |
| 71 | # APPROACH 2: List-based component builder |
| 72 | # ============================================ |
| 73 | |
| 74 | def build_from_list(components: List) -> str: |
| 75 | """Build HTML from a list of component definitions""" |
| 76 | html = [] |
| 77 | |
| 78 | for comp in components: |
| 79 | if isinstance(comp, str): |
| 80 | html.append(comp) |
| 81 | elif isinstance(comp, dict): |
| 82 | html.append(dict_to_bootstrap(comp)) |
| 83 | elif isinstance(comp, list): |
| 84 | # Handle nested lists as containers |
| 85 | html.append(f'<div>{build_from_list(comp)}</div>') |
| 86 | elif isinstance(comp, tuple): |
| 87 | # Tuples as (tag, attrs, content) |
| 88 | tag, attrs, content = comp |
| 89 | attr_str = ' '.join(f'{k}="{v}"' for k, v in attrs.items()) if isinstance(attrs, dict) else attrs |
| 90 | html.append(f'<{tag} {attr_str}>{content}</{tag}>') |
| 91 | |
| 92 | return ''.join(html) |
| 93 | |
| 94 | |
| 95 | # ============================================ |
| 96 | # APPROACH 3: Functional composition |
| 97 | # ============================================ |
| 98 | |
| 99 | def page(**kwargs): |
| 100 | """Create a page structure""" |
| 101 | return { |
| 102 | 'type': 'page', |
| 103 | 'title': kwargs.get('title', 'DBBasic'), |
| 104 | 'body': kwargs.get('body', {}) |
| 105 | } |
| 106 | |
| 107 | def navbar(brand: str, *items): |
| 108 | """Create a navbar""" |
| 109 | return { |
| 110 | 'type': 'navbar', |
| 111 | 'brand': brand, |
| 112 | 'items': [{'text': item[0], 'url': item[1]} for item in items] |
| 113 | } |
| 114 | |
| 115 | def card(title: str, text: str, **kwargs): |
| 116 | """Create a card""" |
| 117 | return { |
| 118 | 'type': 'card', |
| 119 | 'title': title, |
| 120 | 'text': text, |
| 121 | **kwargs |
| 122 | } |
| 123 | |
| 124 | def button(text: str, variant: str = 'primary', **attrs): |
| 125 | """Create a button""" |
| 126 | attr_str = ' '.join(f'{k}="{v}"' for k, v in attrs.items()) |
| 127 | return { |
| 128 | 'type': 'button', |
| 129 | 'text': text, |
| 130 | 'variant': variant, |
| 131 | 'attrs': attr_str |
| 132 | } |
| 133 | |
| 134 | def grid(*columns): |
| 135 | """Create a grid""" |
| 136 | return { |
| 137 | 'type': 'grid', |
| 138 | 'columns': list(columns) |
| 139 | } |
| 140 | |
| 141 | def container(*children): |
| 142 | """Create a container""" |
| 143 | return { |
| 144 | 'type': 'container', |
| 145 | 'children': list(children) |
| 146 | } |
| 147 | |
| 148 | |
| 149 | # ============================================ |
| 150 | # APPROACH 4: JSON schema to Bootstrap |
| 151 | # ============================================ |
| 152 | |
| 153 | def json_schema_to_form(schema: Dict[str, Any]) -> str: |
| 154 | """Convert JSON schema to Bootstrap form""" |
| 155 | form_fields = [] |
| 156 | |
| 157 | for field_name, field_def in schema.get('properties', {}).items(): |
| 158 | field_type = field_def.get('type', 'string') |
| 159 | |
| 160 | if field_type == 'string': |
| 161 | input_type = 'text' |
| 162 | if 'format' in field_def: |
| 163 | if field_def['format'] == 'email': |
| 164 | input_type = 'email' |
| 165 | elif field_def['format'] == 'date': |
| 166 | input_type = 'date' |
| 167 | elif field_type == 'number': |
| 168 | input_type = 'number' |
| 169 | elif field_type == 'boolean': |
| 170 | input_type = 'checkbox' |
| 171 | else: |
| 172 | input_type = 'text' |
| 173 | |
| 174 | form_fields.append(f""" |
| 175 | <div class="mb-3"> |
| 176 | <label for="{field_name}" class="form-label">{field_def.get('title', field_name)}</label> |
| 177 | <input type="{input_type}" class="form-control" id="{field_name}" name="{field_name}" |
| 178 | {'required' if field_name in schema.get('required', []) else ''}> |
| 179 | {f'<div class="form-text">{field_def["description"]}</div>' if 'description' in field_def else ''} |
| 180 | </div> |
| 181 | """) |
| 182 | |
| 183 | return f'<form>{"".join(form_fields)}<button type="submit" class="btn btn-primary">Submit</button></form>' |
| 184 | |
| 185 | |
| 186 | # ============================================ |
| 187 | # APPROACH 5: Template marketplace specific |
| 188 | # ============================================ |
| 189 | |
| 190 | def render_template_marketplace(templates: List[Dict]) -> str: |
| 191 | """Render template marketplace using functional composition""" |
| 192 | |
| 193 | # Build cards for each template |
| 194 | cards = [] |
| 195 | for template in templates: |
| 196 | cards.append(card( |
| 197 | title=template['name'], |
| 198 | text=f"{template['description']} • {template['fields_count']} fields", |
| 199 | footer={ |
| 200 | 'type': 'container', |
| 201 | 'children': [ |
| 202 | button('Preview', 'secondary', onclick=f"previewTemplate('{template['id']}')"), |
| 203 | button('Deploy', 'success', onclick=f"deployTemplate('{template['id']}')") |
| 204 | ] |
| 205 | } |
| 206 | )) |
| 207 | |
| 208 | # Build the page structure |
| 209 | page_structure = page( |
| 210 | title="Template Marketplace", |
| 211 | body=container( |
| 212 | navbar("DBBasic", |
| 213 | ("Monitor", "http://localhost:8004"), |
| 214 | ("Data", "http://localhost:8005"), |
| 215 | ("Templates", "/templates")), |
| 216 | {'type': 'container', 'children': [ |
| 217 | '<h1 class="text-center my-4">Template Marketplace</h1>', |
| 218 | '<p class="text-center text-muted mb-5">Deploy production-ready apps instantly</p>', |
| 219 | grid(*cards) |
| 220 | ]} |
| 221 | ) |
| 222 | ) |
| 223 | |
| 224 | return dict_to_bootstrap(page_structure) |
| 225 | |
| 226 | |
| 227 | # ============================================ |
| 228 | # APPROACH 6: Pure data transformation |
| 229 | # ============================================ |
| 230 | |
| 231 | class BootstrapRenderer: |
| 232 | """Render data structures as Bootstrap HTML""" |
| 233 | |
| 234 | @staticmethod |
| 235 | def render(data: Any) -> str: |
| 236 | """Main render method that handles any data type""" |
| 237 | if isinstance(data, dict): |
| 238 | return BootstrapRenderer._render_dict(data) |
| 239 | elif isinstance(data, list): |
| 240 | return ''.join(BootstrapRenderer.render(item) for item in data) |
| 241 | elif isinstance(data, str): |
| 242 | return data |
| 243 | else: |
| 244 | return str(data) |
| 245 | |
| 246 | @staticmethod |
| 247 | def _render_dict(data: Dict) -> str: |
| 248 | """Render dict based on its structure""" |
| 249 | # Check for special keys that indicate component types |
| 250 | if '_component' in data: |
| 251 | return BootstrapRenderer._render_component(data) |
| 252 | elif '_tag' in data: |
| 253 | tag = data['_tag'] |
| 254 | attrs = data.get('_attrs', {}) |
| 255 | children = data.get('_children', []) |
| 256 | attr_str = ' '.join(f'{k}="{v}"' for k, v in attrs.items()) |
| 257 | content = BootstrapRenderer.render(children) |
| 258 | return f'<{tag} {attr_str}>{content}</{tag}>' |
| 259 | else: |
| 260 | # Try to infer component from keys |
| 261 | if 'title' in data and 'text' in data: |
| 262 | return BootstrapRenderer._render_card(data) |
| 263 | elif 'columns' in data: |
| 264 | return BootstrapRenderer._render_grid(data) |
| 265 | else: |
| 266 | return str(data) |
| 267 | |
| 268 | @staticmethod |
| 269 | def _render_component(data: Dict) -> str: |
| 270 | """Render specific Bootstrap components""" |
| 271 | component = data['_component'] |
| 272 | |
| 273 | if component == 'card': |
| 274 | return BootstrapRenderer._render_card(data) |
| 275 | elif component == 'button': |
| 276 | return f'<button class="btn btn-{data.get("variant", "primary")}">{data.get("text", "")}</button>' |
| 277 | elif component == 'alert': |
| 278 | return f'<div class="alert alert-{data.get("type", "info")}">{data.get("message", "")}</div>' |
| 279 | else: |
| 280 | return f'<div>{data}</div>' |
| 281 | |
| 282 | @staticmethod |
| 283 | def _render_card(data: Dict) -> str: |
| 284 | """Render a Bootstrap card""" |
| 285 | return f""" |
| 286 | <div class="card"> |
| 287 | <div class="card-body"> |
| 288 | <h5 class="card-title">{data.get('title', '')}</h5> |
| 289 | <p class="card-text">{data.get('text', '')}</p> |
| 290 | </div> |
| 291 | </div> |
| 292 | """ |
| 293 | |
| 294 | @staticmethod |
| 295 | def _render_grid(data: Dict) -> str: |
| 296 | """Render a Bootstrap grid""" |
| 297 | cols = ''.join(f'<div class="col">{BootstrapRenderer.render(col)}</div>' |
| 298 | for col in data.get('columns', [])) |
| 299 | return f'<div class="row">{cols}</div>' |
| 300 | |
| 301 | |
| 302 | # ============================================ |
| 303 | # Test the different approaches |
| 304 | # ============================================ |
| 305 | |
| 306 | if __name__ == "__main__": |
| 307 | # Sample template data |
| 308 | sample_templates = [ |
| 309 | { |
| 310 | 'id': 'blog/posts', |
| 311 | 'name': 'Blog Posts', |
| 312 | 'category': 'CMS', |
| 313 | 'description': 'Manage blog posts with SEO', |
| 314 | 'fields_count': 8 |
| 315 | }, |
| 316 | { |
| 317 | 'id': 'ecommerce/products', |
| 318 | 'name': 'Products', |
| 319 | 'category': 'E-Commerce', |
| 320 | 'description': 'Product catalog management', |
| 321 | 'fields_count': 12 |
| 322 | } |
| 323 | ] |
| 324 | |
| 325 | print("Testing different approaches...") |
| 326 | print("\n1. Functional composition approach:") |
| 327 | print(render_template_marketplace(sample_templates)[:500] + "...") |
| 328 | |
| 329 | print("\n2. Direct dict structure:") |
| 330 | test_dict = { |
| 331 | 'type': 'card', |
| 332 | 'title': 'Test Card', |
| 333 | 'text': 'This is a test card' |
| 334 | } |
| 335 | print(dict_to_bootstrap(test_dict)) |
| 336 | |
| 337 | print("\n3. Pure data transformation:") |
| 338 | test_data = { |
| 339 | '_component': 'card', |
| 340 | 'title': 'Test Card', |
| 341 | 'text': 'Using renderer class' |
| 342 | } |
| 343 | print(BootstrapRenderer.render(test_data)) |