askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/component_marketplace.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
component_marketplace.py · 18.4 KB · 535 lines
1#!/usr/bin/env python3
2"""
3DBBasic Component Marketplace
4Reusable UI components that can be shared and imported
5"""
6
7from typing import Dict, List, Any, Optional
8import json
9from pathlib import Path
10
11class ComponentMarketplace:
12 """Marketplace for sharing and discovering UI components"""
13
14 def __init__(self):
15 self.components = {}
16 self.categories = {
17 'navigation': [],
18 'heroes': [],
19 'cards': [],
20 'forms': [],
21 'tables': [],
22 'dashboards': [],
23 'charts': [],
24 'layouts': []
25 }
26 self.load_built_in_components()
27
28 def load_built_in_components(self):
29 """Load built-in component library"""
30
31 # Navigation Components
32 self.register_component({
33 'id': 'unified-nav',
34 'name': 'Unified Navigation',
35 'category': 'navigation',
36 'description': 'DBBasic unified navigation with service links',
37 'author': 'DBBasic Team',
38 'version': '1.0.0',
39 'frameworks': ['bootstrap', 'tailwind'],
40 'data': {
41 'type': 'navbar',
42 'brand': 'DBBasic',
43 'variant': 'dark',
44 'links': [
45 {'text': 'Monitor', 'url': 'http://localhost:8004'},
46 {'text': 'Data', 'url': 'http://localhost:8005'},
47 {'text': 'AI Services', 'url': 'http://localhost:8003'},
48 {'text': 'Events', 'url': 'http://localhost:8006'}
49 ]
50 }
51 })
52
53 # Dashboard Components
54 self.register_component({
55 'id': 'metrics-dashboard',
56 'name': 'Metrics Dashboard',
57 'category': 'dashboards',
58 'description': 'Real-time metrics dashboard with 4 KPIs',
59 'author': 'DBBasic Team',
60 'version': '1.0.0',
61 'frameworks': ['bootstrap', 'tailwind'],
62 'data': {
63 'type': 'grid',
64 'columns': 4,
65 'items': [
66 {
67 'type': 'card',
68 'id': 'metric-1',
69 'body': {
70 'type': 'metric',
71 'label': 'Total Users',
72 'value': '0',
73 'icon': 'bi-people'
74 }
75 },
76 {
77 'type': 'card',
78 'id': 'metric-2',
79 'body': {
80 'type': 'metric',
81 'label': 'Revenue',
82 'value': '$0',
83 'icon': 'bi-currency-dollar'
84 }
85 },
86 {
87 'type': 'card',
88 'id': 'metric-3',
89 'body': {
90 'type': 'metric',
91 'label': 'Orders',
92 'value': '0',
93 'icon': 'bi-cart'
94 }
95 },
96 {
97 'type': 'card',
98 'id': 'metric-4',
99 'body': {
100 'type': 'metric',
101 'label': 'Performance',
102 'value': '100%',
103 'icon': 'bi-speedometer2'
104 }
105 }
106 ]
107 }
108 })
109
110 # Form Components
111 self.register_component({
112 'id': 'user-registration',
113 'name': 'User Registration Form',
114 'category': 'forms',
115 'description': 'Complete user registration form with validation',
116 'author': 'DBBasic Team',
117 'version': '1.0.0',
118 'frameworks': ['bootstrap', 'tailwind'],
119 'data': {
120 'type': 'form',
121 'id': 'registration-form',
122 'fields': [
123 {
124 'type': 'input',
125 'name': 'username',
126 'label': 'Username',
127 'placeholder': 'Choose a username',
128 'required': True
129 },
130 {
131 'type': 'input',
132 'input_type': 'email',
133 'name': 'email',
134 'label': 'Email Address',
135 'placeholder': 'your@email.com',
136 'required': True
137 },
138 {
139 'type': 'input',
140 'input_type': 'password',
141 'name': 'password',
142 'label': 'Password',
143 'placeholder': 'Min 8 characters',
144 'required': True
145 },
146 {
147 'type': 'checkbox',
148 'name': 'terms',
149 'label': 'I agree to the terms and conditions',
150 'required': True
151 }
152 ],
153 'submit': {
154 'text': 'Create Account',
155 'variant': 'primary'
156 }
157 }
158 })
159
160 # Card Components
161 self.register_component({
162 'id': 'service-card',
163 'name': 'Service Status Card',
164 'category': 'cards',
165 'description': 'Card showing service status and metrics',
166 'author': 'DBBasic Team',
167 'version': '1.0.0',
168 'frameworks': ['bootstrap', 'tailwind'],
169 'data': {
170 'type': 'card',
171 'title': '{{service_name}}',
172 'body': {
173 'type': 'div',
174 'children': [
175 {'type': 'badge', 'text': '{{status}}', 'variant': 'success'},
176 {'type': 'p', 'text': '{{description}}'},
177 {
178 'type': 'div',
179 'class': 'mt-3',
180 'children': [
181 {'type': 'small', 'text': 'Port: {{port}}'},
182 {'type': 'small', 'text': ' | '},
183 {'type': 'small', 'text': 'Uptime: {{uptime}}'}
184 ]
185 }
186 ]
187 },
188 'footer': {
189 'type': 'button_group',
190 'buttons': [
191 {'text': 'View', 'variant': 'primary', 'size': 'sm'},
192 {'text': 'Restart', 'variant': 'warning', 'size': 'sm'}
193 ]
194 }
195 }
196 })
197
198 # Table Components
199 self.register_component({
200 'id': 'data-table',
201 'name': 'Interactive Data Table',
202 'category': 'tables',
203 'description': 'Sortable, filterable data table',
204 'author': 'DBBasic Team',
205 'version': '1.0.0',
206 'frameworks': ['bootstrap', 'tailwind'],
207 'data': {
208 'type': 'div',
209 'children': [
210 {
211 'type': 'div',
212 'class': 'table-controls mb-3',
213 'children': [
214 {
215 'type': 'input',
216 'id': 'table-search',
217 'placeholder': 'Search...',
218 'class': 'form-control'
219 }
220 ]
221 },
222 {
223 'type': 'table',
224 'id': 'data-table',
225 'datatable': True,
226 'headers': ['ID', 'Name', 'Status', 'Actions'],
227 'rows': []
228 }
229 ]
230 }
231 })
232
233 # Hero Components
234 self.register_component({
235 'id': 'gradient-hero',
236 'name': 'Gradient Hero Section',
237 'category': 'heroes',
238 'description': 'Eye-catching hero with gradient background',
239 'author': 'DBBasic Team',
240 'version': '1.0.0',
241 'frameworks': ['bootstrap', 'tailwind'],
242 'data': {
243 'type': 'hero',
244 'title': '{{title}}',
245 'subtitle': '{{subtitle}}',
246 'variant': 'gradient-purple',
247 'content': [
248 {
249 'type': 'button_group',
250 'buttons': [
251 {'text': 'Get Started', 'variant': 'primary', 'size': 'lg'},
252 {'text': 'Learn More', 'variant': 'outline-light', 'size': 'lg'}
253 ]
254 }
255 ]
256 }
257 })
258
259 # Chart Components
260 self.register_component({
261 'id': 'line-chart',
262 'name': 'Line Chart Component',
263 'category': 'charts',
264 'description': 'Interactive line chart with real-time updates',
265 'author': 'DBBasic Team',
266 'version': '1.0.0',
267 'frameworks': ['bootstrap', 'tailwind'],
268 'data': {
269 'type': 'card',
270 'title': '{{chart_title}}',
271 'body': {
272 'type': 'chart',
273 'id': '{{chart_id}}',
274 'chartType': 'line',
275 'data': {
276 'labels': [],
277 'datasets': []
278 }
279 }
280 }
281 })
282
283 # Layout Components
284 self.register_component({
285 'id': 'two-column-layout',
286 'name': 'Two Column Layout',
287 'category': 'layouts',
288 'description': 'Responsive two-column layout',
289 'author': 'DBBasic Team',
290 'version': '1.0.0',
291 'frameworks': ['bootstrap', 'tailwind'],
292 'data': {
293 'type': 'div',
294 'class': 'row',
295 'children': [
296 {
297 'type': 'div',
298 'class': 'col-md-8',
299 'id': 'main-content',
300 'children': []
301 },
302 {
303 'type': 'div',
304 'class': 'col-md-4',
305 'id': 'sidebar',
306 'children': []
307 }
308 ]
309 }
310 })
311
312 def register_component(self, component: Dict):
313 """Register a new component in the marketplace"""
314 comp_id = component['id']
315 category = component['category']
316
317 self.components[comp_id] = component
318
319 if category in self.categories:
320 self.categories[category].append(comp_id)
321
322 return comp_id
323
324 def get_component(self, component_id: str) -> Optional[Dict]:
325 """Get a component by ID"""
326 return self.components.get(component_id)
327
328 def search_components(self, query: str = None, category: str = None) -> List[Dict]:
329 """Search for components"""
330 results = []
331
332 for comp_id, component in self.components.items():
333 # Filter by category
334 if category and component['category'] != category:
335 continue
336
337 # Filter by search query
338 if query:
339 search_text = f"{component['name']} {component['description']}".lower()
340 if query.lower() not in search_text:
341 continue
342
343 results.append(component)
344
345 return results
346
347 def use_component(self, component_id: str, **params) -> Dict:
348 """Use a component with parameter substitution"""
349 component = self.get_component(component_id)
350 if not component:
351 raise ValueError(f"Component {component_id} not found")
352
353 # Deep copy the component data
354 import copy
355 data = copy.deepcopy(component['data'])
356
357 # Replace template variables
358 data_str = json.dumps(data)
359 for key, value in params.items():
360 data_str = data_str.replace(f'{{{{{key}}}}}', str(value))
361
362 return json.loads(data_str)
363
364 def export_component(self, component_id: str, format: str = 'json') -> str:
365 """Export a component for sharing"""
366 component = self.get_component(component_id)
367 if not component:
368 raise ValueError(f"Component {component_id} not found")
369
370 if format == 'json':
371 return json.dumps(component, indent=2)
372 elif format == 'python':
373 return f"component = {repr(component)}"
374 else:
375 raise ValueError(f"Unsupported format: {format}")
376
377 def import_component(self, data: str, format: str = 'json') -> str:
378 """Import a component from external source"""
379 if format == 'json':
380 component = json.loads(data)
381 else:
382 raise ValueError(f"Unsupported format: {format}")
383
384 return self.register_component(component)
385
386 def generate_showcase_page(self) -> Dict:
387 """Generate a showcase page for all components"""
388 from dbbasic_unified_ui import get_master_layout
389
390 showcase_items = []
391
392 for category, component_ids in self.categories.items():
393 if not component_ids:
394 continue
395
396 category_section = {
397 'type': 'div',
398 'children': [
399 {'type': 'h2', 'text': category.title()},
400 {
401 'type': 'grid',
402 'columns': 2,
403 'items': []
404 }
405 ]
406 }
407
408 for comp_id in component_ids:
409 component = self.get_component(comp_id)
410 if component:
411 card = {
412 'type': 'card',
413 'title': component['name'],
414 'description': component['description'],
415 'footer': {
416 'type': 'div',
417 'children': [
418 {'type': 'small', 'text': f"v{component['version']} by {component['author']}"},
419 {
420 'type': 'button_group',
421 'class': 'mt-2',
422 'buttons': [
423 {
424 'text': 'Use',
425 'variant': 'primary',
426 'size': 'sm',
427 'onclick': f"useComponent('{comp_id}')"
428 },
429 {
430 'text': 'Preview',
431 'variant': 'info',
432 'size': 'sm',
433 'onclick': f"previewComponent('{comp_id}')"
434 }
435 ]
436 }
437 ]
438 }
439 }
440 category_section['children'][1]['items'].append(card)
441
442 showcase_items.append(category_section)
443
444 return get_master_layout(
445 title='Component Marketplace',
446 service_name='marketplace',
447 content=[
448 {
449 'type': 'hero',
450 'title': '🎨 Component Marketplace',
451 'subtitle': 'Reusable UI components for rapid development',
452 'variant': 'gradient-purple'
453 },
454 {
455 'type': 'alert',
456 'message': f'Browse {len(self.components)} pre-built components across {len(self.categories)} categories',
457 'variant': 'info'
458 },
459 *showcase_items
460 ]
461 )
462
463
464# Global marketplace instance
465marketplace = ComponentMarketplace()
466
467
468def create_custom_component(name: str, description: str, data: Dict) -> str:
469 """Helper to create custom components"""
470 component = {
471 'id': name.lower().replace(' ', '-'),
472 'name': name,
473 'category': 'custom',
474 'description': description,
475 'author': 'User',
476 'version': '1.0.0',
477 'frameworks': ['bootstrap', 'tailwind'],
478 'data': data
479 }
480
481 return marketplace.register_component(component)
482
483
484# Example usage
485if __name__ == "__main__":
486 from presentation_layer import PresentationLayer
487 from bootstrap_components import ExtendedBootstrapRenderer
488
489 # Initialize
490 PresentationLayer.add_renderer('bootstrap', ExtendedBootstrapRenderer())
491
492 # Use a component from marketplace
493 nav_data = marketplace.use_component('unified-nav')
494 metrics_data = marketplace.use_component(
495 'metrics-dashboard',
496 metric_1_value='1,234',
497 metric_2_value='$45,678'
498 )
499
500 # Create a page using marketplace components
501 page = {
502 'type': 'page',
503 'title': 'Component Marketplace Demo',
504 'components': [
505 nav_data,
506 metrics_data,
507 marketplace.use_component(
508 'gradient-hero',
509 title='Component Marketplace',
510 subtitle='Build faster with reusable components'
511 )
512 ]
513 }
514
515 # Render
516 html = PresentationLayer.render(page, 'bootstrap')
517
518 # Generate showcase
519 showcase_page = marketplace.generate_showcase_page()
520 showcase_html = PresentationLayer.render(showcase_page, 'bootstrap')
521
522 with open('static/marketplace.html', 'w') as f:
523 f.write(showcase_html)
524
525 print("✅ Component Marketplace created!")
526 print(f"\n📦 Available components: {len(marketplace.components)}")
527 print("\n🎨 Categories:")
528 for category, items in marketplace.categories.items():
529 if items:
530 print(f" • {category}: {len(items)} components")
531
532 print("\n💡 Usage example:")
533 print(" nav = marketplace.use_component('unified-nav')")
534 print(" html = PresentationLayer.render(nav, 'bootstrap')")
535 print("\n📄 Showcase page generated at static/marketplace.html")