Engineer a real-time experimentation guardrail that blocks UX variants violating…
- User
Engineer a real-time experimentation guardrail that blocks UX variants violating accessibility or latency budgets.
- Assistant
The Challenge: The user wants a "real-time experimentation guardrail that blocks UX variants violating accessibility or latency budgets." This is a highly abstract, non-visual request. As a "code expert" and "advanced front-end designer," I need to translate this into a tangible, demonstrable interface or dashboard that represents such a system. It's not about implementing the backend logic; it's about designing the frontend that visualizes the guardrails, experiments, real-time metrics, and blocking actions.
My Role: I am a top-tier creative front-end engineer/designer. I need to deliver a single HTML file with embedded CSS/JS, using Tailwind CSS (likely via CDN), GSAP for animations, high-end visuals (dark mode, gradients, glassmorphism, noise, etc.), and interacting with mock data. The core is the "guardrail" concept. I need to make it feel like a sophisticated system.
Deconstructing the Request:
- Real-time experimentation: We have A/B tests running. Variants being served to users.
- Guardrail: This is the safety net. It monitors metrics (accessibility, latency). If a variant violates a threshold, the guardrail blocks it (kicks it out of the experiment or stops serving it).
- UX variants: Different versions of the UI.
- Violating accessibility or latency budgets: The two key metrics:
- Latency: e.g., Time to Interactive, LCP. Budgets like < 2s.
- Accessibility: e.g., contrast ratio, ARIA violations, keyboard nav issues.
- Blocks: The action taken.
The Interface Idea: I'm thinking of a "Command Center" or "A/B Experiment Operations Dashboard." Something that looks like a futuristic control room for product managers and engineers. It should show:
- Live Feed: A stream of incoming "events" or "checks" from experiments.
- Current Experiments: Cards representing active experiments, each with a health status (green/yellow/red) based on guardrail compliance.
- Guardrail Details: A panel showing the current thresholds (latency budget, a11y score) and how they are applied.
- Blocking Action: When a variant fails, there's a dramatic but elegant UI update: the variant card flashes red, maybe a "shields up" animation, and it gets quarantined (removed from active list, moved to a "blocked" section). This should be automatic, maybe triggered by a simulated event.
Design Language (Swiss/Minimal/Futuristic):
- Dark Theme: Deep blacks (#0a0a0a) with vibrant accent colors (neon blue for good, red/amber for alerts, purple for UI).
- Typography: Inter (sans-serif) for data, maybe Playfair Display for headings? Probably stick to Inter/Montserrat for a technical feel, large and bold.
- Layout: Bento grid would be perfect for the dashboard. A grid of metrics on top, a main list/grid of experiments below. Use a sidebar for controls/filters. Or a more integrated full-screen dashboard. Let's go with a full-screen, wide layout, using Tailwind's grid system.
- Visual Effects:
- Mesh gradients in the background (subtle).
- Glassmorphism panels (backdrop blur, thin borders).
- Noise texture overlay for grain.
- Smooth scrolling (lenis-like) but maybe simple.
- GSAP animations for entries, status updates.
- Custom cursor? Maybe a subtle ring.
- Dynamic Shadows/Depth: Cards with hover lift.
Technical Implementation Plan:
- HTML Structure:
- Container (full viewport, background with mesh gradient + noise).
- Header: Title "Aegis Guardrails" (Aegis = shield). Current time, status summary.
- Main Grid:
- Left Column: Statistics (Total Experiments, Variants, Blocked Count, Avg Latency, Avg a11y Score). Maybe some sparklines.
- Center Column: The "Experiment Feed" - list of active experiments with progress bars/variant cards showing real-time metrics.
- Right Column: "Guardrail Configuration" (threshold sliders), "Blocked Variants" log.
- Data Simulation:
- We'll generate mock experiments (name, variants A/B/C, current traffic split, current metrics: latency, accessibility score).
- We'll have a
setIntervalthat randomly updates metrics. Some variants will drift over threshold (budget violation). - When a variant's metric crosses the threshold, our "Guardrail" triggers: it visually "blocks" the variant (turns red, reduces traffic to 0, adds to blocked list) and shows a toast notification.
- This demonstrates the "real-time" and "blocking" aspect.
- GSAP Integration:
- Use GSAP for smooth entrance of elements.
- Use GSAP for animating metric updates (counters, width of progress bars).
- Use GSAP for the blocking effect (maybe a shockwave or a "shield" overlay).
- Tailwind CSS: Use the CDN. Configure custom colors in the
<script>tag for Tailwind to use our specific dark palette and gradients.
Refining the "Guardrail" Concept Visuals: Instead of just numbers, let's make the "latency" and "accessibility" visual within each variant card. For latency, a circular gauge or a vertical bar. For accessibility, a score with color coding. The "budget" is represented by a limit line.
When a block happens: Variant card gets a red border/glow. The traffic allocation bar shrinks to 0. A "BLOCKED" stamp appears. The card might get a slight blur or desaturation. The experiment's overall status changes to "Degraded" or "Quarantined".
The "Real-time" aspect: Numbers and small charts update continuously, like a stock ticker.
Design Details:
- Background: A dark radial gradient:
bg-gradient-to-br from-gray-900 via-slate-900 to-black. Overlay a faint SVG grain. - Glass panels:
bg-white/5 backdrop-blur-md border border-white/10. Rounded-2xl or rounded-3xl. - Typography:
font-sans. Headings: uppercase, tracking-widest, small text (like technical labels). - Accents: Cyan for good, Emerald for healthy, Rose/Red for danger, Amber for warning.
- Icons: Use Heroicons (svg) inline.
Step-by-Step implementation outline:
- Skeleton: HTML5 boilerplate with Tailwind CDN and GSAP CDN.
- Styles: Define custom font import (Inter). Add CSS for noise texture and maybe custom scrollbars. Define some utility classes in Tailwind config for gradients.
- Layout: Build the grid. Use
h-screenandoverflow-hiddento keep it app-like. Useflexandgrid. - Components:
- Header: Logo, Global status.
- StatPanel: 4-5 KPI cards.
- ExperimentList: A scrollable area containing experiment cards. Each card has experiment name, a grid of variant cards inside it.
- VariantCard: Shows variant name (A, B, C), a live LCP bar (horizontal with limit marker), an a11y score (circle gauge), traffic % (number), and status indicator.
- BlockedLog: A list of recently blocked variants with timestamps.
- Controls: Sliders for "Max Latency" and "Min a11y Score".
- JavaScript Logic:
- State: An array of experiment objects. Each experiment has an id, name, variants (array). Each variant has id, name, traffic, latency (LCP), a11yScore (0-100), status ('active', 'blocked').
- Config: Guardrail thresholds:
maxLatency: 2500(ms),minA11yScore: 90(percent). - Rendering: A function
renderExperiments()that clears the list and rebuilds DOM based on state. Initially populate with ~5 experiments, each with 2-3 variants. - Simulation Loop:
setInterval(e.g., every 2 seconds) that randomly adjusts latency/a11y for some active variants. Add some noise. - Guardrail Check: After each update, for each active variant, check:
if (variant.latency > config.maxLatency) blockVariant(variant, 'LATENCY')if (variant.a11yScore < config.minA11yScore) blockVariant(variant, 'A11Y')
- Blocking Logic:
- Set variant status = 'blocked'.
- Set traffic = 0.
- Add entry to BlockedLog with reason, timestamp.
- Update visuals (card border red, add overlay).
- Show a toast notification (
gsap.fromToa toast div). - Update KPIs (blocked count).
- Animation:
- Use GSAP to tween the traffic bar width and the LCP bar.
- When a card is blocked, animate a "pulse" or "shockwave".
- Smooth entrance of new elements.
- Configuration: Sliders update the
configobject and trigger a re-evaluation of all active variants (maybe unblock if they now meet thresholds? Or just future blocks? Usually guardrails are static thresholds, but for demo, we can allow adjustment). Let's make it so adjusting thresholds immediately re-checks all active variants. If a variant now passes, we could "unblock" it? Might be complicated. Simpler: thresholds only block, not unblock. Or we can allow unblocking manually. Let's just block and that's it; the blocked log stays. To keep it simple and deterministic, we'll not implement unblocking automatically; just block and stay blocked to show the effect.
Polish:
- Add a "noise" grain overlay using a fixed
divwith a base64 noise image or CSS gradient. - Use Tailwind's
preserve-3dandperspectivefor subtle 3D hover effects on cards. - Ensure fonts are loaded (Inter).
- Add tooltips or explanatory text for what the metrics mean.
Potential Pitfalls:
- DOM manipulation frequency: We are updating the DOM every 2 seconds for many numbers. Use GSAP to animate value changes rather than full re-render. We'll keep the DOM nodes and update their properties directly via references, not re-render entire list. This is more performant and allows smooth animations.
- So:
renderExperimentscreates the DOM once. ThenupdateMetricsfunction loops through data and targets specific DOM elements by ID to update width/text, with GSAP tweens.
Implementation Steps in Code:
- Setup: HTML head with Tailwind CDN (with custom theme colors), GSAP CDN, Google Fonts (Inter). Body with
bg-gray-950 text-white. - Background: Add a
divfor mesh gradient (using SVG filter or radial gradients). Add adivfor grain withmix-blend-mode: overlay. - UI Layout:
<nav>: top bar.<main>withgrid grid-cols-12 gap-6 p-6.- Left col (span 3): KPIs + Config + Blocked Log.
- Right col (span 9): Experiment Feed.
- KPIs Section: 4 small cards.
- Config Section: Two sliders (input range) with labels and current value display.
- Blocked Log: A list container.
- Experiment Feed: A grid container for experiment cards.
- Experiment Card Template: Each experiment card contains a header (name) and a grid of variant cards (3 columns inside). Variant card structure:
- Variant label (A/B/C).
- Metric row: LCP vs Budget (horizontal bar with marker).
- A11y score: maybe a semi-circle gauge using SVG stroke-dasharray.
- Traffic %: large number.
- Status: dot (green/red).
- JavaScript:
- Define
experimentsarray. - Helper function to create gauge arcs.
init(): Render everything.createExperimentCardDOM(exp): returns DOM element, store references in a mapdomRefs[expId][varId]for updates.simulate():setIntervalpicks random active variant, adds random walk to metrics.checkGuardrails(variant): compare to thresholds. If violation, callblockVariant.blockVariant(variant, reason): update data, update DOM (set status red, traffic to 0, animate), add to blocked log.- GSAP tweens: Use
gsap.tofor smooth transitions of bar widths and numbers.
- Define
Visual Polish:
- Variant card default border:
border-gray-800. When blocked:border-red-500glow. - LCP bar: a background track (gray), a fill (cyan). Budget limit line (dashed white vertical line at threshold position).
- A11y gauge: use
conic-gradientor SVG circle. Let's use a simple circle withstroke-dasharray. Green if > threshold, red if below. - Use
clsxor template strings for conditional classes.
Let's write code. I need to be meticulous with Tailwind classes to achieve the high-end look. I'll use:
bg-gray-950text-gray-100border-white/10bg-white/[0.03]backdrop-blur-xlshadow-xl shadow-cyan-500/10etc.
Mesh Gradient Background: Since I can't use external images, I'll create a CSS/SVG mesh. Maybe use a large blurry colored circles with absolute positioning and mix-blend-screen. Or a Tailwind gradient like
bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900. I'll add a noise overlay using a tiny base64 noise or a CSS radial gradient trick. I can generate a noise pattern with data URI or use a simple repeating linear gradient to simulate grain. I'll use a small base64 noise image to be safe.Icons: Use Heroicons SVG strings directly. Shield lock, warning, etc.
Narrative: The page title: "AEGIS // Real-time Guardrail System". Subtitle: "Protecting user experience through latency & accessibility compliance."
Let's build.
Self-Correction during thought process: The user wants "blocks UX variants violating accessibility or latency budgets." So the system must block. It should also likely show that it's blocking. The interface should feel authoritative, precise.
We need to make sure the simulation is visible. The metrics should update every second or two. When they cross the threshold, the block should happen immediately. The visual feedback should be distinct.
A11y Score Representation: Usually a11y is a composite of contrast, ARIA, etc. We'll use a 0-100 score. Threshold is, say, 90. So gauge fill = score%. Color changes when crossing threshold.
Latency: LCP (ms). Threshold is, say, 2500ms. Bar fill is LCP value relative to some max for scaling (maybe 5000ms). The limit marker is at
(2500/5000)*100%width.Blocked Log: Should show timestamp, experiment name, variant, reason, and maybe the offending metric value.
To avoid complexity of "unblocking", once blocked, variant stays blocked. But we might want to show that the guardrail "kicks" it out. So we could animate the traffic bar shrinking to zero and the card dimming.
Let's start coding. I'll structure the single HTML file with embedded CSS and JS.
Key Classes & Design Elements:
font-sanswithInter.tracking-tightfor numbers.uppercase text-xs tracking-widest text-gray-400for labels.- Cards:
rounded-2xl p-4 bg-white/5 border border-white/10. - Buttons:
px-4 py-2 rounded-full bg-white/10 hover:bg-white/20 transition. - Sliders: custom style for range input (dark).
Implementation Steps:
- HTML head: Tailwind via CDN with config for colors. Google Fonts. GSAP.
- Body: background with grain, gradient blobs.
- Layout: Header, Stats row (flex), Main grid (sidebars + feed).
- JS: Data model, render function, simulation loop, event listeners for sliders.
- Add "shockwave" effect using a CSS radial animation triggered on block.
Refining the "Guardrail" Particles: Maybe add subtle floating particles in background using canvas? Could overcomplicate. The prompt mentions "3D particle effects or point cloud" to enhance depth if content sparse. Our dashboard is content-rich, but background could still have subtle particles. I'll add a simple Canvas-based particle system for a "network" effect, very minimal, faint white dots connecting. That's a nice touch.
Let's incorporate Three.js? Prompt says "can combine threejs". But we want to keep it single file and not too heavy. Canvas particles are fine. But for "top-tier" and "3D point cloud or particle effects", maybe use a tiny three.js scene for background: points slowly rotating. That would be impressive. I'll do a full-screen canvas behind everything with a simple three.js particle system. It's doable with CDN links. We'll have a scene with many small white/cyan particles, slow rotation, responsive to mouse slightly. This adds that "space depth" mentioned.
Decision: Use Three.js for a subtle background particle field. It's a single file, we can use module version from unpkg.
Structure of JS:
- Inline script type="module".
- Import Three.js from unpkg.
- Create scene, camera, renderer.
- Create BufferGeometry with points.
- Animate loop.
But wait: We also need GSAP for UI. That's fine.
Now, let's write the code in detail.
I'll aim for about 600-800 lines of code? It's okay.
Detailed UI Design:
- Header: Left: "AEGIS" in big bold font (maybe Inter Black). Right: Status "SYSTEM ACTIVE", latency threshold display, a11y threshold display.
- Stats: 4 cards: Active Experiments, Total Variants, Guardrail Blocks (red), Avg LCP.
- Left Sidebar (below Stats): Configuration: two sliders with labels "Maximum Latency (ms)" and "Minimum Accessibility Score". Also a toggle for "Auto-Remediation"? Not needed. Then a "Blocked Log" panel that appends entries.
- Main Feed: Cards for each experiment.
- Experiment Card:
- Header: Experiment name, maybe a toggle for "Monitoring" (just visual).
- Body: Grid of variant cards (3 cols). Each:
- Top: Variant code (A, B, Control). Traffic % badge.
- Middle: A11y gauge (circular, maybe using SVG with stroke-dasharray). Also numeric score.
- Below: LCP bar: a horizontal bar with fill representing latency, a dashed line for budget. Also numeric LCP.
- Footer: Status text or icon.
- Experiment Card:
- Blocked Log: each entry: time, experiment-variant, reason (e.g., "Latency > 2500ms"), metric value.
Colors:
- Background:
#0a0a0a(very dark). - Panel BG:
rgba(15, 15, 20, 0.6)with blur. - Border:
rgba(255,255,255,0.08). - Accent:
- Good/Cyan:
#06b6d4(cyan-500) - Warning/Amber:
#f59e0b(amber-500) - Danger/Rose:
#f43f5e(rose-500)
- Good/Cyan:
- Text:
#e5e7eb(gray-200) and#9ca3af(gray-400).
Fonts: Google Fonts: Inter (weights: 300,400,600,800). I'll use
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap');Noise Texture: I'll create a small base64 noise pattern:
data:image/svg+xml;base64,...It's a tiny SVG with filter noise. That's reliable.Three.js Background: I'll put a canvas
id="bg-canvas"fixed at z-0. All content relative z-10. The particles will be white with low opacity.Let's draft the code structure:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Aegis Guardrail System</title> <!-- Tailwind --> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { colors: { dark: '#0a0a0a', panel: 'rgba(18, 18, 22, 0.6)', accent: { cyan: '#00f0ff', rose: '#ff2a6d', amber: '#ffb86c', green: '#50fa7b' } }, fontFamily: { sans: ['Inter', 'sans-serif'] }, backdropBlur: { xs: '2px', } } } } </script> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <!-- GSAP --> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <!-- Three.js (module) --> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js" } } </script> <style> body { margin: 0; overflow: hidden; background: #0a0a0a; color: #e5e7eb; font-family: 'Inter', sans-serif; } .noise { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; opacity: 0.03; background-image: url("data:image/svg+xml,..."); } #bg-canvas { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; } .glass-panel { background: rgba(20, 20, 25, 0.6); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.08); border-radius: 1rem; } /* Custom scrollbar */ ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: #333; border-radius: 3px; } </style> </head> <body> <!-- Canvas for Three.js particles --> <canvas id="bg-canvas"></canvas> <!-- Noise overlay --> <div class="noise"></div> <!-- UI Container --> <div class="relative z-10 flex flex-col h-screen p-6"> <!-- Header --> <header class="flex justify-between items-center mb-6"> <div> <h1 class="text-2xl font-bold tracking-tight text-white">AEGIS <span class="text-cyan-400">GUARDRAIL</span></h1> <p class="text-xs text-gray-500 uppercase tracking-widest">Real-time Experimentation Safety System</p> </div> <div class="flex items-center gap-4"> <div class="glass-panel px-4 py-2 flex items-center gap-2"> <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div> <span class="text-sm font-medium">SYSTEM ACTIVE</span> </div> <div class="text-xs text-gray-400 font-mono" id="clock">00:00:00 UTC</div> </div> </header> <!-- KPI Row --> <div class="grid grid-cols-4 gap-4 mb-6"> <div class="glass-panel p-4"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Active Experiments</div> <div class="text-2xl font-bold" id="stat-active-exp">0</div> </div> <div class="glass-panel p-4"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Total Variants</div> <div class="text-2xl font-bold" id="stat-total-variants">0</div> </div> <div class="glass-panel p-4"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Guardrail Blocks</div> <div class="text-2xl font-bold text-rose-500" id="stat-blocks">0</div> </div> <div class="glass-panel p-4"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Avg LCP (ms)</div> <div class="text-2xl font-bold" id="stat-avg-lcp">0</div> </div> </div> <!-- Main Grid --> <div class="grid grid-cols-12 gap-6 flex-1 overflow-hidden"> <!-- Left Sidebar (Config + Log) --> <aside class="col-span-3 flex flex-col gap-6 overflow-y-auto pr-2"> <!-- Config --> <div class="glass-panel p-5"> <h3 class="text-sm font-bold text-white mb-4 uppercase tracking-wider">Guardrail Thresholds</h3> <!-- Latency --> <div class="mb-4"> <label class="flex justify-between text-xs text-gray-400 mb-2"> <span>Max Latency (LCP)</span> <span id="latency-threshold-display" class="text-cyan-400">2500 ms</span> </label> <input type="range" id="latency-slider" min="1000" max="5000" step="100" value="2500" class="w-full h-1 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-400"> </div> <!-- A11y --> <div> <label class="flex justify-between text-xs text-gray-400 mb-2"> <span>Min Accessibility Score</span> <span id="a11y-threshold-display" class="text-cyan-400">90</span> </label> <input type="range" id="a11y-slider" min="50" max="100" step="1" value="90" class="w-full h-1 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-400"> </div> </div> <!-- Blocked Log --> <div class="glass-panel p-5 flex-1 flex flex-col min-h-0"> <h3 class="text-sm font-bold text-white mb-2 uppercase tracking-wider">Blocked Variants</h3> <div id="blocked-log" class="flex-1 overflow-y-auto space-y-2 text-sm"> <!-- Entries go here --> </div> </div> </aside> <!-- Center Feed --> <main class="col-span-9 overflow-y-auto pr-2" id="experiment-feed"> <!-- Experiment cards injected here --> </main> </div> </div> <!-- Toast Container --> <div id="toast-container" class="fixed bottom-8 right-8 z-50 flex flex-col gap-2"></div> <!-- Scripts --> <script type="module"> import * as THREE from 'three'; // ... Three.js setup ... </script> <script> // App logic // ... data, simulation, rendering ... </script> </body> </html>Now, we need to flesh out each part:
Three.js Background:
- Scene, Camera (perspective), Renderer (alpha: true).
- Particles: geometry with random positions within a range. Material: PointsMaterial with small size, cyan/white color, low opacity.
- Animation: rotate slowly, maybe slight wave movement.
- Resize handler.
HTML Components Details:
Variant Card:
<div class="variant-card glass-panel p-4 relative transition-all duration-300" data-id="v-123"> <div class="flex justify-between items-start mb-3"> <span class="text-xs font-bold uppercase tracking-widest text-gray-400">Variant A</span> <span class="text-xs font-mono bg-white/10 px-2 py-0.5 rounded">12%</span> </div> <!-- A11y Score Gauge --> <div class="flex items-center justify-center mb-3"> <svg class="w-16 h-16" viewBox="0 0 36 36"> <path class="track" d="..." fill="none" stroke="#333" stroke-width="3" /> <path class="fill" d="..." fill="none" stroke="#00f0ff" stroke-width="3" stroke-dasharray="0, 100" /> </svg> <div class="absolute text-sm font-bold">97</div> </div> <!-- LCP Bar --> <div class="mb-2"> <div class="flex justify-between text-xs text-gray-500 mb-1"> <span>LCP</span> <span>1800ms</span> </div> <div class="h-2 bg-gray-800 rounded-full overflow-hidden relative"> <div class="h-full bg-cyan-400" style="width: 36%"></div> <div class="absolute top-0 bottom-0 w-0.5 bg-white border-l border-dashed border-white/50" style="left: 50%"></div> <!-- threshold marker --> </div> </div> <!-- Status --> <div class="absolute bottom-4 right-4"> <svg class="w-4 h-4 text-green-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg> </div> </div>When blocked:
- Add class
border-rose-500/50,bg-rose-500/5. - Overlay with diagonal lines or "BLOCKED" text? Maybe add a red badge.
- Hide traffic % or set to 0.
- Dim rest.
Guardrail Simulation:
- We'll randomly pick an active variant and jitter metrics.
- Latency: base around 1500-3000. A11y: base around 85-100.
- To cause blocks, we can make some variants have a tendency to degrade. Or just chance.
- But to make it interesting, we want to see a block happen within a few minutes? The demo might be short. We can speed up: increase metrics drastically after a while for one variant. For example, after 10 seconds, push LCP of a specific variant over threshold. That would be a controlled demo. But random is okay, we might get blocks quickly if thresholds are set low. Let's set thresholds reasonable (latency 2500, a11y 90). Start variants with healthy values. Then every tick (2s), there's a small chance (like 5%) to add a large spike to latency or drop a11y. That should occasionally trigger block.
Data persistence: Not needed.
Traffic Split: We'll have a traffic distribution that sums to 100% per experiment. When a variant gets blocked, we redistribute its traffic to other variants? In real A/B platform, you'd pause. For simplicity, we just set its traffic to 0 and maybe others stay. We'll not auto-redistribute for display clarity.
Blocked Log:
- Append items with timestamp (simulated). Use GSAP to animate entry (slide in, fade).
Sliders:
- Update threshold display and data thresholds.
- When threshold changes, we could re-evaluate all active variants: if a variant's metric is now below new threshold, it becomes valid (but since it's already blocked, we might not unblock). To avoid confusion, we'll not unblock automatically. But if we lower the latency threshold, previously blocked may still be over limit. That's fine.
We need to make sure the gauge animation works:
- The circle circumference = 2 * pi * r. With r=16 (approx 100 width), circumference ~100.4. So dasharray = score, circumference. Fill 0 initially then animate to new.
Update Loop: Instead of full re-render, we will store DOM references. When metrics change:
- Find the variant card by data-id.
- Update the numeric text (with GSAP flip or just set).
- Update bar width with GSAP:
gsap.to(lcpFill, { width: newPercent + "%", duration: 0.5, ease: "power2.out" }). - Update gauge stroke-dashoffset.
GSAP for numbers: We can use a simple tween on a proxy object to update text.
Let's implement the code carefully.
Base64 noise: I'll create an SVG with a filter:
<svg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'><filter id='noise'><feTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/></filter><rect width='100' height='100' filter='url(#noise)' opacity='0.5'/></svg>. Then encode.But simpler: use CSS radial gradient to create grain? Not easy. I'll generate base64 offline? I can include a tiny data URI in code. I'll create a small pattern: a 1x1 transparent GIF? Not good. I'll use a simple CSS trick:
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.05'/%3E%3C/svg%3E");That will work.Three.js:
- Scene, perspective camera 75, aspect = window.inner/inner, near 0.1, far 1000.
- Renderer set size, alpha: true.
- Create particles: Random positions in a cube.
- Add to scene.
- Animate: rotate group.
- Use
requestAnimationFrame. - Also add mouse interaction: maybe particles move slightly toward mouse? That adds the "interactive" feel.
Now, writing the full code. I'll produce a single HTML file.
I'll ensure the code is extremely clean, with comments explaining parts.
Potential issues:
- Tailwind CDN might not support arbitrary values like
bg-white/5. That's fine. - The sliders: need custom styling to look good on dark. Use accent-cyan-400.
- When updating traffic percentage, we need to animate the width of the bar representing traffic? Actually traffic % is just a number, not a bar. But we could add a small bar. I'll just show the number.
A11y gauge: I'll use a simple circle:
<svg class="w-12 h-12 transform -rotate-90"> <circle cx="24" cy="24" r="16" stroke="currentColor" stroke-width="4" fill="none" class="text-gray-700"/> <circle cx="24" cy="24" r="16" stroke="currentColor" stroke-width="4" fill="none" class="text-cyan-400" stroke-dasharray="100" stroke-dashoffset="3"/> </svg>. Then we set stroke-dashoffset to 100 - score (if circumference is 100). To get circumference 100, set r=15.915 (approx) but easier: use stroke-dasharray: score, 100. Actually we can usestroke-dasharraywith the circumference value (2pir). Let's calculate: r=12, circumference ~75.4. So set dasharray="75.4". Then offset = circumference - (score/100)*circumference. I'll compute dynamically.Let's generate the code. I'll include all CSS in style tag, and JS at bottom.
Ensure no external dependencies failure: Use reliable CDNs:
- Tailwind:
https://cdn.tailwindcss.com(works) - GSAP:
https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js - Three.js:
https://unpkg.com/three@0.160.0/build/three.module.js
Now, produce final solution. I'll write the HTML with embedded code.
I'll also include a master "Guardrail" object in JS to manage state.
Let's write step-by-step in the actual answer.
One more thought: The header should have a "threshold display" updating when sliders move.
Blocked variant visual:
- Add a "BLOCKED" badge overlapping the card. Use absolute positioning.
- Or change the border to red and add a lock icon.
Toast notifications:
- Create a container fixed bottom right. When block happens, create a div with glass panel, show reason, animate in (from right), then after some seconds animate out and remove.
A11y:
- The gauge could change color from green to red when below threshold. We'll set stroke color based on score vs threshold.
LCP bar:
- The budget line should be static based on threshold. The fill represents current LCP relative to max scale (maybe 5s). We need to compute max LCP for scaling. We can set max = 5000ms. Then width% = (LCP/5000)*100. The budget marker at (threshold/5000)*100.
Update loop:
- Every 2 seconds: for each active variant, random walk:
- Latency: ± 100ms, but can also spike (set to threshold+200). Use a probability.
- A11y: ± 1, but can dip.
We need to avoid variant being blocked repeatedly. Once blocked, we skip it.
Let's code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AEGIS // Real-time Guardrail System</title> <!-- Tailwind CSS --> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { colors: { dark: '#0a0a0a', panel: 'rgba(18, 18, 22, 0.6)', accent: { cyan: '#00f0ff', rose: '#ff2a6d', amber: '#ffb86c', green: '#50fa7b' } }, fontFamily: { sans: ['Inter', 'sans-serif'] }, backgroundImage: { 'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))', } } } } </script> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <!-- GSAP --> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <!-- Three.js (ES Module) --> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js" } } </script> <style> /* Global Styles */ body { margin: 0; overflow: hidden; background-color: #050505; color: #e5e7eb; font-family: 'Inter', sans-serif; -webkit-font-smoothing: antialiased; } /* Noise Overlay */ .noise { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; opacity: 0.04; background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E"); } /* Background Canvas */ #bg-canvas { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; } /* Glassmorphism Panels */ .glass-panel { background: rgba(20, 20, 25, 0.6); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 1rem; box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3); } /* Custom Range Slider */ input[type=range] { -webkit-appearance: none; background: transparent; } input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; height: 16px; width: 16px; border-radius: 50%; background: #00f0ff; cursor: pointer; margin-top: -6px; box-shadow: 0 0 10px rgba(0, 240, 255, 0.5); } input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 4px; cursor: pointer; background: #374151; border-radius: 2px; } input[type=range]:focus { outline: none; } /* Scrollbar */ ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background: #4b5563; } /* LCP Bar Budget Marker */ .budget-marker { position: absolute; top: 0; bottom: 0; width: 2px; background: repeating-linear-gradient( to bottom, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.8) 2px, transparent 2px, transparent 4px ); } /* Blocked overlay */ .blocked-overlay { background: repeating-linear-gradient( -45deg, rgba(255, 42, 109, 0.1), rgba(255, 42, 109, 0.1) 5px, rgba(255, 42, 109, 0.05) 5px, rgba(255, 42, 109, 0.05) 10px ); } /* Animations */ @keyframes pulse-border { 0% { box-shadow: 0 0 0 0 rgba(255, 42, 109, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(255, 42, 109, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 42, 109, 0); } } .blocked-card { animation: pulse-border 2s infinite; } </style> </head> <body> <!-- Three.js Background --> <canvas id="bg-canvas"></canvas> <!-- Grain Overlay --> <div class="noise"></div> <!-- Main UI Container --> <div class="relative z-10 flex flex-col h-screen p-6 select-none"> <!-- Header --> <header class="flex justify-between items-center mb-6"> <div> <h1 class="text-2xl font-extrabold tracking-tight text-white flex items-center gap-2"> AEGIS <span class="text-cyan-400 text-lg align-top opacity-80">v2.4</span> </h1> <p class="text-xs text-gray-400 uppercase tracking-widest">Real-time Experimentation Guardrail</p> </div> <div class="flex items-center gap-4"> <div class="glass-panel px-4 py-2 flex items-center gap-2"> <div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div> <span class="text-sm font-medium text-gray-200">SYSTEM ACTIVE</span> </div> <div class="text-xs text-gray-400 font-mono bg-black/40 px-3 py-2 rounded border border-white/10" id="clock">00:00:00 UTC</div> </div> </header> <!-- KPI Row --> <div class="grid grid-cols-4 gap-4 mb-6"> <div class="glass-panel p-4 transition hover:border-cyan-500/30"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Active Experiments</div> <div class="text-2xl font-bold font-mono text-cyan-300" id="stat-active-exp">0</div> </div> <div class="glass-panel p-4 transition hover:border-cyan-500/30"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Total Variants</div> <div class="text-2xl font-bold font-mono text-white" id="stat-total-variants">0</div> </div> <div class="glass-panel p-4 transition hover:border-rose-500/30"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Guardrail Blocks</div> <div class="text-2xl font-bold font-mono text-rose-500" id="stat-blocks">0</div> </div> <div class="glass-panel p-4 transition hover:border-cyan-500/30"> <div class="text-xs text-gray-400 uppercase tracking-wider mb-1">Avg LCP (ms)</div> <div class="text-2xl font-bold font-mono text-white" id="stat-avg-lcp">0</div> </div> </div> <!-- Main Grid --> <div class="grid grid-cols-12 gap-6 flex-1 overflow-hidden"> <!-- Left Sidebar --> <aside class="col-span-3 flex flex-col gap-6 overflow-y-auto pr-2 custom-scrollbar pb-8"> <!-- Configuration --> <div class="glass-panel p-5"> <h3 class="text-sm font-bold text-white mb-4 uppercase tracking-wider flex items-center gap-2"> <svg class="w-4 h-4 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg> Thresholds </h3> <!-- Latency Threshold --> <div class="mb-5 group"> <label class="flex justify-between text-xs text-gray-400 mb-2"> <span>Max Latency (LCP)</span> <span id="latency-threshold-display" class="text-cyan-400 font-mono">2500 ms</span> </label> <input type="range" id="latency-slider" min="1000" max="5000" step="100" value="2500" class="w-full h-1 bg-gray-700 rounded-lg appearance-none cursor-pointer hover:accent-cyan-400 transition-colors"> <div class="flex justify-between text-[10px] text-gray-600 mt-1"> <span>1s</span> <span>5s</span> </div> </div> <!-- A11y Threshold --> <div> <label class="flex justify-between text-xs text-gray-400 mb-2"> <span>Min Accessibility Score</span> <span id="a11y-threshold-display" class="text-cyan-400 font-mono">90</span> </label> <input type="range" id="a11y-slider" min="50" max="100" step="1" value="90" class="w-full h-1 bg-gray-700 rounded-lg appearance-none cursor-pointer hover:accent-cyan-400 transition-colors"> <div class="flex justify-between text-[10px] text-gray-600 mt-1"> <span>50</span> <span>100</span> </div> </div> </div> <!-- Blocked Log --> <div class="glass-panel p-5 flex flex-col flex-1 min-h-0"> <h3 class="text-sm font-bold text-white mb-2 uppercase tracking-wider flex items-center gap-2"> <svg class="w-4 h-4 text-rose-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg> Block Log </h3> <div id="blocked-log" class="flex-1 overflow-y-auto space-y-2 text-xs font-mono relative"> <!-- Log entries will appear here --> <div class="text-gray-500 text-center italic mt-4">No blocks yet.</div> </div> </div> </aside> <!-- Main Feed --> <main class="col-span-9 overflow-y-auto pr-2 pb-8" id="experiment-feed"> <!-- Experiment Cards will be injected here --> <div class="flex items-center justify-center h-full text-gray-500 opacity-50"> <div class="text-center"> <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500 mx-auto mb-4"></div> <p>Initializing Guardrail System...</p> </div> </div> </main> </div> </div> <!-- Toast Container --> <div id="toast-container" class="fixed bottom-8 right-8 z-50 flex flex-col gap-3 pointer-events-none"></div> <!-- JavaScript --> <script type="module"> import * as THREE from 'three'; // ========================================== // 1. THREE.JS BACKGROUND (PARTICLES) // ========================================== const initThreeJS = () => { const canvas = document.getElementById('bg-canvas'); const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); const scene = new THREE.Scene(); // Fog for depth scene.fog = new THREE.FogExp2(0x050505, 0.002); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 30; // Particles const particlesGeometry = new THREE.BufferGeometry(); const particleCount = 700; const positions = new Float32Array(particleCount * 3); const colors = new Float32Array(particleCount * 3); const sizes = new Float32Array(particleCount); const color1 = new THREE.Color(0x00f0ff); // cyan const color2 = new THREE.Color(0x888888); // gray for (let i = 0; i < particleCount; i++) { // Random spread in a large volume positions[i * 3] = (Math.random() - 0.5) * 100; positions[i * 3 + 1] = (Math.random() - 0.5) * 100; positions[i * 3 + 2] = (Math.random() - 0.5) * 100; // Mix colors const mixRatio = Math.random(); const mixedColor = color1.clone().lerp(color2, mixRatio * 0.7); colors[i * 3] = mixedColor.r; colors[i * 3 + 1] = mixedColor.g; colors[i * 3 + 2] = mixedColor.b; sizes[i] = Math.random() * 2; } particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); particlesGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); particlesGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); // Material (using points material) const particlesMaterial = new THREE.PointsMaterial({ size: 0.4, vertexColors: true, transparent: true, opacity: 0.8, sizeAttenuation: true }); const particleSystem = new THREE.Points(particlesGeometry, particlesMaterial); scene.add(particleSystem); // Mouse interaction let mouseX = 0, mouseY = 0; const windowHalfX = window.innerWidth / 2; const windowHalfY = window.innerHeight / 2; document.addEventListener('mousemove', (event) => { mouseX = (event.clientX - windowHalfX) / 100; mouseY = (event.clientY - windowHalfY) / 100; }); // Animation Loop const animate = () => { requestAnimationFrame(animate); // Rotate entire system slowly particleSystem.rotation.y += 0.0005; particleSystem.rotation.x += 0.0002; // Subtle camera movement based on mouse camera.position.x += (mouseX - camera.position.x) * 0.05; camera.position.y += (-mouseY - camera.position.y) * 0.05; camera.lookAt(scene.position); renderer.render(scene, camera); }; animate(); // Resize window.addEventListener('resize', () => { const width = window.innerWidth; const height = window.innerHeight; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); }; // ========================================== // 2. APPLICATION STATE & CONFIG // ========================================== const state = { thresholds: { latency: 2500, // ms a11y: 90 // score 0-100 }, experiments: [], totalBlocks: 0 }; // Generate mock experiments const generateData = () => { const expNames = ['Hero-CTA-Color', 'Pricing-Page-Layout', 'Nav-Mega-Menu', 'Checkout-Flow-2', 'Footer-Revamp']; const experiments = []; expNames.forEach((name, i) => { const variantCount = 2 + Math.floor(Math.random() * 2); // 2-3 variants const variants = []; let trafficSum = 0; for (let j = 0; j < variantCount; j++) { // Initial healthy metrics const isControl = (j === 0); const latency = isControl ? 1200 : 1400 + Math.random() * 400; const a11y = 92 + Math.random() * 7; const traffic = isControl ? 50 : Math.floor(30 / (variantCount - 1)); trafficSum += traffic; variants.push({ id: `${i}-${j}`, name: isControl ? 'Control' : `Variant ${String.fromCharCode(65 + j)}`, stats: { latency: Math.round(latency), a11y: parseFloat(a11y.toFixed(1)) }, traffic: traffic, status: 'active', // active, blocked blockReason: null }); } // Normalize traffic to 100% roughly const remainder = 100 - trafficSum; if (remainder > 0) variants[0].traffic += remainder; experiments.push({ id: `exp-${i}`, name: name, variants: variants }); }); state.experiments = experiments; updateKPI(); renderFeed(); }; // ========================================== // 3. DOM RENDERING // ========================================== const feedContainer = document.getElementById('experiment-feed'); const blockedLogContainer = document.getElementById('blocked-log'); const clockEl = document.getElementById('clock'); // Helper: Circle gauge data const circleCircumference = 2 * Math.PI * 12; // r=12 const createGaugePath = (score, threshold) => { const percent = score / 100; const dash = percent * circleCircumference; const offset = circleCircumference - dash; return { dash, offset }; }; // Build SVG for A11y gauge const buildGaugeSVG = (score, isBlocked) => { // Determine color based on score vs threshold const passes = score >= state.thresholds.a11y; const color = isBlocked ? '#ff2a6d' : (passes ? '#50fa7b' : '#ffb86c'); const { dash, offset } = createGaugePath(score, state.thresholds.a11y); return ` <svg class="w-12 h-12 transform -rotate-90" viewBox="0 0 28 28"> <circle cx="14" cy="14" r="12" stroke="currentColor" stroke-width="4" fill="none" class="text-gray-700 opacity-30"></circle> <circle cx="14" cy="14" r="12" stroke="currentColor" stroke-width="4" fill="none" class="transition-all duration-500" style="stroke-dasharray: ${circleCircumference}; stroke-dashoffset: ${offset}; stroke: ${color};"></circle> </svg> `; }; // Build LCP Bar HTML const buildLCPBar = (latency) => { // Scale: 0 - 5000ms -> 0-100% const maxScale = 5000; const percent = Math.min((latency / maxScale) * 100, 100); const budgetPos = (state.thresholds.latency / maxScale) * 100; let fillColor = '#00f0ff'; // cyan if (latency > state.thresholds.latency + 500) fillColor = '#ff2a6d'; else if (latency > state.thresholds.latency) fillColor = '#ffb86c'; return ` <div class="relative h-2 bg-gray-800 rounded-full overflow-hidden"> <div class="h-full transition-all duration-500" style="width: ${percent}%; background: ${fillColor}"></div> <div class="budget-marker" style="left: ${budgetPos}%"></div> </div> `; }; // Render the entire feed const renderFeed = () => { feedContainer.innerHTML = ''; if (state.experiments.length === 0) { feedContainer.innerHTML = `<div class="text-gray-500">No experiments.</div>`; return; } state.experiments.forEach(exp => { const expCard = document.createElement('div'); expCard.className = 'glass-panel p-5 mb-4'; expCard.innerHTML = ` <div class="flex justify-between items-end mb-4 border-b border-white/5 pb-2"> <div> <h2 class="text-sm font-bold text-gray-200 uppercase tracking-widest">${exp.name}</h2> <div class="text-xs text-gray-500 mt-1 font-mono">EXP ID: ${exp.id}</div> </div> <div class="text-xs font-mono text-cyan-400"> STATUS: <span class="${exp.variants.some(v => v.status === 'blocked') ? 'text-rose-500' : 'text-green-400'}"> ${exp.variants.every(v => v.status === 'blocked') ? 'QUARANTINED' : 'MONITORING'} </span> </div> </div> <div class="grid grid-cols-1 md:grid-cols-3 gap-4"> ${exp.variants.map(v => ` <div class="variant-card glass-panel p-4 relative transition-all duration-300 group ${v.status === 'blocked' ? 'border-rose-500/50 bg-rose-500/5 blocked-card' : 'border-white/5'} " data-id="${v.id}" data-exp="${exp.id}"> ${v.status === 'blocked' ? ` <div class="absolute inset-0 flex items-center justify-center pointer-events-none z-10 overflow-hidden"> <div class="blocked-overlay absolute inset-0"></div> <div class="relative bg-rose-500/90 text-white font-bold text-xs px-4 py-2 rounded shadow-lg transform rotate-[-20deg] border-2 border-rose-300 z-20"> BLOCKED </div> </div> ` : ''} <div class="flex justify-between items-start mb-3"> <span class="text-xs font-bold uppercase tracking-wider text-gray-400 group-hover:text-cyan-300 transition-colors">${v.name}</span> <span class="text-xs font-mono bg-white/10 px-2 py-0.5 rounded text-gray-300" id="traffic-${v.id}">${v.traffic}%</span> </div> <!-- A11y Score --> <div class="flex flex-col items-center mb-3"> ${buildGaugeSVG(v.stats.a11y, v.status === 'blocked')} <div class="text-sm font-mono mt-1 ${v.stats.a11y >= state.thresholds.a11y ? 'text-green-400' : 'text-amber-400'}"> <span id="a11y-${v.id}">${v.stats.a11y}</span> </div> <div class="text-[10px] text-gray-500 uppercase">Accessibility</div> </div> <!-- LCP Bar --> <div class="mb-1"> <div class="flex justify-between text-[10px] text-gray-400 mb-1"> <span>LCP</span> <span id="lcp-val-${v.id}" class="font-mono">${v.stats.latency}ms</span> </div> ${buildLCPBar(v.stats.latency)} </div> <!-- Budget reference line label --> <div class="text-[10px] text-gray-600 text-right mt-1">Budget: ${state.thresholds.latency}ms</div> </div> `).join('')} </div> `; feedContainer.appendChild(expCard); }); // Cache references for updates state.domRefs = {}; document.querySelectorAll('.variant-card').forEach(card => { const vId = card.dataset.id; state.domRefs[vId] = { card, traffic: card.querySelector(`#traffic-${vId}`), a11y: card.querySelector(`#a11y-${vId}`), a11ySvg: card.querySelector('svg'), lcp: card.querySelector(`#lcp-val-${vId}`), lcpBarFill: card.querySelector('.h-full.gradient'), lcpBarContainer: card.querySelector('.h-2.bg-gray-800') }; }); }; // Update DOM for a variant (non-blocking) const updateVariantDOM = (variant, changedMetrics) => { const ref = state.domRefs[variant.id]; if (!ref) return; // Traffic if (changedMetrics.includes('traffic')) { ref.traffic.textContent = `${variant.traffic}%`; } // A11y if (changedMetrics.includes('a11y')) { // Update number with counting animation gsap.to({ val: parseFloat(ref.a11y.textContent) }, { val: variant.stats.a11y, duration: 0.6, ease: "power2.out", onUpdate: function() { ref.a11y.textContent = this.targets()[0].val.toFixed(1); } }); // Update SVG gauge const passes = variant.stats.a11y >= state.thresholds.a11y; const color = variant.status === 'blocked' ? '#ff2a6d' : (passes ? '#50fa7b' : '#ffb86c'); const { dash, offset } = createGaugePath(variant.stats.a11y); const circle = ref.a11ySvg.querySelector('circle:last-child'); circle.style.strokeDasharray = `${circleCircumference}`; circle.style.strokeDashoffset = `${offset}`; circle.style.stroke = color; } // LCP if (changedMetrics.includes('latency')) { // Update text ref.lcp.textContent = `${variant.stats.latency}ms`; // Update bar width const maxScale = 5000; const percent = Math.min((variant.stats.latency / maxScale) * 100, 100); gsap.to(ref.lcpBarContainer.querySelector('div'), { width: `${percent}%`, duration: 0.6, ease: "power2.out" }); // Update color based on threshold let fillColor = '#00f0ff'; if (variant.stats.latency > state.thresholds.latency + 500) fillColor = '#ff2a6d'; else if (variant.stats.latency > state.thresholds.latency) fillColor = '#ffb86c'; else fillColor = '#00f0ff'; ref.lcpBarContainer.querySelector('div').style.background = fillColor; } }; // Update KPI counters const updateKPI = () => { const activeExps = state.experiments.length; const totalVariants = state.experiments.reduce((acc, exp) => acc + exp.variants.length, 0); const blockedVariants = state.experiments.reduce((acc, exp) => acc + exp.variants.filter(v => v.status === 'blocked').length, 0); const activeVariants = state.experiments.reduce((acc, exp) => { return acc + exp.variants.filter(v => v.status === 'active').length; }, 0); let sumLatency = 0; state.experiments.forEach(exp => { exp.variants.forEach(v => { if (v.status === 'active') sumLatency += v.stats.latency; }); }); const avgLcp = activeVariants ? Math.round(sumLatency / activeVariants) : 0; // Animate numbers const animateNumber = (el, target) => { gsap.to(obj, { val: target, duration: 1, onUpdate: () => el.textContent = Math.round(obj.val) }); }; const counters = [ { el: document.getElementById('stat-active-exp'), target: activeExps }, { el: document.getElementById('stat-total-variants'), target: totalVariants }, { el: document.getElementById('stat-blocks'), target: state.totalBlocks }, { el: document.getElementById('stat-avg-lcp'), target: avgLcp } ]; counters.forEach(c => { const obj = { val: parseInt(c.el.textContent) }; gsap.to(obj, { val: c.target, duration: 0.8, ease: "power2.out", onUpdate: () => c.el.textContent = obj.val.toLocaleString() }); }); }; // Update clock setInterval(() => { const now = new Date(); clockEl.textContent = now.toISOString().split('T')[1].split('.')[0] + ' UTC'; }, 1000); // ========================================== // 4. GUARDRAIL LOGIC // ========================================== const blockVariant = (variant, reason, metricValue) => { variant.status = 'blocked'; variant.blockReason = reason; state.totalBlocks++; // UI update updateVariantDOM(variant, ['traffic']); // Actually we need to re-render to get the blocked overlay visuals, or we can add class manually const ref = state.domRefs[variant.id]; if (ref) { ref.card.classList.add('border-rose-500/50', 'bg-rose-500/5', 'blocked-card'); // Add overlay HTML if missing (since we didn't render it in initial DOM if status active) if (!ref.card.querySelector('.blocked-overlay')) { const overlay = document.createElement('div'); overlay.className = 'absolute inset-0 z-10 blocked-overlay flex items-center justify-center'; overlay.innerHTML = ` <div class="bg-rose-500/90 text-white font-bold text-xs px-4 py-2 rounded shadow-lg transform -rotate-12 border-2 border-rose-300 relative"> BLOCKED </div> `; ref.card.appendChild(overlay); } // Set traffic to 0 ref.traffic.textContent = '0%'; // Dim a11y gauge color red const circle = ref.a11ySvg.querySelector('circle:last-child'); circle.style.stroke = '#ff2a6d'; // LCP bar red and maybe shrink? ref.lcpBarContainer.querySelector('div').style.background = '#ff2a6d'; } // Add to log addLogEntry(variant, reason, metricValue); updateKPI(); showToast(variant, reason); }; const addLogEntry = (variant, reason, value) => { // Remove "No blocks yet" if present const emptyMsg = blockedLogContainer.querySelector('div.text-gray-500'); if (emptyMsg) emptyMsg.remove(); const entry = document.createElement('div'); entry.className = 'glass-panel p-3 border-l-2 border-rose-500 text-xs'; const time = new Date().toISOString().split('T')[1].split('.')[0]; entry.innerHTML = ` <div class="flex justify-between"> <span class="font-bold text-gray-200">${variant.name}</span> <span class="text-gray-400 font-mono">${time}</span> </div> <div class="text-rose-400 mt-1">❖ ${reason} (${value})</div> <div class="text-gray-500 truncate">Exp: ${variant.id.split('-')[0]}</div> `; // Insert at top blockedLogContainer.insertBefore(entry, blockedLogContainer.firstChild); // Keep max 20 entries if (blockedLogContainer.children.length > 20) { blockedLogContainer.removeChild(blockedLogContainer.lastChild); } }; const showToast = (variant, reason) => { const container = document.getElementById('toast-container'); const toast = document.createElement('div'); toast.className = 'glass-panel px-4 py-3 flex items-center gap-3 border-l-4 border-rose-500 pointer-events-auto transform translate-x-full'; toast.innerHTML = ` <svg class="w-5 h-5 text-rose-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg> <div> <div class="text-sm font-bold text-white">Variant Blocked</div> <div class="text-xs text-gray-400">${variant.name} (${reason})</div> </div> `; container.appendChild(toast); // Animate in gsap.to(toast, { x: 0, duration: 0.4, ease: "back.out(1.7)", onComplete: () => { // Auto dismiss after 5s setTimeout(() => { gsap.to(toast, { x: '100%', opacity: 0, duration: 0.4, onComplete: () => toast.remove() }); }, 8000); }}); }; // ========================================== // 5. SIMULATION LOOP // ========================================== const runSimulation = () => { // Every 2 seconds, update some metrics setInterval(() => { state.experiments.forEach(exp => { exp.variants.forEach(v => { if (v.status === 'blocked') return; const changed = []; // Random walk for latency let deltaLat = Math.floor(Math.random() * 200) - 100; // Occasionally spike (5% chance) if (Math.random() < 0.05) deltaLat += 1000; v.stats.latency = Math.max(400, v.stats.latency + deltaLat); changed.push('latency'); // Random walk for a11y let deltaA11y = (Math.random() * 2 - 1) * 0.5; // Occasionally drop (3% chance) if (Math.random() < 0.03) deltaA11y -= 10; v.stats.a11y = parseFloat(Math.max(50, Math.min(100, v.stats.a11y + deltaA11y)).toFixed(1)); changed.push('a11y'); // Traffic rarely changes if (Math.random() < 0.1) { // Small traffic reallocation within exp (simplified: just jitter one variant) changed.push('traffic'); } // Update DOM updateVariantDOM(v, changed); }); }); // Check guardrails state.experiments.forEach(exp => { exp.variants.forEach(v => { if (v.status === 'blocked') return; let blocked = false; if (v.stats.latency > state.thresholds.latency) { blockVariant(v, 'Latency Budget Exceeded', `${v.stats.latency}ms`); blocked = true; } if (!blocked && v.stats.a11y < state.thresholds.a11y) { blockVariant(v, 'Accessibility Score Low', `${v.stats.a11y}`); } }); }); updateKPI(); }, 2000); }; // ========================================== // 6. INITIALIZATION & EVENT LISTENERS // ========================================== const init = () => { // Start Three.js initThreeJS(); // Generate data generateData(); // Start simulation runSimulation(); // Slider events const latencySlider = document.getElementById('latency-slider'); const latencyDisplay = document.getElementById('latency-threshold-display'); latencySlider.addEventListener('input', (e) => { state.thresholds.latency = parseInt(e.target.value); latencyDisplay.textContent = state.thresholds.latency + ' ms'; // Update LCP bar markers (re-render feed is heavy; we can just update markers via DOM) // For simplicity, we'll re-render the feed to show new budget line position // But we want to preserve animation states. Instead, update the marker style in all bars. const markers = document.querySelectorAll('.budget-marker'); const maxScale = 5000; const pos = (state.thresholds.latency / maxScale) * 100; markers.forEach(m => m.style.left = `${pos}%`); // Update labels document.querySelectorAll('.text-right.mt-1.text-gray-600').forEach(lbl => { lbl.textContent = `Budget: ${state.thresholds.latency}ms`; }); }); const a11ySlider = document.getElementById('a11y-slider'); const a11yDisplay = document.getElementById('a11y-threshold-display'); a11ySlider.addEventListener('input', (e) => { state.thresholds.a11y = parseInt(e.target.value); a11yDisplay.textContent = state.thresholds.a11y; // Re-evaluate active variants immediately if they now pass? // For demo, we will re-color gauges but not auto-unblock. // We can iterate and update gauge colors based on new threshold state.experiments.forEach(exp => { exp.variants.forEach(v => { if (v.status === 'active') { // Update gauge only const ref = state.domRefs[v.id]; if (ref) { const passes = v.stats.a11y >= state.thresholds.a11y; const color = passes ? '#50fa7b' : '#ffb86c'; ref.a11ySvg.querySelector('circle:last-child').style.stroke = color; } } }); }); }); }; // Run init when DOM ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } </script> </body> </html>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.