Here's a thinking process that leads to the suggested solution:
-
Analyze the Request:
-
Topic: Design a widget composer for marketing teams.
-
Key Features: Guardrails around brand rules (colors, fonts), responsive integrity (mobile/desktop preview), and copy validation (text length, forbidden words).
-
Role: Top-tier creative frontend engineer/UIUX designer with a focus on minimalism, Swiss design, motion, and advanced interactivity.
Call to Action: Only one single HTML document that is completely self-contained. All HTML, CSS, and JavaScript must live in the same file. Use Tailwind CSS, GSAP, and Three.js where appropriate. High visual impact and uniqueness are crucial. Never simplify effects due to time/complexity.
-
Constraints: Single HTML file. No external API keys. No paid services. Use Tailwind (CDN), GSAP (CDN), Three.js (CDN).
-
Language: English (the user's prompt is in English). The system instruction says to use exactly the same natural language as the request, so English is required.
-
Conceptualization & Design Strategy:
- Theme: A "Widget Composer" sounds like a tool to build marketing components (like CTAs, banners, promos) without breaking brand guidelines.
- Visual Style: Dark mode (high contrast), Swiss typography (large sans-serif, maybe a serif for accents), "Cyber Blue" or "Neon" accents. Use a mesh gradient background to show depth (Swiss design but digital). Glassmorphism for panels.
- Layout:
- Left: Properties Panel (Controls: brand colors, font size, text, image upload placeholder).
- Center: Canvas/Preview Area (The widget being built, real-time).
- Right: Validation/Guardrails Panel (Log of compliance issues, copy length counter, contrast checks).
- Top/Bottom: Global tools (Export, Reset, Presets).
- Interactivity:
- Real-time updates (typing changes the widget).
- "Guardrail" visual feedback: If text is too long, turn red; if contrast fails, highlight.
- Animations: Smooth transitions (GSAP) when moving panels, switching modes, or applying changes.
- Background: Three.js particle system or a flowing mesh to make it feel "alive" but not distracting.
- Specific "Guardrails" Implementation (Mock functionality for demonstration):
- Brand Colors: Limited palette dropdown.
- Copy Validation: Regex for "bad words" (e.g., "free", "cheap" maybe), character count limits.
- Responsive Integrity: Toggle between Desktop/Mobile view, scaling the preview automatically.
- Wow Factor: The desktop view shouldn't just be a static box. It should have hover states, maybe a subtle grain overlay, and smooth state transitions when validation passes/fails.
-
Technical Stack Selection:
- HTML Structure: Single file.
- CSS Framework: Tailwind CSS (via CDN). Custom config for specific fonts (Inter, Playfair Display) and colors.
- Animation: GSAP (core + ScrollTrigger if needed, probably just core + Draggable logic for this tool). Framer Motion is React-based, so not suitable for vanilla JS/HTML. I'll stick to GSAP for complex UI animations.
- 3D/Background: Three.js for a subtle background network/particles that react to mouse movement.
- Icons: FontAwesome or Phosphor Icons (CDN). I'll use Phosphor for a cleaner look.
- Fonts: Google Fonts (Inter, Playfair Display).
-
Step-by-Step Implementation Plan:
-
Step 1: Setup & Boilerplate.
- HTML5 structure.
- CDN links: Tailwind, Three.js, GSAP, Phosphor Icons, Google Fonts.
- Custom
<style> for glassmorphism, grain texture, and scrollbars.
-
Step 2: Three.js Background.
- Canvas fixed at back.
- Create a scene with floating geometric shapes or particles.
- Add mouse movement interaction (parallax effect).
-
Step 3: Main UI Layout (Tailwind).
- Container: Flex/Grid.
- Sidebar (Left): Widget Config (type, color, headline, cta text, image toggle).
- Main Stage (Center): The Preview. It needs to simulate a viewport (desktop/phone frame).
- Right Panel: Validation & Rules List.
-
Step 4: The Widget Preview (The "Product").
- This is the HTML that gets generated based on inputs.
- It needs to be responsive (media queries inside the preview container).
- Use Tailwind classes for styling, but perhaps some inline styles for dynamic colors.
- Add hover effects to the widget itself to show interactivity.
-
Step 5: Logic & Validation (JavaScript).
- State object:
{ type, headline, subtext, cta, color, bgColor, image }.
- Event Listeners:
input on all fields to update state -> render preview -> run validation.
- Validation Logic:
- Max chars for headline (e.g., 60).
- CTA length (e.g., 20).
- Color contrast check (simple YIQ difference formula against white/black text).
- "Forbidden words" check against a list (e.g., "hustle", "guaranteed" - generic marketing spam words).
- Update UI: Turn validation items green/red, show error messages.
-
Step 6: Polish & Animations.
- GSAP intro animations: Panels slide in, stagger.
- Smooth transitions when color changes.
- Dynamic shadows that move with mouse on the preview card.
-
Refining the "High Impact" Requirement:
- Instead of a plain gray background, use a deep void color (#050505) with a subtle radial gradient.
- Add a "grain" overlay (using base64 noise or CSS noise) to give it a cinematic, physical texture.
- Typography: Large, bold headers in the UI (e.g., "WIDGET COMPOSER") with tight tracking.
- The Validation panel should look like a "system monitor" – monospaced fonts, blinking cursors, or green terminal text.
- Buttons: Magnetic effect (GSAP
quickTo). Button should stick slightly to the cursor when hovering.
-
Drafting the Code (Mental or Scratchpad):
- Tailwind Config: Need arbitrary values for colors. I'll define a palette:
brand-primary, brand-secondary, success, danger.
- Three.js: Simple particles floating and connecting lines (plexus effect) is classic and effective. I'll make it subtle: low opacity, moving slowly.
- Validation:
validateContrast(color) -> calculate luminance.
validateCopy(text) -> regex for spam.
validateLength(text, max) -> count.
-
Writing the actual code (incorporating into the final response):
-
Self-Correction/Review during thought process:
- Critique: Is the UI too complex?
- Fix: Keep controls grouped. Use clear labeling (Brand Rules, Copy, Layout).
- Critique: Is the "Widget" itself interactive?
- Fix: Yes, it needs hover states on buttons, maybe a pulse effect on the CTA.
- Critique: Does the magnetic button work?
- Fix: Need to track mouse position relative to the button center and translate the button slightly. Use
quickTo for performance.
- Critique: Did I include all libraries?
- Check: Tailwind (CDN), Three.js (CDN), GSAP (CDN). All good.
-
Final Polish:
- Add "Presets" to quickly show different widget styles.
- Ensure the contrast validation updates immediately.
- Add a "Copy Code" modal simulation (or toast) for "Export".
- Add a responsive toolbar to toggle device size (Mobile/Desktop) in the preview stage, scaling the inner container accordingly.
-
Generating the Output: Assemble into the single HTML file structure as requested. Ensure all text is in English. Add comments explaining the logic. Ensure the code is robust against null inputs.
(Self-Correction during coding): The "Copy Validation" implies checking for marketing compliance (e.g., not using "Free" or "Guarantee" if the brand forbids it). I'll implement a logic that flags these words.
- Final Output Generation. (Proceeds to generate the HTML string).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BrandGuard Widget Composer</title>
<!-- 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=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@600;700&display=swap" rel="stylesheet">
<!-- Tailwind CSS (via CDN for standalone) -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
mono: ['Fira Code', 'monospace'],
},
colors: {
brand: {
dark: '#0a0a0a',
panel: '#121212',
border: '#222222',
accent: '#3b82f6', // Blue
success: '#10b981',
danger: '#ef4444',
warning: '#f59e0b',
}
},
boxShadow: {
'glow-sm': '0 0 10px rgba(59, 130, 246, 0.15)',
'glow-md': '0 0 20px rgba(59, 130, 246, 0.3)',
'floating': '0 20px 40px -5px rgba(0, 0, 0, 0.5), 0 0 15px rgba(59, 130, 246, 0.1)',
}
}
}
}
</script>
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Phosphor Icons -->
<script src="https://unpkg.com/@phosphor-icons/web"></script>
<style>
/* Custom Styles & Overrides */
body {
background-color: #050505;
color: #e5e5e5;
overflow: hidden; /* App-like feel */
}
/* Grain Texture */
.grain-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
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.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
}
/* Scrollbar Styling */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #0f0f0f;
}
::-webkit-scrollbar-thumb {
background: #333;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #444;
}
/* Glassmorphism */
.glass {
background: rgba(18, 18, 18, 0.6);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.08);
}
.glass-panel {
background: rgba(20, 20, 20, 0.7);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.05);
}
/* Device Frame Simulation */
.device-frame {
transition: width 0.5s cubic-bezier(0.25, 0.8, 0.25, 1), height 0.5s cubic-bezier(0.25, 0.8, 0.25, 1);
}
/* Input Styling */
.form-input {
transition: all 0.2s ease;
}
.form-input:focus {
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
outline: none;
}
/* Magnetic Button Class */
.magnetic-btn {
transition: transform 0.1s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
/* Validation Status Dots */
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
display: inline-block;
}
/* 3D Canvas Background */
#bg-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
}
/* Z-index layering */
#app {
position: relative;
z-index: 10;
}
</style>
</head>
<body>
<!-- Grain Overlay -->
<div class="grain-overlay"></div>
<!-- Three.js Background -->
<canvas id="bg-canvas"></canvas>
<!-- Main Application -->
<div id="app" class="h-screen w-screen flex flex-col">
<!-- Header -->
<header class="h-16 border-b border-white/10 glass flex items-center justify-between px-6 shrink-0 z-20">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded bg-gradient-to-br from-blue-500 to-blue-700 flex items-center justify-center text-white shadow-glow-sm">
<i class="ph ph-polygon text-xl"></i>
</div>
<span class="font-serif font-bold text-xl tracking-wide">BrandGuard</span>
</div>
<nav class="flex items-center gap-6 text-sm text-gray-400">
<span class="hover:text-white cursor-pointer transition-colors">Components</span>
<span class="hover:text-white cursor-pointer transition-colors">Guidelines</span>
<span class="hover:text-white cursor-pointer transition-colors">Export</span>
</nav>
<div class="flex items-center gap-4">
<button class="text-sm text-gray-400 hover:text-white">Log Out</button>
<div class="w-8 h-8 rounded-full bg-gray-700 overflow-hidden border border-gray-600">
<img src="https://api.dicebear.com/7.x/identicon/svg?seed=Felix" alt="User">
</div>
</div>
</header>
<!-- Main Workspace -->
<main class="flex-1 flex overflow-hidden">
<!-- Left Panel: Controls -->
<aside class="w-80 glass-panel border-r border-white/10 flex flex-col shrink-0 z-10 overflow-y-auto">
<div class="p-6 space-y-8">
<!-- Widget Type Section -->
<div>
<h3 class="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3">Widget Type</h3>
<select id="widget-type" class="form-input w-full bg-brand-dark/50 border border-gray-700 rounded px-3 py-2 text-sm text-white focus:border-blue-500">
<option value="hero">Hero Banner</option>
<option value="cta">Call to Action</option>
<option value="card">Feature Card</option>
</select>
</div>
<!-- Brand Colors Section -->
<div>
<div class="flex justify-between items-center mb-3">
<h3 class="text-xs font-bold text-gray-500 uppercase tracking-widest">Brand Colors</h3>
<span class="text-xs text-blue-400 cursor-pointer hover:underline" id="reset-colors">Reset</span>
</div>
<div class="grid grid-cols-2 gap-3">
<div class="space-y-1">
<label class="text-xs text-gray-400">Primary</label>
<div class="flex items-center bg-brand-dark border border-gray-700 rounded px-2 py-1">
<input type="color" id="color-primary" value="#3b82f6" class="w-6 h-6 rounded border-none bg-transparent p-0 cursor-pointer mr-2">
<span class="text-xs font-mono text-gray-300" id="hex-primary">#3b82f6</span>
</div>
</div>
<div class="space-y-1">
<label class="text-xs text-gray-400">Background</label>
<div class="flex items-center bg-brand-dark border border-gray-700 rounded px-2 py-1">
<input type="color" id="color-bg" value="#0f172a" class="w-6 h-6 rounded border-none bg-transparent p-0 cursor-pointer mr-2">
<span class="text-xs font-mono text-gray-300" id="hex-bg">#0f172a</span>
</div>
</div>
</div>
</div>
<!-- Typography Section -->
<div>
<h3 class="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3">Copy</h3>
<div class="space-y-4">
<div class="space-y-1">
<div class="flex justify-between">
<label class="text-xs text-gray-400">Headline</label>
<span class="text-xs font-mono text-gray-500" id="headline-count">0/60</span>
</div>
<textarea id="headline-input" rows="2" class="form-input w-full bg-brand-dark/50 border border-gray-700 rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-blue-500 resize-none" placeholder="Enter main headline..."></textarea>
</div>
<div class="space-y-1">
<label class="text-xs text-gray-400">Subtext</label>
<textarea id="subtext-input" rows="2" class="form-input w-full bg-brand-dark/50 border border-gray-700 rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-blue-500 resize-none" placeholder="Enter supporting copy..."></textarea>
</div>
<div class="space-y-1">
<div class="flex justify-between">
<label class="text-xs text-gray-400">CTA Button</label>
<span class="text-xs font-mono text-gray-500" id="cta-count">0/20</span>
</div>
<input type="text" id="cta-input" class="form-input w-full bg-brand-dark/50 border border-gray-700 rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-blue-500" placeholder="Button text">
</div>
</div>
</div>
<!-- Spacer -->
<div class="pt-4 border-t border-white/10"></div>
<!-- Actions -->
<div class="space-y-3">
<button id="export-btn" class="magnetic-btn w-full bg-blue-600 hover:bg-blue-500 text-white font-medium py-2.5 px-4 rounded shadow-glow-sm transition-all flex items-center justify-center gap-2">
<i class="ph ph-code"></i> Generate Code
</button>
<button id="reset-all-btn" class="w-full border border-gray-600 hover:border-gray-500 text-gray-300 font-medium py-2 px-4 rounded transition-colors text-sm">
Reset Composer
</button>
</div>
</div>
</aside>
<!-- Center: Preview Stage -->
<section class="flex-1 relative flex flex-col items-center justify-center bg-[radial-gradient(ellipse_at_center,var(--tw-gradient-stops))] from-gray-900/40 to-black overflow-hidden">
<!-- Toolbar (Resize) -->
<div class="absolute top-4 glass px-3 py-1.5 rounded-full flex items-center gap-2 z-10 text-xs">
<span class="text-gray-400">Viewport:</span>
<div class="flex bg-black/30 rounded p-0.5">
<button class="device-toggle px-3 py-1 rounded bg-gray-700 text-white transition-all" data-width="1200">Desktop</button>
<button class="device-toggle px-3 py-1 rounded text-gray-400 hover:text-white transition-all" data-width="375">Mobile</button>
</div>
</div>
<!-- The Canvas -->
<div class="relative transition-all duration-500 ease-[cubic-bezier(0.25,0.8,0.25,1)]" id="preview-container">
<!-- The Actual Widget -->
<div id="rendered-widget" class="w-[1200px] h-[600px] overflow-hidden relative bg-gray-900 shadow-floating group">
<!-- Dynamic Background Pattern (SVG pattern based on color) -->
<div class="absolute inset-0 opacity-20 pattern-overlay" id="pattern-bg"></div>
<!-- Content Wrapper -->
<div class="relative z-10 h-full flex flex-col items-center justify-center p-12 text-center">
<!-- Decorative Elements -->
<div id="badge-container" class="mb-6 opacity-0 transform translate-y-4 transition-all duration-500">
<span class="inline-block px-3 py-1 border border-white/20 rounded-full text-xs font-bold uppercase tracking-wider text-white/80 bg-black/20 backdrop-blur-sm">New Feature</span>
</div>
<h1 id="preview-headline" class="text-5xl lg:text-6xl font-serif font-bold text-white mb-6 max-w-4xl leading-tight drop-shadow-lg">
<!-- JS Injected -->
</h1>
<p id="preview-subtext" class="text-lg text-gray-300 max-w-2xl mb-10 leading-relaxed font-light">
<!-- JS Injected -->
</p>
<button id="preview-cta" class="magnetic-btn px-8 py-4 bg-blue-600 text-white font-bold text-lg rounded shadow-glow-md hover:bg-blue-500 hover:shadow-glow-lg transition-all duration-300 transform hover:-translate-y-1">
<!-- JS Injected -->
</button>
</div>
<!-- Overlay Gradient for depth -->
<div class="absolute inset-0 pointer-events-none bg-gradient-to-t from-black/60 to-transparent opacity-80"></div>
</div>
</div>
<!-- Responsive Indicator -->
<div class="absolute bottom-6 text-xs text-gray-600 font-mono flex items-center gap-2">
<span class="w-2 h-2 bg-green-500/50 rounded-full animate-pulse"></span>
<span>Smart Preview</span>
</div>
</section>
<!-- Right Panel: Validation / Guardrails -->
<aside class="w-72 glass-panel border-l border-white/10 flex flex-col shrink-0 z-10">
<div class="p-5 border-b border-white/5">
<h2 class="text-sm font-bold text-gray-200 flex items-center gap-2">
<i class="ph ph-shield-check text-blue-500"></i> Guardrails
</h2>
</div>
<div class="flex-1 overflow-y-auto p-5 space-y-6">
<!-- Brand Colors Check -->
<div class="guardrail-group" data-check="contrast">
<div class="flex items-center justify-between mb-2">
<label class="text-xs text-gray-400 uppercase font-bold">Contrast Ratio</label>
<span id="contrast-score" class="status-dot bg-gray-600" title="Pending"></span>
</div>
<div class="bg-black/30 rounded p-3 h-14 flex items-center justify-center relative overflow-hidden">
<div id="contrast-preview" class="w-16 h-16 rounded shadow-lg transition-all duration-300"></div>
<span id="contrast-text" class="absolute text-[10px] font-mono bottom-1 right-2 text-gray-500">WCAG AA</span>
</div>
<p id="contrast-message" class="text-xs text-gray-500 mt-1">Running check...</p>
</div>
<!-- Copy Validation -->
<div class="guardrail-group" data-check="copy">
<div class="flex items-center justify-between mb-2">
<label class="text-xs text-gray-400 uppercase font-bold">Copy Compliance</label>
<span id="copy-score" class="status-dot bg-gray-600" title="Pending"></span>
</div>
<ul class="space-y-2 text-sm">
<li class="flex justify-between items-center">
<span class="text-gray-300">Forbidden Words</span>
<span id="spam-count" class="font-mono text-gray-500">0</span>
</li>
<li class="flex justify-between items-center">
<span class="text-gray-300">Headline Length</span>
<span id="headline-len-val" class="font-mono text-gray-500">0/60</span>
</li>
<li class="flex justify-between items-center">
<span class="text-gray-300">CTA Length</span>
<span id="cta-len-val" class="font-mono text-gray-500">0/20</span>
</li>
</ul>
<div id="spam-list" class="mt-2 text-xs text-red-400 font-mono space-y-1 hidden">
<!-- Spamwords inject -->
</div>
</div>
<!-- Consistency -->
<div class="guardrail-group" data-check="responsive">
<div class="flex items-center justify-between mb-2">
<label class="text-xs text-gray-400 uppercase font-bold">Responsive</label>
<span class="status-dot bg-green-500" title="Passed"></span>
</div>
<div class="p-3 bg-black/30 rounded text-xs text-gray-400">
<div class="flex justify-between mb-1">
<span>Desktop Width</span>
<span class="text-white">1200px</span>
</div>
<div class="flex justify-between">
<span>Mobile Width</span>
<span class="text-white">375px</span>
</div>
</div>
</div>
</div>
<!-- Footer info -->
<div class="p-4 border-t border-white/5 text-[10px] text-gray-600 font-mono">
BRANDGUARD v2.4.0 • SYSTEM READY
</div>
</aside>
</main>
<!-- Toast Notification -->
<div id="toast" class="fixed bottom-8 right-8 glass border border-blue-500/30 bg-blue-900/80 text-blue-100 px-6 py-3 rounded-lg shadow-glow-sm transform translate-y-20 opacity-0 z-50 transition-all duration-300 flex items-center gap-3">
<i class="ph ph-check-circle text-green-400 text-lg"></i>
<span class="text-sm font-medium">Code exported to clipboard!</span>
</div>
</div>
<!-- Application Logic -->
<script>
/**
* GLOBAL STATE
*/
const state = {
type: 'hero',
colors: {
primary: '#3b82f6',
bg: '#0f172a'
},
copy: {
headline: '',
subtext: '',
cta: ''
},
viewport: 'desktop', // or 'mobile'
validation: {
contrastPass: false,
spamCount: 0,
headlineLen: 0,
ctaLen: 0,
errors: []
}
};
// Forbidden marketing spam words list (Brand Rule example)
const FORBIDDEN_WORDS = ['guaranteed', 'free', 'cheap', 'hustle', 'miracle', 'secret', 'exclusive', 'no obligation'];
/**
* DOM ELEMENTS
*/
const els = {
widgetType: document.getElementById('widget-type'),
colorPrimary: document.getElementById('color-primary'),
hexPrimary: document.getElementById('hex-primary'),
colorBg: document.getElementById('color-bg'),
hexBg: document.getElementById('hex-bg'),
headlineInput: document.getElementById('headline-input'),
headlineCount: document.getElementById('headline-count'),
subtextInput: document.getElementById('subtext-input'),
ctaInput: document.getElementById('cta-input'),
ctaCount: document.getElementById('cta-count'),
resetColors: document.getElementById('reset-colors'),
previewContainer: document.getElementById('preview-container'),
renderedWidget: document.getElementById('rendered-widget'),
previewHeadline: document.getElementById('preview-headline'),
previewSubtext: document.getElementById('preview-subtext'),
previewCta: document.getElementById('preview-cta'),
patternBg: document.getElementById('pattern-bg'),
badgeContainer: document.getElementById('badge-container'),
// Validation
contrastScore: document.getElementById('contrast-score'),
contrastPreview: document.getElementById('contrast-preview'),
contrastMessage: document.getElementById('contrast-message'),
copyScore: document.getElementById('copy-score'),
spamCount: document.getElementById('spam-count'),
spamList: document.getElementById('spam-list'),
headlineLenVal: document.getElementById('headline-len-val'),
ctaLenVal: document.getElementById('cta-len-val'),
// Buttons
exportBtn: document.getElementById('export-btn'),
resetAllBtn: document.getElementById('reset-all-btn'),
deviceToggles: document.querySelectorAll('.device-toggle'),
toast: document.getElementById('toast')
};
/**
* INITIALIZATION
*/
function init() {
// Set initial values
els.colorPrimary.value = state.colors.primary;
els.hexPrimary.innerText = state.colors.primary;
els.colorBg.value = state.colors.bg;
els.hexBg.innerText = state.colors.bg;
// Initial Render
updatePreview();
runValidation();
initThreeJS();
initMagneticButtons();
// Intro Animations
gsap.from('header', { y: -50, opacity: 0, duration: 1, ease: 'power3.out' });
gsap.from('.glass-panel', { x: (i) => i === 0 ? -50 : 50, opacity: 0, duration: 0.8, stagger: 0.15, delay: 0.2, ease: 'power2.out' });
gsap.from('#preview-container', { scale: 0.95, opacity: 0, duration: 1, delay: 0.5, ease: 'back.out(1.7)' });
}
/**
* EVENT LISTENERS
*/
els.widgetType.addEventListener('change', (e) => {
state.type = e.target.value;
updatePreview();
// Animate badge in/out based on type
gsap.fromTo(els.badgeContainer, {opacity: 0, y: 10}, {opacity: 1, y: 0, duration: 0.5});
});
els.colorPrimary.addEventListener('input', (e) => {
state.colors.primary = e.target.value;
els.hexPrimary.innerText = e.target.value;
updatePreview();
runValidation(); // Contrast check depends on color
});
els.colorBg.addEventListener('input', (e) => {
state.colors.bg = e.target.value;
els.hexBg.innerText = e.target.value;
updatePreview();
runValidation();
});
els.resetColors.addEventListener('click', () => {
state.colors.primary = '#3b82f6';
state.colors.bg = '#0f172a';
els.colorPrimary.value = '#3b82f6';
els.hexPrimary.innerText = '#3b82f6';
els.colorBg.value = '#0f172a';
els.hexBg.innerText = '#0f172a';
updatePreview();
runValidation();
});
// Text Inputs
function handleTextInput(el, key, maxLen, countEl) {
return (e) => {
state.copy[key] = e.target.value;
countEl.innerText = `${e.target.value.length}/${maxLen}`;
updatePreview();
runValidation();
};
}
els.headlineInput.addEventListener('input', handleTextInput(els.headlineInput, 'headline', 60, els.headlineCount));
els.subtextInput.addEventListener('input', (e) => {
state.copy.subtext = e.target.value;
updatePreview();
});
els.ctaInput.addEventListener('input', handleTextInput(els.ctaInput, 'cta', 20, els.ctaCount));
// Device Toggles
els.deviceToggles.forEach(btn => {
btn.addEventListener('click', () => {
els.deviceToggles.forEach(b => {
b.classList.remove('bg-gray-700', 'text-white');
b.classList.add('text-gray-400');
});
btn.classList.remove('text-gray-400');
btn.classList.add('bg-gray-700', 'text-white');
const width = parseInt(btn.dataset.width);
state.viewport = width === 375 ? 'mobile' : 'desktop';
// Animate widget size
if (state.viewport === 'mobile') {
els.previewContainer.style.width = '375px';
els.previewContainer.style.height = '667px';
els.renderedWidget.style.width = '100%';
els.renderedWidget.style.height = '100%';
} else {
els.previewContainer.style.width = '1200px';
els.previewContainer.style.height = '600px';
els.renderedWidget.style.width = '100%';
els.renderedWidget.style.height = '100%';
}
});
});
// Export Button
els.exportBtn.addEventListener('click', () => {
// Mock export
const code = `<!-- Generated Widget Code -->
<div class="widget" style="background-color: ${state.colors.bg}; font-family: 'Inter', sans-serif;">
<h1 style="color: ${state.colors.primary}; font-family: 'Playfair Display', serif;">${state.copy.headline}</h1>
<p>${state.copy.subtext}</p>
<button style="background: ${state.colors.primary}">${state.copy.cta}</button>
</div>`;
console.log(code);
// Show Toast
const toast = els.toast;
toast.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => {
toast.classList.add('translate-y-20', 'opacity-0');
}, 3000);
});
els.resetAllBtn.addEventListener('click', () => {
// Reset everything
state.copy.headline = '';
state.copy.subtext = '';
state.copy.cta = '';
state.colors.primary = '#3b82f6';
state.colors.bg = '#0f172a';
state.type = 'hero';
els.widgetType.value = 'hero';
els.headlineInput.value = '';
els.subtextInput.value = '';
els.ctaInput.value = '';
els.colorPrimary.value = '#3b82f6';
els.hexPrimary.innerText = '#3b82f6';
els.colorBg.value = '#0f172a';
els.hexBg.innerText = '#0f172a';
els.headlineCount.innerText = '0/60';
els.ctaCount.innerText = '0/20';
updatePreview();
runValidation();
});
/**
* CORE LOGIC FUNCTIONS
*/
function updatePreview() {
// Update HTML content
els.previewHeadline.innerText = state.copy.headline || 'Headline goes here';
els.previewSubtext.innerText = state.copy.subtext || 'Subtext goes here. This is where you explain the value proposition.';
els.previewCta.innerText = state.copy.cta || 'Call to Action';
// Update Colors
els.renderedWidget.style.backgroundColor = state.colors.bg;
els.previewHeadline.style.color = state.colors.primary;
els.previewCta.style.backgroundColor = state.colors.primary;
// Dynamic Pattern Background based on color
// Create a simple SVG pattern using the primary color
const svgPattern = `
<svg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'>
<g fill='${state.colors.primary}' fill-opacity='0.1' fill-rule='evenodd'>
<path d='M0 40L40 0H20L0 20M40 40V20L20 40'/>
</g>
</svg>
`;
els.patternBg.style.backgroundImage = `url('data:image/svg+xml;base64,${btoa(svgPattern)}')`;
// Type specific tweaks
if (state.type === 'cta') {
els.renderedWidget.className = `w-full h-[200px] flex items-center justify-center bg-cover bg-center relative shadow-floating group`;
els.previewHeadline.className = "text-3xl font-serif font-bold text-white mb-4 max-w-lg leading-tight drop-shadow-lg";
els.previewSubtext.className = "text-base text-gray-300 mb-6 max-w-md";
} else if (state.type === 'card') {
els.renderedWidget.className = `w-[350px] h-[450px] rounded-2xl overflow-hidden relative bg-gray-900 shadow-floating group flex flex-col`;
els.previewHeadline.className = "text-2xl font-serif font-bold text-white mb-3 p-6 pt-10 leading-tight";
els.previewSubtext.className = "text-sm text-gray-300 mb-6 px-6 flex-1";
els.previewCta.className = "magnetic-btn w-[80%] mx-auto mb-8 px-6 py-3 bg-blue-600 text-white font-bold rounded shadow-glow-sm hover:bg-blue-500 transition-all";
} else {
// Hero Default
els.renderedWidget.className = `w-full h-full overflow-hidden relative bg-gray-900 shadow-floating group flex items-center justify-center`;
}
}
function runValidation() {
// 1. Contrast Logic (Simplified YIQ)
const primaryRgb = hexToRgb(state.colors.primary);
const bgRgb = hexToRgb(state.colors.bg);
// Calculate relative luminance for bg and fg (primary color is text color on solid bg)
const yiqlBg = (bgRgb.r * 299 + bgRgb.g * 587 + bgRgb.b * 114) / 1000;
const yiqlFg = (primaryRgb.r * 299 + primaryRgb.g * 587 + primaryRgb.b * 114) / 1000;
// Calculate contrast ratio
const lighter = Math.max(yiqlBg, yiqlFg);
const darker = Math.min(yiqlBg, yiqlFg);
const contrastRatio = (lighter + 0.05) / (darker + 0.05);
const ratioFixed = Math.round(contrastRatio * 100) / 100;
state.validation.contrastPass = contrastRatio >= 4.5; // WCAG AA
// Update UI Contrast
els.contrastPreview.style.backgroundColor = state.colors.primary;
els.contrastPreview.style.color = state.colors.primary; // text color sim
if(state.validation.contrastPass) {
els.contrastScore.className = "status-dot bg-green-500 shadow-[0_0_8px_rgba(16,185,129,0.6)]";
els.contrastMessage.innerText = `Pass (${ratioFixed}:1)`;
els.contrastMessage.className = "text-xs text-green-400 mt-1";
} else {
els.contrastScore.className = "status-dot bg-red-500 animate-pulse";
els.contrastMessage.innerText = `Fail (${ratioFixed}:1 - Needs 4.5:1)`;
els.contrastMessage.className = "text-xs text-red-400 mt-1";
}
// 2. Copy Validation
const headline = state.copy.headline.toLowerCase();
const cta = state.copy.cta.toLowerCase();
// Spam detection
const foundSpam = FORBIDDEN_WORDS.filter(word => headline.includes(word));
state.validation.spamCount = foundSpam.length;
if (foundSpam.length > 0) {
els.copyScore.className = "status-dot bg-red-500 animate-pulse";
els.spamList.innerHTML = foundSpam.map(w => `<div class="flex items-center gap-2"><i class="ph ph-warning"></i> Forbidden: "${w}"</div>`).join('');
els.spamList.classList.remove('hidden');
els.spamCount.innerText = foundSpam.length;
els.spamCount.classList.add('text-red-400');
} else {
els.copyScore.className = "status-dot bg-green-500";
els.spamList.classList.add('hidden');
els.spamCount.innerText = "0";
els.spamCount.classList.remove('text-red-400');
}
// Length checks
const headLen = state.copy.headline.length;
const ctaLen = state.copy.cta.length;
els.headlineLenVal.innerText = `${headLen}/60`;
els.ctaLenVal.innerText = `${ctaLen}/20`;
if (headLen > 60) els.headlineLenVal.classList.add('text-red-400');
else els.headlineLenVal.classList.remove('text-red-400');
if (ctaLen > 20) els.ctaLenVal.classList.add('text-red-400');
else els.ctaLenVal.classList.remove('text-red-400');
}
/**
* UTILS
*/
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : { r: 0, g: 0, b: 0 };
}
function initMagneticButtons() {
const btns = document.querySelectorAll('.magnetic-btn');
btns.forEach(btn => {
btn.addEventListener('mousemove', (e) => {
const rect = btn.getBoundingClientRect();
const x = e.clientX - rect.left - rect.width / 2;
const y = e.clientY - rect.top - rect.height / 2;
// Move button slightly towards mouse
gsap.to(btn, {
x: x * 0.3,
y: y * 0.3,
duration: 0.3,
ease: 'power2.out'
});
});
btn.addEventListener('mouseleave', () => {
gsap.to(btn, { x: 0, y: 0, duration: 0.5, ease: 'elastic.out(1, 0.3)' });
});
});
}
/**
* THREE.JS BACKGROUND
* Creates a subtle, interactive particle network
*/
function initThreeJS() {
const canvas = document.getElementById('bg-canvas');
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Particles
const particlesGeometry = new THREE.BufferGeometry();
const particlesCount = 800;
const posArray = new Float32Array(particlesCount * 3);
for(let i = 0; i < particlesCount * 3; i++) {
posArray[i] = (Math.random() - 0.5) * 15; // Spread
}
particlesGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
// Material - subtle blue-ish dots
const material = new THREE.PointsMaterial({
size: 0.02,
color: 0x3b82f6,
transparent: true,
opacity: 0.6,
blending: THREE.AdditiveBlending
});
const particlesMesh = new THREE.Points(particlesGeometry, material);
scene.add(particlesMesh);
// Lines connecting close particles (Plexus effect)
const lineMaterial = new THREE.LineBasicMaterial({
color: 0x3b82f6,
transparent: true,
opacity: 0.08
});
// We'll draw lines every frame, but for performance with 800 particles, limit to a subset or use shaders.
// For this demo, we will only connect to a small grid or use a moving wave.
// Actually, let's create a flowing "Grid" or "Waves" instead of a full plexus for performance and style.
// Remove points, add wave
scene.remove(particlesMesh);
// Create a flowing wave of particles
const planeGeometry = new THREE.PlaneGeometry(20, 20, 40, 40);
const planeMaterial = new THREE.PointsMaterial({
color: 0x3b82f6,
size: 0.05,
transparent: true,
opacity: 0.4
});
const wave = new THREE.Points(planeGeometry, planeMaterial);
wave.rotation.x = -Math.PI / 2;
scene.add(wave);
camera.position.z = 5;
// Mouse interaction
let mouseX = 0;
let mouseY = 0;
document.addEventListener('mousemove', (event) => {
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
});
// Animation Loop
const clock = new THREE.Clock();
function animate() {
const elapsedTime = clock.getElapsedTime();
// Wave movement
wave.position.y = Math.sin(elapsedTime * 0.5) * 0.2;
wave.position.x = Math.cos(elapsedTime * 0.3) * 0.2;
// Rotate wave slowly
wave.rotation.z = elapsedTime * 0.05;
// React to mouse
camera.position.x += (mouseX * 0.5 - camera.position.x) * 0.02;
camera.position.y += (mouseY * 0.5 - camera.position.y) * 0.02;
camera.lookAt(scene.position);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
// Resize Handler
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
}
// Initialize App
window.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>