developing-preact
Specialized Preact development skill for standards-based web applications with native-first architecture and minimal dependency footprint. Use when building Preact projects, particularly those involving data visualization, interactive applications, single-page apps with HTM synta
Install
npx skills add https://github.com/oaustegard/claude-skills/tree/main/plugins/development-tools/skills/developing-preact
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install oaustegard-claude-skills@llmmart
git clone https://github.com/oaustegard/claude-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole oaustegard/claude-skills collection as a plugin from our marketplace. Git is the plain clone.
README
developing-preact
Specialized Preact development skill for standards-based web applications with native-first architecture and minimal dependency footprint. Use when building Preact projects, particularly those involving data visualization, interactive applications, single-page apps with HTM syntax, Web Components integration, CSV/JSON data parsing, WebGL shader visualizations, or zero-build solutions with CDN imports.
Skill manifest
Preact Developer
Overview
Transform Claude into a specialized Preact developer with expertise in building standards-based web applications using native-first architecture. This skill prioritizes native JavaScript, HTML, and Web APIs over external dependencies, enabling creation of performant, maintainable applications with minimal tooling overhead.
Core Philosophy
Native-First Development: Leverage ES modules, Import Maps, Web Components, native form validation, Fetch API, and built-in DOM methods before reaching for external libraries. Default to zero-build solutions with HTM and vendored ESM imports for rapid prototyping and small-to-medium applications.
Always Deliver in Artifacts: All code should be created as artifacts to enable iterative editing across sessions.
When to Use This Skill
Trigger this skill when working on:
- Preact projects of any complexity level
- Data visualization applications requiring CSV/JSON parsing and interactive charts
- Single-page applications using HTM tagged template literals
- WebGL/shader-based mathematical visualizations
- Web Components integration projects
- Zero-build prototypes with CDN-based dependencies
- Progressive web applications emphasizing accessibility and performance
Project Type Decision Tree
Follow this decision tree to determine the optimal architecture:
1. Standalone Prototype or Demo
Characteristics: Quick prototype, demo, educational example, or proof of concept
Architecture:
- HTM syntax with import maps
- Vendored ESM dependencies (fetched from npm registry via
scripts/vendor.sh) - Tailwind CSS via CLI (purged, minified)
- Single HTML file or minimal file structure
- No build process
Start with: Run bash scripts/vendor.sh to fetch dependencies, then use assets/boilerplate.html as the foundation
2. Small-to-Medium Application (No Build Tooling)
Characteristics: Production application without existing build infrastructure, <10 components, straightforward state management
Architecture:
- HTM syntax with import maps
- ES modules for code organization
- Signals for reactive state management
- Native routing (hash-based or History API)
- Static hosting (Netlify, Vercel, GitHub Pages)
State Management: Use global signals for shared state, useSignal for component-local state
3. Complex Application (Build Tooling Required)
Characteristics: Large codebase, TypeScript requirement, multiple entry points, advanced optimizations needed
Architecture:
- JSX with build tooling (Vite, Webpack)
- TypeScript for type safety
- Consider preact/compat for React ecosystem libraries
- Advanced code splitting and lazy loading
- Professional CI/CD pipeline
When to Recommend: Only after confirming team's development environment and build requirements
4. Existing Project
Approach: Match existing patterns and tooling. Analyze the codebase to determine current architecture before suggesting changes.
Technical Standards
Import Map Configuration
Always use this exact import map structure for standalone examples. Dependencies are vendored locally via scripts/vendor.sh (fetched from registry.npmjs.org):
<script type="importmap">
{
"imports": {
"preact": "./vendor/preact.module.js",
"preact/hooks": "./vendor/hooks.module.js",
"@preact/signals-core": "./vendor/signals-core.mjs",
"@preact/signals": "./vendor/signals.mjs",
"htm": "./vendor/htm.module.js",
"htm/preact": "./vendor/htm.module.js"
}
}
</script>
Critical — modular files, not standalone bundle: Do NOT use htm/preact/standalone.module.js. The standalone bundle embeds its own Preact copy, which causes @preact/signals to get a different Preact instance (it imports from 'preact' as a bare specifier). Modular files + import map = one shared Preact instance for everything.
Why vendored, not CDN: esm.sh is a pass-through to the entire npm registry — allowlisting it opens arbitrary code execution surface. registry.npmjs.org is already on the container egress allowlist and provides scoped, versioned tarballs.
Syntax Preference
Default to HTM tagged template literals unless:
- User explicitly requests JSX
- Project already uses JSX tooling
- TypeScript strict mode requires JSX
JSX to HTM Translation Reference
When mentally converting from React/JSX patterns to HTM, apply these rules:
Mental Model
HTM uses JavaScript template literals. Everything that was {expression} in JSX becomes ${expression}. Component names are also expressions, hence <${Component}>.
Translation Rules
| Pattern | JSX | HTM |
|---|---|---|
| Component tag | <Button /> |
<${Button} /> |
| Component with children | <Modal>...</Modal> |
<${Modal}>...</${Modal}> |
| Closing tag | </Modal> |
</${Modal}> |
| Expression | {value} |
${value} |
| Props | prop={val} |
prop=${val} |
| Spread props | {...obj} |
...${obj} |
| Event handler | onClick={fn} |
onClick=${fn} |
| Conditional | {show && <X />} |
${show && html\<$ />`}` |
| Ternary | {a ? <X /> : <Y />} |
${a ? html\<\({X} />\` : html\`<\) />`}` |
| Map | {items.map(i => <Li />)} |
${items.map(i => html\ |
Key Differences
Component references need
${}: The component name is a JavaScript expression// JSX <Button onClick={handleClick}>Save</Button> // HTM <${Button} onClick=${handleClick}>Save</${Button}>Nested templates for conditional components: When conditionally rendering components (not HTML elements), wrap in
html\``// JSX {isOpen && <Modal title="Hello" />} // HTM ${isOpen && html`<${Modal} title="Hello" />`}No braces for spread: In HTM, spread uses
...${obj}directly// JSX <Input {...inputProps} /> // HTM <${Input} ...${inputProps} />class vs className: Both work in Preact, but prefer
classfor consistency and smaller output
Common Mistakes
| Mistake | Wrong | Correct |
|---|---|---|
Missing ${} on component |
<Button> |
<${Button}> |
| Wrong closing syntax | </MyComponent> |
</${MyComponent}> |
| Braces instead of template | {count} |
${count} |
| Spread with braces | {...props} |
...${props} |
| Missing html wrapper in conditional | ${show && <${X} />} |
${show && html\<$ />`}` |
Component Patterns
Use function components with:
- Hooks for lifecycle and side effects
- Signals for reactive state (preferred over useState)
- Suspense for code splitting and async data
- Context API for cross-component state and dependency injection
- Error boundaries for graceful error handling
Styling Strategy
Default: Tailwind CSS via CLI — install with npm install tailwindcss@3 --save-dev, then generate purged CSS with npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify. This produces ~6KB of CSS containing only used classes.
Avoid: Tailwind CDN (cdn.tailwindcss.com) — not on container egress allowlist, and loads the full 100KB+ JIT compiler.
Avoid: Inline styles except for dynamic values impossible to express through utilities.
Alternative: CSS modules or styled-components only when project requires scoped styling.
Dependency Evaluation Framework
Before recommending any external package, verify:
- Native Web APIs cannot accomplish this - Check MDN documentation
- Preact built-ins are insufficient - Signals, hooks, Context API, preact/compat
- Bundle size cost is justified - Measure actual benefit gained vs. bytes added
Document the specific performance or capability benefits that justify any dependency inclusion.
Architecture Considerations
For complex decisions involving:
- Client-side routing (hash-based vs. History API vs. library)
- SSR requirements
- State management architecture (signals vs. external library)
- preact/compat integration for React libraries
- Performance optimization in constrained environments
Evaluate trade-offs explicitly before committing to an approach. Document reasoning in code comments.
Domain Standards
Progressive Enhancement
Ensure core functionality works without JavaScript where feasible:
- Use semantic HTML
- Leverage native form validation
- Implement keyboard navigation
- Add ARIA attributes for accessibility
- Manage focus states properly
Code Quality
- Generate simplest working solution first
- Document non-obvious Preact patterns in code comments
- Explain hook dependencies
- Note architectural decisions
- Infer TypeScript usage from project context
Development Workflow
1. Understand Requirements
Clarify:
- Target environment (standalone vs. build tools)
- State complexity
- Data sources (CSV, JSON, APIs)
- Accessibility requirements
- Browser support needs
2. Choose Architecture Pattern
Refer to the Project Type Decision Tree above to select the appropriate architecture.
3. Implement Iteratively
Start with:
- Basic HTML structure (use
assets/boilerplate.html) - Core component hierarchy
- State management setup
- Data fetching/parsing logic
- Styling and polish
4. Reference Documentation
Consult bundled references as needed:
references/preact-v10-guide.md- Comprehensive Preact API referencereferences/architecture-patterns.md- Advanced patterns and best practices
5. Use Component Patterns
Leverage assets/component-patterns.md for common UI patterns:
- Data grids with sorting
- File upload with drag & drop
- Search with debouncing
- Modal dialogs
- Tabs
- Toast notifications
- CSV parsing
Common Patterns
Data Parsing (CSV/JSON)
For data-heavy applications:
import { useSignal } from '@preact/signals';
function parseCSV(text) {
const lines = text.trim().split('\n');
const headers = lines[0].split(',').map(h => h.trim());
return lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim());
return Object.fromEntries(headers.map((h, i) => [h, values[i]]));
});
}
function DataAnalyzer() {
const data = useSignal([]);
const handleFile = async (e) => {
const text = await e.target.files[0].text();
data.value = parseCSV(text);
};
return html`
<input type="file" accept=".csv" onChange=${handleFile} />
<div>Loaded ${data.value.length} rows</div>
`;
}
WebGL Integration
For shader-based visualizations:
import { useEffect, useRef } from 'preact/hooks';
function ShaderCanvas({ fragmentShader }) {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
const gl = canvas.getContext('webgl2');
// Setup WebGL context, shaders, buffers
// Render loop
return () => {
// Cleanup
};
}, [fragmentShader]);
return html`<canvas ref=${canvasRef} class="w-full h-full" />`;
}
Global State with Signals
// state.js
import { signal, computed } from '@preact/signals';
export const users = signal([]);
export const currentUser = signal(null);
export const isAuthenticated = computed(() => currentUser.value !== null);
// Any component can import and use
import { users, isAuthenticated } from './state.js';
Constraints
DO NOT:
- Recommend npm tooling without confirming user's development environment
- Suggest dependencies when native solutions exist
- Optimize prematurely - start with simplest working implementation
DO:
- Use HTM syntax by default
- Create artifacts for all code
- Prioritize accessibility and progressive enhancement
- Document architectural decisions in comments
Resources
References (Load as Needed)
references/preact-v10-guide.md: Complete Preact v10 API reference covering import maps, HTM syntax, React differences, Signals API, Web Components, SSR, performance patterns, Context, error boundaries, and common gotchasreferences/architecture-patterns.md: Advanced patterns including zero-build architecture, state management strategies, data fetching, routing, forms, progressive enhancement, accessibility, performance optimization, testing, and security best practices
Assets (Copy into Projects)
assets/boilerplate.html: Complete HTML template with import maps, Tailwind CSS, and basic Preact app structure - use as starting point for all standalone examplesassets/component-patterns.md: Reusable component implementations for data grids, file uploads, search, modals, tabs, toast notifications, and CSV parsing
Examples
Minimal Counter (Standalone)
<!DOCTYPE html>
<html>
<head>
<!-- Run: bash scripts/vendor.sh -->
<script type="importmap">
{
"imports": {
"preact": "./vendor/preact.module.js",
"preact/hooks": "./vendor/hooks.module.js",
"@preact/signals-core": "./vendor/signals-core.mjs",
"@preact/signals": "./vendor/signals.mjs",
"htm": "./vendor/htm.module.js",
"htm/preact": "./vendor/htm.module.js"
}
}
</script>
</head>
<body>
<div id="app"></div>
<script type="module">
import { render } from 'preact';
import { useSignal } from '@preact/signals';
import { html } from 'htm/preact';
function App() {
const count = useSignal(0);
return html`
<button onClick=${() => count.value++}>
Count: ${count}
</button>
`;
}
render(html`<${App} />`, document.getElementById('app'));
</script>
</body>
</html>
Data Visualization App
For applications processing CSV data and displaying interactive charts, reference the DataGrid pattern in assets/component-patterns.md and combine with a charting library like Chart.js or use native Canvas/SVG for custom visualizations.
WebGL Shader Visualization
For mathematical visualizations using WebGL shaders, create a canvas element, initialize WebGL2 context, compile shaders, and set up a render loop. Reference MDN WebGL documentation for shader setup patterns.
Best Practices Summary
- Start Simple: Create working prototype before optimizing
- Use Signals: Prefer signals over useState for reactive state
- Native First: Check if Web APIs can accomplish the task
- Progressive Enhancement: Build with accessibility from the start
- Document Decisions: Explain non-obvious patterns in comments
- Keys in Lists: Always provide stable keys for mapped elements
- Error Boundaries: Wrap async operations in error boundaries
- Avoid Inline Functions: Don't create handlers inside map() loops
Validation Checklist
Before delivering code, verify:
- Import map uses vendored local paths (no CDN URLs)
- HTM syntax is used (unless JSX explicitly requested)
- Keys provided for all mapped elements
- Signals used for reactive state
- Accessibility attributes included (ARIA, keyboard nav)
- Error boundaries wrap async operations
- Loading and error states handled
- Code is in artifact format for iterative editing
- Comments explain non-obvious patterns
- No unnecessary dependencies included
Container Testing
Test Preact apps locally in Claude.ai containers using Playwright. This workflow avoids external CDNs entirely — all dependencies are vendored from registry.npmjs.org.
Setup (one-time per session)
# 1. Vendor JS dependencies
bash scripts/vendor.sh
# 2. Generate Tailwind CSS (if using Tailwind)
npm install tailwindcss@3 --save-dev
npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify
Serve and Test
# 3. Serve locally
python3 -m http.server 8765 &
# 4. Test with Playwright
python3 << 'PYEOF'
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
page = browser.new_page()
errors = []
page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
page.on("pageerror", lambda e: errors.append(str(e)))
page.goto("http://localhost:8765", wait_until="networkidle")
# Verify no console errors (catches import failures immediately)
assert not errors, f"Console errors: {errors}"
# Verify app rendered
assert page.locator("#app").inner_html() != "", "App did not render"
# Example: test interaction
# page.click("button")
# assert "Count: 1" in page.content()
browser.close()
print("All tests passed")
PYEOF
Key guidance
- Use Playwright directly for local testing — not webctl (webctl is for external sites through the proxy)
python3 -m http.serveris sufficient — no npm server needed- Console error capture via
page.on("console")andpage.on("pageerror")catches import failures immediately --no-sandboxis required in container environments
Getting Started
For immediate implementation:
- Run
bash scripts/vendor.shto fetch vendored dependencies - (Optional) Generate Tailwind CSS:
npm install tailwindcss@3 --save-dev && npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify - Copy
assets/boilerplate.htmlas the starting point - Read
references/preact-v10-guide.mdfor API details - Reference
assets/component-patterns.mdfor common UI patterns - Consult
references/architecture-patterns.mdfor advanced scenarios
The skill is designed to enable rapid development of high-quality Preact applications with minimal friction and maximum standards compliance.
Files (claude-skills)
-
assets
-
boilerplate.html 1.9 KB · in bundle
-
component-patterns.md 13.1 KB
# Common Component Patterns This file contains reusable component patterns that can be copied into projects. ## Data Grid with Sorting ```javascript import { useSignal, useComputed } from '@preact/signals'; import { html } from 'htm/preact'; function DataGrid({ data, columns }) { const sortColumn = useSignal(null); const sortDirection = useSignal('asc'); const sortedData = useComputed(() => { if (!sortColumn.value) return data; const sorted = [...data].sort((a, b) => { const aVal = a[sortColumn.value]; const bVal = b[sortColumn.value]; if (typeof aVal === 'string') { return aVal.localeCompare(bVal); } return aVal - bVal; }); return sortDirection.value === 'desc' ? sorted.reverse() : sorted; }); const handleSort = (column) => { if (sortColumn.value === column) { sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'; } else { sortColumn.value = column; sortDirection.value = 'asc'; } }; return html` <div class="overflow-x-auto"> <table class="min-w-full bg-white border border-gray-300"> <thead> <tr class="bg-gray-100"> ${columns.map(col => html` <th key=${col.key} onClick=${() => handleSort(col.key)} class="px-4 py-2 text-left cursor-pointer hover:bg-gray-200" > ${col.label} ${sortColumn.value === col.key && ( sortDirection.value === 'asc' ? ' ↑' : ' ↓' )} </th> `)} </tr> </thead> <tbody> ${sortedData.value.map((row, i) => html` <tr key=${i} class="border-t hover:bg-gray-50"> ${columns.map(col => html` <td key=${col.key} class="px-4 py-2"> ${row[col.key]} </td> `)} </tr> `)} </tbody> </table> </div> `; } // Usage: // const columns = [ // { key: 'name', label: 'Name' }, // { key: 'age', label: 'Age' }, // { key: 'email', label: 'Email' } // ]; // html`<${DataGrid} data=${users} columns=${columns} />`; ``` ## File Upload with Drag & Drop ```javascript import { useSignal } from '@preact/signals'; import { html } from 'htm/preact'; function FileUpload({ onFileSelect, accept = '*' }) { const isDragging = useSignal(false); const files = useSignal([]); const handleDragOver = (e) => { e.preventDefault(); isDragging.value = true; }; const handleDragLeave = (e) => { e.preventDefault(); isDragging.value = false; }; const handleDrop = (e) => { e.preventDefault(); isDragging.value = false; const droppedFiles = Array.from(e.dataTransfer.files); files.value = droppedFiles; onFileSelect?.(droppedFiles); }; const handleFileInput = (e) => { const selectedFiles = Array.from(e.target.files); files.value = selectedFiles; onFileSelect?.(selectedFiles); }; return html` <div class=${`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${ isDragging.value ? 'border-blue-500 bg-blue-50' : 'border-gray-300 bg-gray-50' }`} onDragOver=${handleDragOver} onDragLeave=${handleDragLeave} onDrop=${handleDrop} > <input type="file" onChange=${handleFileInput} accept=${accept} multiple class="hidden" id="file-input" /> <label for="file-input" class="cursor-pointer"> <div class="text-gray-600"> <p class="text-lg font-semibold mb-2"> Drop files here or click to browse </p> <p class="text-sm"> ${accept === '*' ? 'Any file type' : `Accepts: ${accept}`} </p> </div> </label> ${files.value.length > 0 && html` <div class="mt-4"> <p class="font-semibold mb-2">Selected files:</p> <ul class="text-sm text-left"> ${files.value.map(file => html` <li key=${file.name} class="py-1"> ${file.name} (${(file.size / 1024).toFixed(1)} KB) </li> `)} </ul> </div> `} </div> `; } // Usage: // html`<${FileUpload} // accept=".csv,.json" // onFileSelect=${(files) => console.log(files)} // />`; ``` ## Search with Debouncing ```javascript import { useSignal, useSignalEffect } from '@preact/signals'; import { html } from 'htm/preact'; function SearchBox({ onSearch, placeholder = 'Search...', debounceMs = 300 }) { const query = useSignal(''); const results = useSignal([]); const loading = useSignal(false); useSignalEffect(() => { const currentQuery = query.value; if (!currentQuery) { results.value = []; return; } loading.value = true; const timer = setTimeout(async () => { try { const data = await onSearch(currentQuery); // Only update if query hasn't changed if (query.value === currentQuery) { results.value = data; loading.value = false; } } catch (error) { console.error('Search failed:', error); loading.value = false; } }, debounceMs); return () => clearTimeout(timer); }); return html` <div class="relative"> <input type="text" value=${query} onInput=${e => query.value = e.target.value} placeholder=${placeholder} class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> ${loading.value && html` <div class="absolute right-3 top-3"> <div class="animate-spin h-5 w-5 border-2 border-blue-500 border-t-transparent rounded-full"></div> </div> `} ${results.value.length > 0 && html` <div class="absolute z-10 w-full mt-2 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"> ${results.value.map(result => html` <div key=${result.id} class="px-4 py-2 hover:bg-gray-100 cursor-pointer" onClick=${() => { query.value = result.name; results.value = []; }} > ${result.name} </div> `)} </div> `} </div> `; } // Usage: // const searchUsers = async (query) => { // const response = await fetch(`/api/users?q=${query}`); // return response.json(); // }; // html`<${SearchBox} onSearch=${searchUsers} />`; ``` ## Modal Dialog ```javascript import { useEffect, useRef } from 'preact/hooks'; import { html } from 'htm/preact'; function Modal({ isOpen, onClose, title, children }) { const modalRef = useRef(null); const previousFocus = useRef(null); useEffect(() => { if (!isOpen) return; // Store previously focused element previousFocus.current = document.activeElement; // Focus modal modalRef.current?.focus(); // Handle escape key const handleEscape = (e) => { if (e.key === 'Escape') onClose(); }; document.addEventListener('keydown', handleEscape); // Prevent body scroll document.body.style.overflow = 'hidden'; return () => { document.removeEventListener('keydown', handleEscape); document.body.style.overflow = ''; previousFocus.current?.focus(); }; }, [isOpen, onClose]); if (!isOpen) return null; return html` <div class="fixed inset-0 z-50 flex items-center justify-center" onClick=${onClose} > <div class="fixed inset-0 bg-black bg-opacity-50"></div> <div ref=${modalRef} tabindex="-1" role="dialog" aria-modal="true" aria-labelledby="modal-title" class="relative z-10 bg-white rounded-lg shadow-xl max-w-md w-full mx-4 p-6" onClick=${e => e.stopPropagation()} > <div class="flex justify-between items-center mb-4"> <h2 id="modal-title" class="text-xl font-bold"> ${title} </h2> <button onClick=${onClose} aria-label="Close modal" class="text-gray-500 hover:text-gray-700" > ✕ </button> </div> <div class="mb-4"> ${children} </div> </div> </div> `; } // Usage: // const isOpen = useSignal(false); // html` // <button onClick=${() => isOpen.value = true}>Open Modal</button> // <${Modal} // isOpen=${isOpen.value} // onClose=${() => isOpen.value = false} // title="Confirm Action" // > // <p>Are you sure you want to proceed?</p> // <div class="flex gap-2 mt-4"> // <button class="px-4 py-2 bg-blue-500 text-white rounded"> // Confirm // </button> // <button // onClick=${() => isOpen.value = false} // class="px-4 py-2 bg-gray-200 rounded" // > // Cancel // </button> // </div> // </${Modal}> // `; ``` ## Tabs Component ```javascript import { useSignal } from '@preact/signals'; import { html } from 'htm/preact'; function Tabs({ tabs }) { const activeTab = useSignal(0); return html` <div class="w-full"> <div class="flex border-b border-gray-300"> ${tabs.map((tab, index) => html` <button key=${index} onClick=${() => activeTab.value = index} class=${`px-4 py-2 font-medium transition-colors ${ activeTab.value === index ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-800' }`} > ${tab.label} </button> `)} </div> <div class="p-4"> ${tabs[activeTab.value]?.content} </div> </div> `; } // Usage: // const tabs = [ // { label: 'Profile', content: html`<div>Profile content</div>` }, // { label: 'Settings', content: html`<div>Settings content</div>` }, // { label: 'History', content: html`<div>History content</div>` } // ]; // html`<${Tabs} tabs=${tabs} />`; ``` ## Toast Notifications ```javascript import { signal } from '@preact/signals'; import { html } from 'htm/preact'; // Global toast state const toasts = signal([]); let toastId = 0; function addToast(message, type = 'info', duration = 3000) { const id = toastId++; toasts.value = [...toasts.value, { id, message, type }]; if (duration > 0) { setTimeout(() => { removeToast(id); }, duration); } } function removeToast(id) { toasts.value = toasts.value.filter(t => t.id !== id); } function ToastContainer() { return html` <div class="fixed top-4 right-4 z-50 space-y-2"> ${toasts.value.map(toast => { const bgColor = { info: 'bg-blue-500', success: 'bg-green-500', warning: 'bg-yellow-500', error: 'bg-red-500' }[toast.type] || 'bg-gray-500'; return html` <div key=${toast.id} class=${`${bgColor} text-white px-6 py-3 rounded-lg shadow-lg flex items-center gap-3 animate-slideIn`} > <span>${toast.message}</span> <button onClick=${() => removeToast(toast.id)} class="text-white hover:text-gray-200" > ✕ </button> </div> `; })} </div> `; } // Usage: // Add this to your main App component: // html`<${ToastContainer} />` // // Then call from anywhere: // addToast('Operation successful!', 'success'); // addToast('Something went wrong', 'error'); ``` ## CSV Parser Component ```javascript import { useSignal } from '@preact/signals'; import { html } from 'htm/preact'; function parseCSV(text) { const lines = text.trim().split('\n'); const headers = lines[0].split(',').map(h => h.trim()); const data = lines.slice(1).map(line => { const values = line.split(',').map(v => v.trim()); const obj = {}; headers.forEach((header, i) => { obj[header] = values[i]; }); return obj; }); return { headers, data }; } function CSVUploader({ onDataParsed }) { const status = useSignal(''); const handleFile = async (e) => { const file = e.target.files[0]; if (!file) return; status.value = 'Parsing...'; try { const text = await file.text(); const parsed = parseCSV(text); onDataParsed(parsed); status.value = `Parsed ${parsed.data.length} rows`; } catch (error) { status.value = `Error: ${error.message}`; } }; return html` <div class="space-y-4"> <input type="file" accept=".csv" onChange=${handleFile} class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" /> ${status.value && html` <p class="text-sm text-gray-600">${status}</p> `} </div> `; } // Usage: // html`<${CSVUploader} // onDataParsed=${({ headers, data }) => { // console.log('Headers:', headers); // console.log('Data:', data); // }} // />`; ```
-
-
references
-
architecture-patterns.md 11.7 KB
# Architecture Patterns & Best Practices ## Native-First Development Philosophy Prioritize native JavaScript, HTML, and Web APIs over external dependencies. This approach delivers: - Smaller bundle sizes - Better performance - Reduced maintenance burden - Future-proof code that doesn't depend on library churn ### Decision Framework for Dependencies Before adding any external package, verify: 1. **Native APIs cannot accomplish this** - Check MDN and Can I Use 2. **Preact built-ins are insufficient** - signals, hooks, Context API 3. **Bundle size cost is justified** - Measure the actual benefit gained ## Zero-Build Architecture For prototypes, demos, and small applications, use: - ES modules vendored from npm registry (`scripts/vendor.sh`) - Import maps for dependency management - HTM for zero-transpilation JSX-like syntax - Tailwind CSS via CLI (purged, minified to `vendor/tailwind.css`) ### When to Introduce Build Tools Consider build tooling when: - TypeScript is required for team collaboration - Code splitting across multiple entry points is needed - CSS preprocessing (beyond Tailwind) is essential - Bundle optimization for production is critical ## State Management Patterns ### Local Component State Use for isolated component logic: ```javascript import { useSignal } from '@preact/signals'; function Counter() { const count = useSignal(0); return html` <button onClick=${() => count.value++}> Count: ${count} </button> `; } ``` ### Global Signals Use for shared state across components: ```javascript // state.js import { signal } from '@preact/signals'; export const currentUser = signal(null); export const isAuthenticated = signal(false); // Any component can import and use import { currentUser } from './state.js'; ``` ### Context API Use for dependency injection and theme/config: ```javascript import { createContext } from 'preact'; import { useContext } from 'preact/hooks'; const ApiContext = createContext(null); function App() { const api = createApiClient(); return html` <${ApiContext.Provider} value=${api}> <${MainApp} /> </${ApiContext.Provider}> `; } ``` ### External State Libraries Consider Zustand or Jotai only when: - Complex state derivations are needed - Dev tools and time-travel debugging are required - Team has existing patterns with these libraries ## Data Fetching Patterns ### Simple Fetch with Hooks ```javascript import { useSignal, useSignalEffect } from '@preact/signals'; function UserProfile({ userId }) { const user = useSignal(null); const loading = useSignal(true); const error = useSignal(null); useSignalEffect(() => { loading.value = true; fetch(`/api/users/${userId}`) .then(r => r.json()) .then(data => { user.value = data; loading.value = false; }) .catch(err => { error.value = err; loading.value = false; }); }); if (loading.value) return html`<div>Loading...</div>`; if (error.value) return html`<div>Error: ${error.value.message}</div>`; return html`<div>${user.value.name}</div>`; } ``` ### Suspense for Async Data ```javascript import { Suspense, lazy } from 'preact/compat'; // Resource pattern function wrapPromise(promise) { let status = 'pending'; let result; const suspender = promise.then( r => { status = 'success'; result = r; }, e => { status = 'error'; result = e; } ); return { read() { if (status === 'pending') throw suspender; if (status === 'error') throw result; return result; } }; } const userResource = wrapPromise(fetch('/api/user').then(r => r.json())); function UserData() { const user = userResource.read(); return html`<div>${user.name}</div>`; } function App() { return html` <${Suspense} fallback=${html`<div>Loading...</div>`}> <${UserData} /> </${Suspense}> `; } ``` ## Routing Strategies ### Hash-based Routing (Simplest) ```javascript import { useSignal, useSignalEffect } from '@preact/signals'; const currentRoute = signal(window.location.hash.slice(1) || '/'); window.addEventListener('hashchange', () => { currentRoute.value = window.location.hash.slice(1) || '/'; }); function App() { return html` <nav> <a href="#/">Home</a> <a href="#/about">About</a> </nav> ${currentRoute.value === '/' && html`<${HomePage} />`} ${currentRoute.value === '/about' && html`<${AboutPage} />`} `; } ``` ### History API Routing (Production) Consider preact-router or wouter for: - Clean URLs without hashes - Server-side rendering requirements - Nested route patterns ## Form Handling ### Native Form Validation Leverage HTML5 validation before JavaScript: ```javascript function SignupForm() { const handleSubmit = (e) => { e.preventDefault(); if (!e.target.checkValidity()) return; const formData = new FormData(e.target); const data = Object.fromEntries(formData); // Submit data }; return html` <form onSubmit=${handleSubmit}> <input name="email" type="email" required placeholder="Email" /> <input name="password" type="password" required minlength="8" placeholder="Password" /> <button type="submit">Sign Up</button> </form> `; } ``` ### Controlled Inputs with Signals ```javascript function SearchBox() { const query = useSignal(''); return html` <input value=${query} onInput=${e => query.value = e.target.value} placeholder="Search..." /> <div>Results for: ${query}</div> `; } ``` ## Progressive Enhancement ### Core Principles 1. **HTML First** - Structure works without JavaScript 2. **CSS for Presentation** - Visual design doesn't require JS 3. **JavaScript for Enhancement** - Adds interactivity and polish ### Example: Accordion ```javascript // Works without JS (details/summary), enhanced with JS function Accordion({ items }) { const openItems = useSignal(new Set()); return html` <div> ${items.map((item, i) => html` <details key=${item.id} open=${openItems.value.has(i)} onToggle=${e => { const newSet = new Set(openItems.value); if (e.target.open) { newSet.add(i); } else { newSet.delete(i); } openItems.value = newSet; }} > <summary>${item.title}</summary> <div>${item.content}</div> </details> `)} </div> `; } ``` ## Accessibility Patterns ### Keyboard Navigation ```javascript function Modal({ isOpen, onClose, children }) { const modalRef = useRef(null); useEffect(() => { if (!isOpen) return; const handleKeyDown = (e) => { if (e.key === 'Escape') onClose(); }; document.addEventListener('keydown', handleKeyDown); modalRef.current?.focus(); return () => document.removeEventListener('keydown', handleKeyDown); }, [isOpen, onClose]); if (!isOpen) return null; return html` <div role="dialog" aria-modal="true" ref=${modalRef} tabindex="-1" > ${children} </div> `; } ``` ### ARIA Labels and Live Regions ```javascript function SearchResults({ results, loading }) { return html` <div> <div role="status" aria-live="polite" aria-atomic="true" > ${loading ? 'Loading results...' : `${results.length} results found`} </div> <ul role="list"> ${results.map(r => html` <li key=${r.id}>${r.title}</li> `)} </ul> </div> `; } ``` ## Performance Optimization ### Code Splitting ```javascript import { Suspense, lazy } from 'preact/compat'; const HeavyComponent = lazy(() => import('./HeavyComponent.js')); function App() { return html` <${Suspense} fallback=${html`<div>Loading...</div>`}> <${HeavyComponent} /> </${Suspense}> `; } ``` ### Memoization ```javascript import { useMemo } from 'preact/hooks'; import { memo } from 'preact/compat'; // Memoize expensive computations function DataGrid({ rows }) { const sortedRows = useMemo( () => rows.sort((a, b) => a.name.localeCompare(b.name)), [rows] ); return html`<table>...</table>`; } // Memoize components const ExpensiveRow = memo(({ data }) => html` <tr> <td>${data.name}</td> <td>${data.value}</td> </tr> `); ``` ### Virtual Scrolling For large lists (1000+ items), consider: - react-window (via preact/compat) - Manual implementation with Intersection Observer ## Testing Strategies ### Unit Testing Components ```javascript import { render } from '@testing-library/preact'; import { html } from 'htm/preact'; test('Counter increments', async () => { const { getByText } = render(html`<${Counter} />`); const button = getByText(/count:/i); fireEvent.click(button); expect(button.textContent).toBe('Count: 1'); }); ``` ### E2E Testing Use Playwright or Cypress for: - Critical user flows - Cross-browser testing - Visual regression testing ## Common Pitfalls ### 1. Overusing Signals for Local State ```javascript // BAD - Signal not needed for local state function Toggle() { const isOpen = signal(false); // Global signal! // ... } // GOOD - Use useSignal for component-local state function Toggle() { const isOpen = useSignal(false); // ... } ``` ### 2. Forgetting Keys in Lists ```javascript // BAD - No keys items.map(item => html`<li>${item.name}</li>`) // GOOD - Stable keys items.map(item => html`<li key=${item.id}>${item.name}</li>`) ``` ### 3. Missing Error Boundaries Always wrap async operations in error boundaries: ```javascript function App() { return html` <${ErrorBoundary}> <${Suspense} fallback=${html`<Loading />`}> <${AsyncComponent} /> </${Suspense}> </${ErrorBoundary}> `; } ``` ### 4. Inline Function Creation in Loops ```javascript // BAD - Creates new function every render items.map(item => html` <button onClick=${() => handleClick(item.id)}> ${item.name} </button> `) // GOOD - Create handler outside loop or use data attributes const handleItemClick = (e) => { const id = e.target.dataset.id; handleClick(id); }; items.map(item => html` <button onClick=${handleItemClick} data-id=${item.id}> ${item.name} </button> `) ``` ## CSS Architecture ### Utility-First with Tailwind Prefer Tailwind utilities for rapid development: ```javascript html` <div class="flex items-center gap-4 p-4 bg-white rounded-lg shadow"> <img class="w-12 h-12 rounded-full" src=${avatar} /> <div> <h3 class="text-lg font-semibold">${name}</h3> <p class="text-gray-600">${email}</p> </div> </div> ` ``` ### Custom CSS When Needed For complex layouts or animations: ```html <style> @keyframes slideIn { from { transform: translateX(-100%); } to { transform: translateX(0); } } .sidebar { animation: slideIn 0.3s ease-out; } </style> ``` ### CSS Modules (with Build Tools) For component-scoped styles in larger apps: ```javascript import styles from './Button.module.css'; function Button({ children }) { return html` <button class=${styles.button}> ${children} </button> `; } ``` ## Security Best Practices ### XSS Prevention Never use `dangerouslySetInnerHTML` with user content: ```javascript // BAD - XSS vulnerability <div dangerouslySetInnerHTML=${{ __html: userInput }} /> // GOOD - Preact escapes by default <div>${userInput}</div> ``` ### CSRF Protection For forms that mutate state: ```javascript function DeleteForm({ itemId, csrfToken }) { const handleDelete = async () => { await fetch(`/api/items/${itemId}`, { method: 'DELETE', headers: { 'X-CSRF-Token': csrfToken } }); }; return html` <button onClick=${handleDelete}>Delete</button> `; } ``` -
preact-v10-guide.md 8 KB
# Preact v10 - Comprehensive Reference Guide ## Import Map Configuration ### Standard Setup (Use for all standalone examples) Vendor dependencies first: `bash scripts/vendor.sh` ```html <script type="importmap"> { "imports": { "preact": "./vendor/preact.module.js", "preact/hooks": "./vendor/hooks.module.js", "@preact/signals-core": "./vendor/signals-core.mjs", "@preact/signals": "./vendor/signals.mjs", "htm": "./vendor/htm.module.js", "htm/preact": "./vendor/htm.module.js" } } </script> ``` ### With React Aliasing (for React ecosystem compatibility) For compat mode, vendor additional files from the preact package (`compat/dist/compat.module.js`) and add to the import map: ```html <script type="importmap"> { "imports": { "preact": "./vendor/preact.module.js", "preact/hooks": "./vendor/hooks.module.js", "react": "./vendor/compat.module.js", "react-dom": "./vendor/compat.module.js", "@preact/signals-core": "./vendor/signals-core.mjs", "@preact/signals": "./vendor/signals.mjs", "htm": "./vendor/htm.module.js", "htm/preact": "./vendor/htm.module.js" } } </script> ``` **Critical Note**: Use modular vendor files (not standalone bundles) so all packages share a single Preact instance via import map resolution. See SKILL.md for rationale. ## HTM Syntax (Default Preference) ### Basic Usage ```javascript import { render } from 'preact'; import { html } from 'htm/preact'; function App() { return html` <div class="container"> <h1>Hello World</h1> </div> `; } render(html`<${App} />`, document.getElementById('app')); ``` ### Dynamic Values & Props ```javascript const name = 'World'; const count = 42; html` <div class=${className}> <h1>Hello ${name}!</h1> <button onClick=${handleClick}>Count: ${count}</button> <${CustomComponent} value=${count} /> </div> `; ``` ### Conditional Rendering ```javascript html` <div> ${isLoggedIn && html`<UserProfile />`} ${error ? html`<ErrorMessage />` : html`<Content />`} </div> `; ``` ### Lists & Keys ```javascript html` <ul> ${items.map(item => html` <li key=${item.id}>${item.name}</li> `)} </ul> `; ``` ## Key Differences from React ### Event Handling **Preact uses native DOM events** (not synthetic): ```javascript // React - uses onChange <input onChange={e => console.log(e.currentTarget.value)} /> // Preact core - use onInput for text inputs <input onInput={e => console.log(e.currentTarget.value)} /> // Preact with preact/compat - onChange works like React ``` **Event names are case-sensitive** for custom events. ### Props vs Attributes Preact **automatically detects** whether to use property or attribute: ```javascript // Sets property (because setter exists) <input value=${text} /> // Sets attribute (no corresponding property) <div data-foo=${value} /> // SVG: use exact attribute names <circle fill="none" stroke-width="2" /> ``` ### Children Handling `props.children` is **not always an array**: ```javascript import { toChildArray } from 'preact'; // WRONG - may break function Bad(props) { const count = props.children.length; // Error if children isn't array } // CORRECT function Good(props) { const count = toChildArray(props.children).length; } ``` ### State Updates are Asynchronous **Never read state immediately after setState**: ```javascript // WRONG this.setState({ counter: this.state.counter + 1 }); // CORRECT this.setState(prevState => ({ counter: prevState.counter + 1 })); ``` ### Class vs className Both work, but `class` is preferred (smaller): ```javascript <div class="foo" /> // Preferred <div className="foo" /> // Also works ``` ## Signals API ### Core Concepts Signals are **reactive primitives** that auto-update components: ```javascript import { signal, computed, effect } from '@preact/signals'; // Create signal const count = signal(0); // Read value console.log(count.value); // 0 // Update value count.value += 1; // Use directly in JSX (auto-subscribes) function Counter() { return html`<div>Count: ${count}</div>`; } ``` ### Computed Signals **Derived values** that auto-update: ```javascript const firstName = signal('John'); const lastName = signal('Doe'); const fullName = computed(() => `${firstName.value} ${lastName.value}` ); // Auto-updates when dependencies change firstName.value = 'Jane'; console.log(fullName.value); // "Jane Doe" ``` ### Effects Run **side effects** when signals change: ```javascript effect(() => { console.log(`Count is now: ${count.value}`); // Optional cleanup return () => { console.log('Cleaning up'); }; }); count.value = 5; // Logs: "Count is now: 5" ``` ### Batching Updates ```javascript import { batch } from '@preact/signals'; batch(() => { count.value = 1; text.value = "updated"; // Only triggers one re-render }); ``` ### Hooks Integration ```javascript import { useSignal, useComputed } from '@preact/signals'; function Counter() { const count = useSignal(0); const double = useComputed(() => count.value * 2); return html` <div> <p>${count} x 2 = ${double}</p> <button onClick=${() => count.value++}>Increment</button> </div> `; } ``` ## Web Components Integration ### Using Web Components Preact **detects property setters** automatically: ```javascript // Custom element with property setter customElements.define('context-menu', class extends HTMLElement { set position({ x, y }) { this.style.cssText = `left:${x}px; top:${y}px;`; } }); // Preact uses property (not attribute) because setter exists <context-menu position=${{ x: 10, y: 20 }} /> ``` ### Accessing Methods via Refs ```javascript import { useRef, useEffect } from 'preact/hooks'; function Foo() { const myRef = useRef(null); useEffect(() => { if (myRef.current) { myRef.current.doSomething(); // Call custom element method } }, []); return html`<x-foo ref=${myRef} />`; } ``` ## Performance Patterns ### Prevent Re-renders ```javascript import { memo } from 'preact/compat'; // Only re-renders when props change const Expensive = memo(({ value }) => html` <div>${value}</div> `); ``` ### Skip Virtual DOM with Signals ```javascript // Re-renders component when count changes function Unoptimized() { return html`<p>${count.value}</p>`; } // Updates text directly without component re-render function Optimized() { return html`<p>${count}</p>`; // No .value access } ``` ## Context API ```javascript import { createContext } from 'preact'; import { useContext } from 'preact/hooks'; const Theme = createContext('light'); function ThemedButton() { const theme = useContext(Theme); return html`<button class="btn-${theme}">Click</button>`; } function App() { return html` <${Theme.Provider} value="dark"> <${ThemedButton} /> </${Theme.Provider}> `; } ``` ## Error Boundaries ```javascript class ErrorBoundary extends Component { constructor() { super(); this.state = { errored: false }; } static getDerivedStateFromError(error) { return { errored: true }; } componentDidCatch(error, errorInfo) { logErrorToService(error, errorInfo); } render(props, state) { if (state.errored) { return html`<p>Something went wrong</p>`; } return props.children; } } ``` ## Common Gotchas ### 1. Keys Required in Loops ```javascript // WRONG - no key items.map(item => html`<li>${item}</li>`) // CORRECT items.map(item => html`<li key=${item.id}>${item}</li>`) ``` ### 2. useEffect Cleanup Must Return Function ```javascript // WRONG useEffect(() => { subscription.subscribe(); subscription.unsubscribe(); // Called immediately! }); // CORRECT useEffect(() => { subscription.subscribe(); return () => subscription.unsubscribe(); }); ``` ### 3. Refs Need Null Checks ```javascript const inputRef = useRef(null); useEffect(() => { if (inputRef.current) { inputRef.current.focus(); } }, []); ``` ## Version Info - Core: Preact 10.x - Signals: @preact/signals 1.3.x - HTM: 3.1.x - Target: Modern browsers with ES2015+ support
-
-
scripts
-
vendor.sh 2.3 KB
#!/usr/bin/env bash # vendor.sh — Download Preact ecosystem ESM modules from npm registry # # Usage: ./vendor.sh [output_dir] # output_dir: where to write vendor files (default: ./vendor) # # Downloads modular ESM files (not standalone bundles) so that # @preact/signals can resolve 'preact' and 'preact/hooks' via # import map to a single shared Preact instance. set -euo pipefail VENDOR_DIR="${1:-./vendor}" mkdir -p "$VENDOR_DIR" # Package versions — update these as needed PREACT_VER="10.23.1" SIGNALS_CORE_VER="1.8.0" SIGNALS_VER="1.3.0" HTM_VER="3.1.1" # Fetch a single file from an npm package tarball. # Args: package_name version tarball_path output_filename fetch_npm_file() { local pkg="$1" ver="$2" tpath="$3" outfile="$4" local tarball_url # Get tarball URL from registry metadata tarball_url=$(curl -sL "https://registry.npmjs.org/${pkg}/${ver}" \ | python3 -c "import sys,json; print(json.load(sys.stdin)['dist']['tarball'])") # Download tarball and extract the single file we need curl -sL "$tarball_url" \ | tar -xzf - --to-stdout "package/${tpath}" \ > "${VENDOR_DIR}/${outfile}" local size size=$(wc -c < "${VENDOR_DIR}/${outfile}") echo " ✓ ${outfile} (${size} bytes)" } echo "Vendoring Preact ecosystem into ${VENDOR_DIR}/" echo "" echo "Preact ${PREACT_VER}:" fetch_npm_file "preact" "$PREACT_VER" \ "dist/preact.module.js" "preact.module.js" fetch_npm_file "preact" "$PREACT_VER" \ "hooks/dist/hooks.module.js" "hooks.module.js" echo "" echo "@preact/signals-core ${SIGNALS_CORE_VER}:" fetch_npm_file "@preact/signals-core" "$SIGNALS_CORE_VER" \ "dist/signals-core.mjs" "signals-core.mjs" echo "" echo "@preact/signals ${SIGNALS_VER}:" fetch_npm_file "@preact/signals" "$SIGNALS_VER" \ "dist/signals.mjs" "signals.mjs" echo "" echo "HTM ${HTM_VER}:" fetch_npm_file "htm" "$HTM_VER" \ "dist/htm.module.js" "htm.module.js" echo "" echo "Done. Total vendored size:" du -sh "$VENDOR_DIR" echo "" echo "Use this import map in your HTML:" cat << 'IMPORTMAP' <script type="importmap"> { "imports": { "preact": "./vendor/preact.module.js", "preact/hooks": "./vendor/hooks.module.js", "@preact/signals-core": "./vendor/signals-core.mjs", "@preact/signals": "./vendor/signals.mjs", "htm": "./vendor/htm.module.js", "htm/preact": "./vendor/htm.module.js" } } </script> IMPORTMAP
-
-
CHANGELOG.md 991 B
# developing-preact - Changelog All notable changes to the `developing-preact` skill are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.2.1] - 2026-09-09 ### Added - add mapping-features skill for behavioral web app documentation (#432) ### Fixed - repair broken frontmatter, mark obsolete skills, close registry gaps (#746) ### Other - prompt-audit: dated prompting patterns across the skill catalogue (#791) - Remove _MAP.md files, direct agents to tree-sitting for code navigation (#545) - Add SessionStart hook for automatic Muninn boot ## [1.2.0] - 2026-03-08 ### Added - replace esm.sh CDN with vendored deps + container testing - add line numbers, markdown ToC, and other files listing - add code maps and CLAUDE.md integration guidance - Delete VERSION files, complete migration to frontmatter - Migrate all 27 skills from VERSION files to frontmatter ### Fixed - limit markdown ToC to h1/h2 headings only -
README.md 426 B
# developing-preact Specialized Preact development skill for standards-based web applications with native-first architecture and minimal dependency footprint. Use when building Preact projects, particularly those involving data visualization, interactive applications, single-page apps with HTM syntax, Web Components integration, CSV/JSON data parsing, WebGL shader visualizations, or zero-build solutions with CDN imports. -
SKILL.md 17.8 KB
--- name: developing-preact description: Specialized Preact development skill for standards-based web applications with native-first architecture and minimal dependency footprint. Use when building Preact projects, particularly those involving data visualization, interactive applications, single-page apps with HTM syntax, Web Components integration, CSV/JSON data parsing, WebGL shader visualizations, or zero-build solutions with vendored ESM imports. metadata: version: 1.2.1 --- # Preact Developer ## Overview Transform Claude into a specialized Preact developer with expertise in building standards-based web applications using native-first architecture. This skill prioritizes native JavaScript, HTML, and Web APIs over external dependencies, enabling creation of performant, maintainable applications with minimal tooling overhead. ## Core Philosophy **Native-First Development**: Leverage ES modules, Import Maps, Web Components, native form validation, Fetch API, and built-in DOM methods before reaching for external libraries. Default to zero-build solutions with HTM and vendored ESM imports for rapid prototyping and small-to-medium applications. **Always Deliver in Artifacts**: All code should be created as artifacts to enable iterative editing across sessions. ## When to Use This Skill Trigger this skill when working on: - **Preact projects** of any complexity level - **Data visualization applications** requiring CSV/JSON parsing and interactive charts - **Single-page applications** using HTM tagged template literals - **WebGL/shader-based** mathematical visualizations - **Web Components** integration projects - **Zero-build prototypes** with CDN-based dependencies - **Progressive web applications** emphasizing accessibility and performance ## Project Type Decision Tree Follow this decision tree to determine the optimal architecture: ### 1. Standalone Prototype or Demo **Characteristics**: Quick prototype, demo, educational example, or proof of concept **Architecture**: - HTM syntax with import maps - Vendored ESM dependencies (fetched from npm registry via `scripts/vendor.sh`) - Tailwind CSS via CLI (purged, minified) - Single HTML file or minimal file structure - No build process **Start with**: Run `bash scripts/vendor.sh` to fetch dependencies, then use `assets/boilerplate.html` as the foundation ### 2. Small-to-Medium Application (No Build Tooling) **Characteristics**: Production application without existing build infrastructure, <10 components, straightforward state management **Architecture**: - HTM syntax with import maps - ES modules for code organization - Signals for reactive state management - Native routing (hash-based or History API) - Static hosting (Netlify, Vercel, GitHub Pages) **State Management**: Use global signals for shared state, useSignal for component-local state ### 3. Complex Application (Build Tooling Required) **Characteristics**: Large codebase, TypeScript requirement, multiple entry points, advanced optimizations needed **Architecture**: - JSX with build tooling (Vite, Webpack) - TypeScript for type safety - Consider preact/compat for React ecosystem libraries - Advanced code splitting and lazy loading - Professional CI/CD pipeline **When to Recommend**: Only after confirming team's development environment and build requirements ### 4. Existing Project **Approach**: Match existing patterns and tooling. Analyze the codebase to determine current architecture before suggesting changes. ## Technical Standards ### Import Map Configuration Always use this exact import map structure for standalone examples. Dependencies are vendored locally via `scripts/vendor.sh` (fetched from `registry.npmjs.org`): ```html <script type="importmap"> { "imports": { "preact": "./vendor/preact.module.js", "preact/hooks": "./vendor/hooks.module.js", "@preact/signals-core": "./vendor/signals-core.mjs", "@preact/signals": "./vendor/signals.mjs", "htm": "./vendor/htm.module.js", "htm/preact": "./vendor/htm.module.js" } } </script> ``` **Critical — modular files, not standalone bundle**: Do NOT use `htm/preact/standalone.module.js`. The standalone bundle embeds its own Preact copy, which causes `@preact/signals` to get a different Preact instance (it imports `from 'preact'` as a bare specifier). Modular files + import map = one shared Preact instance for everything. **Why vendored, not CDN**: `esm.sh` is a pass-through to the entire npm registry — allowlisting it opens arbitrary code execution surface. `registry.npmjs.org` is already on the container egress allowlist and provides scoped, versioned tarballs. ### Syntax Preference **Default to HTM** tagged template literals unless: - User explicitly requests JSX - Project already uses JSX tooling - TypeScript strict mode requires JSX ### JSX to HTM Translation Reference When mentally converting from React/JSX patterns to HTM, apply these rules: #### Mental Model HTM uses JavaScript template literals. Everything that was `{expression}` in JSX becomes `${expression}`. Component *names* are also expressions, hence `<${Component}>`. #### Translation Rules | Pattern | JSX | HTM | |---------|-----|-----| | Component tag | `<Button />` | `<${Button} />` | | Component with children | `<Modal>...</Modal>` | `<${Modal}>...</${Modal}>` | | Closing tag | `</Modal>` | `</${Modal}>` | | Expression | `{value}` | `${value}` | | Props | `prop={val}` | `prop=${val}` | | Spread props | `{...obj}` | `...${obj}` | | Event handler | `onClick={fn}` | `onClick=${fn}` | | Conditional | `{show && <X />}` | `${show && html\`<${X} />\`}` | | Ternary | `{a ? <X /> : <Y />}` | `${a ? html\`<${X} />\` : html\`<${Y} />\`}` | | Map | `{items.map(i => <Li />)}` | `${items.map(i => html\`<li>...</li>\`)}` | #### Key Differences 1. **Component references need `${}`**: The component name is a JavaScript expression ```javascript // JSX <Button onClick={handleClick}>Save</Button> // HTM <${Button} onClick=${handleClick}>Save</${Button}> ``` 2. **Nested templates for conditional components**: When conditionally rendering components (not HTML elements), wrap in `html\`\`` ```javascript // JSX {isOpen && <Modal title="Hello" />} // HTM ${isOpen && html`<${Modal} title="Hello" />`} ``` 3. **No braces for spread**: In HTM, spread uses `...${obj}` directly ```javascript // JSX <Input {...inputProps} /> // HTM <${Input} ...${inputProps} /> ``` 4. **class vs className**: Both work in Preact, but prefer `class` for consistency and smaller output #### Common Mistakes | Mistake | Wrong | Correct | |---------|-------|---------| | Missing `${}` on component | `<Button>` | `<${Button}>` | | Wrong closing syntax | `</MyComponent>` | `</${MyComponent}>` | | Braces instead of template | `{count}` | `${count}` | | Spread with braces | `{...props}` | `...${props}` | | Missing html wrapper in conditional | `${show && <${X} />}` | `${show && html\`<${X} />\`}` | ### Component Patterns Use function components with: - **Hooks** for lifecycle and side effects - **Signals** for reactive state (preferred over useState) - **Suspense** for code splitting and async data - **Context API** for cross-component state and dependency injection - **Error boundaries** for graceful error handling ### Styling Strategy **Default**: Tailwind CSS via CLI — install with `npm install tailwindcss@3 --save-dev`, then generate purged CSS with `npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify`. This produces ~6KB of CSS containing only used classes. **Avoid**: Tailwind CDN (`cdn.tailwindcss.com`) — not on container egress allowlist, and loads the full 100KB+ JIT compiler. **Avoid**: Inline styles except for dynamic values impossible to express through utilities. **Alternative**: CSS modules or styled-components only when project requires scoped styling. ## Dependency Evaluation Framework Before recommending any external package, verify: 1. **Native Web APIs cannot accomplish this** - Check MDN documentation 2. **Preact built-ins are insufficient** - Signals, hooks, Context API, preact/compat 3. **Bundle size cost is justified** - Measure actual benefit gained vs. bytes added Document the specific performance or capability benefits that justify any dependency inclusion. ## Architecture Considerations For complex decisions involving: - Client-side routing (hash-based vs. History API vs. library) - SSR requirements - State management architecture (signals vs. external library) - preact/compat integration for React libraries - Performance optimization in constrained environments Evaluate trade-offs explicitly before committing to an approach. Document reasoning in code comments. ## Domain Standards ### Progressive Enhancement Ensure core functionality works without JavaScript where feasible: - Use semantic HTML - Leverage native form validation - Implement keyboard navigation - Add ARIA attributes for accessibility - Manage focus states properly ### Code Quality - Generate simplest working solution first - Document non-obvious Preact patterns in code comments - Explain hook dependencies - Note architectural decisions - Infer TypeScript usage from project context ## Development Workflow ### 1. Understand Requirements Clarify: - Target environment (standalone vs. build tools) - State complexity - Data sources (CSV, JSON, APIs) - Accessibility requirements - Browser support needs ### 2. Choose Architecture Pattern Refer to the Project Type Decision Tree above to select the appropriate architecture. ### 3. Implement Iteratively Start with: - Basic HTML structure (use `assets/boilerplate.html`) - Core component hierarchy - State management setup - Data fetching/parsing logic - Styling and polish ### 4. Reference Documentation Consult bundled references as needed: - `references/preact-v10-guide.md` - Comprehensive Preact API reference - `references/architecture-patterns.md` - Advanced patterns and best practices ### 5. Use Component Patterns Leverage `assets/component-patterns.md` for common UI patterns: - Data grids with sorting - File upload with drag & drop - Search with debouncing - Modal dialogs - Tabs - Toast notifications - CSV parsing ## Common Patterns ### Data Parsing (CSV/JSON) For data-heavy applications: ```javascript import { useSignal } from '@preact/signals'; function parseCSV(text) { const lines = text.trim().split('\n'); const headers = lines[0].split(',').map(h => h.trim()); return lines.slice(1).map(line => { const values = line.split(',').map(v => v.trim()); return Object.fromEntries(headers.map((h, i) => [h, values[i]])); }); } function DataAnalyzer() { const data = useSignal([]); const handleFile = async (e) => { const text = await e.target.files[0].text(); data.value = parseCSV(text); }; return html` <input type="file" accept=".csv" onChange=${handleFile} /> <div>Loaded ${data.value.length} rows</div> `; } ``` ### WebGL Integration For shader-based visualizations: ```javascript import { useEffect, useRef } from 'preact/hooks'; function ShaderCanvas({ fragmentShader }) { const canvasRef = useRef(null); useEffect(() => { const canvas = canvasRef.current; const gl = canvas.getContext('webgl2'); // Setup WebGL context, shaders, buffers // Render loop return () => { // Cleanup }; }, [fragmentShader]); return html`<canvas ref=${canvasRef} class="w-full h-full" />`; } ``` ### Global State with Signals ```javascript // state.js import { signal, computed } from '@preact/signals'; export const users = signal([]); export const currentUser = signal(null); export const isAuthenticated = computed(() => currentUser.value !== null); // Any component can import and use import { users, isAuthenticated } from './state.js'; ``` ## Constraints **DO NOT**: - Recommend npm tooling without confirming user's development environment - Suggest dependencies when native solutions exist - Optimize prematurely - start with simplest working implementation **DO**: - Use HTM syntax by default - Create artifacts for all code - Prioritize accessibility and progressive enhancement - Document architectural decisions in comments ## Resources ### References (Load as Needed) - **`references/preact-v10-guide.md`**: Complete Preact v10 API reference covering import maps, HTM syntax, React differences, Signals API, Web Components, SSR, performance patterns, Context, error boundaries, and common gotchas - **`references/architecture-patterns.md`**: Advanced patterns including zero-build architecture, state management strategies, data fetching, routing, forms, progressive enhancement, accessibility, performance optimization, testing, and security best practices ### Assets (Copy into Projects) - **`assets/boilerplate.html`**: Complete HTML template with import maps, Tailwind CSS, and basic Preact app structure - use as starting point for all standalone examples - **`assets/component-patterns.md`**: Reusable component implementations for data grids, file uploads, search, modals, tabs, toast notifications, and CSV parsing ## Examples ### Minimal Counter (Standalone) ```html <!DOCTYPE html> <html> <head> <!-- Run: bash scripts/vendor.sh --> <script type="importmap"> { "imports": { "preact": "./vendor/preact.module.js", "preact/hooks": "./vendor/hooks.module.js", "@preact/signals-core": "./vendor/signals-core.mjs", "@preact/signals": "./vendor/signals.mjs", "htm": "./vendor/htm.module.js", "htm/preact": "./vendor/htm.module.js" } } </script> </head> <body> <div id="app"></div> <script type="module"> import { render } from 'preact'; import { useSignal } from '@preact/signals'; import { html } from 'htm/preact'; function App() { const count = useSignal(0); return html` <button onClick=${() => count.value++}> Count: ${count} </button> `; } render(html`<${App} />`, document.getElementById('app')); </script> </body> </html> ``` ### Data Visualization App For applications processing CSV data and displaying interactive charts, reference the DataGrid pattern in `assets/component-patterns.md` and combine with a charting library like Chart.js or use native Canvas/SVG for custom visualizations. ### WebGL Shader Visualization For mathematical visualizations using WebGL shaders, create a canvas element, initialize WebGL2 context, compile shaders, and set up a render loop. Reference MDN WebGL documentation for shader setup patterns. ## Best Practices Summary 1. **Start Simple**: Create working prototype before optimizing 2. **Use Signals**: Prefer signals over useState for reactive state 3. **Native First**: Check if Web APIs can accomplish the task 4. **Progressive Enhancement**: Build with accessibility from the start 5. **Document Decisions**: Explain non-obvious patterns in comments 6. **Keys in Lists**: Always provide stable keys for mapped elements 7. **Error Boundaries**: Wrap async operations in error boundaries 8. **Avoid Inline Functions**: Don't create handlers inside map() loops ## Validation Checklist Before delivering code, verify: - [ ] Import map uses vendored local paths (no CDN URLs) - [ ] HTM syntax is used (unless JSX explicitly requested) - [ ] Keys provided for all mapped elements - [ ] Signals used for reactive state - [ ] Accessibility attributes included (ARIA, keyboard nav) - [ ] Error boundaries wrap async operations - [ ] Loading and error states handled - [ ] Code is in artifact format for iterative editing - [ ] Comments explain non-obvious patterns - [ ] No unnecessary dependencies included ## Container Testing Test Preact apps locally in Claude.ai containers using Playwright. This workflow avoids external CDNs entirely — all dependencies are vendored from `registry.npmjs.org`. ### Setup (one-time per session) ```bash # 1. Vendor JS dependencies bash scripts/vendor.sh # 2. Generate Tailwind CSS (if using Tailwind) npm install tailwindcss@3 --save-dev npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify ``` ### Serve and Test ```bash # 3. Serve locally python3 -m http.server 8765 & # 4. Test with Playwright python3 << 'PYEOF' from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=True, args=["--no-sandbox"]) page = browser.new_page() errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) page.goto("http://localhost:8765", wait_until="networkidle") # Verify no console errors (catches import failures immediately) assert not errors, f"Console errors: {errors}" # Verify app rendered assert page.locator("#app").inner_html() != "", "App did not render" # Example: test interaction # page.click("button") # assert "Count: 1" in page.content() browser.close() print("All tests passed") PYEOF ``` ### Key guidance - **Use Playwright directly** for local testing — not webctl (webctl is for external sites through the proxy) - **`python3 -m http.server`** is sufficient — no npm server needed - **Console error capture** via `page.on("console")` and `page.on("pageerror")` catches import failures immediately - **`--no-sandbox`** is required in container environments ## Getting Started For immediate implementation: 1. Run `bash scripts/vendor.sh` to fetch vendored dependencies 2. (Optional) Generate Tailwind CSS: `npm install tailwindcss@3 --save-dev && npx tailwindcss -o vendor/tailwind.css --content "*.html" --minify` 3. Copy `assets/boilerplate.html` as the starting point 4. Read `references/preact-v10-guide.md` for API details 5. Reference `assets/component-patterns.md` for common UI patterns 6. Consult `references/architecture-patterns.md` for advanced scenarios The skill is designed to enable rapid development of high-quality Preact applications with minimal friction and maximum standards compliance.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.