From f3aa7d4907162184b88e8ece592afbdd1bce3b16 Mon Sep 17 00:00:00 2001 From: Serik Date: Mon, 22 Jun 2026 23:28:24 +0500 Subject: [PATCH 1/7] feat: add 15 new design skills for Open CoDesign Add comprehensive skill library covering: - E-commerce: product-page, cart-checkout, storefront - SaaS/B2B: admin-dashboard, analytics-dashboard, onboarding-flow, settings-page - Content: blog-article, documentation-site - Interactive: microinteractions, data-visualization, hero-animations - Mobile: mobile-banking-app, progressive-web-app, responsive-design-system Each skill includes detailed workflow, layout patterns, and best practices. Co-Authored-By: Claude Opus 4.8 --- skills/admin-dashboard-skill/SKILL.md | 70 ++++ skills/analytics-dashboard-skill/SKILL.md | 112 ++++++ skills/blog-article-skill/SKILL.md | 106 +++++ skills/cart-checkout-skill/SKILL.md | 368 ++++++++++++++++++ skills/data-visualization-skill/SKILL.md | 99 +++++ skills/documentation-site-skill/SKILL.md | 82 ++++ skills/hero-animations-skill/SKILL.md | 107 +++++ skills/microinteractions-skill/SKILL.md | 104 +++++ skills/mobile-banking-app-skill/SKILL.md | 183 +++++++++ skills/onboarding-flow-skill/SKILL.md | 99 +++++ skills/product-page-skill/SKILL.md | 360 +++++++++++++++++ .../references/best-practices.md | 302 ++++++++++++++ .../product-page-skill/references/layouts.md | 158 ++++++++ skills/progressive-web-app-skill/SKILL.md | 124 ++++++ .../responsive-design-system-skill/SKILL.md | 163 ++++++++ skills/settings-page-skill/SKILL.md | 180 +++++++++ skills/storefront-skill/SKILL.md | 64 +++ 17 files changed, 2681 insertions(+) create mode 100644 skills/admin-dashboard-skill/SKILL.md create mode 100644 skills/analytics-dashboard-skill/SKILL.md create mode 100644 skills/blog-article-skill/SKILL.md create mode 100644 skills/cart-checkout-skill/SKILL.md create mode 100644 skills/data-visualization-skill/SKILL.md create mode 100644 skills/documentation-site-skill/SKILL.md create mode 100644 skills/hero-animations-skill/SKILL.md create mode 100644 skills/microinteractions-skill/SKILL.md create mode 100644 skills/mobile-banking-app-skill/SKILL.md create mode 100644 skills/onboarding-flow-skill/SKILL.md create mode 100644 skills/product-page-skill/SKILL.md create mode 100644 skills/product-page-skill/references/best-practices.md create mode 100644 skills/product-page-skill/references/layouts.md create mode 100644 skills/progressive-web-app-skill/SKILL.md create mode 100644 skills/responsive-design-system-skill/SKILL.md create mode 100644 skills/settings-page-skill/SKILL.md create mode 100644 skills/storefront-skill/SKILL.md diff --git a/skills/admin-dashboard-skill/SKILL.md b/skills/admin-dashboard-skill/SKILL.md new file mode 100644 index 00000000..fe2567eb --- /dev/null +++ b/skills/admin-dashboard-skill/SKILL.md @@ -0,0 +1,70 @@ +--- +name: admin-dashboard-skill +description: | + Enterprise admin panel with navigation, data tables, user management, + bulk actions, and settings. For backend management, CMS, admin tools. +triggers: + - "admin dashboard" + - "admin panel" + - "backend dashboard" + - "management interface" + - "管理后台" +od: + mode: prototype + platform: desktop + scenario: dashboard + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + example_prompt: "Create an admin dashboard for user management with table, filters, bulk actions, and CRUD operations." +--- + +# Admin Dashboard Skill + +Create a powerful admin interface for managing data and users. + +## Layout +``` +┌──────────────────────────────────────────┐ +│ [☰ Logo] Users [Search] [+New] [👤] │ +├─────┬────────────────────────────────────┤ +│ Nav │ Page Title │ +│200px│ [Filters] [Actions] │ +│ │ ┌──────────────────────────────┐ │ +│Users│ │ Table (sortable, selectable) │ │ +│Items│ │ [☑] Name Email Role Status │ │ +│Logs │ │ [☐] John j@... Admin Active │ │ +│Set. │ │ ... 50 rows ... │ │ +│ │ └──────────────────────────────┘ │ +│ │ Showing 1-50 of 1,234 [Pagination]│ +└─────┴────────────────────────────────────┘ +``` + +## Key Features +**Table:** +- Checkbox select all/individual +- Sortable columns (↑↓ icons) +- Row hover highlight +- Row actions menu (⋮) +- Pagination controls + +**Bulk Actions:** +- Delete selected +- Export selected +- Change status +- Assign role + +**Filters:** +- Status dropdown +- Role select +- Date range +- Search query + +**CRUD Operations:** +- Create: Modal or side panel +- Read: View detail page +- Update: Inline edit or modal +- Delete: Confirmation required diff --git a/skills/analytics-dashboard-skill/SKILL.md b/skills/analytics-dashboard-skill/SKILL.md new file mode 100644 index 00000000..f49a8d8c --- /dev/null +++ b/skills/analytics-dashboard-skill/SKILL.md @@ -0,0 +1,112 @@ +--- +name: analytics-dashboard-skill +description: | + Data-heavy analytics dashboard with KPI cards, charts, tables, and filters. + For SaaS analytics, business intelligence, metrics tracking, or data visualization. +triggers: + - "analytics dashboard" + - "data dashboard" + - "metrics" + - "business intelligence" + - "数据看板" +od: + mode: prototype + platform: desktop + scenario: dashboard + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + craft: + requires: [typography, color] + example_prompt: "Create an analytics dashboard for a SaaS product with MRR, user growth, feature usage, and conversion funnel." +--- + +# Analytics Dashboard Skill + +Create a professional data visualization dashboard optimized for quick insights. + +## Layout Structure + +**Desktop (1440px):** +``` +┌──────────────────────────────────────────┐ +│ Header [Logo] [DateRange] [Export] [⚙] │ +├─────┬────────────────────────────────────┤ +│ Nav │ KPI Strip (4 cards) │ +│ 200 ├────────────────────┬───────────────┤ +│ px │ Main Chart │ Side Panel │ +│ │ (Line/Bar) │ (Breakdown) │ +│ │ 60% │ 40% │ +│ ├────────────────────┴───────────────┤ +│ │ Data Table (paginated) │ +└─────┴────────────────────────────────────┘ +``` + +**Components:** + +1. **KPI Cards (4-6 metrics)** + - Large number (primary metric) + - Label below + - Delta indicator (↑5.2% from last week) + - Sparkline (optional mini-trend) + - Color: green for positive, red for negative + +2. **Main Chart** + - Line chart for trends over time + - Bar chart for comparisons + - Stacked area for composition + - Legend, axis labels, tooltips + - Date range selector + +3. **Data Table** + - Sortable columns + - Pagination (10/25/50 rows) + - Search/filter + - Export button + - Row actions (view details) + +4. **Filters** + - Date range picker + - Segment selector + - Metric selector + - Apply/Reset buttons + +## Visual Design + +**Typography:** +- Numbers: Monospace, tabular numerals +- Large metrics: 32-40px +- Labels: 12-14px, uppercase, tracking +- Table: 14px, consistent alignment + +**Color coding:** +- Positive: Green (#10b981) +- Negative: Red (#ef4444) +- Neutral: Blue (#3b82f6) +- Muted: Gray (#6b7280) + +**Charts:** +- Clean, minimal chrome +- Subtle gridlines +- Clear axis labels +- Accessible colors (not just hue differences) + +## Data Best Practices + +**Mock data should be:** +- Realistic (not round numbers like 1000, 2000) +- Trend patterns (growth, seasonal, etc.) +- Proper formatting ($1,234.56, 45.2%, 1.2K) + +**Empty states:** +- "No data for selected period" +- Suggest action (change filter, wait for data) +- Show placeholder chart outline + +**Loading states:** +- Skeleton loaders for cards/charts +- Shimmer effect +- Keep layout stable diff --git a/skills/blog-article-skill/SKILL.md b/skills/blog-article-skill/SKILL.md new file mode 100644 index 00000000..b9d075ef --- /dev/null +++ b/skills/blog-article-skill/SKILL.md @@ -0,0 +1,106 @@ +--- +name: blog-article-skill +description: | + Long-form reading experience with hero, table of contents, typography, + pull quotes, and related articles. For editorial content, documentation, case studies. +triggers: + - "blog article" + - "blog post" + - "article page" + - "editorial" + - "文章页面" +od: + mode: prototype + platform: desktop + scenario: content + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [typography, layout] + craft: + requires: [typography] + example_prompt: "Create a blog article page with hero image area, table of contents sidebar, long-form content, pull quotes, and related articles." +--- + +# Blog Article Skill + +Create an immersive reading experience optimized for long-form content. + +## Layout + +**Desktop:** +``` +┌────────────────────────────────────────┐ +│ Header [Logo] [Nav] │ +├────────────────────────────────────────┤ +│ Hero Image Area (CSS gradient) │ +│ [Large Title] │ +│ [Author] [Date] [Read time] │ +├──────────┬─────────────────────────────┤ +│ TOC │ Article Body │ +│ (sticky)│ Max 680px reading width │ +│ 200px │ │ +│ │ [Paragraphs] │ +│ │ [Pull Quote] │ +│ │ [Inline Images] │ +│ │ [Code Blocks] │ +│ │ [Footnotes] │ +├──────────┴─────────────────────────────┤ +│ Related Articles (3-4 cards) │ +└────────────────────────────────────────┘ +``` + +## Typography + +**Reading comfort:** +- Body: 18-21px, 1.6-1.8 line-height +- Max width: 680px (65-75 characters) +- Serif font for body (optional) +- Generous margins + +**Hierarchy:** +- H1: 40-56px (article title) +- H2: 28-32px (main sections) +- H3: 22-24px (subsections) +- Body: 18-21px +- Caption: 14-16px, muted + +## Components + +**Table of Contents:** +- Sticky sidebar (desktop only) +- Auto-generated from H2/H3 +- Highlight current section +- Smooth scroll on click + +**Pull Quote:** +- Large text (24-28px) +- Italic or serif +- Border or background +- Attribution if external + +**Code Blocks:** +- Monospace font +- Syntax highlighting +- Copy button +- Line numbers (optional) + +**Images:** +- Full-width or inset +- Captions below +- Alt text required +- Lazy loading + +**Related Articles:** +- 3-4 cards at bottom +- Image + title + excerpt +- Same category/tags + +## Mobile Optimization + +- TOC becomes dropdown at top +- Images full-width +- Larger body text (19-20px) +- Comfortable tap targets diff --git a/skills/cart-checkout-skill/SKILL.md b/skills/cart-checkout-skill/SKILL.md new file mode 100644 index 00000000..869ed1e6 --- /dev/null +++ b/skills/cart-checkout-skill/SKILL.md @@ -0,0 +1,368 @@ +--- +name: cart-checkout-skill +description: | + Complete shopping cart and checkout flow with cart summary, shipping form, + payment method, order review, and confirmation. Use for e-commerce checkout, + cart page, payment flow, or order completion. +triggers: + - "checkout" + - "shopping cart" + - "payment flow" + - "order form" + - "购物车" + - "结账流程" +od: + mode: prototype + platform: desktop + scenario: commerce + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + craft: + requires: [typography, color, anti-ai-slop] + inputs: + - name: flow_type + type: enum + values: [single_page, multi_step] + default: multi_step + - name: show_cart + type: boolean + default: true + capabilities_required: + - file_write + example_prompt: "Create a multi-step checkout flow with cart review, shipping address, payment method, and order confirmation." +--- + +# Cart & Checkout Skill + +Create a conversion-optimized checkout flow that minimizes cart abandonment. + +## Workflow + +### Step 1 — Choose flow type + +**Single-page checkout:** +- All steps visible at once +- Good for: Simple products, B2B, desktop-heavy traffic +- Pros: Fewer clicks, faster for power users +- Cons: Can feel overwhelming, harder on mobile + +**Multi-step checkout:** +- Steps revealed progressively (cart → shipping → payment → confirm) +- Good for: Complex orders, mobile-first, general e-commerce +- Pros: Less cognitive load, better mobile UX, clear progress +- Cons: More clicks, perceived as longer + +Default to **multi-step** for most use cases. + +### Step 2 — Structure the flow + +**Multi-step structure:** + +1. **Cart Review** (if show_cart) + - Item list with thumbnails, name, price, quantity + - Quantity adjustment (+ / -) + - Remove item button + - Subtotal calculation + - Promo code input + - "Continue to Shipping" CTA + - "Continue Shopping" secondary link + +2. **Shipping Information** + - Progress indicator (Step 1 of 3) + - Email for order updates + - Shipping address form (name, address, city, zip, country) + - "Ship to different address" checkbox (optional) + - Shipping method selection (standard, express, overnight) + - "Continue to Payment" CTA + - "Back to Cart" link + +3. **Payment Method** + - Progress indicator (Step 2 of 3) + - Order summary sidebar (items, shipping, tax, total) + - Payment options (credit card, PayPal, Apple Pay) + - Credit card form (number, expiry, CVV, name) + - Billing address (same as shipping checkbox) + - "Place Order" CTA + - Security badges (SSL, PCI compliant) + +4. **Order Confirmation** + - Success message with order number + - Estimated delivery date + - Order details summary + - What happens next (email confirmation, tracking) + - "Continue Shopping" or "View Order" CTA + - "Create Account" option (if guest checkout) + +### Step 3 — Cart component design + +**Cart item card:** +``` +┌─────────────────────────────────────┐ +│ [Image] Product Name │ +│ 80×80 Color: Black, Size: M │ +│ $49.99 │ +│ [-] 1 [+] [Remove] │ +└─────────────────────────────────────┘ +``` + +**Cart summary:** +``` +Subtotal: $99.98 +Shipping: $5.00 +Tax: $8.75 +───────────────────────── +Total: $113.73 +``` + +### Step 4 — Form design best practices + +**Field organization:** +- Group related fields (shipping address together) +- Single-column layout on mobile +- Two-column on desktop where logical (first/last name) +- Required fields marked with asterisk +- Optional fields labeled "(optional)" + +**Validation:** +- Real-time validation on blur (not on every keystroke) +- Inline error messages below field +- Green checkmark for valid fields (optional) +- Clear error state (red border, icon, message) +- Disable submit until form valid + +**Autofill support:** +- Use proper autocomplete attributes +- Standard field names for browser autofill +- Support address autocomplete APIs (Google Places optional) + +### Step 5 — Progress indicator + +**Multi-step progress:** +``` +1. Cart ━━━━━━ 2. Shipping ━━━━━━ 3. Payment ━━━━━━ 4. Confirm + ✓ +``` + +**Visual states:** +- Completed: Green checkmark +- Current: Highlighted, larger +- Upcoming: Muted, smaller + +**Mobile:** Simplify to "Step 2 of 4" + +### Step 6 — Payment form security + +**Trust signals:** +- SSL/secure badge in header +- "Your payment info is encrypted and secure" +- PCI compliance badge +- Money-back guarantee +- Accepted payment logos + +**Credit card form:** +- Card number: auto-format with spaces (1234 5678 9012 3456) +- Expiry: MM/YY format, auto-slash +- CVV: 3-4 digits, what is this? tooltip +- Card type detection (Visa/MC logo appears) + +**Alternative payment methods:** +- PayPal button (real button styling) +- Apple Pay (if Safari/iOS) +- Google Pay (if Chrome/Android) +- Buy Now, Pay Later options (Affirm, Klarna) + +### Step 7 — Order review sidebar + +**Always visible summary (desktop):** +- Sticky sidebar on right +- Collapsible on mobile +- Shows: items (count), shipping, tax, total +- Update dynamically as changes made + +**Mobile:** Expandable summary at top + +### Step 8 — Confirmation page + +**Success message:** +``` +✓ Order Confirmed! +Order #12345 + +Thank you, [Customer Name]! + +Your order has been placed and will be +delivered by Wednesday, June 28. + +We've sent a confirmation email to [email]. +``` + +**What's included:** +- Order summary (items, shipping, total) +- Shipping address +- Estimated delivery +- Payment method (last 4 digits) +- Order tracking link (if available immediately) + +**Next steps:** +- "Track Your Order" button +- "Continue Shopping" button +- "Create Account" (if guest) to save order history + +### Step 9 — Mobile optimization + +**Cart page:** +- Stack items vertically +- Larger touch targets for +/- buttons +- Sticky "Checkout" button at bottom + +**Forms:** +- Full-width inputs +- Large input height (48px minimum) +- Proper input types (email, tel, number) +- Native dropdowns for country/state + +**Payment:** +- Stack payment options vertically +- Large radio buttons for selection +- Simplified card form (minimal fields visible) + +### Step 10 — Error handling + +**Common errors:** +- Out of stock: Show immediately in cart +- Invalid promo code: "Code not found" inline message +- Failed payment: Clear message, try again option +- Shipping unavailable: Suggest alternative address +- Session timeout: Save cart, easy recovery + +**Error message template:** +``` +⚠ [Error Title] +[Explanation of what went wrong] +[What user should do next] +``` + +### Step 11 — Empty cart state + +If cart is empty: +``` +🛒 Your cart is empty + +Start adding items to see them here. + +[Continue Shopping] +``` + +**Don't show:** Full checkout UI if cart empty + +### Step 12 — Abandonment recovery hints + +**Exit intent (optional):** +- "Wait! Get 10% off your first order" +- Only show once per session +- Easy to dismiss + +**Save cart:** +- If user has account/email, save cart +- Email reminder after 24 hours (backend feature) +- "You left items in your cart" recovery + +## Visual rules + +**Layout:** +- Desktop: 2-column (form left 60%, summary right 40%) +- Mobile: Single column, summary expandable +- Max width: 1200px, centered + +**Forms:** +- Input height: 48px minimum +- Label above field, 14px, medium weight +- Placeholder for example format +- Error text: 13px, red, below field + +**Buttons:** +- Primary CTA: Full-width on mobile, right-aligned desktop +- Height: 48-56px +- Clear label: "Continue to Shipping" (not "Next") + +**Colors:** +- Use design system for CTAs +- Green for success states, checkmarks +- Red for errors, warnings +- Neutral for form fields + +**Typography:** +- Step headings: 24-28px, bold +- Field labels: 14px, medium +- Input text: 16px (prevent zoom on iOS) +- Summary: Monospace for prices + +## Anti-patterns + +❌ Requiring account creation before checkout +❌ Surprise shipping costs at end +❌ Too many form fields (keep minimal) +❌ No guest checkout option +❌ Unclear error messages +❌ No mobile optimization +❌ Missing progress indicator +❌ Distracting from checkout goal + +## Testing checklist + +□ Cart updates: add/remove/quantity change works +□ Form validation: catches all error cases +□ Mobile: all fields accessible, keyboard doesn't hide inputs +□ Payment: card formatting works +□ Confirmation: shows correct order details +□ Empty cart: handled gracefully +□ Back button: navigates correctly + +## Example HTML structure + +```html +
+ +
...
+ +
+ +
+

