"""
ui/modern_components.py - ENHANCED VERSION
π Modern UI Components for ARF v3.3.9 with Complete Psychological Integration
Features:
1. Design token system with CSS variables
2. All psychological features (observation gate, sequencing, historical evidence, healing intent)
3. Accessibility (ARIA labels, keyboard nav)
4. Performance optimizations
5. Dark mode support
6. Integration with arf_modern_ui.py systems
"""
import json
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional, Tuple
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
# ===========================================
# DESIGN TOKEN SYSTEM - ALIGNED WITH arf_modern_ui.py
# ===========================================
DESIGN_TOKENS = {
"colors": {
"primary": {
"50": "#eff6ff",
"100": "#dbeafe",
"200": "#bfdbfe",
"300": "#93c5fd",
"400": "#60a5fa",
"500": "#3b82f6", # enterprise_primary
"600": "#2563eb",
"700": "#1d4ed8",
"800": "#1e40af",
"900": "#1e3a8a"
},
"success": {
"50": "#f0fdf4",
"100": "#dcfce7",
"200": "#bbf7d0",
"300": "#86efac",
"400": "#4ade80",
"500": "#22c55e", # success
"600": "#16a34a",
"700": "#15803d",
"800": "#166534",
"900": "#14532d"
},
"warning": {
"50": "#fffbeb",
"100": "#fef3c7",
"200": "#fde68a",
"300": "#fcd34d",
"400": "#fbbf24",
"500": "#f59e0b", # warning
"600": "#d97706",
"700": "#b45309",
"800": "#92400e",
"900": "#78350f"
},
"danger": {
"50": "#fef2f2",
"100": "#fee2e2",
"200": "#fecaca",
"300": "#fca5a5",
"400": "#f87171",
"500": "#ef4444", # danger
"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 ''}
"""
# ===========================================
# CRITICAL PSYCHOLOGICAL COMPONENTS
# ===========================================
class ObservationGate(ModernComponent):
"""Observation gate component showing system restraint - PSYCHOLOGICAL CORE"""
@staticmethod
def create(confidence: float = 65.0, **kwargs) -> str:
"""Create observation gate display with psychological restraint"""
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:
try:
frozen_dt = datetime.fromisoformat(frozen_until.replace("Z", "+00:00"))
now = datetime.now(timezone.utc)
if frozen_dt.tzinfo is None:
frozen_dt = frozen_dt.replace(tzinfo=timezone.utc)
time_left = frozen_dt - now
minutes_left = max(0, int(time_left.total_seconds() / 60))
countdown_html = f"""
Next evaluation:
{minutes_left}:00
"""
except:
countdown_html = """
"""
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)"
icon = "β³" if is_blocked else "β
"
# Psychological messaging
restraint_message = """
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%, so the system is enforcing an observation-first policy.
"What you are seeing is not waiting. It is judgment under uncertainty."
""" if is_blocked else """
Proceed with Policy Action
Confidence exceeds threshold. System may proceed with sequenced actions.
Historical evidence will be consulted before any execution.
"""
return f"""
{restraint_message}
Confidence Threshold
{threshold}%
Required for action
Current Confidence
{confidence:.1f}%
{"Below threshold β Observe" if is_blocked else "Above threshold β Proceed"}
{"Observe" if is_blocked else "Ready"} ({confidence:.1f}%)
Threshold ({threshold}%)
{"Act" if is_blocked else "Proceed"} (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 - PSYCHOLOGICAL CORE"""
@staticmethod
def create(steps: List[Dict[str, Any]] = None, **kwargs) -> str:
"""Create sequencing flow visualization"""
if steps is None:
steps = [
{"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"}
]
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.
"What happened is more important than what might happen."
"""
class ProcessDisplay(ModernComponent):
"""Display for ARF processes (Detection, Recall, Decision) - PSYCHOLOGICAL CORE"""
@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']}
"""
# Content with psychological emphasis
content_html = data.get('content', '')
if process_type == 'recall' and 'historical_evidence' in data:
content_html += f"""
π§
Recall Dominance: Historical evidence outweighs predictive confidence.
The system prioritizes what has happened over what might happen.
"""
return f"""
{metrics_html}
{content_html}
{next_step_html}
"""
class HistoricalEvidencePanel(ModernComponent):
"""Historical evidence panel - PSYCHOLOGICAL CORE (Recall Dominance)"""
@staticmethod
def create(evidence_data: Dict[str, Any] = None, **kwargs) -> str:
"""Create historical evidence panel showing recall dominance"""
if evidence_data is None:
evidence_data = {
"scaling_failures": [
{
"date": "2024-11-15",
"environment": "prod-east",
"action": "Scale during retry storm",
"outcome": "Amplification increased 300%",
"lesson": "Scaling during amplification worsens the problem"
},
{
"date": "2024-09-22",
"environment": "staging",
"action": "Add capacity without dampening",
"outcome": "45 min outage, $8.2K loss",
"lesson": "New capacity consumed by amplification loop"
}
],
"dampening_successes": [
{
"date": "2024-12-03",
"environment": "prod-west",
"action": "Request coalescing + backoff",
"outcome": "Resolved in 8 min, $5.1K saved",
"lesson": "Dampening broke amplification cycle"
},
{
"date": "2024-10-17",
"environment": "prod-eu",
"action": "Circuit breaker + observability",
"outcome": "12 min recovery, 0 user impact",
"lesson": "Sequencing prevented escalation"
}
]
}
# Build failures HTML
failures_html = ""
for i, failure in enumerate(evidence_data.get('scaling_failures', [])[:3]):
failures_html += f"""
Action: {failure.get('action', 'Unknown')}
Outcome: {failure.get('outcome', 'Unknown')}
"{failure.get('lesson', 'No lesson captured')}"
"""
# Build successes HTML
successes_html = ""
for i, success in enumerate(evidence_data.get('dampening_successes', [])[:3]):
successes_html += f"""
Action: {success.get('action', 'Unknown')}
Outcome: {success.get('outcome', 'Unknown')}
"{success.get('lesson', 'No lesson captured')}"
"""
return f"""
π§ Historical Evidence (Why Sequencing Matters)
Real outcomes from similar incidentsβthis evidence dominates decision logic
Historical evidence outweighs model confidence
β Scaling-First Failures
{failures_html if failures_html else '''
π
Scaling-First Failures (Evidence Present)
'''}
β
Dampening-First Successes
{successes_html if successes_html else '''
π
Dampening-First Successes (Evidence Present)
'''}
π―
If history shows failure, the system will not repeat it.
The system prioritizes historical evidence over predictive confidence.
If scaling-first failed in similar conditions, scaling is contraindicated regardless of model confidence.
"What happened is more important than what might happen."
"""
class HealingIntentDisplay(ModernComponent):
"""Formal HealingIntent display - PSYCHOLOGICAL CORE"""
@staticmethod
def create(healing_intent: Dict[str, Any], **kwargs) -> str:
"""Create formal HealingIntent display with all fields"""
confidence = healing_intent.get('confidence', 0.0)
primary_action = healing_intent.get('primary_action', '')
sequencing_rule = healing_intent.get('sequencing_rule', '')
preconditions = healing_intent.get('preconditions', [])
contraindications = healing_intent.get('contraindications', [])
reversibility = healing_intent.get('reversibility_statement', '')
historical_evidence = healing_intent.get('historical_evidence', [])
# Preconditions HTML
preconditions_html = ""
if preconditions:
preconditions_html = ""
for pre in preconditions:
preconditions_html += f"
β’ {pre}
"
preconditions_html += "
"
# Contraindications HTML
contraindications_html = ""
if contraindications:
contraindications_html = ""
for contra in contraindications:
contraindications_html += f"
β {contra}
"
contraindications_html += "
"
# Historical evidence HTML
historical_html = ""
if historical_evidence:
historical_html = ""
for evidence in historical_evidence:
historical_html += f"
π {evidence}
"
historical_html += "
"
return f"""
Primary Action
{primary_action}
Sequencing Rule
{sequencing_rule}
Preconditions
{preconditions_html if preconditions_html else '
No preconditions specified
'}
Contraindications
{contraindications_html if contraindications_html else '
No contraindications
'}
Reversibility Statement
{reversibility if reversibility else '
No reversibility statement
'}
{historical_html if historical_html else ''}
βοΈ
Doctrinal Principle: Formal Documentation Prevents Mistakes
Every HealingIntent must document preconditions, contraindications, and reversibility.
This formal structure ensures decisions are reviewable, reversible, and grounded in evidence.
"""
# ===========================================
# COMPONENT STYLES (CSS) - ENHANCED
# ===========================================
def create_component_styles() -> str:
"""Create all component styles with psychological enhancements"""
return """
"""
# ===========================================
# INITIALIZATION FUNCTION
# ===========================================
def initialize_modern_ui() -> str:
"""Initialize all modern UI components and styles"""
components = [
inject_design_tokens(),
create_component_styles(),
"""
"""
]
return "\n".join(components)
# ===========================================
# EXPORT LIST
# ===========================================
__all__ = [
# Core components
'ModernComponent', 'Card',
# CRITICAL PSYCHOLOGICAL COMPONENTS
'ObservationGate', 'SequencingFlow', 'ProcessDisplay',
'HistoricalEvidencePanel', 'HealingIntentDisplay',
# Design system
'DESIGN_TOKENS',
# Initialization
'initialize_modern_ui', 'inject_design_tokens', 'create_component_styles'
]