Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
presentation_layer_extended.py · 11.2 KB · 346 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Extended Presentation Layer - Support for IDs, classes, attributes, and scripts |
| 4 | """ |
| 5 | |
| 6 | from typing import Dict, List, Any, Optional |
| 7 | from presentation_layer import UIRenderer |
| 8 | |
| 9 | class EnhancedBootstrapRenderer(UIRenderer): |
| 10 | """Enhanced Bootstrap renderer with ID, class, and attribute support""" |
| 11 | |
| 12 | def _extract_attrs(self, data: Dict) -> tuple: |
| 13 | """Extract common attributes from data structure""" |
| 14 | attrs = [] |
| 15 | |
| 16 | # Standard attributes |
| 17 | if 'id' in data: |
| 18 | attrs.append(f'id="{data["id"]}"') |
| 19 | |
| 20 | # Custom classes (in addition to component defaults) |
| 21 | custom_classes = [] |
| 22 | if 'class' in data: |
| 23 | custom_classes.append(data['class']) |
| 24 | if 'classes' in data: |
| 25 | if isinstance(data['classes'], list): |
| 26 | custom_classes.extend(data['classes']) |
| 27 | else: |
| 28 | custom_classes.append(data['classes']) |
| 29 | |
| 30 | # Style attribute |
| 31 | if 'style' in data: |
| 32 | attrs.append(f'style="{data["style"]}"') |
| 33 | |
| 34 | # Data attributes (data-*) |
| 35 | if 'data' in data: |
| 36 | for key, value in data['data'].items(): |
| 37 | attrs.append(f'data-{key}="{value}"') |
| 38 | |
| 39 | # Custom attributes |
| 40 | if 'attrs' in data: |
| 41 | for key, value in data['attrs'].items(): |
| 42 | attrs.append(f'{key}="{value}"') |
| 43 | |
| 44 | # Event handlers |
| 45 | for key in data: |
| 46 | if key.startswith('on'): # onclick, onchange, etc. |
| 47 | attrs.append(f'{key}="{data[key]}"') |
| 48 | |
| 49 | return ' '.join(attrs), ' '.join(custom_classes) |
| 50 | |
| 51 | def render_div(self, data: Dict) -> str: |
| 52 | """Render a div with full attribute support""" |
| 53 | attrs, custom_classes = self._extract_attrs(data) |
| 54 | |
| 55 | # Build classes |
| 56 | classes = [] |
| 57 | if data.get('container'): |
| 58 | classes.append('container') |
| 59 | if data.get('fluid'): |
| 60 | classes.append('container-fluid') |
| 61 | if custom_classes: |
| 62 | classes.append(custom_classes) |
| 63 | |
| 64 | class_attr = f'class="{" ".join(classes)}"' if classes else '' |
| 65 | |
| 66 | # Render children |
| 67 | children = data.get('children', []) |
| 68 | content = data.get('content', '') |
| 69 | |
| 70 | if children: |
| 71 | content = ''.join([self.render(child) for child in children]) |
| 72 | |
| 73 | return f'<div {class_attr} {attrs}>{content}</div>' |
| 74 | |
| 75 | def render_enhanced_card(self, data: Dict) -> str: |
| 76 | """Card with ID and custom attributes""" |
| 77 | attrs, custom_classes = self._extract_attrs(data) |
| 78 | |
| 79 | card_classes = ['card'] |
| 80 | if custom_classes: |
| 81 | card_classes.append(custom_classes) |
| 82 | |
| 83 | # Card header |
| 84 | header = '' |
| 85 | if 'header' in data: |
| 86 | header_id = data.get('header_id', '') |
| 87 | header = f'''<div class="card-header" {f'id="{header_id}"' if header_id else ''}> |
| 88 | {self.render(data['header'])} |
| 89 | </div>''' |
| 90 | |
| 91 | # Card body |
| 92 | body_id = data.get('body_id', '') |
| 93 | body_attrs = f'id="{body_id}"' if body_id else '' |
| 94 | |
| 95 | return f''' |
| 96 | <div class="{' '.join(card_classes)}" {attrs}> |
| 97 | {header} |
| 98 | <div class="card-body" {body_attrs}> |
| 99 | {f'<h5 class="card-title">{data.get("title", "")}</h5>' if 'title' in data else ''} |
| 100 | {self.render(data.get('body', data.get('description', '')))} |
| 101 | </div> |
| 102 | {f'<div class="card-footer">{self.render(data["footer"])}</div>' if 'footer' in data else ''} |
| 103 | </div> |
| 104 | ''' |
| 105 | |
| 106 | def render_span(self, data: Dict) -> str: |
| 107 | """Render a span with attributes""" |
| 108 | attrs, custom_classes = self._extract_attrs(data) |
| 109 | classes = custom_classes if custom_classes else '' |
| 110 | |
| 111 | return f'<span class="{classes}" {attrs}>{data.get("text", "")}</span>' |
| 112 | |
| 113 | def render_script(self, data: Dict) -> str: |
| 114 | """Render inline or external script""" |
| 115 | if 'src' in data: |
| 116 | attrs = ' '.join([f'{k}="{v}"' for k, v in data.items() if k != 'type']) |
| 117 | return f'<script {attrs}></script>' |
| 118 | else: |
| 119 | return f'<script>{data.get("content", "")}</script>' |
| 120 | |
| 121 | def render_style(self, data: Dict) -> str: |
| 122 | """Render inline styles""" |
| 123 | return f'<style>{data.get("content", "")}</style>' |
| 124 | |
| 125 | def render(self, data: Any) -> str: |
| 126 | """Enhanced render with new component types""" |
| 127 | if isinstance(data, dict): |
| 128 | component_type = data.get('type', '') |
| 129 | |
| 130 | # New enhanced components |
| 131 | if component_type == 'div': |
| 132 | return self.render_div(data) |
| 133 | elif component_type == 'span': |
| 134 | return self.render_span(data) |
| 135 | elif component_type == 'script': |
| 136 | return self.render_script(data) |
| 137 | elif component_type == 'style': |
| 138 | return self.render_style(data) |
| 139 | elif component_type == 'card': |
| 140 | return self.render_enhanced_card(data) |
| 141 | # ... other enhanced components |
| 142 | |
| 143 | # Fall back to parent implementation |
| 144 | return super().render(data) |
| 145 | |
| 146 | |
| 147 | # Example: Component with IDs and JavaScript |
| 148 | def example_with_ids_and_scripts(): |
| 149 | """Example showing how to use IDs, classes, and scripts""" |
| 150 | return { |
| 151 | 'type': 'page', |
| 152 | 'title': 'Enhanced Example', |
| 153 | 'components': [ |
| 154 | # Style definition |
| 155 | { |
| 156 | 'type': 'style', |
| 157 | 'content': ''' |
| 158 | #myCustomCard { border: 2px solid blue; } |
| 159 | .highlight { background-color: yellow; } |
| 160 | ''' |
| 161 | }, |
| 162 | |
| 163 | # Card with ID for JavaScript targeting |
| 164 | { |
| 165 | 'type': 'card', |
| 166 | 'id': 'myCustomCard', |
| 167 | 'class': 'shadow-lg', |
| 168 | 'data': {'user-id': '123', 'role': 'admin'}, |
| 169 | 'title': 'Interactive Card', |
| 170 | 'body': { |
| 171 | 'type': 'div', |
| 172 | 'children': [ |
| 173 | { |
| 174 | 'type': 'span', |
| 175 | 'id': 'counter', |
| 176 | 'class': 'badge bg-primary', |
| 177 | 'text': '0' |
| 178 | }, |
| 179 | ' clicks', |
| 180 | { |
| 181 | 'type': 'button', |
| 182 | 'id': 'incrementBtn', |
| 183 | 'text': 'Click Me', |
| 184 | 'onclick': 'incrementCounter()' |
| 185 | } |
| 186 | ] |
| 187 | } |
| 188 | }, |
| 189 | |
| 190 | # Inline script |
| 191 | { |
| 192 | 'type': 'script', |
| 193 | 'content': ''' |
| 194 | let count = 0; |
| 195 | function incrementCounter() { |
| 196 | count++; |
| 197 | document.getElementById('counter').textContent = count; |
| 198 | if (count > 5) { |
| 199 | document.getElementById('myCustomCard').classList.add('highlight'); |
| 200 | } |
| 201 | } |
| 202 | ''' |
| 203 | } |
| 204 | ] |
| 205 | } |
| 206 | |
| 207 | |
| 208 | # Better approach: Separate concerns |
| 209 | def structured_component_with_behavior(): |
| 210 | """Better pattern: Structure + Behavior separation""" |
| 211 | return { |
| 212 | 'type': 'page', |
| 213 | 'components': [ |
| 214 | # Structure (data) |
| 215 | { |
| 216 | 'type': 'div', |
| 217 | 'id': 'app', |
| 218 | 'children': [ |
| 219 | { |
| 220 | 'type': 'div', |
| 221 | 'id': 'metrics-container', |
| 222 | 'class': 'row', |
| 223 | 'children': [ |
| 224 | { |
| 225 | 'type': 'div', |
| 226 | 'class': 'col-md-3', |
| 227 | 'children': [{ |
| 228 | 'type': 'card', |
| 229 | 'body_id': 'metric-1', |
| 230 | 'title': 'Metric 1', |
| 231 | 'body': '0' |
| 232 | }] |
| 233 | } |
| 234 | ] |
| 235 | } |
| 236 | ] |
| 237 | } |
| 238 | ], |
| 239 | |
| 240 | # Behavior (separate from structure) |
| 241 | 'scripts': [ |
| 242 | { |
| 243 | 'type': 'script', |
| 244 | 'src': '/static/js/dashboard.js' |
| 245 | }, |
| 246 | { |
| 247 | 'type': 'script', |
| 248 | 'content': 'initDashboard();' |
| 249 | } |
| 250 | ], |
| 251 | |
| 252 | # Styling (separate from structure) |
| 253 | 'styles': [ |
| 254 | { |
| 255 | 'type': 'link', |
| 256 | 'rel': 'stylesheet', |
| 257 | 'href': '/static/css/dashboard.css' |
| 258 | } |
| 259 | ] |
| 260 | } |
| 261 | |
| 262 | |
| 263 | # Advanced: Component registry pattern |
| 264 | class ComponentRegistry: |
| 265 | """Register reusable components with IDs""" |
| 266 | |
| 267 | components = {} |
| 268 | |
| 269 | @classmethod |
| 270 | def register(cls, name: str, component: Dict): |
| 271 | """Register a reusable component""" |
| 272 | cls.components[name] = component |
| 273 | |
| 274 | @classmethod |
| 275 | def get(cls, name: str, **overrides) -> Dict: |
| 276 | """Get component with overrides""" |
| 277 | component = cls.components.get(name, {}).copy() |
| 278 | |
| 279 | # Apply overrides (like ID, custom classes) |
| 280 | for key, value in overrides.items(): |
| 281 | if key == 'classes' and 'classes' in component: |
| 282 | # Merge classes |
| 283 | existing = component.get('classes', []) |
| 284 | if not isinstance(existing, list): |
| 285 | existing = [existing] |
| 286 | if not isinstance(value, list): |
| 287 | value = [value] |
| 288 | component['classes'] = existing + value |
| 289 | else: |
| 290 | component[key] = value |
| 291 | |
| 292 | return component |
| 293 | |
| 294 | |
| 295 | # Register common components |
| 296 | ComponentRegistry.register('metric_card', { |
| 297 | 'type': 'card', |
| 298 | 'classes': ['metric-card'], |
| 299 | 'body': { |
| 300 | 'type': 'div', |
| 301 | 'children': [ |
| 302 | {'type': 'h2', 'id': '{{metric_id}}', 'text': '0'}, |
| 303 | {'type': 'small', 'text': '{{metric_label}}'} |
| 304 | ] |
| 305 | } |
| 306 | }) |
| 307 | |
| 308 | # Use registered component with custom ID |
| 309 | def use_registered_components(): |
| 310 | return { |
| 311 | 'type': 'page', |
| 312 | 'components': [ |
| 313 | ComponentRegistry.get('metric_card', |
| 314 | id='revenue-card', |
| 315 | metric_id='revenue-value', |
| 316 | metric_label='Revenue') |
| 317 | ] |
| 318 | } |
| 319 | |
| 320 | |
| 321 | if __name__ == "__main__": |
| 322 | print("Enhanced Presentation Layer Features:") |
| 323 | print("\n1. ID Support:") |
| 324 | print(" {'type': 'div', 'id': 'myDiv'}") |
| 325 | |
| 326 | print("\n2. Custom Classes:") |
| 327 | print(" {'type': 'card', 'classes': ['shadow-lg', 'my-custom']}") |
| 328 | |
| 329 | print("\n3. Data Attributes:") |
| 330 | print(" {'type': 'div', 'data': {'user-id': '123', 'role': 'admin'}}") |
| 331 | |
| 332 | print("\n4. Event Handlers:") |
| 333 | print(" {'type': 'button', 'onclick': 'handleClick()'}") |
| 334 | |
| 335 | print("\n5. Inline Styles:") |
| 336 | print(" {'type': 'div', 'style': 'background: red; padding: 10px;'}") |
| 337 | |
| 338 | print("\n6. Scripts & Styles:") |
| 339 | print(" {'type': 'script', 'content': 'console.log(\"Hello\");'}") |
| 340 | print(" {'type': 'script', 'src': '/static/js/app.js'}") |
| 341 | |
| 342 | print("\n7. Component Registry:") |
| 343 | print(" Register once, use everywhere with different IDs") |
| 344 | |
| 345 | print("\nBest Practice: Keep structure (HTML) separate from behavior (JS)") |
| 346 | print("This maintains the clean separation while allowing full control!") |