Shipping Information

+
+ +
+
+ + + +
+
+``` + +## Conversion optimization + +**Reduce friction:** +- Auto-fill from saved addresses +- Express checkout buttons (Apple Pay, PayPal) +- Guest checkout option +- Minimal required fields + +**Build trust:** +- Security badges visible +- Clear return policy link +- Customer service contact +- Professional design + +**Speed:** +- Fast page loads +- Instant validation feedback +- Optimistic UI updates +- Loading states during submission diff --git a/skills/data-visualization-skill/SKILL.md b/skills/data-visualization-skill/SKILL.md new file mode 100644 index 00000000..5dee6077 --- /dev/null +++ b/skills/data-visualization-skill/SKILL.md @@ -0,0 +1,99 @@ +--- +name: data-visualization-skill +description: | + Interactive data visualization with charts, graphs, and insights. + For data presentation, reports, analytics, dashboards. +triggers: + - "data visualization" + - "charts" + - "graphs" + - "data dashboard" + - "数据可视化" +od: + mode: prototype + platform: desktop + scenario: dashboard + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography] + example_prompt: "Create a data visualization page with line chart, bar chart, pie chart, and data table showing quarterly revenue." +--- + +# Data Visualization Skill + +Create clear, insightful data visualizations. + +## Chart Types + +**Line Chart:** +- Time-series data +- Trends over time +- Multiple lines for comparison +- Grid lines, axis labels +- Tooltip on hover + +**Bar Chart:** +- Categorical comparisons +- Vertical or horizontal +- Grouped or stacked +- Clear value labels + +**Pie/Donut Chart:** +- Part-to-whole relationships +- Maximum 5-6 slices +- Percentage labels +- Legend with values + +**Area Chart:** +- Composition over time +- Stacked areas +- Smooth curves +- Filled under line + +## Design Principles + +**Color:** +- Use accessible color palette +- Not just hue (add patterns) +- Consistent across charts +- Semantic colors (green=good, red=bad) + +**Typography:** +- Clear axis labels +- Readable value labels +- Legend descriptions +- Data source attribution + +**Interactivity:** +- Hover tooltips with exact values +- Click to drill down +- Filter controls +- Export options + +**Layout:** +``` +┌────────────────────────────────────────┐ +│ Revenue Analysis Q1-Q4 2026 │ +├────────────────────────────────────────┤ +│ [Date Range] [Segment] [Export] │ +├─────────────────────┬──────────────────┤ +│ Line Chart │ Key Metrics │ +│ (Revenue Trend) │ $1.2M Total │ +│ │ +15% Growth │ +├─────────────────────┴──────────────────┤ +│ Bar Chart (By Category) │ +├────────────────────────────────────────┤ +│ Data Table (Top 10) │ +└────────────────────────────────────────┘ +``` + +## Implementation + +Use SVG for charts: +- Scalable, crisp at any size +- CSS styling +- Accessible with ARIA labels +- No external libraries needed for basic charts diff --git a/skills/documentation-site-skill/SKILL.md b/skills/documentation-site-skill/SKILL.md new file mode 100644 index 00000000..389e1de3 --- /dev/null +++ b/skills/documentation-site-skill/SKILL.md @@ -0,0 +1,82 @@ +--- +name: documentation-site-skill +description: | + Technical documentation site with sidebar navigation, search, code examples, + and next/prev links. For API docs, developer guides, knowledge base. +triggers: + - "documentation" + - "docs site" + - "developer docs" + - "knowledge base" + - "文档站点" +od: + mode: prototype + platform: desktop + scenario: content + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [typography, layout, components] + craft: + requires: [typography] + example_prompt: "Create a documentation site with sidebar navigation, code examples, search, and API reference sections." +--- + +# Documentation Site Skill + +Create clear, scannable technical documentation. + +## Layout +``` +┌────────────────────────────────────────┐ +│ [Logo] [Search] [GitHub] [Theme] [v1.2]│ +├────────┬───────────────────────────────┤ +│ Nav │ Breadcrumb: Docs > API > Auth │ +│ Tree │ │ +│200px │ # Authentication │ +│ │ │ +│Getting │ Overview text... │ +│Started │ │ +│API │ ## API Keys │ +│ Auth │ ```js │ +│ Users │ const api = new API({ │ +│ Posts │ key: 'your-key' │ +│Guides │ }) │ +│ │ ``` │ +│ │ │ +│ │ [◀ Prev] [Next ▶] │ +└────────┴───────────────────────────────┘ +``` + +## Features +**Sidebar Nav:** +- Collapsible sections +- Active page highlight +- Scroll to active on load + +**Content:** +- Markdown-style formatting +- Code blocks with syntax highlighting +- Copy button on code +- Inline code styling +- Tables for parameters +- Callout boxes (note/warning/tip) + +**Code Examples:** +- Tabs for multiple languages +- Line numbers +- Highlight specific lines +- "Run in playground" link + +**Search:** +- Fuzzy search across all docs +- Keyboard shortcut (⌘K) +- Results with context + +**Navigation:** +- Breadcrumbs at top +- Prev/Next at bottom +- "Edit on GitHub" link +- Version selector diff --git a/skills/hero-animations-skill/SKILL.md b/skills/hero-animations-skill/SKILL.md new file mode 100644 index 00000000..cbc281af --- /dev/null +++ b/skills/hero-animations-skill/SKILL.md @@ -0,0 +1,107 @@ +--- +name: hero-animations-skill +description: | + Engaging hero section with animations, CTAs, and visual interest. + For landing pages, marketing sites, product launches. +triggers: + - "hero section" + - "animated hero" + - "landing hero" + - "首屏动画" +od: + mode: prototype + platform: desktop + scenario: marketing + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout] + example_prompt: "Create an animated hero section with gradient background, floating elements, headline with typewriter effect, and primary CTA." +--- + +# Hero Animations Skill + +Create captivating hero sections that grab attention. + +## Layout +``` +┌────────────────────────────────────────┐ +│ │ +│ [Animated Elements] │ +│ │ +│ Your Headline Here │ +│ Subheadline text that explains │ +│ │ +│ [Primary CTA] [Secondary CTA] │ +│ │ +│ [Trust Signal] [Social Proof] │ +│ │ +└────────────────────────────────────────┘ +``` + +## Animation Types + +**Background:** +- Gradient shift (hue rotation) +- Particle field (CSS/SVG) +- Geometric shapes floating +- Subtle mesh gradient + +**Text Animations:** +- Fade in + slide up +- Typewriter effect +- Word-by-word reveal +- Gradient text animation + +**Elements:** +- Floating cards/screenshots +- Parallax layers +- Rotating 3D objects (CSS transform) +- Pulsing glows + +## Principles + +**Performance:** +- CSS animations preferred +- GPU-accelerated (transform, opacity) +- No layout thrashing +- Pause on scroll out + +**Accessibility:** +- Respect prefers-reduced-motion +- Don't rely on animation for content +- Keyboard navigable +- No seizure-inducing flashing + +**Subtlety:** +- Smooth, not jarring +- Enhance, don't distract +- 60fps target +- Natural easing + +## Example Animations + +```css +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.headline { + animation: fadeInUp 800ms ease-out forwards; +} + +@media (prefers-reduced-motion: reduce) { + .headline { + animation: none; + } +} +``` diff --git a/skills/microinteractions-skill/SKILL.md b/skills/microinteractions-skill/SKILL.md new file mode 100644 index 00000000..6bf7728d --- /dev/null +++ b/skills/microinteractions-skill/SKILL.md @@ -0,0 +1,104 @@ +--- +name: microinteractions-skill +description: | + Showcase of loading states, transitions, hover effects, and micro-animations. + For component library, design system demos, interaction patterns. +triggers: + - "microinteractions" + - "loading states" + - "hover effects" + - "animations" + - "微交互" +od: + mode: prototype + platform: desktop + scenario: design + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, components] + example_prompt: "Create a microinteractions showcase with loading indicators, button states, toast notifications, and smooth transitions." +--- + +# Microinteractions Skill + +Create delightful micro-animations that enhance UX. + +## Categories + +**1. Loading States:** +- Spinner (circular, dots, bars) +- Skeleton loaders +- Progress bars +- Shimmer effect +- Pulsing placeholders + +**2. Button States:** +- Default → Hover → Active → Disabled +- Loading state (spinner inside) +- Success state (checkmark) +- Error state (shake animation) + +**3. Notifications:** +- Toast (slide in from top/bottom) +- Alert banners +- Snackbar +- Auto-dismiss after 5s + +**4. Form Interactions:** +- Input focus (border glow) +- Validation checkmark +- Error shake +- Character counter + +**5. Hover Effects:** +- Scale up (1.05) +- Shadow increase +- Color transition +- Underline expand + +## Animation Principles +- **Duration:** 150-300ms typically +- **Easing:** ease-out for exits, ease-in for entrances +- **Subtle:** enhance, don't distract +- **Purposeful:** every animation has a reason +- **Accessible:** respect prefers-reduced-motion + +## Layout +``` +┌────────────────────────────────────────┐ +│ Microinteractions Gallery │ +├────────────────────────────────────────┤ +│ ## Loading Indicators │ +│ [Spinner] [Dots] [Bars] [Skeleton] │ +│ │ +│ ## Button States │ +│ [Default] [Hover] [Loading] [Success] │ +│ │ +│ ## Notifications │ +│ [Trigger Toast] [Show Alert] │ +│ │ +│ ... │ +└────────────────────────────────────────┘ +``` + +## CSS Animation Pattern +```css +.button { + transition: transform 200ms ease-out, + box-shadow 200ms ease-out; +} + +.button:hover { + transform: scale(1.05); + box-shadow: 0 4px 12px rgba(0,0,0,0.15); +} + +@media (prefers-reduced-motion: reduce) { + .button { + transition: none; + } +} +``` diff --git a/skills/mobile-banking-app-skill/SKILL.md b/skills/mobile-banking-app-skill/SKILL.md new file mode 100644 index 00000000..8100a558 --- /dev/null +++ b/skills/mobile-banking-app-skill/SKILL.md @@ -0,0 +1,183 @@ +--- +name: mobile-banking-app-skill +description: | + Mobile banking app screen with account overview, transactions, and quick actions. + For fintech apps, banking interfaces, financial dashboards. +triggers: + - "banking app" + - "fintech app" + - "mobile banking" + - "financial app" + - "银行应用" +od: + mode: prototype + platform: mobile + scenario: application + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, components] + example_prompt: "Create a mobile banking home screen with account balance, recent transactions, quick actions, and bottom navigation." +--- + +# Mobile Banking App Skill + +Create secure, trustworthy mobile banking interface. + +## Layout (iPhone Frame) +``` +┌────────────────┐ +│ ⌚ 9:41 📶 🔋 │ Status bar +├────────────────┤ +│ Good morning │ +│ John │ +│ │ +│ ┌────────────┐ │ Balance card +│ │ Checking │ │ +│ │ $12,487.50 │ │ +│ │ +$250 today│ │ +│ └────────────┘ │ +│ │ +│ Quick Actions │ +│ [Pay][Send] │ +│ [Request][More]│ +│ │ +│ Recent Trans. │ +│ ● Starbucks │ +│ -$4.50 │ +│ ● Salary │ +│ +$5,000 │ +│ ... │ +├────────────────┤ +│[⌂][📊][+][⚙]│ Bottom nav +└────────────────┘ +``` + +## Key Features + +**Balance Card:** +- Account type (Checking/Savings) +- Large balance (prominent) +- Today's change (+ green, - red) +- Masked by default (tap to reveal) +- Gradient or solid background + +**Quick Actions:** +- Pay bills +- Send money +- Request payment +- Deposit check (camera) +- 4-6 actions, icon + label + +**Transaction List:** +- Merchant name or description +- Amount (right-aligned, monospace) +- Category icon +- Date/time +- Pending badge if applicable +- Tap for details + +**Bottom Navigation:** +- Home +- Accounts +- Transfer +- More/Settings +- Active state clear + +## Security Considerations + +**Visual Trust:** +- Professional design +- No flashy animations +- Clear branding +- Secure badge + +**Data Display:** +- Balance masked by default +- Card numbers show last 4 +- Biometric prompt UI +- Session timeout warning + +**Feedback:** +- Transaction confirmations +- Loading states +- Error messages clear +- Success animations subtle + +## Visual Design + +**Colors:** +- Professional (blue, navy, green) +- Positive: green +- Negative: red +- Neutral: gray + +**Typography:** +- Numbers: Monospace, tabular +- Balance: 32-40px, bold +- Transaction: 16px body +- Amounts: 18px, bold + +**Spacing:** +- Comfortable padding (16-20px) +- Card spacing (16px gaps) +- List items (12px vertical) + +**Cards:** +- Rounded corners (12-16px) +- Subtle shadow or border +- No heavy effects + +## Interactions + +**Pull-to-refresh:** +- Update balance and transactions +- Loading indicator + +**Swipe actions:** +- Swipe transaction left: categorize, flag +- Swipe right: mark reviewed + +**Tap actions:** +- Balance card: toggle mask +- Transaction: view details +- Quick action: open flow + +## Accessibility + +**Touch targets:** +- Minimum 44×44px +- Comfortable spacing + +**Contrast:** +- WCAG AA for all text +- Especially amounts + +**Labels:** +- Screen reader descriptions +- Amount announced with currency +- Clear button labels + +## States + +**Loading:** +- Skeleton for balance +- Shimmer for transactions + +**Empty:** +- "No transactions yet" +- Helpful message + +**Error:** +- "Can't load balance" +- Retry button +- Support contact + +## Trust Signals + +- Bank logo prominent +- "Your account is secure" message +- FDIC insured badge +- Encrypted connection icon diff --git a/skills/onboarding-flow-skill/SKILL.md b/skills/onboarding-flow-skill/SKILL.md new file mode 100644 index 00000000..2670663d --- /dev/null +++ b/skills/onboarding-flow-skill/SKILL.md @@ -0,0 +1,99 @@ +--- +name: onboarding-flow-skill +description: | + Multi-step user onboarding wizard with progress tracking, form validation, + and completion celebration. For product tours, setup flows, or getting started. +triggers: + - "onboarding" + - "wizard" + - "setup flow" + - "getting started" + - "引导流程" +od: + mode: prototype + platform: desktop + scenario: flow + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + inputs: + - name: step_count + type: integer + default: 4 + min: 2 + max: 8 + example_prompt: "Create a 4-step onboarding flow: profile setup, team invite, integrations, and tutorial completion." +--- + +# Onboarding Flow Skill + +Create an engaging onboarding that gets users to activation quickly. + +## Flow Structure + +**Typical steps:** +1. Welcome + Value prop +2. Profile/Account setup +3. Preferences/Settings +4. Integrations/Connections +5. Tutorial/First action +6. Success celebration + +**Layout:** +``` +┌────────────────────────────────────────┐ +│ [Logo] [Step 2 of 4] [×] │ +├────────────────────────────────────────┤ +│ │ +│ ●━━━━━━●━━━━━━○━━━━━━○ │ +│ Profile Team Setup Done │ +│ │ +│ [Step Content Area] │ +│ │ +│ [Skip] [Next Step →] │ +└────────────────────────────────────────┘ +``` + +## Key Principles + +**Progress visibility:** +- Clear step indicator +- Number of steps shown +- Can't go back (usually) + +**One goal per step:** +- Single focus, no distractions +- Clear benefit statement +- Minimal fields (3-5 max) + +**Skip option:** +- Allow skip for optional steps +- "I'll do this later" link +- Save progress automatically + +**Celebration:** +- Success animation on completion +- Clear next steps +- CTA to main product + +## Visual Design + +**Step indicator:** +- Horizontal dots/line +- Current step highlighted +- Completed steps with checkmark +- Future steps grayed out + +**Content card:** +- Centered, max-width 600px +- Generous padding +- Illustration/icon for each step +- Clear headline and description + +**Buttons:** +- Primary: "Next" / "Complete Setup" +- Secondary: "Skip" / "Back" +- Full-width on mobile diff --git a/skills/product-page-skill/SKILL.md b/skills/product-page-skill/SKILL.md new file mode 100644 index 00000000..1748ffe0 --- /dev/null +++ b/skills/product-page-skill/SKILL.md @@ -0,0 +1,360 @@ +--- +name: product-page-skill +description: | + E-commerce product detail page with image gallery, product information, + reviews, add-to-cart, and related products. Use when the brief asks for + a product page, product detail, item page, or e-commerce product view. +triggers: + - "product page" + - "product detail" + - "item page" + - "e-commerce product" + - "product view" + - "商品详情页" + - "产品页面" +od: + mode: prototype + platform: desktop + scenario: commerce + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + craft: + requires: [typography, color, anti-ai-slop] + inputs: + - name: product_name + type: string + required: true + - name: price + type: string + default: "$99.00" + - name: has_reviews + type: boolean + default: true + - name: has_gallery + type: boolean + default: true + capabilities_required: + - file_write + example_prompt: "Create a product detail page for a premium wireless headphone with gallery, specs, reviews, and add-to-cart." +--- + +# Product Page Skill + +Create a professional e-commerce product detail page optimized for conversion and user trust. + +## Resource map + +``` +product-page-skill/ +├── SKILL.md ← you're reading this +├── assets/ +│ └── template.html ← base HTML structure +├── references/ +│ ├── layouts.md ← layout patterns (split-screen, stacked, sidebar) +│ ├── components.md ← reusable components (gallery, reviews, specs) +│ └── best-practices.md ← e-commerce conversion principles +└── tests/ + ├── basic.prompt ← test case + └── basic.expected.json ← expected output +``` + +## When to use this skill + +Use this when the user asks for: +- Product detail page +- Item page for e-commerce +- Product showcase with purchase option +- Single-product landing page +- Product view with reviews and specs + +If the user asks for a full store or catalog, suggest using the `storefront-skill` instead. + +## Workflow + +### Step 1 — Understand the product + +Ask clarifying questions if needed: +- Product category (electronics, fashion, furniture, etc.) +- Key features to highlight +- Price range +- Target audience (luxury, budget, professional) + +### Step 2 — Choose layout pattern + +Read `references/layouts.md` and pick one: + +| Pattern | Best for | Layout | +|---|---|---| +| **Split-screen** | Products with strong visuals | Gallery left (60%), info right (40%) | +| **Stacked** | Mobile-first, content-heavy | Gallery top, info below, full-width | +| **Sidebar** | Products with many variants | Main content center, sticky sidebar for purchase | + +Default to **split-screen** for desktop, **stacked** for mobile. + +### Step 3 — Build the page structure + +**Required sections (in order):** + +1. **Header/Breadcrumbs** + - Category breadcrumb trail + - Back to category link + - Search and cart icons (non-functional but styled) + +2. **Product Gallery** (if `has_gallery`) + - Main image (large, zoomable affordance) + - Thumbnail strip (3-6 images) + - Use CSS gradient placeholders, not external images + - Add hover states on thumbnails + - Include "zoom" icon or text on hover + +3. **Product Information** + - Product name (H1, prominent) + - Rating stars + review count (if `has_reviews`) + - Price (large, bold, monospace numerals) + - Was/Now pricing if on sale + - Short description (2-3 sentences) + - Key features (bullet list, 4-6 items) + +4. **Variants Selection** (optional but recommended) + - Color swatches (visual, not just text) + - Size selector (buttons, not dropdown) + - Quantity stepper + - Stock status ("In stock" / "Low stock" / "Out of stock") + +5. **Add to Cart Section** + - Primary CTA button ("Add to Cart" or "Buy Now") + - Secondary action ("Add to Wishlist" icon button) + - Trust badges (free shipping, returns, warranty) + +6. **Tabs or Accordion** + - Description (detailed, 2-3 paragraphs) + - Specifications (table format) + - Shipping & Returns (clear policy) + - Reviews (if `has_reviews`) + +7. **Reviews Section** (if `has_reviews`) + - Overall rating summary (stars + breakdown bars) + - Filter/sort controls + - 3-5 review cards with: + - Reviewer name + verified badge + - Star rating + - Review text (2-4 lines) + - Helpful votes count + - Date + +8. **Related Products** + - "You might also like" section + - 4 product cards in a grid + - Each card: image placeholder, name, price, rating + +9. **Footer** (minimal) + - Trust signals (secure checkout, returns policy) + - Company links + +### Step 4 — Apply design system + +Read the active `DESIGN.md`: +- Use color tokens for brand, backgrounds, borders +- Apply typography scales (H1 for product name, body for description) +- Use spacing rhythm (8px grid typically) +- Match button styles to design system + +**E-commerce specific styles:** +- Price: larger than body text, monospace or tabular numerals +- CTA button: high-contrast, minimum 48px height, full-width on mobile +- Trust badges: subtle, not overwhelming +- Reviews: stars in brand color or gold (#F59E0B default) + +### Step 5 — Add interactions + +**Micro-interactions to include:** +- Hover state on thumbnails (border highlight) +- Active state on variant selectors (selected color/size) +- Button hover (slight scale or color shift) +- Quantity stepper (+ and - buttons, disable at limits) +- Tab switching (underline or background change) +- "Add to Cart" success state (checkmark animation or color change) + +**Accessibility:** +- Gallery: alt text on all images ("Product view from front", "Product view from side") +- Variants: proper label association, radio buttons or checkboxes +- Quantity: label for screen readers, min/max attributes +- Reviews: rating announced ("4 out of 5 stars") +- Tabs: ARIA tabs pattern or accordion with proper headings + +### Step 6 — Handle edge cases + +**Empty states:** +- No reviews yet: "Be the first to review this product" with CTA +- Out of stock: disable "Add to Cart", show "Notify when available" +- No variants: hide selector section + +**Long content:** +- Product name: truncate after 2 lines with ellipsis on small screens +- Description: "Read more" expansion if > 200 words +- Reviews: paginate or "Load more" after 5 + +**Mobile considerations:** +- Gallery: swipeable carousel, not thumbnail strip +- Variants: stack vertically, larger touch targets +- Sticky "Add to Cart" bar at bottom +- Tabs become accordion + +### Step 7 — Self-check against e-commerce best practices + +Before calling `done`, verify: + +□ **Conversion-focused:** + - Price is immediately visible (above the fold) + - CTA button is prominent, high-contrast, clear label + - Trust signals are present (reviews, ratings, badges) + - Urgency indicators if appropriate (limited stock, sale ends) + +□ **Trust-building:** + - Real product information (not lorem ipsum) + - Specific features (not generic "high quality") + - Review content is realistic + - Clear shipping and return policy + +□ **Visual hierarchy:** + - Product name is the largest text + - Price is second most prominent + - CTA button is visually heaviest element + - Supporting info is clearly secondary + +□ **Responsive:** + - Gallery adapts (grid → carousel) + - Info sections stack on narrow screens + - CTA remains accessible (sticky or repeated) + - Touch targets ≥ 44px on mobile + +□ **Accessible:** + - All images have alt text + - Form controls have labels + - Color contrast meets WCAG AA + - Keyboard navigation works (tab through variants, CTA) + +### Step 8 — Emit the artifact + +Write one self-contained `index.html` with: +- Inline CSS in ` + + +
+ +
+
+ +
+

