"""
ui/modern_components.py
🚀 Modern UI Components for ARF v3.3.9
Enhanced with design system, accessibility, and performance features
Features:
1. Design token system with CSS variables
2. Responsive, mobile-first components
3. Accessibility (ARIA labels, keyboard nav)
4. Performance optimizations
5. Dark mode support
6. Progressive enhancement
"""
import json
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pandas as pd
# ===========================================
# DESIGN TOKEN SYSTEM (CSS Variables in JavaScript)
# ===========================================
DESIGN_TOKENS = {
"colors": {
"primary": {
"50": "#eff6ff",
"100": "#dbeafe",
"200": "#bfdbfe",
"300": "#93c5fd",
"400": "#60a5fa",
"500": "#3b82f6",
"600": "#2563eb",
"700": "#1d4ed8",
"800": "#1e40af",
"900": "#1e3a8a"
},
"success": {
"50": "#f0fdf4",
"100": "#dcfce7",
"200": "#bbf7d0",
"300": "#86efac",
"400": "#4ade80",
"500": "#22c55e",
"600": "#16a34a",
"700": "#15803d",
"800": "#166534",
"900": "#14532d"
},
"warning": {
"50": "#fffbeb",
"100": "#fef3c7",
"200": "#fde68a",
"300": "#fcd34d",
"400": "#fbbf24",
"500": "#f59e0b",
"600": "#d97706",
"700": "#b45309",
"800": "#92400e",
"900": "#78350f"
},
"danger": {
"50": "#fef2f2",
"100": "#fee2e2",
"200": "#fecaca",
"300": "#fca5a5",
"400": "#f87171",
"500": "#ef4444",
"600": "#dc2626",
"700": "#b91c1c",
"800": "#991b1b",
"900": "#7f1d1d"
},
"neutral": {
"50": "#f8fafc",
"100": "#f1f5f9",
"200": "#e2e8f0",
"300": "#cbd5e1",
"400": "#94a3b8",
"500": "#64748b",
"600": "#475569",
"700": "#334155",
"800": "#1e293b",
"900": "#0f172a"
}
},
"spacing": {
"1": "0.25rem",
"2": "0.5rem",
"3": "0.75rem",
"4": "1rem",
"5": "1.25rem",
"6": "1.5rem",
"8": "2rem",
"10": "2.5rem",
"12": "3rem",
"16": "4rem",
"20": "5rem"
},
"typography": {
"fontSizes": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem",
"2xl": "1.5rem",
"3xl": "1.875rem",
"4xl": "2.25rem"
},
"fontWeights": {
"light": "300",
"normal": "400",
"medium": "500",
"semibold": "600",
"bold": "700",
"extrabold": "800"
}
},
"breakpoints": {
"sm": "640px",
"md": "768px",
"lg": "1024px",
"xl": "1280px",
"2xl": "1536px"
},
"shadows": {
"sm": "0 1px 2px 0 rgb(0 0 0 / 0.05)",
"md": "0 4px 6px -1px rgb(0 0 0 / 0.1)",
"lg": "0 10px 15px -3px rgb(0 0 0 / 0.1)",
"xl": "0 20px 25px -5px rgb(0 0 0 / 0.1)"
},
"borderRadius": {
"sm": "0.25rem",
"md": "0.375rem",
"lg": "0.5rem",
"xl": "0.75rem",
"2xl": "1rem",
"full": "9999px"
}
}
# ===========================================
# CSS VARIABLES INJECTION
# ===========================================
def inject_design_tokens() -> str:
"""Inject CSS variables for design tokens into the page"""
css_variables = []
# Convert design tokens to CSS variables
for category, values in DESIGN_TOKENS.items():
if isinstance(values, dict):
for key, value in values.items():
if isinstance(value, dict):
for subkey, subvalue in value.items():
css_variables.append(f"--{category}-{key}-{subkey}: {subvalue};")
else:
css_variables.append(f"--{category}-{key}: {value};")
return f"""
"""
# ===========================================
# BASE COMPONENT CLASS
# ===========================================
class ModernComponent:
"""Base class for all modern components with consistent styling"""
def __init__(self):
self.component_id = f"component_{datetime.now().timestamp()}"
@staticmethod
def create_container(children: str, **kwargs) -> str:
"""Create a responsive container"""
classes = kwargs.get('classes', '')
style = kwargs.get('style', '')
return f"""
{children}
"""
@staticmethod
def create_section(title: str = "", children: str = "", **kwargs) -> str:
"""Create a semantic section with optional title"""
section_id = kwargs.get('id', '')
aria_label = kwargs.get('aria_label', title)
title_html = f'{title} ' if title else ''
return f"""
"""
# ===========================================
# ATOMIC COMPONENTS
# ===========================================
class Card(ModernComponent):
"""Card component with multiple variants"""
@staticmethod
def create(content: str, **kwargs) -> str:
"""Create a card with optional header and footer"""
title = kwargs.get('title', '')
footer = kwargs.get('footer', '')
variant = kwargs.get('variant', 'default') # default, elevated, outlined, filled
border_color = kwargs.get('border_color', 'var(--colors-neutral-200)')
variant_classes = {
'default': 'card-default',
'elevated': 'card-elevated',
'outlined': 'card-outlined',
'filled': 'card-filled'
}
header_html = f"""
""" if title else ''
footer_html = f"""
""" if footer else ''
return f"""
{header_html}
{content}
{footer_html}
"""
@staticmethod
def create_metric(value: str, label: str, **kwargs) -> str:
"""Create a metric card for KPIs"""
trend = kwargs.get('trend', None) # 'up', 'down', 'neutral'
change = kwargs.get('change', '')
trend_icon = {
'up': '↗',
'down': '↘',
'neutral': '→'
}.get(trend, '')
trend_color = {
'up': 'var(--color-success)',
'down': 'var(--color-danger)',
'neutral': 'var(--colors-neutral-500)'
}.get(trend, 'var(--colors-neutral-500)')
return f"""
{value}
{label}
{f'
{trend_icon} {change}
' if trend else ''}
"""
class Button(ModernComponent):
"""Accessible button component with variants"""
@staticmethod
def create(text: str, **kwargs) -> str:
"""Create a styled button"""
variant = kwargs.get('variant', 'primary') # primary, secondary, danger, ghost
size = kwargs.get('size', 'md') # sm, md, lg
disabled = kwargs.get('disabled', False)
full_width = kwargs.get('full_width', False)
variant_classes = {
'primary': 'btn-primary',
'secondary': 'btn-secondary',
'danger': 'btn-danger',
'ghost': 'btn-ghost'
}
size_classes = {
'sm': 'btn-sm',
'md': 'btn-md',
'lg': 'btn-lg'
}
classes = [
'btn',
variant_classes.get(variant, 'btn-primary'),
size_classes.get(size, 'btn-md'),
'full-width' if full_width else ''
]
disabled_attr = 'disabled aria-disabled="true"' if disabled else ''
return f"""
{text}
"""
@staticmethod
def create_icon_button(icon: str, label: str, **kwargs) -> str:
"""Create an icon-only button with proper accessibility"""
return f"""
{icon}
"""
class Badge(ModernComponent):
"""Badge component for status, tags, etc."""
@staticmethod
def create(text: str, **kwargs) -> str:
"""Create a badge"""
variant = kwargs.get('variant', 'default') # default, success, warning, danger
size = kwargs.get('size', 'md') # sm, md, lg
variant_classes = {
'default': 'badge-default',
'success': 'badge-success',
'warning': 'badge-warning',
'danger': 'badge-danger'
}
size_classes = {
'sm': 'badge-sm',
'md': 'badge-md',
'lg': 'badge-lg'
}
return f"""
{text}
"""
# ===========================================
# LAYOUT COMPONENTS
# ===========================================
class Grid(ModernComponent):
"""Responsive grid system"""
@staticmethod
def create(children: List[str], **kwargs) -> str:
"""Create a responsive grid"""
columns = kwargs.get('columns', { # responsive column definitions
'default': 1,
'sm': 2,
'lg': 3
})
gap = kwargs.get('gap', 'var(--spacing-4)')
# Convert columns dict to CSS
grid_template = []
for breakpoint, col_count in columns.items():
if breakpoint == 'default':
grid_template.append(f"grid-template-columns: repeat({col_count}, 1fr);")
else:
grid_template.append(f"@media (min-width: {DESIGN_TOKENS['breakpoints'][breakpoint]}) {{")
grid_template.append(f" grid-template-columns: repeat({col_count}, 1fr);")
grid_template.append("}")
return f"""
{''.join(children)}
"""
@staticmethod
def create_metric_grid(metrics: List[Dict[str, Any]]) -> str:
"""Create a grid of metric cards"""
metric_cards = []
for metric in metrics:
metric_cards.append(
Card.create_metric(
value=metric.get('value', ''),
label=metric.get('label', ''),
trend=metric.get('trend'),
change=metric.get('change', '')
)
)
return Grid.create(
children=metric_cards,
columns={'default': 2, 'sm': 2, 'lg': 4}
)
class Stack(ModernComponent):
"""Vertical stack layout"""
@staticmethod
def create(children: List[str], **kwargs) -> str:
"""Create a vertical stack"""
spacing = kwargs.get('spacing', 'var(--spacing-4)')
align = kwargs.get('align', 'stretch') # start, center, end, stretch
return f"""
{''.join([f'
{child}
' for child in children])}
"""
# ===========================================
# SPECIALIZED ARF COMPONENTS
# ===========================================
class ObservationGate(ModernComponent):
"""Observation gate component showing system restraint"""
@staticmethod
def create(confidence: float = 65.0, **kwargs) -> str:
"""Create observation gate display"""
reason = kwargs.get('reason', 'uncertainty_too_high_for_action')
frozen_until = kwargs.get('frozen_until', '')
threshold = 70.0
is_blocked = confidence < threshold
# Format countdown if available
countdown_html = ""
if frozen_until:
countdown_html = f"""
Next evaluation:
5:00
"""
status_text = "Observation Gate: Awaiting confirmation" if is_blocked else "Observation Gate Cleared"
status_color = "var(--color-warning)" if is_blocked else "var(--color-success)"
return f"""
Decision Intentionally Deferred
The system has detected uncertainty ({confidence:.1f}% confidence )
and has chosen to observe rather than act. Historical evidence indicates
premature action increases risk by 47% .
Confidence Threshold
{threshold}%
Required for action
Current Confidence
{confidence:.1f}%
Below threshold → Observe
Observe ({confidence:.1f}%)
Threshold ({threshold}%)
Act (75%+)
{countdown_html}
Prevented Actions (Contraindicated)
scale_during_retry_storm
add_capacity_during_amplification
any_action_during_high_uncertainty
"""
class SequencingFlow(ModernComponent):
"""Visualization of policy-enforced sequencing"""
@staticmethod
def create(steps: List[Dict[str, Any]], **kwargs) -> str:
"""Create sequencing flow visualization"""
current_step = kwargs.get('current_step', 0)
steps_html = []
for i, step in enumerate(steps):
is_current = i == current_step
is_completed = i < current_step
is_future = i > current_step
status_class = 'completed' if is_completed else 'current' if is_current else 'future'
steps_html.append(f"""
{i + 1}
{step.get('title', 'Step')}
{step.get('description', '')}
{step.get('badge', 'REQUIRED')}
""")
# Add connecting lines
connectors_html = ''
for i in range(len(steps) - 1):
is_completed = i < current_step
connector_class = 'completed' if is_completed else ''
connectors_html += f'
'
connectors_html += '
'
return f"""
{connectors_html}
{''.join(steps_html)}
🎯
Doctrinal Constraint: Scaling Cannot Appear First
If retry amplification is detected, scaling is contraindicated entirely .
The system must observe stabilization before considering capacity increases.
Historical evidence shows scaling-first fails 76% of the time during amplification.
"""
class ProcessDisplay(ModernComponent):
"""Display for ARF processes (Detection, Recall, Decision)"""
@staticmethod
def create(process_type: str, data: Dict[str, Any]) -> str:
"""Create process display card"""
icons = {
'detection': '🕵️♂️',
'recall': '🧠',
'decision': '🎯',
'safety': '🛡️',
'execution': '⚡',
'learning': '📚'
}
status_colors = {
'active': 'var(--color-success)',
'inactive': 'var(--colors-neutral-400)',
'error': 'var(--color-danger)'
}
icon = icons.get(process_type, '📊')
status = data.get('status', 'inactive')
title = data.get('title', process_type.title())
description = data.get('description', '')
# Metrics display
metrics_html = ""
if 'metrics' in data:
metrics = data['metrics']
metrics_html = ''
for key, value in metrics.items():
metrics_html += f"""
"""
metrics_html += '
'
# Next step
next_step_html = ""
if 'next_step' in data:
next_step_html = f"""
Next Step:
{data['next_step']}
"""
return f"""
{metrics_html}
{data.get('content', '')}
{next_step_html}
"""
# ===========================================
# DATA VISUALIZATION COMPONENTS
# ===========================================
class Chart(ModernComponent):
"""Wrapper for Plotly charts with consistent styling"""
@staticmethod
def create_line(data: Dict[str, Any], **kwargs) -> go.Figure:
"""Create a line chart with ARF styling"""
title = kwargs.get('title', '')
height = kwargs.get('height', 300)
fig = go.Figure()
# Add traces
for trace in data.get('traces', []):
fig.add_trace(go.Scatter(
x=trace.get('x', []),
y=trace.get('y', []),
mode=trace.get('mode', 'lines'),
name=trace.get('name', ''),
line=dict(
color=trace.get('color', 'var(--color-primary)'),
width=trace.get('width', 3)
),
fill=trace.get('fill', None)
))
# Update layout
fig.update_layout(
title={
'text': title,
'font': {
'size': 18,
'color': 'var(--colors-neutral-900)',
'family': 'var(--font-sans)'
}
},
height=height,
plot_bgcolor='white',
paper_bgcolor='white',
font={
'family': 'var(--font-sans)',
'color': 'var(--colors-neutral-700)'
},
margin=dict(l=40, r=20, t=60, b=40),
hovermode='x unified',
showlegend=kwargs.get('show_legend', True),
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="center",
x=0.5
)
)
# Update axes
fig.update_xaxes(
gridcolor='var(--colors-neutral-200)',
linecolor='var(--colors-neutral-300)',
title_font=dict(size=12)
)
fig.update_yaxes(
gridcolor='var(--colors-neutral-200)',
linecolor='var(--colors-neutral-300)',
title_font=dict(size=12)
)
return fig
@staticmethod
def create_gauge(value: float, **kwargs) -> go.Figure:
"""Create a gauge chart for metrics"""
title = kwargs.get('title', '')
min_val = kwargs.get('min', 0)
max_val = kwargs.get('max', 100)
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=value,
domain={'x': [0, 1], 'y': [0, 1]},
title={
'text': title,
'font': {
'size': 16,
'family': 'var(--font-sans)'
}
},
number={
'font': {
'size': 28,
'family': 'var(--font-sans)'
}
},
gauge={
'axis': {
'range': [min_val, max_val],
'tickwidth': 1,
'tickcolor': "var(--colors-neutral-700)"
},
'bar': {'color': "var(--color-primary)"},
'bgcolor': "white",
'borderwidth': 2,
'bordercolor': "var(--colors-neutral-300)",
'steps': [
{
'range': [min_val, max_val * 0.3],
'color': 'var(--color-success)'
},
{
'range': [max_val * 0.3, max_val * 0.7],
'color': 'var(--color-warning)'
},
{
'range': [max_val * 0.7, max_val],
'color': 'var(--color-danger)'
}
],
'threshold': {
'line': {'color': "var(--colors-neutral-900)", 'width': 4},
'thickness': 0.75,
'value': value
}
}
))
fig.update_layout(
height=300,
margin=dict(l=30, r=30, t=70, b=30),
paper_bgcolor='white',
font={
'family': 'var(--font-sans)'
}
)
return fig
# ===========================================
# RESPONSIVE UTILITIES
# ===========================================
class ResponsiveUtils:
"""Responsive design utilities"""
@staticmethod
def create_responsive_styles() -> str:
"""Generate responsive CSS utilities"""
return """
"""
@staticmethod
def create_mobile_navigation() -> str:
"""Create mobile-friendly navigation toggle"""
return """
☰
"""
# ===========================================
# ACCESSIBILITY ENHANCEMENTS
# ===========================================
class Accessibility:
"""Accessibility enhancements"""
@staticmethod
def create_skip_link() -> str:
"""Create skip to content link for keyboard users"""
return """
Skip to main content
"""
@staticmethod
def create_focus_management() -> str:
"""Focus management for modals and dialogs"""
return """
"""
@staticmethod
def create_aria_live_regions() -> str:
"""Create ARIA live regions for dynamic content"""
return """
"""
# ===========================================
# DARK MODE SUPPORT
# ===========================================
class DarkMode:
"""Dark mode toggle and management"""
@staticmethod
def create_toggle() -> str:
"""Create dark mode toggle with system preference detection"""
return """
☀️
🌙
"""
# ===========================================
# COMPONENT STYLES (CSS)
# ===========================================
def create_component_styles() -> str:
"""Create all component styles in one place"""
return """
"""
# ===========================================
# INITIALIZATION FUNCTION
# ===========================================
def initialize_modern_ui() -> str:
"""Initialize all modern UI components and styles"""
components = [
inject_design_tokens(),
create_component_styles(),
ResponsiveUtils.create_responsive_styles(),
Accessibility.create_skip_link(),
Accessibility.create_aria_live_regions(),
DarkMode.create_toggle(),
ResponsiveUtils.create_mobile_navigation(),
Accessibility.create_focus_management()
]
return "\n".join(components)
# ===========================================
# EXAMPLE USAGE (for documentation)
# ===========================================
def create_example_dashboard() -> str:
"""Create an example dashboard using modern components"""
# Example metrics
metrics = [
{"value": "42s", "label": "Detection Time", "trend": "down", "change": "↓ 90%"},
{"value": "94%", "label": "Recall Quality", "trend": "up", "change": "↑ 8%"},
{"value": "87%", "label": "Confidence Score", "trend": "neutral", "change": "→"},
{"value": "Dampening", "label": "Sequencing Stage", "trend": None}
]
# Example process data
detection_process = {
"status": "active",
"title": "Detection Process",
"description": "Telemetry analysis & pattern recognition",
"metrics": {
"Pattern Match": "Retry Amplification",
"Confidence": "92.7%",
"Detection Time": "0.8 seconds",
"Severity": "HIGH_VARIANCE"
},
"content": """
✅ Detected: Retry amplification pattern with exponential growth (r=1.8)
""",
"next_step": "Activate recall process"
}
# Build dashboard
dashboard = f"""
{initialize_modern_ui()}
Modern ARF Dashboard
{Grid.create_metric_grid(metrics)}
{ObservationGate.create(confidence=65.0)}
{ProcessDisplay.create('detection', detection_process)}
{SequencingFlow.create([
{"title": "Dampening", "description": "Prevent amplification first", "badge": "REQUIRED"},
{"title": "Concurrency", "description": "Manage load, then observe", "badge": "REQUIRED"},
{"title": "Observe", "description": "Validate trends for 5+ minutes", "badge": "REQUIRED"},
{"title": "Scale", "description": "Only if all previous succeed", "badge": "OPTIONAL"}
])}
{Card.create(
title="OSS Analysis",
content="Open source advisory intelligence",
footer="Apache 2.0 License",
variant="outlined",
border_color="var(--color-success)"
)}
{Card.create(
title="Enterprise Execution",
content="Commercial autonomous execution",
footer="Requires License",
variant="elevated"
)}
"""
return dashboard
# ===========================================
# EXPORT LIST
# ===========================================
__all__ = [
# Core components
'ModernComponent', 'Card', 'Button', 'Badge',
'Grid', 'Stack',
# ARF-specific components
'ObservationGate', 'SequencingFlow', 'ProcessDisplay',
# Visualization
'Chart',
# Utilities
'ResponsiveUtils', 'Accessibility', 'DarkMode',
# Initialization
'initialize_modern_ui', 'create_example_dashboard',
# Constants
'DESIGN_TOKENS'
]
# ===========================================
# TESTING CODE (Remove in production)
# ===========================================
if __name__ == "__main__":
# Test that components can be created
print("Testing modern components...")
# Create example dashboard
example = create_example_dashboard()
# Save to file for inspection
with open("modern_dashboard_example.html", "w") as f:
f.write(example)
print("✅ Modern components created successfully")
print("📄 Example saved to: modern_dashboard_example.html")