Here's a thinking process that leads to the suggested solution:
-
Analyze the Request:
- Goal: Engineer a static-to-runtime policy translator that enforces architectural layering by generating runtime guards from static analysis results.
- Context: The user wants a "static-to-runtime policy translator."
- Requirements (System Prompt):
- Role: Natural UI/UX Artist, Biophilic Design & Wabi-Sabi aesthetic.
- Principles: Organic shapes, earth tones, texture (noise, paper grain), sophisticated typography (Serif/Humanist), slow/fluid animations, dappled light, frosted glass (but paper-like).
- Tech Stack: Tailwind CSS (implied via single file), Framer Motion (simulated via CSS/JS since single file constraint usually limits heavy libs, but I can use lightweight libraries or write custom shaders/animations), Three.js (heavy, maybe overkill for a specific business logic demo, but fits "texture/shaders").
- Format: Single HTML file (HTML+CSS+JS). No external build steps.
- Language: English (stays consistent).
- Interpretation: The user wants a tool. It needs to translate "static analysis results" (probably a JSON or a set of layers/rules) into "runtime guards" (code snippets or configuration that intercepts calls). As a UI/UX demo, I should create an interactive visualization/editor that shows this translation process.
-
Conceptualization (The "Artistic" Twist):
- Instead of a dry code generator, imagine this as a digital garden of architecture. Layers are like strata of earth or leaves.
- Visual Metaphor: A layered structure (like sedimentary rock or passing through a veil of leaves). Rules travel down from the static analysis view (a tree diagram) to the runtime execution path (a flow chart), becoming "guards" (gateways).
- Interaction:
- User defines a policy (Layer A cannot call Layer B).
- Visualizer shows this rule being "translated" into a guard.
- The "Guard" is represented as a floating, organic widget that can be dragged or clicked to see the generated code.
- Atmosphere: Slow, organic transitions. Colors: Muted greens, terracotta, beige, paper texture background. Noise overlay. Font: Merriweather or similar Serif.
-
Technical Architecture (Single File):
- HTML Structure:
- Header: Title & brand.
- Main:
- Top Section: "Static Analysis" (Input). A list of layers defined (UI to create dependencies).
- Middle Section: The "Translation Engine" (Animation area). Visualizes the transformation.
- Bottom Section: "Runtime Output" (Generated code).
- CSS (Tailwind via CDN + Custom Styles):
- Import Tailwind.
- Import Google Fonts (Merriweather/Playfair Display + Lato).
- Custom classes for blobs, noise, glassmorphism.
- JS (Plain ES6):
- State management: Layers, Rules (allowed accesses), derived Guards (forbidden checks).
- Logic: "Translating" rules -> "Guard" functions (wrappers).
- Animation: Use CSS transitions and
requestAnimationFrame for organic movement. I'll implement a simple "blob" movement script to mimic floating organic shapes.
-
Step-by-Step Implementation Plan:
-
Step 1: Setup & Styling (The Canvas)
- Background: Soft beige/off-white with SVG noise filter.
- Color Palette: Earth tones.
- Typography: Serif headers, Sans-serif UI.
-
Step 2: The Static Analysis Input (User Input)
- Form to add "Layers" (e.g., "Presentation", "Domain", "Infrastructure").
- Matrix or Tree to define allowed dependencies (toggles).
- Style: Organic buttons, smooth checkboxes.
-
Step 3: The Translator (Visualization)
- This is the "hero" section.
- When "Translate" is clicked, show an animation.
- Particles or Blobs representing "Rules" float down and merge to form "Guards".
- I'll use HTML Canvas for the visualizer to draw flowing organic shapes.
-
Step 4: Runtime Output (Code Generation)
- Display generated JavaScript/Python guards.
- Syntax highlighting (simulated with colors).
- Copy button with a "papery" texture.
-
Step 5: Three.js/Shader (Optional but fitting)
- Maybe too complex for a pure static analysis demo, but I can add a subtle "flow" background using a custom shader on a 2D canvas to represent "policy flow".
- Decision: Keep it simpler but high-quality CSS/Canvas animation to ensure the code logic is the focus, wrapped in beautiful UI. I'll implement a seamless "dappled light" effect using a large blurred radial gradient following the mouse.
-
Refining the "Policy Translation" Logic:
-
Drafting the Code (Mental or Scratchpad):
-
Libraries: Tailwind CSS (CDN). FontAwesome (Icons). Google Fonts.
-
Noise Texture: Base64 SVG.
-
Mouse Light: Custom JS tracking cursor to move a div with mix-blend-mode: overlay and radial gradient.
-
Blob Animation:
- Create a class
OrganicBlob.
- Properties: x, y, radius, color, velocity (sine wave based).
- Render loop: update position based on perlin-ish noise.
-
Writing the Code (Iterative refinement for the "Artistic" constraint):
- Colors:
#E6E2DD (paper), #8A9A8E (sage), #C18F7D (terracotta), #5C5C5C (charcoal). Avoid pure white/black.
- Glass:
backdrop-filter: blur(12px); background: rgba(255, 250, 240, 0.4); border: 1px solid rgba(255, 255, 255, 0.3);.
- Typography:
font-family: 'Merriweather', serif; for headings. font-weight: 300; letter-spacing: 0.05em;.
-
Constructing the Functionality:
- State:
layers: Array of strings.
rules: Object { [sourceLayer]: [targetLayers] }.
- UI:
- "Add Layer" button.
- Layer management list.
- Dependency Matrix: Generate table checkboxes dynamically.
- "Generate Policy" button.
- Action:
- On click, calculate all possible pairs.
- Determine forbidden pairs.
- Generate code snippets.
- Start the "Visual Translation" animation: blobs (rules) moving into a "forge" (circle) and outputting a "scroll" (code).
-
Addressing the "Static-to-Runtime" Specifics:
- I need to explain the concept. The UI will have an "Info" modal or section explaining the process: "The architecture is defined at build time (static). These constraints are compiled into runtime guards that execute before every call."
- The generated code will be both generic (template) and specific to the user's input.
-
Polishing:
- Ensure the noise texture covers the screen.
- Ensure the dappled light moves smoothly.
- Check contrast.
- Add "toast" notifications for actions (Add layer, code copied).
- Make the transition between sections (Static -> Animate -> Runtime) smooth and automatic.
-
Final Code Assembly (simulating the output):
- Merge HTML, CSS, JS.
- Use
https://cdn.tailwindcss.com with custom config for colors.
- Add the Google Fonts link.
- Write the script at the bottom.
- Test mental model: User adds "UI", "API", "DB". Checks allow "UI" -> "API". Clicks Translate. Animation plays. Shows generated guard code preventing "DB" -> "UI" etc.
-
Self-Correction during drafting:
- Critique: The matrix gets messy with many layers.
- Fix: Limit to 3-4 layers explicitly in the demo simplicity, but allow adding more with style adjustments (scrollable). I'll stick to 4 for the default demo but handle dynamic sizing gracefully.
- Critique: "Three.js" requested. I can include a very lightweight Three.js scene for a background "smoke" or "fluid" effect, but it might conflict with the 2D UI if not careful.
- Decision: I will use a lightweight custom WebGL shader (using a tiny canvas helper) for the background texture because it's more performant and fits the "code expert" persona without bloating the file. But to strictly follow "Three.js" if possible, I could add a simple Twinkling dust effect. However, for a "translator" tool, a 2D canvas flow is often better. I'll stick to a highly polished 2D Canvas organic flow to represent the "translation stream", as it's more readable and fits the UI framework. I will mention in the code that I'm using Canvas API for organic motion as it's lighter for this specific UI, while keeping the aesthetic consistent with Three.js grade visuals. Correction: The prompt says "threejs... used for interactivity". I will implement a Three.js background scene—a slow-moving, foggy sphere or particle field—to represent the "cloud of policies" floating in the architecture, interacting with the mouse. Yes, I'll do a simple Three.js scene in the background, and the UI sits on top (frosted glass). This will look high-end.
-
Finalizing the Three.js Background:
- Scene, Camera, Renderer.
- Mesh:
IcosahedronGeometry with high detail.
- Material:
MeshPhysicalMaterial with transmission (glass-like) and roughness, plus noise? Actually, simpler: A large point cloud or a soft glowing sphere that undulates. Let's go with a "Breathing Organic Sphere" composed of thousands of particles representing atomic logic. It moves slowly. Mouse movement rotates it.
-
Let's write the code. (Proceeding to generate the HTML string).
- Dependencies: Tailwind (CDN), Three.js (CDN), GSAP (CDN) for smooth UI animations (optional, but I'll stick to CSS transitions to keep dependencies low, maybe GSAP for the "blobs"). I'll use GSAP for the UI "blobs" entering/exiting because it's standard for "slow media".
-
Review against constraints:
- Single HTML? Yes.
- No alerts? Yes, use custom overlay.
- Biophilic/Wabi-Sabi? Earth tones, noise, serif fonts, slow motion, glass, organic shapes.
- Static-to-runtime translator? Yes, core functionality.
Let's build it.
- Title: Architectural Guard Generator
- Theme: "The Silhouette of Security" - translating abstract rules into concrete guards.
(Self-Correction): Ensure the "Generated Code" is realistic. I will produce a JS decorator or function that checks a registry of allowed connections.
Implementation Details:
allowedMatrix: 2D array.
forbiddenPairs: Array of {from, to}.
- Generated code: A
Guard class that has a check(source, target) method. It throws an error if allowedMatrix[from][to] is false.
- Runtime guard injection: Show code that wraps an API call.
Let's go.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Architectural Policy Translator</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- GSAP for smooth organic animations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,400;0,600;1,400&family=Montserrat:wght@300;400&display=swap" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'paper': '#E8E6DF',
'clay': '#C18F7D',
'sage': '#8A9A8E',
'stone': '#5C5C5C',
'mist': '#F7F5F0',
'deep-water': '#2D3A4A'
},
fontFamily: {
serif: ['"Cormorant Garamond"', 'serif'],
sans: ['"Montserrat"', 'sans-serif'],
},
boxShadow: {
'soft': '0 4px 30px rgba(0, 0, 0, 0.05)',
'inset-glass': 'inset 0 0 20px rgba(255, 255, 255, 0.3)',
}
}
}
}
</script>
<style>
body {
background-color: #E8E6DF;
color: #2D3A4A;
overflow-x: hidden;
}
/* Noise Texture Overlay */
.noise-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
opacity: 0.05;
background: 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");
}
/* Organic Glassmorphism */
.glass-panel {
background: rgba(247, 245, 240, 0.65);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.4);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.07);
}
.glass-panel:hover {
border-color: rgba(193, 143, 125, 0.3);
transition: border-color 0.8s ease-out;
}
/* Typography & Spacing */
h1, h2, h3, h4 {
font-weight: 600;
letter-spacing: 0.02em;
}
/* Custom Checkbox for Wabi-Sabi feel */
.sakura-checkbox:checked + label {
background-color: rgba(193, 143, 125, 0.2);
border-color: rgba(193, 143, 125, 0.5);
}
.sakura-checkbox:checked + label::after {
border-color: #C18F7D;
}
/* Dappled Light Effect */
#dappled-light {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
z-index: 0;
background: radial-gradient(circle at var(--x, 50%) var(--y, 50%), rgba(255,255,255,0.15) 0%, transparent 50%);
mix-blend-mode: screen;
}
/* Code Block Styling */
.code-bg {
background-color: rgba(255, 253, 245, 0.9);
background-image: repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(193, 143, 125, 0.03) 10px, rgba(193, 143, 125, 0.03) 20px);
}
/* Blob Animations */
.blob-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
pointer-events: none;
}
.blob {
position: absolute;
border-radius: 50%;
filter: blur(20px);
opacity: 0.6;
mix-blend-mode: screen;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(230, 230, 230, 0.3);
}
::-webkit-scrollbar-thumb {
background: #C18F7D;
border-radius: 4px;
}
/* Transitions */
.fade-enter {
opacity: 0;
transform: translateY(20px);
}
.fade-enter-active {
opacity: 1;
transform: translateY(0);
transition: opacity 0.8s ease-out, transform 0.8s ease-out;
}
</style>
</head>
<body class="antialiased min-h-screen flex flex-col">
<!-- Dappled Light -->
<div id="dappled-light"></div>
<!-- Noise -->
<div class="noise-overlay"></div>
<!-- Three.js Background -->
<canvas id="three-canvas" class="fixed top-0 left-0 w-full h-full -z-10 opacity-30"></canvas>
<!-- Header -->
<header class="relative z-30 p-8 flex justify-between items-center glass-panel border-b border-white/20 mb-8">
<div>
<h1 class="text-3xl md:text-4xl" style="font-family: 'Cormorant Garamond', serif;">Policy Forge</h1>
<p class="text-sm text-stone-500 mt-1 font-sans tracking-wide uppercase">Translating Architecture to Runtime</p>
</div>
<div class="flex gap-4">
<button onclick="resetAll()" class="px-6 py-2 text-sm font-sans text-stone-600 border border-stone-300 rounded-full hover:bg-stone-100 transition-all duration-500">
Reset
</button>
</div>
</header>
<!-- Main Content -->
<main class="relative z-20 container mx-auto px-4 pb-20 max-w-6xl">
<!-- Intro -->
<section class="mb-12 text-center max-w-2xl mx-auto fade-enter-active">
<p class="text-lg leading-relaxed text-stone-600 font-serif">
Design your architectural layers below. Define which interactions are permitted at compile-time.
The system will generate <strong>runtime guards</strong>—code that enforces these rules dynamically to prevent layering violations.
</p>
</section>
<!-- Input Section: Layer Definition -->
<section id="input-section" class="mb-16 fade-enter-active">
<div class="glass-panel rounded-3xl p-8 md:p-10">
<div class="flex flex-col md:flex-row justify-between items-end mb-8 border-b border-stone-300/50 pb-6">
<div>
<h2 class="text-2xl font-serif text-stone-800">1. Define Layers</h2>
<p class="text-stone-500 text-sm mt-2">Name your architectural components (e.g., Presentation, Domain, Infrastructure).</p>
</div>
<div class="flex gap-2 mt-4 md:mt-0">
<input type="text" id="new-layer-input" placeholder="New layer name..."
class="px-4 py-2 bg-white/50 border border-stone-300 rounded-full text-stone-700 placeholder-stone-400 focus:outline-none focus:ring-2 focus:ring-clay/40 transition-all w-48 font-sans text-sm">
<button onclick="addLayer()" class="px-6 py-2 bg-clay/10 text-clay border border-clay/20 rounded-full text-sm font-sans hover:bg-clay/20 transition-all duration-500">
Add
</button>
</div>
</div>
<!-- Layer Tags -->
<div id="layers-list" class="flex flex-wrap gap-3 min-h-[50px]">
<!-- Dynamically populated -->
</div>
</div>
</section>
<!-- Input Section: Dependency Matrix -->
<section id="matrix-section" class="mb-16 fade-enter-active">
<div class="glass-panel rounded-3xl p-8 md:p-10">
<div class="mb-8 border-b border-stone-300/50 pb-6">
<h2 class="text-2xl font-serif text-stone-800">2. Architectural Rules</h2>
<p class="text-stone-500 text-sm mt-2">Select which layers are allowed to communicate. Unchecked options will generate runtime guards blocking those calls.</p>
</div>
<div id="matrix-container" class="overflow-x-auto">
<!-- Matrix Table generated here -->
<p class="text-stone-400 italic text-center py-12 font-serif">Add layers to define the dependency matrix.</p>
</div>
</div>
</section>
<!-- Action Button -->
<div class="text-center mb-24 relative z-20">
<button onclick="generatePolicy()" id="generate-btn"
class="group relative px-10 py-4 bg-stone-700 text-white font-serif text-xl rounded-full overflow-hidden shadow-lg hover:scale-105 transition-transform duration-700 ease-out">
<span class="relative z-10 group-hover:text-white/90">Translate to Runtime Guards</span>
<div class="absolute inset-0 bg-gradient-to-r from-sage to-deep-water opacity-0 group-hover:opacity-100 transition-opacity duration-700"></div>
</button>
<p class="text-xs text-stone-400 mt-4 font-sans tracking-widest uppercase">The engine compiles static constraints into dynamic interceptors</p>
</div>
<!-- Visualizer: The "Translation" Process -->
<section id="visualizer" class="hidden mb-24 relative fade-enter-active">
<div class="h-64 md:h-96 relative rounded-3xl overflow-hidden glass-panel flex items-center justify-center">
<div class="absolute inset-0 flex items-center justify-center pointer-events-none">
<div class="w-24 h-24 border-2 border-clay/30 rounded-full flex items-center justify-center animate-pulse">
<span class="text-xs text-clay uppercase tracking-widest">Processing</span>
</div>
</div>
<canvas id="flow-canvas" class="absolute inset-0 w-full h-full z-0"></canvas>
<div id="translation-status" class="relative z-10 text-center p-6 glass-panel rounded-2xl bg-white/80 max-w-md">
<h3 class="font-serif text-xl text-stone-800 mb-2">Analyzing Architecture</h3>
<p class="text-stone-600 text-sm font-sans" id="status-text">Initializing...</p>
</div>
</div>
</section>
<!-- Output Section -->
<section id="output-section" class="hidden fade-enter-active">
<div class="mb-8 border-b border-stone-300/50 pb-4 flex justify-between items-end">
<div>
<h2 class="text-2xl md:text-3xl font-serif text-stone-800">Runtime Guard Implementation</h2>
<p class="text-stone-500 text-sm mt-1 font-sans">Inject these generated guards into your service mesh or API gateway.</p>
</div>
<button onclick="copyCode()" class="flex items-center gap-2 text-clay text-sm font-sans hover:text-stone-800 transition-colors">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path></svg>
Copy to Clipboard
</button>
</div>
<!-- Code Display -->
<div class="glass-panel rounded-3xl p-1 overflow-hidden relative group">
<div class="absolute top-4 right-4 z-10 opacity-0 group-hover:opacity-100 transition-opacity duration-500">
<div class="w-3 h-3 rounded-full bg-red-400/70 mb-1 shadow-sm"></div>
<div class="w-3 h-3 rounded-full bg-yellow-400/70 mb-1 shadow-sm"></div>
<div class="w-3 h-3 rounded-full bg-green-400/70 shadow-sm"></div>
</div>
<pre class="code-bg p-6 md:p-10 overflow-x-auto h-[500px] md:h-[600px] text-sm md:text-base font-sans leading-loose text-stone-800"><code id="code-output"></code></pre>
</div>
<!-- Explanation -->
<div class="mt-8 grid md:grid-cols-3 gap-6">
<div class="glass-panel p-6 rounded-2xl">
<h4 class="font-serif text-lg text-clay mb-2">Guard Injection</h4>
<p class="text-stone-600 text-sm leading-relaxed">The generated code creates an interceptor function that executes before every cross-layer call. It checks the rule registry before allowing execution.</p>
</div>
<div class="glass-panel p-6 rounded-2xl">
<h4 class="font-serif text-lg text-clay mb-2">Fail Fast</h4>
<p class="text-stone-600 text-sm leading-relaxed">If a violation occurs, the guard throws a descriptive error immediately, preventing the request from hitting the target service and maintaining architectural integrity.</p>
</div>
<div class="glass-panel p-6 rounded-2xl">
<h4 class="font-serif text-lg text-clay mb-2">Zero-Touch Config</h4>
<p class="text-stone-600 text-sm leading-relaxed">The guard logic is derived entirely from your static matrix. No manual rule writing is required; the translator handles the complexity.</p>
</div>
</div>
</section>
</main>
<!-- Footer -->
<footer class="relative z-20 text-center p-8 text-stone-500 text-xs font-sans border-t border-stone-300/30 mt-auto">
<p>Co-created with ♥ by the Architecture Team.</p>
</footer>
<!-- Toast Notification -->
<div id="toast" class="fixed bottom-8 left-1/2 transform -translate-x-1/2 glass-panel px-8 py-4 rounded-full shadow-soft z-50 opacity-0 pointer-events-none transition-opacity duration-500">
<span class="text-stone-700 font-serif text-sm" id="toast-msg">Notification</span>
</div>
<script>
// --- State Management ---
const state = {
layers: ['UI', 'Application', 'Domain', 'Infrastructure'],
allowed: {
'UI': ['Application', 'Domain'],
'Application': ['Domain'],
'Domain': ['Infrastructure'],
'Infrastructure': []
}
};
// --- Utility Functions ---
function showToast(message) {
const toast = document.getElementById('toast');
const msg = document.getElementById('toast-msg');
msg.innerText = message;
toast.classList.remove('opacity-0', 'pointer-events-none');
setTimeout(() => {
toast.classList.add('opacity-0', 'pointer-events-none');
}, 3000);
}
// --- Layer Management ---
function renderLayers() {
const container = document.getElementById('layers-list');
container.innerHTML = '';
state.layers.forEach((layer, index) => {
const tag = document.createElement('div');
tag.className = 'px-4 py-2 bg-stone-200/50 border border-stone-300 rounded-full flex items-center gap-2 shadow-sm group transition-colors duration-500 hover:bg-stone-200/80';
tag.innerHTML = `
<span class="font-serif font-semibold text-stone-700">${layer}</span>
<button onclick="removeLayer('${layer}')" class="text-stone-400 hover:text-red-500 transition-colors duration-300 text-lg leading-none">×</button>
`;
container.appendChild(tag);
});
renderMatrix();
}
function addLayer() {
const input = document.getElementById('new-layer-input');
const name = input.value.trim();
if (!name) return;
if (state.layers.includes(name)) {
showToast('Layer already exists');
return;
}
state.layers.push(name);
state.allowed[name] = [];
input.value = '';
renderLayers();
showToast(`Added layer "${name}"`);
}
function removeLayer(layer) {
if (state.layers.length <= 2) {
showToast("Need at least 2 layers");
return;
}
// Remove from list
state.layers = state.layers.filter(l => l !== layer);
// Remove from allowed maps
delete state.allowed[layer];
Object.keys(state.allowed).forEach(k => {
state.allowed[k] = state.allowed[k].filter(t => t !== layer);
});
renderLayers();
}
// --- Matrix Management ---
function renderMatrix() {
const container = document.getElementById('matrix-container');
if (state.layers.length === 0) {
container.innerHTML = '';
return;
}
// Table Structure
let html = `
<table class="w-full border-collapse text-center">
<thead>
<tr>
<th class="p-3 text-sm uppercase tracking-widest text-stone-400 font-sans">Source \\ Target</th>
${state.layers.map(l => `<th class="p-3 w-24 text-sm uppercase tracking-widest text-stone-400 font-sans border-l border-stone-200">${l}</th>`).join('')}
</tr>
</thead>
<tbody>
`;
state.layers.forEach(source => {
html += `<tr>`;
// Row Header
html += `<td class="p-3 text-sm font-serif font-semibold text-stone-700 border-b border-stone-200">${source}</td>`;
state.layers.forEach(target => {
const isSelf = source === target;
const isChecked = state.allowed[source] && state.allowed[source].includes(target);
const disabled = isSelf ? 'disabled' : '';
const opacity = isSelf ? 'opacity-30' : '';
html += `
<td class="p-3 border-b border-l border-stone-200 align-middle ${opacity}">
<input type="checkbox"
id="chk_${source}_${target}"
${isChecked ? 'checked' : ''}
${disabled ? 'disabled' : ''}
class="sakura-checkbox hidden"
onchange="toggleRule('${source}', '${target}', this.checked)"
>
<label for="chk_${source}_${target}" class="block w-8 h-8 mx-auto border border-stone-300 rounded-full cursor-pointer transition-all duration-700 relative flex items-center justify-center hover:bg-stone-100">
${isChecked ? '<span class="w-2 h-2 rounded-full bg-clay"></span>' : ''}
</label>
</td>
`;
});
html += `</tr>`;
});
html += `</tbody></table>`;
container.innerHTML = html;
}
function toggleRule(source, target, isAllowed) {
if (!state.allowed[source]) state.allowed[source] = [];
if (isAllowed) {
if (!state.allowed[source].includes(target)) {
state.allowed[source].push(target);
}
} else {
state.allowed[source] = state.allowed[source].filter(t => t !== target);
}
}
// --- Policy Generation Engine ---
function generatePolicy() {
// Calculate Forbidden Pairs
const allPairs = [];
state.layers.forEach(src => {
state.layers.forEach(tgt => {
if (src === tgt) return;
const allowed = state.allowed[src] && state.allowed[src].includes(tgt);
if (!allowed) {
allPairs.push({ from: src, to: tgt });
}
});
});
if (allPairs.length === 0) {
showToast("No restrictions to guard. Everything is allowed.");
return;
}
// UI Transition
const visualizer = document.getElementById('visualizer');
const outputSection = document.getElementById('output-section');
// Scroll to visualizer
visualizer.classList.remove('hidden');
visualizer.scrollIntoView({ behavior: 'smooth' });
// Hide output for now
outputSection.classList.add('hidden');
startVisualization(allPairs);
}
// --- Visualization (Canvas) ---
function startVisualization(forbiddenPairs) {
const canvas = document.getElementById('flow-canvas');
const ctx = canvas.getContext('2d');
const statusText = document.getElementById('status-text');
// Resize
const resize = () => {
const rect = canvas.parentElement.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
};
resize();
window.addEventListener('resize', resize);
// Particles
const particles = [];
const particleCount = 50;
class Particle {
constructor() {
this.reset(true);
}
reset(initial = false) {
this.x = initial ? Math.random() * canvas.width : canvas.width / 2;
this.y = initial ? Math.random() * canvas.height : canvas.height / 2;
this.targetX = canvas.width * 0.8 + (Math.random() - 0.5) * 200;
this.targetY = canvas.height * 0.8 + (Math.random() - 0.5) * 100;
this.vx = 0;
this.vy = 0;
this.size = Math.random() * 4 + 2;
this.color = `rgba(138, 154, 142, ${Math.random() * 0.5 + 0.2})`; // Sage
this.speed = 0.005 + Math.random() * 0.005;
this.angle = Math.random() * Math.PI * 2;
}
update(time) {
// Organic movement using sine waves
this.vx = Math.cos(this.angle) * (2 + Math.sin(time * this.speed) * 1);
this.vy = Math.sin(this.angle) * (2 + Math.cos(time * this.speed) * 1);
this.x += this.vx;
this.y += this.vy;
// Gently attract to target area (The Forge)
const dx = this.targetX - this.x;
const dy = this.targetY - this.y;
this.x += dx * 0.01;
this.y += dy * 0.01;
// Check if reached
if (Math.abs(dx) < 20 && Math.abs(dy) < 20) {
this.alpha = 0;
} else {
this.alpha = 0.6;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
ctx.globalAlpha = 1;
}
}
for (let i = 0; i < particleCount; i++) particles.push(new Particle());
// State
let frame = 0;
const duration = 300; // frames
const pairsCount = forbiddenPairs.length;
// Status Text Sequence
const steps = [
"Identifying forbidden dependencies...",
`Found ${pairsCount} architectural violations.`,
"Compiling interceptors...",
"Injecting runtime guard logic.",
"Policy translation complete."
];
let stepIndex = 0;
let stepFrame = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw connecting lines
ctx.beginPath();
ctx.strokeStyle = 'rgba(193, 143, 125, 0.1)';
ctx.lineWidth = 1;
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const dist = Math.sqrt(dx*dx + dy*dy);
if (dist < 100) {
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
}
}
}
ctx.stroke();
// Update & Draw Particles
particles.forEach(p => {
p.update(frame);
p.draw();
});
// Manage Status Text Timeline
stepFrame++;
if (stepIndex < steps.length && stepFrame > 60) { // update every ~1 sec
stepFrame = 0;
statusText.innerText = steps[stepIndex];
// Fade text
gsap.fromTo(statusText, {opacity: 0.5}, {opacity: 1, duration: 0.5});
stepIndex++;
}
if (stepIndex < steps.length || frame < duration * 2) {
frame++;
requestAnimationFrame(animate);
} else {
// Finished
setTimeout(() => {
document.getElementById('visualizer').classList.add('hidden');
renderOutput(forbiddenPairs);
outputSection.classList.remove('hidden');
outputSection.scrollIntoView({ behavior: 'smooth' });
}, 500);
}
}
animate();
}
// --- Code Generation ---
function renderOutput(forbiddenPairs) {
const codeArea = document.getElementById('code-output');
// Generate Configuration Object
const configObj = state.layers.reduce((acc, src) => {
acc[src] = state.layers.reduce((tgtAcc, tgt) => {
// If source is allowed to target, true, else false (blocked)
// Actually the guard checks: if NOT allowed -> throw
tgtAcc[tgt] = state.allowed[src] && state.allowed[src].includes(tgt);
// We won't list self-analysis usually
if (src === tgt) tgtAcc[tgt] = false; // effectively ignored
return tgtAcc;
}, {});
return acc;
}, {});
const configJson = JSON.stringify(configObj, null, 2);
const code = `// Architectural Policy Guard Generator
// Generated on: ${new Date().toLocaleDateString()}
// Philosophy: Fail fast, enforce statically defined layers at runtime.
"use strict";
/**
* The LayeredArchitectureGuard
* Intercepts calls between services and validates against the static policy matrix.
*/
class LayeredArchitectureGuard {
constructor(policyMatrix) {
this.policy = policyMatrix;
}
/**
* Validates if a source layer can invoke a target layer.
* @param {string} sourceLayer - The layer initiating the call (e.g., "UI")
* @param {string} targetLayer - The layer being called (e.g., "Database")
* @throws {Error} If the static policy disallows this dependency.
*/
validateCall(sourceLayer, targetLayer) {
if (!this.policy[sourceLayer]) {
throw new Error(\`Unknown source layer: \$\{sourceLayer\}\`);
}
// Check if the relationship is permitted
const isAllowed = this.policy[sourceLayer][targetLayer];
if (!isAllowed) {
const error = new Error(
\`Architecture Violation: Layer '\$\{sourceLayer\}' is not allowed to access '\$\{targetLayer\}'. \`
+ \`Please adhere to the defined dependency rules.\`
);
error.code = "ARCH_VIOLATION";
// In a real scenario, this could also trigger telemetry
console.error(\`[PolicyGuard] \$\{error.message\}\`);
throw error;
}
}
}
// --- Generated Policy Matrix ---
const ARCHITECTURE_POLICY = ${configJson};
// --- Singleton Guard Instance ---
const guard = new LayeredArchitectureGuard(ARCHITECTURE_POLICY);
// --- Usage Example (Middleware/Wrapper) ---
// Wrap your service calls or database clients:
function guardedInvoke(sourceLayer, targetLayer, operation) {
try {
// Enforce rule before execution
guard.validateCall(sourceLayer, targetLayer);
// Execute actual business logic
return operation();
} catch (err) {
// Centralized error handling for policy breaches
if (err.code === 'ARCH_VIOLATION') {
// Optional: Circuit breaker pattern trigger
return {
success: false,
violation: true,
message: err.message
};
}
throw err;
}
}
// Example:
// guardedInvoke('UI', 'Infrastructure', () => db.connect())
// -> Throws Error because UI cannot talk to Infrastructure directly.
export { LayeredArchitectureGuard, guard, guardedInvoke };
`;
codeArea.innerText = code;
// Simple syntax highlighting simulation (regex)
const highlighted = code
.replace(/\/\*\*[\s\S]*?\*\/|\/\/.*/g, match => `<span class="text-stone-400">${match}</span>`)
.replace(/\b(class|constructor|function|return|throw|new|if|else|const|let|var|this|async|await)\b/g, '<span class="text-deep-water font-semibold">$1</span>')
.replace(/\b(true|false|null|undefined)\b/g, '<span class="text-clay">$1</span>')
.replace(/(['"`].*?['"`])/g, '<span class="text-sage">$1</span>')
.replace(/\b(\d+)\b/g, '<span class="text-stone-500">$1</span>')
.replace(/([A-Z][a-zA-Z0-9_]*)/g, '<span class="text-stone-800">$1</span>'); // Classes
codeArea.innerHTML = highlighted;
}
function copyCode() {
const code = document.getElementById('code-output').innerText;
navigator.clipboard.writeText(code).then(() => {
showToast("Code copied to clipboard");
});
}
function resetAll() {
const input = document.getElementById('new-layer-input');
input.value = '';
state.layers = ['UI', 'Application', 'Domain', 'Infrastructure'];
state.allowed = {
'UI': ['Application', 'Domain'],
'Application': ['Domain'],
'Domain': ['Infrastructure'],
'Infrastructure': []
};
renderLayers();
document.getElementById('output-section').classList.add('hidden');
document.getElementById('visualizer').classList.add('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// --- Three.js Organic Background (Boids-like flow / Fog) ---
function initThreeJS() {
const canvas = document.getElementById('three-canvas');
const scene = new THREE.Scene();
// Fog color matching background roughly
scene.fog = new THREE.FogExp2(0xE8E6DF, 0.002);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 50;
const renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Organic Sphere Particles
const geometry = new THREE.IcosahedronGeometry(20, 4);
const material = new THREE.PointsMaterial({
color: 0x8A9A8E, // Sage
size: 0.4,
transparent: true,
opacity: 0.6
});
const sphere = new THREE.Points(geometry, material);
scene.add(sphere);
// Floating surrounding particles
const pGeometry = new THREE.BufferGeometry();
const pCount = 200;
const pPos = new Float32Array(pCount * 3);
for(let i=0; i<pCount*3; i++) {
pPos[i] = (Math.random() - 0.5) * 200;
}
pGeometry.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
const pMaterial = new THREE.PointsMaterial({
color: 0xC18F7D, // Clay
size: 0.3,
transparent: true,
opacity: 0.4
});
const points = new THREE.Points(pGeometry, pMaterial);
scene.add(points);
// Mouse interaction
let mouseX = 0, mouseY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = (e.clientX - window.innerWidth/2) * 0.05;
mouseY = (e.clientY - window.innerHeight/2) * 0.05;
});
// Window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Animation Loop
let time = 0;
function animate() {
requestAnimationFrame(animate);
time += 0.001;
// Slow rotation
sphere.rotation.x = time * 0.5;
sphere.rotation.y = time * 0.3;
// Gentle breathing scale
const scale = 1 + Math.sin(time * 2) * 0.05;
sphere.scale.set(scale, scale, scale);
// Mouse parallax
sphere.rotation.x += mouseY * 0.0001;
sphere.rotation.y += mouseX * 0.0001;
points.rotation.x -= mouseY * 0.0002;
points.rotation.y += mouseX * 0.0002;
renderer.render(scene, camera);
}
animate();
}
// --- Dappled Light Interaction ---
function initDappledLight() {
const el = document.getElementById('dappled-light');
document.addEventListener('mousemove', (e) => {
const x = e.clientX;
const y = e.clientY;
el.style.setProperty('--x', `${x}px`);
el.style.setProperty('--y', `${y}px`);
});
}
// --- Initialization ---
window.addEventListener('DOMContentLoaded', () => {
initThreeJS();
initDappledLight();
renderLayers();
// Allow 'Enter' to add layer
document.getElementById('new-layer-input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') addLayer();
});
});
</script>
</body>
</html>