+
+

+

+
+ +
+ +
+ + +
+ +
+
+
+ +
+ +
+ + +
+ +
+ + +``` + +## Testing + +Run through these scenarios: +1. Desktop 1440px: gallery and info side-by-side +2. Tablet 768px: info starts to stack +3. Mobile 375px: full stack, sticky CTA +4. Out of stock state: CTA disabled +5. No reviews state: empty state with CTA + +All should look intentional and professional. diff --git a/skills/product-page-skill/references/best-practices.md b/skills/product-page-skill/references/best-practices.md new file mode 100644 index 00000000..66720712 --- /dev/null +++ b/skills/product-page-skill/references/best-practices.md @@ -0,0 +1,302 @@ +# E-Commerce Product Page Best Practices + +## Conversion Optimization + +### Above the Fold (First Screen) +✅ **Must include:** +- Product name (clear, descriptive) +- Main product image (high quality) +- Price (prominent, easy to spot) +- Primary CTA ("Add to Cart") +- Key trust signal (reviews, rating) + +❌ **Avoid:** +- Requiring scroll to see price +- Hidden or unclear CTA +- No visual of product +- Overwhelming with too many options + +### Call-to-Action (CTA) +✅ **Best practices:** +- Clear action verb ("Add to Cart", "Buy Now", not "Submit") +- High contrast color (stands out from page) +- Large enough (min 48px height, full-width on mobile) +- Single primary action (don't compete with multiple CTAs) +- Disabled state when out of stock + +❌ **Avoid:** +- Multiple competing primary buttons +- Generic text ("Click here", "Submit") +- Tiny button with small touch target +- Unclear what happens on click + +--- + +## Trust & Credibility + +### Social Proof +✅ **Include:** +- Star rating (visible, not hidden) +- Number of reviews (e.g., "4.8 ★ (1,234 reviews)") +- Review highlights (verified purchases, photos) +- "Bestseller" or "Trending" badges (if true) + +### Trust Badges +✅ **Effective signals:** +- Free shipping (or threshold: "Free shipping over $50") +- Easy returns ("30-day return policy") +- Warranty or guarantee +- Secure checkout icons +- Customer support availability + +❌ **Avoid:** +- Fake urgency ("Only 2 left!" when false) +- Made-up badges or certifications +- Overwhelming number of badges +- Trust signals that feel spammy + +--- + +## Product Information + +### Product Name +✅ **Good:** "Sony WH-1000XM5 Wireless Noise-Cancelling Headphones - Black" +❌ **Bad:** "Headphones" or "Premium Audio Device XYZ-123" + +**Rules:** +- Include brand if relevant +- Be specific (model, key feature) +- Add variant info (color, size) if applicable +- Keep under 60 characters for SEO + +### Description +✅ **Structure:** +1. **Short description** (2-3 sentences, benefits-focused) +2. **Key features** (bullet list, 4-6 items, scannable) +3. **Long description** (detailed, 2-3 paragraphs, behind tab) + +**Focus on benefits, not just features:** +- ❌ "Bluetooth 5.0 connectivity" +- ✅ "Connect seamlessly to any device with the latest Bluetooth 5.0 — enjoy 30 hours of wireless playback" + +### Specifications +✅ **Format as table:** +``` +Dimensions: 7.3 × 6.5 × 2.9 inches +Weight: 8.8 oz (250g) +Battery Life: Up to 30 hours +Connectivity: Bluetooth 5.0, 3.5mm jack +Warranty: 2 years manufacturer +``` + +❌ **Avoid:** Long paragraphs of specs mixed together + +--- + +## Visual Design + +### Images +✅ **Gallery best practices:** +- Main image: product on white/neutral background +- Multiple angles (front, side, back, detail shots) +- Lifestyle images (product in use) +- Zoom functionality (or high-res on click) +- 4-6 images typically sufficient + +❌ **Avoid:** +- Low-resolution images +- Inconsistent backgrounds +- Only one angle +- Overly edited/unrealistic + +### Layout +✅ **Visual hierarchy:** +1. Product name (largest text) +2. Price (second largest, monospace) +3. Rating/reviews (prominent but supporting) +4. CTA button (visually heaviest element) +5. Everything else (clearly secondary) + +### Color +✅ **Use color purposefully:** +- Brand color for CTA and accent elements +- Green for "In Stock", "Sale", positive indicators +- Red for "Out of Stock", errors, warnings +- Neutral grays for borders and backgrounds + +❌ **Avoid:** +- Random pops of color with no meaning +- Poor contrast (especially price on colored backgrounds) +- Using only color to convey information (accessibility issue) + +--- + +## Variants & Options + +### Color Selection +✅ **Visual swatches:** +- Show actual color (swatch, not just text "Blue") +- Include color name on hover or below +- Clear selected state (border, checkmark) +- Disable unavailable colors (grayed out, diagonal line) + +### Size Selection +✅ **Button group style:** +- Clear buttons for each size (S, M, L, XL) +- Selected state (filled or outlined) +- Size guide link nearby +- Disable unavailable sizes + +### Quantity +✅ **Stepper control:** +- Plus and minus buttons +- Number input in center (editable) +- Disable at min (1) and max (stock limit) +- Show stock level if low ("Only 3 left") + +--- + +## Reviews Section + +### Summary +✅ **Display:** +- Overall rating (large, e.g., "4.8 / 5.0") +- Total review count +- Star distribution bars (5★ to 1★ with percentages) +- Filters: Most helpful, Recent, Highest/Lowest rated + +### Individual Reviews +✅ **Each review includes:** +- Reviewer name or initials +- Verified purchase badge +- Star rating +- Review date +- Review text (2-4 lines visible, "Read more" for longer) +- Helpful votes ("52 people found this helpful") +- Optional: Review photos + +❌ **Avoid:** +- Only showing 5-star reviews (looks fake) +- No verification or credibility signals +- Allowing fake-looking reviews +- Hiding negative reviews + +--- + +## Mobile Optimization + +### Layout Changes +✅ **Mobile adaptations:** +- Gallery becomes swipeable carousel +- Info sections stack vertically +- Variants use larger touch targets (min 44×44px) +- Sticky "Add to Cart" bar at bottom +- Tabs become accordion +- Related products: 2-column grid or horizontal scroll + +### Performance +✅ **Mobile-specific:** +- Lazy-load images below fold +- Optimize main image for mobile (smaller dimensions) +- Reduce animation/effects +- Fast initial load (< 3 seconds) + +--- + +## Accessibility + +### WCAG Requirements +✅ **Must have:** +- Alt text on all images ("Product front view", not just "Product") +- Form labels (not just placeholders) +- Color contrast meets WCAG AA (4.5:1 for text) +- Keyboard navigation (tab through all interactive elements) +- Focus indicators (visible outline on focused elements) +- ARIA labels where needed (star ratings, icon buttons) + +### Common Issues to Avoid +❌ Color-only indicators (e.g., color swatch without name) +❌ Icon-only buttons without labels (wishlist, share) +❌ Auto-playing videos with sound +❌ Time-limited sales without warning + +--- + +## Edge Cases + +### Out of Stock +✅ **Handle gracefully:** +- Clear "Out of Stock" message +- Disable "Add to Cart" button +- Offer "Notify When Available" option +- Show similar available products +- Keep page structure intact (don't hide everything) + +### No Reviews Yet +✅ **Encourage first review:** +- "Be the first to review this product" +- Clear CTA to write review +- Explain review benefits (helps others, builds trust) + +### Sale/Discount +✅ **Show clearly:** +- Original price (crossed out) +- Sale price (prominent, in brand color) +- Discount percentage or amount saved +- Sale end date if applicable +- "Sale" or "Limited Time" badge + +--- + +## SEO Considerations + +✅ **On-page SEO:** +- Unique, descriptive title tag (< 60 chars) +- Product name in H1 (only one H1) +- Structured data (Product schema) +- Descriptive alt text on images +- Readable URLs (not IDs: /products/wireless-headphones not /p/12345) + +--- + +## Performance + +✅ **Speed optimizations:** +- Lazy-load images (especially gallery thumbnails) +- Inline critical CSS +- Defer non-critical JavaScript +- Optimize images (WebP format, responsive sizes) +- Minimize initial bundle size + +**Target metrics:** +- First Contentful Paint: < 1.5s +- Largest Contentful Paint: < 2.5s +- Cumulative Layout Shift: < 0.1 + +--- + +## Common Mistakes to Avoid + +1. **Hidden Costs** + - Show shipping cost early + - Don't surprise at checkout + +2. **Overwhelming Choices** + - Too many variants confuse + - Limit to essential options + +3. **Poor Mobile Experience** + - Desktop-only thinking + - Tiny text and buttons + +4. **Fake Urgency** + - False scarcity + - Fake countdown timers + +5. **No Clear Value Proposition** + - Generic descriptions + - Missing "why this product" + +6. **Ignoring Accessibility** + - Low contrast + - No keyboard navigation diff --git a/skills/product-page-skill/references/layouts.md b/skills/product-page-skill/references/layouts.md new file mode 100644 index 00000000..1ded8826 --- /dev/null +++ b/skills/product-page-skill/references/layouts.md @@ -0,0 +1,158 @@ +# Product Page Layout Patterns + +## Pattern A: Split-Screen (Recommended for Desktop) + +**Best for:** Products with strong visual appeal (fashion, electronics, furniture) + +**Structure:** +``` +┌────────────────────────────────────┐ +│ Breadcrumb │ +├──────────────┬─────────────────────┤ +│ │ │ +│ Gallery │ Product Info │ +│ (60%) │ (40%) │ +│ │ - Name │ +│ [Main Img] │ - Rating │ +│ │ - Price │ +│ [Thumbs] │ - Description │ +│ │ - Variants │ +│ │ - Add to Cart │ +│ │ - Trust Badges │ +│ │ │ +├──────────────┴─────────────────────┤ +│ Tabs (Description/Specs/Reviews) │ +├────────────────────────────────────┤ +│ Reviews Section │ +├────────────────────────────────────┤ +│ Related Products Grid │ +└────────────────────────────────────┘ +``` + +**When to use:** +- Desktop-first experience +- Products benefit from large imagery +- Enough information to fill right column + +**Responsive behavior:** +- < 1024px: Info column narrows to 45% +- < 768px: Stack vertically (gallery top) +- < 480px: Full-width, sticky CTA bar + +--- + +## Pattern B: Stacked (Mobile-First) + +**Best for:** Content-heavy products (books, courses, services) + +**Structure:** +``` +┌────────────────────────┐ +│ Breadcrumb │ +├────────────────────────┤ +│ Gallery (Full-width) │ +│ [Main Image] │ +│ [Thumbnail Strip] │ +├────────────────────────┤ +│ Product Name │ +│ Rating & Reviews │ +│ Price │ +├────────────────────────┤ +│ Short Description │ +│ Key Features List │ +├────────────────────────┤ +│ Variants Selection │ +├────────────────────────┤ +│ Add to Cart │ +│ Trust Badges │ +├────────────────────────┤ +│ Tabs/Accordion │ +├────────────────────────┤ +│ Reviews │ +├────────────────────────┤ +│ Related Products │ +└────────────────────────┘ +``` + +**When to use:** +- Mobile-first strategy +- Product needs detailed explanation +- Limited visual differentiation + +**Responsive behavior:** +- Naturally responsive +- Just adjust padding and font sizes +- Consider sticky CTA on mobile + +--- + +## Pattern C: Sidebar (Variant-Heavy) + +**Best for:** Products with many options (apparel with sizes/colors, configurable items) + +**Structure:** +``` +┌────────────────────────────────────┐ +│ Breadcrumb │ +├──────────────────────┬─────────────┤ +│ │ │ +│ Gallery + Info │ Sticky │ +│ (70%) │ Purchase │ +│ │ Sidebar │ +│ [Main Image] │ (30%) │ +│ │ │ +│ [Thumbnails] │ Price │ +│ │ Variants │ +│ Product Name │ Quantity │ +│ Rating │ Add Cart │ +│ Description │ Wishlist │ +│ │ Trust │ +│ │ │ +├──────────────────────┴─────────────┤ +│ Tabs │ +├────────────────────────────────────┤ +│ Reviews │ +├────────────────────────────────────┤ +│ Related Products │ +└────────────────────────────────────┘ +``` + +**When to use:** +- Many variants (colors, sizes, configurations) +- Price changes based on selection +- Want purchase options always visible + +**Responsive behavior:** +- < 1024px: Sidebar becomes 35% +- < 768px: Sidebar moves to bottom, becomes sticky bar +- < 480px: Full-width stacked + +--- + +## Choosing the Right Pattern + +| Product Type | Pattern | Why | +|---|---|---| +| Fashion/Apparel | Sidebar | Many size/color options | +| Electronics | Split-Screen | Strong visuals, specs matter | +| Furniture | Split-Screen | Large images crucial | +| Books/Digital | Stacked | Content over imagery | +| Custom/Configurable | Sidebar | Complex option selection | +| Luxury Items | Split-Screen | Image quality sells | + +--- + +## Responsive Breakpoints + +```css +/* Desktop-first approach */ +@media (max-width: 1024px) { /* Tablet landscape */ } +@media (max-width: 768px) { /* Tablet portrait */ } +@media (max-width: 480px) { /* Mobile */ } +``` + +**Key transformations:** +- Gallery: Grid → Carousel +- Info sections: Side-by-side → Stacked +- CTA: Inline → Sticky bottom bar +- Tabs: Horizontal → Accordion diff --git a/skills/progressive-web-app-skill/SKILL.md b/skills/progressive-web-app-skill/SKILL.md new file mode 100644 index 00000000..af5da5ab --- /dev/null +++ b/skills/progressive-web-app-skill/SKILL.md @@ -0,0 +1,124 @@ +--- +name: progressive-web-app-skill +description: | + PWA-ready mobile web app with offline support, install prompt, and app-like experience. + For mobile-first web apps, installable experiences, offline-capable apps. +triggers: + - "progressive web app" + - "PWA" + - "mobile web app" + - "installable app" +od: + mode: prototype + platform: mobile + scenario: application + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, components] + example_prompt: "Create a PWA for a task manager with offline support, bottom navigation, and native-like feel." +--- + +# Progressive Web App Skill + +Create mobile web apps that feel native. + +## PWA Characteristics + +**App-like:** +- Full-screen (no browser chrome) +- Bottom tab navigation +- Swipe gestures +- Pull-to-refresh +- Native scrolling + +**Installable:** +- Manifest file (referenced) +- App icons (referenced) +- Launch screen +- Display mode: standalone + +**Offline-ready:** +- Service worker (referenced) +- Offline fallback page +- Cache-first strategy +- Sync when online + +## Layout (Mobile) +``` +┌────────────────┐ +│ [Header/Title] │ +├────────────────┤ +│ │ +│ Main │ +│ Content │ +│ Area │ +│ │ +│ │ +├────────────────┤ +│ [Bottom Nav] │ +│ [⌂][+][☰][👤] │ +└────────────────┘ +``` + +## Features + +**Navigation:** +- Bottom tab bar (4-5 items) +- Active state clear +- Icons + labels +- Large touch targets (56px) + +**Interactions:** +- Smooth page transitions +- Pull-to-refresh indicator +- Loading skeletons +- Toast notifications +- Swipe to dismiss + +**Performance:** +- Fast initial load (< 3s) +- Smooth 60fps scrolling +- Lazy load images +- Code splitting + +**Accessibility:** +- Touch targets ≥ 44px +- High contrast mode +- Keyboard navigation +- Screen reader labels + +## Manifest (referenced) +```html + + + + +``` + +## Visual Design + +**Mobile-first:** +- Full-width content +- Generous padding (16-24px) +- Large touch targets +- Clear hierarchy + +**Typography:** +- Minimum 16px body (no zoom) +- Bold headings +- Comfortable line-height + +**Colors:** +- Theme color for status bar +- Consistent with brand +- Dark mode support + +## Offline Experience +- Show offline indicator +- Queue actions for later +- Cached content available +- "You're offline" message +- Sync icon when reconnected diff --git a/skills/responsive-design-system-skill/SKILL.md b/skills/responsive-design-system-skill/SKILL.md new file mode 100644 index 00000000..2fa1501f --- /dev/null +++ b/skills/responsive-design-system-skill/SKILL.md @@ -0,0 +1,163 @@ +--- +name: responsive-design-system-skill +description: | + Component library showcase with responsive examples, code snippets, and usage guidelines. + For design systems, component docs, pattern libraries. +triggers: + - "design system" + - "component library" + - "pattern library" + - "UI kit" + - "组件库" +od: + mode: design-system + platform: desktop + scenario: design + preview: + type: html + entry: index.html + design_system: + requires: false + example_prompt: "Create a design system showcase with buttons, forms, cards, and navigation components with responsive examples." +--- + +# Responsive Design System Skill + +Create comprehensive component library documentation. + +## Layout +``` +┌────────────────────────────────────────┐ +│ [Logo] Design System [Search] [GitHub]│ +├─────┬──────────────────────────────────┤ +│Nav │ Components > Buttons │ +│ │ │ +│Foun │ # Buttons │ +│dati │ │ +│ons │ ## Variants │ +│Comp │ [Primary] [Secondary] [Ghost] │ +│onen │ │ +│ ts │ ## Sizes │ +│Butt │ [Large] [Medium] [Small] │ +│ons │ │ +│Form │ ## States │ +│ s │ [Default] [Hover] [Disabled] │ +│Card │ │ +│ s │ ## Code │ +│ │ ```html │ +│ │ │ +│ │ ``` │ +└─────┴──────────────────────────────────┘ +``` + +## Sections + +**1. Foundations:** +- Colors (palette with hex codes) +- Typography (scale, weights, line-heights) +- Spacing (scale with visual examples) +- Grid system +- Icons + +**2. Components:** +- Buttons (all variants + states) +- Forms (inputs, selects, checkboxes, radio) +- Cards (different layouts) +- Navigation (header, sidebar, tabs) +- Modals/Dialogs +- Tables +- Alerts/Toasts +- Badges/Pills + +**3. Patterns:** +- Empty states +- Loading states +- Error states +- Success states +- Authentication flows +- Search patterns + +## Component Page Structure + +```markdown +# Component Name + +Brief description of when to use this component. + +## Variants +[Visual examples of each variant] + +## Sizes +[Visual examples of sizes] + +## States +[Default, Hover, Focus, Active, Disabled] + +## Usage Guidelines +✓ Do: Use for primary actions +✗ Don't: Use more than one primary button + +## Accessibility +- Keyboard: Space/Enter to activate +- Screen reader: Announces as button +- Focus: Visible outline required + +## Code +```html + +``` + +## Props / Classes +| Class | Description | +|---|---| +| `.btn-primary` | Primary action | +| `.btn-secondary` | Secondary action | +| `.btn-lg` | Large size | +``` + +## Interactive Demos +- Live playground where users can: + - Toggle variants + - Change sizes + - Test states + - Copy code + +## Responsive Behavior +Show component at different breakpoints: +- Mobile (375px) +- Tablet (768px) +- Desktop (1440px) + +## Design Tokens + +Show CSS custom properties: +```css +:root { + --color-primary: #2563eb; + --color-secondary: #64748b; + --spacing-unit: 8px; + --font-sans: 'Inter', sans-serif; + --radius-md: 6px; +} +``` + +## Visual Design + +**Layout:** +- Generous spacing between examples +- Clear labels +- Grouped by type + +**Code blocks:** +- Syntax highlighting +- Copy button +- Tab for different frameworks (HTML, React, Vue) + +**Examples:** +- Real, not abstract +- Show in context +- Multiple use cases diff --git a/skills/settings-page-skill/SKILL.md b/skills/settings-page-skill/SKILL.md new file mode 100644 index 00000000..bfba73e0 --- /dev/null +++ b/skills/settings-page-skill/SKILL.md @@ -0,0 +1,180 @@ +--- +name: settings-page-skill +description: | + Comprehensive settings interface with sidebar navigation, form sections, + save states, and danger zone. For app settings, user preferences, account management. +triggers: + - "settings page" + - "preferences" + - "account settings" + - "configuration" + - "设置页面" +od: + mode: prototype + platform: desktop + scenario: application + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + example_prompt: "Create a settings page with sidebar navigation for Profile, Notifications, Security, Billing, and Team sections." +--- + +# Settings Page Skill + +Create an organized settings interface that's easy to navigate and understand. + +## Layout Structure + +**Desktop:** +``` +┌────────────────────────────────────────┐ +│ Header │ +├────────┬───────────────────────────────┤ +│ ☰ Nav │ Settings Content │ +│ 240px │ │ +│ │ [Breadcrumb: Settings > Profile]│ +│ Profile│ │ +│ Notif. │ [Section: Personal Info] │ +│ Secur. │ [Form fields...] │ +│ Billing│ │ +│ Team │ [Section: Avatar] │ +│ Integr.│ [Upload area...] │ +│ │ │ +│ │ [Danger Zone] │ +│ │ [Delete Account] │ +│ │ │ +│ │ [Cancel] [Save Changes] │ +└────────┴───────────────────────────────┘ +``` + +## Navigation Sidebar + +**Categories (typical):** +- 👤 Profile +- 🔔 Notifications +- 🔒 Security +- 💳 Billing +- 👥 Team +- 🔌 Integrations +- ⚙️ Advanced + +**States:** +- Active: Highlighted background +- Hover: Subtle background change +- Badge: Show unsaved changes count + +## Content Sections + +**Section structure:** +``` +## Section Title +Brief description of what these settings control. + +[Form fields organized in groups] + +──────────────────────── + +## Next Section +... +``` + +**Form patterns:** +- Label above field +- Help text below (optional) +- Toggle switches for boolean +- Radio/checkbox for choices +- Dropdowns for many options + +## Save Behavior + +**Auto-save vs Manual:** +- Manual save (recommended for settings) +- "Save Changes" button, disabled until changes made +- "Cancel" reverts to last saved state +- Show "Unsaved changes" warning on navigate away + +**Feedback:** +- Success toast: "Settings saved" +- Error toast: "Failed to save. Try again." +- Inline validation on blur + +## Danger Zone + +**Destructive actions:** +- At bottom of relevant section +- Red border, red button +- Requires confirmation modal +- Examples: Delete account, Reset data, Leave team + +**Confirmation modal:** +``` +⚠️ Delete Account? + +This action cannot be undone. All your data +will be permanently deleted. + +Type "DELETE" to confirm: +[_____________] + +[Cancel] [Delete Account] +``` + +## Common Settings Sections + +**Profile:** +- Name, email, avatar +- Bio, timezone, language +- Public profile visibility + +**Notifications:** +- Email preferences (grouped) +- Push notification settings +- Digest frequency + +**Security:** +- Change password +- Two-factor authentication +- Active sessions list +- Connected accounts + +**Billing:** +- Current plan card +- Payment method +- Billing history table +- Update/cancel subscription + +**Team:** +- Team member list +- Invite new members +- Role management +- Team settings + +## Mobile Adaptation + +- Nav becomes hamburger menu +- Full-width form fields +- Stack sections vertically +- Sticky save button bar + +## Visual Design + +**Spacing:** +- Sections: 48px vertical gap +- Form groups: 24px gap +- Fields: 16px gap +- Generous padding in cards + +**Typography:** +- Page title: 32px +- Section headings: 20px, bold +- Labels: 14px, medium +- Help text: 13px, muted + +**Colors:** +- Use design system +- Danger zone: red background/border +- Success: green toast +- Muted: gray for help text diff --git a/skills/storefront-skill/SKILL.md b/skills/storefront-skill/SKILL.md new file mode 100644 index 00000000..6d48ef2b --- /dev/null +++ b/skills/storefront-skill/SKILL.md @@ -0,0 +1,64 @@ +--- +name: storefront-skill +description: | + E-commerce storefront with product grid, filters, search, and categories. + For online store homepage, product catalog, shop page. +triggers: + - "storefront" + - "product catalog" + - "shop page" + - "store homepage" + - "商城首页" +od: + mode: prototype + platform: desktop + scenario: commerce + preview: + type: html + entry: index.html + design_system: + requires: true + sections: [color, typography, layout, components] + example_prompt: "Create an e-commerce storefront with hero banner, featured products, category grid, and product listing with filters." +--- + +# Storefront Skill + +Create a conversion-optimized e-commerce homepage. + +## Layout +``` +┌────────────────────────────────────────┐ +│ Header [Logo] [Search] [Cart] [User] │ +├────────────────────────────────────────┤ +│ Hero Banner (Sale/Featured) │ +├─────┬──────────────────────────────────┤ +│Filters│ Product Grid (3-4 cols) │ +│200px│ [Product Card] [Product Card] │ +│ │ [Product Card] [Product Card] │ +│ │ ... pagination ... │ +└─────┴──────────────────────────────────┘ +``` + +## Product Card +- Image (square, 1:1) +- Product name (2 lines max) +- Price (large, bold) +- Rating (5 stars + count) +- "Add to Cart" on hover +- Sale badge if discounted +- "Out of Stock" overlay if needed + +## Filters +- Category (checkbox list) +- Price range (slider) +- Brand (checkbox) +- Rating (4+ stars) +- Availability (in stock) +- Apply/Clear buttons + +## Responsive +- Desktop: 4 columns +- Tablet: 3 columns +- Mobile: 2 columns +- Filters become drawer From 77d50d9044d5c1b745c964b8995313997f58a458 Mon Sep 17 00:00:00 2001 From: Serik Date: Mon, 22 Jun 2026 23:36:51 +0500 Subject: [PATCH 2/7] feat(core): add accessibility and code quality verification tools Implement comprehensive verification systems: Accessibility Verification (verify-accessibility.ts): - WCAG 2.1 Level A/AA compliance checking - Alt text, form labels, heading hierarchy - Color contrast, focus indicators, touch targets - Semantic HTML and landmark validation - Overall accessibility score (0-100) Code Quality Verification (verify-code-quality.ts): - HTML checks: DOCTYPE, charset, viewport, semantic elements - CSS checks: \!important usage, design tokens, mobile-first - JavaScript checks: console logs, eval, error handling - Performance checks: bundle size, lazy loading, blocking resources - Category scores with actionable recommendations Both tools ready for agent workflow integration. Co-Authored-By: Claude Opus 4.8 --- .../core/src/tools/verify-accessibility.ts | 429 +++++++++++++++ .../core/src/tools/verify-code-quality.ts | 504 ++++++++++++++++++ 2 files changed, 933 insertions(+) create mode 100644 packages/core/src/tools/verify-accessibility.ts create mode 100644 packages/core/src/tools/verify-code-quality.ts diff --git a/packages/core/src/tools/verify-accessibility.ts b/packages/core/src/tools/verify-accessibility.ts new file mode 100644 index 00000000..2550874a --- /dev/null +++ b/packages/core/src/tools/verify-accessibility.ts @@ -0,0 +1,429 @@ +/** + * Accessibility Verification Tool for Open CoDesign + * Checks generated HTML for WCAG 2.1 Level A/AA compliance + */ + +export interface AccessibilityCheck { + id: string; + severity: 'critical' | 'warning' | 'info'; + passed: boolean; + message: string; + element?: string; + line?: number; +} + +export interface AccessibilityReport { + overall_score: number; + total_checks: number; + passed: number; + failed: number; + warnings: number; + checks: AccessibilityCheck[]; + wcag_level: 'A' | 'AA' | 'AAA' | 'failed'; +} + +export interface AccessibilityOptions { + ignoreWarnings?: boolean; + customRules?: string[]; +} + +/** + * Main verification function + */ +export async function verifyAccessibility( + htmlContent: string, + options: AccessibilityOptions = {} +): Promise { + const checks: AccessibilityCheck[] = []; + + // Parse HTML (simple regex-based for now, can upgrade to full parser) + + // Run WCAG Level A checks + checks.push(...checkImages(htmlContent)); + checks.push(...checkFormLabels(htmlContent)); + checks.push(...checkHeadingHierarchy(htmlContent)); + checks.push(...checkSkipLinks(htmlContent)); + checks.push(...checkAriaRequired(htmlContent)); + + // Run WCAG Level AA checks + checks.push(...checkColorContrast(htmlContent)); + checks.push(...checkFocusIndicators(htmlContent)); + checks.push(...checkTouchTargets(htmlContent)); + + // Run best practices + checks.push(...checkSemanticHTML(htmlContent)); + checks.push(...checkLandmarks(htmlContent)); + + return aggregateReport(checks, options); +} + +/** + * WCAG Level A: Check all images have alt text + */ +function checkImages(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + const imgRegex = /]*>/gi; + const matches = html.match(imgRegex) || []; + + for (const img of matches) { + const hasAlt = /alt=["'][^"']*["']/.test(img) || /alt=""/.test(img); + + if (!hasAlt) { + checks.push({ + id: 'alt_text_on_images', + severity: 'critical', + passed: false, + message: 'Image missing alt attribute', + element: img.substring(0, 100) + }); + } else { + const altValue = img.match(/alt=["']([^"']*)["']/)?.[1]; + if (altValue && altValue.length > 0) { + checks.push({ + id: 'alt_text_on_images', + severity: 'critical', + passed: true, + message: 'Image has descriptive alt text', + element: img.substring(0, 100) + }); + } + } + } + + return checks; +} + +/** + * WCAG Level A: Check form inputs have labels + */ +function checkFormLabels(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + const inputRegex = /]*type=["'](?!hidden|submit|button)[^"']*["'][^>]*>/gi; + const matches = html.match(inputRegex) || []; + + for (const input of matches) { + const hasId = /id=["']([^"']+)["']/.test(input); + const idValue = input.match(/id=["']([^"']+)["']/)?.[1]; + + if (!hasId) { + checks.push({ + id: 'form_labels', + severity: 'critical', + passed: false, + message: 'Form input missing id for label association', + element: input.substring(0, 100) + }); + continue; + } + + // Check if there's a corresponding label + const labelRegex = new RegExp(`]*for=["']${idValue}["'][^>]*>`, 'i'); + const hasLabel = labelRegex.test(html); + + checks.push({ + id: 'form_labels', + severity: 'critical', + passed: hasLabel, + message: hasLabel + ? 'Form input has associated label' + : 'Form input missing associated label', + element: input.substring(0, 100) + }); + } + + return checks; +} + +/** + * WCAG Level A: Check heading hierarchy + */ +function checkHeadingHierarchy(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + const headingRegex = /]*>/gi; + const headings: number[] = []; + + let match; + while ((match = headingRegex.exec(html)) !== null) { + headings.push(parseInt(match[1])); + } + + if (headings.length === 0) { + checks.push({ + id: 'heading_hierarchy', + severity: 'warning', + passed: false, + message: 'No headings found - consider adding semantic structure' + }); + return checks; + } + + // Check if starts with h1 + if (headings[0] !== 1) { + checks.push({ + id: 'heading_hierarchy', + severity: 'warning', + passed: false, + message: 'Page should start with

, not ' + }); + } + + // Check for skipped levels + for (let i = 1; i < headings.length; i++) { + const current = headings[i]; + const previous = headings[i - 1]; + + if (current > previous + 1) { + checks.push({ + id: 'heading_hierarchy', + severity: 'warning', + passed: false, + message: `Heading hierarchy skipped from to ` + }); + } + } + + if (checks.length === 0) { + checks.push({ + id: 'heading_hierarchy', + severity: 'critical', + passed: true, + message: 'Heading hierarchy is logical' + }); + } + + return checks; +} + +/** + * WCAG Level A: Check for skip navigation link + */ +function checkSkipLinks(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + const hasSkipLink = /]*href=["']#(main|content|skip)[^"']*["'][^>]*>skip/i.test(html); + + checks.push({ + id: 'skip_links', + severity: 'info', + passed: hasSkipLink, + message: hasSkipLink + ? 'Skip navigation link present' + : 'Consider adding skip navigation link for keyboard users' + }); + + return checks; +} + +/** + * WCAG Level A: Check required ARIA attributes + */ +function checkAriaRequired(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + + // Check buttons have accessible names + const buttonRegex = /]*>/gi; + const buttons = html.match(buttonRegex) || []; + + for (const button of buttons) { + const hasText = /]*>([^<]+)<\/button>/.test( + html.substring(html.indexOf(button)) + ); + const hasAriaLabel = /aria-label=["'][^"']+["']/.test(button); + + if (!hasText && !hasAriaLabel) { + checks.push({ + id: 'aria_required', + severity: 'critical', + passed: false, + message: 'Button missing accessible name (text content or aria-label)', + element: button.substring(0, 100) + }); + } + } + + return checks; +} + +/** + * WCAG Level AA: Check color contrast (basic CSS color extraction) + */ +function checkColorContrast(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + + // This is a simplified check - real implementation would parse CSS + // and calculate actual contrast ratios + const lowContrastPatterns = [ + /color:\s*#[cdef][0-9a-f]{5}/gi, // Light text colors + /color:\s*rgba?\([^)]*0\.[0-5]\)/gi, // Low opacity text + ]; + + for (const pattern of lowContrastPatterns) { + if (pattern.test(html)) { + checks.push({ + id: 'color_contrast', + severity: 'warning', + passed: false, + message: 'Potential low contrast text detected - verify WCAG AA (4.5:1) compliance' + }); + break; + } + } + + if (checks.length === 0) { + checks.push({ + id: 'color_contrast', + severity: 'warning', + passed: true, + message: 'No obvious contrast issues detected (manual verification recommended)' + }); + } + + return checks; +} + +/** + * WCAG Level AA: Check focus indicators + */ +function checkFocusIndicators(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + + // Check if :focus styles are removed + const removesFocus = /(:focus|:focus-visible)\s*{\s*outline:\s*(none|0)/i.test(html); + + if (removesFocus) { + checks.push({ + id: 'focus_indicators', + severity: 'critical', + passed: false, + message: 'Focus outline removed - ensure custom focus indicator is visible' + }); + } else { + checks.push({ + id: 'focus_indicators', + severity: 'critical', + passed: true, + message: 'Focus indicators preserved (default or custom)' + }); + } + + return checks; +} + +/** + * WCAG Level AA: Check touch target sizes (mobile) + */ +function checkTouchTargets(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + + // Check for small button/link sizes + const hasSmallTargets = /height:\s*[1-3][0-9]px|width:\s*[1-3][0-9]px/i.test(html); + + if (hasSmallTargets) { + checks.push({ + id: 'touch_target_size', + severity: 'warning', + passed: false, + message: 'Small touch targets detected - ensure minimum 44×44px on mobile' + }); + } + + return checks; +} + +/** + * Best Practice: Check semantic HTML usage + */ +function checkSemanticHTML(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + const semanticTags = ['header', 'nav', 'main', 'article', 'section', 'aside', 'footer']; + + const hasSemantic = semanticTags.some(tag => + new RegExp(`<${tag}[\\s>]`, 'i').test(html) + ); + + checks.push({ + id: 'semantic_html', + severity: 'info', + passed: hasSemantic, + message: hasSemantic + ? 'Uses semantic HTML5 elements' + : 'Consider using semantic HTML5 elements (header, nav, main, etc.)' + }); + + return checks; +} + +/** + * Best Practice: Check landmark regions + */ +function checkLandmarks(html: string): AccessibilityCheck[] { + const checks: AccessibilityCheck[] = []; + + const hasMain = /]*>/i.test(html) || /role=["']main["']/i.test(html); + const hasNav = /]*>/i.test(html) || /role=["']navigation["']/i.test(html); + + if (!hasMain) { + checks.push({ + id: 'landmarks', + severity: 'warning', + passed: false, + message: 'Missing
landmark - helps screen reader users navigate' + }); + } + + if (hasNav && hasMain) { + checks.push({ + id: 'landmarks', + severity: 'info', + passed: true, + message: 'Document has landmark regions' + }); + } + + return checks; +} + +/** + * Aggregate all checks into final report + */ +function aggregateReport( + checks: AccessibilityCheck[], + options: AccessibilityOptions +): AccessibilityReport { + const total = checks.length; + const passed = checks.filter(c => c.passed).length; + const failed = checks.filter(c => !c.passed && c.severity === 'critical').length; + const warnings = checks.filter(c => !c.passed && c.severity === 'warning').length; + + // Calculate score (critical failures heavily weighted) + const criticalPassed = checks.filter(c => c.severity === 'critical' && c.passed).length; + const criticalTotal = checks.filter(c => c.severity === 'critical').length; + const criticalScore = criticalTotal > 0 ? (criticalPassed / criticalTotal) * 100 : 100; + + const warningScore = warnings === 0 ? 100 : Math.max(0, 100 - (warnings * 5)); + + const overall_score = Math.round((criticalScore * 0.7) + (warningScore * 0.3)); + + // Determine WCAG level + let wcag_level: 'A' | 'AA' | 'AAA' | 'failed'; + if (failed > 0) { + wcag_level = 'failed'; + } else if (warnings === 0) { + wcag_level = 'AA'; + } else if (warnings <= 2) { + wcag_level = 'A'; + } else { + wcag_level = 'failed'; + } + + return { + overall_score, + total_checks: total, + passed, + failed, + warnings, + checks: options.ignoreWarnings + ? checks.filter(c => c.severity === 'critical') + : checks, + wcag_level + }; +} diff --git a/packages/core/src/tools/verify-code-quality.ts b/packages/core/src/tools/verify-code-quality.ts new file mode 100644 index 00000000..0c976d5e --- /dev/null +++ b/packages/core/src/tools/verify-code-quality.ts @@ -0,0 +1,504 @@ +/** + * Code Quality Verification Tool for Open CoDesign + * Automated checking of HTML, CSS, JS, and Performance + */ + +export interface CodeQualityCheck { + category: 'html' | 'css' | 'js' | 'performance'; + rule: string; + severity: 'error' | 'warning' | 'info'; + passed: boolean; + message: string; + line?: number; + suggestion?: string; +} + +export interface CategoryScore { + score: number; + passed: number; + failed: number; + warnings: number; +} + +export interface CodeQualityReport { + overall_score: number; // 0-100 + categories: { + html: CategoryScore; + css: CategoryScore; + js: CategoryScore; + performance: CategoryScore; + }; + checks: CodeQualityCheck[]; + recommendations: string[]; +} + +/** + * Main verification function + */ +export async function verifyCodeQuality( + html: string, + css?: string, + js?: string +): Promise { + const checks: CodeQualityCheck[] = []; + + // Extract CSS and JS from HTML if not provided separately + if (!css) { + const cssMatch = html.match(/]*>([\s\S]*?)<\/style>/i); + css = cssMatch ? cssMatch[1] : ''; + } + + if (!js) { + const jsMatch = html.match(/]*>([\s\S]*?)<\/script>/i); + js = jsMatch ? jsMatch[1] : ''; + } + + // Run HTML checks + checks.push(...checkHTML(html)); + + // Run CSS checks + if (css) { + checks.push(...checkCSS(css)); + } + + // Run JS checks + if (js) { + checks.push(...checkJS(js)); + } + + // Run performance checks + checks.push(...checkPerformance(html, css, js)); + + return aggregateReport(checks); +} + +/** + * HTML Quality Checks + */ +function checkHTML(html: string): CodeQualityCheck[] { + const checks: CodeQualityCheck[] = []; + + // Check 1: Valid DOCTYPE + if (!/^/i.test(html.trim())) { + checks.push({ + category: 'html', + rule: 'valid_doctype', + severity: 'error', + passed: false, + message: 'Missing or invalid DOCTYPE declaration', + suggestion: 'Add at the start of the file' + }); + } else { + checks.push({ + category: 'html', + rule: 'valid_doctype', + severity: 'error', + passed: true, + message: 'Valid DOCTYPE present' + }); + } + + // Check 2: Charset declaration + if (!/]*charset/i.test(html)) { + checks.push({ + category: 'html', + rule: 'charset_declaration', + severity: 'error', + passed: false, + message: 'Missing charset declaration', + suggestion: 'Add in ' + }); + } + + // Check 3: Viewport meta tag + if (!/]*name=["']viewport["']/i.test(html)) { + checks.push({ + category: 'html', + rule: 'meta_viewport', + severity: 'warning', + passed: false, + message: 'Missing viewport meta tag for responsive design', + suggestion: 'Add ' + }); + } + + // Check 4: Inline styles abuse + const inlineStyleCount = (html.match(/style="/g) || []).length; + if (inlineStyleCount > 5) { + checks.push({ + category: 'html', + rule: 'no_inline_styles_abuse', + severity: 'warning', + passed: false, + message: `Too many inline styles (${inlineStyleCount} found) - use CSS classes instead`, + suggestion: 'Extract inline styles to CSS classes' + }); + } + + // Check 5: Proper nesting + const badNesting = [ + { pattern: /]*>[\s\S]*
inside

' }, + { pattern: /]*>[\s\S]*

inside ' }, + { pattern: /]*>[\s\S]* inside ' } + ]; + + for (const { pattern, message } of badNesting) { + if (pattern.test(html)) { + checks.push({ + category: 'html', + rule: 'proper_nesting', + severity: 'error', + passed: false, + message: `HTML nesting error: ${message}`, + suggestion: 'Fix element nesting according to HTML spec' + }); + break; + } + } + + // Check 6: Semantic HTML usage + const semanticTags = ['header', 'nav', 'main', 'article', 'section', 'aside', 'footer']; + const hasSemantic = semanticTags.some(tag => new RegExp(`<${tag}[\\s>]`, 'i').test(html)); + + checks.push({ + category: 'html', + rule: 'semantic_html', + severity: 'info', + passed: hasSemantic, + message: hasSemantic + ? 'Uses semantic HTML5 elements' + : 'Consider using semantic HTML5 elements', + suggestion: hasSemantic ? undefined : 'Use
,
,