Fix .claude/skills data drift, harden search engine, tighten SKILL.md (#412)

Merged by github-maintain cron. Approved by @clark-cant and @jizc. Pre-existing pytest failure on main (ui-styling/shadcn test) is unrelated to PR scope.
This commit is contained in:
sunilchandarjr 2026-07-14 11:32:50 -07:00 committed by GitHub
parent fe3f65e5d0
commit f8ac5e1266
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
41 changed files with 3364 additions and 1528 deletions

View File

@ -1,11 +1,21 @@
{
"name": "ui-ux-pro-max",
"description": "UI/UX design intelligence. Searchable local database with 84 styles, 161 palettes, 73 font pairings, 25 charts, and 17 stacks (React, Next.js, Vue, Nuxt.js, Nuxt UI, Svelte, Astro, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, Jetpack Compose, Angular, Laravel, JavaFX, Three.js). Use when designing, building, or reviewing UI: pages, components, color schemes, typography, layout, accessibility, animation, or data visualization.",
"description": "UI/UX design intelligence. Searchable local database with 84 styles, 192 palettes, 74 font pairings, 25 charts, and 22 stacks (React, Next.js, Vue, Nuxt.js, Nuxt UI, Svelte, Astro, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, Jetpack Compose, Angular, Laravel, JavaFX, WPF, WinUI, Avalonia, Uno Platform, UWP, Three.js). Use when designing, building, or reviewing UI: pages, components, color schemes, typography, layout, accessibility, animation, or data visualization.",
"version": "2.11.0",
"author": {
"name": "nextlevelbuilder"
},
"license": "MIT",
"keywords": ["ui", "ux", "design", "styles", "typography", "color-palette", "accessibility", "charts", "components"],
"keywords": [
"ui",
"ux",
"design",
"styles",
"typography",
"color-palette",
"accessibility",
"charts",
"components"
],
"skills": "./.claude/skills/"
}

View File

@ -1,53 +1,21 @@
---
name: ui-ux-pro-max
description: "UI/UX design intelligence for web and mobile. Searchable local database with 50+ styles, 161 color palettes, 57 font pairings, 161 product types, 99 UX guidelines, and 25 chart types across 10 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, and HTML/CSS). Use when designing, building, or reviewing UI: pages, components, color schemes, typography, layout, accessibility, animation, or data visualization."
description: "UI/UX design intelligence for web and mobile. Searchable local database with 84 styles, 192 color palettes, 74 font pairings, 192 product types, 98 UX guidelines, 104 icon entries, 16 GSAP motion presets, and 25 chart types across 22 stacks (React, Next.js, Vue, Nuxt, Svelte, Astro, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, Jetpack Compose, Angular, Laravel, JavaFX, WPF, WinUI, Avalonia, Uno Platform, UWP, Three.js, and HTML/CSS). Use when designing, building, or reviewing UI: pages, components, color schemes, typography, layout, accessibility, animation, or data visualization."
---
# UI/UX Pro Max - Design Intelligence
Comprehensive design guide for web and mobile applications. Contains 50+ styles, 161 color palettes, 57 font pairings, 161 product types with reasoning rules, 99 UX guidelines, and 25 chart types across 10 technology stacks. Searchable database with priority-based recommendations.
Searchable database of UI/UX design rules with priority-based recommendations: 84 styles, 192 color palettes, 74 font pairings, 192 product types with reasoning rules, 98 UX guidelines, 104 icon entries, 16 GSAP motion presets, and 25 chart types across 22 technology stacks.
## When to Apply
This Skill should be used when the task involves **UI structure, visual design decisions, interaction patterns, or user experience quality control**.
Use this Skill when the task involves **UI structure, visual design decisions, interaction patterns, or user experience quality control**: designing new pages, creating/refactoring UI components, choosing color/typography/spacing/layout systems, reviewing UI for UX/accessibility/consistency, implementing navigation/animation/responsive behavior, or improving perceived quality and usability.
### Primary Use Cases
This Skill is most useful in the following situations:
- Designing new pages (Landing Page, Dashboard, Admin, SaaS, Mobile App)
- Creating or refactoring UI components (buttons, modals, forms, tables, charts, etc.)
- Choosing color schemes, typography systems, spacing standards, or layout systems
- Reviewing UI code for user experience, accessibility, or visual consistency
- Implementing navigation structures, animations, or responsive behavior
- Making product-level design decisions (style, information hierarchy, brand expression)
- Improving perceived quality, clarity, or usability of interfaces
### Recommended
This Skill is recommended in the following situations:
- UI looks "not professional enough" but the reason is unclear
- Receiving feedback on usability or experience
- Pre-launch UI quality optimization
- Aligning cross-platform design (Web / iOS / Android)
- Building design systems or reusable component libraries
### Skip
This Skill is not needed in the following situations:
- Pure backend logic development
- Only involving API or database design
- Performance optimization unrelated to the interface
- Infrastructure or DevOps work
- Non-visual scripts or automation tasks
**Decision criteria**: If the task will change how a feature **looks, feels, moves, or is interacted with**, this Skill should be used.
Skip it for pure backend logic, API/database design, non-visual performance work, infrastructure/DevOps, or non-visual scripts — unless the task changes how something **looks, feels, moves, or is interacted with**.
## Rule Categories by Priority
*For human/AI reference: follow priority 1→10 to decide which rule category to focus on first; use `--domain <Domain>` to query details when needed. Scripts do not read this table.*
*Follow priority 1→10 to decide which category to focus on first; use `--domain <Domain>` to query full details. The full rule text for every category lives in `references/quick-reference.md` — read it on demand rather than loading it every time.*
| Priority | Category | Impact | Domain | Key Checks (Must Have) | Anti-Patterns (Avoid) |
|----------|----------|--------|--------|------------------------|------------------------|
@ -57,355 +25,77 @@ This Skill is not needed in the following situations:
| 4 | Style Selection | HIGH | `style`, `product` | Match product type, Consistency, SVG icons (no emoji) | Mixing flat & skeuomorphic randomly, Emoji as icons |
| 5 | Layout & Responsive | HIGH | `ux` | Mobile-first breakpoints, Viewport meta, No horizontal scroll | Horizontal scroll, Fixed px container widths, Disable zoom |
| 6 | Typography & Color | MEDIUM | `typography`, `color` | Base 16px, Line-height 1.5, Semantic color tokens | Text &lt; 12px body, Gray-on-gray, Raw hex in components |
| 7 | Animation | MEDIUM | `ux` | Duration 150300ms, Motion conveys meaning, Spatial continuity | Decorative-only animation, Animating width/height, No reduced-motion |
| 7 | Animation | MEDIUM | `ux`, `gsap` | Duration 150300ms, Motion conveys meaning, Spatial continuity | Decorative-only animation, Animating width/height, No reduced-motion |
| 8 | Forms & Feedback | MEDIUM | `ux` | Visible labels, Error near field, Helper text, Progressive disclosure | Placeholder-only label, Errors only at top, Overwhelm upfront |
| 9 | Navigation Patterns | HIGH | `ux` | Predictable back, Bottom nav ≤5, Deep linking | Overloaded nav, Broken back behavior, No deep links |
| 10 | Charts & Data | LOW | `chart` | Legends, Tooltips, Accessible colors | Relying on color alone to convey meaning |
## Quick Reference
### 1. Accessibility (CRITICAL)
- `color-contrast` - Minimum 4.5:1 ratio for normal text (large text 3:1); Material Design
- `focus-states` - Visible focus rings on interactive elements (24px; Apple HIG, MD)
- `alt-text` - Descriptive alt text for meaningful images
- `aria-labels` - aria-label for icon-only buttons; accessibilityLabel in native (Apple HIG)
- `keyboard-nav` - Tab order matches visual order; full keyboard support (Apple HIG)
- `form-labels` - Use label with for attribute
- `skip-links` - Skip to main content for keyboard users
- `heading-hierarchy` - Sequential h1→h6, no level skip
- `color-not-only` - Don't convey info by color alone (add icon/text)
- `dynamic-type` - Support system text scaling; avoid truncation as text grows (Apple Dynamic Type, MD)
- `reduced-motion` - Respect prefers-reduced-motion; reduce/disable animations when requested (Apple Reduced Motion API, MD)
- `voiceover-sr` - Meaningful accessibilityLabel/accessibilityHint; logical reading order for VoiceOver/screen readers (Apple HIG, MD)
- `escape-routes` - Provide cancel/back in modals and multi-step flows (Apple HIG)
- `keyboard-shortcuts` - Preserve system and a11y shortcuts; offer keyboard alternatives for drag-and-drop (Apple HIG)
### 2. Touch & Interaction (CRITICAL)
- `touch-target-size` - Min 44×44pt (Apple) / 48×48dp (Material); extend hit area beyond visual bounds if needed
- `touch-spacing` - Minimum 8px/8dp gap between touch targets (Apple HIG, MD)
- `hover-vs-tap` - Use click/tap for primary interactions; don't rely on hover alone
- `loading-buttons` - Disable button during async operations; show spinner or progress
- `error-feedback` - Clear error messages near problem
- `cursor-pointer` - Add cursor-pointer to clickable elements (Web)
- `gesture-conflicts` - Avoid horizontal swipe on main content; prefer vertical scroll
- `tap-delay` - Use touch-action: manipulation to reduce 300ms delay (Web)
- `standard-gestures` - Use platform standard gestures consistently; don't redefine (e.g. swipe-back, pinch-zoom) (Apple HIG)
- `system-gestures` - Don't block system gestures (Control Center, back swipe, etc.) (Apple HIG)
- `press-feedback` - Visual feedback on press (ripple/highlight; MD state layers)
- `haptic-feedback` - Use haptic for confirmations and important actions; avoid overuse (Apple HIG)
- `gesture-alternative` - Don't rely on gesture-only interactions; always provide visible controls for critical actions
- `safe-area-awareness` - Keep primary touch targets away from notch, Dynamic Island, gesture bar and screen edges
- `no-precision-required` - Avoid requiring pixel-perfect taps on small icons or thin edges
- `swipe-clarity` - Swipe actions must show clear affordance or hint (chevron, label, tutorial)
- `drag-threshold` - Use a movement threshold before starting drag to avoid accidental drags
### 3. Performance (HIGH)
- `image-optimization` - Use WebP/AVIF, responsive images (srcset/sizes), lazy load non-critical assets
- `image-dimension` - Declare width/height or use aspect-ratio to prevent layout shift (Core Web Vitals: CLS)
- `font-loading` - Use font-display: swap/optional to avoid invisible text (FOIT); reserve space to reduce layout shift (MD)
- `font-preload` - Preload only critical fonts; avoid overusing preload on every variant
- `critical-css` - Prioritize above-the-fold CSS (inline critical CSS or early-loaded stylesheet)
- `lazy-loading` - Lazy load non-hero components via dynamic import / route-level splitting
- `bundle-splitting` - Split code by route/feature (React Suspense / Next.js dynamic) to reduce initial load and TTI
- `third-party-scripts` - Load third-party scripts async/defer; audit and remove unnecessary ones (MD)
- `reduce-reflows` - Avoid frequent layout reads/writes; batch DOM reads then writes
- `content-jumping` - Reserve space for async content to avoid layout jumps (Core Web Vitals: CLS)
- `lazy-load-below-fold` - Use loading="lazy" for below-the-fold images and heavy media
- `virtualize-lists` - Virtualize lists with 50+ items to improve memory efficiency and scroll performance
- `main-thread-budget` - Keep per-frame work under ~16ms for 60fps; move heavy tasks off main thread (HIG, MD)
- `progressive-loading` - Use skeleton screens / shimmer instead of long blocking spinners for >1s operations (Apple HIG)
- `input-latency` - Keep input latency under ~100ms for taps/scrolls (Material responsiveness standard)
- `tap-feedback-speed` - Provide visual feedback within 100ms of tap (Apple HIG)
- `debounce-throttle` - Use debounce/throttle for high-frequency events (scroll, resize, input)
- `offline-support` - Provide offline state messaging and basic fallback (PWA / mobile)
- `network-fallback` - Offer degraded modes for slow networks (lower-res images, fewer animations)
### 4. Style Selection (HIGH)
- `style-match` - Match style to product type (use `--design-system` for recommendations)
- `consistency` - Use same style across all pages
- `no-emoji-icons` - Use SVG icons (Heroicons, Lucide), not emojis
- `color-palette-from-product` - Choose palette from product/industry (search `--domain color`)
- `effects-match-style` - Shadows, blur, radius aligned with chosen style (glass / flat / clay etc.)
- `platform-adaptive` - Respect platform idioms (iOS HIG vs Material): navigation, controls, typography, motion
- `state-clarity` - Make hover/pressed/disabled states visually distinct while staying on-style (Material state layers)
- `elevation-consistent` - Use a consistent elevation/shadow scale for cards, sheets, modals; avoid random shadow values
- `dark-mode-pairing` - Design light/dark variants together to keep brand, contrast, and style consistent
- `icon-style-consistent` - Use one icon set/visual language (stroke width, corner radius) across the product
- `system-controls` - Prefer native/system controls over fully custom ones; only customize when branding requires it (Apple HIG)
- `blur-purpose` - Use blur to indicate background dismissal (modals, sheets), not as decoration (Apple HIG)
- `primary-action` - Each screen should have only one primary CTA; secondary actions visually subordinate (Apple HIG)
### 5. Layout & Responsive (HIGH)
- `viewport-meta` - width=device-width initial-scale=1 (never disable zoom)
- `mobile-first` - Design mobile-first, then scale up to tablet and desktop
- `breakpoint-consistency` - Use systematic breakpoints (e.g. 375 / 768 / 1024 / 1440)
- `readable-font-size` - Minimum 16px body text on mobile (avoids iOS auto-zoom)
- `line-length-control` - Mobile 3560 chars per line; desktop 6075 chars
- `horizontal-scroll` - No horizontal scroll on mobile; ensure content fits viewport width
- `spacing-scale` - Use 4pt/8dp incremental spacing system (Material Design)
- `touch-density` - Keep component spacing comfortable for touch: not cramped, not causing mis-taps
- `container-width` - Consistent max-width on desktop (max-w-6xl / 7xl)
- `z-index-management` - Define layered z-index scale (e.g. 0 / 10 / 20 / 40 / 100 / 1000)
- `fixed-element-offset` - Fixed navbar/bottom bar must reserve safe padding for underlying content
- `scroll-behavior` - Avoid nested scroll regions that interfere with the main scroll experience
- `viewport-units` - Prefer min-h-dvh over 100vh on mobile
- `orientation-support` - Keep layout readable and operable in landscape mode
- `content-priority` - Show core content first on mobile; fold or hide secondary content
- `visual-hierarchy` - Establish hierarchy via size, spacing, contrast — not color alone
### 6. Typography & Color (MEDIUM)
- `line-height` - Use 1.5-1.75 for body text
- `line-length` - Limit to 65-75 characters per line
- `font-pairing` - Match heading/body font personalities
- `font-scale` - Consistent type scale (e.g. 12 14 16 18 24 32)
- `contrast-readability` - Darker text on light backgrounds (e.g. slate-900 on white)
- `text-styles-system` - Use platform type system: iOS 11 Dynamic Type styles / Material 5 type roles (display, headline, title, body, label) (HIG, MD)
- `weight-hierarchy` - Use font-weight to reinforce hierarchy: Bold headings (600700), Regular body (400), Medium labels (500) (MD)
- `color-semantic` - Define semantic color tokens (primary, secondary, error, surface, on-surface) not raw hex in components (Material color system)
- `color-dark-mode` - Dark mode uses desaturated / lighter tonal variants, not inverted colors; test contrast separately (HIG, MD)
- `color-accessible-pairs` - Foreground/background pairs must meet 4.5:1 (AA) or 7:1 (AAA); use tools to verify (WCAG, MD)
- `color-not-decorative-only` - Functional color (error red, success green) must include icon/text; avoid color-only meaning (HIG, MD)
- `truncation-strategy` - Prefer wrapping over truncation; when truncating use ellipsis and provide full text via tooltip/expand (Apple HIG)
- `letter-spacing` - Respect default letter-spacing per platform; avoid tight tracking on body text (HIG, MD)
- `number-tabular` - Use tabular/monospaced figures for data columns, prices, and timers to prevent layout shift
- `whitespace-balance` - Use whitespace intentionally to group related items and separate sections; avoid visual clutter (Apple HIG)
### 7. Animation (MEDIUM)
- `duration-timing` - Use 150300ms for micro-interactions; complex transitions ≤400ms; avoid >500ms (MD)
- `transform-performance` - Use transform/opacity only; avoid animating width/height/top/left
- `loading-states` - Show skeleton or progress indicator when loading exceeds 300ms
- `excessive-motion` - Animate 1-2 key elements per view max
- `easing` - Use ease-out for entering, ease-in for exiting; avoid linear for UI transitions
- `motion-meaning` - Every animation must express a cause-effect relationship, not just be decorative (Apple HIG)
- `state-transition` - State changes (hover / active / expanded / collapsed / modal) should animate smoothly, not snap
- `continuity` - Page/screen transitions should maintain spatial continuity (shared element, directional slide) (Apple HIG)
- `parallax-subtle` - Use parallax sparingly; must respect reduced-motion and not cause disorientation (Apple HIG)
- `spring-physics` - Prefer spring/physics-based curves over linear or cubic-bezier for natural feel (Apple HIG fluid animations)
- `exit-faster-than-enter` - Exit animations shorter than enter (~6070% of enter duration) to feel responsive (MD motion)
- `stagger-sequence` - Stagger list/grid item entrance by 3050ms per item; avoid all-at-once or too-slow reveals (MD)
- `shared-element-transition` - Use shared element / hero transitions for visual continuity between screens (MD, HIG)
- `interruptible` - Animations must be interruptible; user tap/gesture cancels in-progress animation immediately (Apple HIG)
- `no-blocking-animation` - Never block user input during an animation; UI must stay interactive (Apple HIG)
- `fade-crossfade` - Use crossfade for content replacement within the same container (MD)
- `scale-feedback` - Subtle scale (0.951.05) on press for tappable cards/buttons; restore on release (HIG, MD)
- `gesture-feedback` - Drag, swipe, and pinch must provide real-time visual response tracking the finger (MD Motion)
- `hierarchy-motion` - Use translate/scale direction to express hierarchy: enter from below = deeper, exit upward = back (MD)
- `motion-consistency` - Unify duration/easing tokens globally; all animations share the same rhythm and feel
- `opacity-threshold` - Fading elements should not linger below opacity 0.2; either fade fully or remain visible
- `modal-motion` - Modals/sheets should animate from their trigger source (scale+fade or slide-in) for spatial context (HIG, MD)
- `navigation-direction` - Forward navigation animates left/up; backward animates right/down — keep direction logically consistent (HIG)
- `layout-shift-avoid` - Animations must not cause layout reflow or CLS; use transform for position changes
### 8. Forms & Feedback (MEDIUM)
- `input-labels` - Visible label per input (not placeholder-only)
- `error-placement` - Show error below the related field
- `submit-feedback` - Loading then success/error state on submit
- `required-indicators` - Mark required fields (e.g. asterisk)
- `empty-states` - Helpful message and action when no content
- `toast-dismiss` - Auto-dismiss toasts in 3-5s
- `confirmation-dialogs` - Confirm before destructive actions
- `input-helper-text` - Provide persistent helper text below complex inputs, not just placeholder (Material Design)
- `disabled-states` - Disabled elements use reduced opacity (0.380.5) + cursor change + semantic attribute (MD)
- `progressive-disclosure` - Reveal complex options progressively; don't overwhelm users upfront (Apple HIG)
- `inline-validation` - Validate on blur (not keystroke); show error only after user finishes input (MD)
- `input-type-keyboard` - Use semantic input types (email, tel, number) to trigger the correct mobile keyboard (HIG, MD)
- `password-toggle` - Provide show/hide toggle for password fields (MD)
- `autofill-support` - Use autocomplete / textContentType attributes so the system can autofill (HIG, MD)
- `undo-support` - Allow undo for destructive or bulk actions (e.g. "Undo delete" toast) (Apple HIG)
- `success-feedback` - Confirm completed actions with brief visual feedback (checkmark, toast, color flash) (MD)
- `error-recovery` - Error messages must include a clear recovery path (retry, edit, help link) (HIG, MD)
- `multi-step-progress` - Multi-step flows show step indicator or progress bar; allow back navigation (MD)
- `form-autosave` - Long forms should auto-save drafts to prevent data loss on accidental dismissal (Apple HIG)
- `sheet-dismiss-confirm` - Confirm before dismissing a sheet/modal with unsaved changes (Apple HIG)
- `error-clarity` - Error messages must state cause + how to fix (not just "Invalid input") (HIG, MD)
- `field-grouping` - Group related fields logically (fieldset/legend or visual grouping) (MD)
- `read-only-distinction` - Read-only state should be visually and semantically different from disabled (MD)
- `focus-management` - After submit error, auto-focus the first invalid field (WCAG, MD)
- `error-summary` - For multiple errors, show summary at top with anchor links to each field (WCAG)
- `touch-friendly-input` - Mobile input height ≥44px to meet touch target requirements (Apple HIG)
- `destructive-emphasis` - Destructive actions use semantic danger color (red) and are visually separated from primary actions (HIG, MD)
- `toast-accessibility` - Toasts must not steal focus; use aria-live="polite" for screen reader announcement (WCAG)
- `aria-live-errors` - Form errors use aria-live region or role="alert" to notify screen readers (WCAG)
- `contrast-feedback` - Error and success state colors must meet 4.5:1 contrast ratio (WCAG, MD)
- `timeout-feedback` - Request timeout must show clear feedback with retry option (MD)
### 9. Navigation Patterns (HIGH)
- `bottom-nav-limit` - Bottom navigation max 5 items; use labels with icons (Material Design)
- `drawer-usage` - Use drawer/sidebar for secondary navigation, not primary actions (Material Design)
- `back-behavior` - Back navigation must be predictable and consistent; preserve scroll/state (Apple HIG, MD)
- `deep-linking` - All key screens must be reachable via deep link / URL for sharing and notifications (Apple HIG, MD)
- `tab-bar-ios` - iOS: use bottom Tab Bar for top-level navigation (Apple HIG)
- `top-app-bar-android` - Android: use Top App Bar with navigation icon for primary structure (Material Design)
- `nav-label-icon` - Navigation items must have both icon and text label; icon-only nav harms discoverability (MD)
- `nav-state-active` - Current location must be visually highlighted (color, weight, indicator) in navigation (HIG, MD)
- `nav-hierarchy` - Primary nav (tabs/bottom bar) vs secondary nav (drawer/settings) must be clearly separated (MD)
- `modal-escape` - Modals and sheets must offer a clear close/dismiss affordance; swipe-down to dismiss on mobile (Apple HIG)
- `search-accessible` - Search must be easily reachable (top bar or tab); provide recent/suggested queries (MD)
- `breadcrumb-web` - Web: use breadcrumbs for 3+ level deep hierarchies to aid orientation (MD)
- `state-preservation` - Navigating back must restore previous scroll position, filter state, and input (HIG, MD)
- `gesture-nav-support` - Support system gesture navigation (iOS swipe-back, Android predictive back) without conflict (HIG, MD)
- `tab-badge` - Use badges on nav items sparingly to indicate unread/pending; clear after user visits (HIG, MD)
- `overflow-menu` - When actions exceed available space, use overflow/more menu instead of cramming (MD)
- `bottom-nav-top-level` - Bottom nav is for top-level screens only; never nest sub-navigation inside it (MD)
- `adaptive-navigation` - Large screens (≥1024px) prefer sidebar; small screens use bottom/top nav (Material Adaptive)
- `back-stack-integrity` - Never silently reset the navigation stack or unexpectedly jump to home (HIG, MD)
- `navigation-consistency` - Navigation placement must stay the same across all pages; don't change by page type
- `avoid-mixed-patterns` - Don't mix Tab + Sidebar + Bottom Nav at the same hierarchy level
- `modal-vs-navigation` - Modals must not be used for primary navigation flows; they break the user's path (HIG)
- `focus-on-route-change` - After page transition, move focus to main content region for screen reader users (WCAG)
- `persistent-nav` - Core navigation must remain reachable from deep pages; don't hide it entirely in sub-flows (HIG, MD)
- `destructive-nav-separation` - Dangerous actions (delete account, logout) must be visually and spatially separated from normal nav items (HIG, MD)
- `empty-nav-state` - When a nav destination is unavailable, explain why instead of silently hiding it (MD)
### 10. Charts & Data (LOW)
- `chart-type` - Match chart type to data type (trend → line, comparison → bar, proportion → pie/donut)
- `color-guidance` - Use accessible color palettes; avoid red/green only pairs for colorblind users (WCAG, MD)
- `data-table` - Provide table alternative for accessibility; charts alone are not screen-reader friendly (WCAG)
- `pattern-texture` - Supplement color with patterns, textures, or shapes so data is distinguishable without color (WCAG, MD)
- `legend-visible` - Always show legend; position near the chart, not detached below a scroll fold (MD)
- `tooltip-on-interact` - Provide tooltips/data labels on hover (Web) or tap (mobile) showing exact values (HIG, MD)
- `axis-labels` - Label axes with units and readable scale; avoid truncated or rotated labels on mobile
- `responsive-chart` - Charts must reflow or simplify on small screens (e.g. horizontal bar instead of vertical, fewer ticks)
- `empty-data-state` - Show meaningful empty state when no data exists ("No data yet" + guidance), not a blank chart (MD)
- `loading-chart` - Use skeleton or shimmer placeholder while chart data loads; don't show an empty axis frame
- `animation-optional` - Chart entrance animations must respect prefers-reduced-motion; data should be readable immediately (HIG)
- `large-dataset` - For 1000+ data points, aggregate or sample; provide drill-down for detail instead of rendering all (MD)
- `number-formatting` - Use locale-aware formatting for numbers, dates, currencies on axes and labels (HIG, MD)
- `touch-target-chart` - Interactive chart elements (points, segments) must have ≥44pt tap area or expand on touch (Apple HIG)
- `no-pie-overuse` - Avoid pie/donut for >5 categories; switch to bar chart for clarity
- `contrast-data` - Data lines/bars vs background ≥3:1; data text labels ≥4.5:1 (WCAG)
- `legend-interactive` - Legends should be clickable to toggle series visibility (MD)
- `direct-labeling` - For small datasets, label values directly on the chart to reduce eye travel
- `tooltip-keyboard` - Tooltip content must be keyboard-reachable and not rely on hover alone (WCAG)
- `sortable-table` - Data tables must support sorting with aria-sort indicating current sort state (WCAG)
- `axis-readability` - Axis ticks must not be cramped; maintain readable spacing, auto-skip on small screens
- `data-density` - Limit information density per chart to avoid cognitive overload; split into multiple charts if needed
- `trend-emphasis` - Emphasize data trends over decoration; avoid heavy gradients/shadows that obscure the data
- `gridline-subtle` - Grid lines should be low-contrast (e.g. gray-200) so they don't compete with data
- `focusable-elements` - Interactive chart elements (points, bars, slices) must be keyboard-navigable (WCAG)
- `screen-reader-summary` - Provide a text summary or aria-label describing the chart's key insight for screen readers (WCAG)
- `error-state-chart` - Data load failure must show error message with retry action, not a broken/empty chart
- `export-option` - For data-heavy products, offer CSV/image export of chart data
- `drill-down-consistency` - Drill-down interactions must maintain a clear back-path and hierarchy breadcrumb
- `time-scale-clarity` - Time series charts must clearly label time granularity (day/week/month) and allow switching
## How to Use
Search specific domains using the CLI tool below.
For the full rule list per category (all ~98 UX guidelines with rationale), read `references/quick-reference.md`. For app-specific polish rules (icons, touch feedback, dark mode contrast, safe areas) and the canonical pre-delivery checklist, read `references/pro-rules.md`.
---
## Prerequisites
## Running the search tool
The bundled scripts require Python 3 (standard library only — no third-party packages, no network access). Check if it is available:
The search script lives inside this skill's own directory, not the project directory. Always invoke it by its full path — do not assume a particular working directory:
```bash
python3 --version || python --version
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --domain <domain>
```
If Python is not installed, **do not install it yourself**. Stop and ask the user to install Python 3 using their preferred method (e.g. from [python.org](https://www.python.org/downloads/) or their OS package manager), then continue once it is available. Never run package-manager or system-modifying commands (`sudo`, `brew`, `apt`, `winget`, etc.) on the user's machine for this skill.
If `python` is not found, try `python3`, then `py -3`. Requires Python 3.x, no external dependencies (see README for install instructions if Python is missing).
If the user prefers not to install Python, skip the CLI searches and rely on the Quick Reference sections above.
> **Note:** On Windows, use `python` instead of `python3` to run scripts (e.g., `python scripts/search.py` instead of `python3 scripts/search.py`).
---
## How to Use This Skill
Use this skill when the user requests any of the following:
| Scenario | Trigger Examples | Start From |
|----------|-----------------|------------|
| **New project / page** | "Build a landing page", "Build a dashboard" | Step 1 → Step 2 (design system) |
| **New component** | "Create a pricing card", "Add a modal" | Step 3 (domain search: style, ux) |
| **Choose style / color / font** | "What style fits a fintech app?", "Recommend a color palette" | Step 2 (design system) |
| **Review existing UI** | "Review this page for UX issues", "Check accessibility" | Quick Reference checklist above |
| **Fix a UI bug** | "Button hover is broken", "Layout shifts on load" | Quick Reference → relevant section |
| **Improve / optimize** | "Make this faster", "Improve mobile experience" | Step 3 (domain search: ux, react) |
| **Implement dark mode** | "Add dark mode support" | Step 3 (domain: style "dark mode") |
| **Add charts / data viz** | "Add an analytics dashboard chart" | Step 3 (domain: chart) |
| **Stack best practices** | "React performance tips"、"SwiftUI navigation" | Step 4 (stack search) |
Follow this workflow:
## Workflow
### Step 1: Analyze User Requirements
Extract key information from user request:
- **Product type**: Entertainment (social, video, music, gaming), Tool (scanner, editor, converter), Productivity (task manager, notes, calendar), or hybrid
- **Target audience**: C-end consumer users; consider age group, usage context (commute, leisure, work)
Extract from the user request:
- **Product type**: SaaS, e-commerce, portfolio, dashboard, entertainment, tool, productivity, or hybrid
- **Target audience & context**: age group, usage context (commute, leisure, work)
- **Style keywords**: playful, vibrant, minimal, dark mode, content-first, immersive, etc.
- **Stack**: Match the project's framework. The engine ships guidance for many stacks (see [Available Stacks](#available-stacks) below) — pass the matching `--stack` (e.g. `nextjs`, `react`, `shadcn`, `vue`, `svelte`, `astro`, `swiftui`, `flutter`, `react-native`).
- **Stack**: detect from the project — check `package.json` deps (react/next/vue/svelte/nuxt/@angular), `pubspec.yaml` (Flutter), `*.xcodeproj`/`Package.swift` (SwiftUI), `composer.json` (Laravel), or React Native markers (`app.json` + `react-native` dep). If nothing is detectable, ask the user or default to `html-tailwind`. **Never assume a stack** — a hardcoded default silently misroutes every recommendation.
### Step 2: Generate Design System (REQUIRED)
### Step 2: Generate Design System (REQUIRED for new pages/projects)
**Always start with `--design-system`** to get comprehensive recommendations with reasoning:
Always start with `--design-system` to get comprehensive recommendations with reasoning:
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<product_type> <industry> <keywords>" --design-system [-p "Project Name"]
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<product_type> <industry> <keywords>" --design-system [-p "Project Name"]
```
This command:
1. Searches domains in parallel (product, style, color, landing, typography)
2. Applies reasoning rules from `ui-reasoning.csv` to select best matches
3. Returns complete design system: pattern, style, colors, typography, effects
4. Includes anti-patterns to avoid
This searches product/style/color/landing/typography domains in parallel, applies reasoning rules from `ui-reasoning.csv`, and returns pattern, style, colors, typography, effects, and anti-patterns to avoid.
**Example:**
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --design-system -p "Serenity Spa"
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "beauty spa wellness service" --design-system -p "Serenity Spa"
```
### Step 2b: Persist Design System (Master + Overrides Pattern)
To save the design system for **hierarchical retrieval across sessions**, add `--persist`:
To save the design system for retrieval across sessions, add `--persist` **and always pass `--output-dir` pointed at the project root** — without it, files are written relative to whatever directory the tool happens to run from:
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --persist -p "Project Name"
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --design-system --persist -p "Project Name" --output-dir "<project-root>"
```
This creates:
- `design-system/MASTER.md` — Global Source of Truth with all design rules
- `design-system/pages/` — Folder for page-specific overrides
- `design-system/<project-slug>/MASTER.md` — Global Source of Truth
- `design-system/<project-slug>/pages/` — Folder for page-specific overrides
**With page-specific override:**
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --persist -p "Project Name" --page "dashboard"
```
With a page-specific override, add `--page "dashboard"` to also create `design-system/<project-slug>/pages/dashboard.md`.
This also creates:
- `design-system/pages/dashboard.md` — Page-specific deviations from Master
If `design-system/<project-slug>/MASTER.md` already exists, `--persist` **skips writing and leaves it untouched** unless you also pass `--force` — check whether it exists first (and read it) before regenerating, so you don't silently discard prior decisions the user or a teammate made.
**How hierarchical retrieval works:**
1. When building a specific page (e.g., "Checkout"), first check `design-system/pages/checkout.md`
2. If the page file exists, its rules **override** the Master file
3. If not, use `design-system/MASTER.md` exclusively
**Context-aware retrieval prompt:**
```
I am building the [Page Name] page. Please read design-system/MASTER.md.
Also check if design-system/pages/[page-name].md exists.
If the page file exists, prioritize its rules.
If not, use the Master rules exclusively.
Now, generate the code...
```
**Retrieval when building a specific page:**
1. Read `design-system/<project-slug>/MASTER.md`
2. Check if `design-system/<project-slug>/pages/<page-name>.md` exists — if so, its rules override Master
3. Otherwise use Master rules exclusively
### Step 2c: Design Dials (optional)
Three optional 1-10 sliders that tune `--design-system` output without changing your query. Add any combination of them to the same command:
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --variance <1-10> --motion <1-10> --density <1-10>
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --design-system --variance <1-10> --motion <1-10> --density <1-10>
```
| Dial | Low (1-3) | Mid (4-7) | High (8-10) |
@ -420,272 +110,87 @@ python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --varia
**Example:**
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "internal analytics dashboard" --design-system --variance 8 --motion 7 --density 8 -p "Ops Console"
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "internal analytics dashboard" --design-system --variance 8 --motion 7 --density 8 -p "Ops Console"
```
### Step 3: Supplement with Detailed Searches (as needed)
After getting the design system, use domain searches to get additional details:
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<keyword>" --domain <domain> [-n <max_results>]
```
**When to use detailed searches:**
| Need | Domain | Example |
|------|--------|---------|
| Product type patterns | `product` | `--domain product "entertainment social"` |
| More style options | `style` | `--domain style "glassmorphism dark"` |
| Color palettes | `color` | `--domain color "entertainment vibrant"` |
| Font pairings | `typography` | `--domain typography "playful modern"` |
| Individual Google Fonts | `google-fonts` | `--domain google-fonts "sans serif popular variable"` |
| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` |
| UX best practices | `ux` | `--domain ux "animation accessibility"` |
| Alternative fonts | `typography` | `--domain typography "elegant luxury"` |
| Individual Google Fonts | `google-fonts` | `--domain google-fonts "sans serif popular variable"` |
| Landing structure | `landing` | `--domain landing "hero social-proof"` |
| React Native perf | `react` | `--domain react "rerender memo list"` |
| App interface a11y | `web` | `--domain web "accessibilityLabel touch safe-areas"` |
| AI prompt / CSS keywords | `prompt` | `--domain prompt "minimalism"` |
| Landing page structure | `landing` | `--domain landing "hero social-proof"` |
| Icon recommendations | `icons` | `--domain icons "navigation outline"` |
| GSAP animation presets | `gsap` | `--domain gsap "scroll reveal stagger"` |
| React/Next.js performance | `react` | `--domain react "rerender memo list"` |
| App/native interface guidelines | `web` | `--domain web "accessibilityLabel touch safe-areas"` |
### Step 4: Stack Guidelines (match your framework)
Get implementation-specific best practices for the stack you're building in.
Pass the `--stack` that matches the project's framework:
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack <your-stack>
# e.g. --stack nextjs | react | shadcn | vue | svelte | astro | swiftui | flutter | react-native
```
---
## Search Reference
### Available Domains
| Domain | Use For | Example Keywords |
|--------|---------|------------------|
| `product` | Product type recommendations | SaaS, e-commerce, portfolio, healthcare, beauty, service |
| `style` | UI styles, colors, effects | glassmorphism, minimalism, dark mode, brutalism |
| `typography` | Font pairings, Google Fonts | elegant, playful, professional, modern |
| `color` | Color palettes by product type | saas, ecommerce, healthcare, beauty, fintech, service |
| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof |
| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie |
| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading |
| `gsap` | GSAP animation skeletons by intensity tier | scroll reveal, stagger, magnetic cursor, page transition |
| `google-fonts` | Individual Google Fonts lookup | sans serif, monospace, japanese, variable font, popular |
| `react` | React/Next.js performance | waterfall, bundle, suspense, memo, rerender, cache |
| `web` | App interface guidelines (iOS/Android/React Native) | accessibilityLabel, touch targets, safe areas, Dynamic Type |
| `prompt` | AI prompts, CSS keywords | (style name) |
### Available Stacks
Run `ls <skill>/data/stacks/` to see the live set. Shipped stacks:
| Stack | Focus |
|-------|-------|
| `react` | Components, hooks, render performance |
| `nextjs` | App Router, RSC, Server Actions, rendering |
| `vue` | Components, Composition API, reactivity |
| `nuxtjs` | Nuxt app patterns, SSR data fetching |
| `nuxt-ui` | Nuxt UI component patterns |
| `svelte` | Components, stores, transitions |
| `astro` | Islands, content, partial hydration |
| `shadcn` | shadcn/ui primitives, composition |
| `html-tailwind` | Tailwind utility patterns |
| `angular` | Components, signals, services |
| `laravel` | Blade / server-rendered UI patterns |
| `swiftui` | Views, state, navigation (iOS/macOS) |
| `flutter` | Widgets, state, navigation |
| `jetpack-compose` | Composables, state, navigation (Android) |
| `react-native` | Components, Navigation, Lists |
| `threejs` | 3D scenes, materials, performance |
---
## Example Workflow
**User request:** "Make an AI search homepage."
### Step 1: Analyze Requirements
- Product type: Tool (AI search engine)
- Target audience: C-end users looking for fast, intelligent search
- Style keywords: modern, minimal, content-first, dark mode
- Stack: Next.js (a homepage is a web surface; use a web `--stack`)
### Step 2: Generate Design System (REQUIRED)
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "AI search tool modern minimal" --design-system -p "AI Search"
```
**Output:** Complete design system with pattern, style, colors, typography, effects, and anti-patterns.
### Step 3: Supplement with Detailed Searches (as needed)
```bash
# Get style options for a modern tool product
python3 skills/ui-ux-pro-max/scripts/search.py "minimalism dark mode" --domain style
# Get UX best practices for search interaction and loading
python3 skills/ui-ux-pro-max/scripts/search.py "search loading animation" --domain ux
```
Domain is auto-detected from the query if `--domain` is omitted — but auto-detection can misroute overlapping terms (e.g. "font" matches both `typography` and `google-fonts`). If results look off-topic, pass `--domain` explicitly.
### Step 4: Stack Guidelines
```bash
python3 skills/ui-ux-pro-max/scripts/search.py "list performance navigation" --stack nextjs
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<keyword>" --stack <stack>
```
**Then:** Synthesize design system + detailed searches and implement the design.
**Available stacks:** `react`, `nextjs`, `vue`, `svelte`, `astro`, `nuxtjs`, `nuxt-ui`, `angular`, `laravel`, `swiftui`, `react-native`, `flutter`, `jetpack-compose`, `html-tailwind`, `shadcn`, `threejs`, `javafx`, `wpf`, `winui`, `avalonia`, `uno`, `uwp`. Use the stack detected in Step 1.
---
## If a search returns 0 results
Do not fabricate output. Instead:
1. Retry once with broader or differently-worded keywords (try product + style separately rather than combined).
2. If still empty, fall back to the priority table above and say explicitly to the user that this recommendation came from the built-in defaults, not a database match (e.g. "no palette match for X, using general SaaS defaults").
3. Never present a 0-result search as if it returned data.
## Example Workflow
**User request:** "Make an AI search homepage." (stack detected as Next.js from `package.json`)
```bash
# Step 2: design system
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "AI search tool modern minimal" --design-system -p "AI Search"
# Step 3: supplement
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "search loading animation" --domain ux
# Step 4: stack guidelines
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "suspense streaming bundle" --stack nextjs
```
Then synthesize the design system + detailed searches and implement.
## Output Formats
The `--design-system` flag supports two output formats:
```bash
# ASCII box (default) - best for terminal display
python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system
# Markdown - best for documentation
python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system -f markdown
```
---
`--design-system` supports `-f ascii` (default, terminal display), `-f markdown` (documentation), and `--json` (machine-readable, includes the raw design system dict plus persistence status).
## Tips for Better Results
### Query Strategy
- Use **multi-dimensional keywords** — combine product + industry + tone + density: `"entertainment social vibrant content-dense"` not just `"app"`
- Try different keywords for the same need: `"playful neon"``"vibrant dark"``"content-first minimal"`
- Use **multi-dimensional keywords** — combine product + industry + tone + density: `"entertainment social vibrant content-dense"`, not just `"app"`
- Try different phrasings for the same need: `"playful neon"``"vibrant dark"``"content-first minimal"`
- Use `--design-system` first for full recommendations, then `--domain` to deep-dive any dimension you're unsure about
- Add the `--stack` that matches the project's framework for implementation-specific guidance
### Common Sticking Points
- Pass the detected stack explicitly for implementation-specific guidance
| Problem | What to Do |
|---------|------------|
| Can't decide on style/color | Re-run `--design-system` with different keywords |
| Dark mode contrast issues | Quick Reference §6: `color-dark-mode` + `color-accessible-pairs` |
| Animations feel unnatural | Quick Reference §7: `spring-physics` + `easing` + `exit-faster-than-enter` |
| Form UX is poor | Quick Reference §8: `inline-validation` + `error-clarity` + `focus-management` |
| Navigation feels confusing | Quick Reference §9: `nav-hierarchy` + `bottom-nav-limit` + `back-behavior` |
| Layout breaks on small screens | Quick Reference §5: `mobile-first` + `breakpoint-consistency` |
| Performance / jank | Quick Reference §3: `virtualize-lists` + `main-thread-budget` + `debounce-throttle` |
| Dark mode contrast issues | `references/quick-reference.md` §6: `color-dark-mode` + `color-accessible-pairs` |
| Animations feel unnatural | `references/quick-reference.md` §7: `spring-physics` + `easing` + `exit-faster-than-enter` |
| Form UX is poor | `references/quick-reference.md` §8: `inline-validation` + `error-clarity` + `focus-management` |
| Navigation feels confusing | `references/quick-reference.md` §9: `nav-hierarchy` + `bottom-nav-limit` + `back-behavior` |
| Layout breaks on small screens | `references/quick-reference.md` §5: `mobile-first` + `breakpoint-consistency` |
| Performance / jank | `references/quick-reference.md` §3: `virtualize-lists` + `main-thread-budget` + `debounce-throttle` |
### Pre-Delivery Checklist
## Before Delivering App UI
- Run `--domain ux "animation accessibility z-index loading"` as a UX validation pass before implementation
- Run through Quick Reference **§1§3** (CRITICAL + HIGH) as a final review
- Test on 375px (small phone) and landscape orientation
- Verify behavior with **reduced-motion** enabled and **Dynamic Type** at largest size
- Check dark mode contrast independently (don't assume light mode values work)
- Confirm all touch targets ≥44pt and no content hidden behind safe areas
---
## Common Rules for Professional UI
These are frequently overlooked issues that make UI look unprofessional:
Scope notice: The rules below are for App UI (iOS/Android/React Native/Flutter), not desktop-web interaction patterns.
### Icons & Visual Elements
| Rule | Standard | Avoid | Why It Matters |
|------|----------|--------|----------------|
| **No Emoji as Structural Icons** | Use vector-based icons (e.g., Lucide, react-native-vector-icons, @expo/vector-icons). | Using emojis (🎨 🚀 ⚙️) for navigation, settings, or system controls. | Emojis are font-dependent, inconsistent across platforms, and cannot be controlled via design tokens. |
| **Vector-Only Assets** | Use SVG or platform vector icons that scale cleanly and support theming. | Raster PNG icons that blur or pixelate. | Ensures scalability, crisp rendering, and dark/light mode adaptability. |
| **Stable Interaction States** | Use color, opacity, or elevation transitions for press states without changing layout bounds. | Layout-shifting transforms that move surrounding content or trigger visual jitter. | Prevents unstable interactions and preserves smooth motion/perceived quality on mobile. |
| **Correct Brand Logos** | Use official brand assets and follow their usage guidelines (spacing, color, clear space). | Guessing logo paths, recoloring unofficially, or modifying proportions. | Prevents brand misuse and ensures legal/platform compliance. |
| **Consistent Icon Sizing** | Define icon sizes as design tokens (e.g., icon-sm, icon-md = 24pt, icon-lg). | Mixing arbitrary values like 20pt / 24pt / 28pt randomly. | Maintains rhythm and visual hierarchy across the interface. |
| **Stroke Consistency** | Use a consistent stroke width within the same visual layer (e.g., 1.5px or 2px). | Mixing thick and thin stroke styles arbitrarily. | Inconsistent strokes reduce perceived polish and cohesion. |
| **Filled vs Outline Discipline** | Use one icon style per hierarchy level. | Mixing filled and outline icons at the same hierarchy level. | Maintains semantic clarity and stylistic coherence. |
| **Touch Target Minimum** | Minimum 44×44pt interactive area (use hitSlop if icon is smaller). | Small icons without expanded tap area. | Meets accessibility and platform usability standards. |
| **Icon Alignment** | Align icons to text baseline and maintain consistent padding. | Misaligned icons or inconsistent spacing around them. | Prevents subtle visual imbalance that reduces perceived quality. |
| **Icon Contrast** | Follow WCAG contrast standards: 4.5:1 for small elements, 3:1 minimum for larger UI glyphs. | Low-contrast icons that blend into the background. | Ensures accessibility in both light and dark modes. |
### Interaction (App)
| Rule | Do | Don't |
|------|----|----- |
| **Tap feedback** | Provide clear pressed feedback (ripple/opacity/elevation) within 80-150ms | No visual response on tap |
| **Animation timing** | Keep micro-interactions around 150-300ms with platform-native easing | Instant transitions or slow animations (>500ms) |
| **Accessibility focus** | Ensure screen reader focus order matches visual order and labels are descriptive | Unlabeled controls or confusing focus traversal |
| **Disabled state clarity** | Use disabled semantics (`disabled`/native disabled props), reduced emphasis, and no tap action | Controls that look tappable but do nothing |
| **Touch target minimum** | Keep tap areas >=44x44pt (iOS) or >=48x48dp (Android), expand hit area when icon is smaller | Tiny tap targets or icon-only hit areas without padding |
| **Gesture conflict prevention** | Keep one primary gesture per region and avoid nested tap/drag conflicts | Overlapping gestures causing accidental actions |
| **Semantic native controls** | Prefer native interactive primitives (`Button`, `Pressable`, platform equivalents) with proper accessibility roles | Generic containers used as primary controls without semantics |
### Light/Dark Mode Contrast
| Rule | Do | Don't |
|------|----|----- |
| **Surface readability (light)** | Keep cards/surfaces clearly separated from background with sufficient opacity/elevation | Overly transparent surfaces that blur hierarchy |
| **Text contrast (light)** | Maintain body text contrast >=4.5:1 against light surfaces | Low-contrast gray body text |
| **Text contrast (dark)** | Maintain primary text contrast >=4.5:1 and secondary text >=3:1 on dark surfaces | Dark mode text that blends into background |
| **Border and divider visibility** | Ensure separators are visible in both themes (not just light mode) | Theme-specific borders disappearing in one mode |
| **State contrast parity** | Keep pressed/focused/disabled states equally distinguishable in light and dark themes | Defining interaction states for one theme only |
| **Token-driven theming** | Use semantic color tokens mapped per theme across app surfaces/text/icons | Hardcoded per-screen hex values |
| **Scrim and modal legibility** | Use a modal scrim strong enough to isolate foreground content (typically 40-60% black) | Weak scrim that leaves background visually competing |
### Layout & Spacing
| Rule | Do | Don't |
|------|----|----- |
| **Safe-area compliance** | Respect top/bottom safe areas for all fixed headers, tab bars, and CTA bars | Placing fixed UI under notch, status bar, or gesture area |
| **System bar clearance** | Add spacing for status/navigation bars and gesture home indicator | Let tappable content collide with OS chrome |
| **Consistent content width** | Keep predictable content width per device class (phone/tablet) | Mixing arbitrary widths between screens |
| **8dp spacing rhythm** | Use a consistent 4/8dp spacing system for padding/gaps/section spacing | Random spacing increments with no rhythm |
| **Readable text measure** | Keep long-form text readable on large devices (avoid edge-to-edge paragraphs on tablets) | Full-width long text that hurts readability |
| **Section spacing hierarchy** | Define clear vertical rhythm tiers (e.g., 16/24/32/48) by hierarchy | Similar UI levels with inconsistent spacing |
| **Adaptive gutters by breakpoint** | Increase horizontal insets on larger widths and in landscape | Same narrow gutter on all device sizes/orientations |
| **Scroll and fixed element coexistence** | Add bottom/top content insets so lists are not hidden behind fixed bars | Scroll content obscured by sticky headers/footers |
---
## Pre-Delivery Checklist
Before delivering UI code, verify these items:
Scope notice: This checklist is for App UI (iOS/Android/React Native/Flutter).
### Visual Quality
- [ ] No emojis used as icons (use SVG instead)
- [ ] All icons come from a consistent icon family and style
- [ ] Official brand assets are used with correct proportions and clear space
- [ ] Pressed-state visuals do not shift layout bounds or cause jitter
- [ ] Semantic theme tokens are used consistently (no ad-hoc per-screen hardcoded colors)
### Interaction
- [ ] All tappable elements provide clear pressed feedback (ripple/opacity/elevation)
- [ ] Touch targets meet minimum size (>=44x44pt iOS, >=48x48dp Android)
- [ ] Micro-interaction timing stays in the 150-300ms range with native-feeling easing
- [ ] Disabled states are visually clear and non-interactive
- [ ] Screen reader focus order matches visual order, and interactive labels are descriptive
- [ ] Gesture regions avoid nested/conflicting interactions (tap/drag/back-swipe conflicts)
### Light/Dark Mode
- [ ] Primary text contrast >=4.5:1 in both light and dark mode
- [ ] Secondary text contrast >=3:1 in both light and dark mode
- [ ] Dividers/borders and interaction states are distinguishable in both modes
- [ ] Modal/drawer scrim opacity is strong enough to preserve foreground legibility (typically 40-60% black)
- [ ] Both themes are tested before delivery (not inferred from a single theme)
### Layout
- [ ] Safe areas are respected for headers, tab bars, and bottom CTA bars
- [ ] Scroll content is not hidden behind fixed/sticky bars
- [ ] Verified on small phone, large phone, and tablet (portrait + landscape)
- [ ] Horizontal insets/gutters adapt correctly by device size and orientation
- [ ] 4/8dp spacing rhythm is maintained across component, section, and page levels
- [ ] Long-form text measure remains readable on larger devices (no edge-to-edge paragraphs)
### Accessibility
- [ ] All meaningful images/icons have accessibility labels
- [ ] Form fields have labels, hints, and clear error messages
- [ ] Color is not the only indicator
- [ ] Reduced motion and dynamic text size are supported without layout breakage
- [ ] Accessibility traits/roles/states (selected, disabled, expanded) are announced correctly
Read `references/pro-rules.md` and run through its canonical Pre-Delivery Checklist. It covers icon/visual-element discipline, interaction feedback, light/dark contrast, safe-area layout, and accessibility — scoped to native/mobile app UI (iOS/Android/React Native/Flutter).

View File

@ -159,4 +159,35 @@ No,Product Type,Primary,On Primary,Secondary,On Secondary,Accent,On Accent,Backg
158,Emergency SOS & Safety,#DC2626,#FFFFFF,#EF4444,#FFFFFF,#2563EB,#FFFFFF,#FFF1F2,#0F172A,#FFFFFF,#0F172A,#FCF1F1,#64748B,#FAE4E4,#DC2626,#FFFFFF,#DC2626,Alert red + safety blue
159,Wallpaper & Theme App,#7C3AED,#FFFFFF,#EC4899,#FFFFFF,#2563EB,#FFFFFF,#FAF5FF,#0F172A,#FFFFFF,#0F172A,#F7F3FD,#64748B,#EFE7FC,#DC2626,#FFFFFF,#7C3AED,Aesthetic purple + trending pink
160,White Noise & Ambient Sound,#475569,#FFFFFF,#334155,#FFFFFF,#4338CA,#FFFFFF,#0F172A,#FFFFFF,#192134,#FFFFFF,#131B2F,#94A3B8,"rgba(255,255,255,0.08)",#DC2626,#FFFFFF,#475569,Ambient grey + deep indigo on dark
161,Home Decoration & Interior Design,#78716C,#FFFFFF,#A8A29E,#FFFFFF,#D97706,#FFFFFF,#FAF5F2,#0F172A,#FFFFFF,#0F172A,#F6F6F6,#64748B,#EEEDED,#DC2626,#FFFFFF,#78716C,Interior warm grey + gold accent
161,Home Decoration & Interior Design,#78716C,#FFFFFF,#A8A29E,#FFFFFF,#D97706,#FFFFFF,#FAF5F2,#0F172A,#FFFFFF,#0F172A,#F6F6F6,#64748B,#EEEDED,#DC2626,#FFFFFF,#78716C,Interior warm grey + gold accent
162,Academic Journal / Scholarly Publishing,#1E3A5F,#FFFFFF,#334155,#FFFFFF,#B45309,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Scholarly navy + citation gold + serif accent
163,API Developer Portal,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#22C55E,#0F172A,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#EF4444,#FFFFFF,#0F172A,Code dark + endpoint green + syntax colors
164,Forum / Discussion Board,#475569,#FFFFFF,#64748B,#FFFFFF,#2563EB,#FFFFFF,#F8FAFC,#1E293B,#FFFFFF,#1E293B,#EAEFF3,#64748B,#E2E8F0,#DC2626,#FFFFFF,#475569,Neutral grey + topic accent + unread indicator
165,Directory / Listing Site,#059669,#FFFFFF,#10B981,#0F172A,#D97706,#FFFFFF,#ECFDF5,#064E3B,#FFFFFF,#064E3B,#E8F1F3,#64748B,#A7F3D0,#DC2626,#FFFFFF,#059669,Category green + verified badge + map accent
166,Status Page / Incident Management,#16A34A,#FFFFFF,#22C55E,#0F172A,#DC2626,#FFFFFF,#F0FDF4,#14532D,#FFFFFF,#14532D,#E8F0F1,#64748B,#BBF7D0,#DC2626,#FFFFFF,#16A34A,Operational green + incident red + maintenance amber
167,Wiki / Encyclopedia,#1E3A8A,#FFFFFF,#3B82F6,#FFFFFF,#7C3AED,#FFFFFF,#F8FAFC,#1E40AF,#FFFFFF,#1E40AF,#E9EEF5,#64748B,#BFDBFE,#DC2626,#FFFFFF,#1E3A8A,Knowledge blue + link purple + clean white
168,Auction Platform,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#16A34A,#0F172A,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#DC2626,#FFFFFF,#0F172A,Dark luxury + bid green + outbid red + urgency
169,Changelog / Release Notes,#475569,#FFFFFF,#64748B,#FFFFFF,#059669,#FFFFFF,#F8FAFC,#1E293B,#FFFFFF,#1E293B,#EAEFF3,#64748B,#E2E8F0,#DC2626,#FFFFFF,#475569,Feature green + fix blue + breaking red badges
170,Citizen Science Platform,#15803D,#FFFFFF,#22C55E,#0F172A,#D97706,#FFFFFF,#F0FDF4,#14532D,#FFFFFF,#14532D,#E8F0F1,#64748B,#BBF7D0,#DC2626,#FFFFFF,#15803D,Discovery green + volunteer badge + data neutral
171,Classifieds / Buy-Sell,#2563EB,#FFFFFF,#3B82F6,#FFFFFF,#16A34A,#FFFFFF,#EFF6FF,#1E40AF,#FFFFFF,#1E40AF,#E9EFF8,#64748B,#BFDBFE,#DC2626,#FFFFFF,#2563EB,Listing blue + price green + seller badge
172,Conference / Symposium Landing Page,#1E3A5F,#FFFFFF,#2563EB,#FFFFFF,#A16207,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Academic navy + gold keynote + track chips
173,Crowdfunding Platform,#D97706,#FFFFFF,#F59E0B,#0F172A,#16A34A,#FFFFFF,#FFFBEB,#0F172A,#FFFFFF,#0F172A,#FCF6F0,#64748B,#FAEEE1,#DC2626,#FFFFFF,#D97706,Funding progress amber + goal green + urgency
174,Digital Signage / Kiosk,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#EF4444,#FFFFFF,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#EF4444,#FFFFFF,#0F172A,High contrast dark + brand accent + large touch targets
175,E-signature / Document Workflow,#1E3A5F,#FFFFFF,#2563EB,#FFFFFF,#16A34A,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Trust navy + signature green + audit trail
176,Feature Flag / Config Management,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#16A34A,#0F172A,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#DC2626,#FFFFFF,#0F172A,Enabled green + disabled grey + experimental amber
177,Government Portal / Civic Services,#1E40AF,#FFFFFF,#3B82F6,#FFFFFF,#16A34A,#FFFFFF,#EFF6FF,#1E3A8A,#FFFFFF,#1E3A8A,#E9EFF5,#64748B,#BFDBFE,#DC2626,#FFFFFF,#1E40AF,Professional blue + service green + accessibility
178,Grant / Funding Portal,#1E3A5F,#FFFFFF,#2563EB,#FFFFFF,#16A34A,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Institution navy + funding green + deadline urgency
179,LMS (Learning Management System),#0D9488,#FFFFFF,#2DD4BF,#0F172A,#D97706,#FFFFFF,#F0FDFA,#134E4A,#FFFFFF,#134E4A,#E8F1F4,#64748B,#5EEAD4,#DC2626,#FFFFFF,#0D9488,Education teal + course amber + grade green
180,No-code / Low-code Builder,#7C3AED,#FFFFFF,#A78BFA,#0F172A,#EC4899,#FFFFFF,#FAF5FF,#4C1D95,#FFFFFF,#4C1D95,#ECEEF9,#64748B,#DDD6FE,#DC2626,#FFFFFF,#7C3AED,Builder purple + component pink + canvas neutral
181,Open Source Project Landing,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#A16207,#FFFFFF,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#22C55E,#FFFFFF,#0F172A,Dark code + star gold + fork silver + sponsor purple
182,Patient Portal / Health Records,#0284C7,#FFFFFF,#0891B2,#FFFFFF,#16A34A,#FFFFFF,#F0F9FF,#0C4A6E,#FFFFFF,#0C4A6E,#E8F2F8,#64748B,#BAE6FD,#DC2626,#FFFFFF,#0284C7,Clinical blue + health green + alert red
183,Patent / IP Database,#475569,#FFFFFF,#64748B,#FFFFFF,#A16207,#FFFFFF,#F8FAFC,#1E293B,#FFFFFF,#1E293B,#EAEFF3,#64748B,#E2E8F0,#DC2626,#FFFFFF,#475569,Formal neutral + patent type chips + status badges
184,Q&A Community Platform,#2563EB,#FFFFFF,#0891B2,#FFFFFF,#D97706,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#F1F5FD,#64748B,#E4ECFC,#DC2626,#FFFFFF,#2563EB,Knowledge blue + accepted green + reputation gold
185,Research Lab / University Department,#1E3A5F,#FFFFFF,#2563EB,#FFFFFF,#A16207,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Institutional navy + research accent + serif headings
186,Resume / CV Builder,#1E3A5F,#FFFFFF,#2563EB,#FFFFFF,#16A34A,#FFFFFF,#F8FAFC,#0F172A,#FFFFFF,#0F172A,#E9EEF5,#64748B,#CBD5E1,#DC2626,#FFFFFF,#1E3A5F,Professional navy + section accent + success green
187,Review Platform,#F59E0B,#0F172A,#FBBF24,#0F172A,#16A34A,#FFFFFF,#FFFBEB,#0F172A,#FFFFFF,#0F172A,#FCF6F0,#64748B,#FAEEE1,#DC2626,#FFFFFF,#F59E0B,Star gold + positive green + negative red
188,RPA / Automation Dashboard,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#16A34A,#0F172A,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#DC2626,#FFFFFF,#0F172A,Dark terminal + running green + failed red + queued amber
189,Survey / Form Builder,#0D9488,#FFFFFF,#2DD4BF,#0F172A,#D97706,#FFFFFF,#F0FDFA,#134E4A,#FFFFFF,#134E4A,#E8F1F4,#64748B,#5EEAD4,#DC2626,#FFFFFF,#0D9488,Question teal + progress green + submit blue
190,Telemedicine Platform,#0891B2,#FFFFFF,#22D3EE,#0F172A,#16A34A,#FFFFFF,#F0FDFA,#134E4A,#FFFFFF,#134E4A,#E8F1F6,#64748B,#CCFBF1,#DC2626,#FFFFFF,#0891B2,Medical teal + video green + waiting amber
191,Testimonial & Social Proof Widget,#7C3AED,#FFFFFF,#A78BFA,#0F172A,#F59E0B,#0F172A,#FAF5FF,#4C1D95,#FFFFFF,#4C1D95,#ECEEF9,#64748B,#DDD6FE,#DC2626,#FFFFFF,#7C3AED,Trust purple + quote gold + verified blue
192,Ticketing / Box Office,#0F172A,#FFFFFF,#1E293B,#FFFFFF,#16A34A,#0F172A,#020617,#F8FAFC,#0E1223,#F8FAFC,#1A1E2F,#94A3B8,#334155,#DC2626,#FFFFFF,#0F172A,Event theme colors + available green + sold-out red

1 No Product Type Primary On Primary Secondary On Secondary Accent On Accent Background Foreground Card Card Foreground Muted Muted Foreground Border Destructive On Destructive Ring Notes
159 158 Emergency SOS & Safety #DC2626 #FFFFFF #EF4444 #FFFFFF #2563EB #FFFFFF #FFF1F2 #0F172A #FFFFFF #0F172A #FCF1F1 #64748B #FAE4E4 #DC2626 #FFFFFF #DC2626 Alert red + safety blue
160 159 Wallpaper & Theme App #7C3AED #FFFFFF #EC4899 #FFFFFF #2563EB #FFFFFF #FAF5FF #0F172A #FFFFFF #0F172A #F7F3FD #64748B #EFE7FC #DC2626 #FFFFFF #7C3AED Aesthetic purple + trending pink
161 160 White Noise & Ambient Sound #475569 #FFFFFF #334155 #FFFFFF #4338CA #FFFFFF #0F172A #FFFFFF #192134 #FFFFFF #131B2F #94A3B8 rgba(255,255,255,0.08) #DC2626 #FFFFFF #475569 Ambient grey + deep indigo on dark
162 161 Home Decoration & Interior Design #78716C #FFFFFF #A8A29E #FFFFFF #D97706 #FFFFFF #FAF5F2 #0F172A #FFFFFF #0F172A #F6F6F6 #64748B #EEEDED #DC2626 #FFFFFF #78716C Interior warm grey + gold accent
163 162 Academic Journal / Scholarly Publishing #1E3A5F #FFFFFF #334155 #FFFFFF #B45309 #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Scholarly navy + citation gold + serif accent
164 163 API Developer Portal #0F172A #FFFFFF #1E293B #FFFFFF #22C55E #0F172A #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #EF4444 #FFFFFF #0F172A Code dark + endpoint green + syntax colors
165 164 Forum / Discussion Board #475569 #FFFFFF #64748B #FFFFFF #2563EB #FFFFFF #F8FAFC #1E293B #FFFFFF #1E293B #EAEFF3 #64748B #E2E8F0 #DC2626 #FFFFFF #475569 Neutral grey + topic accent + unread indicator
166 165 Directory / Listing Site #059669 #FFFFFF #10B981 #0F172A #D97706 #FFFFFF #ECFDF5 #064E3B #FFFFFF #064E3B #E8F1F3 #64748B #A7F3D0 #DC2626 #FFFFFF #059669 Category green + verified badge + map accent
167 166 Status Page / Incident Management #16A34A #FFFFFF #22C55E #0F172A #DC2626 #FFFFFF #F0FDF4 #14532D #FFFFFF #14532D #E8F0F1 #64748B #BBF7D0 #DC2626 #FFFFFF #16A34A Operational green + incident red + maintenance amber
168 167 Wiki / Encyclopedia #1E3A8A #FFFFFF #3B82F6 #FFFFFF #7C3AED #FFFFFF #F8FAFC #1E40AF #FFFFFF #1E40AF #E9EEF5 #64748B #BFDBFE #DC2626 #FFFFFF #1E3A8A Knowledge blue + link purple + clean white
169 168 Auction Platform #0F172A #FFFFFF #1E293B #FFFFFF #16A34A #0F172A #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #DC2626 #FFFFFF #0F172A Dark luxury + bid green + outbid red + urgency
170 169 Changelog / Release Notes #475569 #FFFFFF #64748B #FFFFFF #059669 #FFFFFF #F8FAFC #1E293B #FFFFFF #1E293B #EAEFF3 #64748B #E2E8F0 #DC2626 #FFFFFF #475569 Feature green + fix blue + breaking red badges
171 170 Citizen Science Platform #15803D #FFFFFF #22C55E #0F172A #D97706 #FFFFFF #F0FDF4 #14532D #FFFFFF #14532D #E8F0F1 #64748B #BBF7D0 #DC2626 #FFFFFF #15803D Discovery green + volunteer badge + data neutral
172 171 Classifieds / Buy-Sell #2563EB #FFFFFF #3B82F6 #FFFFFF #16A34A #FFFFFF #EFF6FF #1E40AF #FFFFFF #1E40AF #E9EFF8 #64748B #BFDBFE #DC2626 #FFFFFF #2563EB Listing blue + price green + seller badge
173 172 Conference / Symposium Landing Page #1E3A5F #FFFFFF #2563EB #FFFFFF #A16207 #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Academic navy + gold keynote + track chips
174 173 Crowdfunding Platform #D97706 #FFFFFF #F59E0B #0F172A #16A34A #FFFFFF #FFFBEB #0F172A #FFFFFF #0F172A #FCF6F0 #64748B #FAEEE1 #DC2626 #FFFFFF #D97706 Funding progress amber + goal green + urgency
175 174 Digital Signage / Kiosk #0F172A #FFFFFF #1E293B #FFFFFF #EF4444 #FFFFFF #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #EF4444 #FFFFFF #0F172A High contrast dark + brand accent + large touch targets
176 175 E-signature / Document Workflow #1E3A5F #FFFFFF #2563EB #FFFFFF #16A34A #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Trust navy + signature green + audit trail
177 176 Feature Flag / Config Management #0F172A #FFFFFF #1E293B #FFFFFF #16A34A #0F172A #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #DC2626 #FFFFFF #0F172A Enabled green + disabled grey + experimental amber
178 177 Government Portal / Civic Services #1E40AF #FFFFFF #3B82F6 #FFFFFF #16A34A #FFFFFF #EFF6FF #1E3A8A #FFFFFF #1E3A8A #E9EFF5 #64748B #BFDBFE #DC2626 #FFFFFF #1E40AF Professional blue + service green + accessibility
179 178 Grant / Funding Portal #1E3A5F #FFFFFF #2563EB #FFFFFF #16A34A #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Institution navy + funding green + deadline urgency
180 179 LMS (Learning Management System) #0D9488 #FFFFFF #2DD4BF #0F172A #D97706 #FFFFFF #F0FDFA #134E4A #FFFFFF #134E4A #E8F1F4 #64748B #5EEAD4 #DC2626 #FFFFFF #0D9488 Education teal + course amber + grade green
181 180 No-code / Low-code Builder #7C3AED #FFFFFF #A78BFA #0F172A #EC4899 #FFFFFF #FAF5FF #4C1D95 #FFFFFF #4C1D95 #ECEEF9 #64748B #DDD6FE #DC2626 #FFFFFF #7C3AED Builder purple + component pink + canvas neutral
182 181 Open Source Project Landing #0F172A #FFFFFF #1E293B #FFFFFF #A16207 #FFFFFF #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #22C55E #FFFFFF #0F172A Dark code + star gold + fork silver + sponsor purple
183 182 Patient Portal / Health Records #0284C7 #FFFFFF #0891B2 #FFFFFF #16A34A #FFFFFF #F0F9FF #0C4A6E #FFFFFF #0C4A6E #E8F2F8 #64748B #BAE6FD #DC2626 #FFFFFF #0284C7 Clinical blue + health green + alert red
184 183 Patent / IP Database #475569 #FFFFFF #64748B #FFFFFF #A16207 #FFFFFF #F8FAFC #1E293B #FFFFFF #1E293B #EAEFF3 #64748B #E2E8F0 #DC2626 #FFFFFF #475569 Formal neutral + patent type chips + status badges
185 184 Q&A Community Platform #2563EB #FFFFFF #0891B2 #FFFFFF #D97706 #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #F1F5FD #64748B #E4ECFC #DC2626 #FFFFFF #2563EB Knowledge blue + accepted green + reputation gold
186 185 Research Lab / University Department #1E3A5F #FFFFFF #2563EB #FFFFFF #A16207 #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Institutional navy + research accent + serif headings
187 186 Resume / CV Builder #1E3A5F #FFFFFF #2563EB #FFFFFF #16A34A #FFFFFF #F8FAFC #0F172A #FFFFFF #0F172A #E9EEF5 #64748B #CBD5E1 #DC2626 #FFFFFF #1E3A5F Professional navy + section accent + success green
188 187 Review Platform #F59E0B #0F172A #FBBF24 #0F172A #16A34A #FFFFFF #FFFBEB #0F172A #FFFFFF #0F172A #FCF6F0 #64748B #FAEEE1 #DC2626 #FFFFFF #F59E0B Star gold + positive green + negative red
189 188 RPA / Automation Dashboard #0F172A #FFFFFF #1E293B #FFFFFF #16A34A #0F172A #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #DC2626 #FFFFFF #0F172A Dark terminal + running green + failed red + queued amber
190 189 Survey / Form Builder #0D9488 #FFFFFF #2DD4BF #0F172A #D97706 #FFFFFF #F0FDFA #134E4A #FFFFFF #134E4A #E8F1F4 #64748B #5EEAD4 #DC2626 #FFFFFF #0D9488 Question teal + progress green + submit blue
191 190 Telemedicine Platform #0891B2 #FFFFFF #22D3EE #0F172A #16A34A #FFFFFF #F0FDFA #134E4A #FFFFFF #134E4A #E8F1F6 #64748B #CCFBF1 #DC2626 #FFFFFF #0891B2 Medical teal + video green + waiting amber
192 191 Testimonial & Social Proof Widget #7C3AED #FFFFFF #A78BFA #0F172A #F59E0B #0F172A #FAF5FF #4C1D95 #FFFFFF #4C1D95 #ECEEF9 #64748B #DDD6FE #DC2626 #FFFFFF #7C3AED Trust purple + quote gold + verified blue
193 192 Ticketing / Box Office #0F172A #FFFFFF #1E293B #FFFFFF #16A34A #0F172A #020617 #F8FAFC #0E1223 #F8FAFC #1A1E2F #94A3B8 #334155 #DC2626 #FFFFFF #0F172A Event theme colors + available green + sold-out red

View File

@ -1,17 +1,17 @@
No,Category,Intensity Tier,Keywords,Trigger,Duration,Easing,GSAP Snippet,Framework Notes,Do,Don't,Performance Notes
1,Hover Micro-interaction,Subtle,"hover, button, opacity, lift, press feedback",hover,150-200ms,power1.out,"gsap.to(el, { y: -1, opacity: 0.9, duration: 0.15, ease: 'power1.out' });",Bind on mouseenter/mouseleave; in React wrap in a ref + useEffect (or onMouseEnter/onMouseLeave props directly calling gsap.to),Keep displacement under 2px so it reads as feedback not motion,Don't animate layout-affecting props (width/height/margin) on hover,Runs on transform/opacity only so it stays on the compositor thread
2,Hover Micro-interaction,Standard,"hover, card, scale, tilt, cursor feedback",hover,200-300ms,power2.out,"gsap.to(el, { y: -4, scale: 1.02, boxShadow: '0 12px 24px rgba(0,0,0,0.12)', duration: 0.25, ease: 'power2.out' });","Use gsap.quickTo(el, 'y') for cards with many hover targets to avoid re-creating tweens every event",Pair with a matching mouseleave tween that reverses the same properties,Don't leave the hover state stuck if the pointer leaves fast; always attach the reverse tween,quickTo() avoids GC churn on lists with 20+ hoverable cards
3,Hover Micro-interaction,Complex,"hover, magnetic, cursor follow, 3d tilt",hover + mousemove,300-500ms,"elastic.out(1,0.4)","const xTo = gsap.quickTo(el, 'x', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); const yTo = gsap.quickTo(el, 'y', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); el.addEventListener('mousemove', (e) => { const r = el.getBoundingClientRect(); xTo((e.clientX - r.left - r.width/2) * 0.3); yTo((e.clientY - r.top - r.height/2) * 0.3); });",Debounce is not needed since quickTo interpolates; remove listeners on component unmount in React/Vue to avoid leaks,Clamp the pull strength (e.g. * 0.3) so the element never fully leaves its hit box,Don't apply magnetic effect to more than 1-2 focal elements per screen; it becomes noisy,Use will-change: transform on the target element for smoother compositing
4,Scroll Reveal,Subtle,"scroll, fade in, reveal, on view",scroll (viewport enter),300-400ms,power1.out,"gsap.from(el, { opacity: 0, y: 12, duration: 0.35, ease: 'power1.out', scrollTrigger: { trigger: el, start: 'top 90%', toggleActions: 'play none none reverse' } });",Requires the ScrollTrigger plugin registered once via gsap.registerPlugin(ScrollTrigger),"Keep the y offset small (8-16px) so it reads as a fade, not a slide",Don't reveal below-the-fold content needed for SEO/crawlers as invisible-by-default without a no-JS fallback,toggleActions 'play none none reverse' avoids re-triggering on every scroll direction change
5,Scroll Reveal,Standard,"scroll, slide up, staggered section, reveal",scroll (viewport enter),400-600ms,power2.out,"gsap.from(el.children, { opacity: 0, y: 24, duration: 0.5, stagger: 0.08, ease: 'power2.out', scrollTrigger: { trigger: el, start: 'top 85%' } });","In React use useGSAP(() => {...}, { scope: containerRef }) from @gsap/react to auto-cleanup on unmount",Scope the ScrollTrigger to the section container so it doesn't re-scan the whole page,Don't stagger more than ~8 children; beyond that the last items feel laggy,Set scroller/markers: false in production; markers is dev-only
6,Scroll Reveal,Complex,"scroll, pin, scrub, storytelling, scrollytelling",scroll (continuous scrub),tied to scroll position,none (scrub-driven),"gsap.timeline({ scrollTrigger: { trigger: section, start: 'top top', end: '+=150%', scrub: 1, pin: true } }).from('.headline', { opacity: 0, y: 40 }).to('.bg-layer', { yPercent: -20 }, '<');",Pinning needs the section to have deterministic height; recalc ScrollTrigger.refresh() after images/fonts load,Use scrub: true or a small number (0.5-1.5) instead of instant jumps so it feels tied to the scrollbar,Don't pin more than 1-2 sections per page; excessive pinning fights native scroll feel and hurts mobile UX,"Pinning forces layout reflow; test on mid-tier mobile devices, not just desktop"
7,Stagger List,Subtle,"list, stagger, cards, grid entrance",load or scroll,250-350ms,power1.out,"gsap.from('.list-item', { opacity: 0, y: 8, duration: 0.3, stagger: 0.03 });",Select items with a stable class/data-attribute (not array index) so re-renders in React don't break targeting,Keep per-item stagger delay small (0.02-0.04s) for lists longer than 10 items,Don't stagger by more than 0.1s per item on long lists; total reveal time becomes sluggish,"For virtualized lists, only animate items currently mounted in the DOM"
8,Stagger List,Standard,"grid, bento, cards, staggered scale",load or scroll,300-450ms,back.out(1.4),"gsap.from('.grid-item', { opacity: 0, scale: 0.92, y: 16, duration: 0.4, stagger: { each: 0.06, from: 'start', grid: 'auto' }, ease: 'back.out(1.4)' });",grid: 'auto' lets GSAP infer rows/columns from a CSS grid layout for a natural wave stagger,Combine with from: 'center' for a bento-grid layout to draw the eye inward first,Don't use back.out on dense data tables; the overshoot reads as sloppy on informational UI,Group DOM writes; avoid interleaving layout reads (getBoundingClientRect) between staggered tweens
9,Stagger List,Complex,"stagger, wave, text reveal, split text",load or scroll,400-700ms,expo.out,"const split = new SplitText(headline, { type: 'chars' }); gsap.from(split.chars, { opacity: 0, y: 20, rotateX: -40, duration: 0.6, stagger: 0.015, ease: 'expo.out' });",SplitText is a GSAP Club/paid plugin; confirm license before shipping and provide a plain fade fallback if unavailable,Revert SplitText on unmount/cleanup (split.revert()) to restore original text nodes for accessibility tools,Don't split-animate long paragraphs; reserve for short headlines (under ~8 words),Splitting text creates one element per character; keep it to headline-length copy only for DOM size
10,Page Transition,Subtle,"route change, fade, page transition",route change,200-300ms,power1.inOut,"gsap.to(main, { opacity: 0, duration: 0.2, onComplete: () => { navigate(); gsap.fromTo(main, { opacity: 0 }, { opacity: 1, duration: 0.2 }); } });","Pair with the router's transition hooks (Next.js App Router transitions, React Router's useNavigate, Vue Router's beforeEach/afterEach)",Preload the destination route's critical assets before the exit tween finishes,Don't block navigation on animation; cap exit duration at ~250ms so the app never feels unresponsive,Exit animation should always resolve faster than entrance (asymmetric timing) so back/forward feels snappy
11,Page Transition,Standard,"route change, slide, overlay wipe",route change,400-600ms,power2.inOut,"const tl = gsap.timeline(); tl.to('.transition-overlay', { yPercent: 0, duration: 0.4, ease: 'power2.inOut' }).call(navigate).to('.transition-overlay', { yPercent: -100, duration: 0.4, ease: 'power2.inOut', delay: 0.1 });",Keep the overlay element mounted at the layout root (outside the page component) so it survives the route swap,Show a lightweight loading indicator if the destination route's data fetch outlasts the overlay,Don't tie the overlay's reveal directly to data-fetch completion without a max-wait timeout; a slow API stalls the whole transition,Prefer CSS transform (yPercent) over top/left to keep the overlay animation on the compositor thread
12,Page Transition,Complex,"shared element, morph, hero transition",route change,500-800ms,expo.inOut,"const state = Flip.getState('.hero-image'); navigate(); Flip.from(state, { duration: 0.6, ease: 'expo.inOut', absolute: true, zIndex: 100 });",Requires the GSAP Flip plugin; the 'from' and 'to' route must render the same element with a shared data-flip-id,Verify the shared element exists in both DOM states before calling Flip.from to avoid a silent no-op,Don't use shared-element transitions across more than one element pair per navigation; compounding Flips are hard to time correctly,Flip recalculates layout (FLIP technique) so test on low-end devices for jank
13,Parallax Scroll,Subtle,"parallax, background, depth, scroll speed",scroll (continuous),tied to scroll position,linear (scrub),"gsap.to('.bg-layer', { yPercent: 10, ease: 'none', scrollTrigger: { trigger: section, scrub: true } });","Apply parallax to background/decorative layers only, never to text or interactive controls",Keep the yPercent delta small (5-15) so foreground and background never desync distractingly,Don't parallax body copy; it hurts reading comfort and can trigger motion sickness,will-change: transform on the parallax layer only; remove it after scroll settles to free GPU memory
14,Parallax Scroll,Standard,"multi-layer parallax, depth, hero background",scroll (continuous),tied to scroll position,linear (scrub),"gsap.utils.toArray('.parallax-layer').forEach((layer, i) => { gsap.to(layer, { yPercent: (i + 1) * -8, ease: 'none', scrollTrigger: { trigger: layer.parentElement, scrub: 0.5 } }); });",Layer count beyond 3-4 has diminishing visual return and multiplies scroll-listener cost,"Vary speed per layer (background slowest, foreground fastest) to sell the depth illusion",Don't let parallax layers overflow their container; clip with overflow: hidden on the wrapper,Batch all layers under one ScrollTrigger container where possible instead of one per layer
15,Loading / Skeleton,Subtle,"loading, skeleton, shimmer, pulse",on mount / async wait,1200-1600ms loop,sine.inOut,"gsap.to('.skeleton', { backgroundPosition: '200% 0', duration: 1.4, ease: 'sine.inOut', repeat: -1 });",Kill the loop tween (tween.kill()) as soon as real content mounts to avoid orphaned repeating animations,Use a CSS gradient background-position sweep rather than opacity pulsing; reads as 'loading' more clearly,Don't run more than one shimmer loop per skeleton group; sync them under one timeline so the wave reads as a single unit,repeat: -1 tweens are cheap but must be explicitly killed on unmount or they leak in SPA route changes
16,Loading / Skeleton,Standard,"progress, spinner, morphing loader",on mount / async wait,800-1200ms loop,power1.inOut,"gsap.timeline({ repeat: -1 }).to('.loader-dot', { y: -8, duration: 0.4, stagger: { each: 0.15, yoyo: true, repeat: 1 } });",Wrap the whole loop timeline in useGSAP with { revertOnUpdate: false } in React so it isn't rebuilt every render,Cap total loop duration under ~1.5s so long waits don't feel like the UI froze on a single beat,Don't use elaborate loaders for sub-300ms waits; they flash and feel worse than no indicator,Pause the timeline (tl.pause()) when the loading tab/view is not visible to save CPU on background tabs
No,Category,Intensity Tier,Keywords,Trigger,Duration,Easing,GSAP Snippet,Framework Notes,Do,Don't,Performance Notes
1,Hover Micro-interaction,Subtle,"hover, button, opacity, lift, press feedback",hover,150-200ms,power1.out,"gsap.to(el, { y: -1, opacity: 0.9, duration: 0.15, ease: 'power1.out' });",Bind on mouseenter/mouseleave; in React wrap in a ref + useEffect (or onMouseEnter/onMouseLeave props directly calling gsap.to),Keep displacement under 2px so it reads as feedback not motion,Don't animate layout-affecting props (width/height/margin) on hover,Runs on transform/opacity only so it stays on the compositor thread
2,Hover Micro-interaction,Standard,"hover, card, scale, tilt, cursor feedback",hover,200-300ms,power2.out,"gsap.to(el, { y: -4, scale: 1.02, boxShadow: '0 12px 24px rgba(0,0,0,0.12)', duration: 0.25, ease: 'power2.out' });","Use gsap.quickTo(el, 'y') for cards with many hover targets to avoid re-creating tweens every event",Pair with a matching mouseleave tween that reverses the same properties,Don't leave the hover state stuck if the pointer leaves fast; always attach the reverse tween,quickTo() avoids GC churn on lists with 20+ hoverable cards
3,Hover Micro-interaction,Complex,"hover, magnetic, cursor follow, 3d tilt",hover + mousemove,300-500ms,"elastic.out(1,0.4)","const xTo = gsap.quickTo(el, 'x', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); const yTo = gsap.quickTo(el, 'y', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); el.addEventListener('mousemove', (e) => { const r = el.getBoundingClientRect(); xTo((e.clientX - r.left - r.width/2) * 0.3); yTo((e.clientY - r.top - r.height/2) * 0.3); });",Debounce is not needed since quickTo interpolates; remove listeners on component unmount in React/Vue to avoid leaks,Clamp the pull strength (e.g. * 0.3) so the element never fully leaves its hit box,Don't apply magnetic effect to more than 1-2 focal elements per screen; it becomes noisy,Use will-change: transform on the target element for smoother compositing
4,Scroll Reveal,Subtle,"scroll, fade in, reveal, on view",scroll (viewport enter),300-400ms,power1.out,"gsap.from(el, { opacity: 0, y: 12, duration: 0.35, ease: 'power1.out', scrollTrigger: { trigger: el, start: 'top 90%', toggleActions: 'play none none reverse' } });",Requires the ScrollTrigger plugin registered once via gsap.registerPlugin(ScrollTrigger),"Keep the y offset small (8-16px) so it reads as a fade, not a slide",Don't reveal below-the-fold content needed for SEO/crawlers as invisible-by-default without a no-JS fallback,toggleActions 'play none none reverse' avoids re-triggering on every scroll direction change
5,Scroll Reveal,Standard,"scroll, slide up, staggered section, reveal",scroll (viewport enter),400-600ms,power2.out,"gsap.from(el.children, { opacity: 0, y: 24, duration: 0.5, stagger: 0.08, ease: 'power2.out', scrollTrigger: { trigger: el, start: 'top 85%' } });","In React use useGSAP(() => {...}, { scope: containerRef }) from @gsap/react to auto-cleanup on unmount",Scope the ScrollTrigger to the section container so it doesn't re-scan the whole page,Don't stagger more than ~8 children; beyond that the last items feel laggy,Set scroller/markers: false in production; markers is dev-only
6,Scroll Reveal,Complex,"scroll, pin, scrub, storytelling, scrollytelling",scroll (continuous scrub),tied to scroll position,none (scrub-driven),"gsap.timeline({ scrollTrigger: { trigger: section, start: 'top top', end: '+=150%', scrub: 1, pin: true } }).from('.headline', { opacity: 0, y: 40 }).to('.bg-layer', { yPercent: -20 }, '<');",Pinning needs the section to have deterministic height; recalc ScrollTrigger.refresh() after images/fonts load,Use scrub: true or a small number (0.5-1.5) instead of instant jumps so it feels tied to the scrollbar,Don't pin more than 1-2 sections per page; excessive pinning fights native scroll feel and hurts mobile UX,"Pinning forces layout reflow; test on mid-tier mobile devices, not just desktop"
7,Stagger List,Subtle,"list, stagger, cards, grid entrance",load or scroll,250-350ms,power1.out,"gsap.from('.list-item', { opacity: 0, y: 8, duration: 0.3, stagger: 0.03 });",Select items with a stable class/data-attribute (not array index) so re-renders in React don't break targeting,Keep per-item stagger delay small (0.02-0.04s) for lists longer than 10 items,Don't stagger by more than 0.1s per item on long lists; total reveal time becomes sluggish,"For virtualized lists, only animate items currently mounted in the DOM"
8,Stagger List,Standard,"grid, bento, cards, staggered scale",load or scroll,300-450ms,back.out(1.4),"gsap.from('.grid-item', { opacity: 0, scale: 0.92, y: 16, duration: 0.4, stagger: { each: 0.06, from: 'start', grid: 'auto' }, ease: 'back.out(1.4)' });",grid: 'auto' lets GSAP infer rows/columns from a CSS grid layout for a natural wave stagger,Combine with from: 'center' for a bento-grid layout to draw the eye inward first,Don't use back.out on dense data tables; the overshoot reads as sloppy on informational UI,Group DOM writes; avoid interleaving layout reads (getBoundingClientRect) between staggered tweens
9,Stagger List,Complex,"stagger, wave, text reveal, split text",load or scroll,400-700ms,expo.out,"const split = new SplitText(headline, { type: 'chars' }); gsap.from(split.chars, { opacity: 0, y: 20, rotateX: -40, duration: 0.6, stagger: 0.015, ease: 'expo.out' });",SplitText is a GSAP Club/paid plugin; confirm license before shipping and provide a plain fade fallback if unavailable,Revert SplitText on unmount/cleanup (split.revert()) to restore original text nodes for accessibility tools,Don't split-animate long paragraphs; reserve for short headlines (under ~8 words),Splitting text creates one element per character; keep it to headline-length copy only for DOM size
10,Page Transition,Subtle,"route change, fade, page transition",route change,200-300ms,power1.inOut,"gsap.to(main, { opacity: 0, duration: 0.2, onComplete: () => { navigate(); gsap.fromTo(main, { opacity: 0 }, { opacity: 1, duration: 0.2 }); } });","Pair with the router's transition hooks (Next.js App Router transitions, React Router's useNavigate, Vue Router's beforeEach/afterEach)",Preload the destination route's critical assets before the exit tween finishes,Don't block navigation on animation; cap exit duration at ~250ms so the app never feels unresponsive,Exit animation should always resolve faster than entrance (asymmetric timing) so back/forward feels snappy
11,Page Transition,Standard,"route change, slide, overlay wipe",route change,400-600ms,power2.inOut,"const tl = gsap.timeline(); tl.to('.transition-overlay', { yPercent: 0, duration: 0.4, ease: 'power2.inOut' }).call(navigate).to('.transition-overlay', { yPercent: -100, duration: 0.4, ease: 'power2.inOut', delay: 0.1 });",Keep the overlay element mounted at the layout root (outside the page component) so it survives the route swap,Show a lightweight loading indicator if the destination route's data fetch outlasts the overlay,Don't tie the overlay's reveal directly to data-fetch completion without a max-wait timeout; a slow API stalls the whole transition,Prefer CSS transform (yPercent) over top/left to keep the overlay animation on the compositor thread
12,Page Transition,Complex,"shared element, morph, hero transition",route change,500-800ms,expo.inOut,"const state = Flip.getState('.hero-image'); navigate(); Flip.from(state, { duration: 0.6, ease: 'expo.inOut', absolute: true, zIndex: 100 });",Requires the GSAP Flip plugin; the 'from' and 'to' route must render the same element with a shared data-flip-id,Verify the shared element exists in both DOM states before calling Flip.from to avoid a silent no-op,Don't use shared-element transitions across more than one element pair per navigation; compounding Flips are hard to time correctly,Flip recalculates layout (FLIP technique) so test on low-end devices for jank
13,Parallax Scroll,Subtle,"parallax, background, depth, scroll speed",scroll (continuous),tied to scroll position,linear (scrub),"gsap.to('.bg-layer', { yPercent: 10, ease: 'none', scrollTrigger: { trigger: section, scrub: true } });","Apply parallax to background/decorative layers only, never to text or interactive controls",Keep the yPercent delta small (5-15) so foreground and background never desync distractingly,Don't parallax body copy; it hurts reading comfort and can trigger motion sickness,will-change: transform on the parallax layer only; remove it after scroll settles to free GPU memory
14,Parallax Scroll,Standard,"multi-layer parallax, depth, hero background",scroll (continuous),tied to scroll position,linear (scrub),"gsap.utils.toArray('.parallax-layer').forEach((layer, i) => { gsap.to(layer, { yPercent: (i + 1) * -8, ease: 'none', scrollTrigger: { trigger: layer.parentElement, scrub: 0.5 } }); });",Layer count beyond 3-4 has diminishing visual return and multiplies scroll-listener cost,"Vary speed per layer (background slowest, foreground fastest) to sell the depth illusion",Don't let parallax layers overflow their container; clip with overflow: hidden on the wrapper,Batch all layers under one ScrollTrigger container where possible instead of one per layer
15,Loading / Skeleton,Subtle,"loading, skeleton, shimmer, pulse",on mount / async wait,1200-1600ms loop,sine.inOut,"gsap.to('.skeleton', { backgroundPosition: '200% 0', duration: 1.4, ease: 'sine.inOut', repeat: -1 });",Kill the loop tween (tween.kill()) as soon as real content mounts to avoid orphaned repeating animations,Use a CSS gradient background-position sweep rather than opacity pulsing; reads as 'loading' more clearly,Don't run more than one shimmer loop per skeleton group; sync them under one timeline so the wave reads as a single unit,repeat: -1 tweens are cheap but must be explicitly killed on unmount or they leak in SPA route changes
16,Loading / Skeleton,Standard,"progress, spinner, morphing loader",on mount / async wait,800-1200ms loop,power1.inOut,"gsap.timeline({ repeat: -1 }).to('.loader-dot', { y: -8, duration: 0.4, stagger: { each: 0.15, yoyo: true, repeat: 1 } });",Wrap the whole loop timeline in useGSAP with { revertOnUpdate: false } in React so it isn't rebuilt every render,Cap total loop duration under ~1.5s so long waits don't feel like the UI froze on a single beat,Don't use elaborate loaders for sub-300ms waits; they flash and feel worse than no indicator,Pause the timeline (tl.pause()) when the loading tab/view is not visible to save CPU on background tabs

1 No Category Intensity Tier Keywords Trigger Duration Easing GSAP Snippet Framework Notes Do Don't Performance Notes
2 1 Hover Micro-interaction Subtle hover, button, opacity, lift, press feedback hover 150-200ms power1.out gsap.to(el, { y: -1, opacity: 0.9, duration: 0.15, ease: 'power1.out' }); Bind on mouseenter/mouseleave; in React wrap in a ref + useEffect (or onMouseEnter/onMouseLeave props directly calling gsap.to) Keep displacement under 2px so it reads as feedback not motion Don't animate layout-affecting props (width/height/margin) on hover Runs on transform/opacity only so it stays on the compositor thread
3 2 Hover Micro-interaction Standard hover, card, scale, tilt, cursor feedback hover 200-300ms power2.out gsap.to(el, { y: -4, scale: 1.02, boxShadow: '0 12px 24px rgba(0,0,0,0.12)', duration: 0.25, ease: 'power2.out' }); Use gsap.quickTo(el, 'y') for cards with many hover targets to avoid re-creating tweens every event Pair with a matching mouseleave tween that reverses the same properties Don't leave the hover state stuck if the pointer leaves fast; always attach the reverse tween quickTo() avoids GC churn on lists with 20+ hoverable cards
4 3 Hover Micro-interaction Complex hover, magnetic, cursor follow, 3d tilt hover + mousemove 300-500ms elastic.out(1,0.4) const xTo = gsap.quickTo(el, 'x', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); const yTo = gsap.quickTo(el, 'y', { duration: 0.4, ease: 'elastic.out(1,0.4)' }); el.addEventListener('mousemove', (e) => { const r = el.getBoundingClientRect(); xTo((e.clientX - r.left - r.width/2) * 0.3); yTo((e.clientY - r.top - r.height/2) * 0.3); }); Debounce is not needed since quickTo interpolates; remove listeners on component unmount in React/Vue to avoid leaks Clamp the pull strength (e.g. * 0.3) so the element never fully leaves its hit box Don't apply magnetic effect to more than 1-2 focal elements per screen; it becomes noisy Use will-change: transform on the target element for smoother compositing
5 4 Scroll Reveal Subtle scroll, fade in, reveal, on view scroll (viewport enter) 300-400ms power1.out gsap.from(el, { opacity: 0, y: 12, duration: 0.35, ease: 'power1.out', scrollTrigger: { trigger: el, start: 'top 90%', toggleActions: 'play none none reverse' } }); Requires the ScrollTrigger plugin registered once via gsap.registerPlugin(ScrollTrigger) Keep the y offset small (8-16px) so it reads as a fade, not a slide Don't reveal below-the-fold content needed for SEO/crawlers as invisible-by-default without a no-JS fallback toggleActions 'play none none reverse' avoids re-triggering on every scroll direction change
6 5 Scroll Reveal Standard scroll, slide up, staggered section, reveal scroll (viewport enter) 400-600ms power2.out gsap.from(el.children, { opacity: 0, y: 24, duration: 0.5, stagger: 0.08, ease: 'power2.out', scrollTrigger: { trigger: el, start: 'top 85%' } }); In React use useGSAP(() => {...}, { scope: containerRef }) from @gsap/react to auto-cleanup on unmount Scope the ScrollTrigger to the section container so it doesn't re-scan the whole page Don't stagger more than ~8 children; beyond that the last items feel laggy Set scroller/markers: false in production; markers is dev-only
7 6 Scroll Reveal Complex scroll, pin, scrub, storytelling, scrollytelling scroll (continuous scrub) tied to scroll position none (scrub-driven) gsap.timeline({ scrollTrigger: { trigger: section, start: 'top top', end: '+=150%', scrub: 1, pin: true } }).from('.headline', { opacity: 0, y: 40 }).to('.bg-layer', { yPercent: -20 }, '<'); Pinning needs the section to have deterministic height; recalc ScrollTrigger.refresh() after images/fonts load Use scrub: true or a small number (0.5-1.5) instead of instant jumps so it feels tied to the scrollbar Don't pin more than 1-2 sections per page; excessive pinning fights native scroll feel and hurts mobile UX Pinning forces layout reflow; test on mid-tier mobile devices, not just desktop
8 7 Stagger List Subtle list, stagger, cards, grid entrance load or scroll 250-350ms power1.out gsap.from('.list-item', { opacity: 0, y: 8, duration: 0.3, stagger: 0.03 }); Select items with a stable class/data-attribute (not array index) so re-renders in React don't break targeting Keep per-item stagger delay small (0.02-0.04s) for lists longer than 10 items Don't stagger by more than 0.1s per item on long lists; total reveal time becomes sluggish For virtualized lists, only animate items currently mounted in the DOM
9 8 Stagger List Standard grid, bento, cards, staggered scale load or scroll 300-450ms back.out(1.4) gsap.from('.grid-item', { opacity: 0, scale: 0.92, y: 16, duration: 0.4, stagger: { each: 0.06, from: 'start', grid: 'auto' }, ease: 'back.out(1.4)' }); grid: 'auto' lets GSAP infer rows/columns from a CSS grid layout for a natural wave stagger Combine with from: 'center' for a bento-grid layout to draw the eye inward first Don't use back.out on dense data tables; the overshoot reads as sloppy on informational UI Group DOM writes; avoid interleaving layout reads (getBoundingClientRect) between staggered tweens
10 9 Stagger List Complex stagger, wave, text reveal, split text load or scroll 400-700ms expo.out const split = new SplitText(headline, { type: 'chars' }); gsap.from(split.chars, { opacity: 0, y: 20, rotateX: -40, duration: 0.6, stagger: 0.015, ease: 'expo.out' }); SplitText is a GSAP Club/paid plugin; confirm license before shipping and provide a plain fade fallback if unavailable Revert SplitText on unmount/cleanup (split.revert()) to restore original text nodes for accessibility tools Don't split-animate long paragraphs; reserve for short headlines (under ~8 words) Splitting text creates one element per character; keep it to headline-length copy only for DOM size
11 10 Page Transition Subtle route change, fade, page transition route change 200-300ms power1.inOut gsap.to(main, { opacity: 0, duration: 0.2, onComplete: () => { navigate(); gsap.fromTo(main, { opacity: 0 }, { opacity: 1, duration: 0.2 }); } }); Pair with the router's transition hooks (Next.js App Router transitions, React Router's useNavigate, Vue Router's beforeEach/afterEach) Preload the destination route's critical assets before the exit tween finishes Don't block navigation on animation; cap exit duration at ~250ms so the app never feels unresponsive Exit animation should always resolve faster than entrance (asymmetric timing) so back/forward feels snappy
12 11 Page Transition Standard route change, slide, overlay wipe route change 400-600ms power2.inOut const tl = gsap.timeline(); tl.to('.transition-overlay', { yPercent: 0, duration: 0.4, ease: 'power2.inOut' }).call(navigate).to('.transition-overlay', { yPercent: -100, duration: 0.4, ease: 'power2.inOut', delay: 0.1 }); Keep the overlay element mounted at the layout root (outside the page component) so it survives the route swap Show a lightweight loading indicator if the destination route's data fetch outlasts the overlay Don't tie the overlay's reveal directly to data-fetch completion without a max-wait timeout; a slow API stalls the whole transition Prefer CSS transform (yPercent) over top/left to keep the overlay animation on the compositor thread
13 12 Page Transition Complex shared element, morph, hero transition route change 500-800ms expo.inOut const state = Flip.getState('.hero-image'); navigate(); Flip.from(state, { duration: 0.6, ease: 'expo.inOut', absolute: true, zIndex: 100 }); Requires the GSAP Flip plugin; the 'from' and 'to' route must render the same element with a shared data-flip-id Verify the shared element exists in both DOM states before calling Flip.from to avoid a silent no-op Don't use shared-element transitions across more than one element pair per navigation; compounding Flips are hard to time correctly Flip recalculates layout (FLIP technique) so test on low-end devices for jank
14 13 Parallax Scroll Subtle parallax, background, depth, scroll speed scroll (continuous) tied to scroll position linear (scrub) gsap.to('.bg-layer', { yPercent: 10, ease: 'none', scrollTrigger: { trigger: section, scrub: true } }); Apply parallax to background/decorative layers only, never to text or interactive controls Keep the yPercent delta small (5-15) so foreground and background never desync distractingly Don't parallax body copy; it hurts reading comfort and can trigger motion sickness will-change: transform on the parallax layer only; remove it after scroll settles to free GPU memory
15 14 Parallax Scroll Standard multi-layer parallax, depth, hero background scroll (continuous) tied to scroll position linear (scrub) gsap.utils.toArray('.parallax-layer').forEach((layer, i) => { gsap.to(layer, { yPercent: (i + 1) * -8, ease: 'none', scrollTrigger: { trigger: layer.parentElement, scrub: 0.5 } }); }); Layer count beyond 3-4 has diminishing visual return and multiplies scroll-listener cost Vary speed per layer (background slowest, foreground fastest) to sell the depth illusion Don't let parallax layers overflow their container; clip with overflow: hidden on the wrapper Batch all layers under one ScrollTrigger container where possible instead of one per layer
16 15 Loading / Skeleton Subtle loading, skeleton, shimmer, pulse on mount / async wait 1200-1600ms loop sine.inOut gsap.to('.skeleton', { backgroundPosition: '200% 0', duration: 1.4, ease: 'sine.inOut', repeat: -1 }); Kill the loop tween (tween.kill()) as soon as real content mounts to avoid orphaned repeating animations Use a CSS gradient background-position sweep rather than opacity pulsing; reads as 'loading' more clearly Don't run more than one shimmer loop per skeleton group; sync them under one timeline so the wave reads as a single unit repeat: -1 tweens are cheap but must be explicitly killed on unmount or they leak in SPA route changes
17 16 Loading / Skeleton Standard progress, spinner, morphing loader on mount / async wait 800-1200ms loop power1.inOut gsap.timeline({ repeat: -1 }).to('.loader-dot', { y: -8, duration: 0.4, stagger: { each: 0.15, yoyo: true, repeat: 1 } }); Wrap the whole loop timeline in useGSAP with { revertOnUpdate: false } in React so it isn't rebuilt every render Cap total loop duration under ~1.5s so long waits don't feel like the UI froze on a single beat Don't use elaborate loaders for sub-300ms waits; they flash and feel worse than no indicator Pause the timeline (tl.pause()) when the loading tab/view is not visible to save CPU on background tabs

View File

@ -1,17 +1,17 @@
No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing Page Pattern,Dashboard Style (if applicable),Color Palette Focus,Key Considerations
1,SaaS (General),"app, b2b, cloud, general, saas, software, subscription",Glassmorphism + Flat Design,"Soft UI Evolution, Minimalism",Hero + Features + CTA,Data-Dense + Real-Time Monitoring,Trust blue + accent contrast,Balance modern feel with clarity. Focus on CTAs.
2,Micro SaaS,"app, b2b, cloud, indie, micro, micro-saas, niche, saas, small, software, solo, subscription",Flat Design + Vibrant & Block,"Motion-Driven, Micro-interactions",Minimal & Direct + Demo,Executive Dashboard,Vibrant primary + white space,"Keep simple, show product quickly. Speed is key."
2,Micro SaaS,"indie, micro-saas, niche, solo, bootstrap, micro, side-project, solopreneur, small-team, indie-hacker, product-hunt",Flat Design + Vibrant & Block,"Motion-Driven, Micro-interactions",Minimal & Direct + Demo,Executive Dashboard,Vibrant primary + white space,"Keep simple, show product quickly. Speed is key."
3,E-commerce,"buy, commerce, e, ecommerce, products, retail, sell, shop, store",Vibrant & Block-based,"Aurora UI, Motion-Driven",Feature-Rich Showcase,Sales Intelligence Dashboard,Brand primary + success green,Engagement & conversions. High visual hierarchy.
4,E-commerce Luxury,"buy, commerce, e, ecommerce, elegant, exclusive, high-end, luxury, premium, products, retail, sell, shop, store",Liquid Glass + Glassmorphism,"3D & Hyperrealism, Aurora UI",Feature-Rich Showcase,Sales Intelligence Dashboard,Premium colors + minimal accent,Elegance & sophistication. Premium materials.
5,B2B Service,"appointment, b, b2b, booking, business, consultation, corporate, enterprise, service",Trust & Authority + Minimal,"Feature-Rich, Conversion-Optimized",Feature-Rich Showcase,Sales Intelligence Dashboard,Professional blue + neutral grey,Credibility essential. Clear ROI messaging.
6,Financial Dashboard,"admin, analytics, dashboard, data, financial, panel",Dark Mode (OLED) + Data-Dense,"Minimalism, Accessible & Ethical",N/A - Dashboard focused,Financial Dashboard,Dark bg + red/green alerts + trust blue,"High contrast, real-time updates, accuracy paramount."
7,Analytics Dashboard,"admin, analytics, dashboard, data, panel",Data-Dense + Heat Map & Heatmap,"Minimalism, Dark Mode (OLED)",N/A - Analytics focused,Drill-Down Analytics + Comparative,Cool→Hot gradients + neutral grey,Clarity > aesthetics. Color-coded data priority.
5,B2B Service,"b2b, enterprise, consulting, professional, solution, contract, corporate, strategy, advisory, roi, deliverable, whitepaper",Trust & Authority + Minimal,"Feature-Rich, Conversion-Optimized",Feature-Rich Showcase,Sales Intelligence Dashboard,Professional blue + neutral grey,Credibility essential. Clear ROI messaging.
6,Financial Dashboard,"portfolio, trading, pnl, budget, revenue, expense, cashflow, balance-sheet, investment, bank, accounting, fintech",Dark Mode (OLED) + Data-Dense,"Minimalism, Accessible & Ethical",N/A - Dashboard focused,Financial Dashboard,Dark bg + red/green alerts + trust blue,"High contrast, real-time updates, accuracy paramount."
7,Analytics Dashboard,"kpi, metric, funnel, conversion, cohort, retention, segment, attribution, ab-test, dashboard-data, business-intelligence",Data-Dense + Heat Map & Heatmap,"Minimalism, Dark Mode (OLED)",N/A - Analytics focused,Drill-Down Analytics + Comparative,Cool→Hot gradients + neutral grey,Clarity > aesthetics. Color-coded data priority.
8,Healthcare App,"app, clinic, health, healthcare, medical, patient",Neumorphism + Accessible & Ethical,"Soft UI Evolution, Claymorphism (for patients)",Social Proof-Focused,User Behavior Analytics,Calm blue + health green + trust,Accessibility mandatory. Calming aesthetic.
9,Educational App,"app, course, education, educational, learning, school, training",Claymorphism + Micro-interactions,"Vibrant & Block-based, Flat Design",Storytelling-Driven,User Behavior Analytics,Playful colors + clear hierarchy,Engagement & ease of use. Age-appropriate design.
10,Creative Agency,"agency, creative, design, marketing, studio",Brutalism + Motion-Driven,"Retro-Futurism, Storytelling-Driven",Storytelling-Driven,N/A - Portfolio focused,Bold primaries + artistic freedom,Differentiation key. Wow-factor necessary.
10,Creative Agency,"branding, identity, portfolio, logo, visual, rebrand, creative-director, campaign, awards, award-winning, showreel",Brutalism + Motion-Driven,"Retro-Futurism, Storytelling-Driven",Storytelling-Driven,N/A - Portfolio focused,Bold primaries + artistic freedom,Differentiation key. Wow-factor necessary.
11,Portfolio/Personal,"creative, personal, portfolio, projects, showcase, work",Motion-Driven + Minimalism,"Brutalism, Aurora UI",Storytelling-Driven,N/A - Personal branding,Brand primary + artistic interpretation,Showcase work. Personality shine through.
12,Gaming,"entertainment, esports, game, gaming, play",3D & Hyperrealism + Retro-Futurism,"Motion-Driven, Vibrant & Block",Feature-Rich Showcase,N/A - Game focused,Vibrant + neon + immersive colors,Immersion priority. Performance critical.
13,Government/Public Service,"appointment, booking, consultation, government, public, service",Accessible & Ethical + Minimalism,"Flat Design, Inclusive Design",Minimal & Direct,Executive Dashboard,Professional blue + high contrast,WCAG AAA mandatory. Trust paramount.
13,Government/Public Service,"government, civic, municipal, federal, citizen, public, administration, permit, tax, voter, transparency, regulation",Accessible & Ethical + Minimalism,"Flat Design, Inclusive Design",Minimal & Direct,Executive Dashboard,Professional blue + high contrast,WCAG AAA mandatory. Trust paramount.
14,Fintech/Crypto,"banking, blockchain, crypto, defi, finance, fintech, money, nft, payment, web3",Glassmorphism + Dark Mode (OLED),"Retro-Futurism, Motion-Driven",Conversion-Optimized,Real-Time Monitoring + Predictive,Dark tech colors + trust + vibrant accents,Security perception. Real-time data critical.
15,Social Media App,"app, community, content, entertainment, media, network, sharing, social, streaming, users, video",Vibrant & Block-based + Motion-Driven,"Aurora UI, Micro-interactions",Feature-Rich Showcase,User Behavior Analytics,Vibrant + engagement colors,Engagement & retention. Addictive design ethics.
16,Productivity Tool,"collaboration, productivity, project, task, tool, workflow",Flat Design + Micro-interactions,"Minimalism, Soft UI Evolution",Interactive Product Demo,Drill-Down Analytics,Clear hierarchy + functional colors,Ease of use. Speed & efficiency focus.
@ -24,21 +24,21 @@ No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing P
23,Pet Tech App,"app, pet, tech",Claymorphism + Vibrant & Block-based,"Micro-interactions, Flat Design",Storytelling-Driven,User Behavior Analytics,Playful + Warm colors,Pet profiles. Health tracking. Playful UI. Photo galleries. Vet integration.
24,Smart Home/IoT Dashboard,"admin, analytics, dashboard, data, home, iot, panel, smart",Glassmorphism + Dark Mode (OLED),"Minimalism, AI-Native UI",Interactive Product Demo,Real-Time Monitoring,Dark + Status indicator colors,Device status. Real-time controls. Energy monitoring. Automation rules. Quick actions.
25,EV/Charging Ecosystem,"charging, ecosystem, ev",Minimalism + Aurora UI,"Glassmorphism, Organic Biophilic",Hero-Centric Design,Energy/Utilities Dashboard,Electric Blue (#009CD1) + Green,Charging station maps. Range estimation. Cost calculation. Environmental impact.
26,Subscription Box Service,"appointment, booking, box, consultation, membership, plan, recurring, service, subscription",Vibrant & Block-based + Motion-Driven,"Claymorphism, Aurora UI",Feature-Rich Showcase,E-commerce Analytics,Brand + Excitement colors,Unboxing experience. Personalization quiz. Subscription management. Product reveals.
26,Subscription Box Service,"subscription, box, recurring, membership, unboxing, curated, plan, monthly, surprise, product-box",Vibrant & Block-based + Motion-Driven,"Claymorphism, Aurora UI",Feature-Rich Showcase,E-commerce Analytics,Brand + Excitement colors,Unboxing experience. Personalization quiz. Subscription management. Product reveals.
27,Podcast Platform,"platform, podcast",Dark Mode (OLED) + Minimalism,"Motion-Driven, Vibrant & Block-based",Storytelling-Driven,Media/Entertainment Dashboard,Dark + Audio waveform accents,Audio player UX. Episode discovery. Creator tools. Analytics for podcasters.
28,Dating App,"app, dating",Vibrant & Block-based + Motion-Driven,"Aurora UI, Glassmorphism",Social Proof-Focused,User Behavior Analytics,Warm + Romantic (Pink/Red gradients),Profile cards. Swipe interactions. Match animations. Safety features. Video chat.
29,Micro-Credentials/Badges Platform,"badges, credentials, micro, platform",Minimalism + Flat Design,"Accessible & Ethical, Swiss Modernism 2.0",Trust & Authority,Education Dashboard,Trust Blue + Gold (#FFD700),Credential verification. Badge display. Progress tracking. Issuer trust. LinkedIn integration.
30,Knowledge Base/Documentation,"base, documentation, knowledge",Minimalism + Accessible & Ethical,"Swiss Modernism 2.0, Flat Design",FAQ/Documentation,N/A - Documentation focused,Clean hierarchy + minimal color,Search-first. Clear navigation. Code highlighting. Version switching. Feedback system.
31,Hyperlocal Services,"appointment, booking, consultation, hyperlocal, service, services",Minimalism + Vibrant & Block-based,"Micro-interactions, Flat Design",Conversion-Optimized,Drill-Down Analytics + Map,Location markers + Trust colors,Map integration. Service categories. Provider profiles. Booking system. Reviews.
32,Beauty/Spa/Wellness Service,"appointment, beauty, booking, consultation, service, spa, wellness",Soft UI Evolution + Neumorphism,"Glassmorphism, Minimalism",Hero-Centric Design + Social Proof,User Behavior Analytics,Soft pastels (Pink #FFB6C1 Sage #90EE90) + Cream + Gold accents,Calming aesthetic. Booking system. Service menu. Before/after gallery. Testimonials. Relaxing imagery.
31,Hyperlocal Services,"hyperlocal, local, neighborhood, nearby, community, nearby, zip, map, local-business, geo-target, city",Minimalism + Vibrant & Block-based,"Micro-interactions, Flat Design",Conversion-Optimized,Drill-Down Analytics + Map,Location markers + Trust colors,Map integration. Service categories. Provider profiles. Booking system. Reviews.
32,Beauty/Spa/Wellness Service,"spa, beauty, salon, wellness, treatment, relaxation, massage, skincare, facial, aesthetic, self-care, pamper",Soft UI Evolution + Neumorphism,"Glassmorphism, Minimalism",Hero-Centric Design + Social Proof,User Behavior Analytics,Soft pastels (Pink #FFB6C1 Sage #90EE90) + Cream + Gold accents,Calming aesthetic. Booking system. Service menu. Before/after gallery. Testimonials. Relaxing imagery.
33,Luxury/Premium Brand,"brand, elegant, exclusive, high-end, luxury, premium",Liquid Glass + Glassmorphism,"Minimalism, 3D & Hyperrealism",Storytelling-Driven + Feature-Rich,Sales Intelligence Dashboard,Black + Gold (#FFD700) + White + Minimal accent,Elegance paramount. Premium imagery. Storytelling. High-quality visuals. Exclusive feel.
34,Restaurant/Food Service,"appointment, booking, consultation, delivery, food, menu, order, restaurant, service",Vibrant & Block-based + Motion-Driven,"Claymorphism, Flat Design",Hero-Centric Design + Conversion,N/A - Booking focused,Warm colors (Orange Red Brown) + appetizing imagery,Menu display. Online ordering. Reservation system. Food photography. Location/hours prominent.
34,Restaurant/Food Service,"restaurant, menu, order, food, dining, reservation, delivery, cuisine, chef, table, takeaway, eatery",Vibrant & Block-based + Motion-Driven,"Claymorphism, Flat Design",Hero-Centric Design + Conversion,N/A - Booking focused,Warm colors (Orange Red Brown) + appetizing imagery,Menu display. Online ordering. Reservation system. Food photography. Location/hours prominent.
35,Fitness/Gym App,"app, exercise, fitness, gym, health, workout",Vibrant & Block-based + Dark Mode (OLED),"Motion-Driven, Neumorphism",Feature-Rich Showcase,User Behavior Analytics,Energetic (Orange #FF6B35 Electric Blue) + Dark bg,Progress tracking. Workout plans. Community features. Achievements. Motivational design.
36,Real Estate/Property,"buy, estate, housing, property, real, real-estate, rent",Glassmorphism + Minimalism,"Motion-Driven, 3D & Hyperrealism",Hero-Centric Design + Feature-Rich,Sales Intelligence Dashboard,Trust Blue (#0077B6) + Gold accents + White,Property listings. Virtual tours. Map integration. Agent profiles. Mortgage calculator. High-quality imagery.
37,Travel/Tourism Agency,"agency, booking, creative, design, flight, hotel, marketing, studio, tourism, travel, vacation",Aurora UI + Motion-Driven,"Vibrant & Block-based, Glassmorphism",Storytelling-Driven + Hero-Centric,Booking Analytics,Vibrant destination colors + Sky Blue + Warm accents,Destination showcase. Booking system. Itinerary builder. Reviews. Inspiration galleries. Mobile-first.
37,Travel/Tourism Agency,"travel, tourism, vacation, flight, hotel, destination, adventure, cruise, safari, backpacking, guided-tour, holiday-package",Aurora UI + Motion-Driven,"Vibrant & Block-based, Glassmorphism",Storytelling-Driven + Hero-Centric,Booking Analytics,Vibrant destination colors + Sky Blue + Warm accents,Destination showcase. Booking system. Itinerary builder. Reviews. Inspiration galleries. Mobile-first.
38,Hotel/Hospitality,"hospitality, hotel",Liquid Glass + Minimalism,"Glassmorphism, Soft UI Evolution",Hero-Centric Design + Social Proof,Revenue Management Dashboard,Warm neutrals + Gold (#D4AF37) + Brand accent,Room booking. Amenities showcase. Location maps. Guest reviews. Seasonal pricing. Luxury imagery.
39,Wedding/Event Planning,"conference, event, meetup, planning, registration, ticket, wedding",Soft UI Evolution + Aurora UI,"Glassmorphism, Motion-Driven",Storytelling-Driven + Social Proof,N/A - Planning focused,Soft Pink (#FFD6E0) + Gold + Cream + Sage,Portfolio gallery. Vendor directory. Planning tools. Timeline. Budget tracker. Romantic aesthetic.
40,Legal Services,"appointment, attorney, booking, compliance, consultation, contract, law, legal, service, services",Trust & Authority + Minimalism,"Accessible & Ethical, Swiss Modernism 2.0",Trust & Authority + Minimal,Case Management Dashboard,Navy Blue (#1E3A5F) + Gold + White,Credibility paramount. Practice areas. Attorney profiles. Case results. Contact forms. Professional imagery.
40,Legal Services,"law, attorney, legal, case, compliance, contract, court, firm, counsel, litigation, practice-area, jurisdiction",Trust & Authority + Minimalism,"Accessible & Ethical, Swiss Modernism 2.0",Trust & Authority + Minimal,Case Management Dashboard,Navy Blue (#1E3A5F) + Gold + White,Credibility paramount. Practice areas. Attorney profiles. Case results. Contact forms. Professional imagery.
41,Insurance Platform,"insurance, platform",Trust & Authority + Flat Design,"Accessible & Ethical, Minimalism",Conversion-Optimized + Trust,Claims Analytics Dashboard,Trust Blue (#0066CC) + Green (security) + Neutral,Quote calculator. Policy comparison. Claims process. Trust signals. Clear pricing. Security badges.
42,Banking/Traditional Finance,"banking, finance, traditional",Minimalism + Accessible & Ethical,"Trust & Authority, Dark Mode (OLED)",Trust & Authority + Feature-Rich,Financial Dashboard,Navy (#0A1628) + Trust Blue + Gold accents,Security-first. Account overview. Transaction history. Mobile banking. Accessibility critical. Trust paramount.
43,Online Course/E-learning,"course, e, learning, online",Claymorphism + Vibrant & Block-based,"Motion-Driven, Flat Design",Feature-Rich Showcase + Social Proof,Education Dashboard,Vibrant learning colors + Progress green,Course catalog. Progress tracking. Video player. Quizzes. Certificates. Community forums. Gamification.
@ -53,7 +53,7 @@ No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing P
52,Automotive/Car Dealership,"automotive, car, dealership",Motion-Driven + 3D & Hyperrealism,"Dark Mode (OLED), Glassmorphism",Hero-Centric Design + Feature-Rich,Sales Intelligence Dashboard,Brand colors + Metallic accents + Dark/Light,Vehicle showcase. 360° views. Comparison tools. Financing calculator. Test drive booking. High-quality imagery.
53,Photography Studio,"photography, studio",Motion-Driven + Minimalism,"Aurora UI, Glassmorphism",Storytelling-Driven + Hero-Centric,N/A - Portfolio focused,Black + White + Minimal accent,Portfolio gallery. Before/after. Service packages. Booking system. Client galleries. Full-bleed imagery.
54,Coworking Space,"coworking, space",Vibrant & Block-based + Glassmorphism,"Minimalism, Motion-Driven",Hero-Centric Design + Feature-Rich,Occupancy Dashboard,Energetic colors + Wood tones + Brand accent,Space tour. Membership plans. Booking system. Amenities. Community events. Virtual tour.
55,Home Services (Plumber/Electrician),"appointment, booking, consultation, electrician, home, plumber, service, services",Flat Design + Trust & Authority,"Minimalism, Accessible & Ethical",Conversion-Optimized + Trust,Service Analytics,Trust Blue + Safety Orange + Professional grey,Service list. Emergency contact. Booking. Price transparency. Certifications. Local trust signals.
55,Home Services (Plumber/Electrician),"plumber, electrician, hvac, handyman, repair, maintenance, home, emergency, leak, wiring, inspection, licensed",Flat Design + Trust & Authority,"Minimalism, Accessible & Ethical",Conversion-Optimized + Trust,Service Analytics,Trust Blue + Safety Orange + Professional grey,Service list. Emergency contact. Booking. Price transparency. Certifications. Local trust signals.
56,Childcare/Daycare,"childcare, daycare",Claymorphism + Vibrant & Block-based,"Soft UI Evolution, Accessible & Ethical",Social Proof-Focused + Trust,Parent Dashboard,Playful pastels + Safe colors + Warm accents,Programs. Staff profiles. Safety certifications. Parent portal. Activity updates. Cheerful imagery.
57,Senior Care/Elderly,"care, elderly, senior",Accessible & Ethical + Soft UI Evolution,"Minimalism, Neumorphism",Trust & Authority + Social Proof,Healthcare Analytics,Calm Blue + Warm neutrals + Large text,Care services. Staff qualifications. Facility tour. Family portal. Large touch targets. High contrast. Accessibility-first.
58,Medical Clinic,"clinic, medical",Accessible & Ethical + Minimalism,"Neumorphism, Trust & Authority",Trust & Authority + Conversion,Healthcare Analytics,Medical Blue (#0077B6) + Trust White + Calm Green,Services. Doctor profiles. Online booking. Patient portal. Insurance info. HIPAA compliant. Trust signals.
@ -67,7 +67,7 @@ No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing P
66,News/Media Platform,"content, entertainment, media, news, platform, streaming, video",Minimalism + Flat Design,"Dark Mode (OLED), Accessible & Ethical",Hero-Centric Design + Feature-Rich,Media Analytics Dashboard,Brand colors + High contrast + Category colors,Article layout. Breaking news. Categories. Search. Subscription. Mobile reading. Fast loading.
67,Magazine/Blog,"articles, blog, content, magazine, posts, writing",Swiss Modernism 2.0 + Motion-Driven,"Minimalism, Aurora UI",Storytelling-Driven + Hero-Centric,Content Analytics,Editorial colors + Brand primary + Clean white,Article showcase. Category navigation. Author profiles. Newsletter signup. Related content. Typography-focused.
68,Freelancer Platform,"freelancer, platform",Flat Design + Minimalism,"Vibrant & Block-based, Micro-interactions",Feature-Rich Showcase + Conversion,Marketplace Analytics,Professional Blue + Success Green + Neutral,Profile creation. Portfolio. Skill matching. Messaging. Payment. Reviews. Project management.
69,Marketing Agency,"agency, creative, design, marketing, studio",Brutalism + Motion-Driven,"Vibrant & Block-based, Aurora UI",Storytelling-Driven + Feature-Rich,Campaign Analytics,Bold brand colors + Creative freedom,Portfolio. Case studies. Services. Team. Creative showcase. Results-focused. Bold aesthetic.
69,Marketing Agency,"campaign, ads, growth, roi, seo, sem, ppc, social-media, conversion-funnel, ab-test, attribution, performance-marketing",Brutalism + Motion-Driven,"Vibrant & Block-based, Aurora UI",Storytelling-Driven + Feature-Rich,Campaign Analytics,Bold brand colors + Creative freedom,Portfolio. Case studies. Services. Team. Creative showcase. Results-focused. Bold aesthetic.
70,Event Management,"conference, event, management, meetup, registration, ticket",Vibrant & Block-based + Motion-Driven,"Glassmorphism, Aurora UI",Hero-Centric Design + Feature-Rich,Event Analytics,Event theme colors + Excitement accents,Event showcase. Registration. Agenda. Speakers. Sponsors. Ticket sales. Countdown timer.
71,Membership/Community,"community, membership",Vibrant & Block-based + Soft UI Evolution,"Bento Box Grid, Micro-interactions",Social Proof-Focused + Conversion,Community Analytics,Community brand colors + Engagement accents,Member benefits. Pricing tiers. Community showcase. Events. Member directory. Exclusive content.
72,Newsletter Platform,"newsletter, platform",Minimalism + Flat Design,"Swiss Modernism 2.0, Accessible & Ethical",Minimal & Direct + Conversion,Email Analytics,Brand primary + Clean white + CTA accent,Subscribe form. Archive. About. Social proof. Sample content. Simple conversion.
@ -160,3 +160,34 @@ No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing P
159,Wallpaper & Theme App,"wallpaper, theme, background, customize, aesthetic, home-screen, lock-screen, widget, design, zedge",Vibrant & Block-based + Aurora UI,"Glassmorphism, Motion-Driven",Feature-Rich Showcase + Social Proof,N/A - Gallery focused,Content-driven + trending aesthetic palettes + download accent,Category browsing. Preview on device. Daily wallpaper auto-set. Widget matching. Creator uploads. Resolution auto-fit.
160,White Noise & Ambient Sound,"white noise, ambient, sound, sleep, focus, rain, nature, relax, concentration, background, noisli",Minimalism + Dark Mode (OLED),"Neumorphism, Organic Biophilic",Minimal & Direct + Social Proof,N/A - Player focused,Calming dark + ambient texture visual + subtle sound wave + sleep blue,Sound mixer with multiple simultaneous layers. Sleep timer with fade. Custom soundscapes. Offline. Background audio.
161,Home Decoration & Interior Design,"home, interior, decor, design, furniture, room, renovation, ar, plan, inspire, 3d, houzz",Minimalism + 3D Product Preview,"Organic Biophilic, Aurora UI",Storytelling-Driven + Feature-Rich,N/A - Project focused,Neutral interior palette + material texture accent + AR blue,AR room visualization. Style quiz. Product catalog with purchase links. 3D room planner. Mood board. Before/after.
162,Academic Journal / Scholarly Publishing,"academic, journal, paper, research, peer-review, open-access, scholarly, publication, citation, manuscript, issn, doi",Swiss Modernism 2.0 + Minimalism,"Trust & Authority, Accessible & Ethical",Content-Index + Search,N/A - Publication focused,Trust navy + White + Citation blue + Serif accents,"Prioritize readability (serif body text). Clear article hierarchy. Abstract/DOI prominence. WCAG AAA. Minimal visual noise. Trust signals: ISSN, indexing badges."
163,API Developer Portal,"api, developer, documentation, sdk, endpoint, integration, rest, graphql, webhook, reference, getting-started, auth",Trust & Authority + Minimalism,"Glassmorphism, Dark Mode (OLED)",Quick Start + Interactive Docs,N/A - Documentation focused,Dark code theme + Brand accent + Syntax colors,Endpoint discoverability. Copy-paste code samples. Auth flow clarity. Version switching. Interactive playground. Rate limit visibility.
164,Forum / Discussion Board,"forum, discussion, thread, post, reply, community, comment, moderation, subreddit, stackexchange, topic",Dark Mode (OLED) + Minimalism,"Flat Design, Vibrant & Block-based",Feed + Thread View,N/A - Discussion focused,Dark neutral + topic accent colors + unread indicator + reputation badge,Thread list with pagination. Rich text editor. Quote/mention system. Upvote/downvote. User badges. Moderation tools.
165,Directory / Listing Site,"directory, listing, classifieds, catalogue, business-directory, yellow-pages, venue, find, search, filter, map",Flat Design + Vibrant & Block-based,"Minimalism, Trust & Authority",Filter-Heavy Grid + Map,N/A - Listing focused,Neutral bg + category color chips + map accent + verified badge,Category tree. Multi-filter sidebar. Map/list toggle. Verified badges. Reviews. Claim listing flow.
166,Status Page / Incident Management,"status, incident, outage, uptime, downtime, statuspage, monitoring, sla, maintenance, sev1, postmortem",Data-Dense + Trust & Authority,"Minimalism, Dark Mode (OLED)",Timeline + Severity Indicators,Real-Time Monitoring + Timeline,Status green + incident red + maintenance amber + neutral dark,Service status matrix. Incident timeline. Severity badges. Maintenance schedule. SLA uptime history. Email/SMS subscribe.
167,Wiki / Encyclopedia,"wiki, encyclopedia, knowledge, article, reference, wikipedia, documentation, collaborative, edit, version, citation",Minimalism + Flat Design,"Swiss Modernism 2.0, Accessible & Ethical",Search-First + Hierarchical Navigation,N/A - Reference focused,Clean white + link blue + heading hierarchy + citation grey,Full-text search bar. Table of contents sidebar. Edit history. Inter-page linking. Mobile responsive. Print-friendly.
168,Auction Platform,"auction, bid, hammer, lot, live-auction, bidding-war, estate-sale, proxibid, gavel, lot-number, reserve-price",Dark Mode (OLED) + Motion-Driven,"Vibrant & Block-based, Real-Time Monitor",Live Auction Feed + Countdown,N/A - Auction focused,Dark bg + bid green + outbid red + countdown amber,Real-time bid updates. Countdown timer urgency. Auto-bid ceiling. Outbid notifications. Bid history. Reserve price indicator.
169,Changelog / Release Notes,"changelog, release-notes, version-history, whats-new, product-updates, semver, patch-notes, release-tracker",Minimalism + Flat Design,"Swiss Modernism 2.0, Trust & Authority",Timeline + Version List,N/A - Documentation focused,"Neutral bg + version badge colors (feat=green, fix=blue, breaking=red) + date grey",Chronological release feed. Semver badges. Breaking change warnings. Copy-paste install commands. Subscribe to feed. Search by version.
170,Citizen Science Platform,"citizen-science, zooniverse, crowdsourced-research, volunteer-science, public-participation, distributed-research, citizen-researcher",Organic Biophilic + Vibrant & Block-based,"Claymorphism, Motion-Driven",Storytelling-Driven + Social Proof,Project Participation Dashboard,Earth green + discovery orange + volunteer badge blue + data neutral,Project cards with impact metrics. Contribution tracker. Beginner-friendly onboarding. Data quality feedback loop. Leaderboards. Community forums.
171,Classifieds / Buy-Sell,"classifieds, buy-sell, craigslist, secondhand, marketplace-listing, for-sale, trade, flea-market, thrift, resell",Flat Design + Vibrant & Block-based,"Minimalism, Trust & Authority",Filter-Heavy Grid + Map,N/A - Listing focused,Neutral bg + price green + category chips + verified seller badge,Category tree. Photo-first listing cards. Price negotiation. Location radius filter. Saved searches. Seller reputation. Flag/report.
172,Conference / Symposium Landing Page,"conference, symposium, summit, cfp, call-for-papers, speaker-lineup, registration, venue, proceedings, keynote, track",Swiss Modernism 2.0 + Minimalism,"Trust & Authority, Accessible & Ethical",Hero + Agenda + CFP,N/A - Event focused,Academic navy + track color chips + gold keynote + neutral white,Speaker grid. Multi-track agenda. CFP deadline countdown. Venue map. Sponsor tiers. Early-bird pricing. Proceedings download.
173,Crowdfunding Platform,"crowdfunding, kickstarter, indiegogo, campaign, backer, pledge, funding-goal, stretch-goal, reward-tier, all-or-nothing",Vibrant & Block-based + Motion-Driven,"Claymorphism, Storytelling-Driven",Storytelling-Driven + Social Proof,Campaign Analytics Dashboard,Brand primary + funding progress green + urgency amber + reward tier colors,Funding progress bar with % goal. Reward tier selector. Backer count. Countdown timer. Updates feed. Creator profile. Risk/disclaimer section.
174,Digital Signage / Kiosk,"digital-signage, kiosk, interactive-display, touchscreen, wayfinding, lobby-display, menu-board, point-of-sale-display",Minimalism + Dark Mode (OLED),"Flat Design, Motion-Driven",Full-Screen Immersive,N/A - Display focused,High contrast + brand accent + touch target emphasis (56px min),Full-screen single-purpose layout. Touch targets ≥56px. Auto-rotate content. Offline fallback. Brightness-aware color palette. No scroll.
175,E-signature / Document Workflow,"esignature, e-sign, docusign, digital-signature, document-workflow, approval-chain, contract-signing, signing-ceremony",Trust & Authority + Minimalism,"Accessible & Ethical, Flat Design",Feature-Rich Showcase + Conversion,Document Pipeline Dashboard,Trust navy + signature green + pending amber + neutral grey,Document preview with annotation. Signature placement UI. Multi-signer workflow. Audit trail. Compliance badges. Mobile signing. Expiry reminders.
176,Feature Flag / Config Management,"feature-flag, config, launchdarkly, feature-toggle, experiment, rollout, kill-switch, a-b-test-config, percentage-rollout",Dark Mode (OLED) + Data-Dense,"Minimalism, Trust & Authority",Feature List + Toggle Panel,N/A - Config focused,Dark bg + enabled green + disabled grey + experimental amber + kill-switch red,Feature list with on/off toggles. Percentage rollout slider. Environment selector (prod/staging). User targeting rules. Kill switch. Audit log.
177,Government Portal / Civic Services,"government-portal, civic-services, city-hall, permit-application, tax-payment, voter-registration, public-records, municipal-online",Accessible & Ethical + Trust & Authority,"Flat Design, Inclusive Design",Service Directory + Search,N/A - Service focused,Professional blue + accessibility high contrast + service category colors,Multilingual toggle. Service A-Z index. Form wizard with save-progress. Document upload. Appointment booking. Status tracker. WCAG AAA. Plain language.
178,Grant / Funding Portal,"grant, funding, rfp, proposal, research-grant, foundation, fellowship, award, application-portal, funding-opportunity",Trust & Authority + Minimalism,"Accessible & Ethical, Swiss Modernism 2.0",Opportunity Grid + Search,Application Tracking Dashboard,Institution navy + funding green + deadline red + neutral white,Funding opportunity cards. Eligibility checker. Deadline countdown. Application form wizard. Document checklist. Review status tracker. Award announcement feed.
179,LMS (Learning Management System),"lms, course-management, learning-management, canvas, moodle, blackboard, enrollment, gradebook, syllabus, assignment-submit",Flat Design + Accessible & Ethical,"Minimalism, Vibrant & Block-based",Dashboard + Course Grid,Education Analytics Dashboard,Calm blue + course category colors + grade green + alert red,Dashboard with enrolled courses. Assignment deadlines. Gradebook view. Discussion forums. File upload. Calendar integration. Mobile offline sync.
180,No-code / Low-code Builder,"no-code, low-code, builder, bubble, webflow, drag-drop, visual-builder, app-builder, workflow-builder, logic-blocks",Vibrant & Block-based + Bento Box Grid,"Motion-Driven, Glassmorphism",Interactive Product Demo,App Builder Workspace,Brand primary + component palette colors + canvas neutral + connect blue,Drag-drop canvas. Component library sidebar. Logic flow visual editor. Preview pane. Template gallery. Publish button. Version history.
181,Open Source Project Landing,"open-source, github-project, oss, contributor, star, fork, pull-request, maintainer, sponsoring, readme, repository",Dark Mode (OLED) + Minimalism,"Trust & Authority, Flat Design",Hero + Install + Contribute,Contributor Analytics Dashboard,Dark bg + language color bar + star gold + fork silver + sponsor purple,Star/fork count badges. Install command (copy-paste). Language breakdown bar. Top contributors grid. Sponsor CTA. Documentation link. Issue/pr status.
182,Patient Portal / Health Records,"patient-portal, health-records, ehr, emr, mychart, lab-results, prescription-refill, medical-history, test-results, care-team",Trust & Authority + Accessible & Ethical,"Minimalism, Flat Design",Health Summary Dashboard,Healthcare Analytics,Clinical blue + health green + alert red + calm white + accessible contrast,Labs and results timeline. Medication list with refill. Appointment scheduling. Message care team. Immunization records. Allergy alerts. Family access proxy.
183,Patent / IP Database,"patent, intellectual-property, trademark, prior-art, uspto, wipo, invention, ip-portfolio, patent-search, claims",Swiss Modernism 2.0 + Minimalism,"Trust & Authority, Data-Dense",Search-First + Results Grid,N/A - Search focused,Formal neutral + patent type chips + status badges (granted/pending/rejected),Full-text patent search. Classification tree. Citation graph. Prior art comparison. Patent family view. PDF download. Legal status tracker.
184,Q&A Community Platform,"qa, stack-overflow, question-answer, knowledge-sharing, community-qa, expert-answer, upvote, accepted-answer, reputation",Minimalism + Flat Design,"Dark Mode (OLED), Accessible & Ethical",Feed + Thread View,Community Analytics Dashboard,Clean white + upvote orange + accepted green + reputation gold + tag colors,Question list with vote count. Rich code blocks. Tag filter. Reputation system. Accepted answer highlight. Comment threads. Bookmark/save.
185,Research Lab / University Department,"research-lab, university-department, academic-lab, principal-investigator, lab-members, publications, research-group, pi-page",Swiss Modernism 2.0 + Minimalism,"Trust & Authority, Accessible & Ethical",Overview + People + Publications,N/A - Academic focused,Institutional navy + white + research area accent colors + serif headings,PI bio and research focus. Current members grid. Publication list with links. Open positions. Lab facilities photos. Funding acknowledgments.
186,Resume / CV Builder,"resume, cv, builder, job-search, curriculum-vitae, portfolio-resume, cover-letter, career-builder, ats-friendly",Minimalism + Flat Design,"Swiss Modernism 2.0, Trust & Authority",Interactive Product Demo + CTA,Template Selection Gallery,Professional navy + section accent + success green + clean white,Template picker. Section-by-section editor. Real-time preview. ATS score indicator. PDF export. Cover letter generator. Import from LinkedIn.
187,Review Platform,"review, rating, yelp, trustpilot, testimonial, customer-review, star-rating, verified-purchase, pros-cons",Flat Design + Vibrant & Block-based,"Trust & Authority, Minimalism",Hero + Rating Summary + Review Feed,Review Analytics Dashboard,Brand primary + star gold + positive green + negative red + verified blue,Star rating summary with distribution. Verified purchase badge. Photo/video reviews. Helpful/upvote. Filter by rating. Response from business. Sort by recency.
188,RPA / Automation Dashboard,"rpa, robotic-process-automation, uipath, automation-anywhere, bot-orchestrator, process-discovery, attended-bot, unattended-bot",Dark Mode (OLED) + Data-Dense,"Minimalism, Trust & Authority",Bot Fleet Dashboard,Real-Time Monitoring + Process Analytics,Dark bg + running green + failed red + queued amber + completed blue,Bot status grid (running/idle/failed). Queue depth. Process flow visualization. Exception handling alert. ROI metrics. Bot scheduling calendar. Audit trail.
189,Survey / Form Builder,"survey, form-builder, questionnaire, typeform, survey-monkey, poll, feedback-form, multi-step-form, nps-survey, logic-jump",Minimalism + Micro-interactions,"Claymorphism, Flat Design",Interactive Product Demo,Response Analytics Dashboard,Clean white + question accent + progress green + submit blue,Drag-drop form builder. Question type library. Conditional logic visualizer. Theme picker. Response dashboard with charts. Export CSV. Share link/QR/embed.
190,Telemedicine Platform,"telemedicine, telehealth, virtual-visit, remote-consultation, video-doctor, remote-patient-monitoring, telehealth-app",Neumorphism + Accessible & Ethical,"Trust & Authority, Soft UI Evolution",Trust & Authority + Conversion,Healthcare Analytics,Calm medical blue + video green + waiting amber + trust white,Video call UI with screen share. Appointment queue. Symptom intake form. Prescription e-delivery. Waiting room with ETA. Post-visit summary. Insurance verification.
191,Testimonial & Social Proof Widget,"testimonial, social-proof, wall-of-love, customer-quote, case-study, review-widget, trust-signal, user-story",Vibrant & Block-based + Flat Design,"Motion-Driven, Minimalism",Wall-of-Love Grid,Engagement Analytics Dashboard,Brand primary + quote accent + star gold + verified blue,Testimonial cards with photo. Star ratings. Video testimonials. Case study summaries. Filter by industry/product. Embeddable widget code. Auto-rotate carousel.
192,Ticketing / Box Office,"ticketing, box-office, eventbrite, ticket-sales, seat-selection, will-call, qr-ticket, venue-capacity, will-call-pickup",Vibrant & Block-based + Motion-Driven,"Dark Mode (OLED), Glassmorphism",Event Grid + Seat Map,Sales Analytics Dashboard,Event theme colors + available green + sold-out red + seat map neutral,Event cards with date/venue. Interactive seat map. Cart with countdown. QR code ticket. Will-call pickup. Group discounts. Refund policy.

1 No Product Type Keywords Primary Style Recommendation Secondary Styles Landing Page Pattern Dashboard Style (if applicable) Color Palette Focus Key Considerations
2 1 SaaS (General) app, b2b, cloud, general, saas, software, subscription Glassmorphism + Flat Design Soft UI Evolution, Minimalism Hero + Features + CTA Data-Dense + Real-Time Monitoring Trust blue + accent contrast Balance modern feel with clarity. Focus on CTAs.
3 2 Micro SaaS app, b2b, cloud, indie, micro, micro-saas, niche, saas, small, software, solo, subscription indie, micro-saas, niche, solo, bootstrap, micro, side-project, solopreneur, small-team, indie-hacker, product-hunt Flat Design + Vibrant & Block Motion-Driven, Micro-interactions Minimal & Direct + Demo Executive Dashboard Vibrant primary + white space Keep simple, show product quickly. Speed is key.
4 3 E-commerce buy, commerce, e, ecommerce, products, retail, sell, shop, store Vibrant & Block-based Aurora UI, Motion-Driven Feature-Rich Showcase Sales Intelligence Dashboard Brand primary + success green Engagement & conversions. High visual hierarchy.
5 4 E-commerce Luxury buy, commerce, e, ecommerce, elegant, exclusive, high-end, luxury, premium, products, retail, sell, shop, store Liquid Glass + Glassmorphism 3D & Hyperrealism, Aurora UI Feature-Rich Showcase Sales Intelligence Dashboard Premium colors + minimal accent Elegance & sophistication. Premium materials.
6 5 B2B Service appointment, b, b2b, booking, business, consultation, corporate, enterprise, service b2b, enterprise, consulting, professional, solution, contract, corporate, strategy, advisory, roi, deliverable, whitepaper Trust & Authority + Minimal Feature-Rich, Conversion-Optimized Feature-Rich Showcase Sales Intelligence Dashboard Professional blue + neutral grey Credibility essential. Clear ROI messaging.
7 6 Financial Dashboard admin, analytics, dashboard, data, financial, panel portfolio, trading, pnl, budget, revenue, expense, cashflow, balance-sheet, investment, bank, accounting, fintech Dark Mode (OLED) + Data-Dense Minimalism, Accessible & Ethical N/A - Dashboard focused Financial Dashboard Dark bg + red/green alerts + trust blue High contrast, real-time updates, accuracy paramount.
8 7 Analytics Dashboard admin, analytics, dashboard, data, panel kpi, metric, funnel, conversion, cohort, retention, segment, attribution, ab-test, dashboard-data, business-intelligence Data-Dense + Heat Map & Heatmap Minimalism, Dark Mode (OLED) N/A - Analytics focused Drill-Down Analytics + Comparative Cool→Hot gradients + neutral grey Clarity > aesthetics. Color-coded data priority.
9 8 Healthcare App app, clinic, health, healthcare, medical, patient Neumorphism + Accessible & Ethical Soft UI Evolution, Claymorphism (for patients) Social Proof-Focused User Behavior Analytics Calm blue + health green + trust Accessibility mandatory. Calming aesthetic.
10 9 Educational App app, course, education, educational, learning, school, training Claymorphism + Micro-interactions Vibrant & Block-based, Flat Design Storytelling-Driven User Behavior Analytics Playful colors + clear hierarchy Engagement & ease of use. Age-appropriate design.
11 10 Creative Agency agency, creative, design, marketing, studio branding, identity, portfolio, logo, visual, rebrand, creative-director, campaign, awards, award-winning, showreel Brutalism + Motion-Driven Retro-Futurism, Storytelling-Driven Storytelling-Driven N/A - Portfolio focused Bold primaries + artistic freedom Differentiation key. Wow-factor necessary.
12 11 Portfolio/Personal creative, personal, portfolio, projects, showcase, work Motion-Driven + Minimalism Brutalism, Aurora UI Storytelling-Driven N/A - Personal branding Brand primary + artistic interpretation Showcase work. Personality shine through.
13 12 Gaming entertainment, esports, game, gaming, play 3D & Hyperrealism + Retro-Futurism Motion-Driven, Vibrant & Block Feature-Rich Showcase N/A - Game focused Vibrant + neon + immersive colors Immersion priority. Performance critical.
14 13 Government/Public Service appointment, booking, consultation, government, public, service government, civic, municipal, federal, citizen, public, administration, permit, tax, voter, transparency, regulation Accessible & Ethical + Minimalism Flat Design, Inclusive Design Minimal & Direct Executive Dashboard Professional blue + high contrast WCAG AAA mandatory. Trust paramount.
15 14 Fintech/Crypto banking, blockchain, crypto, defi, finance, fintech, money, nft, payment, web3 Glassmorphism + Dark Mode (OLED) Retro-Futurism, Motion-Driven Conversion-Optimized Real-Time Monitoring + Predictive Dark tech colors + trust + vibrant accents Security perception. Real-time data critical.
16 15 Social Media App app, community, content, entertainment, media, network, sharing, social, streaming, users, video Vibrant & Block-based + Motion-Driven Aurora UI, Micro-interactions Feature-Rich Showcase User Behavior Analytics Vibrant + engagement colors Engagement & retention. Addictive design ethics.
17 16 Productivity Tool collaboration, productivity, project, task, tool, workflow Flat Design + Micro-interactions Minimalism, Soft UI Evolution Interactive Product Demo Drill-Down Analytics Clear hierarchy + functional colors Ease of use. Speed & efficiency focus.
24 23 Pet Tech App app, pet, tech Claymorphism + Vibrant & Block-based Micro-interactions, Flat Design Storytelling-Driven User Behavior Analytics Playful + Warm colors Pet profiles. Health tracking. Playful UI. Photo galleries. Vet integration.
25 24 Smart Home/IoT Dashboard admin, analytics, dashboard, data, home, iot, panel, smart Glassmorphism + Dark Mode (OLED) Minimalism, AI-Native UI Interactive Product Demo Real-Time Monitoring Dark + Status indicator colors Device status. Real-time controls. Energy monitoring. Automation rules. Quick actions.
26 25 EV/Charging Ecosystem charging, ecosystem, ev Minimalism + Aurora UI Glassmorphism, Organic Biophilic Hero-Centric Design Energy/Utilities Dashboard Electric Blue (#009CD1) + Green Charging station maps. Range estimation. Cost calculation. Environmental impact.
27 26 Subscription Box Service appointment, booking, box, consultation, membership, plan, recurring, service, subscription subscription, box, recurring, membership, unboxing, curated, plan, monthly, surprise, product-box Vibrant & Block-based + Motion-Driven Claymorphism, Aurora UI Feature-Rich Showcase E-commerce Analytics Brand + Excitement colors Unboxing experience. Personalization quiz. Subscription management. Product reveals.
28 27 Podcast Platform platform, podcast Dark Mode (OLED) + Minimalism Motion-Driven, Vibrant & Block-based Storytelling-Driven Media/Entertainment Dashboard Dark + Audio waveform accents Audio player UX. Episode discovery. Creator tools. Analytics for podcasters.
29 28 Dating App app, dating Vibrant & Block-based + Motion-Driven Aurora UI, Glassmorphism Social Proof-Focused User Behavior Analytics Warm + Romantic (Pink/Red gradients) Profile cards. Swipe interactions. Match animations. Safety features. Video chat.
30 29 Micro-Credentials/Badges Platform badges, credentials, micro, platform Minimalism + Flat Design Accessible & Ethical, Swiss Modernism 2.0 Trust & Authority Education Dashboard Trust Blue + Gold (#FFD700) Credential verification. Badge display. Progress tracking. Issuer trust. LinkedIn integration.
31 30 Knowledge Base/Documentation base, documentation, knowledge Minimalism + Accessible & Ethical Swiss Modernism 2.0, Flat Design FAQ/Documentation N/A - Documentation focused Clean hierarchy + minimal color Search-first. Clear navigation. Code highlighting. Version switching. Feedback system.
32 31 Hyperlocal Services appointment, booking, consultation, hyperlocal, service, services hyperlocal, local, neighborhood, nearby, community, nearby, zip, map, local-business, geo-target, city Minimalism + Vibrant & Block-based Micro-interactions, Flat Design Conversion-Optimized Drill-Down Analytics + Map Location markers + Trust colors Map integration. Service categories. Provider profiles. Booking system. Reviews.
33 32 Beauty/Spa/Wellness Service appointment, beauty, booking, consultation, service, spa, wellness spa, beauty, salon, wellness, treatment, relaxation, massage, skincare, facial, aesthetic, self-care, pamper Soft UI Evolution + Neumorphism Glassmorphism, Minimalism Hero-Centric Design + Social Proof User Behavior Analytics Soft pastels (Pink #FFB6C1 Sage #90EE90) + Cream + Gold accents Calming aesthetic. Booking system. Service menu. Before/after gallery. Testimonials. Relaxing imagery.
34 33 Luxury/Premium Brand brand, elegant, exclusive, high-end, luxury, premium Liquid Glass + Glassmorphism Minimalism, 3D & Hyperrealism Storytelling-Driven + Feature-Rich Sales Intelligence Dashboard Black + Gold (#FFD700) + White + Minimal accent Elegance paramount. Premium imagery. Storytelling. High-quality visuals. Exclusive feel.
35 34 Restaurant/Food Service appointment, booking, consultation, delivery, food, menu, order, restaurant, service restaurant, menu, order, food, dining, reservation, delivery, cuisine, chef, table, takeaway, eatery Vibrant & Block-based + Motion-Driven Claymorphism, Flat Design Hero-Centric Design + Conversion N/A - Booking focused Warm colors (Orange Red Brown) + appetizing imagery Menu display. Online ordering. Reservation system. Food photography. Location/hours prominent.
36 35 Fitness/Gym App app, exercise, fitness, gym, health, workout Vibrant & Block-based + Dark Mode (OLED) Motion-Driven, Neumorphism Feature-Rich Showcase User Behavior Analytics Energetic (Orange #FF6B35 Electric Blue) + Dark bg Progress tracking. Workout plans. Community features. Achievements. Motivational design.
37 36 Real Estate/Property buy, estate, housing, property, real, real-estate, rent Glassmorphism + Minimalism Motion-Driven, 3D & Hyperrealism Hero-Centric Design + Feature-Rich Sales Intelligence Dashboard Trust Blue (#0077B6) + Gold accents + White Property listings. Virtual tours. Map integration. Agent profiles. Mortgage calculator. High-quality imagery.
38 37 Travel/Tourism Agency agency, booking, creative, design, flight, hotel, marketing, studio, tourism, travel, vacation travel, tourism, vacation, flight, hotel, destination, adventure, cruise, safari, backpacking, guided-tour, holiday-package Aurora UI + Motion-Driven Vibrant & Block-based, Glassmorphism Storytelling-Driven + Hero-Centric Booking Analytics Vibrant destination colors + Sky Blue + Warm accents Destination showcase. Booking system. Itinerary builder. Reviews. Inspiration galleries. Mobile-first.
39 38 Hotel/Hospitality hospitality, hotel Liquid Glass + Minimalism Glassmorphism, Soft UI Evolution Hero-Centric Design + Social Proof Revenue Management Dashboard Warm neutrals + Gold (#D4AF37) + Brand accent Room booking. Amenities showcase. Location maps. Guest reviews. Seasonal pricing. Luxury imagery.
40 39 Wedding/Event Planning conference, event, meetup, planning, registration, ticket, wedding Soft UI Evolution + Aurora UI Glassmorphism, Motion-Driven Storytelling-Driven + Social Proof N/A - Planning focused Soft Pink (#FFD6E0) + Gold + Cream + Sage Portfolio gallery. Vendor directory. Planning tools. Timeline. Budget tracker. Romantic aesthetic.
41 40 Legal Services appointment, attorney, booking, compliance, consultation, contract, law, legal, service, services law, attorney, legal, case, compliance, contract, court, firm, counsel, litigation, practice-area, jurisdiction Trust & Authority + Minimalism Accessible & Ethical, Swiss Modernism 2.0 Trust & Authority + Minimal Case Management Dashboard Navy Blue (#1E3A5F) + Gold + White Credibility paramount. Practice areas. Attorney profiles. Case results. Contact forms. Professional imagery.
42 41 Insurance Platform insurance, platform Trust & Authority + Flat Design Accessible & Ethical, Minimalism Conversion-Optimized + Trust Claims Analytics Dashboard Trust Blue (#0066CC) + Green (security) + Neutral Quote calculator. Policy comparison. Claims process. Trust signals. Clear pricing. Security badges.
43 42 Banking/Traditional Finance banking, finance, traditional Minimalism + Accessible & Ethical Trust & Authority, Dark Mode (OLED) Trust & Authority + Feature-Rich Financial Dashboard Navy (#0A1628) + Trust Blue + Gold accents Security-first. Account overview. Transaction history. Mobile banking. Accessibility critical. Trust paramount.
44 43 Online Course/E-learning course, e, learning, online Claymorphism + Vibrant & Block-based Motion-Driven, Flat Design Feature-Rich Showcase + Social Proof Education Dashboard Vibrant learning colors + Progress green Course catalog. Progress tracking. Video player. Quizzes. Certificates. Community forums. Gamification.
53 52 Automotive/Car Dealership automotive, car, dealership Motion-Driven + 3D & Hyperrealism Dark Mode (OLED), Glassmorphism Hero-Centric Design + Feature-Rich Sales Intelligence Dashboard Brand colors + Metallic accents + Dark/Light Vehicle showcase. 360° views. Comparison tools. Financing calculator. Test drive booking. High-quality imagery.
54 53 Photography Studio photography, studio Motion-Driven + Minimalism Aurora UI, Glassmorphism Storytelling-Driven + Hero-Centric N/A - Portfolio focused Black + White + Minimal accent Portfolio gallery. Before/after. Service packages. Booking system. Client galleries. Full-bleed imagery.
55 54 Coworking Space coworking, space Vibrant & Block-based + Glassmorphism Minimalism, Motion-Driven Hero-Centric Design + Feature-Rich Occupancy Dashboard Energetic colors + Wood tones + Brand accent Space tour. Membership plans. Booking system. Amenities. Community events. Virtual tour.
56 55 Home Services (Plumber/Electrician) appointment, booking, consultation, electrician, home, plumber, service, services plumber, electrician, hvac, handyman, repair, maintenance, home, emergency, leak, wiring, inspection, licensed Flat Design + Trust & Authority Minimalism, Accessible & Ethical Conversion-Optimized + Trust Service Analytics Trust Blue + Safety Orange + Professional grey Service list. Emergency contact. Booking. Price transparency. Certifications. Local trust signals.
57 56 Childcare/Daycare childcare, daycare Claymorphism + Vibrant & Block-based Soft UI Evolution, Accessible & Ethical Social Proof-Focused + Trust Parent Dashboard Playful pastels + Safe colors + Warm accents Programs. Staff profiles. Safety certifications. Parent portal. Activity updates. Cheerful imagery.
58 57 Senior Care/Elderly care, elderly, senior Accessible & Ethical + Soft UI Evolution Minimalism, Neumorphism Trust & Authority + Social Proof Healthcare Analytics Calm Blue + Warm neutrals + Large text Care services. Staff qualifications. Facility tour. Family portal. Large touch targets. High contrast. Accessibility-first.
59 58 Medical Clinic clinic, medical Accessible & Ethical + Minimalism Neumorphism, Trust & Authority Trust & Authority + Conversion Healthcare Analytics Medical Blue (#0077B6) + Trust White + Calm Green Services. Doctor profiles. Online booking. Patient portal. Insurance info. HIPAA compliant. Trust signals.
67 66 News/Media Platform content, entertainment, media, news, platform, streaming, video Minimalism + Flat Design Dark Mode (OLED), Accessible & Ethical Hero-Centric Design + Feature-Rich Media Analytics Dashboard Brand colors + High contrast + Category colors Article layout. Breaking news. Categories. Search. Subscription. Mobile reading. Fast loading.
68 67 Magazine/Blog articles, blog, content, magazine, posts, writing Swiss Modernism 2.0 + Motion-Driven Minimalism, Aurora UI Storytelling-Driven + Hero-Centric Content Analytics Editorial colors + Brand primary + Clean white Article showcase. Category navigation. Author profiles. Newsletter signup. Related content. Typography-focused.
69 68 Freelancer Platform freelancer, platform Flat Design + Minimalism Vibrant & Block-based, Micro-interactions Feature-Rich Showcase + Conversion Marketplace Analytics Professional Blue + Success Green + Neutral Profile creation. Portfolio. Skill matching. Messaging. Payment. Reviews. Project management.
70 69 Marketing Agency agency, creative, design, marketing, studio campaign, ads, growth, roi, seo, sem, ppc, social-media, conversion-funnel, ab-test, attribution, performance-marketing Brutalism + Motion-Driven Vibrant & Block-based, Aurora UI Storytelling-Driven + Feature-Rich Campaign Analytics Bold brand colors + Creative freedom Portfolio. Case studies. Services. Team. Creative showcase. Results-focused. Bold aesthetic.
71 70 Event Management conference, event, management, meetup, registration, ticket Vibrant & Block-based + Motion-Driven Glassmorphism, Aurora UI Hero-Centric Design + Feature-Rich Event Analytics Event theme colors + Excitement accents Event showcase. Registration. Agenda. Speakers. Sponsors. Ticket sales. Countdown timer.
72 71 Membership/Community community, membership Vibrant & Block-based + Soft UI Evolution Bento Box Grid, Micro-interactions Social Proof-Focused + Conversion Community Analytics Community brand colors + Engagement accents Member benefits. Pricing tiers. Community showcase. Events. Member directory. Exclusive content.
73 72 Newsletter Platform newsletter, platform Minimalism + Flat Design Swiss Modernism 2.0, Accessible & Ethical Minimal & Direct + Conversion Email Analytics Brand primary + Clean white + CTA accent Subscribe form. Archive. About. Social proof. Sample content. Simple conversion.
160 159 Wallpaper & Theme App wallpaper, theme, background, customize, aesthetic, home-screen, lock-screen, widget, design, zedge Vibrant & Block-based + Aurora UI Glassmorphism, Motion-Driven Feature-Rich Showcase + Social Proof N/A - Gallery focused Content-driven + trending aesthetic palettes + download accent Category browsing. Preview on device. Daily wallpaper auto-set. Widget matching. Creator uploads. Resolution auto-fit.
161 160 White Noise & Ambient Sound white noise, ambient, sound, sleep, focus, rain, nature, relax, concentration, background, noisli Minimalism + Dark Mode (OLED) Neumorphism, Organic Biophilic Minimal & Direct + Social Proof N/A - Player focused Calming dark + ambient texture visual + subtle sound wave + sleep blue Sound mixer with multiple simultaneous layers. Sleep timer with fade. Custom soundscapes. Offline. Background audio.
162 161 Home Decoration & Interior Design home, interior, decor, design, furniture, room, renovation, ar, plan, inspire, 3d, houzz Minimalism + 3D Product Preview Organic Biophilic, Aurora UI Storytelling-Driven + Feature-Rich N/A - Project focused Neutral interior palette + material texture accent + AR blue AR room visualization. Style quiz. Product catalog with purchase links. 3D room planner. Mood board. Before/after.
163 162 Academic Journal / Scholarly Publishing academic, journal, paper, research, peer-review, open-access, scholarly, publication, citation, manuscript, issn, doi Swiss Modernism 2.0 + Minimalism Trust & Authority, Accessible & Ethical Content-Index + Search N/A - Publication focused Trust navy + White + Citation blue + Serif accents Prioritize readability (serif body text). Clear article hierarchy. Abstract/DOI prominence. WCAG AAA. Minimal visual noise. Trust signals: ISSN, indexing badges.
164 163 API Developer Portal api, developer, documentation, sdk, endpoint, integration, rest, graphql, webhook, reference, getting-started, auth Trust & Authority + Minimalism Glassmorphism, Dark Mode (OLED) Quick Start + Interactive Docs N/A - Documentation focused Dark code theme + Brand accent + Syntax colors Endpoint discoverability. Copy-paste code samples. Auth flow clarity. Version switching. Interactive playground. Rate limit visibility.
165 164 Forum / Discussion Board forum, discussion, thread, post, reply, community, comment, moderation, subreddit, stackexchange, topic Dark Mode (OLED) + Minimalism Flat Design, Vibrant & Block-based Feed + Thread View N/A - Discussion focused Dark neutral + topic accent colors + unread indicator + reputation badge Thread list with pagination. Rich text editor. Quote/mention system. Upvote/downvote. User badges. Moderation tools.
166 165 Directory / Listing Site directory, listing, classifieds, catalogue, business-directory, yellow-pages, venue, find, search, filter, map Flat Design + Vibrant & Block-based Minimalism, Trust & Authority Filter-Heavy Grid + Map N/A - Listing focused Neutral bg + category color chips + map accent + verified badge Category tree. Multi-filter sidebar. Map/list toggle. Verified badges. Reviews. Claim listing flow.
167 166 Status Page / Incident Management status, incident, outage, uptime, downtime, statuspage, monitoring, sla, maintenance, sev1, postmortem Data-Dense + Trust & Authority Minimalism, Dark Mode (OLED) Timeline + Severity Indicators Real-Time Monitoring + Timeline Status green + incident red + maintenance amber + neutral dark Service status matrix. Incident timeline. Severity badges. Maintenance schedule. SLA uptime history. Email/SMS subscribe.
168 167 Wiki / Encyclopedia wiki, encyclopedia, knowledge, article, reference, wikipedia, documentation, collaborative, edit, version, citation Minimalism + Flat Design Swiss Modernism 2.0, Accessible & Ethical Search-First + Hierarchical Navigation N/A - Reference focused Clean white + link blue + heading hierarchy + citation grey Full-text search bar. Table of contents sidebar. Edit history. Inter-page linking. Mobile responsive. Print-friendly.
169 168 Auction Platform auction, bid, hammer, lot, live-auction, bidding-war, estate-sale, proxibid, gavel, lot-number, reserve-price Dark Mode (OLED) + Motion-Driven Vibrant & Block-based, Real-Time Monitor Live Auction Feed + Countdown N/A - Auction focused Dark bg + bid green + outbid red + countdown amber Real-time bid updates. Countdown timer urgency. Auto-bid ceiling. Outbid notifications. Bid history. Reserve price indicator.
170 169 Changelog / Release Notes changelog, release-notes, version-history, whats-new, product-updates, semver, patch-notes, release-tracker Minimalism + Flat Design Swiss Modernism 2.0, Trust & Authority Timeline + Version List N/A - Documentation focused Neutral bg + version badge colors (feat=green, fix=blue, breaking=red) + date grey Chronological release feed. Semver badges. Breaking change warnings. Copy-paste install commands. Subscribe to feed. Search by version.
171 170 Citizen Science Platform citizen-science, zooniverse, crowdsourced-research, volunteer-science, public-participation, distributed-research, citizen-researcher Organic Biophilic + Vibrant & Block-based Claymorphism, Motion-Driven Storytelling-Driven + Social Proof Project Participation Dashboard Earth green + discovery orange + volunteer badge blue + data neutral Project cards with impact metrics. Contribution tracker. Beginner-friendly onboarding. Data quality feedback loop. Leaderboards. Community forums.
172 171 Classifieds / Buy-Sell classifieds, buy-sell, craigslist, secondhand, marketplace-listing, for-sale, trade, flea-market, thrift, resell Flat Design + Vibrant & Block-based Minimalism, Trust & Authority Filter-Heavy Grid + Map N/A - Listing focused Neutral bg + price green + category chips + verified seller badge Category tree. Photo-first listing cards. Price negotiation. Location radius filter. Saved searches. Seller reputation. Flag/report.
173 172 Conference / Symposium Landing Page conference, symposium, summit, cfp, call-for-papers, speaker-lineup, registration, venue, proceedings, keynote, track Swiss Modernism 2.0 + Minimalism Trust & Authority, Accessible & Ethical Hero + Agenda + CFP N/A - Event focused Academic navy + track color chips + gold keynote + neutral white Speaker grid. Multi-track agenda. CFP deadline countdown. Venue map. Sponsor tiers. Early-bird pricing. Proceedings download.
174 173 Crowdfunding Platform crowdfunding, kickstarter, indiegogo, campaign, backer, pledge, funding-goal, stretch-goal, reward-tier, all-or-nothing Vibrant & Block-based + Motion-Driven Claymorphism, Storytelling-Driven Storytelling-Driven + Social Proof Campaign Analytics Dashboard Brand primary + funding progress green + urgency amber + reward tier colors Funding progress bar with % goal. Reward tier selector. Backer count. Countdown timer. Updates feed. Creator profile. Risk/disclaimer section.
175 174 Digital Signage / Kiosk digital-signage, kiosk, interactive-display, touchscreen, wayfinding, lobby-display, menu-board, point-of-sale-display Minimalism + Dark Mode (OLED) Flat Design, Motion-Driven Full-Screen Immersive N/A - Display focused High contrast + brand accent + touch target emphasis (56px min) Full-screen single-purpose layout. Touch targets ≥56px. Auto-rotate content. Offline fallback. Brightness-aware color palette. No scroll.
176 175 E-signature / Document Workflow esignature, e-sign, docusign, digital-signature, document-workflow, approval-chain, contract-signing, signing-ceremony Trust & Authority + Minimalism Accessible & Ethical, Flat Design Feature-Rich Showcase + Conversion Document Pipeline Dashboard Trust navy + signature green + pending amber + neutral grey Document preview with annotation. Signature placement UI. Multi-signer workflow. Audit trail. Compliance badges. Mobile signing. Expiry reminders.
177 176 Feature Flag / Config Management feature-flag, config, launchdarkly, feature-toggle, experiment, rollout, kill-switch, a-b-test-config, percentage-rollout Dark Mode (OLED) + Data-Dense Minimalism, Trust & Authority Feature List + Toggle Panel N/A - Config focused Dark bg + enabled green + disabled grey + experimental amber + kill-switch red Feature list with on/off toggles. Percentage rollout slider. Environment selector (prod/staging). User targeting rules. Kill switch. Audit log.
178 177 Government Portal / Civic Services government-portal, civic-services, city-hall, permit-application, tax-payment, voter-registration, public-records, municipal-online Accessible & Ethical + Trust & Authority Flat Design, Inclusive Design Service Directory + Search N/A - Service focused Professional blue + accessibility high contrast + service category colors Multilingual toggle. Service A-Z index. Form wizard with save-progress. Document upload. Appointment booking. Status tracker. WCAG AAA. Plain language.
179 178 Grant / Funding Portal grant, funding, rfp, proposal, research-grant, foundation, fellowship, award, application-portal, funding-opportunity Trust & Authority + Minimalism Accessible & Ethical, Swiss Modernism 2.0 Opportunity Grid + Search Application Tracking Dashboard Institution navy + funding green + deadline red + neutral white Funding opportunity cards. Eligibility checker. Deadline countdown. Application form wizard. Document checklist. Review status tracker. Award announcement feed.
180 179 LMS (Learning Management System) lms, course-management, learning-management, canvas, moodle, blackboard, enrollment, gradebook, syllabus, assignment-submit Flat Design + Accessible & Ethical Minimalism, Vibrant & Block-based Dashboard + Course Grid Education Analytics Dashboard Calm blue + course category colors + grade green + alert red Dashboard with enrolled courses. Assignment deadlines. Gradebook view. Discussion forums. File upload. Calendar integration. Mobile offline sync.
181 180 No-code / Low-code Builder no-code, low-code, builder, bubble, webflow, drag-drop, visual-builder, app-builder, workflow-builder, logic-blocks Vibrant & Block-based + Bento Box Grid Motion-Driven, Glassmorphism Interactive Product Demo App Builder Workspace Brand primary + component palette colors + canvas neutral + connect blue Drag-drop canvas. Component library sidebar. Logic flow visual editor. Preview pane. Template gallery. Publish button. Version history.
182 181 Open Source Project Landing open-source, github-project, oss, contributor, star, fork, pull-request, maintainer, sponsoring, readme, repository Dark Mode (OLED) + Minimalism Trust & Authority, Flat Design Hero + Install + Contribute Contributor Analytics Dashboard Dark bg + language color bar + star gold + fork silver + sponsor purple Star/fork count badges. Install command (copy-paste). Language breakdown bar. Top contributors grid. Sponsor CTA. Documentation link. Issue/pr status.
183 182 Patient Portal / Health Records patient-portal, health-records, ehr, emr, mychart, lab-results, prescription-refill, medical-history, test-results, care-team Trust & Authority + Accessible & Ethical Minimalism, Flat Design Health Summary Dashboard Healthcare Analytics Clinical blue + health green + alert red + calm white + accessible contrast Labs and results timeline. Medication list with refill. Appointment scheduling. Message care team. Immunization records. Allergy alerts. Family access proxy.
184 183 Patent / IP Database patent, intellectual-property, trademark, prior-art, uspto, wipo, invention, ip-portfolio, patent-search, claims Swiss Modernism 2.0 + Minimalism Trust & Authority, Data-Dense Search-First + Results Grid N/A - Search focused Formal neutral + patent type chips + status badges (granted/pending/rejected) Full-text patent search. Classification tree. Citation graph. Prior art comparison. Patent family view. PDF download. Legal status tracker.
185 184 Q&A Community Platform qa, stack-overflow, question-answer, knowledge-sharing, community-qa, expert-answer, upvote, accepted-answer, reputation Minimalism + Flat Design Dark Mode (OLED), Accessible & Ethical Feed + Thread View Community Analytics Dashboard Clean white + upvote orange + accepted green + reputation gold + tag colors Question list with vote count. Rich code blocks. Tag filter. Reputation system. Accepted answer highlight. Comment threads. Bookmark/save.
186 185 Research Lab / University Department research-lab, university-department, academic-lab, principal-investigator, lab-members, publications, research-group, pi-page Swiss Modernism 2.0 + Minimalism Trust & Authority, Accessible & Ethical Overview + People + Publications N/A - Academic focused Institutional navy + white + research area accent colors + serif headings PI bio and research focus. Current members grid. Publication list with links. Open positions. Lab facilities photos. Funding acknowledgments.
187 186 Resume / CV Builder resume, cv, builder, job-search, curriculum-vitae, portfolio-resume, cover-letter, career-builder, ats-friendly Minimalism + Flat Design Swiss Modernism 2.0, Trust & Authority Interactive Product Demo + CTA Template Selection Gallery Professional navy + section accent + success green + clean white Template picker. Section-by-section editor. Real-time preview. ATS score indicator. PDF export. Cover letter generator. Import from LinkedIn.
188 187 Review Platform review, rating, yelp, trustpilot, testimonial, customer-review, star-rating, verified-purchase, pros-cons Flat Design + Vibrant & Block-based Trust & Authority, Minimalism Hero + Rating Summary + Review Feed Review Analytics Dashboard Brand primary + star gold + positive green + negative red + verified blue Star rating summary with distribution. Verified purchase badge. Photo/video reviews. Helpful/upvote. Filter by rating. Response from business. Sort by recency.
189 188 RPA / Automation Dashboard rpa, robotic-process-automation, uipath, automation-anywhere, bot-orchestrator, process-discovery, attended-bot, unattended-bot Dark Mode (OLED) + Data-Dense Minimalism, Trust & Authority Bot Fleet Dashboard Real-Time Monitoring + Process Analytics Dark bg + running green + failed red + queued amber + completed blue Bot status grid (running/idle/failed). Queue depth. Process flow visualization. Exception handling alert. ROI metrics. Bot scheduling calendar. Audit trail.
190 189 Survey / Form Builder survey, form-builder, questionnaire, typeform, survey-monkey, poll, feedback-form, multi-step-form, nps-survey, logic-jump Minimalism + Micro-interactions Claymorphism, Flat Design Interactive Product Demo Response Analytics Dashboard Clean white + question accent + progress green + submit blue Drag-drop form builder. Question type library. Conditional logic visualizer. Theme picker. Response dashboard with charts. Export CSV. Share link/QR/embed.
191 190 Telemedicine Platform telemedicine, telehealth, virtual-visit, remote-consultation, video-doctor, remote-patient-monitoring, telehealth-app Neumorphism + Accessible & Ethical Trust & Authority, Soft UI Evolution Trust & Authority + Conversion Healthcare Analytics Calm medical blue + video green + waiting amber + trust white Video call UI with screen share. Appointment queue. Symptom intake form. Prescription e-delivery. Waiting room with ETA. Post-visit summary. Insurance verification.
192 191 Testimonial & Social Proof Widget testimonial, social-proof, wall-of-love, customer-quote, case-study, review-widget, trust-signal, user-story Vibrant & Block-based + Flat Design Motion-Driven, Minimalism Wall-of-Love Grid Engagement Analytics Dashboard Brand primary + quote accent + star gold + verified blue Testimonial cards with photo. Star ratings. Video testimonials. Case study summaries. Filter by industry/product. Embeddable widget code. Auto-rotate carousel.
193 192 Ticketing / Box Office ticketing, box-office, eventbrite, ticket-sales, seat-selection, will-call, qr-ticket, venue-capacity, will-call-pickup Vibrant & Block-based + Motion-Driven Dark Mode (OLED), Glassmorphism Event Grid + Seat Map Sales Analytics Dashboard Event theme colors + available green + sold-out red + seat map neutral Event cards with date/venue. Interactive seat map. Cart with countdown. QR code ticket. Will-call pickup. Group discounts. Refund policy.

View File

@ -1,51 +1,51 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Components,Use standalone components,Angular 17+ default; no NgModule needed,Standalone components for all new code,NgModule-based components for new projects,"@Component({ standalone: true imports: [CommonModule] })","@NgModule({ declarations: [MyComp] })",High,https://angular.dev/guide/components/importing
2,Components,Use signals for state,Signals are Angular's reactive primitive for fine-grained reactivity,Signals for component state over class properties,Mutable class properties without signals,"count = signal(0); increment() { this.count.update(v => v + 1) }","count = 0; increment() { this.count++ }",High,https://angular.dev/guide/signals
3,Components,Use @if/@for/@switch control flow,Built-in control flow syntax replaces *ngIf/*ngFor directives,@if and @for in templates,*ngIf and *ngFor structural directives,"@if (isLoggedIn) { <Dashboard /> } @else { <Login /> }","<div *ngIf=""isLoggedIn""><Dashboard /></div>",High,https://angular.dev/guide/templates/control-flow
4,Components,Use input() and output() signals,Signal-based inputs/outputs replace @Input()/@Output() decorators,input() and output() for component API,@Input() and @Output() decorators,"name = input<string>(); clicked = output<void>()","@Input() name: string; @Output() clicked = new EventEmitter()",High,https://angular.dev/guide/components/inputs
1,Components,Use standalone components,Angular 17+ default; no NgModule needed,Standalone components for all new code,NgModule-based components for new projects,@Component({ standalone: true imports: [CommonModule] }),@NgModule({ declarations: [MyComp] }),High,https://angular.dev/guide/components/importing
2,Components,Use signals for state,Signals are Angular's reactive primitive for fine-grained reactivity,Signals for component state over class properties,Mutable class properties without signals,count = signal(0); increment() { this.count.update(v => v + 1) },count = 0; increment() { this.count++ },High,https://angular.dev/guide/signals
3,Components,Use @if/@for/@switch control flow,Built-in control flow syntax replaces *ngIf/*ngFor directives,@if and @for in templates,*ngIf and *ngFor structural directives,@if (isLoggedIn) { <Dashboard /> } @else { <Login /> },"<div *ngIf=""isLoggedIn""><Dashboard /></div>",High,https://angular.dev/guide/templates/control-flow
4,Components,Use input() and output() signals,Signal-based inputs/outputs replace @Input()/@Output() decorators,input() and output() for component API,@Input() and @Output() decorators,name = input<string>(); clicked = output<void>(),@Input() name: string; @Output() clicked = new EventEmitter(),High,https://angular.dev/guide/components/inputs
5,Components,Use content projection,ng-content for flexible component composition,ng-content with select for named slots,Rigid templates that can't be customized,"<ng-content select=""[header]"" /> <ng-content />","<div class=""header"">{{ title }}</div>",Medium,https://angular.dev/guide/components/content-projection
6,Components,Keep components small,Single responsibility; components should do one thing,Extract sub-components when template exceeds 50 lines,Monolithic components handling multiple concerns,"<UserAvatar /> <UserDetails /> <UserActions />",One 300-line component template,Medium,https://angular.dev/guide/components
7,Components,Use OnPush change detection,Reduces re-renders by only checking on input changes or signal updates,OnPush for all components,Default change detection strategy,"changeDetection: ChangeDetectionStrategy.OnPush","changeDetection: ChangeDetectionStrategy.Default",High,https://angular.dev/guide/components/lifecycle
8,Components,Avoid direct DOM manipulation,Use renderer or ElementRef sparingly; prefer template bindings,Template bindings and Angular directives,Direct document.querySelector or innerHTML,"[class.active]=""isActive""","this.el.nativeElement.classList.add('active')",High,https://angular.dev/guide/components/host-elements
9,Routing,Lazy load feature routes,Load route chunks on demand to reduce initial bundle,loadComponent() for all feature routes,Eager-loaded routes in app config,"{ path: 'admin' loadComponent: () => import('./admin/admin.component') }","{ path: 'admin' component: AdminComponent }",High,https://angular.dev/guide/routing/lazy-loading
10,Routing,Use route guards with functional API,Protect routes with canActivate/canMatch functional guards,Functional guards returning boolean or UrlTree,Class-based guards with CanActivate interface,"canActivate: [() => inject(AuthService).isLoggedIn()]","canActivate: [AuthGuard]",High,https://angular.dev/guide/routing/common-router-tasks#preventing-unauthorized-access
11,Routing,Use route resolvers for data,Pre-fetch data before route activation using resolve,ResolveFn for route data,Fetching data in ngOnInit causing flash of empty state,"resolve: { user: () => inject(UserService).getUser() }",Fetch in ngOnInit with loading state flickering,Medium,https://angular.dev/guide/routing/common-router-tasks#resolve
12,Routing,Type route params with inject,Use inject(ActivatedRoute) with signals or toSignal,Typed route params via ActivatedRoute,Untyped route.snapshot.params string access,"const id = toSignal(route.paramMap.pipe(map(p => p.get('id'))))","const id = this.route.snapshot.params['id']",Medium,https://angular.dev/api/router/ActivatedRoute
13,Routing,Use nested routes for layouts,Compose shared layouts using router-outlet nesting,Nested routes with shared layout components,Duplicating layout code across routes,"{ path: 'app' component: ShellComponent children: [...] }",Duplicate header/sidebar in each route component,Medium,https://angular.dev/guide/routing/router-tutorial-toh#child-route-configuration
14,Routing,Configure preloading strategies,Preload lazy modules in background after initial load,PreloadAllModules or custom strategy,No preloading causing delayed navigation,"provideRouter(routes withPreloading(PreloadAllModules))","provideRouter(routes)",Low,https://angular.dev/api/router/PreloadAllModules
15,State,Use signals for local state,Signals provide synchronous reactive state without RxJS overhead,signal() for component-local reactive state,BehaviorSubject for simple local state,"const items = signal<Item[]>([]); addItem(i: Item) { this.items.update(arr => [...arr i]) }","items$ = new BehaviorSubject<Item[]>([])",High,https://angular.dev/guide/signals
16,State,Use computed() for derived state,Lazily evaluated derived values that update when dependencies change,computed() for values derived from other signals,Duplicated state or manual sync,"readonly total = computed(() => this.items().reduce((s i) => s + i.price 0))","this.total = this.items.reduce(...) // called manually",High,https://angular.dev/guide/signals#computed-signals
17,State,Use effect() carefully,Effects run side effects when signals change; avoid overuse,effect() for side effects like logging or localStorage sync,effect() for deriving state (use computed instead),"effect(() => localStorage.setItem('cart' JSON.stringify(this.cart())))","effect(() => { this.total.set(this.items().length) })",Medium,https://angular.dev/guide/signals#effects
18,State,Use NgRx Signal Store for complex state,NgRx Signal Store is the modern lightweight state management for Angular,@ngrx/signals SignalStore for feature state,Full NgRx reducer/action/effect boilerplate for simple state,"const Store = signalStore(withState({ count: 0 }) withMethods(s => ({ increment: () => patchState(s { count: s.count() + 1 }) })))","createReducer(on(increment state => ({ ...state count: state.count + 1 })))",Medium,https://ngrx.io/guide/signals
19,State,Inject services for shared state,Services with signals share state across components without a store,Injectable service with signals for cross-component state,Prop drilling or @Input chains for shared state,"@Injectable({ providedIn: 'root' }) class CartService { items = signal<Item[]>([]) }","@Input() cartItems passed through 4 component levels",Medium,https://angular.dev/guide/di/creating-injectable-service
20,State,Avoid mixing RxJS and signals unnecessarily,Use toSignal() to bridge RxJS into signal world at the boundary,toSignal() to convert observable to signal at component edge,Subscribing in components and storing in signal manually,"readonly user = toSignal(this.userService.user$)","this.userService.user$.subscribe(u => this.user.set(u))",Medium,https://angular.dev/guide/rxjs-interop
21,Forms,Use typed reactive forms,FormGroup/FormControl with explicit generics for compile-time safety,FormBuilder with typed controls,Untyped FormControl or any casts,"fb.group<LoginForm>({ email: fb.control('') password: fb.control('') })","new FormGroup({ email: new FormControl(null) })",High,https://angular.dev/guide/forms/typed-forms
6,Components,Keep components small,Single responsibility; components should do one thing,Extract sub-components when template exceeds 50 lines,Monolithic components handling multiple concerns,<UserAvatar /> <UserDetails /> <UserActions />,One 300-line component template,Medium,https://angular.dev/guide/components
7,Components,Use OnPush change detection,Reduces re-renders by only checking on input changes or signal updates,OnPush for all components,Default change detection strategy,changeDetection: ChangeDetectionStrategy.OnPush,changeDetection: ChangeDetectionStrategy.Default,High,https://angular.dev/guide/components/lifecycle
8,Components,Avoid direct DOM manipulation,Use renderer or ElementRef sparingly; prefer template bindings,Template bindings and Angular directives,Direct document.querySelector or innerHTML,"[class.active]=""isActive""",this.el.nativeElement.classList.add('active'),High,https://angular.dev/guide/components/host-elements
9,Routing,Lazy load feature routes,Load route chunks on demand to reduce initial bundle,loadComponent() for all feature routes,Eager-loaded routes in app config,{ path: 'admin' loadComponent: () => import('./admin/admin.component') },{ path: 'admin' component: AdminComponent },High,https://angular.dev/guide/routing/lazy-loading
10,Routing,Use route guards with functional API,Protect routes with canActivate/canMatch functional guards,Functional guards returning boolean or UrlTree,Class-based guards with CanActivate interface,canActivate: [() => inject(AuthService).isLoggedIn()],canActivate: [AuthGuard],High,https://angular.dev/guide/routing/common-router-tasks#preventing-unauthorized-access
11,Routing,Use route resolvers for data,Pre-fetch data before route activation using resolve,ResolveFn for route data,Fetching data in ngOnInit causing flash of empty state,resolve: { user: () => inject(UserService).getUser() },Fetch in ngOnInit with loading state flickering,Medium,https://angular.dev/guide/routing/common-router-tasks#resolve
12,Routing,Type route params with inject,Use inject(ActivatedRoute) with signals or toSignal,Typed route params via ActivatedRoute,Untyped route.snapshot.params string access,const id = toSignal(route.paramMap.pipe(map(p => p.get('id')))),const id = this.route.snapshot.params['id'],Medium,https://angular.dev/api/router/ActivatedRoute
13,Routing,Use nested routes for layouts,Compose shared layouts using router-outlet nesting,Nested routes with shared layout components,Duplicating layout code across routes,{ path: 'app' component: ShellComponent children: [...] },Duplicate header/sidebar in each route component,Medium,https://angular.dev/guide/routing/router-tutorial-toh#child-route-configuration
14,Routing,Configure preloading strategies,Preload lazy modules in background after initial load,PreloadAllModules or custom strategy,No preloading causing delayed navigation,provideRouter(routes withPreloading(PreloadAllModules)),provideRouter(routes),Low,https://angular.dev/api/router/PreloadAllModules
15,State,Use signals for local state,Signals provide synchronous reactive state without RxJS overhead,signal() for component-local reactive state,BehaviorSubject for simple local state,const items = signal<Item[]>([]); addItem(i: Item) { this.items.update(arr => [...arr i]) },items$ = new BehaviorSubject<Item[]>([]),High,https://angular.dev/guide/signals
16,State,Use computed() for derived state,Lazily evaluated derived values that update when dependencies change,computed() for values derived from other signals,Duplicated state or manual sync,readonly total = computed(() => this.items().reduce((s i) => s + i.price 0)),this.total = this.items.reduce(...) // called manually,High,https://angular.dev/guide/signals#computed-signals
17,State,Use effect() carefully,Effects run side effects when signals change; avoid overuse,effect() for side effects like logging or localStorage sync,effect() for deriving state (use computed instead),effect(() => localStorage.setItem('cart' JSON.stringify(this.cart()))),effect(() => { this.total.set(this.items().length) }),Medium,https://angular.dev/guide/signals#effects
18,State,Use NgRx Signal Store for complex state,NgRx Signal Store is the modern lightweight state management for Angular,@ngrx/signals SignalStore for feature state,Full NgRx reducer/action/effect boilerplate for simple state,const Store = signalStore(withState({ count: 0 }) withMethods(s => ({ increment: () => patchState(s { count: s.count() + 1 }) }))),createReducer(on(increment state => ({ ...state count: state.count + 1 }))),Medium,https://ngrx.io/guide/signals
19,State,Inject services for shared state,Services with signals share state across components without a store,Injectable service with signals for cross-component state,Prop drilling or @Input chains for shared state,@Injectable({ providedIn: 'root' }) class CartService { items = signal<Item[]>([]) },@Input() cartItems passed through 4 component levels,Medium,https://angular.dev/guide/di/creating-injectable-service
20,State,Avoid mixing RxJS and signals unnecessarily,Use toSignal() to bridge RxJS into signal world at the boundary,toSignal() to convert observable to signal at component edge,Subscribing in components and storing in signal manually,readonly user = toSignal(this.userService.user$),this.userService.user$.subscribe(u => this.user.set(u)),Medium,https://angular.dev/guide/rxjs-interop
21,Forms,Use typed reactive forms,FormGroup/FormControl with explicit generics for compile-time safety,FormBuilder with typed controls,Untyped FormControl or any casts,fb.group<LoginForm>({ email: fb.control('') password: fb.control('') }),new FormGroup({ email: new FormControl(null) }),High,https://angular.dev/guide/forms/typed-forms
22,Forms,Use reactive forms over template-driven,Reactive forms scale better and are fully testable,ReactiveFormsModule for all non-trivial forms,FormsModule with ngModel for complex forms,"<input [formControl]=""emailControl"" />","<input [(ngModel)]=""email"" />",Medium,https://angular.dev/guide/forms/reactive-forms
23,Forms,Write custom validators as functions,Functional validators are composable and tree-shakeable,ValidatorFn functions for custom validation,Class-based validators implementing Validator interface,"const noSpaces: ValidatorFn = ctrl => ctrl.value?.includes(' ') ? { noSpaces: true } : null","class NoSpacesValidator implements Validator { validate(c) {} }",Medium,https://angular.dev/guide/forms/form-validation#custom-validators
24,Forms,Use updateOn for performance,Control when validation runs to avoid per-keystroke validation overhead,updateOn: 'blur' or 'submit' for expensive validators,Default updateOn: 'change' for async validators,"fb.control('' { updateOn: 'blur' validators: [Validators.email] })","fb.control('' [Validators.email]) // validates on every key",Low,https://angular.dev/api/forms/AbstractControl#updateOn
25,Forms,Use FormArray for dynamic fields,FormArray manages variable-length lists of controls,FormArray for add/remove field scenarios,Manually tracking index-based controls,"get items(): FormArray { return this.form.get('items') as FormArray }","items: [FormControl] managed outside form",Medium,https://angular.dev/guide/forms/reactive-forms#using-the-formarray-class
26,Forms,Display validation errors clearly,Use form control touched and dirty states to show errors at the right time,Show errors after field is touched,Show all errors on page load,"@if (email.invalid && email.touched) { <span>Invalid email</span> }","@if (email.invalid) { <span>Invalid email</span> }",Medium,https://angular.dev/guide/forms/form-validation
23,Forms,Write custom validators as functions,Functional validators are composable and tree-shakeable,ValidatorFn functions for custom validation,Class-based validators implementing Validator interface,const noSpaces: ValidatorFn = ctrl => ctrl.value?.includes(' ') ? { noSpaces: true } : null,class NoSpacesValidator implements Validator { validate(c) {} },Medium,https://angular.dev/guide/forms/form-validation#custom-validators
24,Forms,Use updateOn for performance,Control when validation runs to avoid per-keystroke validation overhead,updateOn: 'blur' or 'submit' for expensive validators,Default updateOn: 'change' for async validators,fb.control('' { updateOn: 'blur' validators: [Validators.email] }),fb.control('' [Validators.email]) // validates on every key,Low,https://angular.dev/api/forms/AbstractControl#updateOn
25,Forms,Use FormArray for dynamic fields,FormArray manages variable-length lists of controls,FormArray for add/remove field scenarios,Manually tracking index-based controls,get items(): FormArray { return this.form.get('items') as FormArray },items: [FormControl] managed outside form,Medium,https://angular.dev/guide/forms/reactive-forms#using-the-formarray-class
26,Forms,Display validation errors clearly,Use form control touched and dirty states to show errors at the right time,Show errors after field is touched,Show all errors on page load,@if (email.invalid && email.touched) { <span>Invalid email</span> },@if (email.invalid) { <span>Invalid email</span> },Medium,https://angular.dev/guide/forms/form-validation
27,Performance,Apply OnPush to all components,OnPush + signals eliminates most unnecessary change detection cycles,OnPush change detection everywhere,Default strategy which checks entire tree on every event,changeDetection: ChangeDetectionStrategy.OnPush,changeDetection: ChangeDetectionStrategy.Default,High,https://angular.dev/best-practices/skipping-component-subtrees
28,Performance,Use trackBy in @for blocks,Stable identity for list items prevents full DOM re-creation on change,track item.id in @for,"@for (item of items; track item.id) { <li>{{ item.name }}</li> }","@for (item of items; track $index) { <li>{{ item.name }}</li> }",High,https://angular.dev/guide/templates/control-flow#track-and-identity
29,Performance,Use @defer for below-the-fold content,Defer blocks lazy-load components when they enter the viewport,@defer with on viewport for non-critical UI,Eagerly loading all components at startup,"@defer (on viewport) { <HeavyChart /> } @placeholder { <Skeleton /> }","<HeavyChart /> loaded at startup",High,https://angular.dev/guide/defer
28,Performance,Use trackBy in @for blocks,Stable identity for list items prevents full DOM re-creation on change,track item.id in @for,track $index for dynamic data,@for (item of items; track item.id) { <li>{{ item.name }}</li> },@for (item of items; track $index) { <li>{{ item.name }}</li> },High,https://angular.dev/guide/templates/control-flow#track-and-identity
29,Performance,Use @defer for below-the-fold content,Defer blocks lazy-load components when they enter the viewport,@defer with on viewport for non-critical UI,Eagerly loading all components at startup,@defer (on viewport) { <HeavyChart /> } @placeholder { <Skeleton /> },<HeavyChart /> loaded at startup,High,https://angular.dev/guide/defer
30,Performance,Use NgOptimizedImage,Enforces image best practices: lazy loading LCP hints and proper sizing,NgOptimizedImage for all img tags,Plain img tags for CMS or user content,"<img ngSrc=""/hero.jpg"" width=""800"" height=""400"" priority />","<img src=""/hero.jpg"" />",High,https://angular.dev/guide/image-optimization
31,Performance,Tree-shake unused Angular features,Import only what you use from Angular packages,Import specific Angular modules needed,Import BrowserAnimationsModule when not using animations,"import { NgOptimizedImage } from '@angular/common'","import { CommonModule } from '@angular/common' // entire module",Medium,https://angular.dev/tools/cli/build
32,Performance,Avoid subscribe in components,Subscriptions leak and cause bugs; prefer async pipe or toSignal,toSignal() or async pipe instead of manual subscribe,Manual subscribe without unsubscribe in ngOnDestroy,"readonly data = toSignal(this.service.data$)","this.service.data$.subscribe(d => this.data = d)",High,https://angular.dev/guide/rxjs-interop
33,Performance,Use SSR with Angular Universal,Pre-render pages for faster LCP and better SEO,SSR or SSG for public-facing routes,Pure CSR for SEO-critical pages,"ng add @angular/ssr","// no SSR, client renders empty shell",Medium,https://angular.dev/guide/ssr
34,Performance,Minimize bundle with standalone APIs,Standalone components + provideRouter() eliminate dead NgModule code,provideRouter() and provideHttpClient() in app.config,Root AppModule with all imports,provideRouter(routes) in app.config.ts,"@NgModule({ imports: [RouterModule.forRoot(routes)] })",Medium,https://angular.dev/guide/routing/standalone
35,Testing,Use TestBed for component tests,TestBed sets up Angular DI for realistic component testing,TestBed.configureTestingModule for component tests,Instantiate components with new keyword,"TestBed.configureTestingModule({ imports: [MyComponent] })","const comp = new MyComponent()",High,https://angular.dev/guide/testing/components-basics
36,Testing,Use Angular CDK component harnesses,Harnesses provide a stable testing API that survives template refactors,MatButtonHarness and custom HarnessLoader,Direct native element queries that break on template changes,"const btn = await loader.getHarness(MatButtonHarness)","fixture.debugElement.query(By.css('button'))",Medium,https://material.angular.io/cdk/test-harnesses/overview
37,Testing,Use Spectator for less boilerplate,Spectator wraps TestBed with a cleaner API reducing test setup noise,Spectator for unit tests,Raw TestBed for every test,"const spectator = createComponentFactory(MyComponent)","TestBed.configureTestingModule({ declarations: [MyComponent] providers: [...] })",Low,https://github.com/ngneat/spectator
38,Testing,Mock services with jasmine.createSpyObj,Isolate unit tests by providing mock implementations of dependencies,SpyObj or jest.fn() mocks for services,Real HTTP calls in unit tests,"const spy = jasmine.createSpyObj('UserService' ['getUser']); spy.getUser.and.returnValue(of(user))","providers: [UserService] // real service in unit test",High,https://angular.dev/guide/testing/services
39,Testing,Write integration tests for routes,Test full route navigation including guards and resolvers,RouterTestingHarness for route integration tests,Mock all routing behavior in unit tests,"const harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/home')","// manually calling route guard methods",Medium,https://angular.dev/api/router/testing/RouterTestingHarness
40,Testing,Test signal-based components,Signals update synchronously; no async flush needed in most cases,Read signal value directly in test assertions,TestBed.tick() or fakeAsync for signal reads,"component.count.set(5); expect(component.double()).toBe(10)","fakeAsync(() => { component.count.set(5); tick(); expect(component.double()).toBe(10) })",Medium,https://angular.dev/guide/testing
31,Performance,Tree-shake unused Angular features,Import only what you use from Angular packages,Import specific Angular modules needed,Import BrowserAnimationsModule when not using animations,import { NgOptimizedImage } from '@angular/common',import { CommonModule } from '@angular/common' // entire module,Medium,https://angular.dev/tools/cli/build
32,Performance,Avoid subscribe in components,Subscriptions leak and cause bugs; prefer async pipe or toSignal,toSignal() or async pipe instead of manual subscribe,Manual subscribe without unsubscribe in ngOnDestroy,readonly data = toSignal(this.service.data$),this.service.data$.subscribe(d => this.data = d),High,https://angular.dev/guide/rxjs-interop
33,Performance,Use SSR with Angular Universal,Pre-render pages for faster LCP and better SEO,SSR or SSG for public-facing routes,Pure CSR for SEO-critical pages,ng add @angular/ssr,"// no SSR, client renders empty shell",Medium,https://angular.dev/guide/ssr
34,Performance,Minimize bundle with standalone APIs,Standalone components + provideRouter() eliminate dead NgModule code,provideRouter() and provideHttpClient() in app.config,Root AppModule with all imports,provideRouter(routes) in app.config.ts,@NgModule({ imports: [RouterModule.forRoot(routes)] }),Medium,https://angular.dev/guide/routing/standalone
35,Testing,Use TestBed for component tests,TestBed sets up Angular DI for realistic component testing,TestBed.configureTestingModule for component tests,Instantiate components with new keyword,TestBed.configureTestingModule({ imports: [MyComponent] }),const comp = new MyComponent(),High,https://angular.dev/guide/testing/components-basics
36,Testing,Use Angular CDK component harnesses,Harnesses provide a stable testing API that survives template refactors,MatButtonHarness and custom HarnessLoader,Direct native element queries that break on template changes,const btn = await loader.getHarness(MatButtonHarness),fixture.debugElement.query(By.css('button')),Medium,https://material.angular.io/cdk/test-harnesses/overview
37,Testing,Use Spectator for less boilerplate,Spectator wraps TestBed with a cleaner API reducing test setup noise,Spectator for unit tests,Raw TestBed for every test,const spectator = createComponentFactory(MyComponent),TestBed.configureTestingModule({ declarations: [MyComponent] providers: [...] }),Low,https://github.com/ngneat/spectator
38,Testing,Mock services with jasmine.createSpyObj,Isolate unit tests by providing mock implementations of dependencies,SpyObj or jest.fn() mocks for services,Real HTTP calls in unit tests,const spy = jasmine.createSpyObj('UserService' ['getUser']); spy.getUser.and.returnValue(of(user)),providers: [UserService] // real service in unit test,High,https://angular.dev/guide/testing/services
39,Testing,Write integration tests for routes,Test full route navigation including guards and resolvers,RouterTestingHarness for route integration tests,Mock all routing behavior in unit tests,const harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/home'),// manually calling route guard methods,Medium,https://angular.dev/api/router/testing/RouterTestingHarness
40,Testing,Test signal-based components,Signals update synchronously; no async flush needed in most cases,Read signal value directly in test assertions,TestBed.tick() or fakeAsync for signal reads,component.count.set(5); expect(component.double()).toBe(10),fakeAsync(() => { component.count.set(5); tick(); expect(component.double()).toBe(10) }),Medium,https://angular.dev/guide/testing
41,Styling,Use ViewEncapsulation.Emulated,Default emulation scopes styles to component preventing global leaks,Emulated or None for intentional global styles,ViewEncapsulation.None for component-specific styles,ViewEncapsulation.Emulated (default),ViewEncapsulation.None on feature components,Medium,https://angular.dev/guide/components/styling#style-scoping
42,Styling,Use :host selector,Style the component's host element using :host pseudo-class,":host for host element styles",Adding wrapper div just for styling,":host { display: block; padding: 1rem }","<div class=""wrapper"">...</div> + .wrapper { padding: 1rem }",Medium,https://angular.dev/guide/components/styling#host-element
43,Styling,Use CSS custom properties for theming,CSS variables work across component boundaries and enable dynamic theming,CSS custom properties for colors and spacing,Hardcoded hex values in component styles,":root { --primary: #6200ee } button { background: var(--primary) }","button { background: #6200ee }",Medium,https://angular.dev/guide/components/styling
42,Styling,Use :host selector,Style the component's host element using :host pseudo-class,:host for host element styles,Adding wrapper div just for styling,:host { display: block; padding: 1rem },"<div class=""wrapper"">...</div> + .wrapper { padding: 1rem }",Medium,https://angular.dev/guide/components/styling#host-element
43,Styling,Use CSS custom properties for theming,CSS variables work across component boundaries and enable dynamic theming,CSS custom properties for colors and spacing,Hardcoded hex values in component styles,:root { --primary: #6200ee } button { background: var(--primary) },button { background: #6200ee },Medium,https://angular.dev/guide/components/styling
44,Styling,Integrate Tailwind with Angular,Tailwind utilities work alongside Angular's ViewEncapsulation via global stylesheet,Add Tailwind in styles.css and use utility classes in templates,Custom CSS for layout that Tailwind already handles,"<div class=""flex items-center gap-4 p-6"">","<div class=""my-custom-flex""> /* .my-custom-flex { display: flex } */",Low,https://tailwindcss.com/docs/guides/angular
45,Styling,Use Angular Material theming tokens,Material 3 uses design tokens for systematic theming,M3 token-based theming for Angular Material,Overriding Angular Material CSS with deep selectors,"@include mat.button-theme($my-theme)","::ng-deep .mat-button { background: red }",Medium,https://material.angular.io/guide/theming
46,Architecture,Use injection tokens for config,Provide configuration via InjectionToken for testability and flexibility,InjectionToken for environment-specific values,Importing environment.ts directly in services,"const API_URL = new InjectionToken<string>('apiUrl'); provide: [{ provide: API_URL useValue: env.apiUrl }]","constructor(private env: Environment) { this.url = env.apiUrl }",Medium,https://angular.dev/guide/di/dependency-injection-providers#using-an-injectiontoken-object
47,Architecture,Use HTTP interceptors,Intercept requests for auth headers error handling and logging,Functional interceptors with withInterceptors(),Service-level header management in every request,"withInterceptors([authInterceptor errorInterceptor])","httpClient.get(url { headers: { Authorization: token } }) in every call",High,https://angular.dev/guide/http/interceptors
48,Architecture,Organize by feature not type,Feature-based folder structure scales better than type-based,Feature folders with collocated component service and routes,Flat folders: all-components/ all-services/,"src/features/checkout/checkout.component.ts checkout.service.ts checkout.routes.ts","src/components/checkout.component.ts src/services/checkout.service.ts",Medium,https://angular.dev/style-guide#folders-by-feature-structure
49,Architecture,Use environment configurations,Separate environment values for dev staging and prod via Angular build configs,angular.json fileReplacements for env configs,Hardcoded API URLs or feature flags in source,"fileReplacements: [{ replace: environment.ts with: environment.prod.ts }]","const API = 'https://api.example.com' // hardcoded in service",High,https://angular.dev/tools/cli/environments
50,Architecture,Prefer inject() over constructor DI,inject() function is composable and works in more contexts than constructor injection,inject() for dependency injection,Constructor parameters for new code,"readonly http = inject(HttpClient); readonly router = inject(Router)","constructor(private http: HttpClient private router: Router) {}",Medium,https://angular.dev/api/core/inject
45,Styling,Use Angular Material theming tokens,Material 3 uses design tokens for systematic theming,M3 token-based theming for Angular Material,Overriding Angular Material CSS with deep selectors,@include mat.button-theme($my-theme),::ng-deep .mat-button { background: red },Medium,https://material.angular.io/guide/theming
46,Architecture,Use injection tokens for config,Provide configuration via InjectionToken for testability and flexibility,InjectionToken for environment-specific values,Importing environment.ts directly in services,const API_URL = new InjectionToken<string>('apiUrl'); provide: [{ provide: API_URL useValue: env.apiUrl }],constructor(private env: Environment) { this.url = env.apiUrl },Medium,https://angular.dev/guide/di/dependency-injection-providers#using-an-injectiontoken-object
47,Architecture,Use HTTP interceptors,Intercept requests for auth headers error handling and logging,Functional interceptors with withInterceptors(),Service-level header management in every request,withInterceptors([authInterceptor errorInterceptor]),httpClient.get(url { headers: { Authorization: token } }) in every call,High,https://angular.dev/guide/http/interceptors
48,Architecture,Organize by feature not type,Feature-based folder structure scales better than type-based,Feature folders with collocated component service and routes,Flat folders: all-components/ all-services/,src/features/checkout/checkout.component.ts checkout.service.ts checkout.routes.ts,src/components/checkout.component.ts src/services/checkout.service.ts,Medium,https://angular.dev/style-guide#folders-by-feature-structure
49,Architecture,Use environment configurations,Separate environment values for dev staging and prod via Angular build configs,angular.json fileReplacements for env configs,Hardcoded API URLs or feature flags in source,fileReplacements: [{ replace: environment.ts with: environment.prod.ts }],const API = 'https://api.example.com' // hardcoded in service,High,https://angular.dev/tools/cli/environments
50,Architecture,Prefer inject() over constructor DI,inject() function is composable and works in more contexts than constructor injection,inject() for dependency injection,Constructor parameters for new code,readonly http = inject(HttpClient); readonly router = inject(Router),constructor(private http: HttpClient private router: Router) {},Medium,https://angular.dev/api/core/inject

Can't render this file because it has a wrong number of fields in line 29.

View File

@ -3,42 +3,42 @@ No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
2,Architecture,Default to zero JS,Astro ships zero JS by default - add only when needed,Static components without client directive,Add client:load to everything,<Header /> (static),<Header client:load /> (unnecessary),High,https://docs.astro.build/en/basics/astro-components/
3,Architecture,Choose right client directive,Different directives for different hydration timing,client:visible for below-fold client:idle for non-critical,client:load for everything,<Comments client:visible />,<Comments client:load />,Medium,https://docs.astro.build/en/reference/directives-reference/#client-directives
4,Architecture,Use content collections,Type-safe content management for blogs docs,Content collections for structured content,Loose markdown files without schema,const posts = await getCollection('blog'),import.meta.glob('./posts/*.md'),High,https://docs.astro.build/en/guides/content-collections/
5,Architecture,Define collection schemas,Zod schemas for content validation,Schema with required fields and types,No schema validation,"defineCollection({ schema: z.object({...}) })",defineCollection({}),High,https://docs.astro.build/en/guides/content-collections/#defining-a-collection-schema
5,Architecture,Define collection schemas,Zod schemas for content validation,Schema with required fields and types,No schema validation,defineCollection({ schema: z.object({...}) }),defineCollection({}),High,https://docs.astro.build/en/guides/content-collections/#defining-a-collection-schema
6,Routing,Use file-based routing,Create routes by adding .astro files in pages/,pages/ directory for routes,Manual route configuration,src/pages/about.astro,Custom router setup,Medium,https://docs.astro.build/en/basics/astro-pages/
7,Routing,Dynamic routes with brackets,Use [param] for dynamic routes,Bracket notation for params,Query strings for dynamic content,pages/blog/[slug].astro,pages/blog.astro?slug=x,Medium,https://docs.astro.build/en/guides/routing/#dynamic-routes
8,Routing,Use getStaticPaths for SSG,Generate static pages at build time,getStaticPaths for known dynamic routes,Fetch at runtime for static content,"export async function getStaticPaths() { return [...] }",No getStaticPaths with dynamic route,High,https://docs.astro.build/en/reference/api-reference/#getstaticpaths
9,Routing,Enable SSR when needed,Server-side rendering for dynamic content,output: 'server' or 'hybrid' for dynamic,SSR for purely static sites,"export const prerender = false;",SSR for static blog,Medium,https://docs.astro.build/en/guides/server-side-rendering/
8,Routing,Use getStaticPaths for SSG,Generate static pages at build time,getStaticPaths for known dynamic routes,Fetch at runtime for static content,export async function getStaticPaths() { return [...] },No getStaticPaths with dynamic route,High,https://docs.astro.build/en/reference/api-reference/#getstaticpaths
9,Routing,Enable SSR when needed,Server-side rendering for dynamic content,output: 'server' or 'hybrid' for dynamic,SSR for purely static sites,export const prerender = false;,SSR for static blog,Medium,https://docs.astro.build/en/guides/server-side-rendering/
10,Components,Keep .astro for static,Use .astro components for static content,Astro components for layout structure,React/Vue for static markup,<Layout><slot /></Layout>,<ReactLayout>{children}</ReactLayout>,High,
11,Components,Use framework components for interactivity,React Vue Svelte for complex interactivity,Framework component with client directive,Astro component with inline scripts,<ReactCounter client:load />,<script> in .astro for complex state,Medium,https://docs.astro.build/en/guides/framework-components/
12,Components,Pass data via props,Astro components receive props in frontmatter,Astro.props for component data,Global state for simple data,"const { title } = Astro.props;",Import global store,Low,https://docs.astro.build/en/basics/astro-components/#component-props
13,Components,Use slots for composition,Named and default slots for flexible layouts,<slot /> for child content,Props for HTML content,<slot name="header" />,<Component header={<div>...</div>} />,Medium,https://docs.astro.build/en/basics/astro-components/#slots
12,Components,Pass data via props,Astro components receive props in frontmatter,Astro.props for component data,Global state for simple data,const { title } = Astro.props;,Import global store,Low,https://docs.astro.build/en/basics/astro-components/#component-props
13,Components,Use slots for composition,Named and default slots for flexible layouts,<slot /> for child content,Props for HTML content,"<slot name=""header"" />",<Component header={<div>...</div>} />,Medium,https://docs.astro.build/en/basics/astro-components/#slots
14,Components,Colocate component styles,Scoped styles in component file,<style> in same .astro file,Separate CSS files for component styles,<style> .card { } </style>,import './Card.css',Low,
15,Styling,Use scoped styles by default,Astro scopes styles to component automatically,<style> for component-specific styles,Global styles for everything,<style> h1 { } </style> (scoped),<style is:global> for everything,Medium,https://docs.astro.build/en/guides/styling/#scoped-styles
16,Styling,Use is:global sparingly,Global styles only when truly needed,is:global for base styles or overrides,is:global for component styles,<style is:global> body { } </style>,<style is:global> .card { } </style>,Medium,
17,Styling,Integrate Tailwind properly,Use @astrojs/tailwind integration,Official Tailwind integration,Manual Tailwind setup,npx astro add tailwind,Manual PostCSS config,Low,https://docs.astro.build/en/guides/integrations-guide/tailwind/
18,Styling,Use CSS variables for theming,Define tokens in :root,CSS custom properties for themes,Hardcoded colors everywhere,:root { --primary: #3b82f6; },color: #3b82f6; everywhere,Medium,
19,Data,Fetch in frontmatter,Data fetching in component frontmatter,Top-level await in frontmatter,useEffect for initial data,const data = await fetch(url),client-side fetch on mount,High,https://docs.astro.build/en/guides/data-fetching/
20,Data,Use Astro.glob for local files,Import multiple local files,Astro.glob for markdown/data files,Manual imports for each file,const posts = await Astro.glob('./posts/*.md'),"import post1; import post2;",Medium,
20,Data,Use Astro.glob for local files,Import multiple local files,Astro.glob for markdown/data files,Manual imports for each file,const posts = await Astro.glob('./posts/*.md'),import post1; import post2;,Medium,
21,Data,Prefer content collections over glob,Type-safe collections for structured content,getCollection() for blog/docs,Astro.glob for structured content,await getCollection('blog'),await Astro.glob('./blog/*.md'),High,
22,Data,Use environment variables correctly,Import.meta.env for env vars,PUBLIC_ prefix for client vars,Expose secrets to client,import.meta.env.PUBLIC_API_URL,import.meta.env.SECRET in client,High,https://docs.astro.build/en/guides/environment-variables/
23,Performance,Preload critical assets,Use link preload for important resources,Preload fonts above-fold images,No preload hints,"<link rel=""preload"" href=""font.woff2"" as=""font"">",No preload for critical assets,Medium,
24,Performance,Optimize images with astro:assets,Built-in image optimization,<Image /> component for optimization,<img> for local images,"import { Image } from 'astro:assets';","<img src=""./image.jpg"">",High,https://docs.astro.build/en/guides/images/
24,Performance,Optimize images with astro:assets,Built-in image optimization,<Image /> component for optimization,<img> for local images,import { Image } from 'astro:assets';,"<img src=""./image.jpg"">",High,https://docs.astro.build/en/guides/images/
25,Performance,Use picture for responsive images,Multiple formats and sizes,<Picture /> for art direction,Single image size for all screens,<Picture /> with multiple sources,<Image /> with single size,Medium,
26,Performance,Lazy load below-fold content,Defer loading non-critical content,loading=lazy for images client:visible for components,Load everything immediately,"<img loading=""lazy"">",No lazy loading,Medium,
27,Performance,Minimize client directives,Each directive adds JS bundle,Audit client: usage regularly,Sprinkle client:load everywhere,Only interactive components hydrated,Every component with client:load,High,
28,ViewTransitions,Enable View Transitions,Smooth page transitions,<ViewTransitions /> in head,Full page reloads,"import { ViewTransitions } from 'astro:transitions';",No transition API,Medium,https://docs.astro.build/en/guides/view-transitions/
28,ViewTransitions,Enable View Transitions,Smooth page transitions,<ViewTransitions /> in head,Full page reloads,import { ViewTransitions } from 'astro:transitions';,No transition API,Medium,https://docs.astro.build/en/guides/view-transitions/
29,ViewTransitions,Use transition:name,Named elements for morphing,transition:name for persistent elements,Unnamed transitions,"<header transition:name=""header"">",<header> without name,Low,
30,ViewTransitions,Handle transition:persist,Keep state across navigations,transition:persist for media players,Re-initialize on every navigation,"<video transition:persist id=""player"">",Video restarts on navigation,Medium,
31,ViewTransitions,Add fallback for no-JS,Graceful degradation,Content works without JS,Require JS for basic navigation,Static content accessible,Broken without ViewTransitions JS,High,
32,SEO,Use built-in SEO component,Head management for meta tags,Astro SEO integration or manual head,No meta tags,"<title>{title}</title><meta name=""description"">",No SEO tags,High,
33,SEO,Generate sitemap,Automatic sitemap generation,@astrojs/sitemap integration,Manual sitemap maintenance,npx astro add sitemap,Hand-written sitemap.xml,Medium,https://docs.astro.build/en/guides/integrations-guide/sitemap/
34,SEO,Add RSS feed for content,RSS for blogs and content sites,@astrojs/rss for feed generation,No RSS feed,rss() helper in pages/rss.xml.js,No feed for blog,Low,https://docs.astro.build/en/guides/rss/
35,SEO,Use canonical URLs,Prevent duplicate content issues,Astro.url for canonical generation,"<link rel=""canonical"" href={Astro.url}>",No canonical tags,Medium,
35,SEO,Use canonical URLs,Prevent duplicate content issues,Astro.url for canonical generation,No canonical tags,"<link rel=""canonical"" href={Astro.url}>",No canonical tags,Medium,
36,Integrations,Use official integrations,Astro's integration system,npx astro add for integrations,Manual configuration,npx astro add react,Manual React setup,Medium,https://docs.astro.build/en/guides/integrations-guide/
37,Integrations,Configure integrations in astro.config,Centralized configuration,integrations array in config,Scattered configuration,"integrations: [react(), tailwind()]",Multiple config files,Low,
38,Integrations,Use adapter for deployment,Platform-specific adapters,Correct adapter for host,Wrong or no adapter,@astrojs/vercel for Vercel,No adapter for SSR,High,https://docs.astro.build/en/guides/deploy/
39,TypeScript,Enable TypeScript,Type safety for Astro projects,tsconfig.json with astro types,No TypeScript,Astro TypeScript template,JavaScript only,Medium,https://docs.astro.build/en/guides/typescript/
40,TypeScript,Type component props,Define prop interfaces,Props interface in frontmatter,Untyped props,"interface Props { title: string }",No props typing,Medium,
40,TypeScript,Type component props,Define prop interfaces,Props interface in frontmatter,Untyped props,interface Props { title: string },No props typing,Medium,
41,TypeScript,Use strict mode,Catch errors early,strict: true in tsconfig,Loose TypeScript config,strictest template,base template,Low,
42,Markdown,Use MDX for components,Components in markdown content,@astrojs/mdx for interactive docs,Plain markdown with workarounds,<Component /> in .mdx,HTML in .md files,Medium,https://docs.astro.build/en/guides/integrations-guide/mdx/
43,Markdown,Configure markdown plugins,Extend markdown capabilities,remarkPlugins rehypePlugins in config,Manual HTML for features,remarkPlugins: [remarkToc],Manual TOC in every post,Low,
@ -46,7 +46,7 @@ No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
45,API,Use API routes for endpoints,Server endpoints in pages/api,pages/api/[endpoint].ts for APIs,External API for simple endpoints,pages/api/posts.json.ts,Separate Express server,Medium,https://docs.astro.build/en/guides/endpoints/
46,API,Return proper responses,Use Response object,new Response() with headers,Plain objects,return new Response(JSON.stringify(data)),return data,Medium,
47,API,Handle methods correctly,Export named method handlers,export GET POST handlers,Single default export,export const GET = async () => {},export default async () => {},Low,
48,Security,Sanitize user content,Prevent XSS in dynamic content,set:html only for trusted content,set:html with user input,"<Fragment set:html={sanitized} />","<div set:html={userInput} />",High,
48,Security,Sanitize user content,Prevent XSS in dynamic content,set:html only for trusted content,set:html with user input,<Fragment set:html={sanitized} />,<div set:html={userInput} />,High,
49,Security,Use HTTPS in production,Secure connections,HTTPS for all production sites,HTTP in production,https://example.com,http://example.com,High,
50,Security,Validate API input,Check and sanitize all input,Zod validation for API routes,Trust all input,const body = schema.parse(data),const body = await request.json(),High,
51,Build,Use hybrid rendering,Mix static and dynamic pages,output: 'hybrid' for flexibility,All SSR or all static,prerender per-page basis,Single rendering mode,Medium,https://docs.astro.build/en/guides/server-side-rendering/#hybrid-rendering

Can't render this file because it contains an unexpected character in line 14 and column 147.

View File

@ -0,0 +1,57 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,XAML,Use Avalonia XAML namespace,Avalonia has its own XAML namespace not WPF,xmlns= for Avalonia-specific namespace,WPF xmlns or UWP xmlns,"<Window xmlns=""https://github.com/avaloniaui"">","<Window xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">",High,https://docs.avaloniaui.net/docs/fundamentals/avalonia-xaml
2,XAML,Use compiled bindings with x:DataType,Enable compile-time binding validation,x:DataType on root or DataTemplate for compiled bindings,Reflection-based bindings in production,"<Window x:DataType=""vm:MainViewModel""><TextBlock Text=""{Binding Name}""/></Window>","<Window><TextBlock Text=""{Binding Name}""/> without x:DataType",High,https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
3,XAML,Enable compiled bindings globally,AvaloniaUseCompiledBindingsByDefault in csproj makes every binding require x:DataType and is required for trim-safe Native AOT,AvaloniaUseCompiledBindingsByDefault MSBuild property in csproj,Relying on runtime binding resolution,"<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>","No compiled binding enforcement",High,https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
4,XAML,Use #name shorthand for element-to-element bindings,Compiled bindings cannot resolve {Binding ElementName=...} - use the #name shorthand which relies on NameScope lookup,#name shorthand referencing x:Name controls in the same NameScope,ElementName binding inside a compiled-binding scope,"<TextBlock Text=""{Binding #SearchBox.Text}""/>","<TextBlock Text=""{Binding ElementName=SearchBox, Path=Text}""/> under compiled bindings",Medium,https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
5,Styling,Use CSS-like selectors,Avalonia uses selectors not implicit styles,Selectors targeting control types classes and pseudoclasses,WPF-style implicit Style with TargetType,"<Style Selector=""Button.primary""><Setter Property=""Background"" Value=""Blue""/></Style>","<Style TargetType=""Button""> without Selector",High,https://docs.avaloniaui.net/docs/styling/selectors
6,Styling,Use pseudoclass selectors for states,Target control states with colon syntax,:pointerover :pressed :focus for interactive states,VisualStateManager or Triggers,"<Style Selector=""Button:pointerover""><Setter Property=""Opacity"" Value=""0.8""/></Style>","<VisualStateManager> for hover effects",Medium,https://docs.avaloniaui.net/docs/styling/pseudoclasses
7,Styling,Use nesting selectors,Child and descendant combinators for scoped styles,> for direct child and space for descendant,Flat selectors that match too broadly,"<Style Selector=""StackPanel > Button""><Setter Property=""Margin"" Value=""4""/></Style>","<Style Selector=""Button""> that affects all buttons unintentionally",Medium,https://docs.avaloniaui.net/docs/styling/style-selector-syntax
8,Styling,Use StyleInclude for modularity,Split styles into separate AXAML files,StyleInclude to import themed resource files,All styles in a single monolithic App.axaml,"<StyleInclude Source=""/Styles/ButtonStyles.axaml""/>","1000+ line App.axaml with all styles",Medium,https://docs.avaloniaui.net/docs/styling/styles
9,Styling,Use Fluent or Simple theme,Built-in Avalonia themes,FluentTheme or SimpleTheme as base,Custom theme from scratch,"<FluentTheme/>","Building all control templates manually",High,https://docs.avaloniaui.net/docs/styling/themes
10,Styling,Use theme variants for dark mode,Switch between light and dark,RequestedThemeVariant for theme switching,"Hardcoded colors ignoring theme variants","Application.Current.RequestedThemeVariant = ThemeVariant.Dark;","Manually changing every brush for dark mode",Medium,https://docs.avaloniaui.net/docs/styling/themes
11,Controls,Use DataGrid for tabular data,DataGrid is a separate Avalonia.Controls.DataGrid NuGet package and requires its theme StyleInclude in App.axaml,DataGrid after adding package and StyleInclude for the matching theme,Custom Grid layouts for tabular data or DataGrid without the theme StyleInclude,"<DataGrid ItemsSource=""{Binding Items}"" AutoGenerateColumns=""False""/> with <StyleInclude Source=""avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml""/> in App.axaml","<DataGrid/> with no package reference or no StyleInclude (renders unstyled)",Medium,https://docs.avaloniaui.net/docs/reference/controls/datagrid/
12,Controls,Use TreeView with TreeDataTemplate,Avalonia uses TreeDataTemplate for hierarchical data - HierarchicalDataTemplate is WPF only,TreeDataTemplate inside TreeView.ItemTemplate with ItemsSource pointing at child collection,HierarchicalDataTemplate copied from WPF or nested ItemsControls,"<TreeView ItemsSource=""{Binding Nodes}""><TreeView.ItemTemplate><TreeDataTemplate ItemsSource=""{Binding Children}""><TextBlock Text=""{Binding Name}""/></TreeDataTemplate></TreeView.ItemTemplate></TreeView>","<TreeView><TreeView.ItemTemplate><HierarchicalDataTemplate/></TreeView.ItemTemplate></TreeView> // HierarchicalDataTemplate does not exist in Avalonia",High,https://docs.avaloniaui.net/docs/reference/controls/treeview-1
13,Controls,Use NativeMenu for platform menus,Native menu bar on macOS and desktop,NativeMenu for cross-platform menu bar,Custom menu implementation per platform,"<NativeMenu.Menu><NativeMenu><NativeMenuItem Header=""File""/></NativeMenu></NativeMenu.Menu>","Custom menu bar control for each platform",Medium,https://docs.avaloniaui.net/docs/reference/controls/nativemenu
14,Data Binding,Implement INotifyPropertyChanged,Standard .NET property notification,INotifyPropertyChanged or CommunityToolkit.Mvvm,Properties without change notification,"[ObservableProperty] private string _name;","public string Name { get; set; } without notification",High,https://docs.avaloniaui.net/docs/data-binding/inotifypropertychanged
15,Data Binding,Use ObservableCollection for lists,UI updates on collection changes,ObservableCollection<T> for bound collections,List<T> for ItemsSources,"ObservableCollection<Item> Items { get; } = new();","List<Item> Items { get; set; }",High,https://docs.avaloniaui.net/docs/data-binding/inotifypropertychanged
16,Data Binding,Use binding to named controls,Element-to-element binding with # syntax,#ElementName.Property for cross-element binding,Code-behind for element references,"<TextBlock Text=""{Binding #slider.Value, StringFormat='{}{0:F0}'}""/>","Code-behind ValueChanged handler to update TextBlock",Medium,https://docs.avaloniaui.net/docs/data-binding/introduction-to-data-binding
17,Data Binding,Use converters or FuncValueConverter,Transform data for display,FuncValueConverter for simple inline conversions,Complex IValueConverter classes for trivial transforms,"public static FuncValueConverter<bool, IBrush> BoolToColor = new(b => b ? Brushes.Green : Brushes.Red);","Full IValueConverter class for bool to color",Medium,https://docs.avaloniaui.net/docs/data-binding/how-to-create-a-custom-data-binding-converter
18,Cross-Platform,Use platform-specific code carefully,Isolate platform code behind abstractions,Interface + platform implementation pattern,#if directives scattered through ViewModels,"IPlatformService with platform-specific implementations","#if WINDOWS ... #elif LINUX ... in ViewModel",Medium,https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/
19,Cross-Platform,Test on all target platforms,Rendering and behavior varies across platforms,CI testing on Windows macOS and Linux,Testing only on development platform,"GitHub Actions matrix with windows-latest ubuntu-latest macos-latest","Testing only on Windows assuming cross-platform works",High,https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/
20,Cross-Platform,Handle platform file paths,Path separators differ across OS,Path.Combine and Environment.SpecialFolder,Hardcoded backslashes or forward slashes,"Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ""MyApp"")","@""C:\Users\data\config.json""",Medium,https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/dealing-with-platforms
21,Cross-Platform,Use Avalonia asset system,Platform-agnostic resource loading,avares:// URI scheme for embedded resources,File system paths for assets,"<Image Source=""avares://MyApp/Assets/logo.png""/>","<Image Source=""C:/images/logo.png""/>",High,https://docs.avaloniaui.net/docs/fundamentals/including-assets
22,Performance,Use virtualization for large lists,Only render visible items,ListBox and ItemsRepeater with virtualization,Non-virtualizing ItemsControl for large lists,"<ListBox ItemsSource=""{Binding LargeList}""/>","<ItemsControl><StackPanel> for 10K items",High,https://docs.avaloniaui.net/docs/reference/controls/listbox
23,Performance,Avoid unnecessary bindings,Each binding has overhead,Bind only properties that change,Binding static labels and headers,"<TextBlock Text=""{Binding DynamicTitle}""/> but static: <TextBlock Text=""Settings""/>","<TextBlock Text=""{Binding SettingsLabel}""/> for constant string",Low,https://docs.avaloniaui.net/docs/data-binding/introduction-to-data-binding
24,Performance,Set bitmap interpolation mode on scaled images,RenderOptions.BitmapInterpolationMode controls image scaling quality vs cost; default may look aliased on upscaled or downscaled bitmaps,RenderOptions.SetBitmapInterpolationMode tuned to the use case,Default interpolation on scaled images that look blurry or aliased,"RenderOptions.SetBitmapInterpolationMode(image, BitmapInterpolationMode.HighQuality);","Image scaled with Stretch and no interpolation hint set",Low,https://docs.avaloniaui.net/docs/concepts/image-interpolation
25,Performance,Profile with Avalonia DevTools,Built-in diagnostic tools,DevTools for visual tree and binding inspection,Console.WriteLine debugging,Attach DevTools in debug mode with F12,Print statements to debug layout issues,Medium,https://docs.avaloniaui.net/docs/guides/implementation-guides/developer-tools
26,Architecture,Use MVVM with ReactiveUI or CommunityToolkit,Proven MVVM frameworks for Avalonia,ReactiveUI or CommunityToolkit.Mvvm for ViewModels,Code-behind for all logic,"public class MainViewModel : ReactiveObject { }","MainWindow.axaml.cs with all business logic",High,https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/
27,Architecture,Use ViewLocator pattern,Convention-based View-ViewModel resolution,ViewLocator for automatic view resolution,Manual view instantiation and DataContext wiring,"class ViewLocator : IDataTemplate { Build(object data) => new MainView(); }","new MainView { DataContext = new MainViewModel() } everywhere",Medium,https://docs.avaloniaui.net/docs/data-templates/view-locator
28,Architecture,Use dependency injection,Register services in a Microsoft.Extensions.DependencyInjection container during startup before any view is constructed - resolve ViewModels through the provider not via a static ServiceLocator,Build the ServiceProvider in BuildAvaloniaApp or OnFrameworkInitializationCompleted then resolve ViewModels from it,Static ServiceLocator or new-ing ViewModels inline in code-behind,"services.AddSingleton<IDataService, DataService>(); services.AddTransient<MainViewModel>(); var provider = services.BuildServiceProvider(); // wired before windows are created","ServiceLocator.Current.GetInstance<IDataService>() called from random ViewModels with no registration ordering",Medium,https://docs.avaloniaui.net/docs/app-development/dependency-injection
29,Architecture,Separate Views from ViewModels,Keep UI and logic in separate projects,ViewModels in a separate class library,ViewModels in the same project referencing Avalonia types,"MyApp.Core (no Avalonia refs) + MyApp.Desktop (Avalonia views)","ViewModel importing Avalonia.Controls",Medium,https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/
30,Accessibility,Set AutomationProperties,Enable screen reader support,AutomationProperties.Name on interactive controls,Controls without accessible names,"<Button AutomationProperties.Name=""Close dialog""><PathIcon Data=""...""/></Button>","<Button><PathIcon/></Button> without accessible name",High,https://docs.avaloniaui.net/api/avalonia/automation/automationproperties
31,Accessibility,Support keyboard navigation,Full keyboard operability,TabIndex and KeyboardNavigation properties,Mouse-only interactions,"<Button TabIndex=""1"" Content=""Save""/>","Clickable controls without keyboard support",High,https://docs.avaloniaui.net/docs/input-interaction/keyboard-and-hotkeys
32,Accessibility,Use semantic control types,Controls convey meaning to assistive tech,Button for actions ListBox for selection,TextBlock with PointerPressed as fake button,"<Button Content=""Submit""/>","<TextBlock PointerPressed=""OnSubmitClick"" Text=""Submit""/>",High,https://docs.avaloniaui.net/docs/reference/controls/
33,Testing,Use Avalonia.Headless for UI tests,Run UI tests without display server,Avalonia.Headless for CI-compatible UI testing,Skipping UI tests in CI,"[AvaloniaTest] public void Button_Click_Updates_Label() { ... }","UI tests that require a display server",Medium,https://docs.avaloniaui.net/docs/concepts/headless/
34,Testing,Unit test ViewModels,Test business logic independently,xUnit or NUnit on ViewModel methods,Testing through UI only,"[Fact] public void AddItem_IncreasesCount() { vm.AddItem(); Assert.Equal(1, vm.Items.Count); }","Manual testing by running the app",Medium,https://docs.avaloniaui.net/docs/concepts/headless/
35,Testing,Test converters independently,Value converters contain testable logic,Unit tests on Convert and ConvertBack,Assuming converters work without tests,"[Fact] public void BoolToColor_True_ReturnsGreen() { Assert.Equal(Brushes.Green, converter.Convert(true)); }","No converter tests",Low,https://docs.avaloniaui.net/docs/data-binding/how-to-create-a-custom-data-binding-converter
36,Navigation,Use ReactiveUI routing for navigation,IScreen and RoutingState for page navigation,ReactiveUI RoutingState with IScreen on main ViewModel,Manual content swapping in code-behind,"public RoutingState Router { get; } = new(); Router.Navigate.Execute(new DetailViewModel());","contentControl.Content = new DetailView(); in code-behind",Medium,https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/routing
37,Navigation,Use UserControl for views,Pages and screens should be UserControls hosted in a ContentControl,UserControl for each view with RoutedViewHost or ContentControl,Window per page or nested Windows,"<UserControl x:Class=""MyApp.Views.DetailView"">","new Window() for each page in the app",Medium,https://docs.avaloniaui.net/docs/custom-controls/
38,Navigation,Use page transitions for view switching,Built-in transitions for smooth navigation,CrossFade PageSlide or CompositePageTransition declared as a property element,Abrupt content swaps with no visual continuity,"<RoutedViewHost><RoutedViewHost.PageTransition><PageSlide Orientation=""Horizontal"" Duration=""0:0:0.3""/></RoutedViewHost.PageTransition></RoutedViewHost>","ContentControl with no transition between views",Low,https://docs.avaloniaui.net/docs/reference/controls/transitioningcontentcontrol
39,Navigation,Support back navigation,Maintain navigation history for complex apps,Router.NavigateBack or custom back stack,No way to return to previous views,"<Button Command=""{Binding Router.NavigateBack}"" Content=""Back""/>","Single-direction navigation with no back support",Medium,https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/routing
40,Controls,Use AutoCompleteBox for search,Built-in autocomplete and suggestion control,AutoCompleteBox with FilterMode and ItemsSource,TextBox with manual Popup and ListBox for suggestions,"<AutoCompleteBox ItemsSource=""{Binding Suggestions}"" FilterMode=""Contains""/>","TextBox with custom Popup for autocomplete",Medium,https://docs.avaloniaui.net/docs/reference/controls/autocompletebox
41,Controls,Use TabControl for tabbed interfaces,Standard tabbed navigation and content switching,TabControl with TabItem for tabbed layouts,Manual toggle buttons swapping content,"<TabControl><TabItem Header=""General""><GeneralView/></TabItem><TabItem Header=""Advanced""><AdvancedView/></TabItem></TabControl>","ToggleButtons with manual content switching logic",Medium,https://docs.avaloniaui.net/docs/reference/controls/tabcontrol
42,Controls,Use SplitView for master-detail,Collapsible pane layout for navigation or panels,SplitView with Pane and Content areas,Manual Grid with column toggling for sidebar,"<SplitView IsPaneOpen=""{Binding IsPaneOpen}"" DisplayMode=""Inline""><SplitView.Pane><ListBox/></SplitView.Pane><ContentControl/></SplitView>","Grid with manual column width animation for sidebar",Medium,https://docs.avaloniaui.net/docs/reference/controls/splitview
43,Controls,Use Flyout for contextual actions,Attach popup menus and actions to controls,Flyout and MenuFlyout on Button or other controls,Custom Popup positioning and management,"<Button Content=""Options""><Button.Flyout><MenuFlyout><MenuItem Header=""Edit""/><MenuItem Header=""Delete""/></MenuFlyout></Button.Flyout></Button>","Custom Popup with manual open/close and positioning",Medium,https://docs.avaloniaui.net/docs/reference/controls/flyouts
44,Lifecycle,Use AppBuilder for app configuration,Configure platform features and services at startup,AppBuilder with UsePlatformDetect and fluent API,Manual platform initialization,"AppBuilder.Configure<App>().UsePlatformDetect().WithInterFont().StartWithClassicDesktopLifetime(args);","Manual platform-specific startup code per OS",High,https://docs.avaloniaui.net/docs/fundamentals/application-lifetimes
45,Lifecycle,Initialize MainWindow in OnFrameworkInitializationCompleted,Override OnFrameworkInitializationCompleted on App and check ApplicationLifetime - on desktop cast to IClassicDesktopStyleApplicationLifetime to set MainWindow and ShutdownMode; never create windows in the App constructor before the framework is ready,Override OnFrameworkInitializationCompleted and pattern-match on IClassicDesktopStyleApplicationLifetime for desktop-only setup,Creating windows in the App constructor or assuming the same lifetime type on every platform,"public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new MainWindow(); desktop.ShutdownMode = ShutdownMode.OnMainWindowClose; } base.OnFrameworkInitializationCompleted(); }","public App() { new MainWindow().Show(); } // window created before framework init and ignores lifetime type",High,https://docs.avaloniaui.net/docs/fundamentals/application-lifetimes
46,Animation,Use CSS-like keyframe animations,Avalonia supports declarative animations in XAML and code,Animation with KeyFrame and Setter for property animations,Manual timer-based property updates,"<Border.Transitions><DoubleTransition Property=""Opacity"" Duration=""0:0:0.3""/></Border.Transitions>","DispatcherTimer ticking to update Opacity manually",Medium,https://docs.avaloniaui.net/docs/graphics-animation/animations
47,Animation,Use Transitions for implicit animations,Automatic animation when property values change,Transitions collection on controls for smooth changes,Instant property changes with no visual feedback,"<Button.Transitions><TransformOperationsTransition Property=""RenderTransform"" Duration=""0:0:0.2""/></Button.Transitions>","Direct property set with no transition",Low,https://docs.avaloniaui.net/docs/graphics-animation/control-transitions
48,Performance,Use compiled bindings and TrimmerRoots.xml for PublishAot,Avalonia 11+ supports Native AOT for self-contained desktop deployments; XAML reflection paths must use compiled bindings or be preserved via TrimmerRoots so trimming does not strip them,x:CompileBindings=True on every view plus TrimmerRoots.xml for runtime-resolved types,PublishAot with reflection-based {Binding} markup or trimming without checking warnings,"<UserControl x:CompileBindings=""True"" x:DataType=""vm:MainViewModel""/> with <PublishAot>true</PublishAot> and TrimmerRoots.xml listing reflected types","<PublishAot>true</PublishAot> with default <Binding> markup and no TrimmerRoots configuration",Medium,https://docs.avaloniaui.net/docs/deployment/native-aot
49,Threading,Marshal cross-thread work to the UI thread,Avalonia controls and bound properties are not thread-safe and touching them off the UI thread throws InvalidOperationException,Dispatcher.UIThread.Post or InvokeAsync to bounce work back to the UI thread,Direct property writes from Task.Run or background threads,"await Dispatcher.UIThread.InvokeAsync(() => Status = ""Done"");","Task.Run(() => { Status = ""Done""; }); // throws Call from invalid thread",High,https://docs.avaloniaui.net/docs/app-development/threading
50,Commands,Use AsyncRelayCommand or ReactiveCommand for async work,Async-aware commands disable themselves while running and surface CancellationToken so users cannot double-invoke a long operation,[RelayCommand] async Task method or ReactiveCommand.CreateFromTask,async void event handlers or fire-and-forget Task.Run from a click handler,"[RelayCommand] private async Task LoadAsync(CancellationToken ct) { await _api.GetAsync(ct); }","private async void OnClick(object s, RoutedEventArgs e) { await LongOperation(); }",High,https://docs.avaloniaui.net/docs/input-interaction/commanding
51,Styling,Use DynamicResource for theme-aware brushes,ResourceDictionary.ThemeDictionaries entries must be looked up via DynamicResource - StaticResource resolves once at load and won't update when the active theme variant changes,DynamicResource for brushes and colors that follow the active theme variant,Hardcoded hex colors or StaticResource for values that should follow theme,"<Border Background=""{DynamicResource SystemControlBackgroundAccentBrush}""/>","<Border Background=""#FF0078D4""/> while the rest of the app honors light/dark variants",Medium,https://docs.avaloniaui.net/docs/app-development/resource-dictionary
52,Input,Use HotKey or KeyBinding for keyboard shortcuts,Built-in HotKey on ICommandSource and Window.KeyBindings handle modifier keys focus scoping and cross-platform Ctrl/Cmd mapping,HotKey on a command-bound control or KeyBinding on the Window,Manual KeyDown handlers checking Key and KeyModifiers,"<Button Command=""{Binding SaveCommand}"" HotKey=""Ctrl+S"" Content=""Save""/>","OnKeyDown checking e.Key == Key.S && e.KeyModifiers == KeyModifiers.Control",Medium,https://docs.avaloniaui.net/docs/input-interaction/mouse-and-keyboard-shortcuts
53,Windowing,Customize window chrome with ExtendClientAreaToDecorationsHint,Set ExtendClientAreaToDecorationsHint to extend content into the title bar area and tag a region with WindowDecorationProperties.ElementRole=TitleBar to keep native drag and maximize behavior,ExtendClientAreaToDecorationsHint plus a region tagged ElementRole=TitleBar,SystemDecorations=None with hand-rolled PointerPressed dragging in code-behind,"<Window ExtendClientAreaToDecorationsHint=""True""><Border WindowDecorationProperties.ElementRole=""TitleBar""/></Window>","<Window SystemDecorations=""None""> with manual BeginMoveDrag from code-behind",Medium,https://docs.avaloniaui.net/docs/app-development/window-management
54,Storage,Use TopLevel.StorageProvider for file pickers,The legacy OpenFileDialog/SaveFileDialog APIs are obsolete in Avalonia 11 - use TopLevel.GetTopLevel(this).StorageProvider with OpenFilePickerAsync/SaveFilePickerAsync/OpenFolderPickerAsync which returns IStorageFile/IStorageFolder and works on desktop mobile and browser,TopLevel.StorageProvider with OpenFilePickerAsync and FilePickerOpenOptions,OpenFileDialog or SaveFileDialog from older Avalonia samples or copied from WPF,"var top = TopLevel.GetTopLevel(this); var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false });","var dlg = new OpenFileDialog(); var paths = await dlg.ShowAsync(window); // obsolete API",High,https://docs.avaloniaui.net/docs/concepts/services/storage-provider/
55,Windowing,Use TrayIcon for system tray icon,TrayIcon shows a native system tray/notification-area icon with a NativeMenu - declare it via the Application.TrayIcon.Icons attached property in App.axaml; works on Windows macOS and most Linux desktops,TrayIcon with NativeMenu inside TrayIcon.Icons on the Application,Custom borderless window pretending to be a tray icon or per-platform native interop,"<TrayIcon.Icons><TrayIcons><TrayIcon Icon=""/Assets/tray.ico"" ToolTipText=""MyApp""><TrayIcon.Menu><NativeMenu><NativeMenuItem Header=""Show"" Command=""{Binding ShowCommand}""/></NativeMenu></TrayIcon.Menu></TrayIcon></TrayIcons></TrayIcon.Icons>","Hidden Window with custom shell-notification-area P/Invoke",Medium,https://docs.avaloniaui.net/docs/controls/tray-icon
56,Cross-Platform,Use OnPlatform and OnFormFactor markup for per-OS values,OnPlatform and OnFormFactor markup extensions resolve to a different value per OS or form factor at XAML load time and replace if-statements in code-behind for tweaks like fonts spacing or icon sizes,OnPlatform with Default Windows macOS Linux entries directly in the property setter,RuntimeInformation.IsOSPlatform branches in code-behind to set XAML properties,"<TextBlock FontFamily=""{OnPlatform Default='Inter', Windows='Segoe UI', macOS='SF Pro Text', Linux='Ubuntu'}""/>","if (OperatingSystem.IsWindows()) textBlock.FontFamily = new(""Segoe UI""); else if (OperatingSystem.IsMacOS()) ...",Medium,https://docs.avaloniaui.net/docs/platform-specific-guides/xaml
1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 XAML Use Avalonia XAML namespace Avalonia has its own XAML namespace not WPF xmlns= for Avalonia-specific namespace WPF xmlns or UWP xmlns <Window xmlns="https://github.com/avaloniaui"> <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> High https://docs.avaloniaui.net/docs/fundamentals/avalonia-xaml
3 2 XAML Use compiled bindings with x:DataType Enable compile-time binding validation x:DataType on root or DataTemplate for compiled bindings Reflection-based bindings in production <Window x:DataType="vm:MainViewModel"><TextBlock Text="{Binding Name}"/></Window> <Window><TextBlock Text="{Binding Name}"/> without x:DataType High https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
4 3 XAML Enable compiled bindings globally AvaloniaUseCompiledBindingsByDefault in csproj makes every binding require x:DataType and is required for trim-safe Native AOT AvaloniaUseCompiledBindingsByDefault MSBuild property in csproj Relying on runtime binding resolution <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault> No compiled binding enforcement High https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
5 4 XAML Use #name shorthand for element-to-element bindings Compiled bindings cannot resolve {Binding ElementName=...} - use the #name shorthand which relies on NameScope lookup #name shorthand referencing x:Name controls in the same NameScope ElementName binding inside a compiled-binding scope <TextBlock Text="{Binding #SearchBox.Text}"/> <TextBlock Text="{Binding ElementName=SearchBox, Path=Text}"/> under compiled bindings Medium https://docs.avaloniaui.net/docs/data-binding/compiled-bindings
6 5 Styling Use CSS-like selectors Avalonia uses selectors not implicit styles Selectors targeting control types classes and pseudoclasses WPF-style implicit Style with TargetType <Style Selector="Button.primary"><Setter Property="Background" Value="Blue"/></Style> <Style TargetType="Button"> without Selector High https://docs.avaloniaui.net/docs/styling/selectors
7 6 Styling Use pseudoclass selectors for states Target control states with colon syntax :pointerover :pressed :focus for interactive states VisualStateManager or Triggers <Style Selector="Button:pointerover"><Setter Property="Opacity" Value="0.8"/></Style> <VisualStateManager> for hover effects Medium https://docs.avaloniaui.net/docs/styling/pseudoclasses
8 7 Styling Use nesting selectors Child and descendant combinators for scoped styles > for direct child and space for descendant Flat selectors that match too broadly <Style Selector="StackPanel > Button"><Setter Property="Margin" Value="4"/></Style> <Style Selector="Button"> that affects all buttons unintentionally Medium https://docs.avaloniaui.net/docs/styling/style-selector-syntax
9 8 Styling Use StyleInclude for modularity Split styles into separate AXAML files StyleInclude to import themed resource files All styles in a single monolithic App.axaml <StyleInclude Source="/Styles/ButtonStyles.axaml"/> 1000+ line App.axaml with all styles Medium https://docs.avaloniaui.net/docs/styling/styles
10 9 Styling Use Fluent or Simple theme Built-in Avalonia themes FluentTheme or SimpleTheme as base Custom theme from scratch <FluentTheme/> Building all control templates manually High https://docs.avaloniaui.net/docs/styling/themes
11 10 Styling Use theme variants for dark mode Switch between light and dark RequestedThemeVariant for theme switching Hardcoded colors ignoring theme variants Application.Current.RequestedThemeVariant = ThemeVariant.Dark; Manually changing every brush for dark mode Medium https://docs.avaloniaui.net/docs/styling/themes
12 11 Controls Use DataGrid for tabular data DataGrid is a separate Avalonia.Controls.DataGrid NuGet package and requires its theme StyleInclude in App.axaml DataGrid after adding package and StyleInclude for the matching theme Custom Grid layouts for tabular data or DataGrid without the theme StyleInclude <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False"/> with <StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/> in App.axaml <DataGrid/> with no package reference or no StyleInclude (renders unstyled) Medium https://docs.avaloniaui.net/docs/reference/controls/datagrid/
13 12 Controls Use TreeView with TreeDataTemplate Avalonia uses TreeDataTemplate for hierarchical data - HierarchicalDataTemplate is WPF only TreeDataTemplate inside TreeView.ItemTemplate with ItemsSource pointing at child collection HierarchicalDataTemplate copied from WPF or nested ItemsControls <TreeView ItemsSource="{Binding Nodes}"><TreeView.ItemTemplate><TreeDataTemplate ItemsSource="{Binding Children}"><TextBlock Text="{Binding Name}"/></TreeDataTemplate></TreeView.ItemTemplate></TreeView> <TreeView><TreeView.ItemTemplate><HierarchicalDataTemplate/></TreeView.ItemTemplate></TreeView> // HierarchicalDataTemplate does not exist in Avalonia High https://docs.avaloniaui.net/docs/reference/controls/treeview-1
14 13 Controls Use NativeMenu for platform menus Native menu bar on macOS and desktop NativeMenu for cross-platform menu bar Custom menu implementation per platform <NativeMenu.Menu><NativeMenu><NativeMenuItem Header="File"/></NativeMenu></NativeMenu.Menu> Custom menu bar control for each platform Medium https://docs.avaloniaui.net/docs/reference/controls/nativemenu
15 14 Data Binding Implement INotifyPropertyChanged Standard .NET property notification INotifyPropertyChanged or CommunityToolkit.Mvvm Properties without change notification [ObservableProperty] private string _name; public string Name { get; set; } without notification High https://docs.avaloniaui.net/docs/data-binding/inotifypropertychanged
16 15 Data Binding Use ObservableCollection for lists UI updates on collection changes ObservableCollection<T> for bound collections List<T> for ItemsSources ObservableCollection<Item> Items { get; } = new(); List<Item> Items { get; set; } High https://docs.avaloniaui.net/docs/data-binding/inotifypropertychanged
17 16 Data Binding Use binding to named controls Element-to-element binding with # syntax #ElementName.Property for cross-element binding Code-behind for element references <TextBlock Text="{Binding #slider.Value, StringFormat='{}{0:F0}'}"/> Code-behind ValueChanged handler to update TextBlock Medium https://docs.avaloniaui.net/docs/data-binding/introduction-to-data-binding
18 17 Data Binding Use converters or FuncValueConverter Transform data for display FuncValueConverter for simple inline conversions Complex IValueConverter classes for trivial transforms public static FuncValueConverter<bool, IBrush> BoolToColor = new(b => b ? Brushes.Green : Brushes.Red); Full IValueConverter class for bool to color Medium https://docs.avaloniaui.net/docs/data-binding/how-to-create-a-custom-data-binding-converter
19 18 Cross-Platform Use platform-specific code carefully Isolate platform code behind abstractions Interface + platform implementation pattern #if directives scattered through ViewModels IPlatformService with platform-specific implementations #if WINDOWS ... #elif LINUX ... in ViewModel Medium https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/
20 19 Cross-Platform Test on all target platforms Rendering and behavior varies across platforms CI testing on Windows macOS and Linux Testing only on development platform GitHub Actions matrix with windows-latest ubuntu-latest macos-latest Testing only on Windows assuming cross-platform works High https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/
21 20 Cross-Platform Handle platform file paths Path separators differ across OS Path.Combine and Environment.SpecialFolder Hardcoded backslashes or forward slashes Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp") @"C:\Users\data\config.json" Medium https://docs.avaloniaui.net/docs/guides/building-cross-platform-applications/dealing-with-platforms
22 21 Cross-Platform Use Avalonia asset system Platform-agnostic resource loading avares:// URI scheme for embedded resources File system paths for assets <Image Source="avares://MyApp/Assets/logo.png"/> <Image Source="C:/images/logo.png"/> High https://docs.avaloniaui.net/docs/fundamentals/including-assets
23 22 Performance Use virtualization for large lists Only render visible items ListBox and ItemsRepeater with virtualization Non-virtualizing ItemsControl for large lists <ListBox ItemsSource="{Binding LargeList}"/> <ItemsControl><StackPanel> for 10K items High https://docs.avaloniaui.net/docs/reference/controls/listbox
24 23 Performance Avoid unnecessary bindings Each binding has overhead Bind only properties that change Binding static labels and headers <TextBlock Text="{Binding DynamicTitle}"/> but static: <TextBlock Text="Settings"/> <TextBlock Text="{Binding SettingsLabel}"/> for constant string Low https://docs.avaloniaui.net/docs/data-binding/introduction-to-data-binding
25 24 Performance Set bitmap interpolation mode on scaled images RenderOptions.BitmapInterpolationMode controls image scaling quality vs cost; default may look aliased on upscaled or downscaled bitmaps RenderOptions.SetBitmapInterpolationMode tuned to the use case Default interpolation on scaled images that look blurry or aliased RenderOptions.SetBitmapInterpolationMode(image, BitmapInterpolationMode.HighQuality); Image scaled with Stretch and no interpolation hint set Low https://docs.avaloniaui.net/docs/concepts/image-interpolation
26 25 Performance Profile with Avalonia DevTools Built-in diagnostic tools DevTools for visual tree and binding inspection Console.WriteLine debugging Attach DevTools in debug mode with F12 Print statements to debug layout issues Medium https://docs.avaloniaui.net/docs/guides/implementation-guides/developer-tools
27 26 Architecture Use MVVM with ReactiveUI or CommunityToolkit Proven MVVM frameworks for Avalonia ReactiveUI or CommunityToolkit.Mvvm for ViewModels Code-behind for all logic public class MainViewModel : ReactiveObject { } MainWindow.axaml.cs with all business logic High https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/
28 27 Architecture Use ViewLocator pattern Convention-based View-ViewModel resolution ViewLocator for automatic view resolution Manual view instantiation and DataContext wiring class ViewLocator : IDataTemplate { Build(object data) => new MainView(); } new MainView { DataContext = new MainViewModel() } everywhere Medium https://docs.avaloniaui.net/docs/data-templates/view-locator
29 28 Architecture Use dependency injection Register services in a Microsoft.Extensions.DependencyInjection container during startup before any view is constructed - resolve ViewModels through the provider not via a static ServiceLocator Build the ServiceProvider in BuildAvaloniaApp or OnFrameworkInitializationCompleted then resolve ViewModels from it Static ServiceLocator or new-ing ViewModels inline in code-behind services.AddSingleton<IDataService, DataService>(); services.AddTransient<MainViewModel>(); var provider = services.BuildServiceProvider(); // wired before windows are created ServiceLocator.Current.GetInstance<IDataService>() called from random ViewModels with no registration ordering Medium https://docs.avaloniaui.net/docs/app-development/dependency-injection
30 29 Architecture Separate Views from ViewModels Keep UI and logic in separate projects ViewModels in a separate class library ViewModels in the same project referencing Avalonia types MyApp.Core (no Avalonia refs) + MyApp.Desktop (Avalonia views) ViewModel importing Avalonia.Controls Medium https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/
31 30 Accessibility Set AutomationProperties Enable screen reader support AutomationProperties.Name on interactive controls Controls without accessible names <Button AutomationProperties.Name="Close dialog"><PathIcon Data="..."/></Button> <Button><PathIcon/></Button> without accessible name High https://docs.avaloniaui.net/api/avalonia/automation/automationproperties
32 31 Accessibility Support keyboard navigation Full keyboard operability TabIndex and KeyboardNavigation properties Mouse-only interactions <Button TabIndex="1" Content="Save"/> Clickable controls without keyboard support High https://docs.avaloniaui.net/docs/input-interaction/keyboard-and-hotkeys
33 32 Accessibility Use semantic control types Controls convey meaning to assistive tech Button for actions ListBox for selection TextBlock with PointerPressed as fake button <Button Content="Submit"/> <TextBlock PointerPressed="OnSubmitClick" Text="Submit"/> High https://docs.avaloniaui.net/docs/reference/controls/
34 33 Testing Use Avalonia.Headless for UI tests Run UI tests without display server Avalonia.Headless for CI-compatible UI testing Skipping UI tests in CI [AvaloniaTest] public void Button_Click_Updates_Label() { ... } UI tests that require a display server Medium https://docs.avaloniaui.net/docs/concepts/headless/
35 34 Testing Unit test ViewModels Test business logic independently xUnit or NUnit on ViewModel methods Testing through UI only [Fact] public void AddItem_IncreasesCount() { vm.AddItem(); Assert.Equal(1, vm.Items.Count); } Manual testing by running the app Medium https://docs.avaloniaui.net/docs/concepts/headless/
36 35 Testing Test converters independently Value converters contain testable logic Unit tests on Convert and ConvertBack Assuming converters work without tests [Fact] public void BoolToColor_True_ReturnsGreen() { Assert.Equal(Brushes.Green, converter.Convert(true)); } No converter tests Low https://docs.avaloniaui.net/docs/data-binding/how-to-create-a-custom-data-binding-converter
37 36 Navigation Use ReactiveUI routing for navigation IScreen and RoutingState for page navigation ReactiveUI RoutingState with IScreen on main ViewModel Manual content swapping in code-behind public RoutingState Router { get; } = new(); Router.Navigate.Execute(new DetailViewModel()); contentControl.Content = new DetailView(); in code-behind Medium https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/routing
38 37 Navigation Use UserControl for views Pages and screens should be UserControls hosted in a ContentControl UserControl for each view with RoutedViewHost or ContentControl Window per page or nested Windows <UserControl x:Class="MyApp.Views.DetailView"> new Window() for each page in the app Medium https://docs.avaloniaui.net/docs/custom-controls/
39 38 Navigation Use page transitions for view switching Built-in transitions for smooth navigation CrossFade PageSlide or CompositePageTransition declared as a property element Abrupt content swaps with no visual continuity <RoutedViewHost><RoutedViewHost.PageTransition><PageSlide Orientation="Horizontal" Duration="0:0:0.3"/></RoutedViewHost.PageTransition></RoutedViewHost> ContentControl with no transition between views Low https://docs.avaloniaui.net/docs/reference/controls/transitioningcontentcontrol
40 39 Navigation Support back navigation Maintain navigation history for complex apps Router.NavigateBack or custom back stack No way to return to previous views <Button Command="{Binding Router.NavigateBack}" Content="Back"/> Single-direction navigation with no back support Medium https://v11.docs.avaloniaui.net/docs/concepts/reactiveui/routing
41 40 Controls Use AutoCompleteBox for search Built-in autocomplete and suggestion control AutoCompleteBox with FilterMode and ItemsSource TextBox with manual Popup and ListBox for suggestions <AutoCompleteBox ItemsSource="{Binding Suggestions}" FilterMode="Contains"/> TextBox with custom Popup for autocomplete Medium https://docs.avaloniaui.net/docs/reference/controls/autocompletebox
42 41 Controls Use TabControl for tabbed interfaces Standard tabbed navigation and content switching TabControl with TabItem for tabbed layouts Manual toggle buttons swapping content <TabControl><TabItem Header="General"><GeneralView/></TabItem><TabItem Header="Advanced"><AdvancedView/></TabItem></TabControl> ToggleButtons with manual content switching logic Medium https://docs.avaloniaui.net/docs/reference/controls/tabcontrol
43 42 Controls Use SplitView for master-detail Collapsible pane layout for navigation or panels SplitView with Pane and Content areas Manual Grid with column toggling for sidebar <SplitView IsPaneOpen="{Binding IsPaneOpen}" DisplayMode="Inline"><SplitView.Pane><ListBox/></SplitView.Pane><ContentControl/></SplitView> Grid with manual column width animation for sidebar Medium https://docs.avaloniaui.net/docs/reference/controls/splitview
44 43 Controls Use Flyout for contextual actions Attach popup menus and actions to controls Flyout and MenuFlyout on Button or other controls Custom Popup positioning and management <Button Content="Options"><Button.Flyout><MenuFlyout><MenuItem Header="Edit"/><MenuItem Header="Delete"/></MenuFlyout></Button.Flyout></Button> Custom Popup with manual open/close and positioning Medium https://docs.avaloniaui.net/docs/reference/controls/flyouts
45 44 Lifecycle Use AppBuilder for app configuration Configure platform features and services at startup AppBuilder with UsePlatformDetect and fluent API Manual platform initialization AppBuilder.Configure<App>().UsePlatformDetect().WithInterFont().StartWithClassicDesktopLifetime(args); Manual platform-specific startup code per OS High https://docs.avaloniaui.net/docs/fundamentals/application-lifetimes
46 45 Lifecycle Initialize MainWindow in OnFrameworkInitializationCompleted Override OnFrameworkInitializationCompleted on App and check ApplicationLifetime - on desktop cast to IClassicDesktopStyleApplicationLifetime to set MainWindow and ShutdownMode; never create windows in the App constructor before the framework is ready Override OnFrameworkInitializationCompleted and pattern-match on IClassicDesktopStyleApplicationLifetime for desktop-only setup Creating windows in the App constructor or assuming the same lifetime type on every platform public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new MainWindow(); desktop.ShutdownMode = ShutdownMode.OnMainWindowClose; } base.OnFrameworkInitializationCompleted(); } public App() { new MainWindow().Show(); } // window created before framework init and ignores lifetime type High https://docs.avaloniaui.net/docs/fundamentals/application-lifetimes
47 46 Animation Use CSS-like keyframe animations Avalonia supports declarative animations in XAML and code Animation with KeyFrame and Setter for property animations Manual timer-based property updates <Border.Transitions><DoubleTransition Property="Opacity" Duration="0:0:0.3"/></Border.Transitions> DispatcherTimer ticking to update Opacity manually Medium https://docs.avaloniaui.net/docs/graphics-animation/animations
48 47 Animation Use Transitions for implicit animations Automatic animation when property values change Transitions collection on controls for smooth changes Instant property changes with no visual feedback <Button.Transitions><TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2"/></Button.Transitions> Direct property set with no transition Low https://docs.avaloniaui.net/docs/graphics-animation/control-transitions
49 48 Performance Use compiled bindings and TrimmerRoots.xml for PublishAot Avalonia 11+ supports Native AOT for self-contained desktop deployments; XAML reflection paths must use compiled bindings or be preserved via TrimmerRoots so trimming does not strip them x:CompileBindings=True on every view plus TrimmerRoots.xml for runtime-resolved types PublishAot with reflection-based {Binding} markup or trimming without checking warnings <UserControl x:CompileBindings="True" x:DataType="vm:MainViewModel"/> with <PublishAot>true</PublishAot> and TrimmerRoots.xml listing reflected types <PublishAot>true</PublishAot> with default <Binding> markup and no TrimmerRoots configuration Medium https://docs.avaloniaui.net/docs/deployment/native-aot
50 49 Threading Marshal cross-thread work to the UI thread Avalonia controls and bound properties are not thread-safe and touching them off the UI thread throws InvalidOperationException Dispatcher.UIThread.Post or InvokeAsync to bounce work back to the UI thread Direct property writes from Task.Run or background threads await Dispatcher.UIThread.InvokeAsync(() => Status = "Done"); Task.Run(() => { Status = "Done"; }); // throws Call from invalid thread High https://docs.avaloniaui.net/docs/app-development/threading
51 50 Commands Use AsyncRelayCommand or ReactiveCommand for async work Async-aware commands disable themselves while running and surface CancellationToken so users cannot double-invoke a long operation [RelayCommand] async Task method or ReactiveCommand.CreateFromTask async void event handlers or fire-and-forget Task.Run from a click handler [RelayCommand] private async Task LoadAsync(CancellationToken ct) { await _api.GetAsync(ct); } private async void OnClick(object s, RoutedEventArgs e) { await LongOperation(); } High https://docs.avaloniaui.net/docs/input-interaction/commanding
52 51 Styling Use DynamicResource for theme-aware brushes ResourceDictionary.ThemeDictionaries entries must be looked up via DynamicResource - StaticResource resolves once at load and won't update when the active theme variant changes DynamicResource for brushes and colors that follow the active theme variant Hardcoded hex colors or StaticResource for values that should follow theme <Border Background="{DynamicResource SystemControlBackgroundAccentBrush}"/> <Border Background="#FF0078D4"/> while the rest of the app honors light/dark variants Medium https://docs.avaloniaui.net/docs/app-development/resource-dictionary
53 52 Input Use HotKey or KeyBinding for keyboard shortcuts Built-in HotKey on ICommandSource and Window.KeyBindings handle modifier keys focus scoping and cross-platform Ctrl/Cmd mapping HotKey on a command-bound control or KeyBinding on the Window Manual KeyDown handlers checking Key and KeyModifiers <Button Command="{Binding SaveCommand}" HotKey="Ctrl+S" Content="Save"/> OnKeyDown checking e.Key == Key.S && e.KeyModifiers == KeyModifiers.Control Medium https://docs.avaloniaui.net/docs/input-interaction/mouse-and-keyboard-shortcuts
54 53 Windowing Customize window chrome with ExtendClientAreaToDecorationsHint Set ExtendClientAreaToDecorationsHint to extend content into the title bar area and tag a region with WindowDecorationProperties.ElementRole=TitleBar to keep native drag and maximize behavior ExtendClientAreaToDecorationsHint plus a region tagged ElementRole=TitleBar SystemDecorations=None with hand-rolled PointerPressed dragging in code-behind <Window ExtendClientAreaToDecorationsHint="True"><Border WindowDecorationProperties.ElementRole="TitleBar"/></Window> <Window SystemDecorations="None"> with manual BeginMoveDrag from code-behind Medium https://docs.avaloniaui.net/docs/app-development/window-management
55 54 Storage Use TopLevel.StorageProvider for file pickers The legacy OpenFileDialog/SaveFileDialog APIs are obsolete in Avalonia 11 - use TopLevel.GetTopLevel(this).StorageProvider with OpenFilePickerAsync/SaveFilePickerAsync/OpenFolderPickerAsync which returns IStorageFile/IStorageFolder and works on desktop mobile and browser TopLevel.StorageProvider with OpenFilePickerAsync and FilePickerOpenOptions OpenFileDialog or SaveFileDialog from older Avalonia samples or copied from WPF var top = TopLevel.GetTopLevel(this); var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false }); var dlg = new OpenFileDialog(); var paths = await dlg.ShowAsync(window); // obsolete API High https://docs.avaloniaui.net/docs/concepts/services/storage-provider/
56 55 Windowing Use TrayIcon for system tray icon TrayIcon shows a native system tray/notification-area icon with a NativeMenu - declare it via the Application.TrayIcon.Icons attached property in App.axaml; works on Windows macOS and most Linux desktops TrayIcon with NativeMenu inside TrayIcon.Icons on the Application Custom borderless window pretending to be a tray icon or per-platform native interop <TrayIcon.Icons><TrayIcons><TrayIcon Icon="/Assets/tray.ico" ToolTipText="MyApp"><TrayIcon.Menu><NativeMenu><NativeMenuItem Header="Show" Command="{Binding ShowCommand}"/></NativeMenu></TrayIcon.Menu></TrayIcon></TrayIcons></TrayIcon.Icons> Hidden Window with custom shell-notification-area P/Invoke Medium https://docs.avaloniaui.net/docs/controls/tray-icon
57 56 Cross-Platform Use OnPlatform and OnFormFactor markup for per-OS values OnPlatform and OnFormFactor markup extensions resolve to a different value per OS or form factor at XAML load time and replace if-statements in code-behind for tweaks like fonts spacing or icon sizes OnPlatform with Default Windows macOS Linux entries directly in the property setter RuntimeInformation.IsOSPlatform branches in code-behind to set XAML properties <TextBlock FontFamily="{OnPlatform Default='Inter', Windows='Segoe UI', macOS='SF Pro Text', Linux='Ubuntu'}"/> if (OperatingSystem.IsWindows()) textBlock.FontFamily = new("Segoe UI"); else if (OperatingSystem.IsMacOS()) ... Medium https://docs.avaloniaui.net/docs/platform-specific-guides/xaml

View File

@ -0,0 +1,76 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Application,Start UI from Application subclass,JavaFX apps should bootstrap the primary Stage through Application.start(),Extend Application and configure Scene in start(),Create UI from a random main method without launching JavaFX,"public class App extends Application { public void start(Stage stage) { stage.setScene(new Scene(root)); stage.show(); } }",new Stage().show(),High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/application/Application.html
2,Threading,Keep work off the FX Application Thread,Long-running work blocks rendering and input when executed on the UI thread,Use Task or Service for background work,Run network database or file work in button handlers,"Task<List<Item>> task = new Task<>() { protected List<Item> call() { return repo.load(); } }; new Thread(task).start();",loadLargeFile(); table.setItems(items);,High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/concurrent/Task.html
3,Threading,Update UI only on FX thread,Scene graph changes must happen on the JavaFX Application Thread,Use bindings task handlers or Platform.runLater for UI changes,Mutate controls directly from background threads,"task.setOnSucceeded(e -> table.setItems(FXCollections.observableArrayList(task.getValue())));",new Thread(() -> label.setText("Done")).start(),High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/application/Platform.html
4,Threading,Bind progress to background tasks,Task exposes progress and message properties for responsive feedback,Bind ProgressBar and Label to task properties,Poll progress manually or leave users without feedback,"progress.progressProperty().bind(task.progressProperty()); status.textProperty().bind(task.messageProperty());",while(running) progress.setProgress(x);,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/concurrent/Task.html
5,FXML,Use FXML for stable declarative layouts,FXML keeps view structure readable for screens with many controls,Place layout in FXML and behavior in controller,Build large screens entirely in one Java method,"<VBox spacing=""12"" xmlns:fx=""http://javafx.com/fxml"" fx:controller=""app.MainController"">",VBox root = new VBox(); root.getChildren().add(... 200 lines ...);,Medium,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXMLLoader.html
6,FXML,Keep controllers focused on view behavior,Controllers should coordinate controls and delegate business logic to services,Inject services or call application services from controller,Put database queries and domain rules directly in controller,"public void save() { customerService.save(form.toCommand()); }",public void save() { DriverManager.getConnection(...); },High,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXML.html
7,FXML,Use fx:id for injected controls,FXML controls need stable fx:id values that match controller fields,Annotate fields with @FXML and keep ids descriptive,Look up controls by CSS selector for normal wiring,"@FXML private TableView<Customer> customerTable;",root.lookup("#customerTable"),Medium,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXML.html
8,FXML,Fail fast when loading FXML,FXML load errors should surface during screen creation with clear context,Load resources with getResource and handle IOException explicitly,Swallow loader errors and show a blank scene,"URL view = getClass().getResource(\"/views/main.fxml\"); Parent root = FXMLLoader.load(view);",try { FXMLLoader.load(url); } catch(Exception ignored) {},High,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXMLLoader.html
9,CSS,Style with style classes,JavaFX CSS works best through reusable styleClass names,Add semantic style classes and define them in CSS,Set long inline style strings throughout code,"button.getStyleClass().add(\"primary-action\");",".setStyle(\"-fx-background-color: #2563eb; -fx-padding: 12; ...\")",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/doc-files/cssref.html
10,CSS,Use design tokens through looked-up colors,Looked-up colors keep palettes consistent across controls,Define named colors on root and reuse them in CSS,Repeat hex values in every selector,".root { -brand-primary: #2563eb; } .button.primary { -fx-background-color: -brand-primary; }",".save { -fx-background-color: #2563eb; } .link { -fx-text-fill: #2563eb; }",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/doc-files/cssref.html
11,CSS,Avoid overusing inline effects,Expensive CSS effects and shadows can hurt desktop UI responsiveness,Use subtle shadows only on important elevated surfaces,Apply blur drop shadow and glow to every node,".dialog-card { -fx-effect: dropshadow(gaussian, rgba(0,0,0,.18), 16, 0, 0, 4); }",".table-row-cell { -fx-effect: dropshadow(gaussian, black, 20, .5, 0, 0); }",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/effect/package-summary.html
12,Layout,Choose layout panes by responsibility,Each pane solves a different layout problem and should be selected intentionally,Use BorderPane for app shell GridPane for forms VBox/HBox for simple stacks,Use absolute positioning for resizable app screens,"BorderPane shell = new BorderPane(); shell.setTop(toolbar); shell.setCenter(content);",Pane root = new Pane(); button.setLayoutX(742);,High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/layout/package-summary.html
13,Layout,Prefer constraints over fixed coordinates,Responsive JavaFX layouts depend on constraints and grow priorities,Use hgrow vgrow column constraints and alignment,Hard-code pixel positions and sizes,"GridPane.setHgrow(nameField, Priority.ALWAYS); column.setPercentWidth(50);",field.setPrefWidth(328); field.setLayoutX(120);,High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/layout/GridPane.html
14,Layout,Set sensible min pref and max sizes,Controls should resize predictably across windows and DPI settings,Use Region.USE_COMPUTED_SIZE and max widths intentionally,Lock every control to fixed width and height,"button.setMaxWidth(Double.MAX_VALUE); VBox.setVgrow(table, Priority.ALWAYS);","button.setMinSize(96, 32); button.setMaxSize(96, 32);",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/layout/Region.html
15,Layout,Use spacing and padding consistently,Desktop UI needs scan-friendly rhythm and clear grouping,Set spacing padding and Insets through shared constants or CSS,Use inconsistent ad hoc gaps between controls,"form.setHgap(12); form.setVgap(10); form.setPadding(new Insets(16));",box.setSpacing(3); other.setSpacing(17);,Low,https://openjfx.io/javadoc/21/javafx.graphics/javafx/geometry/Insets.html
16,Controls,Use ObservableList for list controls,TableView ListView and ComboBox update automatically from observable collections,Back controls with FXCollections.observableArrayList(),Mutate plain lists and manually refresh controls,"ObservableList<Customer> rows = FXCollections.observableArrayList(); table.setItems(rows);",List<Customer> rows = new ArrayList<>(); table.setItems((ObservableList) rows);,High,https://openjfx.io/javadoc/21/javafx.base/javafx/collections/ObservableList.html
17,Controls,Configure TableView cell value factories with properties,Table columns should observe stable JavaFX properties for updates,Expose StringProperty ObjectProperty or use ReadOnlyObjectWrapper,Return transient strings without observable support,"nameCol.setCellValueFactory(data -> data.getValue().nameProperty());",nameCol.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().toString()));,Medium,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/TableColumn.html
18,Controls,Use cell factories for custom rendering,Custom table or list visuals belong in reusable cell factories,Override updateItem and handle empty state,Place complex Nodes directly in model objects,"col.setCellFactory(c -> new TableCell<>() { protected void updateItem(Status s, boolean empty) { super.updateItem(s, empty); setText(empty ? null : s.label()); } });",row.setBadge(new Label("Active"));,Medium,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/Cell.html
19,Controls,Virtualized controls are for large data,TableView ListView TreeView virtualize cells and outperform manual node lists,Use TableView or ListView for hundreds of rows,Create hundreds of HBoxes inside a VBox,"ListView<Item> list = new ListView<>(items);",items.forEach(i -> vbox.getChildren().add(new ItemRow(i)));,High,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/ListView.html
20,Controls,Handle empty states explicitly,Empty tables and lists need visible guidance or next actions,Set placeholder nodes for empty data views,Leave blank white areas that look broken,"table.setPlaceholder(new Label(\"No customers match this filter\"));",table.setPlaceholder(null);,Low,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/TableView.html
21,Binding,Use property binding for derived UI state,JavaFX binding reduces imperative synchronization bugs,Bind disabled visible text and progress properties to source state,Manually update every dependent control in each event handler,"saveButton.disableProperty().bind(form.validProperty().not());",if(!valid) saveButton.setDisable(true);,High,https://openjfx.io/javadoc/21/javafx.base/javafx/beans/binding/Bindings.html
22,Binding,Unbind before manual updates,Bound properties cannot be set directly without errors,Call unbind when switching from bound to manual state,Set a bound property directly,"label.textProperty().unbind(); label.setText(\"Ready\");",label.textProperty().bind(task.messageProperty()); label.setText(\"Ready\");,Medium,https://openjfx.io/javadoc/21/javafx.base/javafx/beans/property/Property.html
23,Binding,Use listeners sparingly,Bindings express simple relationships more clearly than listeners,Use listeners for side effects and bindings for values,Create listener chains for simple computed text,"totalLabel.textProperty().bind(Bindings.format(""Total: %d"", total));","count.addListener((o, a, b) -> totalLabel.setText(""Total: "" + b));",Low,https://openjfx.io/javadoc/21/javafx.base/javafx/beans/value/ObservableValue.html
24,Events,Use action handlers for commands,Buttons and menu items should route to named command methods,Use setOnAction or @FXML handler methods with clear names,Put large lambdas inline for complex operations,"@FXML private void handleSave(ActionEvent event) { saveCustomer(); }",saveButton.setOnAction(e -> { validate(); transform(); query(); save(); refresh(); });,Medium,https://openjfx.io/javadoc/21/javafx.base/javafx/event/ActionEvent.html
25,Events,Use event filters for global shortcuts,Filters can intercept keyboard events before child controls consume them,Register accelerators or filters at Scene level,Add duplicate key handlers to every control,"scene.getAccelerators().put(new KeyCodeCombination(KeyCode.S, SHORTCUT_DOWN), this::save);",nameField.setOnKeyPressed(...); table.setOnKeyPressed(...);,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/Scene.html
26,Accessibility,Connect labels to inputs,Accessible desktop forms need labels associated with controls,Use Label.setLabelFor and clear prompt text,Use placeholder-only labels,"nameLabel.setLabelFor(nameField); nameField.setPromptText(\"Jane Doe\");",nameField.setPromptText(\"Name\");,High,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/Label.html
27,Accessibility,Expose accessible text for icon buttons,Icon-only controls need names for screen readers and tooltips,Set accessibleText and Tooltip on icon buttons,Use unlabeled graphic-only buttons,"button.setAccessibleText(""Refresh""); button.setTooltip(new Tooltip(""Refresh""));","new Button("""", refreshIcon)",High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/AccessibleRole.html
28,Accessibility,Keep keyboard focus visible,Desktop users rely on focus traversal and visible focus indicators,Preserve focus rings and tab order,Remove outlines without alternative focus state,".button:focused { -fx-border-color: -brand-focus; -fx-border-width: 2; }",".button:focused { -fx-background-insets: 0; }",High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/Node.html
29,Accessibility,Use mnemonics for menu and form workflows,Mnemonics make desktop workflows faster and more accessible,Enable mnemonicParsing and choose unique mnemonic letters,Ignore keyboard alternatives for frequent actions,"saveButton.setMnemonicParsing(true); saveButton.setText(""_Save"");","saveButton.setText(""Save"");",Low,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/Labeled.html
30,Validation,Show validation near the field,Users should not hunt for form errors in desktop dialogs,Bind error labels or pseudo classes next to invalid controls,Show only a generic alert after submit,"field.pseudoClassStateChanged(PseudoClass.getPseudoClass(""invalid""), !valid);","new Alert(ERROR, ""Invalid input"").show();",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/css/PseudoClass.html
31,Validation,Use TextFormatter for constrained input,TextFormatter prevents invalid edits before they enter the model,Attach TextFormatter for numeric dates and masks,Parse and reject invalid text only after submit,"amountField.setTextFormatter(new TextFormatter<>(new IntegerStringConverter(), 0, c -> c.getControlNewText().matches(""\\d*"") ? c : null));",Integer.parseInt(amountField.getText());,Medium,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/TextFormatter.html
32,Dialogs,Use modal ownership for dialogs,Dialogs should block only the relevant window and return structured results,Set owner modality and use showAndWait,Open unmanaged windows for confirmations,"dialog.initOwner(stage); dialog.initModality(Modality.WINDOW_MODAL); Optional<ButtonType> result = dialog.showAndWait();",new Stage().show();,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/stage/Modality.html
33,Dialogs,Prefer custom DialogPane over ad hoc stages,Dialog gives consistent buttons focus and result handling,Use Dialog<T> for forms confirmations and wizards,Build every modal as a new Stage manually,"Dialog<Customer> dialog = new Dialog<>(); dialog.getDialogPane().getButtonTypes().addAll(OK, CANCEL);",Stage modal = new Stage(); modal.setScene(new Scene(new VBox()));,Low,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/Dialog.html
34,Images,Load images as resources,Packaged apps need resources resolved from the classpath or module path,Use getResourceAsStream for bundled assets,Use absolute local file paths in production UI,"new Image(getClass().getResourceAsStream(""/images/logo.png""));","new Image(""file:/Users/me/Desktop/logo.png"")",High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/image/Image.html
35,Images,Use background loading for large images,Large image decoding can pause UI startup,Use Image(url true) or a background Task for heavy assets,Load many full-size images synchronously during startup,"Image preview = new Image(url, true);",gallery.add(new Image(url));,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/image/Image.html
36,Animation,Keep animations purposeful and short,Desktop UI animations should clarify state changes without delaying work,Use 150-250ms transitions for reveal hover and selection,Animate every layout change with long timelines,"FadeTransition ft = new FadeTransition(Duration.millis(180), pane); ft.setToValue(1);","new Timeline(new KeyFrame(Duration.seconds(2), ...)).play();",Low,https://openjfx.io/javadoc/21/javafx.graphics/javafx/animation/package-summary.html
37,Animation,Respect reduced-motion contexts where possible,Some users experience motion sensitivity in desktop apps,Provide a setting to disable decorative animations,Make animation required for comprehension,"if (settings.reducedMotion()) pane.setOpacity(1); else fade.play();",alwaysSpin.play();,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/animation/Animation.html
38,Performance,Avoid recreating scenes for small state changes,Replacing whole scenes loses state and can flicker,Swap center content or update view models,Rebuild the entire Stage for every navigation click,"shell.setCenter(customerView);",stage.setScene(new Scene(loadMainAgain()));,Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/Scene.html
39,Performance,Reuse loaded views when appropriate,FXML loading and CSS application are not free,Cache stable views or controllers for frequent navigation,Reload heavyweight screens repeatedly without need,"Node settings = viewCache.computeIfAbsent(""settings"", this::loadSettings);","button.setOnAction(e -> shell.setCenter(loadFxml(""settings.fxml"")));",Low,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXMLLoader.html
40,Performance,Batch observable list changes,Many single-item updates can cause repeated layout and sort work,Use setAll or addAll for bulk replacement,Loop add items one by one to visible lists,"items.setAll(repository.findAll());",for(Item item : loaded) items.add(item);,Medium,https://openjfx.io/javadoc/21/javafx.base/javafx/collections/ObservableList.html
41,Architecture,Use view models for complex screens,View models keep controller state testable and separate from controls,Expose JavaFX properties from a screen model,Store all state only inside controls,"customerNameField.textProperty().bindBidirectional(viewModel.nameProperty());",String name = customerNameField.getText(); // everywhere,Medium,https://openjfx.io/javadoc/21/javafx.base/javafx/beans/property/package-summary.html
42,Architecture,Separate navigation from feature controllers,Feature controllers should not know how every screen is launched,Use a navigator or application shell service,Call FXMLLoader for unrelated screens from each controller,"navigator.showCustomers();",FXMLLoader.load(getClass().getResource(\"/views/admin.fxml\"));,Medium,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXMLLoader.html
43,Modules,Declare required JavaFX modules,Modular JavaFX apps must require the modules they use,Add javafx.controls javafx.fxml and opens controller packages,Depend on classpath accidents only,"module app { requires javafx.controls; requires javafx.fxml; opens app.ui to javafx.fxml; }",module app { requires javafx.controls; },High,https://openjfx.io/openjfx-docs/#modular
44,Packaging,Use jlink or jpackage for desktop delivery,JavaFX apps should ship with the runtime they need,Package a runtime image or native installer,Ask end users to install matching Java and JavaFX manually,"jpackage --name MyApp --module app/app.Main --runtime-image build/image",java -jar app.jar,Medium,https://openjfx.io/openjfx-docs/#modular
45,Testing,Use TestFX for interaction tests,UI flows need automated coverage beyond controller unit tests,Write TestFX tests for key forms dialogs and navigation,Only manually click through releases,"clickOn(""#nameField"").write(""Alice""); clickOn(""Save""); verifyThat(""Saved"", isVisible());",// manual QA only,Medium,https://github.com/TestFX/TestFX
46,Theme,Use AtlantaFX as the enterprise theme baseline,AtlantaFX provides modern JavaFX themes while preserving standard controls,Use AtlantaFX user-agent stylesheet plus a small app CSS layer,Rewrite every standard control style from scratch,"Application.setUserAgentStylesheet(new PrimerLight().getUserAgentStylesheet());",scene.getStylesheets().add("/css/huge-custom-theme.css");,High,https://mkpaz.github.io/atlantafx/
47,Theme,Prefer Primer for enterprise applications,PrimerLight and PrimerDark are neutral enough for dense business workflows,Use PrimerLight as default and PrimerDark for dark mode,Use Dracula or Cupertino as the default enterprise theme,"Application.setUserAgentStylesheet(new PrimerLight().getUserAgentStylesheet());",Application.setUserAgentStylesheet(new Dracula().getUserAgentStylesheet());,Medium,https://mkpaz.github.io/atlantafx/themes/
48,Theme,Layer brand CSS after AtlantaFX,Application CSS should customize brand tokens and business states after the base theme,Add app.css to the Scene after setting AtlantaFX,Edit AtlantaFX source CSS directly,"scene.getStylesheets().add(getClass().getResource(""/css/app.css"").toExternalForm());",modify atlantafx-base CSS files,High,https://mkpaz.github.io/atlantafx/theming/
49,Theme,Use looked-up colors as enterprise tokens,JavaFX looked-up colors keep brand and semantic colors reusable across controls,Define app-primary app-success app-warning app-danger on root,Repeat hex values in every selector,".root { -app-primary: #2563eb; -app-danger: #dc2626; }",".save { -fx-background-color: #2563eb; } .link { -fx-text-fill: #2563eb; }",High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/doc-files/cssref.html
50,Theme,Keep theme switching centralized,Dark mode switching should not be scattered across controllers,Use a ThemeService that sets user-agent stylesheet and app CSS variants,Let each controller decide its own theme,themeService.apply(ThemeMode.DARK);,if(dark) button.setStyle(...);,Medium,https://mkpaz.github.io/atlantafx/
51,Theme,Validate contrast for business status colors,Enterprise screens use status colors heavily and need readable contrast,Check text on success warning danger and selected row backgrounds,Assume brand colors are accessible,".status-danger { -fx-text-fill: -app-danger; }",red text on dark red background,High,https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html
52,Theme,Use AtlantaFX style classes before custom CSS,AtlantaFX exposes utility styles that reduce custom CSS drift,Prefer Styles constants or documented style classes,Create one-off class names for every button variant,saveButton.getStyleClass().add(Styles.ACCENT);,"saveButton.getStyleClass().add(""blue-button-42"");",Medium,https://mkpaz.github.io/atlantafx/
53,Theme,Treat AtlantaFX as a base not the whole design system,AtlantaFX modernizes controls but enterprise UX still needs layout density and workflow rules,Define app shell navigation table density form and validation conventions,Assume theme choice alone solves enterprise usability,"root.getStyleClass().add(""enterprise-shell"");",only set PrimerLight and stop,High,https://mkpaz.github.io/atlantafx/
54,Icons,Use Ikonli for consistent enterprise icons,Icon fonts integrate cleanly with JavaFX controls and avoid emoji-style UI,Use FontIcon with semantic style classes,Use emoji as toolbar or menu icons,"Button refresh = new Button(""Refresh"", new FontIcon(""mdi2r-refresh""));",new Button("Refresh"),Medium,https://kordamp.org/ikonli/
55,Components,Use AtlantaFX controls for common app affordances,AtlantaFX provides useful controls such as Card Message ModalPane Popover and ToggleSwitch,Use built-in AtlantaFX controls before adding another dependency,Add ControlsFX for components AtlantaFX already covers,"Message message = new Message(""Saved"", ""Customer updated successfully"");","new Label(""Saved"") with ad hoc styling",Medium,https://mkpaz.github.io/atlantafx/
56,Components,Add ControlsFX only for missing enterprise controls,ControlsFX is useful for specialized controls but should stay optional,Use ControlsFX for SpreadsheetView PropertySheet CheckComboBox or StatusBar needs,Add ControlsFX by default before requirements are clear,PropertySheet sheet = new PropertySheet(items);,"implementation ""org.controlsfx:controlsfx"" with no usage",Low,https://controlsfx.github.io/
57,Testing,Test theme-critical flows with TestFX,Theme and CSS changes can break focus visibility dialogs and button affordance,Use TestFX for login save validation and modal workflows,Only inspect AtlantaFX screens manually,"clickOn(""#saveButton""); verifyThat("".message"", isVisible());",manual theme QA only,Medium,https://github.com/TestFX/TestFX
58,Architecture,Use application shell plus feature workspaces,Enterprise JavaFX apps need stable navigation around changing work areas,Use BorderPane shell with navigation toolbar and central workspace,Replace the whole Stage for every feature,"shell.setLeft(navigation); shell.setTop(toolbar); shell.setCenter(workspace);",stage.setScene(new Scene(loadFeature()));,High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/layout/BorderPane.html
59,Architecture,Use MVVM for complex enterprise screens,Large forms and tables need testable state outside the controller,Expose JavaFX properties from view models and bind controls to them,Put all screen state and validation in the controller,amountField.textProperty().bindBidirectional(vm.amountProperty());,controller.amount = amountField.getText();,High,https://openjfx.io/javadoc/21/javafx.base/javafx/beans/property/package-summary.html
60,Architecture,Inject services into controllers,Enterprise controllers should coordinate UI and call application services,Use a controller factory or DI container for services,Create database connections inside FXML controllers,loader.setControllerFactory(type -> injector.getInstance(type));,new CustomerRepository(new DriverManager(...)),High,https://openjfx.io/javadoc/21/javafx.fxml/javafx/fxml/FXMLLoader.html
61,Navigation,Use role-aware navigation models,Menus toolbars and shortcuts should reflect the same permission model,Build navigation items from commands with required roles,Hide buttons in one place and leave shortcuts enabled,"command.enabledProperty().bind(permissionService.allowed(""invoice.approve""));",approveButton.setVisible(false);,High,
62,Workflow,Represent workflow states visibly,Approval and processing screens need clear business state signals,Use semantic badges row styles and disabled actions by workflow state,Use only free text status columns,"row.pseudoClassStateChanged(PseudoClass.getPseudoClass(""blocked""), item.isBlocked());","statusCol.setText(""B"");",Medium,https://openjfx.io/javadoc/21/javafx.graphics/javafx/css/PseudoClass.html
63,TableView,Design TableView for high-density enterprise data,Enterprise users scan compare sort filter and act on rows for long periods,Use compact row height clear columns sorting filtering and selection summary,Use card grids for large tabular datasets,"table.getStyleClass().add(""dense-table""); table.getSortOrder().setAll(updatedAtCol);",new TilePane(customerCards),High,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/TableView.html
64,TableView,Keep row actions predictable,Inline actions in dense tables should be limited and permission-aware,Use context menus or a side detail panel for secondary actions,Place many buttons in every row,"table.setRowFactory(tv -> { TableRow<Order> row = new TableRow<>(); row.setContextMenu(orderMenu); return row; });",row contains Edit Delete Approve Print Email buttons,Medium,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/ContextMenu.html
65,TableView,Use server-side paging for large enterprise datasets,Desktop clients should not load entire enterprise tables into memory,Fetch pages or filtered slices from services,Load all records and filter in the UI,"Page<Customer> page = customerService.search(criteria, pageRequest);",customerRepository.findAll(),High,
66,Forms,Use form sections for enterprise data entry,Long enterprise forms need grouping and progressive disclosure,Group fields into titled sections with validation summaries,Place dozens of inputs in one unbroken GridPane,"TitledPane billing = new TitledPane(""Billing"", billingForm);",new GridPane with 80 controls,Medium,https://openjfx.io/javadoc/21/javafx.controls/javafx/scene/control/TitledPane.html
67,Forms,Provide validation summary plus field errors,Enterprise forms often need multiple corrections before submission,Show a summary at top and field-level messages near controls,Show only one modal alert after Save,"summary.setItems(vm.validationErrors()); field.pseudoClassStateChanged(INVALID, fieldError);","new Alert(ERROR, ""Invalid form"").showAndWait();",High,
68,Tasks,Make long operations cancellable,Enterprise imports exports sync and reports need cancel paths,Expose cancel button bound to Task running state,Force users to wait or kill the app,cancelButton.setOnAction(e -> task.cancel());,runReportButton.setDisable(true);,High,https://openjfx.io/javadoc/21/javafx.graphics/javafx/concurrent/Task.html
69,Tasks,Surface retryable errors without losing context,Network and service failures should preserve user input and next action,Show inline retry messages and keep form/table state,Clear the screen on service failure,"message.setDescription(""Could not save. Check connection and retry."");",loadErrorScene();,High,
70,Audit,Log business actions through services,Enterprise desktop apps need traceability for sensitive changes,Record user action entity result and timestamp in service layer,Log only UI button clicks,"audit.log(user, ""invoice.approve"", invoiceId, SUCCESS);","System.out.println(""clicked approve"");",Medium,
71,Configuration,Separate user preferences from application config,Enterprise apps need deploy-time config and per-user preferences,Use config files for endpoints and Preferences for UI choices,Hard-code environment URLs and window state,"Preferences.userNodeForPackage(App.class).put(""theme"", ""dark"");","private static final String API = ""http://localhost:8080"";",Medium,https://docs.oracle.com/en/java/javase/21/docs/api/java.prefs/java/util/prefs/Preferences.html
72,Deployment,Package resources and themes inside the runtime image,AtlantaFX app CSS icons and FXML must be available after jpackage,Load resources from classpath or module resources,Load theme files from developer machine paths,"getClass().getResource(""/css/app.css"").toExternalForm();","new File(""src/main/resources/css/app.css"").toURI()",High,https://openjfx.io/openjfx-docs/#modular
73,Deployment,Write logs to user-writable locations,Installed desktop apps may not write inside the application directory,Use platform-specific user data directories for logs and cache,Write logs beside the executable,"Path logs = appData.resolve(""logs/app.log"");",Path.of("app.log"),Medium,
74,Testing,Cover enterprise happy path and failure path,Enterprise UI tests should verify save validation permission and service failure flows,Use TestFX for core workflows and service fakes,Only test controller methods without UI interaction,"clickOn(""Save""); verifyThat(""Customer saved"", isVisible());",controller.save(); assertTrue(saved);,High,https://github.com/TestFX/TestFX
75,Dependencies,Keep optional UI libraries behind actual needs,AtlantaFX should be default but additional libraries should be justified,Start with JavaFX AtlantaFX Ikonli TestFX and add ControlsFX only for missing controls,Adopt many UI libraries at project start,"dependencies { implementation(""io.github.mkpaz:atlantafx-base:2.1.0"") }",implementation controlsfx gemsfx tilesfx materialfx all at once,Medium,
Can't render this file because it contains an unexpected character in line 4 and column 345.

View File

@ -1,51 +1,51 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Blade Templates,Use Blade components for reusable UI,Extract repeated markup into named Blade components,Use x-* components with @props for all reusable UI,Duplicate HTML blocks across views,<x-card :title="$title">{{ $slot }}</x-card>,@include('card' ['title' => $title]),High,https://laravel.com/docs/blade#components
1,Blade Templates,Use Blade components for reusable UI,Extract repeated markup into named Blade components,Use x-* components with @props for all reusable UI,Duplicate HTML blocks across views,"<x-card :title=""$title"">{{ $slot }}</x-card>",@include('card' ['title' => $title]),High,https://laravel.com/docs/blade#components
2,Blade Templates,Use layouts with @extends and @section,Define one master layout and extend it per page,@extends layout with named @section blocks,Duplicate header/footer HTML in every view,@extends('layouts.app') @section('content'),Full HTML in every view file,High,https://laravel.com/docs/blade#layouts-using-template-inheritance
3,Blade Templates,Use @props for component type-safety,Declare accepted props inside components with @props,@props with defaults to document component API,Pass arbitrary variables without declaration,@props(['title' => '' 'variant' => 'primary']),No @props declaration in component,Medium,https://laravel.com/docs/blade#component-data-and-attributes
4,Blade Templates,Use conditional CSS classes with @class,Build class strings conditionally without ternary noise,@class directive for conditional class binding,String concatenation or nested ternaries,@class(['btn' 'btn-primary' => $primary 'btn-disabled' => $disabled]),class="btn {{ $primary ? 'btn-primary' : '' }}",Medium,https://laravel.com/docs/blade#conditional-classes-and-styles
5,Blade Templates,Use named slots for flexible layouts,Named slots let callers inject content into specific regions,@slot('header') and $slot for flexible component APIs,Hard-code all sub-sections inside components,"<x-modal><x-slot:header>Title</x-slot>Body</x-modal>",<x-modal title="Title">Body with no slot control</x-modal>,Medium,https://laravel.com/docs/blade#slots
4,Blade Templates,Use conditional CSS classes with @class,Build class strings conditionally without ternary noise,@class directive for conditional class binding,String concatenation or nested ternaries,@class(['btn' 'btn-primary' => $primary 'btn-disabled' => $disabled]),"class=""btn {{ $primary ? 'btn-primary' : '' }}""",Medium,https://laravel.com/docs/blade#conditional-classes-and-styles
5,Blade Templates,Use named slots for flexible layouts,Named slots let callers inject content into specific regions,@slot('header') and $slot for flexible component APIs,Hard-code all sub-sections inside components,<x-modal><x-slot:header>Title</x-slot>Body</x-modal>,"<x-modal title=""Title"">Body with no slot control</x-modal>",Medium,https://laravel.com/docs/blade#slots
6,Blade Templates,Use Blade directives instead of raw PHP,Blade directives are readable and IDE-supported,@if @foreach @forelse @empty instead of <?php ?>,Raw PHP tags inside Blade templates,@forelse($items as $item) ... @empty <p>None</p> @endforelse,<?php foreach($items as $item): ?>,High,https://laravel.com/docs/blade#blade-directives
7,Blade Templates,Escape output with {{ }},Use double curly braces for XSS-safe output,{{ }} for all user-supplied or dynamic text,{!! !!} for untrusted data,{{ $user->name }},{!! $user->name !!},High,https://laravel.com/docs/blade#displaying-data
8,Blade Templates,Use @vite for asset loading,Vite integration handles cache busting and HMR automatically,@vite(['resources/css/app.css' 'resources/js/app.js']),Manual script/link tags with hardcoded paths,@vite(['resources/css/app.css' 'resources/js/app.js']),<link href="/css/app.css?v=123">,High,https://laravel.com/docs/vite
9,Livewire,Bind inputs with wire:model,Two-way data binding keeps component state in sync,wire:model for all form inputs managed by Livewire,Manual JavaScript listeners syncing to component,<input wire:model="email">,<input @change="$wire.email = $event.target.value">,High,https://livewire.laravel.com/docs/properties
10,Livewire,Use wire:model.live for real-time validation,Validate on input rather than only on submit,wire:model.live + #[Validate] for instant feedback,Only validate on form submit,<input wire:model.live="email"> with #[Validate('email')],<input wire:model="email"> with validate() on submit only,Medium,https://livewire.laravel.com/docs/validation
11,Livewire,Use wire:click for actions,Bind UI events to component methods cleanly,wire:click for buttons and interactive elements,JavaScript fetch calls replicating Livewire actions,<button wire:click="save">Save</button>,<button onclick="fetch('/save')">Save</button>,High,https://livewire.laravel.com/docs/actions
8,Blade Templates,Use @vite for asset loading,Vite integration handles cache busting and HMR automatically,@vite(['resources/css/app.css' 'resources/js/app.js']),Manual script/link tags with hardcoded paths,@vite(['resources/css/app.css' 'resources/js/app.js']),"<link href=""/css/app.css?v=123"">",High,https://laravel.com/docs/vite
9,Livewire,Bind inputs with wire:model,Two-way data binding keeps component state in sync,wire:model for all form inputs managed by Livewire,Manual JavaScript listeners syncing to component,"<input wire:model=""email"">","<input @change=""$wire.email = $event.target.value"">",High,https://livewire.laravel.com/docs/properties
10,Livewire,Use wire:model.live for real-time validation,Validate on input rather than only on submit,wire:model.live + #[Validate] for instant feedback,Only validate on form submit,"<input wire:model.live=""email""> with #[Validate('email')]","<input wire:model=""email""> with validate() on submit only",Medium,https://livewire.laravel.com/docs/validation
11,Livewire,Use wire:click for actions,Bind UI events to component methods cleanly,wire:click for buttons and interactive elements,JavaScript fetch calls replicating Livewire actions,"<button wire:click=""save"">Save</button>","<button onclick=""fetch('/save')"">Save</button>",High,https://livewire.laravel.com/docs/actions
12,Livewire,Use lifecycle hooks appropriately,mount() for init; updated() for reactive side effects,mount() for initialization updatedFoo() for property changes,Heavy logic in render() or __construct(),public function mount(): void { $this->items = Item::all(); },public function render(): View { $this->items = Item::all(); },Medium,https://livewire.laravel.com/docs/lifecycle-hooks
13,Livewire,Use lazy loading for heavy components,Defer render of expensive components until visible,wire:init or lazy attribute on components,Load all Livewire components on page load,<livewire:analytics-chart lazy />,<livewire:analytics-chart /> with heavy DB queries on mount,Medium,https://livewire.laravel.com/docs/lazy
14,Livewire,Integrate Alpine.js for local UI state,Use Alpine.js for UI-only state that doesn't need server round-trips,x-data / x-show / x-transition for tooltips dropdowns,Livewire server calls for purely visual toggle state,<div x-data="{ open: false }"><button @click="open = !open">,<button wire:click="toggleDropdown"> for a local dropdown,Medium,https://livewire.laravel.com/docs/alpine
15,Livewire,Use wire:loading for feedback,Always indicate to users when a server action is in progress,wire:loading.attr="disabled" and wire:loading elements,Provide no feedback while Livewire request is in flight,<button wire:click="save" wire:loading.attr="disabled">Save</button>,<button wire:click="save">Save</button> with no loading state,High,https://livewire.laravel.com/docs/wire-loading
16,Livewire,Handle file uploads with WithFileUploads,Livewire's trait manages chunked upload and temp storage,WithFileUploads trait + wire:model for file inputs,Manual multipart form submissions for Livewire pages,use WithFileUploads; public $photo; <input wire:model="photo" type="file">,<form action="/upload" method="POST" enctype="multipart/form-data">,Medium,https://livewire.laravel.com/docs/uploads
14,Livewire,Integrate Alpine.js for local UI state,Use Alpine.js for UI-only state that doesn't need server round-trips,x-data / x-show / x-transition for tooltips dropdowns,Livewire server calls for purely visual toggle state,"<div x-data=""{ open: false }""><button @click=""open = !open"">","<button wire:click=""toggleDropdown""> for a local dropdown",Medium,https://livewire.laravel.com/docs/alpine
15,Livewire,Use wire:loading for feedback,Always indicate to users when a server action is in progress,"wire:loading.attr=""disabled"" and wire:loading elements",Provide no feedback while Livewire request is in flight,"<button wire:click=""save"" wire:loading.attr=""disabled"">Save</button>","<button wire:click=""save"">Save</button> with no loading state",High,https://livewire.laravel.com/docs/wire-loading
16,Livewire,Handle file uploads with WithFileUploads,Livewire's trait manages chunked upload and temp storage,WithFileUploads trait + wire:model for file inputs,Manual multipart form submissions for Livewire pages,"use WithFileUploads; public $photo; <input wire:model=""photo"" type=""file"">","<form action=""/upload"" method=""POST"" enctype=""multipart/form-data"">",Medium,https://livewire.laravel.com/docs/uploads
17,Inertia.js,Use Inertia page components as route endpoints,Each page is a Vue/React component rendered server-side via Inertia::render(),Inertia::render('Dashboard' ['data' => $data]) in controllers,Return JSON and fetch from JavaScript,return Inertia::render('Users/Index' ['users' => $users]);,return response()->json($users); with client-side fetch,High,https://inertiajs.com/responses
18,Inertia.js,Share global data via HandleInertiaRequests,Middleware share() provides auth user and flash to every page,Share auth/flash in HandleInertiaRequests middleware,Pass auth to every Inertia::render() call,public function share(Request $r): array { return ['auth' => ['user' => $r->user()]]; },Inertia::render('Page' ['auth' => auth()->user()]) every controller,High,https://inertiajs.com/shared-data
19,Inertia.js,Use <Link> for client-side navigation,Inertia Link intercepts clicks for SPA-like transitions,<Link href="/dashboard"> instead of <a href>,Regular <a> tags for internal navigation,<Link href={route('dashboard')}>Dashboard</Link>,<a href="/dashboard">Dashboard</a>,High,https://inertiajs.com/links
20,Inertia.js,Use useForm for form state and submission,Inertia's useForm manages progress errors and transforms,"useForm for all page-level forms, form.post() for submit",Axios/fetch for form submissions on Inertia pages,"const form = useForm({ name: '' }); form.post('/users');","axios.post('/users', { name });",High,https://inertiajs.com/forms
19,Inertia.js,Use <Link> for client-side navigation,Inertia Link intercepts clicks for SPA-like transitions,"<Link href=""/dashboard""> instead of <a href>",Regular <a> tags for internal navigation,<Link href={route('dashboard')}>Dashboard</Link>,"<a href=""/dashboard"">Dashboard</a>",High,https://inertiajs.com/links
20,Inertia.js,Use useForm for form state and submission,Inertia's useForm manages progress errors and transforms,"useForm for all page-level forms, form.post() for submit",Axios/fetch for form submissions on Inertia pages,const form = useForm({ name: '' }); form.post('/users');,"axios.post('/users', { name });",High,https://inertiajs.com/forms
21,Inertia.js,Use persistent layouts to preserve state,Wrap pages in a persistent layout so header/sidebar don't remount,layout property on page component for persistent UI,Re-render full layout on every page visit,MyPage.layout = (page) => <AppLayout>{page}</AppLayout>,No layout — full page reload feel on navigation,Medium,https://inertiajs.com/pages#persistent-layouts
22,Inertia.js,Enable SSR for public pages,Server-side rendering improves SEO and first paint,Enable Inertia SSR for marketing and public pages,Client-only rendering for all pages including public,php artisan inertia:start-ssr with @inertiaHead,No SSR on pages requiring good SEO,Medium,https://inertiajs.com/server-side-rendering
23,Styling,Set up Tailwind CSS via Vite,Use Vite + tailwindcss plugin for fast HMR and optimized builds,Install tailwindcss @tailwindcss/vite and configure vite.config.js,Laravel Mix or manual PostCSS pipeline for new projects,plugins: [tailwindcss()] in vite.config.js + @import 'tailwindcss' in app.css,Laravel Mix with require('tailwindcss') in webpack,High,https://tailwindcss.com/docs/installation/framework-guides
24,Styling,Purge unused styles via content config,Tailwind scans Blade and JS files to tree-shake unused classes,content: ['./resources/views/**/*.blade.php' './resources/js/**/*.{js,vue}'],No content config — ship all 3MB of CSS,content: ['./resources/**/*.blade.php' './resources/**/*.js'],content: [],High,https://tailwindcss.com/docs/content-configuration
24,Styling,Purge unused styles via content config,Tailwind scans Blade and JS files to tree-shake unused classes,"content: ['./resources/views/**/*.blade.php', './resources/js/**/*.{js,vue}']",No content config — ship all 3MB of CSS,"content: ['./resources/**/*.blade.php', './resources/**/*.js']",content: [],High,https://tailwindcss.com/docs/content-configuration
25,Styling,Use dark mode class strategy,class-based dark mode integrates with server-rendered preference,darkMode: 'class' with a toggle that sets class on <html>,Media query only — no user override possible,darkMode: 'class'; document.documentElement.classList.toggle('dark'),darkMode: 'media' — no programmatic control,Medium,https://tailwindcss.com/docs/dark-mode
26,Styling,Use @apply sparingly in component CSS,Extract only truly repeated multi-class patterns,@apply for BEM base classes shared across many components,@apply for every single element — defeats Tailwind's purpose,@apply flex items-center gap-2 (shared button base),@apply text-sm for a single use,Low,https://tailwindcss.com/docs/functions-and-directives#apply
27,Styling,Configure custom design tokens in CSS,Define brand colors spacing fonts as CSS variables consumed by Tailwind,Custom @theme tokens matched to brand guidelines,Magic color hex codes scattered across Blade templates,@theme { --color-brand: oklch(0.6 0.2 250); },bg-[#1a2b3c] inline throughout templates,Medium,https://tailwindcss.com/docs/theme
28,Components,Use anonymous Blade components for UI primitives,Blade files in resources/views/components/ auto-register as x-* components,Anonymous components for buttons alerts badges cards,Blade @includes for anything reusable,<x-badge variant="success">Active</x-badge>,@include('partials.badge' ['variant' => 'success']),Medium,https://laravel.com/docs/blade#anonymous-components
28,Components,Use anonymous Blade components for UI primitives,Blade files in resources/views/components/ auto-register as x-* components,Anonymous components for buttons alerts badges cards,Blade @includes for anything reusable,"<x-badge variant=""success"">Active</x-badge>",@include('partials.badge' ['variant' => 'success']),Medium,https://laravel.com/docs/blade#anonymous-components
29,Components,Use class-based components for complex logic,PHP class components can inject services and pre-process data,app/View/Components/ class when component needs PHP logic,Blade @php blocks for business logic inside templates,class AlertComponent { public function __construct(public string $type) {} },@php $color = $type === 'error' ? 'red' : 'green'; @endphp,Medium,https://laravel.com/docs/blade#components
30,Components,Forward extra attributes with $attributes,Pass through HTML attributes like class id aria to root element,$attributes->merge() on root element of components,Ignore caller-provided HTML attributes silently,<div {{ $attributes->merge(['class' => 'btn']) }}>,<div class="btn"> — drops extra class/id from caller,High,https://laravel.com/docs/blade#component-attributes
31,Components,Separate variant logic from templates,Keep variant/size/color logic in a PHP class or helper not in Blade,Variant class or match() expression in component class,Long @if chains for variants inside Blade templates,"public function classes(): string { return match($this->variant) { 'primary' => 'bg-blue-600', } }","@if($variant === 'primary') bg-blue-600 @elseif($variant === 'secondary')...",Medium,https://laravel.com/docs/blade#components
30,Components,Forward extra attributes with $attributes,Pass through HTML attributes like class id aria to root element,$attributes->merge() on root element of components,Ignore caller-provided HTML attributes silently,<div {{ $attributes->merge(['class' => 'btn']) }}>,"<div class=""btn""> — drops extra class/id from caller",High,https://laravel.com/docs/blade#component-attributes
31,Components,Separate variant logic from templates,Keep variant/size/color logic in a PHP class or helper not in Blade,Variant class or match() expression in component class,Long @if chains for variants inside Blade templates,"public function classes(): string { return match($this->variant) { 'primary' => 'bg-blue-600', } }",@if($variant === 'primary') bg-blue-600 @elseif($variant === 'secondary')...,Medium,https://laravel.com/docs/blade#components
32,Components,Provide default slot content,Use {{ $slot ?? '' }} or named slot defaults so components are usable empty,Default content in slots for optional regions,Require every slot to be filled — throws errors on empty usage,{{ $icon ?? '' }} in component Blade file,{{ $icon }} — fatal if caller omits slot,Low,https://laravel.com/docs/blade#slots
33,Components,Use component namespacing for packages,Prefix third-party or module components to avoid collisions,Register custom prefix via Blade::componentNamespace(),Mix first-party and package component names with no prefix,Blade::componentNamespace('Modules\\Shop\\Views' 'shop'); <x-shop::product-card />,<x-product-card /> colliding with first-party card,Low,https://laravel.com/docs/blade#manually-registering-components
34,Forms,Validate with Form Request classes,Move validation rules out of controllers into dedicated FormRequest classes,php artisan make:request and define rules() + authorize(),Inline validate() in controller actions,class StorePostRequest extends FormRequest { public function rules() { return ['title' => 'required|max:255']; } },public function store(Request $r) { $r->validate(['title' => 'required']); },High,https://laravel.com/docs/validation#form-request-validation
35,Forms,Preserve old input on validation failure,Use old() to repopulate form fields after server-side error redirect,old('field') as default value on all form inputs,Empty form fields when validation fails,<input name="email" value="{{ old('email') }}">,<input name="email">,High,https://laravel.com/docs/validation#repopulating-forms
36,Forms,Display validation errors with @error,Use the @error directive for inline field-level error messages,@error('field') to show per-field messages,Dump $errors->all() in one block at top of form,@error('email') <p class="text-red-500">{{ $message }}</p> @enderror,@foreach($errors->all() as $e) {{ $e }} @endforeach,Medium,https://laravel.com/docs/validation#quick-displaying-the-validation-errors
37,Forms,Use CSRF token on all forms,CSRF protection is enabled by default — include @csrf in every form,@csrf in every POST/PUT/PATCH/DELETE form,Disable VerifyCsrfToken middleware for convenience,<form method="POST">@csrf ...,<form method="POST"> without @csrf,High,https://laravel.com/docs/csrf
38,Forms,Use method spoofing for PUT/PATCH/DELETE,HTML forms only support GET/POST — use @method for REST actions,@method('PUT') inside form for update/delete routes,Route::post for all mutations including updates,"<form method=""POST"">@csrf @method('PUT')",<form method="POST" action="/users/update">,Medium,https://laravel.com/docs/routing#form-method-spoofing
39,Forms,Display flash messages consistently,Flash success/error in controller; read in layout with session(),session('status') in layout for global flash display,Re-query DB or pass flash from every controller individually,@if(session('success')) <div class="alert">{{ session('success') }}</div> @endif,if($user) return back()->with(['user' => $user]);,Medium,https://laravel.com/docs/session#flash-data
35,Forms,Preserve old input on validation failure,Use old() to repopulate form fields after server-side error redirect,old('field') as default value on all form inputs,Empty form fields when validation fails,"<input name=""email"" value=""{{ old('email') }}"">","<input name=""email"">",High,https://laravel.com/docs/validation#repopulating-forms
36,Forms,Display validation errors with @error,Use the @error directive for inline field-level error messages,@error('field') to show per-field messages,Dump $errors->all() in one block at top of form,"@error('email') <p class=""text-red-500"">{{ $message }}</p> @enderror",@foreach($errors->all() as $e) {{ $e }} @endforeach,Medium,https://laravel.com/docs/validation#quick-displaying-the-validation-errors
37,Forms,Use CSRF token on all forms,CSRF protection is enabled by default — include @csrf in every form,@csrf in every POST/PUT/PATCH/DELETE form,Disable VerifyCsrfToken middleware for convenience,"<form method=""POST"">@csrf ...","<form method=""POST""> without @csrf",High,https://laravel.com/docs/csrf
38,Forms,Use method spoofing for PUT/PATCH/DELETE,HTML forms only support GET/POST — use @method for REST actions,@method('PUT') inside form for update/delete routes,Route::post for all mutations including updates,"<form method=""POST"">@csrf @method('PUT')","<form method=""POST"" action=""/users/update"">",Medium,https://laravel.com/docs/routing#form-method-spoofing
39,Forms,Display flash messages consistently,Flash success/error in controller; read in layout with session(),session('status') in layout for global flash display,Re-query DB or pass flash from every controller individually,"@if(session('success')) <div class=""alert"">{{ session('success') }}</div> @endif",if($user) return back()->with(['user' => $user]);,Medium,https://laravel.com/docs/session#flash-data
40,Performance,Eager load relationships to prevent N+1,Always eager load related models used in views with with(),with() in queries before passing collections to views,Lazy-load relations inside Blade loops,User::with('posts' 'avatar')->get(),User::all() then @foreach $user->posts in Blade,High,https://laravel.com/docs/eloquent-relationships#eager-loading
41,Performance,Cache rendered Blade fragments,Use cache() helper to wrap expensive rendered partials,cache() around slow partials that change infrequently,Re-render identical content on every request,@php echo cache()->remember('sidebar' 3600 fn() => view('sidebar')->render()); @endphp,{{ view('sidebar')->render() }} on every page load,Medium,https://laravel.com/docs/cache
42,Performance,Paginate large data sets,Always paginate collections in list views,->paginate() or ->simplePaginate() with {{ $items->links() }},->get() for large tables in views,User::paginate(20) with <x-pagination :links="$users" />,User::all() passed to Blade,High,https://laravel.com/docs/pagination
42,Performance,Paginate large data sets,Always paginate collections in list views,->paginate() or ->simplePaginate() with {{ $items->links() }},->get() for large tables in views,"User::paginate(20) with <x-pagination :links=""$users"" />",User::all() passed to Blade,High,https://laravel.com/docs/pagination
43,Performance,Queue slow background tasks,Offload emails notifications and heavy processing to queues,Dispatch jobs for anything taking >200ms,Block HTTP request with slow operations,ProcessImage::dispatch($file); return back();,Storage::put(); Mail::send(); Image::resize(); in controller,High,https://laravel.com/docs/queues
44,Performance,Use route model binding,Laravel resolves models automatically — avoids manual find(),Type-hint model in controller method,Manual User::findOrFail($id) in every method,public function show(User $user): View { return view('users.show' compact('user')); },public function show($id) { $user = User::findOrFail($id); },Medium,https://laravel.com/docs/routing#route-model-binding
45,Performance,Enable HTTP response caching for static content,Cache control headers for pages that rarely change,Cache-Control headers via middleware for public pages,No caching — serve every response fresh,response()->view('home')->header('Cache-Control' 'public, max-age=3600'),No cache headers on marketing pages,Medium,https://laravel.com/docs/responses#response-headers
45,Performance,Enable HTTP response caching for static content,Cache control headers for pages that rarely change,Cache-Control headers via middleware for public pages,No caching — serve every response fresh,"response()->view('home')->header('Cache-Control', 'public, max-age=3600')",No cache headers on marketing pages,Medium,https://laravel.com/docs/responses#response-headers
46,Security,Escape all output in Blade,{{ }} auto-escapes HTML — never use {!! !!} on user data,{{ }} for all untrusted or dynamic content,{!! !!} for user-controlled strings,{{ $comment->body }},{!! $comment->body !!},High,https://laravel.com/docs/blade#displaying-data
47,Security,Protect routes with Gate and Policy,Use policies for authorization — never inline permission checks in views,@can / Gate::allows() for UI visibility; policy()->authorize() for actions,Hardcode role checks inline across templates,@can('update' $post) <a href="{{ route('posts.edit' $post) }}">Edit</a> @endcan,@if(auth()->user()->role === 'admin') <a href="/edit">,High,https://laravel.com/docs/authorization#policies
47,Security,Protect routes with Gate and Policy,Use policies for authorization — never inline permission checks in views,@can / Gate::allows() for UI visibility; policy()->authorize() for actions,Hardcode role checks inline across templates,"@can('update' $post) <a href=""{{ route('posts.edit' $post) }}"">Edit</a> @endcan","@if(auth()->user()->role === 'admin') <a href=""/edit"">",High,https://laravel.com/docs/authorization#policies
48,Security,Validate and authorize file uploads,Check MIME type size and store outside public root,Store in storage/app/private + validate mimes and max,Store raw upload in public/ without validation,"'avatar' => ['required' 'image' 'mimes:jpg,png' 'max:2048']",'avatar' => 'required' with no MIME or size check,High,https://laravel.com/docs/filesystem#file-uploads
49,Security,Use signed URLs for temporary links,Generate expiring URLs for private downloads or email confirmations,URL::signedRoute() or temporarySignedRoute(),Expose sequential IDs in download URLs without auth,URL::temporarySignedRoute('file.download' now()->addMinutes(30) ['file' => $id]),route('file.download' $id) with no expiry or signature,High,https://laravel.com/docs/urls#signed-urls
50,Security,Set a strict Content Security Policy,CSP headers prevent XSS injection of external scripts,spatie/laravel-csp or custom middleware to emit CSP header,No CSP — browser runs any injected script,Header: Content-Security-Policy: default-src 'self'; script-src 'self',No Content-Security-Policy header on responses,Medium,https://laravel.com/docs/middleware

Can't render this file because it contains an unexpected character in line 2 and column 209.

View File

@ -6,8 +6,8 @@ No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
5,Components,Use semantic color props,Use semantic colors like primary secondary error,color="primary" color="error",Hardcoded colors,"<UButton color=""primary"">","<UButton class=""bg-green-500"">",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
6,Components,Use variant prop for styling,Nuxt UI provides solid outline soft subtle ghost link variants,variant="soft" variant="outline",Custom button classes,"<UButton variant=""soft"">","<UButton class=""border bg-transparent"">",Medium,https://ui.nuxt.com/docs/components/button
7,Components,Use size prop consistently,Components support xs sm md lg xl sizes,size="sm" size="lg",Arbitrary sizing classes,"<UButton size=""lg"">","<UButton class=""text-xl px-6"">",Low,https://ui.nuxt.com/docs/components/button
8,Icons,Use icon prop with Iconify format,Nuxt UI supports Iconify icons via icon prop,icon="lucide:home" icon="heroicons:user",i-lucide-home format,"<UButton icon=""lucide:home"">","<UButton icon=""i-lucide-home"">",Medium,https://ui.nuxt.com/docs/getting-started/integrations/icons/nuxt
9,Icons,Use leadingIcon and trailingIcon,Position icons with dedicated props for clarity,leadingIcon="lucide:plus" trailingIcon="lucide:arrow-right",Manual icon positioning,"<UButton leadingIcon=""lucide:plus"">","<UButton><Icon name=""lucide:plus""/>Add</UButton>",Low,https://ui.nuxt.com/docs/components/button
8,Icons,Use i-{collection}-{name} format for icons,Nuxt UI v4 uses Iconify i-prefix format — lucide:home is v3 legacy,i-lucide-home i-heroicons-user format,lucide:home format (v3 syntax),"<UButton icon=""i-lucide-home"">","<UButton icon=""lucide:home"">",High,https://ui.nuxt.com/docs/getting-started/installation/nuxt
9,Icons,Use leadingIcon and trailingIcon props,Position icons with dedicated props for clarity,leadingIcon="i-lucide-plus" trailingIcon="i-lucide-arrow-right",Manual icon positioning or slots,"<UButton leadingIcon=""i-lucide-plus"" label=""Add"">","<UButton><UIcon name=""i-lucide-plus""/>Add</UButton>",Low,https://ui.nuxt.com/docs/components/button
10,Theming,Configure colors in app.config.ts,Runtime color configuration without restart,ui.colors.primary in app.config.ts,Hardcoded colors in components,"defineAppConfig({ ui: { colors: { primary: 'blue' } } })","<UButton class=""bg-blue-500"">",High,https://ui.nuxt.com/docs/getting-started/theme/design-system
11,Theming,Use @theme directive for custom colors,Define design tokens in CSS with Tailwind @theme,@theme { --color-brand-500: #xxx },Inline color definitions,@theme { --color-brand-500: #ef4444; },:style="{ color: '#ef4444' }",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
12,Theming,Extend semantic colors in nuxt.config,Register new colors like tertiary in theme.colors,theme.colors array in ui config,Use undefined colors,"ui: { theme: { colors: ['primary', 'tertiary'] } }","<UButton color=""tertiary""> without config",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
@ -16,7 +16,7 @@ No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
15,Forms,Handle form submit with @submit,UForm emits submit event with validated data,@submit handler on UForm,@click on submit button,"<UForm @submit=""onSubmit"">","<UButton @click=""onSubmit"">",Medium,https://ui.nuxt.com/docs/components/form
16,Forms,Use validateOn prop for validation timing,Control when validation triggers (blur change input),validateOn="['blur']" for performance,Always validate on input,"<UForm :validateOn=""['blur', 'change']"">","<UForm> (validates on every keystroke)",Low,https://ui.nuxt.com/docs/components/form
17,Overlays,Use v-model:open for overlay control,Modal Slideover Drawer use v-model:open,v-model:open for controlled state,Manual show/hide logic,"<UModal v-model:open=""isOpen"">",<UModal v-if="isOpen">,Medium,https://ui.nuxt.com/docs/components/modal
18,Overlays,Use useOverlay composable for programmatic overlays,Open overlays programmatically without template refs,useOverlay().open(MyModal),Template ref and manual control,"const overlay = useOverlay(); overlay.open(MyModal, { props })","const modal = ref(); modal.value.open()",Medium,https://ui.nuxt.com/docs/components/modal
18,Overlays,Use useOverlay composable for programmatic overlays,Open overlays programmatically — v4 API is create().open() not open(Component),overlay.create(Component).open({ props }) pattern,v3 overlay.open(Component) pattern (removed in v4),"const modal = overlay.create(MyModal); const { result } = modal.open({ title: 'Confirm' })","overlay.open(MyModal, { props: { title: 'Confirm' } })",High,https://ui.nuxt.com/docs/components/modal
19,Overlays,Use title and description props,Built-in header support for overlays,title="Confirm" description="Are you sure?",Manual header content,"<UModal title=""Confirm"" description=""Are you sure?"">","<UModal><template #header><h2>Confirm</h2></template>",Low,https://ui.nuxt.com/docs/components/modal
20,Dashboard,Use UDashboardSidebar for navigation,Provides collapsible resizable sidebar with mobile support,UDashboardSidebar with header default footer slots,Custom sidebar implementation,<UDashboardSidebar><template #header>...</template></UDashboardSidebar>,<aside class="w-64 border-r">,Medium,https://ui.nuxt.com/docs/components/dashboard-sidebar
21,Dashboard,Use UDashboardGroup for layout,Wraps dashboard components with sidebar state management,UDashboardGroup > UDashboardSidebar + UDashboardPanel,Manual layout flex containers,<UDashboardGroup><UDashboardSidebar/><UDashboardPanel/></UDashboardGroup>,"<div class=""flex""><aside/><main/></div>",Medium,https://ui.nuxt.com/docs/components/dashboard-group
@ -49,3 +49,23 @@ No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
48,Links,Use external prop for outside links,Explicitly mark external links,target="_blank" with external URLs,Forget rel="noopener","<UButton to=""https://example.com"" target=""_blank"">","<UButton href=""https://..."">",Low,https://ui.nuxt.com/docs/components/link
49,Loading,Use loadingAuto on buttons,Automatic loading state from @click promise,loadingAuto prop on UButton,Manual loading state,"<UButton loadingAuto @click=""async () => await save()"">","<UButton :loading=""isLoading"" @click=""save"">",Low,https://ui.nuxt.com/docs/components/button
50,Loading,Use UForm loadingAuto,Auto-disable form during submit,loadingAuto on UForm (default true),Manual form disabled state,"<UForm @submit=""handleSubmit"">","<UForm :disabled=""isSubmitting"">",Low,https://ui.nuxt.com/docs/components/form
51,Installation,Do not manually add auto-registered modules,Nuxt UI v4 auto-registers @nuxt/icon @nuxt/fonts @nuxtjs/color-mode,Configure via root-level keys in nuxt.config,Adding them to modules array causes duplicate registration,"icon: { /* opts */ } in nuxt.config","modules: ['@nuxt/ui', '@nuxt/icon']",High,https://ui.nuxt.com/docs/getting-started/installation/nuxt
52,Installation,Use official templates to bootstrap projects,Nuxt UI provides starter templates via nuxi init,npx nuxi init -t ui/dashboard for dashboard project,Manual project setup from scratch,"npx nuxi@latest init -t ui/dashboard","pnpm create nuxt app (manual UI setup)",Medium,https://ui.nuxt.com/docs/getting-started/installation/nuxt
53,Icons,Install icon collections locally for SSR,Local Iconify JSON prevents network requests and flash,pnpm i @iconify-json/lucide for reliable server rendering,Rely on remote icon fetching in production,"pnpm i @iconify-json/lucide @iconify-json/simple-icons",No local icon packages,Medium,https://ui.nuxt.com/docs/getting-started/installation/nuxt
54,Icons,Override default component icons globally,Components use default icons configurable via appConfig.ui.icons,Set loading close check icons in app.config.ts,Accept default icons for all components,"defineAppConfig({ ui: { icons: { loading: 'i-lucide-refresh-cw', close: 'i-lucide-x' } } })","<UModal :close-icon=""'i-lucide-x'""> on every usage",Low,https://ui.nuxt.com/docs/getting-started/installation/nuxt
55,Forms,Use UFileUpload for file input,Built-in drag-drop and preview support,UFileUpload with v-model and accept prop,Custom input type=file,"<UFileUpload v-model=""files"" accept=""image/*"" multiple/>","<input type=""file"" @change=""handleFiles"">",Medium,https://ui.nuxt.com/docs/components/file-upload
56,Forms,Use UInputDate for date selection,Locale-aware date picker built on UCalendar,UInputDate with v-model and locale prop,Third-party date picker libraries,"<UInputDate v-model=""date"" />","<DatePicker v-model=""date"" />",Medium,https://ui.nuxt.com/docs/components/input-date
57,Forms,Use UInputTags for tag input,Multi-value tag input with keyboard support,UInputTags with v-model and max prop,Custom chip input implementation,"<UInputTags v-model=""tags"" :max=""5"" />","<UInput @keydown.enter=""addTag"">",Low,https://ui.nuxt.com/docs/components/input-tags
58,Forms,Use UColorPicker for color selection,Full-featured color picker with multiple format support,UColorPicker with v-model and format prop,Native input type=color,"<UColorPicker v-model=""color"" format=""hex"" />","<input type=""color"" v-model=""color"">",Low,https://ui.nuxt.com/docs/components/color-picker
59,Data,Use UTree for hierarchical data,Built-in tree component with expand/collapse,UTree with items prop containing nested children,Custom recursive component,"<UTree :items=""treeItems"" />","<TreeNode v-for=""item in items"" :key=""item.id"">",Low,https://ui.nuxt.com/docs/components/tree
60,Data,Use UMarquee for infinite scroll content,Animated infinite scroll band for logos or testimonials,UMarquee with repeat and pauseOnHover props,CSS animation keyframes loop,"<UMarquee :repeat=""3"" pause-on-hover>","<div class=""animate-marquee"">",Low,https://ui.nuxt.com/docs/components/marquee
61,Overlays,Use UContextMenu for right-click menus,Context menu triggered by right-click on children,UContextMenu wrapping target element,Browser default context menu,<UContextMenu :items="menuItems"><div>Right-click me</div></UContextMenu>,"<div @contextmenu.prevent=""showMenu"">",Medium,https://ui.nuxt.com/docs/components/context-menu
62,Overlays,Await overlay result for confirmation dialogs,useOverlay returns a result Promise resolving to user action,await instance.result to get confirm/cancel,Emit events from overlay components,"const { result } = modal.open(); if (await result) { deleteItem() }","overlay.open(Confirm, { onConfirm: deleteItem })",Medium,https://ui.nuxt.com/docs/components/modal
63,Navigation,Use UCommandPalette with grouped items,Command palette supports grouped search with icons and kbds,groups array with id label items,Flat list without categories,"<UCommandPalette :groups=""[{ id: 'actions', label: 'Actions', items }]""/>","<UCommandPalette :items=""flatList""/>",Medium,https://ui.nuxt.com/docs/components/command-palette
64,Navigation,Use defineShortcuts with extractShortcuts,Wire keyboard shortcuts from menu item kbds automatically,extractShortcuts(items) + defineShortcuts to sync keybindings,Manually duplicate shortcuts from menu items,"defineShortcuts(extractShortcuts(items))","defineShortcuts({ meta_n: () => newFile() }) // duplicated from items",Low,https://ui.nuxt.com/docs/composables/define-shortcuts
65,Layout,Use UHeader and UFooter for page layout,Responsive header/footer with built-in mobile menu,UHeader with #default slot for nav UFooter with columns,Custom header/footer from scratch,"<UHeader><template #right><UNavigationMenu/></template></UHeader>","<header class=""sticky top-0"">",Low,https://ui.nuxt.com/docs/components/header
66,Layout,Use UPageAside for sidebar content,Sidebar that hides below lg breakpoint automatically,UPageAside for docs and landing page sidebars,Manual hidden lg: classes,"<UPageAside><UNavigationMenu orientation=""vertical""/></UPageAside>","<aside class=""hidden lg:block"">",Low,https://ui.nuxt.com/docs/components/page-aside
67,Color Mode,Wrap custom color mode toggles in ClientOnly,Prevents hydration mismatch on server-rendered color mode,ClientOnly with fallback placeholder,Direct useColorMode in template without ClientOnly,"<ClientOnly><USwitch v-model=""isDark""/><template #fallback><div class=""size-8""/></template></ClientOnly>",<USwitch v-model="isDark"/> directly in template,Medium,https://ui.nuxt.com/docs/getting-started/installation/nuxt
68,Theming,Read generated theme file to find slot names,Nuxt UI generates theme files listing all component slots and variants,Check .nuxt/ui/<component>.ts for slot names,Guess slot names or use trial-and-error,".nuxt/ui/button.ts for UButton slot names","<UButton :ui=""{ base: 'rounded-full' }""/> without checking slots",Medium,https://ui.nuxt.com/docs/getting-started/theme/components
69,Composables,Use defineShortcuts whenever keyword shortcut,whenever array condition prevents shortcut firing when inactive,whenever: [isFormValid] to guard shortcut execution,Always-on shortcuts that fire in wrong context,"defineShortcuts({ meta_enter: { handler: submit, whenever: [isFormValid] } })","defineShortcuts({ meta_enter: () => submit() }) // fires even when invalid",Low,https://ui.nuxt.com/docs/composables/define-shortcuts
70,i18n,Use UApp locale prop for internationalization,Nuxt UI supports 50+ built-in locales via locale prop on UApp,Import locale from @nuxt/ui/locale and pass to UApp,Manual translation of component UI strings,"import { fr } from '@nuxt/ui/locale'; // <UApp :locale=""fr"">","<UModal title=""Fermer""> manually for each component",Low,https://ui.nuxt.com/docs/composables/define-locale

Can't render this file because it contains an unexpected character in line 6 and column 94.

View File

@ -1,54 +1,54 @@
Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,"// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag","<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime","function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color","renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });","// No resize handler — scene stretches to fill a wider window without correcting the projection",High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));","// No position or lookAt set — subject at y:2 is behind or above the default camera view",Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,"function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); }","scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });","const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit",Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material","for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials",High,https://threejs.org/docs/#api/en/materials/Material
Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,"const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();","const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload",High,https://threejs.org/docs/#api/en/textures/Texture.dispose
Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;","dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags","for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,"mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED","mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored",Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes","const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children",High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,"if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; }","raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.","Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame","Call clock.getDelta() more than once per frame or inside a helper called from animate()","const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz }",High,https://threejs.org/docs/#api/en/core/Clock
Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,"// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);","// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing",Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });","let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps",High,https://gsap.com/docs/v3/GSAP/Timeline/
Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';","import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js",Critical,https://gsap.com/docs/v3/Installation
GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,"renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128","const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context","const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear","// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame",Low,https://threejs.org/docs/#api/en/scenes/FogExp2
Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,"const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);","const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone",High,https://threejs.org/docs/#api/en/objects/Points
Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,"// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload","// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move",Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.","Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value","Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes","const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }","const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely",High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);","document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing",Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,"npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';","<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);","scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera",Medium,https://threejs.org/docs/#api/en/objects/LOD
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
2,Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
3,Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
4,Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
5,Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag,"<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
6,Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime",function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile,Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
7,Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
8,Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color",renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
9,Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });",// No resize handler — scene stretches to fill a wider window without correcting the projection,High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
10,Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11,Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));",// No position or lookAt set — subject at y:2 is behind or above the default camera view,Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
12,Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
13,Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
14,Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
15,Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); },scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever,Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
16,Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
17,Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
18,Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });",const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit,Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
19,Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material",for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials,High,https://threejs.org/docs/#api/en/materials/Material
20,Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();,const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload,High,https://threejs.org/docs/#api/en/textures/Texture.dispose
21,Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
22,Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;,dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
23,Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags,for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24,Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
25,Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
26,Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored,Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
27,Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
28,Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes",const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children,High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
29,Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; },"raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
30,Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
31,Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.",Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame,Call clock.getDelta() more than once per frame or inside a helper called from animate(),"const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }",function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz },High,https://threejs.org/docs/#api/en/core/Clock
32,Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);,// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing,Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
33,Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });",let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps,High,https://gsap.com/docs/v3/GSAP/Timeline/
34,Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
35,GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';",import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js,Critical,https://gsap.com/docs/v3/Installation
36,GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
37,GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
38,GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
39,Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
40,Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128,const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
41,Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context",const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
42,Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear",// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame,Low,https://threejs.org/docs/#api/en/scenes/FogExp2
43,Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
44,Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);,const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone,High,https://threejs.org/docs/#api/en/objects/Points
45,Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload,// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move,Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
46,Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
47,Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
48,Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
49,Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.",Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value,Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes,"const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }",const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely,High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
50,Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);",document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing,Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
51,Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';,"<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
52,Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
53,Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);",scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera,Medium,https://threejs.org/docs/#api/en/objects/LOD

1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 Setup CDN Version Lock Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning. Pin to the exact r128 cdnjs URL in every HTML file Use unpkg@latest or any unversioned CDN URL that can silently update <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://unpkg.com/three@latest"></script> Critical https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
3 2 Setup CapsuleGeometry Does Not Exist in r128 THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead. Build a capsule from CylinderGeometry plus two SphereGeometry end caps Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap); const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128 Critical https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
4 3 Setup OrbitControls Must Be Loaded Separately OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it. Load the OrbitControls script from cdnjs examples path before your scene script Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script <!-- Load AFTER core Three.js script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js"></script> <!-- Core only loaded — OrbitControls undefined --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> Critical https://cdnjs.com/libraries/three.js/r128
5 4 Setup Custom Drag Orbit Fallback When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly. Rotate camera in spherical coordinates so both axes respond correctly to drag Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere High https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
6 5 Setup ESM vs CDN Import When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors. Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages Mix a CDN script tag with an ES module import in the same file // Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag <!-- CDN script --> <script src="r128.cdn"></script> <script type="module"> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script> Critical https://threejs.org/docs/#manual/en/introduction/Installation
7 6 Setup Single Renderer Per Page Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (8–16 contexts) and cause context-lost errors especially on mobile. Reuse a single renderer and swap scene content instead of recreating the renderer Create a new renderer on each component mount or scene transition const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer
8 7 Setup Pixel Ratio Cap at 2 Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance. Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3 Pass window.devicePixelRatio directly without any cap renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
9 8 Setup Alpha Canvas Plus CSS Background Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it. Set alpha:true on renderer and let body or a parent div provide the background color Set a solid renderer clear color when the canvas must composite over HTML behind it const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
10 9 Camera Aspect Ratio on Resize Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally. Update camera.aspect then call updateProjectionMatrix() on every resize Let aspect ratio become stale after the browser window changes size window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); }); // No resize handler — scene stretches to fill a wider window without correcting the projection High https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11 10 Camera FOV Range 45 to 75 Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges. Start at 75 for general interactive scenes; use 45–55 for product close-ups Use FOV above 90 or below 30 without a deliberate artistic reason const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges Medium https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
12 11 Camera Explicit Position and lookAt Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny. Set camera.position.set() and camera.lookAt() to frame the subject before the first render Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0)); // No position or lookAt set — subject at y:2 is behind or above the default camera view Medium https://threejs.org/docs/#api/en/cameras/Camera.lookAt
13 12 Camera OrbitControls vs GSAP Camera Rig Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed. Match camera control approach to the UX intent of the scene Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes // Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate() // Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes High https://threejs.org/docs/#examples/en/controls/OrbitControls
14 13 Geometry Never Create Geometry Per Frame Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame. Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed Call any new XxxGeometry() constructor inside the animation loop const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
15 14 Geometry Share Geometry Across Meshes When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer. Create one geometry and pass the same reference to every Mesh constructor Create a separate identical geometry inside a loop for each object const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); } for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
16 15 Geometry dispose on Scene Removal Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed. Dispose of geometry + material + every texture map before calling scene.remove() Call scene.remove() alone without any dispose calls function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); } scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever Critical https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
17 16 Geometry Segment Count Budget Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 32–64 segments. Background objects: 8–16. Particle stand-ins: 6–8. High counts on background geometry waste GPU draw calls with zero visible benefit. Apply a tiered segment budget based on the visual priority of each object in the scene Default every sphere and cylinder to 64+ segments regardless of its role const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw Medium https://threejs.org/docs/#api/en/geometries/SphereGeometry
18 17 Geometry BufferGeometry for Custom Vertex Data For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128. Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data Reference or instantiate the removed THREE.Geometry class const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3)); const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128 High https://threejs.org/docs/#api/en/core/BufferGeometry
19 18 Materials MeshBasicMaterial vs MeshStandardMaterial MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices. Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 }); const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit Medium https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
20 19 Materials Share Material Instances Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM. Assign the same material reference to all meshes with identical visual properties Create a new material inside a loop for objects that look identical const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials High https://threejs.org/docs/#api/en/materials/Material
21 20 Materials Dispose Textures Explicitly Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically. Track all loaded textures and call dispose() on each one during scene teardown or on object removal Load textures without any cleanup path — they persist in VRAM for the entire page lifetime const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose(); const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload High https://threejs.org/docs/#api/en/textures/Texture.dispose
22 21 Lighting Ambient Plus Directional Minimum Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it. Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used Use MeshStandardMaterial without adding any lights to the scene scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight); const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene Critical https://threejs.org/docs/#api/en/lights/DirectionalLight
23 22 Lighting Enable shadowMap Before castShadow renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored. Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true; dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24 23 Lighting Selective Shadow Casting Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane. Enable shadows only on the key light and the most important meshes Enable castShadow and receiveShadow on every object in the scene including particles renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
25 24 Lighting Skip Lights for MeshBasicMaterial MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect. Omit lights entirely when every material in the scene is MeshBasicMaterial Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial // Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely Low https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
26 25 Raycasting Single Shared Raycaster Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event. Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate() Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate() window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec }); Critical https://threejs.org/docs/#api/en/core/Raycaster
27 26 Raycasting NDC Mouse Coordinates Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects. Apply the full NDC formula — including the negation on the Y axis Forget to negate Y — raycasting appears to work but hits objects mirrored vertically mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored Critical https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
28 27 Raycasting setFromCamera and intersectObjects in animate Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction. Call setFromCamera then intersectObjects in order inside every animate() frame Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); } Critical https://threejs.org/docs/#api/en/core/Raycaster
29 28 Raycasting Recursive Flag for Groups and GLTF Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty. Use intersectObjects(targets true) for Groups or any loaded model Raycast against a parent Group without the recursive flag const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children High https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
30 29 Raycasting Cursor Feedback on Hover Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive. Update cursor to pointer on hit; reset to auto on miss in the same animate loop block Run raycasting and read hits without ever updating the cursor style if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive Medium https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
31 30 Animation requestAnimationFrame Loop Only Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery. Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver Use setInterval or setTimeout for render timing function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate(); setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
32 31 Animation THREE.Clock for Delta Time Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it. Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame Call clock.getDelta() more than once per frame or inside a helper called from animate() const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz } High https://threejs.org/docs/#api/en/core/Clock
33 32 Animation Lerp for Smooth Pointer Follow Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.03–0.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP. Apply the lerp formula each frame with a small alpha for smooth organic motion Snap a value directly to the target producing an instant jarring jump // In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position); // In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing Medium https://threejs.org/docs/#api/en/math/MathUtils.lerp
34 33 Animation GSAP for Multi-Step Sequences Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines. Use GSAP timelines for sequences with more than two steps and for scroll-driven animations Implement multi-step sequences with boolean flags and manual frame counters const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 }); let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps High https://gsap.com/docs/v3/GSAP/Timeline/
35 34 Animation Pause Render Loop on Tab Hidden Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit. Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); }); function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery High https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
36 35 GSAP Load GSAP Before Scene Script Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package. Load GSAP CDN before the scene script; or npm install gsap and import separately Import gsap from three or expect it to be defined without a separate load <!-- CDN: load GSAP before your scene script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js Critical https://gsap.com/docs/v3/Installation
37 36 GSAP Register ScrollTrigger Before Use Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately. Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger Include scrollTrigger config in gsap.to() calls without first registering the plugin gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } }); gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered Critical https://gsap.com/docs/v3/Plugins/ScrollTrigger/
38 37 GSAP Tween Three.js Properties Directly GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts. Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity Use a plain proxy object then manually copy values to Three.js properties every frame gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 }); const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper Medium https://gsap.com/docs/v3/GSAP/gsap.to()
39 38 GSAP scrub for Scroll-Driven Camera Path Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 0–1 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path. Use scrub:1 for any scroll-controlled camera movement Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } }); gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub High https://gsap.com/docs/v3/Plugins/ScrollTrigger/
40 39 Performance InstancedMesh for Repeated Objects Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically. Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material Create 50+ separate Mesh objects with the same geometry and material const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/InstancedMesh
41 40 Performance Tone Mapping and sRGB Encoding Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately. Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes Leave tone mapping and output encoding at defaults when the scene targets realistic visuals renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128 const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
42 41 Performance antialias Set at Construction Only The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating. Set antialias:true inside the WebGLRenderer constructor options object Construct the renderer without antialias then try to enable it by assigning the property const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased High https://threejs.org/docs/#api/en/renderers/WebGLRenderer
43 42 Performance FogExp2 for Depth and Far Culling Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances. Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear // far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame Low https://threejs.org/docs/#api/en/scenes/FogExp2
44 43 Particles BufferGeometry Plus Points for Particle Systems Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance. Use Points plus BufferGeometry for all particle effects Create hundreds of individual Mesh objects to simulate a particle system const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/Points
45 44 Particles Particle Count Ceiling Start particle systems at 1000–3000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1. Start at 3000 particles and profile on actual mobile hardware before raising the limit Set particle count at 100000 or higher without any mobile profiling const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3); const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone High https://threejs.org/docs/#api/en/objects/Points
46 45 Particles needsUpdate After Buffer Mutation After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen. Set needsUpdate = true on the position attribute after every per-frame mutation of the array Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU // In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload // In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move Critical https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
47 46 Responsive Canvas Dimensions Not Window Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport. Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
48 47 Responsive ResizeObserver Over window resize Event Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing. Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement); window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs Medium https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
49 48 Responsive Touch Events for Mobile Interaction Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault. Handle both mouse and touch input for any interactive 3D scene Add only mouse event listeners and leave touch users with no interaction canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false }); canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction Medium https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
50 49 Accessibility prefers-reduced-motion Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime. Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; } const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely High https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
51 50 Accessibility Canvas aria-label Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users. Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it Append the canvas to the DOM with no accessibility attributes — invisible to screen readers renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement); document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing Medium https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
52 51 Production Bundler Stack for Production For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support. Use npm install three plus Vite or Webpack for any production client-facing project Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; <!-- In a Vite/React production build: --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> // no tree-shaking — entire Three.js ships Medium https://threejs.org/docs/#manual/en/introduction/Installation
53 52 Production GLTFLoader with scene traverse Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration. Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); }); loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children }); Medium https://threejs.org/docs/#examples/en/loaders/GLTFLoader
54 53 Production LOD for Distance-Based Detail Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range. Use THREE.LOD to reduce triangle count on distant objects automatically Render the same high-polygon geometry for every object regardless of its distance from the camera const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 15–50 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod); scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera Medium https://threejs.org/docs/#api/en/objects/LOD

View File

@ -0,0 +1,60 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,XAML,Use WinUI XAML API surface,Uno implements the WinUI API across platforms,Microsoft.UI.Xaml namespace for all UI code,WPF or Xamarin.Forms namespaces,"using Microsoft.UI.Xaml.Controls;","using System.Windows.Controls; or using Xamarin.Forms;",High,https://platform.uno/docs/articles/implemented-views.html
2,XAML,Check API implementation status,Not all WinUI APIs are implemented on every platform,Uno API compatibility docs before using new APIs,Assuming all WinUI APIs work everywhere,"Check platform.uno/docs for API status","Using unimplemented API and discovering at runtime",High,https://platform.uno/docs/articles/implemented-views.html
3,XAML,Use Uno.WinUI not Uno.UI for new projects,Uno.WinUI uses WinUI 3 APIs,Uno.WinUI NuGet packages for new projects,Uno.UI (UWP API surface) for new projects,"<Project Sdk=""Uno.Sdk""> (Uno.WinUI / WinUI 3 surface implicit)","<PackageReference Include=""Uno.UI""/> (legacy UWP API surface)",Medium,https://platform.uno/docs/articles/updating-to-winui3.html
4,XAML,Use XAML Hot Reload,Speed up development with live XAML editing,Hot Reload for iterating on layouts,Restarting app for every XAML change,"Click Hot Reload button in VS toolbar or save in VS Code/Rider to apply XAML changes","Full rebuild for margin tweak",Medium,https://platform.uno/docs/articles/features/working-with-xaml-hot-reload.html
5,Conditional,Use platform-specific XAML,Conditional namespaces for platform-specific UI,xmlns:android xmlns:ios xmlns:wasm for platform XAML,Shared XAML when platforms need different controls,"<TextBlock android:Text=""Android"" ios:Text=""iOS"" Text=""Default""/>","#if in code-behind to set text per platform",Medium,https://platform.uno/docs/articles/platform-specific-xaml.html
6,Conditional,Use partial classes for platform code,Separate platform implementations in partial files,Partial class files with platform-specific logic,#if directives in shared code for large blocks,"MainPage.iOS.cs MainPage.Android.cs partial class files","#if __IOS__ ... #elif __ANDROID__ ... 100-line blocks in shared file",Medium,https://platform.uno/docs/articles/platform-specific-csharp.html
7,Conditional,Use preprocessor symbols correctly,Target correct platforms with defines,__IOS__ __ANDROID__ __WASM__ __DESKTOP__ for platform checks,Inventing custom symbols or checking OS at runtime,"#if __ANDROID__ Android-specific code #endif","if (RuntimeInformation.IsOSPlatform(OSPlatform.Android)) for compile-time choice",Medium,https://platform.uno/docs/articles/platform-specific-csharp.html
8,Conditional,Minimize platform-specific code,Keep shared code maximized,Abstract platform differences behind interfaces,Duplicating logic across platform files,"IDeviceService with per-platform implementation","Same 50 lines copy-pasted into iOS and Android partial classes",High,https://platform.uno/docs/articles/platform-specific-csharp.html
9,Navigation,Use Frame-based navigation,Standard WinUI navigation pattern,Frame.Navigate with page types,Manual content swapping,"rootFrame.Navigate(typeof(DetailPage), parameter);","contentPresenter.Content = new DetailPage();",Medium,https://platform.uno/docs/articles/guides/native-frame-nav-tutorial.html
10,Navigation,Use Uno.Extensions.Navigation,Type-safe navigation with DI integration,Uno.Extensions navigation for complex apps,Manual Frame management in large apps,"navigator.NavigateViewModelAsync<DetailViewModel>(this, data: item);","Frame.Navigate with string parsing everywhere",Medium,https://platform.uno/docs/articles/external/uno.extensions/doc/Overview/Navigation/NavigationOverview.html
11,Navigation,Handle platform back navigation,SystemNavigationManager.BackRequested works on Android iOS and WASM but is unimplemented on WinAppSDK desktop where calling GetForCurrentView() throws at runtime,Subscribe to BackRequested only on platforms that support it or use Uno.Toolkit NavigationBar for cross-platform back UX,Calling SystemNavigationManager.GetForCurrentView() on WinUI 3 desktop without a guard,"#if __ANDROID__ || __IOS__ || __WASM__ SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; #endif","SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; with no platform guard — crashes on Windows desktop",High,https://platform.uno/docs/articles/guides/native-frame-nav-tutorial.html
12,Navigation,Use deep linking,Support URI activation across platforms,Handle protocol activation and URI routing,Single entry point ignoring activation,Route URIs to specific pages on activation,Ignoring OnLaunched activation args,Medium,https://platform.uno/docs/articles/features/protocol-activation.html
13,Renderers,Understand Skia vs native rendering,Uno offers both rendering approaches,Skia for pixel-perfect cross-platform consistency,Assuming native rendering on all platforms,"<TargetFrameworks>net10.0-desktop;net10.0-browserwasm</TargetFrameworks> uses unified Skia Desktop shell","Expecting platform-native controls on Skia targets",High,https://platform.uno/docs/articles/features/using-skia-desktop.html
14,Renderers,Use unified net10.0-desktop target,Uno 5.2+ ships a single Skia Desktop shell that auto-selects X11 Win32 or AppKit per OS — Skia.Gtk Skia.Linux.Framebuffer and Skia.WPF heads are deprecated,net10.0-desktop TFM with UnoPlatformHostBuilder for cross-platform desktop,Targeting the legacy Skia.Gtk or Skia.Linux.Framebuffer heads in new projects,"<TargetFrameworks>net10.0-desktop</TargetFrameworks> in the Uno.Sdk single project","Per-OS Skia.Gtk Skia.MacOS Skia.Linux.Framebuffer head projects",Medium,https://platform.uno/docs/articles/features/using-skia-desktop.html
15,Renderers,Test rendering on each target,Visual differences exist between renderers,Visual testing on each active target platform,Testing only on Windows assuming others match,"Screenshot tests on iOS Android WASM and Desktop","Testing only on Windows Desktop",High,https://platform.uno/docs/articles/external/uno.uitest/doc/using-uno-uitest.html
16,Renderers,Use platform-native features when needed,Access native APIs through Uno abstractions,Native platform APIs via platform-specific code,Avoiding native features for purity,"#if __IOS__ UIKit API call #endif for camera access","Pure shared code that avoids using the camera",Medium,https://platform.uno/docs/articles/platform-specific-csharp.html
17,Performance,Optimize WASM bundle size,WebAssembly downloads can be large,IL linker and AOT for smaller WASM bundles,Default settings for production WASM,"<WasmShellILLinkerEnabled>true</WasmShellILLinkerEnabled>","Publishing WASM without linker",High,https://platform.uno/docs/articles/features/using-il-linker-webassembly.html
18,Performance,Use x:Load for deferred XAML,Defer element creation until needed,x:Load=False for hidden panels and tabs,Loading all UI elements upfront,"<StackPanel x:Load=""{x:Bind ShowAdvanced}"">","Always-loaded Collapsed panels",Medium,https://platform.uno/docs/articles/features/windows-ui-xaml-xbind.html
19,Data Binding,Use x:Bind for compiled bindings,Compiled bindings eliminate runtime reflection — Uno supports x:Bind across iOS Android WASM Skia and Windows targets that compile XAML so prefer it over {Binding} for static well-typed bindings,x:Bind for property and event bindings; reserve {Binding} for runtime-typed DataContext scenarios,{Binding} everywhere when x:Bind would compile,"<TextBlock Text=""{x:Bind ViewModel.Title, Mode=OneWay}""/>","<TextBlock Text=""{Binding Title}""/> for a statically known property",High,https://platform.uno/docs/articles/features/windows-ui-xaml-xbind.html
20,Performance,Profile per platform,Performance characteristics vary by target,Platform-specific profiling tools,Assuming desktop perf equals mobile,"Instruments on iOS and Android Profiler on Android","Profiling only on Windows",Medium,https://platform.uno/docs/articles/guides/profiling-applications.html
21,Styling,Use WinUI theme resources,Consistent theming across platforms,ThemeResource for adaptive colors,Hardcoded colors per platform,"Background=""{ThemeResource ApplicationPageBackgroundThemeBrush}""","Background=""#FFFFFF""",High,https://platform.uno/docs/articles/features/working-with-themes.html
22,Styling,Support light and dark themes,Application.RequestedTheme accepts only ApplicationTheme.Light/Dark — to follow the system theme leave it unset entirely. ElementTheme.Default exists only on FrameworkElement.RequestedTheme not on Application,Omit Application.RequestedTheme so the OS theme wins; use RequestedTheme=Default on FrameworkElement to inherit from parent,Setting Application.RequestedTheme=""Default"" — not a valid ApplicationTheme value and throws at parse time,"<Application></Application> with RequestedTheme unset; <Grid RequestedTheme=""Default"">...</Grid> on a FrameworkElement","<Application RequestedTheme=""Default""> // not a valid ApplicationTheme",Medium,https://platform.uno/docs/articles/features/working-with-themes.html
23,Styling,Use Lightweight Styling,Override control sub-properties via resources,Lightweight styling keys for minor tweaks,Full ControlTemplate for small changes,"<Button><Button.Resources><StaticResource x:Key=""ButtonBackground"" ResourceKey=""AccentBrush""/></Button.Resources></Button>","Copying entire ControlTemplate to change one color",Medium,https://platform.uno/docs/articles/external/uno.themes/doc/lightweight-styling.html
24,Styling,Test themes on each platform,Theme rendering differs across platforms,Visual theme testing on all targets,Assuming themes look identical everywhere,"Screenshot comparison across platforms for themed controls","Theming only tested on Windows",Low,https://platform.uno/docs/articles/features/working-with-themes.html
25,Architecture,Use MVVM pattern,Separate view and logic,CommunityToolkit.Mvvm or Prism for MVVM,Code-behind for business logic,"[ObservableProperty] public partial string Title { get; set; } [RelayCommand] private void Save() { }","MainPage.xaml.cs with all logic",High,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
26,Architecture,Use Uno.Extensions,Official extension libraries for common patterns,Uno.Extensions for DI navigation configuration,Building infrastructure from scratch,"Host.CreateDefaultBuilder().UseNavigation().UseConfiguration()","Manual DI and navigation setup",Medium,https://platform.uno/docs/articles/external/uno.extensions/doc/ExtensionsOverview.html
27,Architecture,Use dependency injection,Register services for testability,Microsoft.Extensions.DI through Uno.Extensions,Static service locators and singletons,"services.AddSingleton<IApiService, ApiService>();","ApiService.Instance or new ApiService() in ViewModels",Medium,https://platform.uno/docs/articles/external/uno.extensions/doc/Learn/DependencyInjection/DependencyInjectionOverview.html
28,Architecture,Share code via class libraries,Maximize code reuse across targets,Business logic in .NET Standard or shared library,Business logic in platform head projects,"MyApp.Core class library referenced by all heads","Business logic in MyApp.Wasm.csproj",Medium,https://platform.uno/docs/articles/cross-targeted-libraries.html
29,Architecture,Use Uno.Resizetizer for assets,Single source SVG to multi-platform assets,UnoImage for automatic asset generation from SVG,Manual asset export per resolution and platform,"<UnoImage Include=""Assets/icon.svg"" BaseSize=""24,24""/>","Manually exporting icon_1x.png icon_2x.png icon_3x.png per platform",Medium,https://platform.uno/docs/articles/external/uno.resizetizer/doc/using-uno-resizetizer.html
30,Accessibility,Set AutomationProperties,Enable screen readers across platforms,AutomationProperties.Name on interactive controls,Controls without accessible names,"<Button AutomationProperties.Name=""Submit form""><SymbolIcon Symbol=""Accept""/></Button>","<Button><SymbolIcon Symbol=""Accept""/></Button> without name",High,https://platform.uno/docs/articles/features/working-with-accessibility.html
31,Accessibility,Test accessibility per platform,Each platform has different assistive tech,Test with VoiceOver TalkBack and Narrator,Testing accessibility on one platform only,"VoiceOver on iOS + TalkBack on Android + Narrator on Windows","Only testing with Narrator on Windows",High,https://platform.uno/docs/articles/features/working-with-accessibility.html
32,Accessibility,Support platform text scaling,Respect user font size preferences,Dynamic font scaling for all text,Fixed font sizes ignoring accessibility,"FontSize=""{ThemeResource BodyTextBlockFontSize}""","FontSize=""14"" everywhere",Medium,https://platform.uno/docs/articles/features/working-with-accessibility.html
33,Testing,Unit test ViewModels,Test business logic independently,xUnit or MSTest on shared ViewModel code,UI testing only,"[Fact] public void LoadData_SetsItems() { vm.Load(); Assert.NotEmpty(vm.Items); }","Manual testing on each platform",Medium,https://platform.uno/docs/articles/external/uno.uitest/doc/using-uno-uitest.html
34,Testing,Use Uno.UITest for integration,Cross-platform UI testing framework,Uno.UITest for automated UI tests across platforms,Manual regression testing,"app.WaitForElement(""SaveButton""); app.Tap(""SaveButton"");","Manual click-through on each platform",Medium,https://platform.uno/docs/articles/external/uno.uitest/doc/using-uno-uitest.html
35,WASM,Show an extended splash screen on WASM,WASM bundle download and runtime startup take several seconds on first load — render branded UI immediately so users do not see a blank page (AOT and trimming are covered separately),Render a splash overlay in wwwroot/index.html that hides on first XAML navigation,Letting the user wait on a blank white page while the runtime boots,"index.html: <div id=""uno-loading"">Loading…</div> hidden via JS interop after first Frame.Navigate","No splash markup in index.html — 5-second blank page on first visit",Medium,https://platform.uno/docs/articles/external/uno.wasm.bootstrap/doc/runtime-execution-modes.html
36,WASM,Use AOT compilation for performance,Ahead-of-time compilation improves runtime speed,AOT for production WASM builds,Interpreter mode in production,"<WasmShellMonoRuntimeExecutionMode>InterpreterAndAOT</WasmShellMonoRuntimeExecutionMode>","Default interpreter mode in production deployment",Medium,https://platform.uno/docs/articles/external/uno.wasm.bootstrap/doc/runtime-execution-modes.html
37,WASM,Handle browser limitations,WASM runs in browser sandbox,Feature detection for browser APIs,Assuming desktop capabilities in browser,"[JSImport(""globalThis.hasApi"")] static partial bool HasApi(); #if __WASM__ if (HasApi()) { ... } #endif","#if __WASM__ StorageFile.GetFileFromPathAsync(""C:/data"") #endif",Medium,https://platform.uno/docs/articles/platform-specific-csharp.html
38,Controls,Use NavigationView for app shell,WinUI NavigationView for consistent navigation across platforms,NavigationView with MenuItems for app navigation,Custom hamburger menu implementation,"<NavigationView><NavigationView.MenuItems><NavigationViewItem Content=""Home"" Icon=""Home""/></NavigationView.MenuItems></NavigationView>","Custom SplitView with manual toggle button",High,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/navigationview
39,Controls,Use ContentDialog for modal interactions,Cross-platform modal dialogs using WinUI API,ContentDialog for confirmations and input,Custom overlay Panel as dialog,"<ContentDialog Title=""Confirm"" PrimaryButtonText=""OK"" CloseButtonText=""Cancel""/>","Grid overlay with manual focus trapping",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/dialogs-and-flyouts/dialogs
40,Controls,Use CommandBar for app actions,Standard command bar with primary and secondary commands,CommandBar with AppBarButtons for toolbar actions,Custom StackPanel toolbar,"<CommandBar><AppBarButton Icon=""Save"" Label=""Save""/><AppBarButton Icon=""Delete"" Label=""Delete""/></CommandBar>","<StackPanel Orientation=""Horizontal""><Button>Save</Button></StackPanel>",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/command-bar
41,Controls,Use ToggleSwitch for boolean settings,Platform-native toggle control for on/off preferences,ToggleSwitch for settings and feature flags,CheckBox for toggle settings,"<ToggleSwitch Header=""Dark Mode"" IsOn=""{x:Bind ViewModel.IsDarkMode, Mode=TwoWay}""/>","<CheckBox Content=""Enable dark mode""/>",Low,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/toggles
42,Data Binding,Implement INotifyPropertyChanged,Enable UI updates when ViewModel properties change,CommunityToolkit.Mvvm [ObservableProperty] for auto-notification,Properties without change notification,"[ObservableProperty] public partial string Title { get; set; }","public string Title { get; set; } without notification",High,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
43,Data Binding,Use ObservableCollection for bound lists,Collection change notifications for ItemsSources across platforms,ObservableCollection<T> for data-bound lists,List<T> for bound ItemsSources,"ObservableCollection<Item> Items { get; } = new();","List<Item> Items { get; set; } = new();",High,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
44,Lifecycle,Handle app suspension on mobile,iOS and Android may suspend or terminate the app — WinAppSDK desktop does not raise Suspending so use window Closed for desktop save-state,Save state in OnSuspending and restore on activation,Ignoring lifecycle losing user state on mobile,"Application.Current.Suspending += (s, e) => { var d = e.SuspendingOperation.GetDeferral(); SaveState(); d.Complete(); };","No suspend handler losing form data on mobile",High,https://platform.uno/docs/articles/features/windows-ui-xaml-application.html
45,Lifecycle,Use Uno.Extensions.Hosting for startup,Structured app initialization with DI and configuration,IHost builder pattern for app startup and service registration,Manual initialization in App constructor,"Host.CreateDefaultBuilder().ConfigureServices(s => s.AddSingleton<MainViewModel>()).Build();","new MainViewModel() in App.xaml.cs constructor",Medium,https://platform.uno/docs/articles/external/uno.extensions/doc/Overview/Hosting/HostingOverview.html
46,Performance,Use ListView virtualization for large lists,Only renders visible items to reduce memory and layout cost,ListView with default ItemsStackPanel virtualization,ItemsControl or StackPanel for large data sets,"<ListView ItemsSource=""{x:Bind Items}""/> (virtualizes by default)","<ItemsControl><StackPanel> rendering 5000 items at once",High,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/listview-and-gridview
47,Accessibility,Support keyboard navigation on desktop,Skia and WinAppSDK targets need full keyboard operability — note TabIndex routing is not fully implemented on every Uno target,AccessKey and KeyboardAccelerator on Skia and WinAppSDK targets,Mouse-only interactions on desktop,"<Button AccessKey=""S"" Content=""Save""><Button.KeyboardAccelerators><KeyboardAccelerator Modifiers=""Control"" Key=""S""/></Button.KeyboardAccelerators></Button>","Clickable controls without keyboard support on desktop",High,https://learn.microsoft.com/en-us/windows/apps/develop/input/keyboard-accelerators
48,WASM,Use service workers for offline support,Enable PWA capabilities for WASM deployments,Service worker registration for caching and offline mode,Online-only WASM app with no offline fallback,"<WasmPWAManifestFile>manifest.webmanifest</WasmPWAManifestFile>","No service worker leaving WASM app unusable offline",Low,https://platform.uno/docs/articles/external/uno.wasm.bootstrap/doc/features-pwa.html
49,Performance,Marshal to UI thread with DispatcherQueue,Cross-thread access to UI elements throws — capture the UI DispatcherQueue once and use TryEnqueue to update from background work,DispatcherQueue.GetForCurrentThread().TryEnqueue from background work,Touching UI controls directly from a Task,"_dispatcher.TryEnqueue(() => StatusText.Text = ""Done"");","await Task.Run(() => StatusText.Text = ""Done""); throws on non-UI thread",High,https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.dispatching.dispatcherqueue
50,Styling,Merge XamlControlsResources in App.xaml,Required for Fluent control styles to load — without it controls render with no template,Add XamlControlsResources at the top of Application.Resources MergedDictionaries,Skipping the merged dictionary and wondering why Buttons look unstyled,"<Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><XamlControlsResources xmlns=""using:Microsoft.UI.Xaml.Controls""/></ResourceDictionary.MergedDictionaries></ResourceDictionary></Application.Resources>","<Application.Resources><SolidColorBrush x:Key=""MyBrush"" Color=""Red""/></Application.Resources> with no XamlControlsResources merged",High,https://platform.uno/docs/articles/features/fluent-styles.html
51,Architecture,Use async [RelayCommand] for I/O,AsyncRelayCommand reports CanExecute=false (raising CanExecuteChanged) and exposes IsRunning while the Task is in flight — the bound control is disabled and re-entrancy is prevented by default (AllowConcurrentExecutions=false),[RelayCommand] on a Task-returning method for awaitable work,async void event handlers calling .Wait() or .Result,"[RelayCommand] private async Task LoadAsync() { Items = await _api.GetAsync(); }","public void OnLoadClick(object s, EventArgs e) { LoadAsync().Wait(); } deadlock risk",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/relaycommand
52,Architecture,Use x:Uid for localized strings,WinUI x:Uid resolves UI text from .resw resources at runtime — use it instead of hardcoded strings to support localization across iOS Android WASM and desktop from a single project,x:Uid on every user-facing string with matching .resw entries per language under Strings/{lang}/Resources.resw,Hardcoding language-specific strings into XAML or code-behind,"<Button x:Uid=""SubmitButton""/> with Strings/en/Resources.resw entry SubmitButton.Content=Submit","<Button Content=""Submit""/> hardcoded in XAML",High,https://platform.uno/docs/articles/features/working-with-strings.html
53,Architecture,Wire up ILogger via Uno.Extensions.Logging,Cross-platform logging routes to platform-native sinks (OSLog on iOS Console on WASM Debug elsewhere) when configured through the IHost builder,Inject ILogger<T> into ViewModels and services and call UseLogging() on the host builder,Console.WriteLine or platform-specific log APIs scattered across shared code,"Host.CreateDefaultBuilder().UseLogging(c => c.SetMinimumLevel(LogLevel.Information)) and ILogger<MainViewModel> via constructor injection","Console.WriteLine(""error"") in shared code with no platform-aware routing",Medium,https://platform.uno/docs/articles/external/uno.extensions/doc/Overview/Logging/LoggingOverview.html
54,Performance,Enable PublishAot on net10.0-desktop,Skia Desktop on .NET 10 supports Native AOT for faster cold start and smaller deployments — opt in per-target so debug builds remain fast,<PublishAot>true</PublishAot> in a TFM-conditional PropertyGroup for net10.0-desktop release builds,Enabling PublishAot globally and breaking debug iteration on every TFM,"<PropertyGroup Condition=""'$(TargetFramework)'=='net10.0-desktop' AND '$(Configuration)'=='Release'""><PublishAot>true</PublishAot></PropertyGroup>","<PublishAot>true</PublishAot> at root with no TFM/Configuration condition",Medium,https://platform.uno/docs/articles/features/using-skia-desktop.html
55,Performance,Never block on async with .Result or .Wait(),Blocking on a Task from the UI thread deadlocks because the awaiter cannot resume on the captured SynchronizationContext — always await async APIs through to the event handler,Await async methods all the way up; in libraries call ConfigureAwait(false) to avoid context capture,Calling .Result .Wait() or GetAwaiter().GetResult() on a Task from the UI thread,"private async void OnLoadClick(object s, RoutedEventArgs e) { var data = await _api.GetAsync(); Items = data; }","private void OnLoadClick(object s, RoutedEventArgs e) { var data = _api.GetAsync().Result; } // deadlocks on UI thread",High,https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
56,Styling,Define ThemeDictionaries for Light Dark and HighContrast,Resources placed inside ResourceDictionary.ThemeDictionaries entries are automatically swapped when the system theme changes — required for theme-aware brushes,Wrap brushes in a ThemeDictionaries dictionary keyed by Light Dark and HighContrast in App.xaml or page resources,Defining a single brush at the root and missing dark/high-contrast variants,"<ResourceDictionary.ThemeDictionaries><ResourceDictionary x:Key=""Light""><SolidColorBrush x:Key=""Brand"" Color=""#005A9E""/></ResourceDictionary><ResourceDictionary x:Key=""Dark""><SolidColorBrush x:Key=""Brand"" Color=""#3A96DD""/></ResourceDictionary></ResourceDictionary.ThemeDictionaries>","<SolidColorBrush x:Key=""Brand"" Color=""#005A9E""/> at root with no theme variants",Medium,https://platform.uno/docs/articles/features/working-with-themes.html
57,Architecture,Use Uno.Sdk with UnoFeatures,Uno.Sdk is the modern single-project SDK that auto-resolves Uno.WinUI Uno.Toolkit Material and other packages from a UnoFeatures property — declare features by name instead of hand-managing dozens of PackageReferences,Declare features in the csproj via <UnoFeatures>...</UnoFeatures> and let the SDK resolve transitive packages,Hand-adding every Uno.* PackageReference and matching version numbers across packages,"<Project Sdk=""Uno.Sdk""><PropertyGroup><UnoFeatures>Material;Hosting;Toolkit;Logging;MVVM</UnoFeatures></PropertyGroup></Project>","<PackageReference Include=""Uno.WinUI""/><PackageReference Include=""Uno.Material.WinUI""/> ... duplicated per feature with mismatched versions",Medium,https://platform.uno/docs/articles/features/using-the-uno-sdk.html
58,Lifecycle,Persist desktop window state via Window.Closed,WinAppSDK and Skia desktop heads do not raise Application.Suspending — handle the Window.Closed event (and AppWindow size/position changes) to save user state when desktop apps shut down,Subscribe to MainWindow.Closed and persist any unsaved state before the window is destroyed,Relying on Application.Suspending to fire on desktop targets,"m_window.Closed += (s, e) => SaveState();","Application.Current.Suspending += SaveState; // never fires on WinAppSDK or Skia desktop",Medium,https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.window
59,Architecture,Use WinRT.Interop for native window handle on Windows,Calling Win32 APIs from a WinUI Window (file pickers icon embedding etc.) requires the HWND — retrieve it via WinRT.Interop.WindowNative.GetWindowHandle and guard the call so non-Windows targets stay unaffected,GetWindowHandle inside a #if WINDOWS block when you need the HWND,Calling WinRT.Interop in shared code without a platform guard,"#if WINDOWS\nvar hWnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow);\n#endif","var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow); // breaks build on iOS Android WASM",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/retrieve-hwnd
Can't render this file because it contains an unexpected character in line 23 and column 412.

View File

@ -0,0 +1,56 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,XAML,Use x:Bind for compiled bindings,Compile-time validated bindings with better performance,x:Bind for type-safe performant bindings,{Binding} when x:Bind is available,"<TextBlock Text=""{x:Bind ViewModel.Name, Mode=OneWay}""/>","<TextBlock Text=""{Binding Name}""/>",High,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
2,XAML,Use x:Load for deferred elements,Delay creation of elements until needed,x:Load=False for hidden or conditional panels,Loading all UI elements at page load,"<StackPanel x:Name=""AdvancedPanel"" x:Load=""{x:Bind ShowAdvanced, Mode=OneWay}"">","Collapsed StackPanel that is always instantiated",Medium,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-load-attribute
3,XAML,Use x:Phase for incremental item rendering,Render list items in priority phases,x:Phase on secondary content in item DataTemplates,All template content loaded in one pass,"<TextBlock x:Phase=""1"" Text=""{x:Bind Description}""/>","Complex DataTemplate with no phasing",Medium,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-phase-attribute
4,XAML,Use x:DefaultBindMode,Reduce repetitive Mode= declarations,x:DefaultBindMode=OneWay on containers,Mode=OneWay on every individual x:Bind,"<StackPanel x:DefaultBindMode=""OneWay"">","Mode=OneWay repeated on every binding in a panel",Low,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
5,XAML,Use x:DeferLoadStrategy for legacy support,Deferred loading before x:Load was available,x:Load (preferred) or x:DeferLoadStrategy=Lazy,Eagerly loading rarely shown UI,"x:Load=""False"" (or x:DeferLoadStrategy=""Lazy"" on older targets)","Always-loaded panels toggled with Visibility",Low,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-deferloadstrategy-attribute
6,Controls,Use NavigationView for app shell,Standard UWP navigation pattern with hamburger menu,NavigationView for top-level navigation,Custom SplitView hamburger menu,"<NavigationView><NavigationView.MenuItems><NavigationViewItem Content=""Home"" Icon=""Home""/></NavigationView.MenuItems></NavigationView>","Custom SplitView with manual toggle button",High,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/navigationview
7,Controls,Use CommandBar for app actions,Standard app bar for primary commands,CommandBar with AppBarButtons,Custom StackPanel toolbar,"<CommandBar><AppBarButton Icon=""Save"" Label=""Save""/></CommandBar>","<StackPanel Orientation=""Horizontal""><Button>Save</Button></StackPanel>",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/command-bar
8,Controls,Use ContentDialog for modals,System-styled modal dialogs,ContentDialog for confirmations and input,Custom popup overlays,"<ContentDialog Title=""Confirm"" PrimaryButtonText=""Yes"" CloseButtonText=""No""/>","Grid overlay with manual focus trapping",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/dialogs-and-flyouts/dialogs
9,Controls,Use AutoSuggestBox for search,Built-in search box with suggestions,AutoSuggestBox with QuerySubmitted and SuggestionChosen,TextBox with manual suggestion popup,"<AutoSuggestBox QueryIcon=""Find"" TextChanged=""OnTextChanged"" SuggestionChosen=""OnChosen"" QuerySubmitted=""OnQuerySubmitted""/>","TextBox with custom Popup and ListBox for suggestions",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/auto-suggest-box
10,Controls,Use CalendarDatePicker and TimePicker,Platform-consistent date and time selection,Built-in date and time pickers,Custom date selection controls,"<CalendarDatePicker Header=""Start date""/><TimePicker Header=""Time""/>","TextBox with date parsing and validation",Low,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/date-and-time
11,Controls,Use PersonPicture for user avatars,Consistent avatar display with fallback initials,PersonPicture with DisplayName and ProfilePicture,Custom Ellipse with ImageBrush for avatars,"<PersonPicture DisplayName=""Jane Doe"" ProfilePicture=""{x:Bind AvatarUri}""/>","<Ellipse><Ellipse.Fill><ImageBrush ImageSource=""avatar.png""/></Ellipse.Fill></Ellipse>",Low,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/person-picture
12,Styling,Use ThemeResource for adaptive colors,Colors that switch with light and dark theme,ThemeResource for all color references,Hardcoded hex values that break in dark mode,"Foreground=""{ThemeResource SystemControlForegroundBaseHighBrush}""","Foreground=""#000000""",High,https://learn.microsoft.com/en-us/windows/uwp/design/style/color
13,Styling,Use Fluent Design materials,Acrylic translucent material for depth,Built-in Fluent materials for depth and motion,Custom shader effects for blur and reveal,"<Grid Background=""{ThemeResource SystemControlAcrylicWindowBrush}""/>","Custom CompositionEffectBrush recreating acrylic",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/style/acrylic
14,Styling,Use Lightweight Styling,Override control resource keys for subtle changes,Lightweight styling resource overrides,Full ControlTemplate copy for small tweaks,"<Button><Button.Resources><SolidColorBrush x:Key=""ButtonBackground"" Color=""Blue""/></Button.Resources></Button>","Entire ControlTemplate copied to change background",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-styles#lightweight-styling
15,Styling,Use implicit styles for consistency,TargetType without x:Key applies to all instances,Implicit Style for default control appearance,Repeating Setters on every control instance,"<Style TargetType=""Button""><Setter Property=""CornerRadius"" Value=""4""/></Style>","CornerRadius=""4"" on every Button in the page",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-styles
16,Styling,Use VisualStateManager for visual states,Define visual states with Setters that change properties when triggered,VisualStateGroup containing VisualStates with Setter targets,Toggling Visibility from code-behind on SizeChanged,"<VisualStateGroup><VisualState x:Name=""Wide""><VisualState.Setters><Setter Target=""root.Orientation"" Value=""Horizontal""/></VisualState.Setters></VisualState></VisualStateGroup>","SizeChanged handler that flips Orientation in code-behind",High,https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml
17,Navigation,Use Frame for page navigation,Windows.UI.Xaml.Controls.Frame for UWP page navigation,Frame.Navigate with typed parameters,Swapping UserControls manually,"rootFrame.Navigate(typeof(DetailPage), itemId);","contentArea.Content = new DetailPage();",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/basics/navigate-between-two-pages
18,Navigation,Handle back button correctly,Provide an in-app Back button styled with NavigationBackButtonNormalStyle and handle SystemNavigationManager.BackRequested for hardware back gamepad B and Tablet-Mode back; also handle CoreDispatcher.AcceleratorKeyActivated for Alt+Left,In-app NavigationBackButtonNormalStyle button plus SystemNavigationManager.BackRequested handler,Relying on the deprecated title-bar back button (AppViewBackButtonVisibility) or ignoring system back signals,"SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;","No back button support on phone or tablet",High,https://learn.microsoft.com/en-us/windows/uwp/ui-input/back-navigation
19,Navigation,Support deep linking with protocol activation,Respond to URI activation and toast taps,OnActivated handler with proper page routing,Ignoring activation arguments,"protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { ... } }","Empty OnActivated ignoring URI parameters",Medium,https://learn.microsoft.com/en-us/windows/uwp/launch-resume/handle-uri-activation
20,Navigation,Use ConnectedAnimations for continuity,Smooth transitions between pages,ConnectedAnimationService for shared element transitions,Abrupt page transitions with no visual continuity,"ConnectedAnimationService.GetForCurrentView().PrepareToAnimate(""image"", sourceImage);","No transition animation between list and detail",Low,https://learn.microsoft.com/en-us/windows/uwp/design/motion/connected-animation
21,Data Binding,Implement INotifyPropertyChanged,Enable UI updates on property changes,INotifyPropertyChanged on all ViewModels,Auto-properties without notification,"public string Title { get => _title; set { _title = value; OnPropertyChanged(); } }","public string Title { get; set; } expecting UI updates",High,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
22,Data Binding,Use ObservableCollection for lists,Collection change notifications for ItemsSources,ObservableCollection<T> for bound lists,List<T> for data-bound collections,"ObservableCollection<Item> Items { get; } = new();","List<Item> Items { get; set; } = new();",High,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
23,Data Binding,Use function bindings with x:Bind,Call static methods directly in markup,x:Bind to static converter methods,IValueConverter for trivial transforms,"<TextBlock Visibility=""{x:Bind local:Converters.BoolToVisibility(IsActive), Mode=OneWay}""/>","Full IValueConverter class for bool to Visibility",Medium,https://learn.microsoft.com/en-us/windows/uwp/data-binding/function-bindings
24,Data Binding,Specify Mode on x:Bind,x:Bind defaults to OneTime not OneWay,Mode=OneWay or TwoWay when live updates needed,Omitting Mode and getting stale UI,"Text=""{x:Bind Title, Mode=OneWay}""","Text=""{x:Bind Title}"" expecting live updates",High,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
25,Data Binding,Use CollectionViewSource for grouping,Group and sort collections declaratively,CollectionViewSource for grouped ListView and GridView,Manual grouping logic in code-behind,"<CollectionViewSource x:Key=""GroupedItems"" IsSourceGrouped=""True"" Source=""{x:Bind GroupedData}""/>","Manual loop building grouped StackPanels",Medium,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
26,Performance,Use ListView and GridView virtualization,Only creates containers for visible items,Default virtualization in ListView and GridView,Setting ItemsPanel to non-virtualizing panel,"<ListView ItemsSource=""{x:Bind Items}""/> (virtualizes by default)","<ListView><ListView.ItemsPanel><ItemsPanelTemplate><StackPanel/></ItemsPanelTemplate></ListView.ItemsPanel></ListView>",High,https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/optimize-gridview-and-listview
27,Performance,Use ISupportIncrementalLoading,Load data on demand as user scrolls,ISupportIncrementalLoading for large datasets,Loading entire collection upfront,"class IncrementalSource : ObservableCollection<Item>, ISupportIncrementalLoading","await LoadAll() loading 50K items at startup",Medium,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
28,Performance,Reduce XAML visual tree depth,Simpler trees layout and render faster,Flat templates with minimal nesting,Deeply nested panels in DataTemplates,"<StackPanel><TextBlock/><TextBlock/></StackPanel> in item template","<Grid><Border><StackPanel><Grid>... 8 levels in item template",Medium,https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/optimize-xaml-loading
29,Performance,Use compiled bindings in DataTemplates,x:Bind in templates requires x:DataType,x:DataType on DataTemplate for compiled bindings,{Binding} in item templates for large lists,"<DataTemplate x:DataType=""local:Item""><TextBlock Text=""{x:Bind Name}""/></DataTemplate>","<DataTemplate><TextBlock Text=""{Binding Name}""/></DataTemplate>",High,https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
30,Performance,Profile with Visual Studio diagnostics,Measure before optimizing,Application Timeline and Memory Usage tools,Guessing at performance problems,"VS Diagnostic Tools > Application Timeline","Optimizing without profiling data",Medium,https://learn.microsoft.com/en-us/visualstudio/profiling/application-timeline
31,Threading,Use async/await for all IO,Keep UI thread responsive,async/await for file network and database operations,Synchronous IO blocking the UI thread,"var file = await StorageFile.GetFileFromPathAsync(path);","StorageFile.GetFileFromPathAsync(path).AsTask().Result;",High,https://learn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps
32,Threading,Use CoreDispatcher for UI thread access,Post work back to the UI thread from background,Dispatcher.RunAsync from background threads,Touching UI elements from background threads,"await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Status = ""Done"");","textBlock.Text = ""Done"" from Task.Run",High,https://learn.microsoft.com/en-us/uwp/api/windows.ui.core.coredispatcher
33,Threading,Offload CPU work with Task.Run,Keep compute-heavy work off UI thread,Task.Run for CPU-bound operations,Heavy computation blocking UI,"var result = await Task.Run(() => ProcessData(items));","var result = ProcessData(items); freezing UI",High,https://learn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps
34,Threading,Use IProgress for status updates,Report progress from background operations,IProgress<T> for progress reporting to UI,Polling shared variables for progress,"var progress = new Progress<int>(p => ProgressBar.Value = p); await Task.Run(() => Process(progress));","while (!done) { await Task.Delay(100); check shared field; }",Medium,https://learn.microsoft.com/en-us/dotnet/api/system.progress-1
35,Adaptive,Use AdaptiveTrigger for responsive layouts,MinWindowWidth and MinWindowHeight triggers fire at standard breakpoints (640 small / 1008 medium),AdaptiveTrigger inside VisualState.StateTriggers with the 640 and 1008 breakpoints,Fixed layouts for a single screen size,"<VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth=""640""/></VisualState.StateTriggers>","Single-column layout at all widths",High,https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml
36,Adaptive,Design for multiple device families,Phone tablet desktop Xbox and HoloLens,DeviceFamily-specific views and resources,Desktop-only design ignoring other form factors,"DeviceFamily-Mobile/MainPage.xaml for phone-specific layout","Fixed 1920x1080 layout",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/layout/screen-sizes-and-breakpoints-for-responsive-design
37,Adaptive,Use RelativePanel for adaptive positioning,Controls position relative to each other,RelativePanel for layouts that reflow at breakpoints,Absolute positioning or fixed margins,"<Button RelativePanel.Below=""title"" RelativePanel.AlignLeftWithPanel=""True""/>","<Button Margin=""0,60,0,0""/> calculated from title height",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml#relativepanel
38,Adaptive,Support multi-window with secondary views,Open detached views with CoreApplication.CreateNewView and ApplicationViewSwitcher,CreateNewView and TryShowAsStandaloneAsync for multi-document scenarios,Single-window assumptions when scenarios benefit from secondary views,"var view = CoreApplication.CreateNewView(); await view.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { /* set content */ });","Modal overlay used for content that should be a separate window",Medium,https://learn.microsoft.com/en-us/windows/uwp/design/layout/show-multiple-views
39,Accessibility,Set AutomationProperties,Enable Narrator and screen reader support,AutomationProperties.Name on all interactive controls,Controls without accessible names,"<AppBarButton AutomationProperties.Name=""Save document"" Icon=""Save""/>","<AppBarButton Icon=""Save""/> without name",High,https://learn.microsoft.com/en-us/windows/uwp/design/accessibility/basic-accessibility-information
40,Accessibility,Support keyboard and gamepad,All functions reachable without touch,Tab navigation XYFocus and access keys,Touch-only interactions,"<Button AccessKey=""S"" XYFocusDown=""{x:Bind OtherButton}""/>","No keyboard or gamepad support",High,https://learn.microsoft.com/en-us/windows/uwp/design/input/keyboard-interactions
41,Accessibility,Support contrast themes,Respect system contrast themes (renamed from high contrast in Windows 11),ThemeResource brushes that adapt to contrast themes,Hardcoded colors that vanish under contrast themes,"Foreground=""{ThemeResource SystemControlForegroundBaseHighBrush}""","Foreground=""#444444""",High,https://learn.microsoft.com/en-us/windows/uwp/design/accessibility/high-contrast-themes
42,Accessibility,Test with Narrator and Accessibility Insights,Validate screen reader and automation compliance,Regular Narrator walkthrough and Accessibility Insights scan,Shipping without accessibility testing,"Accessibility Insights FastPass on every page","No accessibility testing before release",Medium,https://accessibilityinsights.io/
43,Architecture,Use MVVM pattern,Separate View ViewModel and Model,ViewModel with INotifyPropertyChanged and ICommand,Business logic in code-behind,"ViewModel bound via DataContext with commands","MainPage.xaml.cs with database calls and UI logic",Medium,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm
44,Architecture,Use Template Studio for scaffolding,Proven project templates with navigation and services,Windows Template Studio for new UWP projects,Blank project with manual boilerplate,"Template Studio with MVVM Toolkit and navigation service","Blank App template building everything from scratch",Low,https://github.com/microsoft/TemplateStudio
45,Architecture,Use dependency injection,Register services for testability,Microsoft.Extensions.DI for service resolution,Static singletons and manual construction,"services.AddTransient<MainViewModel>(); services.AddSingleton<IDataService, DataService>();","DataService.Instance or new DataService() everywhere",Medium,https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
46,Architecture,Keep platform APIs behind abstractions,Isolate WinRT APIs from business logic,Interfaces wrapping StorageFile FilePicker etc,Direct WinRT calls in ViewModels,"IFileService wrapping FileOpenPicker and StorageFile","FileOpenPicker usage directly in ViewModel",Medium,https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm
47,Lifecycle,Handle suspend and resume,UWP apps are suspended when not in foreground,Save state in OnSuspending and restore in OnLaunched,Ignoring app lifecycle losing user state,"Application.Current.Suspending += (s, e) => SaveState();","No suspend handler losing in-progress form data",High,https://learn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle
48,Lifecycle,Use ExtendedExecutionSession for background work,Request extended time for unfinished operations,ExtendedExecutionSession for saving or uploads,Assuming background work completes after suspend,"var session = new ExtendedExecutionSession { Reason = ExtendedExecutionReason.SavingData };","Long upload with no extended execution that gets killed on suspend",Medium,https://learn.microsoft.com/en-us/windows/uwp/launch-resume/run-minimized-with-extended-execution
49,Lifecycle,Handle prelaunch,Apps must opt in to prelaunch via CoreApplication.EnablePrelaunch(true) starting in Windows 10 1607; check LaunchActivatedEventArgs.PrelaunchActivated to skip user-visible work,Opt in with EnablePrelaunch and skip heavy init when PrelaunchActivated is true,Performing full initialization or navigating during prelaunch,"CoreApplication.EnablePrelaunch(true); if (e.PrelaunchActivated) return; // skip heavy init","Loading all data and navigating on prelaunch",Medium,https://learn.microsoft.com/en-us/windows/uwp/launch-resume/handle-app-prelaunch
50,Testing,Unit test ViewModels,Test logic without UI framework dependencies,xUnit or MSTest on ViewModel methods,Testing only through the running app,"[Fact] public async Task Load_PopulatesItems() { await vm.LoadAsync(); Assert.NotEmpty(vm.Items); }","Manual testing by tapping through the app",Medium,https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
51,Testing,Use WinAppDriver with Appium for UI tests,Automated UI testing for UWP (Coded UI Test was deprecated in Visual Studio 2019); WinAppDriver v1 is in low-maintenance mode and Appium 2 is the modern direction,WinAppDriver with Appium for end-to-end tests,Manual regression testing,"session.FindElementByAccessibilityId(""SaveButton"").Click();","Manual click-through testing before each release",Medium,https://github.com/microsoft/WinAppDriver
52,Testing,Test on multiple device families,Behavior varies across phone desktop and Xbox,Test on device emulators and real hardware,Desktop-only testing,"Test on Mobile emulator and Xbox dev mode","Only running on local desktop",Medium,https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal
53,Architecture,Prefer WinUI 3 for new projects,UWP is in maintenance mode and Microsoft recommends WinUI 3 and Windows App SDK for new development,WinUI 3 with Windows App SDK for new desktop apps,Starting new projects on UWP when WinUI 3 is available,"New project with Microsoft.WindowsAppSDK and WinUI 3","New UWP project for a desktop-only app in 2024+",Medium,https://learn.microsoft.com/en-us/windows/apps/get-started/
54,Architecture,Plan migration to Windows App SDK,Microsoft provides migration guides from UWP to WinUI 3,Incremental migration using XAML Islands or full port to WinUI 3,Ignoring migration path and accumulating UWP technical debt,"Follow UWP to WinUI 3 migration guide for existing apps","Continuing major feature development on UWP without migration plan",Medium,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/migrate-to-windows-app-sdk/overall-migration-strategy
55,Lifecycle,Use a deferral when saving async state on suspend,Suspending grants only ~5 seconds before the OS may terminate; await work needs SuspendingOperation.GetDeferral and Complete or save returns before it finishes,GetDeferral around async save calls and Complete in finally,Async work that returns the suspending handler before completion,"async void OnSuspending(object s, SuspendingEventArgs e) { var d = e.SuspendingOperation.GetDeferral(); try { await SaveAsync(); } finally { d.Complete(); } }","async void OnSuspending(object s, SuspendingEventArgs e) { await SaveAsync(); } // handler returns before save completes",Medium,https://learn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle
1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 XAML Use x:Bind for compiled bindings Compile-time validated bindings with better performance x:Bind for type-safe performant bindings {Binding} when x:Bind is available <TextBlock Text="{x:Bind ViewModel.Name, Mode=OneWay}"/> <TextBlock Text="{Binding Name}"/> High https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
3 2 XAML Use x:Load for deferred elements Delay creation of elements until needed x:Load=False for hidden or conditional panels Loading all UI elements at page load <StackPanel x:Name="AdvancedPanel" x:Load="{x:Bind ShowAdvanced, Mode=OneWay}"> Collapsed StackPanel that is always instantiated Medium https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-load-attribute
4 3 XAML Use x:Phase for incremental item rendering Render list items in priority phases x:Phase on secondary content in item DataTemplates All template content loaded in one pass <TextBlock x:Phase="1" Text="{x:Bind Description}"/> Complex DataTemplate with no phasing Medium https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-phase-attribute
5 4 XAML Use x:DefaultBindMode Reduce repetitive Mode= declarations x:DefaultBindMode=OneWay on containers Mode=OneWay on every individual x:Bind <StackPanel x:DefaultBindMode="OneWay"> Mode=OneWay repeated on every binding in a panel Low https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
6 5 XAML Use x:DeferLoadStrategy for legacy support Deferred loading before x:Load was available x:Load (preferred) or x:DeferLoadStrategy=Lazy Eagerly loading rarely shown UI x:Load="False" (or x:DeferLoadStrategy="Lazy" on older targets) Always-loaded panels toggled with Visibility Low https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-deferloadstrategy-attribute
7 6 Controls Use NavigationView for app shell Standard UWP navigation pattern with hamburger menu NavigationView for top-level navigation Custom SplitView hamburger menu <NavigationView><NavigationView.MenuItems><NavigationViewItem Content="Home" Icon="Home"/></NavigationView.MenuItems></NavigationView> Custom SplitView with manual toggle button High https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/navigationview
8 7 Controls Use CommandBar for app actions Standard app bar for primary commands CommandBar with AppBarButtons Custom StackPanel toolbar <CommandBar><AppBarButton Icon="Save" Label="Save"/></CommandBar> <StackPanel Orientation="Horizontal"><Button>Save</Button></StackPanel> Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/command-bar
9 8 Controls Use ContentDialog for modals System-styled modal dialogs ContentDialog for confirmations and input Custom popup overlays <ContentDialog Title="Confirm" PrimaryButtonText="Yes" CloseButtonText="No"/> Grid overlay with manual focus trapping Medium https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/dialogs-and-flyouts/dialogs
10 9 Controls Use AutoSuggestBox for search Built-in search box with suggestions AutoSuggestBox with QuerySubmitted and SuggestionChosen TextBox with manual suggestion popup <AutoSuggestBox QueryIcon="Find" TextChanged="OnTextChanged" SuggestionChosen="OnChosen" QuerySubmitted="OnQuerySubmitted"/> TextBox with custom Popup and ListBox for suggestions Medium https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/auto-suggest-box
11 10 Controls Use CalendarDatePicker and TimePicker Platform-consistent date and time selection Built-in date and time pickers Custom date selection controls <CalendarDatePicker Header="Start date"/><TimePicker Header="Time"/> TextBox with date parsing and validation Low https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/date-and-time
12 11 Controls Use PersonPicture for user avatars Consistent avatar display with fallback initials PersonPicture with DisplayName and ProfilePicture Custom Ellipse with ImageBrush for avatars <PersonPicture DisplayName="Jane Doe" ProfilePicture="{x:Bind AvatarUri}"/> <Ellipse><Ellipse.Fill><ImageBrush ImageSource="avatar.png"/></Ellipse.Fill></Ellipse> Low https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/person-picture
13 12 Styling Use ThemeResource for adaptive colors Colors that switch with light and dark theme ThemeResource for all color references Hardcoded hex values that break in dark mode Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}" Foreground="#000000" High https://learn.microsoft.com/en-us/windows/uwp/design/style/color
14 13 Styling Use Fluent Design materials Acrylic translucent material for depth Built-in Fluent materials for depth and motion Custom shader effects for blur and reveal <Grid Background="{ThemeResource SystemControlAcrylicWindowBrush}"/> Custom CompositionEffectBrush recreating acrylic Medium https://learn.microsoft.com/en-us/windows/uwp/design/style/acrylic
15 14 Styling Use Lightweight Styling Override control resource keys for subtle changes Lightweight styling resource overrides Full ControlTemplate copy for small tweaks <Button><Button.Resources><SolidColorBrush x:Key="ButtonBackground" Color="Blue"/></Button.Resources></Button> Entire ControlTemplate copied to change background Medium https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-styles#lightweight-styling
16 15 Styling Use implicit styles for consistency TargetType without x:Key applies to all instances Implicit Style for default control appearance Repeating Setters on every control instance <Style TargetType="Button"><Setter Property="CornerRadius" Value="4"/></Style> CornerRadius="4" on every Button in the page Medium https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-styles
17 16 Styling Use VisualStateManager for visual states Define visual states with Setters that change properties when triggered VisualStateGroup containing VisualStates with Setter targets Toggling Visibility from code-behind on SizeChanged <VisualStateGroup><VisualState x:Name="Wide"><VisualState.Setters><Setter Target="root.Orientation" Value="Horizontal"/></VisualState.Setters></VisualState></VisualStateGroup> SizeChanged handler that flips Orientation in code-behind High https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml
18 17 Navigation Use Frame for page navigation Windows.UI.Xaml.Controls.Frame for UWP page navigation Frame.Navigate with typed parameters Swapping UserControls manually rootFrame.Navigate(typeof(DetailPage), itemId); contentArea.Content = new DetailPage(); Medium https://learn.microsoft.com/en-us/windows/uwp/design/basics/navigate-between-two-pages
19 18 Navigation Handle back button correctly Provide an in-app Back button styled with NavigationBackButtonNormalStyle and handle SystemNavigationManager.BackRequested for hardware back gamepad B and Tablet-Mode back; also handle CoreDispatcher.AcceleratorKeyActivated for Alt+Left In-app NavigationBackButtonNormalStyle button plus SystemNavigationManager.BackRequested handler Relying on the deprecated title-bar back button (AppViewBackButtonVisibility) or ignoring system back signals SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; No back button support on phone or tablet High https://learn.microsoft.com/en-us/windows/uwp/ui-input/back-navigation
20 19 Navigation Support deep linking with protocol activation Respond to URI activation and toast taps OnActivated handler with proper page routing Ignoring activation arguments protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { ... } } Empty OnActivated ignoring URI parameters Medium https://learn.microsoft.com/en-us/windows/uwp/launch-resume/handle-uri-activation
21 20 Navigation Use ConnectedAnimations for continuity Smooth transitions between pages ConnectedAnimationService for shared element transitions Abrupt page transitions with no visual continuity ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("image", sourceImage); No transition animation between list and detail Low https://learn.microsoft.com/en-us/windows/uwp/design/motion/connected-animation
22 21 Data Binding Implement INotifyPropertyChanged Enable UI updates on property changes INotifyPropertyChanged on all ViewModels Auto-properties without notification public string Title { get => _title; set { _title = value; OnPropertyChanged(); } } public string Title { get; set; } expecting UI updates High https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
23 22 Data Binding Use ObservableCollection for lists Collection change notifications for ItemsSources ObservableCollection<T> for bound lists List<T> for data-bound collections ObservableCollection<Item> Items { get; } = new(); List<Item> Items { get; set; } = new(); High https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
24 23 Data Binding Use function bindings with x:Bind Call static methods directly in markup x:Bind to static converter methods IValueConverter for trivial transforms <TextBlock Visibility="{x:Bind local:Converters.BoolToVisibility(IsActive), Mode=OneWay}"/> Full IValueConverter class for bool to Visibility Medium https://learn.microsoft.com/en-us/windows/uwp/data-binding/function-bindings
25 24 Data Binding Specify Mode on x:Bind x:Bind defaults to OneTime not OneWay Mode=OneWay or TwoWay when live updates needed Omitting Mode and getting stale UI Text="{x:Bind Title, Mode=OneWay}" Text="{x:Bind Title}" expecting live updates High https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
26 25 Data Binding Use CollectionViewSource for grouping Group and sort collections declaratively CollectionViewSource for grouped ListView and GridView Manual grouping logic in code-behind <CollectionViewSource x:Key="GroupedItems" IsSourceGrouped="True" Source="{x:Bind GroupedData}"/> Manual loop building grouped StackPanels Medium https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
27 26 Performance Use ListView and GridView virtualization Only creates containers for visible items Default virtualization in ListView and GridView Setting ItemsPanel to non-virtualizing panel <ListView ItemsSource="{x:Bind Items}"/> (virtualizes by default) <ListView><ListView.ItemsPanel><ItemsPanelTemplate><StackPanel/></ItemsPanelTemplate></ListView.ItemsPanel></ListView> High https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/optimize-gridview-and-listview
28 27 Performance Use ISupportIncrementalLoading Load data on demand as user scrolls ISupportIncrementalLoading for large datasets Loading entire collection upfront class IncrementalSource : ObservableCollection<Item>, ISupportIncrementalLoading await LoadAll() loading 50K items at startup Medium https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth
29 28 Performance Reduce XAML visual tree depth Simpler trees layout and render faster Flat templates with minimal nesting Deeply nested panels in DataTemplates <StackPanel><TextBlock/><TextBlock/></StackPanel> in item template <Grid><Border><StackPanel><Grid>... 8 levels in item template Medium https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/optimize-xaml-loading
30 29 Performance Use compiled bindings in DataTemplates x:Bind in templates requires x:DataType x:DataType on DataTemplate for compiled bindings {Binding} in item templates for large lists <DataTemplate x:DataType="local:Item"><TextBlock Text="{x:Bind Name}"/></DataTemplate> <DataTemplate><TextBlock Text="{Binding Name}"/></DataTemplate> High https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
31 30 Performance Profile with Visual Studio diagnostics Measure before optimizing Application Timeline and Memory Usage tools Guessing at performance problems VS Diagnostic Tools > Application Timeline Optimizing without profiling data Medium https://learn.microsoft.com/en-us/visualstudio/profiling/application-timeline
32 31 Threading Use async/await for all IO Keep UI thread responsive async/await for file network and database operations Synchronous IO blocking the UI thread var file = await StorageFile.GetFileFromPathAsync(path); StorageFile.GetFileFromPathAsync(path).AsTask().Result; High https://learn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps
33 32 Threading Use CoreDispatcher for UI thread access Post work back to the UI thread from background Dispatcher.RunAsync from background threads Touching UI elements from background threads await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Status = "Done"); textBlock.Text = "Done" from Task.Run High https://learn.microsoft.com/en-us/uwp/api/windows.ui.core.coredispatcher
34 33 Threading Offload CPU work with Task.Run Keep compute-heavy work off UI thread Task.Run for CPU-bound operations Heavy computation blocking UI var result = await Task.Run(() => ProcessData(items)); var result = ProcessData(items); freezing UI High https://learn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-universal-windows-platform-apps
35 34 Threading Use IProgress for status updates Report progress from background operations IProgress<T> for progress reporting to UI Polling shared variables for progress var progress = new Progress<int>(p => ProgressBar.Value = p); await Task.Run(() => Process(progress)); while (!done) { await Task.Delay(100); check shared field; } Medium https://learn.microsoft.com/en-us/dotnet/api/system.progress-1
36 35 Adaptive Use AdaptiveTrigger for responsive layouts MinWindowWidth and MinWindowHeight triggers fire at standard breakpoints (640 small / 1008 medium) AdaptiveTrigger inside VisualState.StateTriggers with the 640 and 1008 breakpoints Fixed layouts for a single screen size <VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="640"/></VisualState.StateTriggers> Single-column layout at all widths High https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml
37 36 Adaptive Design for multiple device families Phone tablet desktop Xbox and HoloLens DeviceFamily-specific views and resources Desktop-only design ignoring other form factors DeviceFamily-Mobile/MainPage.xaml for phone-specific layout Fixed 1920x1080 layout Medium https://learn.microsoft.com/en-us/windows/uwp/design/layout/screen-sizes-and-breakpoints-for-responsive-design
38 37 Adaptive Use RelativePanel for adaptive positioning Controls position relative to each other RelativePanel for layouts that reflow at breakpoints Absolute positioning or fixed margins <Button RelativePanel.Below="title" RelativePanel.AlignLeftWithPanel="True"/> <Button Margin="0,60,0,0"/> calculated from title height Medium https://learn.microsoft.com/en-us/windows/uwp/design/layout/layouts-with-xaml#relativepanel
39 38 Adaptive Support multi-window with secondary views Open detached views with CoreApplication.CreateNewView and ApplicationViewSwitcher CreateNewView and TryShowAsStandaloneAsync for multi-document scenarios Single-window assumptions when scenarios benefit from secondary views var view = CoreApplication.CreateNewView(); await view.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { /* set content */ }); Modal overlay used for content that should be a separate window Medium https://learn.microsoft.com/en-us/windows/uwp/design/layout/show-multiple-views
40 39 Accessibility Set AutomationProperties Enable Narrator and screen reader support AutomationProperties.Name on all interactive controls Controls without accessible names <AppBarButton AutomationProperties.Name="Save document" Icon="Save"/> <AppBarButton Icon="Save"/> without name High https://learn.microsoft.com/en-us/windows/uwp/design/accessibility/basic-accessibility-information
41 40 Accessibility Support keyboard and gamepad All functions reachable without touch Tab navigation XYFocus and access keys Touch-only interactions <Button AccessKey="S" XYFocusDown="{x:Bind OtherButton}"/> No keyboard or gamepad support High https://learn.microsoft.com/en-us/windows/uwp/design/input/keyboard-interactions
42 41 Accessibility Support contrast themes Respect system contrast themes (renamed from high contrast in Windows 11) ThemeResource brushes that adapt to contrast themes Hardcoded colors that vanish under contrast themes Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}" Foreground="#444444" High https://learn.microsoft.com/en-us/windows/uwp/design/accessibility/high-contrast-themes
43 42 Accessibility Test with Narrator and Accessibility Insights Validate screen reader and automation compliance Regular Narrator walkthrough and Accessibility Insights scan Shipping without accessibility testing Accessibility Insights FastPass on every page No accessibility testing before release Medium https://accessibilityinsights.io/
44 43 Architecture Use MVVM pattern Separate View ViewModel and Model ViewModel with INotifyPropertyChanged and ICommand Business logic in code-behind ViewModel bound via DataContext with commands MainPage.xaml.cs with database calls and UI logic Medium https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm
45 44 Architecture Use Template Studio for scaffolding Proven project templates with navigation and services Windows Template Studio for new UWP projects Blank project with manual boilerplate Template Studio with MVVM Toolkit and navigation service Blank App template building everything from scratch Low https://github.com/microsoft/TemplateStudio
46 45 Architecture Use dependency injection Register services for testability Microsoft.Extensions.DI for service resolution Static singletons and manual construction services.AddTransient<MainViewModel>(); services.AddSingleton<IDataService, DataService>(); DataService.Instance or new DataService() everywhere Medium https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
47 46 Architecture Keep platform APIs behind abstractions Isolate WinRT APIs from business logic Interfaces wrapping StorageFile FilePicker etc Direct WinRT calls in ViewModels IFileService wrapping FileOpenPicker and StorageFile FileOpenPicker usage directly in ViewModel Medium https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm
48 47 Lifecycle Handle suspend and resume UWP apps are suspended when not in foreground Save state in OnSuspending and restore in OnLaunched Ignoring app lifecycle losing user state Application.Current.Suspending += (s, e) => SaveState(); No suspend handler losing in-progress form data High https://learn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle
49 48 Lifecycle Use ExtendedExecutionSession for background work Request extended time for unfinished operations ExtendedExecutionSession for saving or uploads Assuming background work completes after suspend var session = new ExtendedExecutionSession { Reason = ExtendedExecutionReason.SavingData }; Long upload with no extended execution that gets killed on suspend Medium https://learn.microsoft.com/en-us/windows/uwp/launch-resume/run-minimized-with-extended-execution
50 49 Lifecycle Handle prelaunch Apps must opt in to prelaunch via CoreApplication.EnablePrelaunch(true) starting in Windows 10 1607; check LaunchActivatedEventArgs.PrelaunchActivated to skip user-visible work Opt in with EnablePrelaunch and skip heavy init when PrelaunchActivated is true Performing full initialization or navigating during prelaunch CoreApplication.EnablePrelaunch(true); if (e.PrelaunchActivated) return; // skip heavy init Loading all data and navigating on prelaunch Medium https://learn.microsoft.com/en-us/windows/uwp/launch-resume/handle-app-prelaunch
51 50 Testing Unit test ViewModels Test logic without UI framework dependencies xUnit or MSTest on ViewModel methods Testing only through the running app [Fact] public async Task Load_PopulatesItems() { await vm.LoadAsync(); Assert.NotEmpty(vm.Items); } Manual testing by tapping through the app Medium https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
52 51 Testing Use WinAppDriver with Appium for UI tests Automated UI testing for UWP (Coded UI Test was deprecated in Visual Studio 2019); WinAppDriver v1 is in low-maintenance mode and Appium 2 is the modern direction WinAppDriver with Appium for end-to-end tests Manual regression testing session.FindElementByAccessibilityId("SaveButton").Click(); Manual click-through testing before each release Medium https://github.com/microsoft/WinAppDriver
53 52 Testing Test on multiple device families Behavior varies across phone desktop and Xbox Test on device emulators and real hardware Desktop-only testing Test on Mobile emulator and Xbox dev mode Only running on local desktop Medium https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal
54 53 Architecture Prefer WinUI 3 for new projects UWP is in maintenance mode and Microsoft recommends WinUI 3 and Windows App SDK for new development WinUI 3 with Windows App SDK for new desktop apps Starting new projects on UWP when WinUI 3 is available New project with Microsoft.WindowsAppSDK and WinUI 3 New UWP project for a desktop-only app in 2024+ Medium https://learn.microsoft.com/en-us/windows/apps/get-started/
55 54 Architecture Plan migration to Windows App SDK Microsoft provides migration guides from UWP to WinUI 3 Incremental migration using XAML Islands or full port to WinUI 3 Ignoring migration path and accumulating UWP technical debt Follow UWP to WinUI 3 migration guide for existing apps Continuing major feature development on UWP without migration plan Medium https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/migrate-to-windows-app-sdk/overall-migration-strategy
56 55 Lifecycle Use a deferral when saving async state on suspend Suspending grants only ~5 seconds before the OS may terminate; await work needs SuspendingOperation.GetDeferral and Complete or save returns before it finishes GetDeferral around async save calls and Complete in finally Async work that returns the suspending handler before completion async void OnSuspending(object s, SuspendingEventArgs e) { var d = e.SuspendingOperation.GetDeferral(); try { await SaveAsync(); } finally { d.Complete(); } } async void OnSuspending(object s, SuspendingEventArgs e) { await SaveAsync(); } // handler returns before save completes Medium https://learn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle

View File

@ -0,0 +1,60 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,XAML,Use x:Bind for compiled bindings,Compile-time checked bindings with better performance,x:Bind for type-safe bindings,{Binding} when x:Bind works,"<TextBlock Text=""{x:Bind ViewModel.Title, Mode=OneWay}""/>","<TextBlock Text=""{Binding Title}""/>",High,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
2,XAML,Use x:Load for deferred loading,Only instantiate UI elements when needed,x:Load=False for hidden panels and dialogs,Loading all UI upfront,"<StackPanel x:Load=""{x:Bind ShowDetails, Mode=OneWay}"">","Always-loaded collapsed panels",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-load-attribute
3,XAML,Use x:Phase for incremental rendering,Load list items in phases for smooth scrolling,x:Phase on secondary content in DataTemplates,Loading all template content in phase 0,"<TextBlock x:Phase=""1"" Text=""{x:Bind Description}""/>","All content in single phase for complex templates",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
4,XAML,Use x:DefaultBindMode,Set default binding mode for a scope,x:DefaultBindMode=OneWay on containers with many bindings,Mode=OneWay on every individual x:Bind,"<StackPanel x:DefaultBindMode=""OneWay"">","Mode=OneWay repeated on 20 bindings",Low,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
5,Controls,Use NavigationView for app navigation,WinUI 3 NavigationView with Left Top and LeftCompact display modes plus footer items,NavigationView with PaneDisplayMode for main app shell,Custom hamburger menu implementation,"<NavigationView><NavigationView.MenuItems><NavigationViewItem Content=""Home""/></NavigationView.MenuItems></NavigationView>","Custom SplitView with manual hamburger button",High,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/navigationview
6,Controls,Use InfoBar for status messages,Non-intrusive informational messages,InfoBar for success warning and error messages,Custom styled StackPanel for status,"<InfoBar IsOpen=""True"" Severity=""Warning"" Title=""Update available""/>","<StackPanel Background=""Yellow""><TextBlock Text=""Warning""/></StackPanel>",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/infobar
7,Controls,Use TeachingTip for onboarding,Contextual tips attached to UI elements,TeachingTip for feature discovery,Custom popup for teaching,"<TeachingTip Target=""{x:Bind SearchBox}"" Title=""Try searching""/>","Custom Popup positioned near target element",Low,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/dialogs-and-flyouts/teaching-tip
8,Controls,Use ContentDialog for modal interactions,Standard modal dialog pattern,ContentDialog for confirmations and input,Custom overlay Panel as dialog,"<ContentDialog Title=""Delete?"" PrimaryButtonText=""Delete"" CloseButtonText=""Cancel""/>","Grid overlay with manual focus trapping",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/dialogs-and-flyouts/dialogs
9,Controls,Use BreadcrumbBar for hierarchy,Show navigation path in hierarchical apps,BreadcrumbBar for folder or category navigation,Manual TextBlock breadcrumb chain,"<BreadcrumbBar ItemsSource=""{x:Bind Breadcrumbs}""/>","<StackPanel Orientation=""Horizontal""><TextBlock Text=""Home > Settings > Display""/></StackPanel>",Low,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/breadcrumbbar
10,Styling,Use Lightweight Styling,Override control sub-properties via resources,Lightweight styling resource keys to tweak controls,Full ControlTemplate override for small changes,"<Button><Button.Resources><ResourceDictionary><ResourceDictionary.ThemeDictionaries><ResourceDictionary x:Key=""Light""><SolidColorBrush x:Key=""ButtonBackground"" Color=""MediumSlateBlue""/></ResourceDictionary></ResourceDictionary.ThemeDictionaries></ResourceDictionary></Button.Resources></Button>","Full ControlTemplate copy to change background color",High,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-styles#lightweight-styling
11,Styling,Use WinUI theme resources,Consistent Fluent Design colors and brushes,WinUI theme resource keys for colors,Hardcoded hex color values,"Background=""{ThemeResource CardBackgroundFillColorDefaultBrush}""","Background=""#FF2D2D30""",High,https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/color
12,Styling,Support light and dark themes,Respect user and system theme preference,ThemeResource for theme-adaptive values,Hardcoded colors that break in dark mode,"Foreground=""{ThemeResource TextFillColorPrimaryBrush}""","Foreground=""Black""",High,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-theme-resources
13,Styling,Use Fluent Design system,Acrylic Mica Reveal and rounded corners,Built-in Fluent materials and effects,Custom blur and shadow implementations,"<Grid Background=""{ThemeResource AcrylicInAppFillColorDefaultBrush}""/>","Custom CompositionBrush recreating acrylic",Medium,https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/materials
14,Navigation,Use Frame for page navigation,Microsoft.UI.Xaml.Controls.Frame for WinUI 3 page navigation,Frame.Navigate with page types and parameters,Swapping UserControls in a ContentControl,"rootFrame.Navigate(typeof(SettingsPage), parameter);","contentArea.Content = new SettingsControl();",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigate-between-two-pages
15,Navigation,Pass typed navigation parameters,Type-safe data passing between pages,Typed parameter in OnNavigatedTo,Dictionary or string parsing for parameters,"protected override void OnNavigatedTo(NavigationEventArgs e) { var item = (Item)e.Parameter; }","var id = int.Parse(e.Parameter.ToString());",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigate-between-two-pages
16,Navigation,Handle back navigation,WinUI 3 uses NavigationView.BackRequested instead of UWP SystemNavigationManager,Register NavigationView.BackRequested handler and manage back stack,"Ignoring back navigation","navigationView.BackRequested += OnBackRequested;","No back button support",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigation-history-and-backwards-navigation
17,Navigation,Use deep linking,Handle protocol activation so URIs route to the right page,Register protocol then check ExtendedActivationKind.Protocol on activation,Single entry point ignoring activation context,"AppInstance.GetCurrent().GetActivatedEventArgs() with ExtendedActivationKind.Protocol","Ignoring activation arguments",Medium,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-rich-activation
18,Data Binding,Use ObservableCollection for lists,Notifies UI of collection changes,ObservableCollection<T> for bound ItemsSources,List<T> for bound collections,"ObservableCollection<Item> Items { get; } = new();","List<Item> Items { get; set; } = new();",High,https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
19,Data Binding,Use INotifyPropertyChanged,Enable property change notification for UI updates,INotifyPropertyChanged on ViewModels,Properties without notification,"public string Name { get => _name; set => SetProperty(ref _name, value); }","public string Name { get; set; } without notification",High,https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
20,Data Binding,Use function binding with x:Bind,Call methods directly in bindings,x:Bind with method references for transforms,IValueConverter for simple logic,"<TextBlock Visibility=""{x:Bind local:Converters.BoolToVisibility(IsActive), Mode=OneWay}""/>","IValueConverter class for bool to visibility",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/function-bindings
21,Data Binding,Specify Mode explicitly on x:Bind,x:Bind defaults to OneTime not OneWay,Mode=OneWay or Mode=TwoWay when updates needed,Forgetting Mode and getting stale UI,"Text=""{x:Bind Title, Mode=OneWay}""","Text=""{x:Bind Title}"" expecting live updates",High,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
22,Performance,Use ItemsRepeater for custom lists,Virtualizing layout with full control,ItemsRepeater for custom list layouts,ListView for highly customized item layouts,"<ItemsRepeater ItemsSource=""{x:Bind Items}""><ItemsRepeater.Layout><StackLayout/></ItemsRepeater.Layout></ItemsRepeater>","ListView with heavily modified template and removed chrome",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/items-repeater
23,Performance,Use incremental loading,Load data on demand as user scrolls,ISupportIncrementalLoading for large data sets,Loading entire dataset upfront,"class IncrementalItemSource : ObservableCollection<Item>, ISupportIncrementalLoading","await LoadAllItems() on page load for 10K items",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
24,Performance,Reduce visual tree complexity,Simpler trees render faster,Minimal nesting in DataTemplates,Deeply nested panels in item templates,"<StackPanel><TextBlock/><TextBlock/></StackPanel>","<Grid><Border><StackPanel><Grid>... 8 levels deep",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/performance/optimize-xaml-loading
25,Performance,Use compiled bindings over reflection,x:Bind generates code at compile time,x:Bind for hot paths and list items,{Binding} in DataTemplates and frequently updated UI,"<DataTemplate x:DataType=""local:Item""><TextBlock Text=""{x:Bind Name}""/></DataTemplate>","<DataTemplate><TextBlock Text=""{Binding Name}""/></DataTemplate>",High,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
26,Threading,Use DispatcherQueue not Dispatcher,WinUI 3 uses Microsoft.UI.Dispatching.DispatcherQueue instead of UWP CoreDispatcher,DispatcherQueue.TryEnqueue for UI thread access,Dispatcher.RunAsync (UWP pattern),"_dispatcherQueue.TryEnqueue(() => Status = ""Done"");","Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ...);",High,https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.dispatching.dispatcherqueue
27,Threading,Use async/await for IO operations,Keep UI responsive during file and network access,async/await for IO so the UI thread keeps rendering,Synchronous IO on UI thread,"var data = await httpClient.GetStringAsync(url);","var data = httpClient.GetStringAsync(url).Result;",High,https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
28,Threading,Use Task.Run for CPU-bound work,Offload compute to thread pool,Task.Run for heavy computation,Long-running CPU work on UI thread,"var result = await Task.Run(() => ProcessLargeDataSet());","var result = ProcessLargeDataSet(); blocking UI",High,https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming
29,Packaging,Use WinAppSDK correctly,Windows App SDK provides the runtime,WinAppSDK NuGet package and WindowsAppSDK bootstrapper,Mixing UWP and WinUI 3 APIs,"<PackageReference Include=""Microsoft.WindowsAppSDK""/>","Using Windows.UI.Xaml instead of Microsoft.UI.Xaml",High,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/
30,Packaging,Use unpackaged or packaged appropriately,Choose deployment model for your scenario,Packaged (MSIX) for Store distribution,Unpackaged without considering API limitations,"<WindowsPackageType>None</WindowsPackageType> for unpackaged","Assuming all APIs work in unpackaged mode",Medium,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/deploy-packaged-apps
31,Packaging,Use single-project MSIX,Simplified packaging for single app,Single-project MSIX packaging,Separate WAP project when not needed,"<EnableMsixTooling>true</EnableMsixTooling> in csproj","Separate Windows Application Packaging project for simple apps",Low,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/single-project-msix
32,Accessibility,Set AutomationProperties,Enable Narrator and screen reader support,AutomationProperties.Name on all interactive controls,Controls without accessible names,"<Button AutomationProperties.Name=""Save document""><FontIcon Glyph=""&#xE74E;""/></Button>","<Button><FontIcon Glyph=""&#xE74E;""/></Button> without name",High,https://learn.microsoft.com/en-us/windows/apps/design/accessibility/basic-accessibility-information
33,Accessibility,Support keyboard navigation,Full keyboard accessibility,Tab navigation and access keys for all controls,Mouse-only interactions,"<Button AccessKey=""S"" Content=""Save""/>","Interactive elements unreachable by keyboard",High,https://learn.microsoft.com/en-us/windows/apps/develop/input/keyboard-interactions
34,Accessibility,Use proper heading levels,Screen readers use headings for navigation,AutomationProperties.HeadingLevel on section headers,All text at same heading level,"<TextBlock AutomationProperties.HeadingLevel=""Level1"" Text=""Settings""/>","<TextBlock Style=""{StaticResource TitleTextBlockStyle}""/> without heading level",Medium,https://learn.microsoft.com/en-us/windows/apps/design/accessibility/basic-accessibility-information
35,Accessibility,Support high contrast,Respect system high contrast settings,ThemeResource brushes that adapt to high contrast,Hardcoded colors ignoring high contrast,"Foreground=""{ThemeResource TextFillColorPrimaryBrush}""","Foreground=""#333333""",High,https://learn.microsoft.com/en-us/windows/apps/design/accessibility/high-contrast-themes
36,Accessibility,Test with Accessibility Insights,Validate accessibility compliance,Accessibility Insights for Windows scanning,Manual accessibility checking only,"Run Accessibility Insights FastPass on every page","Ship without accessibility testing",Medium,https://accessibilityinsights.io/
37,Architecture,Use MVVM with CommunityToolkit,Source generators reduce boilerplate,[ObservableProperty] and [RelayCommand] attributes,Manual INotifyPropertyChanged and ICommand,"[ObservableProperty] private string _title; [RelayCommand] private void Save() { }","Full INotifyPropertyChanged implementation per property",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
38,Architecture,Use dependency injection,Register services with Microsoft.Extensions.DI,IServiceProvider for ViewModel and service resolution,new ViewModel() and new Service() everywhere,"services.AddTransient<MainViewModel>(); services.AddSingleton<IDataService, DataService>();","new MainViewModel(new DataService()) in code-behind",Medium,https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/overview
39,Architecture,Use Template Studio patterns,Start with proven architectural templates,Template Studio for WinUI 3 project scaffolding,Blank project with manual setup for complex apps,"WinUI 3 Template Studio with MVVM and navigation","Blank App template for production app",Low,https://github.com/microsoft/TemplateStudio
40,Architecture,Separate platform from business logic,Keep business logic in .NET Standard or shared libraries,Business logic in separate class library,Business logic mixed with WinUI types,"Shared.Core project with no WinUI references","ViewModel importing Microsoft.UI.Xaml types",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
41,Architecture,Use WinUI 3 Window management,Proper window lifecycle management,AppWindow API for multi-window scenarios,Single Window assumption in complex apps,"var appWindow = this.AppWindow;","Relying solely on MainWindow for everything",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/manage-app-windows
42,Testing,Unit test ViewModels,Test logic independent of UI framework,xUnit or MSTest on ViewModel properties and commands,Testing through UI only,"[Fact] public async Task LoadItems_PopulatesCollection() { await vm.LoadCommand.ExecuteAsync(null); Assert.NotEmpty(vm.Items); }","Manual testing by running the app",Medium,https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
43,Testing,Use WinAppDriver for UI tests,Automated UI testing for WinUI 3,WinAppDriver or Appium for end-to-end tests,Manual regression testing,"var element = session.FindElementByAccessibilityId(""SaveButton""); element.Click();","Click-through manual testing",Medium,https://github.com/microsoft/WinAppDriver
44,Testing,Mock WinRT APIs in tests,Isolate tests from platform dependencies,Interface wrappers around WinRT APIs,Direct WinRT API calls in testable code,"IFileService wrapping StorageFile APIs","StorageFile.GetFileFromPathAsync directly in ViewModel",Medium,https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
45,Controls,Use NumberBox for numeric input,Built-in numeric entry with validation formatting and spin buttons,NumberBox with Minimum Maximum and SpinButtonPlacementMode,TextBox with manual numeric parsing and validation,"<NumberBox Value=""{x:Bind Quantity, Mode=TwoWay}"" Minimum=""0"" Maximum=""100"" SpinButtonPlacementMode=""Inline""/>","TextBox with regex validation for numbers",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/number-box
46,Controls,Use Expander for collapsible sections,Expandable content area with header for progressive disclosure,Expander for settings groups and optional content,Manual visibility toggling with buttons,"<Expander Header=""Advanced Settings""><StackPanel><ToggleSwitch Header=""Debug mode""/></StackPanel></Expander>","Button toggling StackPanel.Visibility for collapsible content",Low,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/expander
47,Controls,Use ProgressRing and ProgressBar for loading,Built-in loading indicators for determinate and indeterminate states,ProgressRing for indeterminate and ProgressBar for determinate progress,Custom spinning animation or text-based loading indicators,"<ProgressRing IsActive=""{x:Bind IsLoading, Mode=OneWay}""/>","<TextBlock Text=""Loading..."" Visibility=""{x:Bind IsLoading}""/>",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/progress-controls
48,Layout,Use VisualStateManager for responsive layouts,Adapt UI layout to window size using adaptive triggers,AdaptiveTrigger with MinWindowWidth for responsive breakpoints,Fixed layouts that break at different window sizes,"<VisualState><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth=""720""/></VisualState.StateTriggers><VisualState.Setters><Setter Target=""sidebar.Visibility"" Value=""Visible""/></VisualState.Setters></VisualState>","Fixed two-column layout at all window sizes",High,https://learn.microsoft.com/en-us/windows/apps/develop/ui/layouts-with-xaml
49,Lifecycle,Handle app activation and launch,WinUI 3 apps receive activation events for URI and notification launches,Check LaunchActivatedEventArgs in OnLaunched for activation context,Ignoring activation arguments losing deep link context,"protected override void OnLaunched(LaunchActivatedEventArgs args) { if (args.Arguments.Contains(""settings"")) NavigateToSettings(); }","Empty OnLaunched ignoring all activation parameters",Medium,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-rich-activation
50,Lifecycle,Use single instancing with AppInstance,Prevent multiple app windows competing for resources,AppInstance.FindOrRegisterForKey for single-instance enforcement,Multiple instances with conflicting state,"var instance = AppInstance.FindOrRegisterForKey(""main""); if (!instance.IsCurrent) { await instance.RedirectActivationToAsync(args); }","No instance management allowing duplicate windows",Medium,https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-instancing
51,Lifecycle,Save and restore app state,Persist UI state across app restarts for continuity (ApplicationData APIs require packaged apps; unpackaged apps must use file IO or registry),Save state to local settings on window close or navigation,Losing user context on every restart,"ApplicationData.Current.LocalSettings.Values[""lastPage""] = currentPage;","No state persistence losing navigation position on restart",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/data/store-and-retrieve-app-data
52,Styling,Choose Mica vs Acrylic by surface lifetime,Mica is for long-lived primary surfaces like main windows; Acrylic is for transient light-dismiss surfaces like flyouts and context menus,Mica on root window backgrounds and Acrylic on flyouts and overlays,Acrylic on the main window or Mica on transient flyouts,"<Window.SystemBackdrop><MicaBackdrop/></Window.SystemBackdrop> ... <FlyoutPresenter Background=""{ThemeResource AcrylicInAppFillColorDefaultBrush}""/>","Acrylic on every Window background causing battery and perf cost",Medium,https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/materials
53,Styling,Set SystemBackdrop on Window directly,WinUI 3 1.3+ exposes Window.SystemBackdrop with MicaBackdrop and DesktopAcrylicBackdrop classes replacing manual MicaController plumbing,Window.SystemBackdrop in XAML or code,Hand-rolled MicaController wiring when SystemBackdrop API is available,"<Window.SystemBackdrop><MicaBackdrop Kind=""Base""/></Window.SystemBackdrop>","var ctrl = new Microsoft.UI.Composition.SystemBackdrops.MicaController(); ctrl.AddSystemBackdropTarget(this.As<ICompositionSupportsSystemBackdrop>());",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/system-backdrops
54,Architecture,Open secondary windows with new Window,WinUI 3 supports multiple top-level windows; each Window owns an AppWindow accessible via Window.AppWindow for size and position control,new Window().Activate() for secondary windows tracking them in App state,Faking multi-window via main-window content swaps or ContentDialog,"var settings = new SettingsWindow(); settings.Activate();","MainWindow.Content = new SettingsView(); when a separate window is needed",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/ui/manage-app-windows
55,Architecture,Extend client area into the title bar,Use Window.ExtendsContentIntoTitleBar with SetTitleBar to host custom XAML in the chrome while preserving caption buttons,ExtendsContentIntoTitleBar=true plus SetTitleBar(element) for custom drag region,Hardcoded chrome height or custom caption buttons that break with theme and size changes,"this.ExtendsContentIntoTitleBar = true; this.SetTitleBar(AppTitleBar);","Padding=""0,32,0,0"" to reserve space without SetTitleBar leaves window non-draggable",Medium,https://learn.microsoft.com/en-us/windows/apps/develop/title-bar
56,Accessibility,Use KeyboardAccelerator for shortcuts,Map Ctrl/Alt/Shift combinations to commands using KeyboardAccelerator on UIElement,KeyboardAccelerator with Modifiers and Key on relevant controls,Manual KeyDown handlers swallowing shortcuts,"<Button Command=""{x:Bind SaveCommand}""><Button.KeyboardAccelerators><KeyboardAccelerator Modifiers=""Control"" Key=""S""/></Button.KeyboardAccelerators></Button>","Window.PreviewKeyDown=""OnKeyDown"" with switch over args.Key",High,https://learn.microsoft.com/en-us/windows/apps/develop/input/keyboard-accelerators
57,Styling,Organize resources with merged dictionaries,Share styles and brushes via App.xaml MergedDictionaries instead of duplicating per page,MergedDictionaries in App.xaml for shared styles brushes and colors,Duplicating SolidColorBrush definitions on every page,"<Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source=""Themes/Brushes.xaml""/></ResourceDictionary.MergedDictionaries></ResourceDictionary></Application.Resources>",SolidColorBrush Color hardcoded inline on every page,Medium,https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-resource-dictionary
58,Architecture,Use AsyncRelayCommand for async commands,AsyncRelayCommand exposes IsRunning and supports cancellation for IO bound work,[RelayCommand] on async Task method or AsyncRelayCommand for IO work,async void event handlers or fire-and-forget Task.Run from button click,"[RelayCommand] private async Task LoadAsync(CancellationToken ct) { Items = await _service.FetchAsync(ct); }","private async void Button_Click(object s, RoutedEventArgs e) { await LoadAsync(); }",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/asyncrelaycommand
59,Architecture,Use ILogger for structured logging,Microsoft.Extensions.Logging ILogger<T> with DI for structured leveled logs,ILogger<T> injected via constructor for diagnostic logging,Debug.WriteLine or Console.WriteLine for app diagnostics,"public MainViewModel(ILogger<MainViewModel> logger) { _logger = logger; } _logger.LogInformation(""Loaded {Count} items"", count);","Debug.WriteLine($""Loaded {count} items"");",Medium,https://learn.microsoft.com/en-us/dotnet/core/extensions/logging/overview
1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 XAML Use x:Bind for compiled bindings Compile-time checked bindings with better performance x:Bind for type-safe bindings {Binding} when x:Bind works <TextBlock Text="{x:Bind ViewModel.Title, Mode=OneWay}"/> <TextBlock Text="{Binding Title}"/> High https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
3 2 XAML Use x:Load for deferred loading Only instantiate UI elements when needed x:Load=False for hidden panels and dialogs Loading all UI upfront <StackPanel x:Load="{x:Bind ShowDetails, Mode=OneWay}"> Always-loaded collapsed panels Medium https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-load-attribute
4 3 XAML Use x:Phase for incremental rendering Load list items in phases for smooth scrolling x:Phase on secondary content in DataTemplates Loading all template content in phase 0 <TextBlock x:Phase="1" Text="{x:Bind Description}"/> All content in single phase for complex templates Medium https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
5 4 XAML Use x:DefaultBindMode Set default binding mode for a scope x:DefaultBindMode=OneWay on containers with many bindings Mode=OneWay on every individual x:Bind <StackPanel x:DefaultBindMode="OneWay"> Mode=OneWay repeated on 20 bindings Low https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
6 5 Controls Use NavigationView for app navigation WinUI 3 NavigationView with Left Top and LeftCompact display modes plus footer items NavigationView with PaneDisplayMode for main app shell Custom hamburger menu implementation <NavigationView><NavigationView.MenuItems><NavigationViewItem Content="Home"/></NavigationView.MenuItems></NavigationView> Custom SplitView with manual hamburger button High https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/navigationview
7 6 Controls Use InfoBar for status messages Non-intrusive informational messages InfoBar for success warning and error messages Custom styled StackPanel for status <InfoBar IsOpen="True" Severity="Warning" Title="Update available"/> <StackPanel Background="Yellow"><TextBlock Text="Warning"/></StackPanel> Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/infobar
8 7 Controls Use TeachingTip for onboarding Contextual tips attached to UI elements TeachingTip for feature discovery Custom popup for teaching <TeachingTip Target="{x:Bind SearchBox}" Title="Try searching"/> Custom Popup positioned near target element Low https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/dialogs-and-flyouts/teaching-tip
9 8 Controls Use ContentDialog for modal interactions Standard modal dialog pattern ContentDialog for confirmations and input Custom overlay Panel as dialog <ContentDialog Title="Delete?" PrimaryButtonText="Delete" CloseButtonText="Cancel"/> Grid overlay with manual focus trapping Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/dialogs-and-flyouts/dialogs
10 9 Controls Use BreadcrumbBar for hierarchy Show navigation path in hierarchical apps BreadcrumbBar for folder or category navigation Manual TextBlock breadcrumb chain <BreadcrumbBar ItemsSource="{x:Bind Breadcrumbs}"/> <StackPanel Orientation="Horizontal"><TextBlock Text="Home > Settings > Display"/></StackPanel> Low https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/breadcrumbbar
11 10 Styling Use Lightweight Styling Override control sub-properties via resources Lightweight styling resource keys to tweak controls Full ControlTemplate override for small changes <Button><Button.Resources><ResourceDictionary><ResourceDictionary.ThemeDictionaries><ResourceDictionary x:Key="Light"><SolidColorBrush x:Key="ButtonBackground" Color="MediumSlateBlue"/></ResourceDictionary></ResourceDictionary.ThemeDictionaries></ResourceDictionary></Button.Resources></Button> Full ControlTemplate copy to change background color High https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-styles#lightweight-styling
12 11 Styling Use WinUI theme resources Consistent Fluent Design colors and brushes WinUI theme resource keys for colors Hardcoded hex color values Background="{ThemeResource CardBackgroundFillColorDefaultBrush}" Background="#FF2D2D30" High https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/color
13 12 Styling Support light and dark themes Respect user and system theme preference ThemeResource for theme-adaptive values Hardcoded colors that break in dark mode Foreground="{ThemeResource TextFillColorPrimaryBrush}" Foreground="Black" High https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-theme-resources
14 13 Styling Use Fluent Design system Acrylic Mica Reveal and rounded corners Built-in Fluent materials and effects Custom blur and shadow implementations <Grid Background="{ThemeResource AcrylicInAppFillColorDefaultBrush}"/> Custom CompositionBrush recreating acrylic Medium https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/materials
15 14 Navigation Use Frame for page navigation Microsoft.UI.Xaml.Controls.Frame for WinUI 3 page navigation Frame.Navigate with page types and parameters Swapping UserControls in a ContentControl rootFrame.Navigate(typeof(SettingsPage), parameter); contentArea.Content = new SettingsControl(); Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigate-between-two-pages
16 15 Navigation Pass typed navigation parameters Type-safe data passing between pages Typed parameter in OnNavigatedTo Dictionary or string parsing for parameters protected override void OnNavigatedTo(NavigationEventArgs e) { var item = (Item)e.Parameter; } var id = int.Parse(e.Parameter.ToString()); Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigate-between-two-pages
17 16 Navigation Handle back navigation WinUI 3 uses NavigationView.BackRequested instead of UWP SystemNavigationManager Register NavigationView.BackRequested handler and manage back stack Ignoring back navigation navigationView.BackRequested += OnBackRequested; No back button support Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/navigation/navigation-history-and-backwards-navigation
18 17 Navigation Use deep linking Handle protocol activation so URIs route to the right page Register protocol then check ExtendedActivationKind.Protocol on activation Single entry point ignoring activation context AppInstance.GetCurrent().GetActivatedEventArgs() with ExtendedActivationKind.Protocol Ignoring activation arguments Medium https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-rich-activation
19 18 Data Binding Use ObservableCollection for lists Notifies UI of collection changes ObservableCollection<T> for bound ItemsSources List<T> for bound collections ObservableCollection<Item> Items { get; } = new(); List<Item> Items { get; set; } = new(); High https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
20 19 Data Binding Use INotifyPropertyChanged Enable property change notification for UI updates INotifyPropertyChanged on ViewModels Properties without notification public string Name { get => _name; set => SetProperty(ref _name, value); } public string Name { get; set; } without notification High https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
21 20 Data Binding Use function binding with x:Bind Call methods directly in bindings x:Bind with method references for transforms IValueConverter for simple logic <TextBlock Visibility="{x:Bind local:Converters.BoolToVisibility(IsActive), Mode=OneWay}"/> IValueConverter class for bool to visibility Medium https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/function-bindings
22 21 Data Binding Specify Mode explicitly on x:Bind x:Bind defaults to OneTime not OneWay Mode=OneWay or Mode=TwoWay when updates needed Forgetting Mode and getting stale UI Text="{x:Bind Title, Mode=OneWay}" Text="{x:Bind Title}" expecting live updates High https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
23 22 Performance Use ItemsRepeater for custom lists Virtualizing layout with full control ItemsRepeater for custom list layouts ListView for highly customized item layouts <ItemsRepeater ItemsSource="{x:Bind Items}"><ItemsRepeater.Layout><StackLayout/></ItemsRepeater.Layout></ItemsRepeater> ListView with heavily modified template and removed chrome Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/items-repeater
24 23 Performance Use incremental loading Load data on demand as user scrolls ISupportIncrementalLoading for large data sets Loading entire dataset upfront class IncrementalItemSource : ObservableCollection<Item>, ISupportIncrementalLoading await LoadAllItems() on page load for 10K items Medium https://learn.microsoft.com/en-us/windows/apps/develop/data-binding/data-binding-in-depth
25 24 Performance Reduce visual tree complexity Simpler trees render faster Minimal nesting in DataTemplates Deeply nested panels in item templates <StackPanel><TextBlock/><TextBlock/></StackPanel> <Grid><Border><StackPanel><Grid>... 8 levels deep Medium https://learn.microsoft.com/en-us/windows/apps/develop/performance/optimize-xaml-loading
26 25 Performance Use compiled bindings over reflection x:Bind generates code at compile time x:Bind for hot paths and list items {Binding} in DataTemplates and frequently updated UI <DataTemplate x:DataType="local:Item"><TextBlock Text="{x:Bind Name}"/></DataTemplate> <DataTemplate><TextBlock Text="{Binding Name}"/></DataTemplate> High https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension
27 26 Threading Use DispatcherQueue not Dispatcher WinUI 3 uses Microsoft.UI.Dispatching.DispatcherQueue instead of UWP CoreDispatcher DispatcherQueue.TryEnqueue for UI thread access Dispatcher.RunAsync (UWP pattern) _dispatcherQueue.TryEnqueue(() => Status = "Done"); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ...); High https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.dispatching.dispatcherqueue
28 27 Threading Use async/await for IO operations Keep UI responsive during file and network access async/await for IO so the UI thread keeps rendering Synchronous IO on UI thread var data = await httpClient.GetStringAsync(url); var data = httpClient.GetStringAsync(url).Result; High https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
29 28 Threading Use Task.Run for CPU-bound work Offload compute to thread pool Task.Run for heavy computation Long-running CPU work on UI thread var result = await Task.Run(() => ProcessLargeDataSet()); var result = ProcessLargeDataSet(); blocking UI High https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming
30 29 Packaging Use WinAppSDK correctly Windows App SDK provides the runtime WinAppSDK NuGet package and WindowsAppSDK bootstrapper Mixing UWP and WinUI 3 APIs <PackageReference Include="Microsoft.WindowsAppSDK"/> Using Windows.UI.Xaml instead of Microsoft.UI.Xaml High https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/
31 30 Packaging Use unpackaged or packaged appropriately Choose deployment model for your scenario Packaged (MSIX) for Store distribution Unpackaged without considering API limitations <WindowsPackageType>None</WindowsPackageType> for unpackaged Assuming all APIs work in unpackaged mode Medium https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/deploy-packaged-apps
32 31 Packaging Use single-project MSIX Simplified packaging for single app Single-project MSIX packaging Separate WAP project when not needed <EnableMsixTooling>true</EnableMsixTooling> in csproj Separate Windows Application Packaging project for simple apps Low https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/single-project-msix
33 32 Accessibility Set AutomationProperties Enable Narrator and screen reader support AutomationProperties.Name on all interactive controls Controls without accessible names <Button AutomationProperties.Name="Save document"><FontIcon Glyph="&#xE74E;"/></Button> <Button><FontIcon Glyph="&#xE74E;"/></Button> without name High https://learn.microsoft.com/en-us/windows/apps/design/accessibility/basic-accessibility-information
34 33 Accessibility Support keyboard navigation Full keyboard accessibility Tab navigation and access keys for all controls Mouse-only interactions <Button AccessKey="S" Content="Save"/> Interactive elements unreachable by keyboard High https://learn.microsoft.com/en-us/windows/apps/develop/input/keyboard-interactions
35 34 Accessibility Use proper heading levels Screen readers use headings for navigation AutomationProperties.HeadingLevel on section headers All text at same heading level <TextBlock AutomationProperties.HeadingLevel="Level1" Text="Settings"/> <TextBlock Style="{StaticResource TitleTextBlockStyle}"/> without heading level Medium https://learn.microsoft.com/en-us/windows/apps/design/accessibility/basic-accessibility-information
36 35 Accessibility Support high contrast Respect system high contrast settings ThemeResource brushes that adapt to high contrast Hardcoded colors ignoring high contrast Foreground="{ThemeResource TextFillColorPrimaryBrush}" Foreground="#333333" High https://learn.microsoft.com/en-us/windows/apps/design/accessibility/high-contrast-themes
37 36 Accessibility Test with Accessibility Insights Validate accessibility compliance Accessibility Insights for Windows scanning Manual accessibility checking only Run Accessibility Insights FastPass on every page Ship without accessibility testing Medium https://accessibilityinsights.io/
38 37 Architecture Use MVVM with CommunityToolkit Source generators reduce boilerplate [ObservableProperty] and [RelayCommand] attributes Manual INotifyPropertyChanged and ICommand [ObservableProperty] private string _title; [RelayCommand] private void Save() { } Full INotifyPropertyChanged implementation per property Medium https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
39 38 Architecture Use dependency injection Register services with Microsoft.Extensions.DI IServiceProvider for ViewModel and service resolution new ViewModel() and new Service() everywhere services.AddTransient<MainViewModel>(); services.AddSingleton<IDataService, DataService>(); new MainViewModel(new DataService()) in code-behind Medium https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/overview
40 39 Architecture Use Template Studio patterns Start with proven architectural templates Template Studio for WinUI 3 project scaffolding Blank project with manual setup for complex apps WinUI 3 Template Studio with MVVM and navigation Blank App template for production app Low https://github.com/microsoft/TemplateStudio
41 40 Architecture Separate platform from business logic Keep business logic in .NET Standard or shared libraries Business logic in separate class library Business logic mixed with WinUI types Shared.Core project with no WinUI references ViewModel importing Microsoft.UI.Xaml types Medium https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
42 41 Architecture Use WinUI 3 Window management Proper window lifecycle management AppWindow API for multi-window scenarios Single Window assumption in complex apps var appWindow = this.AppWindow; Relying solely on MainWindow for everything Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/manage-app-windows
43 42 Testing Unit test ViewModels Test logic independent of UI framework xUnit or MSTest on ViewModel properties and commands Testing through UI only [Fact] public async Task LoadItems_PopulatesCollection() { await vm.LoadCommand.ExecuteAsync(null); Assert.NotEmpty(vm.Items); } Manual testing by running the app Medium https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
44 43 Testing Use WinAppDriver for UI tests Automated UI testing for WinUI 3 WinAppDriver or Appium for end-to-end tests Manual regression testing var element = session.FindElementByAccessibilityId("SaveButton"); element.Click(); Click-through manual testing Medium https://github.com/microsoft/WinAppDriver
45 44 Testing Mock WinRT APIs in tests Isolate tests from platform dependencies Interface wrappers around WinRT APIs Direct WinRT API calls in testable code IFileService wrapping StorageFile APIs StorageFile.GetFileFromPathAsync directly in ViewModel Medium https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
46 45 Controls Use NumberBox for numeric input Built-in numeric entry with validation formatting and spin buttons NumberBox with Minimum Maximum and SpinButtonPlacementMode TextBox with manual numeric parsing and validation <NumberBox Value="{x:Bind Quantity, Mode=TwoWay}" Minimum="0" Maximum="100" SpinButtonPlacementMode="Inline"/> TextBox with regex validation for numbers Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/number-box
47 46 Controls Use Expander for collapsible sections Expandable content area with header for progressive disclosure Expander for settings groups and optional content Manual visibility toggling with buttons <Expander Header="Advanced Settings"><StackPanel><ToggleSwitch Header="Debug mode"/></StackPanel></Expander> Button toggling StackPanel.Visibility for collapsible content Low https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/expander
48 47 Controls Use ProgressRing and ProgressBar for loading Built-in loading indicators for determinate and indeterminate states ProgressRing for indeterminate and ProgressBar for determinate progress Custom spinning animation or text-based loading indicators <ProgressRing IsActive="{x:Bind IsLoading, Mode=OneWay}"/> <TextBlock Text="Loading..." Visibility="{x:Bind IsLoading}"/> Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/progress-controls
49 48 Layout Use VisualStateManager for responsive layouts Adapt UI layout to window size using adaptive triggers AdaptiveTrigger with MinWindowWidth for responsive breakpoints Fixed layouts that break at different window sizes <VisualState><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="720"/></VisualState.StateTriggers><VisualState.Setters><Setter Target="sidebar.Visibility" Value="Visible"/></VisualState.Setters></VisualState> Fixed two-column layout at all window sizes High https://learn.microsoft.com/en-us/windows/apps/develop/ui/layouts-with-xaml
50 49 Lifecycle Handle app activation and launch WinUI 3 apps receive activation events for URI and notification launches Check LaunchActivatedEventArgs in OnLaunched for activation context Ignoring activation arguments losing deep link context protected override void OnLaunched(LaunchActivatedEventArgs args) { if (args.Arguments.Contains("settings")) NavigateToSettings(); } Empty OnLaunched ignoring all activation parameters Medium https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-rich-activation
51 50 Lifecycle Use single instancing with AppInstance Prevent multiple app windows competing for resources AppInstance.FindOrRegisterForKey for single-instance enforcement Multiple instances with conflicting state var instance = AppInstance.FindOrRegisterForKey("main"); if (!instance.IsCurrent) { await instance.RedirectActivationToAsync(args); } No instance management allowing duplicate windows Medium https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-instancing
52 51 Lifecycle Save and restore app state Persist UI state across app restarts for continuity (ApplicationData APIs require packaged apps; unpackaged apps must use file IO or registry) Save state to local settings on window close or navigation Losing user context on every restart ApplicationData.Current.LocalSettings.Values["lastPage"] = currentPage; No state persistence losing navigation position on restart Medium https://learn.microsoft.com/en-us/windows/apps/develop/data/store-and-retrieve-app-data
53 52 Styling Choose Mica vs Acrylic by surface lifetime Mica is for long-lived primary surfaces like main windows; Acrylic is for transient light-dismiss surfaces like flyouts and context menus Mica on root window backgrounds and Acrylic on flyouts and overlays Acrylic on the main window or Mica on transient flyouts <Window.SystemBackdrop><MicaBackdrop/></Window.SystemBackdrop> ... <FlyoutPresenter Background="{ThemeResource AcrylicInAppFillColorDefaultBrush}"/> Acrylic on every Window background causing battery and perf cost Medium https://learn.microsoft.com/en-us/windows/apps/design/signature-experiences/materials
54 53 Styling Set SystemBackdrop on Window directly WinUI 3 1.3+ exposes Window.SystemBackdrop with MicaBackdrop and DesktopAcrylicBackdrop classes replacing manual MicaController plumbing Window.SystemBackdrop in XAML or code Hand-rolled MicaController wiring when SystemBackdrop API is available <Window.SystemBackdrop><MicaBackdrop Kind="Base"/></Window.SystemBackdrop> var ctrl = new Microsoft.UI.Composition.SystemBackdrops.MicaController(); ctrl.AddSystemBackdropTarget(this.As<ICompositionSupportsSystemBackdrop>()); Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/system-backdrops
55 54 Architecture Open secondary windows with new Window WinUI 3 supports multiple top-level windows; each Window owns an AppWindow accessible via Window.AppWindow for size and position control new Window().Activate() for secondary windows tracking them in App state Faking multi-window via main-window content swaps or ContentDialog var settings = new SettingsWindow(); settings.Activate(); MainWindow.Content = new SettingsView(); when a separate window is needed Medium https://learn.microsoft.com/en-us/windows/apps/develop/ui/manage-app-windows
56 55 Architecture Extend client area into the title bar Use Window.ExtendsContentIntoTitleBar with SetTitleBar to host custom XAML in the chrome while preserving caption buttons ExtendsContentIntoTitleBar=true plus SetTitleBar(element) for custom drag region Hardcoded chrome height or custom caption buttons that break with theme and size changes this.ExtendsContentIntoTitleBar = true; this.SetTitleBar(AppTitleBar); Padding="0,32,0,0" to reserve space without SetTitleBar leaves window non-draggable Medium https://learn.microsoft.com/en-us/windows/apps/develop/title-bar
57 56 Accessibility Use KeyboardAccelerator for shortcuts Map Ctrl/Alt/Shift combinations to commands using KeyboardAccelerator on UIElement KeyboardAccelerator with Modifiers and Key on relevant controls Manual KeyDown handlers swallowing shortcuts <Button Command="{x:Bind SaveCommand}"><Button.KeyboardAccelerators><KeyboardAccelerator Modifiers="Control" Key="S"/></Button.KeyboardAccelerators></Button> Window.PreviewKeyDown="OnKeyDown" with switch over args.Key High https://learn.microsoft.com/en-us/windows/apps/develop/input/keyboard-accelerators
58 57 Styling Organize resources with merged dictionaries Share styles and brushes via App.xaml MergedDictionaries instead of duplicating per page MergedDictionaries in App.xaml for shared styles brushes and colors Duplicating SolidColorBrush definitions on every page <Application.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="Themes/Brushes.xaml"/></ResourceDictionary.MergedDictionaries></ResourceDictionary></Application.Resources> SolidColorBrush Color hardcoded inline on every page Medium https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/xaml-resource-dictionary
59 58 Architecture Use AsyncRelayCommand for async commands AsyncRelayCommand exposes IsRunning and supports cancellation for IO bound work [RelayCommand] on async Task method or AsyncRelayCommand for IO work async void event handlers or fire-and-forget Task.Run from button click [RelayCommand] private async Task LoadAsync(CancellationToken ct) { Items = await _service.FetchAsync(ct); } private async void Button_Click(object s, RoutedEventArgs e) { await LoadAsync(); } Medium https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/asyncrelaycommand
60 59 Architecture Use ILogger for structured logging Microsoft.Extensions.Logging ILogger<T> with DI for structured leveled logs ILogger<T> injected via constructor for diagnostic logging Debug.WriteLine or Console.WriteLine for app diagnostics public MainViewModel(ILogger<MainViewModel> logger) { _logger = logger; } _logger.LogInformation("Loaded {Count} items", count); Debug.WriteLine($"Loaded {count} items"); Medium https://learn.microsoft.com/en-us/dotnet/core/extensions/logging/overview

View File

@ -0,0 +1,57 @@
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,XAML,Use XAML for declarative UI,Define layout and visuals in XAML not code-behind,XAML for structure and styling,Build UI trees in C# code-behind,"<Button Content=""Save"" Click=""OnSave""/>",var btn = new Button(); btn.Content = "Save";,Low,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/xaml/
2,XAML,Set x:Class on root element,Connects XAML to its code-behind partial class,x:Class on Window UserControl and Page,"Missing x:Class or mismatched namespace","<Window x:Class=""MyApp.MainWindow"">","<Window> without x:Class",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/xaml/
3,XAML,Use x:Name sparingly,Only name elements accessed from code-behind,x:Name when code-behind reference is needed,Naming every element,"<TextBox x:Name=""SearchBox""/>","x:Name on every control",Low,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/xaml/
4,XAML,Prefer attached properties for layout,Grid.Row Grid.Column DockPanel.Dock etc,Attached properties for panel positioning,Margin hacks for alignment,"<Button Grid.Row=""1"" Grid.Column=""2""/>","<Button Margin=""200,100,0,0""/>",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/attached-properties-overview
5,XAML,Use routed events for tree-wide handling,Events bubble up or tunnel down the element tree letting parents handle child events with one handler,Handler at parent using TypeName.EventName syntax with e.Handled=true when consumed,Wiring identical handlers on every child when one parent handler suffices,"<StackPanel Button.Click=""OnAnyButtonClick"">","Click=""OnClick"" repeated on every Button under a common parent",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/events/routed-events-overview
6,Data Binding,Implement INotifyPropertyChanged,Enable UI updates when properties change,INotifyPropertyChanged on ViewModels,Public properties without notification,"public string Name { get => _name; set { if (_name != value) { _name = value; OnPropertyChanged(); } } }","public string Name { get; set; } without notification",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-property-change-notification
7,Data Binding,Use ObservableCollection for lists,Notifies UI of add remove and reset,ObservableCollection<T> for bound collections,List<T> or Array for bound ItemsSources,"ObservableCollection<Item> Items { get; } = new();","List<Item> Items { get; set; } = new();",High,https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1
8,Data Binding,Set DataContext at the right level,Enables binding for the visual subtree,DataContext on Window or root container,DataContext on every child control,"<Window DataContext=""{Binding Source={StaticResource VM}}"">","Setting DataContext on each TextBlock individually",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/
9,Data Binding,Prefer Binding over code-behind assignments,Declarative binding keeps UI and logic separate,"{Binding Path=Name} in XAML","textBlock.Text = viewModel.Name in code-behind","<TextBlock Text=""{Binding Name}""/>","Loaded event handler that sets every property",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-binding-overview
10,Data Binding,Use UpdateSourceTrigger appropriately,Controls when source updates,PropertyChanged for instant feedback,Default LostFocus when search-as-you-type is needed,"Text=""{Binding Query, UpdateSourceTrigger=PropertyChanged}""","Text=""{Binding Query}"" when search-as-you-type needed",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-control-when-the-textbox-text-updates-the-source
11,Data Binding,Use IValueConverter for display transforms,Convert data for presentation without changing the model,IValueConverter for bool-to-visibility etc,Visibility properties on ViewModel,"<TextBlock Visibility=""{Binding IsActive, Converter={StaticResource BoolToVis}}""/>","public Visibility IsActiveVisibility => IsActive ? Visibility.Visible : Visibility.Collapsed;",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-convert-bound-data
12,Data Binding,Use INotifyDataErrorInfo for validation,Surface validation errors to the binding system instead of ad-hoc error UI,ObservableValidator with DataAnnotations attributes,Throwing in setters or maintaining separate error properties,"public partial class FormVm : ObservableValidator { [ObservableProperty][NotifyDataErrorInfo][Required] private string _email; }","if (string.IsNullOrEmpty(Email)) ErrorMessage = ""Required"";",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/observablevalidator
13,Layout,Use Grid for complex layouts,Rows and columns with proportional or fixed sizing,Grid with RowDefinitions and ColumnDefinitions,Canvas with absolute positions for forms,"<Grid><Grid.RowDefinitions><RowDefinition Height=""Auto""/><RowDefinition Height=""*""/></Grid.RowDefinitions></Grid>","<Canvas><TextBox Canvas.Left=""50"" Canvas.Top=""80""/></Canvas>",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/grid
14,Layout,Use StackPanel for linear content,Simple vertical or horizontal stacking,StackPanel for toolbars and simple lists,Grid with single column for linear content,"<StackPanel Orientation=""Horizontal""><Button/><Button/></StackPanel>","<Grid><Grid.RowDefinitions>..12 Auto rows..</Grid.RowDefinitions></Grid>",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/stackpanel
15,Layout,Use DockPanel for docked regions,Dock children to edges with last child filling,DockPanel for shell layouts (menu top sidebar left),Nested StackPanels to simulate docking,"<DockPanel><Menu DockPanel.Dock=""Top""/><TreeView DockPanel.Dock=""Left""/><Frame/></DockPanel>","Nested StackPanels with fixed widths for shell",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/dockpanel
16,Layout,Avoid hardcoded sizes,Use Auto Star and MinWidth/MaxWidth,Proportional sizing with * and Auto,Fixed pixel widths on resizable content,"<ColumnDefinition Width=""2*""/>","<ColumnDefinition Width=""350""/> on main content",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/grid
17,Layout,Use ScrollViewer for overflow,Wrap content that may exceed available space,ScrollViewer around long forms or lists,Clipping content without scroll,"<ScrollViewer><StackPanel>...long content...</StackPanel></ScrollViewer>","<StackPanel> that clips off-screen items",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/scrollviewer
18,Styling,Use Resource Dictionaries,Centralize colors brushes and styles,ResourceDictionary in App.xaml for theme values,Inline colors and font sizes on every element,"<SolidColorBrush x:Key=""PrimaryBrush"" Color=""#0078D4""/>","<Button Background=""#0078D4""/> repeated everywhere",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/systems/xaml-resources-overview
19,Styling,Use pack URIs for embedded resources,Reference embedded images fonts and resource dictionaries via the pack scheme,"pack://application:,,, syntax for cross-assembly assets",File-system paths for resources compiled into the assembly,"<Image Source=""pack://application:,,,/MyApp;component/Resources/icon.png""/>","<Image Source=""C:\Resources\icon.png""/>",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/pack-uris-in-wpf
20,Styling,Use implicit styles,Apply a Style to all instances of a TargetType,Style with TargetType and no x:Key for defaults,Manually styling every Button instance,"<Style TargetType=""Button""><Setter Property=""Padding"" Value=""12,6""/></Style>","Padding=""12,6"" on every Button",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/styles-templates-overview
21,Styling,Use explicit styles with x:Key and BasedOn,Named variant styles that inherit from a base via BasedOn,x:Key styles that BasedOn an implicit or named style,Duplicating setters across variants,"<Style x:Key=""PrimaryButton"" TargetType=""Button"" BasedOn=""{StaticResource {x:Type Button}}"">","Copy-pasting 10 Setters into a second Style",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/styles-templates-overview
22,Styling,Prefer StaticResource over DynamicResource,StaticResource is resolved once and faster,StaticResource for values that do not change at runtime,DynamicResource for static theme values,"Background=""{StaticResource PrimaryBrush}""","Background=""{DynamicResource PrimaryBrush}"" when theme never changes",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/systems/xaml-resources-overview
23,Styling,Use ControlTemplate for full control,Override default rendering of a control,ControlTemplate when built-in styles are insufficient,Nesting extra panels to hide the default template,"<ControlTemplate TargetType=""Button""><Border><ContentPresenter/></Border></ControlTemplate>","Wrapping Button in Border to fake a custom look",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-create-apply-template
24,Styling,Use DataTemplate for data presentation,Define how data objects render in ItemsControls,DataTemplate for ListBox ComboBox and ItemsControl items,ToString overrides for display,"<DataTemplate DataType=""{x:Type local:Person}""><TextBlock Text=""{Binding FullName}""/></DataTemplate>","Relying on ToString() in ListBox",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-templating-overview
25,Styling,Use Fluent theme on .NET 9+,ThemeMode applies the Windows 11 Fluent style; values are Light Dark System and None (default Aero2),ThemeMode on Application or Window,Legacy Aero2 styling for new Windows 11 apps,"<Application ThemeMode=""System"">","<Application> with default Aero2 look",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/whats-new/net90
26,Commands,Use ICommand for user actions,Decouple UI actions from logic,ICommand implementations (RelayCommand DelegateCommand),Click event handlers in code-behind,"<Button Command=""{Binding SaveCommand}""/>","<Button Click=""OnSaveClick""/> with logic in code-behind",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/commanding-overview
27,Commands,Use CanExecute for enable/disable,Automatically disable controls when action unavailable; call NotifyCanExecuteChanged when state changes,CanExecute returning false to disable buttons,IsEnabled binding to a separate bool,"new RelayCommand(Save, () => !IsBusy)","<Button IsEnabled=""{Binding IsNotBusy}""/>",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/commanding-overview
28,Commands,Use RelayCommand or DelegateCommand,Avoid implementing ICommand from scratch every time,RelayCommand (CommunityToolkit.Mvvm) or DelegateCommand (Prism),New ICommand class per command,"[RelayCommand] private void Save() { }","class SaveCommand : ICommand { ... } for each action",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/relaycommand
29,Commands,Use AsyncRelayCommand for async operations,Tracks IsRunning and disables the command while it executes preventing re-entry,AsyncRelayCommand or [RelayCommand] on async Task method,async void event handlers in code-behind,[RelayCommand] private async Task SaveAsync() { await _service.SaveAsync(); },"private async void OnSaveClick(object s, RoutedEventArgs e) { await _service.SaveAsync(); }",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/asyncrelaycommand
30,Commands,Use CommandParameter for context,Pass data from the UI element to the command handler,CommandParameter for item-specific actions,Relying on SelectedItem in every command,"<Button Command=""{Binding DeleteCommand}"" CommandParameter=""{Binding}""/>","Command handler accessing SelectedItem directly",Low,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/commanding-overview
31,Commands,Use InputBindings for keyboard shortcuts,Bind keyboard gestures to commands without manual key handling,KeyBinding inside Window.InputBindings,Custom key handling in PreviewKeyDown,"<Window.InputBindings><KeyBinding Key=""S"" Modifiers=""Ctrl"" Command=""{Binding SaveCommand}""/></Window.InputBindings>",PreviewKeyDown handler checking for Ctrl+S,Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/commanding-overview
32,Performance,Use VirtualizingStackPanel for large lists,Only creates UI elements for visible items. ListBox/ListView virtualize by default; TreeView requires opt-in,VirtualizingStackPanel.IsVirtualizing=True (set on TreeView; default for ListBox),Disabling virtualization on long lists,"<TreeView VirtualizingStackPanel.IsVirtualizing=""True"" VirtualizingStackPanel.VirtualizationMode=""Recycling""/>","<ListBox ScrollViewer.CanContentScroll=""False""/>",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/optimizing-performance-controls
33,Performance,Freeze Freezable objects,Frozen brushes and geometries skip change tracking,Freeze brushes and pens that do not change,Mutable brushes used as static resources,"var brush = new SolidColorBrush(Colors.Blue); brush.Freeze();","new SolidColorBrush() without Freeze in resources",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/freezable-objects-overview
34,Performance,Use DependencyProperty for custom-control binding targets,Binding target properties on custom controls must be DependencyProperties (sources can be plain CLR properties with INPC),Define DependencyProperty for properties bound TO on a custom control,Plain CLR properties as binding targets on custom controls,"public static readonly DependencyProperty NameProperty = ...","public string Name { get; set; } as binding target on custom control",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/dependency-properties-overview
35,Performance,Use async for long operations,Keep UI thread responsive,async/await with Task.Run for CPU work,Synchronous operations that freeze the UI,"await Task.Run(() => HeavyComputation());","HeavyComputation() on UI thread",High,https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
36,Performance,Profile with PerfView and Visual Studio,Measure before optimizing,Visual Studio diagnostic tools and PerfView,Guessing at performance bottlenecks,Performance Profiler in Visual Studio (Alt+F2),Optimize without profiling,Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/optimizing-wpf-application-performance
37,Threading,Use Dispatcher for UI updates,UI elements can only be accessed from the UI thread,Dispatcher.Invoke or BeginInvoke from background threads,Accessing UI elements from background threads,"Application.Current.Dispatcher.Invoke(() => Status = ""Done"");","textBlock.Text = ""Done"" from Task.Run",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/threading-model
38,Threading,Prefer async/await over Dispatcher,Modern async code returns to UI context automatically,async/await which resumes on captured SynchronizationContext,Manual Dispatcher.BeginInvoke for every callback,"var data = await LoadDataAsync(); Items = data;","Dispatcher.BeginInvoke(() => Items = result) in callback",Medium,https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/
39,Threading,Use Task.Run for CPU-bound work,Offload intensive work from UI thread,Task.Run for compute-bound work,Long-running computations on UI thread,"var result = await Task.Run(() => Compute());","var result = Compute(); on UI thread",High,https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming
40,Threading,Report progress from background tasks,Update UI with progress during long operations,IProgress<T> with Task.Run,Polling a shared variable for progress,"var progress = new Progress<int>(p => ProgressBar.Value = p); await Task.Run(() => Work(progress));","while (!done) { Thread.Sleep(100); check shared int; }",Medium,https://learn.microsoft.com/en-us/dotnet/api/system.progress-1
41,Threading,Handle DispatcherUnhandledException,Catch unhandled UI-thread exceptions to log them and prevent the default WPF crash dialog,Subscribe in App.xaml or App.OnStartup and set e.Handled=true after logging,Letting WPF show its default crash dialog and silently shut down,"<Application DispatcherUnhandledException=""App_OnUnhandledException"">",No global handler so any unhandled exception crashes the app,High,https://learn.microsoft.com/en-us/dotnet/api/system.windows.application.dispatcherunhandledexception
42,Accessibility,Set AutomationProperties,Enable screen reader support,AutomationProperties.Name on interactive controls,Controls without automation names,"<Button AutomationProperties.Name=""Save document""/>","<Button><Image Source=""save.png""/></Button> without name",High,https://learn.microsoft.com/en-us/dotnet/api/system.windows.automation.automationproperties
43,Accessibility,Support keyboard navigation,All functionality reachable via keyboard,Tab order and KeyboardNavigation properties,Mouse-only interactions,"<StackPanel KeyboardNavigation.TabNavigation=""Cycle"">","Click handlers with no keyboard equivalent",High,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/focus-overview
44,Accessibility,Support high contrast themes,Respect Windows high contrast settings,SystemColors and SystemFonts resources,Hardcoded colors that disappear in high contrast,"Foreground=""{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}""","Foreground=""#333333"" everywhere",Medium,https://learn.microsoft.com/en-us/dotnet/framework/ui-automation/accessibility-best-practices
45,Accessibility,Use appropriate control types,Semantic controls convey role to assistive tech,Button for actions CheckBox for toggles,Styled TextBlock with click handler as fake button,"<Button Content=""Submit""/>","<TextBlock MouseDown=""OnSubmitClick"" Text=""Submit""/>",High,https://learn.microsoft.com/en-us/dotnet/framework/ui-automation/accessibility-best-practices
46,Accessibility,Support DPI scaling,Ensure UI is crisp at all display scale factors,Device-independent units and vector graphics,Pixel-based bitmaps that blur at high DPI,"<Path Data=""M 10,10 L 20,20""/> or DrawingImage","<Image Source=""icon_32x32.png""/> at 200% scaling",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/graphics
47,Accessibility,Declare PerMonitorV2 DPI awareness,WPF defaults to System-DPI-aware unless you opt into PerMonitorV2 via app.manifest,app.manifest with dpiAwareness PerMonitorV2,Default System DPI awareness for Windows 10/11 apps,"<dpiAwareness xmlns=""http://schemas.microsoft.com/SMI/2016/WindowsSettings"">PerMonitorV2</dpiAwareness>",No app.manifest leaving app at System DPI,Medium,https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows
48,Architecture,Use MVVM pattern,Separate View ViewModel and Model concerns,MVVM with data binding and commands,Logic in code-behind,ViewModel with INotifyPropertyChanged and ICommand,MainWindow.xaml.cs with all business logic,High,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
49,Architecture,Override App.OnStartup for app initialization,Wire DI build the host resolve MainWindow and parse command-line args in OnStartup,Override OnStartup when DI or argument parsing is needed,Relying on StartupUri when MainWindow needs constructor injection,protected override void OnStartup(StartupEventArgs e) { _host.Start(); _host.Services.GetRequiredService<MainWindow>().Show(); },"<Application StartupUri=""MainWindow.xaml""/> when MainWindow has constructor dependencies",Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview
50,Architecture,Use dependency injection,Wire Microsoft.Extensions.Hosting Generic Host in App.OnStartup and resolve ViewModels from the container,Generic Host with Microsoft.Extensions.DependencyInjection,new Service() in ViewModel constructors,"services.AddTransient<MainViewModel>();","new MainViewModel(new DataService()) in App.xaml.cs",Medium,https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/overview
51,Architecture,Use CommunityToolkit.Mvvm,Source generators reduce MVVM boilerplate,[ObservableProperty] and [RelayCommand] attributes,Hand-written INotifyPropertyChanged for every property,"[ObservableProperty] private string _name;","private string _name; public string Name { get ... set ... OnPropertyChanged ... }",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
52,Architecture,Keep code-behind minimal,Code-behind should only contain view-specific logic,View logic like focus management and animations in code-behind,Business logic and data access in code-behind,Loaded handler that sets initial focus,Loaded handler that calls database and populates grid,Medium,https://learn.microsoft.com/en-us/dotnet/desktop/wpf/xaml/
53,Architecture,Use messaging for loose coupling,Communicate between ViewModels without references,WeakReferenceMessenger from CommunityToolkit.Mvvm,Direct ViewModel-to-ViewModel references,"WeakReferenceMessenger.Default.Send(new ItemSavedMessage(item));","MainViewModel.Instance.RefreshItems() from DetailViewModel",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger
54,Testing,Unit test ViewModels,Test business logic independent of UI,xUnit or NUnit tests on ViewModel methods and properties,Manual testing through the UI only,"[Fact] public void Save_WhenValid_SetsIsBusy() { vm.Save(); Assert.True(vm.IsBusy); }","Clicking buttons in the running app to verify",Medium,https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/
55,Testing,Mock services in tests,Isolate ViewModel from external dependencies,Moq or NSubstitute for service interfaces,Real database calls in unit tests,"var mock = new Mock<IDataService>(); var vm = new MainViewModel(mock.Object);","new MainViewModel(new SqlDataService()) in tests",Medium,https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
56,Testing,Use UI Automation for integration tests,Automated UI testing with Microsoft UI Automation,FlaUI or Appium 2 (appium-windows-driver) for end-to-end tests,Manual regression testing only,"AutomationElement.FindFirst(TreeScope.Children, condition)",Manual click-through testing,Medium,https://learn.microsoft.com/en-us/dotnet/framework/ui-automation/ui-automation-overview
Can't render this file because it contains an unexpected character in line 2 and column 234.

View File

@ -69,12 +69,12 @@ No,Style Category,Type,Keywords,Primary Colors,Secondary Colors,Effects & Animat
69,Bauhaus (包豪斯),Mobile,"bauhaus, geometric, constructivist, primary colors, hard shadow, bold, tactile, functional, poster, mechanical, architectural","Primary Red #D02020, Primary Blue #1040C0, Primary Yellow #F0C020","Background #F0F0F0 (Off-white), Foreground #121212 (Stark Black), Muted #E0E0E0","Hard offset shadows (4px 4px 0px black), mechanical press active:translate, no smooth hover — instant 0ms transitions, dot grid pattern on sections, slide-over transitions","Mobile-first apps needing high personality, onboarding flows, branding-forward product screens, artisan/design brands, editorial mobile experiences","Enterprise dashboards, accessibility-critical contexts (requires extra a11y work), data-heavy screens, conservative industries",✓ Full,◐ Partial (primary palette only),⚡ Excellent,⚠ WCAG AA (high contrast primaries; verify yellow text separately),✓ Mobile-First,◐ Medium,"React Native 10/10, Expo 10/10, SwiftUI 9/10, Flutter 9/10, Tailwind 9/10",1919 Bauhaus Movement,Medium,"Design a Bauhaus mobile app. Use strict geometric shapes (circles and squares only), primary color blocking (Red #D02020, Blue #1040C0, Yellow #F0C020), hard 4px offset black shadows, OFF-WHITE canvas (#F0F0F0), massive bold uppercase headlines (Outfit Black 900), rectangular full-width buttons with mechanical press animation. No gradients. No rounded cards. No soft transitions.","border-radius: 0px (cards/inputs) or 9999px (buttons/FAB), box-shadow: 4px 4px 0px 0px #121212, active:translate-x-[2px] active:translate-y-[2px] active:shadow-none, border: 2px solid #121212, font-family: Outfit, font-weight: 900 uppercase tracking-tighter (headlines)","☐ Geometric shapes only (circle/square), ☐ Primary color blocking applied, ☐ Hard offset shadows 4px, ☐ border-2 border-black on all elements, ☐ Mechanical press active state, ☐ Outfit Black 900 uppercase headlines, ☐ Safe area (pt-safe pb-safe) respected, ☐ Thumb-friendly h-12/h-14 touch targets, ☐ No hover states (mobile-only), ☐ Vertical rhythm single-column stack","--color-red: #D02020, --color-blue: #1040C0, --color-yellow: #F0C020, --color-bg: #F0F0F0, --color-fg: #121212, --border-width: 2px, --shadow-hard: 4px 4px 0px 0px #121212, --radius-block: 0px, --radius-pill: 9999px, --font-display: Outfit, --font-weight-hero: 900"
70,Minimalist Monochrome,Mobile,"monochrome, black white, editorial, austere, typographic, sharp, zero radius, high contrast, brutalist, pocket editorial, serif, mechanical","Pure Black #000000, Pure White #FFFFFF","Muted #F5F5F5, Dark Gray #525252, Border Light #E5E5E5","Instant inversion active state (tap → bg-black text-white, zero transition-none), no shadows (strictly 2D), full-bleed horizontal rules (4px black section dividers), subtle paper noise texture (opacity: 0.03), slide-in page transitions with hard edge","Luxury fashion e-commerce mobile, editorial publications, high-end portfolio apps, experimental/avant-garde brands, digital exhibitions","Entertainment, colorful brands, friendly consumer apps, anything requiring visual warmth or gradient",✓ Full (Light Mode Enforced),◐ Dark by section only (inverted sections),⚡ Excellent,✓ WCAG AAA (pure black/white),✓ Mobile-First,◐ Medium,"React Native 10/10, Expo 10/10, SwiftUI 9/10, Tailwind 9/10",2020s Editorial Mobile,Medium,"Design a minimalist monochrome mobile app. Use ONLY black (#000000) and white (#FFFFFF). Zero border-radius on every element. No shadows — depth is created by 14px black borders and color inversion only. Typography is the primary visual: Playfair Display for heroes (text-5xltext-6xl, tracking-tighter, leading-[0.9]), Source Serif 4 for body, JetBrains Mono for labels/tags. Tap states instantly invert (bg-black text-white). Full-width horizontal rules separate sections. Use the word 'MENU' instead of hamburger icon.","border-radius: 0px (ALL elements including modals), box-shadow: none, active:bg-black active:text-white transition-none, border-b-4 border-black (section dividers), divide-y divide-black (lists), font-family: Playfair Display (headers) + Source Serif 4 (body) + JetBrains Mono (labels), background-image: noise SVG opacity-[0.03]","☐ 0px border-radius on ALL elements, ☐ No shadows anywhere, ☐ Instant inversion on every tap (transition-none), ☐ 4px black line separates hero from content, ☐ Safe area respected (pt-safe pb-safe), ☐ h-14 touch targets, ☐ Sticky section headers with border-b, ☐ Typography hero: word spans full screen width, ☐ Paper noise texture on backgrounds, ☐ Menu word-label instead of icon","--color-bg: #FFFFFF, --color-fg: #000000, --color-muted: #F5F5F5, --color-muted-fg: #525252, --color-border: #000000, --color-border-light: #E5E5E5, --radius: 0px, --shadow: none, --border-hairline: 1px solid #E5E5E5, --border-thin: 1px solid #000000, --border-thick: 2px solid #000000, --border-heavy: 4px solid #000000, --font-display: Playfair Display, --font-body: Source Serif 4, --font-mono: JetBrains Mono"
71,Modern Dark (Cinema Mobile),Mobile,"dark mode, cinematic, ambient light, glassmorphism, deep black, indigo, glow, blur, atmospheric, reanimated, haptic, premium, layered, frosted glass, linear gradient","Deep #020203, Base #050506, Elevated #0a0a0c, Accent #5E6AD2","Foreground #EDEDEF, Muted #8A8F98, Accent Glow rgba(94 106 210/0.2), Border rgba(255 255 255/0.08), Surface rgba(255 255 255/0.05)","Expo.out Bezier(0.16,1,0.3,1) easing; spring modals (damping:20 stiffness:90); haptic-linked press (Impact Light/Medium); animated ambient light blobs (Reanimated translateX/Y slow oscillation); BlurView glassmorphism headers/nav (intensity 20); scale press 0.97 → 1.0; avoid pure #000000 (OLED smear)","Developer tools, pro productivity apps, fintech/trading dashboards, media/streaming platforms, AI tool interfaces, high-end gaming companion apps","Consumer apps needing warmth, children's apps, health/medical contexts where dark feels harsh, high-accessibility contexts needing maximum contrast",✓ Light mode only as exception,✓ Dark Mode Primary,⚠ Good (blur effects require native driver),⚠ WCAG AA (requires careful accent contrast check),✓ Mobile-First,◐ Medium,"React Native 10/10, Expo 10/10, react-native-skia 9/10, SwiftUI 8/10",2020s Cinematic Mobile,High,"Design a cinematic dark mobile app. Background: LinearGradient from #0a0a0f (top) to #020203 (bottom). Add 23 absolute animated 'blob' views: circular, blurRadius 3050, opacity 0.080.12, slow Reanimated oscillation. Cards: borderRadius 16, border rgba(255,255,255,0.08) hairline, subtle top-edge shine gradient. Primary button: #5E6AD2, scale press 0.97, haptic on press. BlurView (intensity 20, tint dark) for tab bar and headers. Typography: Inter 700 for headers, 400 for body. Never use pure #000000. Accent glow: rgba(94,106,210,0.2) behind primary actions.","borderRadius: 16 (cards/buttons), background: LinearGradient #0a0a0f→#020203, border: StyleSheet.hairlineWidth rgba(255,255,255,0.08), BlurView intensity={20} tint='dark', useAnimatedStyle + withRepeat (blob oscillation), Easing.bezier(0.16,1,0.3,1), withSpring damping:20 stiffness:90, Haptics.impactAsync(ImpactFeedbackStyle.Light), scale: 0.97 press","☐ No pure #000000 backgrounds, ☐ LinearGradient base screen, ☐ Animated ambient blobs (Reanimated, native driver), ☐ BlurView on tab bar and headers, ☐ borderRadius 16 on all cards, ☐ Haptic feedback on every Pressable, ☐ Bezier(0.16,1,0.3,1) easing used, ☐ Accent glow behind primary button, ☐ No solid grey borders (rgba only), ☐ Bottom sheets replace all modals","--bg-deep: #020203, --bg-base: #050506, --bg-elevated: #0a0a0c, --surface: rgba(255 255 255/0.05), --foreground: #EDEDEF, --foreground-muted: #8A8F98, --accent: #5E6AD2, --accent-glow: rgba(94 106 210/0.2), --border: rgba(255 255 255/0.08), --radius: 16px, --easing: cubic-bezier(0.16 1 0.3 1), --font: Inter"
72,SaaS Mobile (High-Tech Boutique),Mobile,"saas, electric blue, gradient, fintech, spring animation, dual font, glassmorphism, boutique, premium, calistoga, inter, mono, tactile, haptic, bento","Electric Blue #0052FF, Gradient End #4D7CFF","Background #FAFAFA, Foreground #0F172A, Muted #F1F5F9, Card #FFFFFF, Border #E2E8F0","Spring animations (mass:1 damping:15 stiffness:120); gradient buttons (0052FF→4D7CFF); scale press 0.96→1.0 with haptics; floating FAB with gentle bobbing (Reanimated); glassmorphism BlurView navigation bars; staggered fade-in entrance (Y:20→0 + opacity:0→1); pulsing status dot on section badges; layout transitions (LayoutAnimation or Reanimated entering)","B2B SaaS mobile dashboards, fintech apps, developer tool mobile companions, marketing analytics apps, HR/operations apps, modern business productivity","Pure consumer entertainment, children's apps, highly decorative lifestyle apps, contexts where Electric Blue feels too corporate",✓ Full,◐ Partial,⚡ Excellent,✓ WCAG AA,✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10, NativeWind 10/10, SwiftUI 8/10, Flutter 9/10",2020s SaaS Mobile,Medium,"Design a high-tech boutique SaaS mobile app. Primary canvas: #FAFAFA (warm off-white). Cards: #FFFFFF with 1pt Slate-200 border, iOS shadow (shadowOpacity:0.1, shadowRadius:10, offset y:4), Android elevation:4, padding 24px, borderRadius 16. Buttons: LinearGradient #0052FF→#4D7CFF, height 56px, borderRadius 16, scale press 0.96 + haptic. Section badges: rounded pill with rgba(0,82,255,0.05) bg and rgba(0,82,255,0.2) border + PulseDot + JetBrains Mono text. Typography: Calistoga for heroes (3642pt), Inter for body (1618pt), JetBrains Mono for data labels. All screen transitions: spring (mass:1 damping:15 stiffness:120). Always include SafeAreaView.","borderRadius: 16 (buttons/cards), LinearGradient colors={['#0052FF','#4D7CFF']}, shadowOpacity: 0.1, shadowRadius: 10, elevation: 4, Haptics.impactAsync(ImpactFeedbackStyle.Light) on press, withSpring({mass:1, damping:15, stiffness:120}), withTiming Y:20→0 opacity:0→1 staggered entrance, LayoutAnimation.configureNext for list updates, BlurView on nav bars","☐ SafeAreaView wraps all screens, ☐ All touch targets ≥ 44×44px, ☐ Spring config used for all transitions, ☐ Gradient buttons (not flat), ☐ Haptic on every Pressable, ☐ Section badges with PulseDot, ☐ Staggered entrance animation on screen mount, ☐ JetBrains Mono for data labels, ☐ Calistoga for hero headlines, ☐ Elevation/shadow on cards","--bg: #FAFAFA, --fg: #0F172A, --muted: #F1F5F9, --accent: #0052FF, --accent-sec: #4D7CFF, --card: #FFFFFF, --border: #E2E8F0, --radius: 16px, --shadow: shadowOpacity 0.1 shadowRadius 10, --spring: mass 1 damping 15 stiffness 120, --font-display: Calistoga, --font-body: Inter, --font-mono: JetBrains Mono"
72,SaaS Mobile (High-Tech Boutique),Mobile,"saas, electric blue, gradient, fintech, spring animation, dual font, glassmorphism, boutique, premium, calistoga, inter, mono, tactile, haptic, bento","Electric Blue #0052FF, Gradient End #4D7CFF","Background #FAFAFA, Foreground #0F172A, Muted #F1F5F9, Card #FFFFFF, Border #E2E8F0",Spring animations (mass:1 damping:15 stiffness:120); gradient buttons (0052FF→4D7CFF); scale press 0.96→1.0 with haptics; floating FAB with gentle bobbing (Reanimated); glassmorphism BlurView navigation bars; staggered fade-in entrance (Y:20→0 + opacity:0→1); pulsing status dot on section badges; layout transitions (LayoutAnimation or Reanimated entering),"B2B SaaS mobile dashboards, fintech apps, developer tool mobile companions, marketing analytics apps, HR/operations apps, modern business productivity","Pure consumer entertainment, children's apps, highly decorative lifestyle apps, contexts where Electric Blue feels too corporate",✓ Full,◐ Partial,⚡ Excellent,✓ WCAG AA,✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10, NativeWind 10/10, SwiftUI 8/10, Flutter 9/10",2020s SaaS Mobile,Medium,"Design a high-tech boutique SaaS mobile app. Primary canvas: #FAFAFA (warm off-white). Cards: #FFFFFF with 1pt Slate-200 border, iOS shadow (shadowOpacity:0.1, shadowRadius:10, offset y:4), Android elevation:4, padding 24px, borderRadius 16. Buttons: LinearGradient #0052FF→#4D7CFF, height 56px, borderRadius 16, scale press 0.96 + haptic. Section badges: rounded pill with rgba(0,82,255,0.05) bg and rgba(0,82,255,0.2) border + PulseDot + JetBrains Mono text. Typography: Calistoga for heroes (3642pt), Inter for body (1618pt), JetBrains Mono for data labels. All screen transitions: spring (mass:1 damping:15 stiffness:120). Always include SafeAreaView.","borderRadius: 16 (buttons/cards), LinearGradient colors={['#0052FF','#4D7CFF']}, shadowOpacity: 0.1, shadowRadius: 10, elevation: 4, Haptics.impactAsync(ImpactFeedbackStyle.Light) on press, withSpring({mass:1, damping:15, stiffness:120}), withTiming Y:20→0 opacity:0→1 staggered entrance, LayoutAnimation.configureNext for list updates, BlurView on nav bars","☐ SafeAreaView wraps all screens, ☐ All touch targets ≥ 44×44px, ☐ Spring config used for all transitions, ☐ Gradient buttons (not flat), ☐ Haptic on every Pressable, ☐ Section badges with PulseDot, ☐ Staggered entrance animation on screen mount, ☐ JetBrains Mono for data labels, ☐ Calistoga for hero headlines, ☐ Elevation/shadow on cards","--bg: #FAFAFA, --fg: #0F172A, --muted: #F1F5F9, --accent: #0052FF, --accent-sec: #4D7CFF, --card: #FFFFFF, --border: #E2E8F0, --radius: 16px, --shadow: shadowOpacity 0.1 shadowRadius 10, --spring: mass 1 damping 15 stiffness 120, --font-display: Calistoga, --font-body: Inter, --font-mono: JetBrains Mono"
73,Terminal CLI (Mobile),Mobile,"terminal, cli, matrix green, monospace, hacker, ascii, command line, developer, web3, crypto, sci-fi, OLED, retro-future, field operative","Matrix Green #33FF00, OLED Black #050505","Amber #FFB000, Muted Green #1A3D1A, Error Red #FF3333, Border Green #33FF00","Blinking cursor (500ms opacity loop), typewriter text reveal hook, scanline overlay (repeating lines 0.05 opacity), ASCII art headers, instant color inversion on press (bg-green text-black), haptic on every keystroke, boot sequence splash on launch","Developer tools, Web3/blockchain apps, geek-culture apps, ARG games, sci-fi/noir gaming companions, hacker/security tools, creative studio portfolios","Consumer products, health apps, anything requiring approachability or warmth, children's apps, standard enterprise contexts",✗ No,✓ OLED Dark Only,⚡ Excellent,✓ High contrast (green on black ≫4.5:1 ratio),✓ Mobile-First (OLED optimized),✗ Low,"React Native 10/10, Expo 10/10, NativeWind 9/10",Retro-Future 1980s2020s,Medium,"Design a Mobile Terminal CLI app. Background: #050505 OLED black. ALL text in Matrix Green #33FF00. Font: JetBrains Mono or SpaceMono ONLY — zero border-radius everywhere. ASCII borders using +, -, |, * characters instead of standard containers. Buttons displayed as [ EXECUTE ] or > PROCEED. On press: instantly inverts to green bg + black text + haptic. Cursor: blinking View opacity 0→1 at 500ms. Show boot sequence on launch (fake log scroll). Progress bars as [#####-----] text. Status bar footer: [BATTERY:88%] [NET:CONNECTED]. Scanline overlay: absolute View with repeating 1px horizontal lines at opacity 0.05. Typewriter effect on new data.","borderRadius: 0 (ALL elements), borderWidth: 1, borderColor: '#33FF00', backgroundColor: '#050505', color: '#33FF00', fontFamily: 'SpaceMono-Regular' or JetBrains Mono, fontSize: 12 or 14 or 16 only, lineHeight: 1.2x fontSize, Haptics.impactAsync(Light) on every press, useAnimatedValue blink 500ms, hitSlop: 12px all sides for bracketed buttons","☐ 0px border-radius everywhere, ☐ ASCII-style borders on cards, ☐ Boot sequence on launch, ☐ Blinking cursor component, ☐ Typewriter hook for new content, ☐ Scanline overlay (0.05 opacity), ☐ Haptic on every button press, ☐ Footer status bar component, ☐ hitSlop on all bracketed buttons (44×44dp), ☐ Reduced motion respected","--bg: #050505, --fg-primary: #33FF00, --fg-amber: #FFB000, --fg-muted: #1A3D1A, --fg-error: #FF3333, --border: #33FF00, --radius: 0px, --font: SpaceMono-Regular or JetBrains Mono, --font-sizes: 12 14 16 only, --blink-duration: 500ms, --scanline-opacity: 0.05"
74,Kinetic Brutalism (Mobile),Mobile,"kinetic, brutalism, motion, marquee, acid yellow, uppercase, oversized, aggressive typography, street, zine, high contrast, scroll-driven, haptic, reanimated","Acid Yellow #DFE104, Rich Black #09090B","Off-white #FAFAFA, Dark Gray #27272A, Zinc #A1A1AA, Border Zinc #3F3F46","Infinite marquee (Reanimated, Linear easing, 5s loop, hard clip), hero parallax (scale 1.0→1.3 + fade), sticky section header push, card flood inversion on press (bg→#DFE104, text→#000000), haptic Medium on every press, scroll-triggered interpolate transforms, 0px radius, 2px borders, 100ms color transitions","Immersive storytelling apps, brand flagship mobile, music/culture platforms, sports apps, underground zines, limited-edition product drops, performance dashboards","Calm informational apps, healthcare, finance contexts needing trust, children's, any context where aggressive typography feels inappropriate",✓ Dark Primary,◐ Dark only (inverted sections),⚡ Excellent (native driver required),⚠ WCAG AA (verify zinc body text on dark bg),✓ Mobile-First,✓ High energy,"React Native 10/10, Expo 10/10, Reanimated 10/10, NativeWind 9/10",2020s Mobile Brutalism,High,"Design a Kinetic Brutalism mobile app. Canvas: #09090B. Primary accent: Acid Yellow #DFE104 (text: #000000). Typography: Space Grotesk BOLD. Display text: 60120pt, uppercase, letterSpacing -1, lineHeight 0.91.1x. Body: 1820pt. Labels: 12pt uppercase letterSpacing +2. Add infinite marquee rows (Reanimated, no easing, hard edge clip). Hero text parallax on scroll (Interpolate: scale 1.0→1.3, opacity 1→0). Card press: instantly flood to #DFE104 + flip text to #000. Haptic Medium on every press. 0px radius. 2px solid borders. NO shadows. No gradients. Scale all fonts by (windowWidth / 375 * size) for responsiveness.","borderRadius: 0, borderWidth: 2, borderColor: '#3F3F46', backgroundColor: '#09090B', color: '#FAFAFA', fontWeight: '800 or 900', letterSpacing: -1 (large) or 2 (labels), lineHeight: 0.91.1 * fontSize, Reanimated withRepeat marquee timing 5000ms Easing.linear, Interpolate scroll→scale + opacity, Haptics.impactAsync(Medium), scale press: 0.95, 100ms color transitions","☐ Infinite marquee rows (Reanimated, no fade edges), ☐ Hero parallax scroll (scale+opacity Interpolate), ☐ All display text uppercase, ☐ 0px border-radius, ☐ 2px borders, ☐ Acid yellow card flood on press, ☐ Haptic Medium on every interaction, ☐ Font scale helper (windowWidth/375*size), ☐ Safe area for massive headers, ☐ Reduced motion stops marquees","--bg: #09090B, --fg: #FAFAFA, --muted: #27272A, --muted-fg: #A1A1AA, --accent: #DFE104, --accent-fg: #000000, --border: #3F3F46, --radius: 0px, --border-width: 2px, --shadow: none, --marquee-speed: 5000ms, --press-duration: 100ms, --font: Space Grotesk or Inter"
75,Flat Design Mobile (Touch-First),Mobile,"flat, 2D, no shadow, color blocking, geometric, bold, poster, icon, touch-first, minimal, clean, tailored, cross-platform","Blue #3B82F6, Emerald #10B981","Background #FFFFFF, Surface #F3F4F6, Text #111827, Amber #F59E0B, Border #E5E7EB","Immediate press feedback (scale 0.97, no delay), color section blocking (full-width contrasting View), zero elevation/shadow, solid icon containers (colored squares/circles), geometric low-opacity shape overlays, bottom tabs solid fill (no floating)","Cross-platform apps (iOS+Android parity), information-dense dashboards, system UI, brand illustration, onboarding flows, marketing pages, icon design","Ultra-premium contexts needing depth/shadow, dark-mode-first products, contexts where flat design reads as unfinished or sterile",✓ Full,◐ Partial (Dark mode via color swap only),⚡ Excellent (no GPU effects),✓ WCAG AA (large bold type helps),✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10, NativeWind 10/10, Flutter 9/10, SwiftUI 9/10",2010s2020s Flat Mobile,Low,"Design a Flat Mobile app. NO shadows (shadowOpacity: 0, elevation: 0). Color creates all hierarchy. Sections: full-width View blocks alternating contrasting bg colors (Blue Hero → White Content → Gray Block). Buttons: solid #3B82F6, borderRadius 8, height 56. Cards: backgroundColor #FFFFFF (on gray bg) or #DBEAFE (blue tint) — no shadow. Text: fontWeight 800 letterSpacing -0.5 (heads), 600 (sub), 400 (body). Inputs: #F3F4F6 bg, focused: borderWidth 2 borderColor #3B82F6. Icons: Lucide strokeWidth 2.5 inside solid colored square/circle. Press feedback: scale 0.97 Pressable. Use position absolute low-opacity geometric shapes (circles, rotated squares) as background decoration.","shadowOpacity: 0, elevation: 0, borderRadius: 6/12/999, height: 48 minimum touch targets, spacing: 4/8/16/24/32/48 system, backgroundColor (section blocking), Pressable scale: pressed ? 0.97 : 1, fontWeight: '800' heads / '600' sub / '400' body, letterSpacing: -0.5 heads / 1 labels, textTransform: 'uppercase' labels, strokeWidth={2.5} icons, borderWidth: 3/4 for featured CTAs","☐ Zero elevation AND shadowOpacity on all elements, ☐ Color-blocking sections (not borders), ☐ All touch targets ≥ 48×48, ☐ No gradients on flat elements, ☐ Icons inside solid colored containers, ☐ Pressable scale feedback, ☐ Geometric shapes as bg decoration, ☐ Bold flat bottom tabs (no floating), ☐ Primary headlines much larger than body, ☐ 4pt spacing system throughout","--bg: #FFFFFF, --surface: #F3F4F6, --fg: #111827, --primary: #3B82F6, --secondary: #10B981, --accent: #F59E0B, --border: #E5E7EB, --radius-sm: 6px, --radius-md: 12px, --radius-pill: 999px, --shadow: none, --elevation: 0, --touch-target: 48px, --spacing: 4 8 16 24 32 48"
76,Material You (MD3 Mobile),Mobile,"material design 3, md3, tonal surfaces, pills, soft curves, android, md3 easing, state layers, haptic, fab, google","Primary Violet #6750A4, Secondary Container #E8DEF8, Tertiary #7D5260","Surface #FFFBFE, On Surface #1C1B1F, Surface Container #F3EDF7, Outline #79747E","Tonal elevation (overlay colors instead of strong shadows), pill-shaped buttons and chips (borderRadius 999), emphasized easing Easing.bezier(0.2,0,0,1), state layers (pressed overlays 1015% opacity), Reanimated-filled label float for inputs, HapticFeedback on FAB/toggles","Android ecosystem apps, cross-platform productivity tools, MD3-based admin panels, data-heavy back-office UI with Material UI","Ultra-minimal brutalist brands, terminal/hacker aesthetics, monochrome editorial apps",✓ Full,✓ Full,⚠ Good (requires gradients and overlays),✓ WCAG AA (with MD3 token checks),✓ Mobile-First,✓ High,"React Native 9/10, Expo 10/10, React Native Paper 9/10","Material Design 3",Medium,"Design a Material You (MD3) mobile app. Use #FFFBFE background, #6750A4 primary, #E8DEF8 secondary container, #F3EDF7 surface container. All interactive elements are pill-shaped (borderRadius: 999). Buttons use Pressable with scale: 0.95 on press and state-layer overlays (black 10% or primary 12%). Inputs use filled M3 style: background #E7E0EC with floating label animation on focus. Elevation is tonal (layering containers) plus light shadow/elevation on Android. Animations use emphasized easing (0.2,0,0,1) at 100400ms. FABs are tertiary-colored rounded squares/circles with level 3 elevation.","borderRadius: 999 (buttons/chips), containerRadius: 1628, backgroundColor: '#FFFBFE', colorPrimary: '#6750A4', colorSecondaryContainer: '#E8DEF8', colorSurfaceContainer: '#F3EDF7', outlineColor: '#79747E', Pressable state-layer overlay (opacity 0.10.15), Easing.bezier(0.2,0,0,1), HapticFeedback.impactMedium on FAB, floating label using Reanimated translateY/scale","☐ MD3 color tokens applied (background/surface/container), ☐ All CTAs are pill-shaped, ☐ State-layer overlays instead of opacity 0.5 hacks, ☐ Emphasized easing used for all animations, ☐ Floating label inputs implemented, ☐ FAB uses tertiary color with correct elevation, ☐ Safe areas respected for organic shapes, ☐ No pure white background, ☐ No harsh box-shadows (ambient only)","--md3-bg: #FFFBFE, --md3-on-surface: #1C1B1F, --md3-primary: #6750A4, --md3-on-primary: #FFFFFF, --md3-secondary-container: #E8DEF8, --md3-on-secondary-container: #1D192B, --md3-tertiary: #7D5260, --md3-surface-container: #F3EDF7, --md3-outline: #79747E, --radius-pill: 999px, --easing-emphasized: cubic-bezier(0.2,0,0,1)"
77,Neo Brutalism (Mobile),Mobile,"neo brutalism, pop art, stickers, thick borders, cream background, hot red, vivid yellow, soft violet, hard offset shadow, mechanical press, collage","Cream #FFFDF5, Hot Red #FF6B6B, Vivid Yellow #FFD93D","Soft Violet #C4B5FD, Pure Black #000000, White #FFFFFF","Thick 4px black borders on all major elements, hard offset shadows (48px, no blur), mechanical press: translateX/Y equal to shadow offset, slightly rotated cards/badges (-2deg/2deg), high-saturation color blocking, spring/linear animations only","Creative tools, collab platforms, Gen Z marketing & e-commerce, portfolio sites, sticker-book style content apps","Serious enterprise apps, conservative industries, sober fintech, accessibility-first contexts (must tune contrast)",✓ Light-first,✗ Dark,⚠ Moderate (shadows + transforms),⚠ Requires careful contrast tuning,✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10, NativeWind 9/10",2020s Neo-Brutalism,High,"Design a Mobile Neo-Brutalist app. Background: Cream #FFFDF5. All content blocks: white or violet with borderWidth 4 borderColor #000. Shadows are solid offset blocks (no blur) using an extra View behind offset by 4px or 8px. Typography: Space Grotesk Bold/Black only (700900). Buttons: 56px tall, 4px border, 0 radius; press animation translates button to cover the shadow. Cards slightly rotated (-1deg, 2deg). Colors: Hot Red #FF6B6B for primary, Yellow #FFD93D for focus/badges, Soft Violet #C4B5FD as tertiary. Animation: spring/linear only, no ease-out luxury motion.","borderWidth: 4 (primary), 2 (secondary), borderRadius: 0 or 999 (badges only), backgroundColor: '#FFFDF5', shadow implemented as offset View, transform: [{translateX:4},{translateY:4}] on PressIn, fontFamily: 'SpaceGrotesk-Bold', fontWeight: '700/900', transform: [{ rotate: '-1deg' }] on cards, padding: 20,"☐ 4px borders on major elements, ☐ Hard offset shadow implemented via extra View, ☐ Mechanical press hides shadow, ☐ Cream canvas background, ☐ Pop-art color palette used, ☐ Cards/badges slightly rotated, ☐ No gradients or soft shadows, ☐ Only bold/black type weights, ☐ Badges slapped with absolute positioning, ☐ Anti-patterns (no subtle gray, no blur) avoided","--bg: #FFFDF5, --ink: #000000, --accent-primary: #FF6B6B, --accent-secondary: #FFD93D, --accent-muted: #C4B5FD, --white: #FFFFFF, --border-primary: 4px solid #000000, --shadow-offset-small: 4px, --shadow-offset-medium: 8px, --radius: 0px, --radius-pill: 999px, --font: Space Grotesk"
76,Material You (MD3 Mobile),Mobile,"material design 3, md3, tonal surfaces, pills, soft curves, android, md3 easing, state layers, haptic, fab, google","Primary Violet #6750A4, Secondary Container #E8DEF8, Tertiary #7D5260","Surface #FFFBFE, On Surface #1C1B1F, Surface Container #F3EDF7, Outline #79747E","Tonal elevation (overlay colors instead of strong shadows), pill-shaped buttons and chips (borderRadius 999), emphasized easing Easing.bezier(0.2,0,0,1), state layers (pressed overlays 1015% opacity), Reanimated-filled label float for inputs, HapticFeedback on FAB/toggles","Android ecosystem apps, cross-platform productivity tools, MD3-based admin panels, data-heavy back-office UI with Material UI","Ultra-minimal brutalist brands, terminal/hacker aesthetics, monochrome editorial apps",✓ Full,✓ Full,⚠ Good (requires gradients and overlays),✓ WCAG AA (with MD3 token checks),✓ Mobile-First,✓ High,"React Native 9/10, Expo 10/10, React Native Paper 9/10",Material Design 3,Medium,"Design a Material You (MD3) mobile app. Use #FFFBFE background, #6750A4 primary, #E8DEF8 secondary container, #F3EDF7 surface container. All interactive elements are pill-shaped (borderRadius: 999). Buttons use Pressable with scale: 0.95 on press and state-layer overlays (black 10% or primary 12%). Inputs use filled M3 style: background #E7E0EC with floating label animation on focus. Elevation is tonal (layering containers) plus light shadow/elevation on Android. Animations use emphasized easing (0.2,0,0,1) at 100400ms. FABs are tertiary-colored rounded squares/circles with level 3 elevation.","borderRadius: 999 (buttons/chips), containerRadius: 1628, backgroundColor: '#FFFBFE', colorPrimary: '#6750A4', colorSecondaryContainer: '#E8DEF8', colorSurfaceContainer: '#F3EDF7', outlineColor: '#79747E', Pressable state-layer overlay (opacity 0.10.15), Easing.bezier(0.2,0,0,1), HapticFeedback.impactMedium on FAB, floating label using Reanimated translateY/scale","☐ MD3 color tokens applied (background/surface/container), ☐ All CTAs are pill-shaped, ☐ State-layer overlays instead of opacity 0.5 hacks, ☐ Emphasized easing used for all animations, ☐ Floating label inputs implemented, ☐ FAB uses tertiary color with correct elevation, ☐ Safe areas respected for organic shapes, ☐ No pure white background, ☐ No harsh box-shadows (ambient only)","--md3-bg: #FFFBFE, --md3-on-surface: #1C1B1F, --md3-primary: #6750A4, --md3-on-primary: #FFFFFF, --md3-secondary-container: #E8DEF8, --md3-on-secondary-container: #1D192B, --md3-tertiary: #7D5260, --md3-surface-container: #F3EDF7, --md3-outline: #79747E, --radius-pill: 999px, --easing-emphasized: cubic-bezier(0.2,0,0,1)"
77,Neo Brutalism (Mobile),Mobile,"neo brutalism, pop art, stickers, thick borders, cream background, hot red, vivid yellow, soft violet, hard offset shadow, mechanical press, collage","Cream #FFFDF5, Hot Red #FF6B6B, Vivid Yellow #FFD93D","Soft Violet #C4B5FD, Pure Black #000000, White #FFFFFF","Thick 4px black borders on all major elements, hard offset shadows (48px, no blur), mechanical press: translateX/Y equal to shadow offset, slightly rotated cards/badges (-2deg/2deg), high-saturation color blocking, spring/linear animations only","Creative tools, collab platforms, Gen Z marketing & e-commerce, portfolio sites, sticker-book style content apps","Serious enterprise apps, conservative industries, sober fintech, accessibility-first contexts (must tune contrast)",✓ Light-first,✗ Dark,⚠ Moderate (shadows + transforms),⚠ Requires careful contrast tuning,✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10, NativeWind 9/10",2020s Neo-Brutalism,High,"Design a Mobile Neo-Brutalist app. Background: Cream #FFFDF5. All content blocks: white or violet with borderWidth 4 borderColor #000. Shadows are solid offset blocks (no blur) using an extra View behind offset by 4px or 8px. Typography: Space Grotesk Bold/Black only (700900). Buttons: 56px tall, 4px border, 0 radius; press animation translates button to cover the shadow. Cards slightly rotated (-1deg, 2deg). Colors: Hot Red #FF6B6B for primary, Yellow #FFD93D for focus/badges, Soft Violet #C4B5FD as tertiary. Animation: spring/linear only, no ease-out luxury motion.","borderWidth: 4 (primary), 2 (secondary), borderRadius: 0 or 999 (badges only), backgroundColor: '#FFFDF5', shadow implemented as offset View, transform: [{translateX:4},{translateY:4}] on PressIn, fontFamily: 'SpaceGrotesk-Bold', fontWeight: '700/900', transform: [{ rotate: '-1deg' }] on cards, padding: 20","☐ 4px borders on major elements, ☐ Hard offset shadow implemented via extra View, ☐ Mechanical press hides shadow, ☐ Cream canvas background, ☐ Pop-art color palette used, ☐ Cards/badges slightly rotated, ☐ No gradients or soft shadows, ☐ Only bold/black type weights, ☐ Badges slapped with absolute positioning, ☐ Anti-patterns (no subtle gray, no blur) avoided","--bg: #FFFDF5, --ink: #000000, --accent-primary: #FF6B6B, --accent-secondary: #FFD93D, --accent-muted: #C4B5FD, --white: #FFFFFF, --border-primary: 4px solid #000000, --shadow-offset-small: 4px, --shadow-offset-medium: 8px, --radius: 0px, --radius-pill: 999px, --font: Space Grotesk"
78,Bold Typography (Mobile Poster),Mobile,"bold typography, editorial, poster, broadsheet, vermillion, negative space, edge-to-edge type, underline CTA, near-black, warm white","Near Black #0A0A0A, Warm White #FAFAFA","Muted #1A1A1A, Secondary Text #737373, Accent Vermillion #FF3D00, Border #262626","Hero headlines 4872px (5:1 vs body size), tight tracking (-1.5px), edge-to-edge type, massive vertical spacing (60px+), underline CTAs (23px accent line), instant 200ms transitions (no bounce), strictly 0px radius containers, color shifts for active state instead of elevation","Creative brand heroes, reading-focused apps, event/exhibition pages, editorial mobile experiences, landing hero sections","Utility dashboards, kids apps, playful consumer products, contexts needing many icons or heavy imagery",✓ Dark Mode Primary,◐ Light sections optional,⚡ Excellent,✓ Contrast 18:1 achievable,✓ Mobile-First,✓ High,"React Native 10/10, Expo 10/10",Editorial 2020s,Medium,"Design a Bold Typography mobile screen. Background #0A0A0A, text #FAFAFA, accent #FF3D00. Use Inter Tight/Inter 600+ for all type; JetBrains Mono for labels. Headline: 5672px, tracking -1.5, lineHeight 1.1, full-bleed width with slight bleed off-screen. Body: 1618px, leading 1.6. Buttons: underline CTA (accent text + 2px underline block), or inverted box with 0 radius. No shadows, no rounded corners. Layout: single column, paddingHorizontal 24, vertical gaps 64 between sections. Animation: 200ms, Easing.bezier(0.25,0,0,1), slight slide-up 10px + fade on mount.","backgroundColor: '#0A0A0A', color: '#FAFAFA', accent: '#FF3D00', borderColor: '#262626', borderRadius: 0, paddingHorizontal: 24, headline style: fontSize:5672, fontWeight:'700/800', letterSpacing:-1.5, lineHeight:1.1*fontSize, body: fontSize:1618, lineHeight:1.6*fontSize, underline CTA: 23px height View under text, transition: 200ms cubic-bezier(0.25,0,0,1)","☐ H1 at least 45× body size, ☐ All containers 0 radius, ☐ Underline CTA pattern used, ☐ Large vertical gaps between sections, ☐ No shadows or soft corners, ☐ Accent used only for interaction, ☐ Text bleeds to/over screen edges, ☐ Animation timings 200ms, ☐ Accessible contrast ≥ 18:1, ☐ Body text never below 16px","--bg: #0A0A0A, --fg: #FAFAFA, --muted: #1A1A1A, --muted-fg: #737373, --accent: #FF3D00, --accent-fg: #0A0A0A, --border: #262626, --font-primary: Inter Tight, --font-display: Playfair Display Italic, --font-mono: JetBrains Mono"
79,Academia (Scholarly Mobile),Mobile,"academia, library, mahogany, parchment, brass, crimson, serif, drop cap, arch-top, vignette, leather, scholarly, tactile","Mahogany #1C1714, Oak #251E19","Parchment #E8DFD4, Worn Leather #3D332B, Faded Ink #9C8B7A, Brass #C9A962, Library Crimson #8B2635","Deep mahogany backgrounds, oak surface cards, brass accented CTAs, arch-top hero/imagery, heavy vignette overlays, sepia-tinted images, drop caps with brass Cinzel, Roman numeral volume headings, slow timing-based animations (Easing.out poly(4)), zero neon or modern tech cues","Knowledge management apps, deep reading tools, ritual-heavy personal brands, lore-heavy RPG/roleplay apps, culture-specific community platforms","Hyper-modern tech dashboards, neon/glassmorphism, playful Gen Z branding",✓ Dark Rich,◐ Light parchment sections,⚠ Moderate (vignette + shadows),✓ Legible (serif optimized),◐ Mobile-First,◐ Medium,"React Native 9/10, Expo 10/10",Timeless Scholarly,High,"Design a Scholarly Academia mobile app. Background #1C1714 (mahogany), alt surfaces #251E19 (oak), text #E8DFD4 (parchment). Accent brass #C9A962 for CTAs + borders; crimson #8B2635 for wax seals. Typography: Cormorant Garamond (headings), Crimson Pro (body), Cinzel (labels/overlines). Use arch-top hero containers (borderTopRadius 100). Cards: oak bg, 1px wood-grain border. Inputs: worn-leather background, brass focus border. Global vignette overlay and ornate brass dividers (Unicode glyph + gradient line). Animations: no spring, only Timing with Easing.out(Easing.poly(4)).","backgroundColor: '#1C1714', altSurface: '#251E19', textColor: '#E8DFD4', mutedBg: '#3D332B', borderColor: '#4A3F35', brass: '#C9A962', crimson: '#8B2635', borderRadius: 4 (default), archTopRadius: 100 for hero, shadowOpacity:0.4 shadowRadius:6 elevation:8 for cards, textShadow on headings, vignette overlay via LinearGradient","☐ Mahogany/oak/parchment palette applied, ☐ Brass used on all tappable items, ☐ Arch-top imagery used in hero/cards, ☐ Drop caps & Roman numerals used, ☐ Vignette overlay present, ☐ No sans-serif body fonts, ☐ No neon/bright modern colors, ☐ Animations use non-spring timing, ☐ Inputs use worn-leather style, ☐ Wax seal badges implemented","--bg: #1C1714, --bg-alt: #251E19, --fg: #E8DFD4, --muted: #3D332B, --muted-fg: #9C8B7A, --border: #4A3F35, --accent-brass: #C9A962, --accent-crimson: #8B2635, --radius: 4px, --arch-radius: 100px, --shadow-card: 0 4px 6px rgba(0,0,0,0.4), --font-heading: Cormorant Garamond, --font-body: Crimson Pro, --font-label: Cinzel"
80,Cyberpunk Mobile HUD,Mobile,"cyberpunk, neon, glitch, chamfered, orbitron, jetbrains, scanlines, crt, hud, matrix, military, decker","Void #0A0A0F, Card #12121A","Neon Green #00FF88, Neon Magenta #FF00FF, Cyber Cyan #00D4FF, Neutral Text #E0E0E0, Alert Red #FF3366, Border #2A2A3A","Deep void background with neon radiance, chamfered 45° corners via SVG/Skia, scanline overlay, CRT flicker opacity oscillation, glitch animations (translateX ±2), neon pulses around buttons, HUD corner brackets, terminal prompt text inputs, heavy use of blurView holographic panels","Gaming dashboards, crypto/cyberpunk apps, sci-fi companion tools, hacker OS skins, data-heavy monitoring HUDs","Serious enterprise, health/finance requiring calm trust, minimal editorial apps",✗ Light,✓ Dark-only,⚠ ModerateHeavy (Skia/blur/animations),⚠ Requires careful reduced-motion handling,✓ Mobile-First HUD,✓ High,"React Native 10/10, Skia 9/10, Expo 10/10",Cyber-Noir,High,"Design a Cyberpunk mobile HUD. Background #0A0A0F, card #12121A. Accents: #00FF88 (primary), #FF00FF, #00D4FF. Typography: Orbitron for headings, JetBrains Mono for data. All shapes use chamfered corners via SVG or Skia clipPath. Buttons: neon glow shadows, scale 0.98 + haptic on press, optional glitch jitter on active. Global scanline overlay (semi-transparent horizontal lines) and CRT flicker (root opacity 0.981). Inputs: prompt style with '>' in accent, custom blinking block cursor. HUD cards use corner brackets and subtle gradients.","backgroundColor: '#0A0A0F', cardBg: '#12121A', accent: '#00FF88', accent2: '#FF00FF', accent3: '#00D4FF', borderColor: '#2A2A3A', destructive: '#FF3366', borderRadius: 0, chamfer via SVG path, shadowColor accent with animated radius, scanline overlay View pointerEvents='none', withRepeat glitch translateX [-2,2,0], Easing.steps(2)","☐ Chamfered corners used instead of radius, ☐ Scanline & CRT flicker implemented, ☐ Orbitron + JetBrains Mono typography, ☐ Neon glow shadows on primary buttons, ☐ Glitch animation on active states, ☐ Prompt-style inputs with custom cursor, ☐ HUD corner brackets implemented, ☐ Safe-area system status bar styled, ☐ Reduced motion disables glitch/flicker, ☐ Icons configured with Lucide accent color","--bg: #0A0A0F, --card: #12121A, --fg: #E0E0E0, --muted: #1C1C2E, --accent: #00FF88, --accent2: #FF00FF, --accent3: #00D4FF, --border: #2A2A3A, --destructive: #FF3366, --radius: 0px, --font-heading: Orbitron, --font-body: JetBrains Mono"

Can't render this file because it contains an unexpected character in line 77 and column 1866.

View File

@ -1,74 +1,75 @@
No,Font Pairing Name,Category,Heading Font,Body Font,Mood/Style Keywords,Best For,Google Fonts URL,CSS Import,Tailwind Config,Notes
1,Classic Elegant,"Serif + Sans",Playfair Display,Inter,"elegant, luxury, sophisticated, timeless, premium, editorial","Luxury brands, fashion, spa, beauty, editorial, magazines, high-end e-commerce","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700|Playfair+Display:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Playfair Display', 'serif'], sans: ['Inter', 'sans-serif'] }","High contrast between elegant heading and clean body. Perfect for luxury/premium."
2,Modern Professional,"Sans + Sans",Poppins,Open Sans,"modern, professional, clean, corporate, friendly, approachable","SaaS, corporate sites, business apps, startups, professional services","https://fonts.google.com/share?selection.family=Open+Sans:wght@300;400;500;600;700|Poppins:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Poppins', 'sans-serif'], body: ['Open Sans', 'sans-serif'] }","Geometric Poppins for headings, humanist Open Sans for readability."
3,Tech Startup,"Sans + Sans",Space Grotesk,DM Sans,"tech, startup, modern, innovative, bold, futuristic","Tech companies, startups, SaaS, developer tools, AI products","https://fonts.google.com/share?selection.family=DM+Sans:wght@400;500;700|Space+Grotesk:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['DM Sans', 'sans-serif'] }","Space Grotesk has unique character, DM Sans is highly readable."
4,Editorial Classic,"Serif + Serif",Cormorant Garamond,Libre Baskerville,"editorial, classic, literary, traditional, refined, bookish","Publishing, blogs, news sites, literary magazines, book covers","https://fonts.google.com/share?selection.family=Cormorant+Garamond:wght@400;500;600;700|Libre+Baskerville:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Libre+Baskerville:wght@400;700&display=swap');","fontFamily: { heading: ['Cormorant Garamond', 'serif'], body: ['Libre Baskerville', 'serif'] }","All-serif pairing for traditional editorial feel."
5,Minimal Swiss,"Sans + Sans",Inter,Inter,"minimal, clean, swiss, functional, neutral, professional","Dashboards, admin panels, documentation, enterprise apps, design systems","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","Single font family with weight variations. Ultimate simplicity."
6,Playful Creative,"Display + Sans",Fredoka,Nunito,"playful, friendly, fun, creative, warm, approachable","Children's apps, educational, gaming, creative tools, entertainment","https://fonts.google.com/share?selection.family=Fredoka:wght@400;500;600;700|Nunito:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Nunito:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Fredoka', 'sans-serif'], body: ['Nunito', 'sans-serif'] }","Rounded, friendly fonts perfect for playful UIs."
7,Bold Statement,"Display + Sans",Bebas Neue,Source Sans 3,"bold, impactful, strong, dramatic, modern, headlines","Marketing sites, portfolios, agencies, event pages, sports","https://fonts.google.com/share?selection.family=Bebas+Neue|Source+Sans+3:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');","fontFamily: { display: ['Bebas Neue', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }","Bebas Neue for large headlines only. All-caps display font."
8,Wellness Calm,"Serif + Sans",Lora,Raleway,"calm, wellness, health, relaxing, natural, organic","Health apps, wellness, spa, meditation, yoga, organic brands","https://fonts.google.com/share?selection.family=Lora:wght@400;500;600;700|Raleway:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&family=Raleway:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Lora', 'serif'], sans: ['Raleway', 'sans-serif'] }","Lora's organic curves with Raleway's elegant simplicity."
9,Developer Mono,"Mono + Sans",JetBrains Mono,IBM Plex Sans,"code, developer, technical, precise, functional, hacker","Developer tools, documentation, code editors, tech blogs, CLI apps","https://fonts.google.com/share?selection.family=IBM+Plex+Sans:wght@300;400;500;600;700|JetBrains+Mono:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap');","fontFamily: { mono: ['JetBrains Mono', 'monospace'], sans: ['IBM Plex Sans', 'sans-serif'] }","JetBrains for code, IBM Plex for UI. Developer-focused."
10,Retro Vintage,"Display + Serif",Abril Fatface,Merriweather,"retro, vintage, nostalgic, dramatic, decorative, bold","Vintage brands, breweries, restaurants, creative portfolios, posters","https://fonts.google.com/share?selection.family=Abril+Fatface|Merriweather:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Merriweather:wght@300;400;700&display=swap');","fontFamily: { display: ['Abril Fatface', 'serif'], body: ['Merriweather', 'serif'] }","Abril Fatface for hero headlines only. High-impact vintage feel."
11,Geometric Modern,"Sans + Sans",Outfit,Work Sans,"geometric, modern, clean, balanced, contemporary, versatile","General purpose, portfolios, agencies, modern brands, landing pages","https://fonts.google.com/share?selection.family=Outfit:wght@300;400;500;600;700|Work+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Work+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Work Sans', 'sans-serif'] }","Both geometric but Outfit more distinctive for headings."
12,Luxury Serif,"Serif + Sans",Cormorant,Montserrat,"luxury, high-end, fashion, elegant, refined, premium","Fashion brands, luxury e-commerce, jewelry, high-end services","https://fonts.google.com/share?selection.family=Cormorant:wght@400;500;600;700|Montserrat:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Cormorant:wght@400;500;600;700&family=Montserrat:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Cormorant', 'serif'], sans: ['Montserrat', 'sans-serif'] }","Cormorant's elegance with Montserrat's geometric precision."
13,Friendly SaaS,"Sans + Sans",Plus Jakarta Sans,Plus Jakarta Sans,"friendly, modern, saas, clean, approachable, professional","SaaS products, web apps, dashboards, B2B, productivity tools","https://fonts.google.com/share?selection.family=Plus+Jakarta+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single versatile font. Modern alternative to Inter."
14,News Editorial,"Serif + Sans",Newsreader,Roboto,"news, editorial, journalism, trustworthy, readable, informative","News sites, blogs, magazines, journalism, content-heavy sites","https://fonts.google.com/share?selection.family=Newsreader:wght@400;500;600;700|Roboto:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Newsreader:wght@400;500;600;700&family=Roboto:wght@300;400;500;700&display=swap');","fontFamily: { serif: ['Newsreader', 'serif'], sans: ['Roboto', 'sans-serif'] }","Newsreader designed for long-form reading. Roboto for UI."
15,Handwritten Charm,"Script + Sans",Caveat,Quicksand,"handwritten, personal, friendly, casual, warm, charming","Personal blogs, invitations, creative portfolios, lifestyle brands","https://fonts.google.com/share?selection.family=Caveat:wght@400;500;600;700|Quicksand:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Quicksand:wght@300;400;500;600;700&display=swap');","fontFamily: { script: ['Caveat', 'cursive'], sans: ['Quicksand', 'sans-serif'] }","Use Caveat sparingly for accents. Quicksand for body."
16,Corporate Trust,"Sans + Sans",Lexend,Source Sans 3,"corporate, trustworthy, accessible, readable, professional, clean","Enterprise, government, healthcare, finance, accessibility-focused","https://fonts.google.com/share?selection.family=Lexend:wght@300;400;500;600;700|Source+Sans+3:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@300;400;500;600;700&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Lexend', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }","Lexend designed for readability. Excellent accessibility."
17,Brutalist Raw,"Mono + Mono",Space Mono,Space Mono,"brutalist, raw, technical, monospace, minimal, stark","Brutalist designs, developer portfolios, experimental, tech art","https://fonts.google.com/share?selection.family=Space+Mono:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');","fontFamily: { mono: ['Space Mono', 'monospace'] }","All-mono for raw brutalist aesthetic. Limited weights."
18,Fashion Forward,"Sans + Sans",Syne,Manrope,"fashion, avant-garde, creative, bold, artistic, edgy","Fashion brands, creative agencies, art galleries, design studios","https://fonts.google.com/share?selection.family=Manrope:wght@300;400;500;600;700|Syne:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&family=Syne:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Syne', 'sans-serif'], body: ['Manrope', 'sans-serif'] }","Syne's unique character for headlines. Manrope for readability."
19,Soft Rounded,"Sans + Sans",Varela Round,Nunito Sans,"soft, rounded, friendly, approachable, warm, gentle","Children's products, pet apps, friendly brands, wellness, soft UI","https://fonts.google.com/share?selection.family=Nunito+Sans:wght@300;400;500;600;700|Varela+Round","@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Varela+Round&display=swap');","fontFamily: { heading: ['Varela Round', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }","Both rounded and friendly. Perfect for soft UI designs."
20,Premium Sans,"Sans + Sans",Satoshi,General Sans,"premium, modern, clean, sophisticated, versatile, balanced","Premium brands, modern agencies, SaaS, portfolios, startups","https://fonts.google.com/share?selection.family=DM+Sans:wght@400;500;700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap');","fontFamily: { sans: ['DM Sans', 'sans-serif'] }","Note: Satoshi/General Sans on Fontshare. DM Sans as Google alternative."
21,Vietnamese Friendly,"Sans + Sans",Be Vietnam Pro,Noto Sans,"vietnamese, international, readable, clean, multilingual, accessible","Vietnamese sites, multilingual apps, international products","https://fonts.google.com/share?selection.family=Be+Vietnam+Pro:wght@300;400;500;600;700|Noto+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Be Vietnam Pro', 'Noto Sans', 'sans-serif'] }","Be Vietnam Pro excellent Vietnamese support. Noto as fallback."
22,Japanese Elegant,"Serif + Sans",Noto Serif JP,Noto Sans JP,"japanese, elegant, traditional, modern, multilingual, readable","Japanese sites, Japanese restaurants, cultural sites, anime/manga","https://fonts.google.com/share?selection.family=Noto+Sans+JP:wght@300;400;500;700|Noto+Serif+JP:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&family=Noto+Serif+JP:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Noto Serif JP', 'serif'], sans: ['Noto Sans JP', 'sans-serif'] }","Noto fonts excellent Japanese support. Traditional + modern feel."
23,Korean Modern,"Sans + Sans",Noto Sans KR,Noto Sans KR,"korean, modern, clean, professional, multilingual, readable","Korean sites, K-beauty, K-pop, Korean businesses, multilingual","https://fonts.google.com/share?selection.family=Noto+Sans+KR:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans KR', 'sans-serif'] }","Clean Korean typography. Single font with weight variations."
24,Chinese Traditional,"Serif + Sans",Noto Serif TC,Noto Sans TC,"chinese, traditional, elegant, cultural, multilingual, readable","Traditional Chinese sites, cultural content, Taiwan/Hong Kong markets","https://fonts.google.com/share?selection.family=Noto+Sans+TC:wght@300;400;500;700|Noto+Serif+TC:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&family=Noto+Serif+TC:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Noto Serif TC', 'serif'], sans: ['Noto Sans TC', 'sans-serif'] }","Traditional Chinese character support. Elegant pairing."
25,Chinese Simplified,"Sans + Sans",Noto Sans SC,Noto Sans SC,"chinese, simplified, modern, professional, multilingual, readable","Simplified Chinese sites, mainland China market, business apps","https://fonts.google.com/share?selection.family=Noto+Sans+SC:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans SC', 'sans-serif'] }","Simplified Chinese support. Clean modern look."
26,Arabic Elegant,"Serif + Sans",Noto Naskh Arabic,Noto Sans Arabic,"arabic, elegant, traditional, cultural, RTL, readable","Arabic sites, Middle East market, Islamic content, bilingual sites","https://fonts.google.com/share?selection.family=Noto+Naskh+Arabic:wght@400;500;600;700|Noto+Sans+Arabic:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;500;600;700&family=Noto+Sans+Arabic:wght@300;400;500;700&display=swap');","fontFamily: { serif: ['Noto Naskh Arabic', 'serif'], sans: ['Noto Sans Arabic', 'sans-serif'] }","RTL support. Naskh for traditional, Sans for modern Arabic."
27,Thai Modern,"Sans + Sans",Noto Sans Thai,Noto Sans Thai,"thai, modern, readable, clean, multilingual, accessible","Thai sites, Southeast Asia, tourism, Thai restaurants","https://fonts.google.com/share?selection.family=Noto+Sans+Thai:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans Thai', 'sans-serif'] }","Clean Thai typography. Excellent readability."
28,Hebrew Modern,"Sans + Sans",Noto Sans Hebrew,Noto Sans Hebrew,"hebrew, modern, RTL, clean, professional, readable","Hebrew sites, Israeli market, Jewish content, bilingual sites","https://fonts.google.com/share?selection.family=Noto+Sans+Hebrew:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Hebrew:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans Hebrew', 'sans-serif'] }","RTL support. Clean modern Hebrew typography."
29,Legal Professional,"Serif + Sans",EB Garamond,Lato,"legal, professional, traditional, trustworthy, formal, authoritative","Law firms, legal services, contracts, formal documents, government","https://fonts.google.com/share?selection.family=EB+Garamond:wght@400;500;600;700|Lato:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500;600;700&family=Lato:wght@300;400;700&display=swap');","fontFamily: { serif: ['EB Garamond', 'serif'], sans: ['Lato', 'sans-serif'] }","EB Garamond for authority. Lato for clean body text."
30,Medical Clean,"Sans + Sans",Figtree,Noto Sans,"medical, clean, accessible, professional, healthcare, trustworthy","Healthcare, medical clinics, pharma, health apps, accessibility","https://fonts.google.com/share?selection.family=Figtree:wght@300;400;500;600;700|Noto+Sans:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;700&display=swap');","fontFamily: { heading: ['Figtree', 'sans-serif'], body: ['Noto Sans', 'sans-serif'] }","Clean, accessible fonts for medical contexts."
31,Financial Trust,"Sans + Sans",IBM Plex Sans,IBM Plex Sans,"financial, trustworthy, professional, corporate, banking, serious","Banks, finance, insurance, investment, fintech, enterprise","https://fonts.google.com/share?selection.family=IBM+Plex+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['IBM Plex Sans', 'sans-serif'] }","IBM Plex conveys trust and professionalism. Excellent for data."
32,Real Estate Luxury,"Serif + Sans",Cinzel,Josefin Sans,"real estate, luxury, elegant, sophisticated, property, premium","Real estate, luxury properties, architecture, interior design","https://fonts.google.com/share?selection.family=Cinzel:wght@400;500;600;700|Josefin+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600;700&family=Josefin+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Cinzel', 'serif'], sans: ['Josefin Sans', 'sans-serif'] }","Cinzel's elegance for headlines. Josefin for modern body."
33,Restaurant Menu,"Serif + Sans",Playfair Display SC,Karla,"restaurant, menu, culinary, elegant, foodie, hospitality","Restaurants, cafes, food blogs, culinary, hospitality","https://fonts.google.com/share?selection.family=Karla:wght@300;400;500;600;700|Playfair+Display+SC:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Karla:wght@300;400;500;600;700&family=Playfair+Display+SC:wght@400;700&display=swap');","fontFamily: { display: ['Playfair Display SC', 'serif'], sans: ['Karla', 'sans-serif'] }","Small caps Playfair for menu headers. Karla for descriptions."
34,Art Deco,"Display + Sans",Poiret One,Didact Gothic,"art deco, vintage, 1920s, elegant, decorative, gatsby","Vintage events, art deco themes, luxury hotels, classic cocktails","https://fonts.google.com/share?selection.family=Didact+Gothic|Poiret+One","@import url('https://fonts.googleapis.com/css2?family=Didact+Gothic&family=Poiret+One&display=swap');","fontFamily: { display: ['Poiret One', 'sans-serif'], sans: ['Didact Gothic', 'sans-serif'] }","Poiret One for art deco headlines only. Didact for body."
35,Magazine Style,"Serif + Sans",Libre Bodoni,Public Sans,"magazine, editorial, publishing, refined, journalism, print","Magazines, online publications, editorial content, journalism","https://fonts.google.com/share?selection.family=Libre+Bodoni:wght@400;500;600;700|Public+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Libre+Bodoni:wght@400;500;600;700&family=Public+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Libre Bodoni', 'serif'], sans: ['Public Sans', 'sans-serif'] }","Bodoni's editorial elegance. Public Sans for clean UI."
36,Crypto/Web3,"Sans + Sans",Orbitron,Exo 2,"crypto, web3, futuristic, tech, blockchain, digital","Crypto platforms, NFT, blockchain, web3, futuristic tech","https://fonts.google.com/share?selection.family=Exo+2:wght@300;400;500;600;700|Orbitron:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Orbitron', 'sans-serif'], body: ['Exo 2', 'sans-serif'] }","Orbitron for futuristic headers. Exo 2 for readable body."
37,Gaming Bold,"Display + Sans",Russo One,Chakra Petch,"gaming, bold, action, esports, competitive, energetic","Gaming, esports, action games, competitive sports, entertainment","https://fonts.google.com/share?selection.family=Chakra+Petch:wght@300;400;500;600;700|Russo+One","@import url('https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@300;400;500;600;700&family=Russo+One&display=swap');","fontFamily: { display: ['Russo One', 'sans-serif'], body: ['Chakra Petch', 'sans-serif'] }","Russo One for impact. Chakra Petch for techy body text."
38,Indie/Craft,"Display + Sans",Amatic SC,Cabin,"indie, craft, handmade, artisan, organic, creative","Craft brands, indie products, artisan, handmade, organic products","https://fonts.google.com/share?selection.family=Amatic+SC:wght@400;700|Cabin:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Cabin:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Amatic SC', 'sans-serif'], sans: ['Cabin', 'sans-serif'] }","Amatic for handwritten feel. Cabin for readable body."
39,Startup Bold,"Sans + Sans",Clash Display,Satoshi,"startup, bold, modern, innovative, confident, dynamic","Startups, pitch decks, product launches, bold brands","https://fonts.google.com/share?selection.family=Outfit:wght@400;500;600;700|Rubik:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Rubik', 'sans-serif'] }","Note: Clash Display on Fontshare. Outfit as Google alternative."
40,E-commerce Clean,"Sans + Sans",Rubik,Nunito Sans,"ecommerce, clean, shopping, product, retail, conversion","E-commerce, online stores, product pages, retail, shopping","https://fonts.google.com/share?selection.family=Nunito+Sans:wght@300;400;500;600;700|Rubik:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Rubik', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }","Clean readable fonts perfect for product descriptions."
41,Academic/Research,"Serif + Sans",Crimson Pro,Atkinson Hyperlegible,"academic, research, scholarly, accessible, readable, educational","Universities, research papers, academic journals, educational","https://fonts.google.com/share?selection.family=Atkinson+Hyperlegible:wght@400;700|Crimson+Pro:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&family=Crimson+Pro:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Crimson Pro', 'serif'], sans: ['Atkinson Hyperlegible', 'sans-serif'] }","Crimson for scholarly headlines. Atkinson for accessibility."
42,Dashboard Data,"Mono + Sans",Fira Code,Fira Sans,"dashboard, data, analytics, code, technical, precise","Dashboards, analytics, data visualization, admin panels","https://fonts.google.com/share?selection.family=Fira+Code:wght@400;500;600;700|Fira+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600;700&family=Fira+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { mono: ['Fira Code', 'monospace'], sans: ['Fira Sans', 'sans-serif'] }","Fira family cohesion. Code for data, Sans for labels."
43,Music/Entertainment,"Display + Sans",Righteous,Poppins,"music, entertainment, fun, energetic, bold, performance","Music platforms, entertainment, events, festivals, performers","https://fonts.google.com/share?selection.family=Poppins:wght@300;400;500;600;700|Righteous","@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Righteous&display=swap');","fontFamily: { display: ['Righteous', 'sans-serif'], sans: ['Poppins', 'sans-serif'] }","Righteous for bold entertainment headers. Poppins for body."
44,Minimalist Portfolio,"Sans + Sans",Archivo,Space Grotesk,"minimal, portfolio, designer, creative, clean, artistic","Design portfolios, creative professionals, minimalist brands","https://fonts.google.com/share?selection.family=Archivo:wght@300;400;500;600;700|Space+Grotesk:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Archivo:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['Archivo', 'sans-serif'] }","Space Grotesk for distinctive headers. Archivo for clean body."
45,Kids/Education,"Display + Sans",Baloo 2,Comic Neue,"kids, education, playful, friendly, colorful, learning","Children's apps, educational games, kid-friendly content","https://fonts.google.com/share?selection.family=Baloo+2:wght@400;500;600;700|Comic+Neue:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=Baloo+2:wght@400;500;600;700&family=Comic+Neue:wght@300;400;700&display=swap');","fontFamily: { display: ['Baloo 2', 'sans-serif'], sans: ['Comic Neue', 'sans-serif'] }","Fun, playful fonts for children. Comic Neue is readable comic style."
46,Wedding/Romance,"Script + Serif",Great Vibes,Cormorant Infant,"wedding, romance, elegant, script, invitation, feminine","Wedding sites, invitations, romantic brands, bridal","https://fonts.google.com/share?selection.family=Cormorant+Infant:wght@300;400;500;600;700|Great+Vibes","@import url('https://fonts.googleapis.com/css2?family=Cormorant+Infant:wght@300;400;500;600;700&family=Great+Vibes&display=swap');","fontFamily: { script: ['Great Vibes', 'cursive'], serif: ['Cormorant Infant', 'serif'] }","Great Vibes for elegant accents. Cormorant for readable text."
47,Science/Tech,"Sans + Sans",Exo,Roboto Mono,"science, technology, research, data, futuristic, precise","Science, research, tech documentation, data-heavy sites","https://fonts.google.com/share?selection.family=Exo:wght@300;400;500;600;700|Roboto+Mono:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Exo:wght@300;400;500;600;700&family=Roboto+Mono:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Exo', 'sans-serif'], mono: ['Roboto Mono', 'monospace'] }","Exo for modern tech feel. Roboto Mono for code/data."
48,Accessibility First,"Sans + Sans",Atkinson Hyperlegible,Atkinson Hyperlegible,"accessible, readable, inclusive, WCAG, dyslexia-friendly, clear","Accessibility-critical sites, government, healthcare, inclusive design","https://fonts.google.com/share?selection.family=Atkinson+Hyperlegible:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap');","fontFamily: { sans: ['Atkinson Hyperlegible', 'sans-serif'] }","Designed for maximum legibility. Excellent for accessibility."
49,Sports/Fitness,"Sans + Sans",Barlow Condensed,Barlow,"sports, fitness, athletic, energetic, condensed, action","Sports, fitness, gyms, athletic brands, competition","https://fonts.google.com/share?selection.family=Barlow+Condensed:wght@400;500;600;700|Barlow:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600;700&family=Barlow:wght@300;400;500;600;700&display=swap');","fontFamily: { display: ['Barlow Condensed', 'sans-serif'], body: ['Barlow', 'sans-serif'] }","Condensed for impact headlines. Regular Barlow for body."
50,Luxury Minimalist,"Serif + Sans",Bodoni Moda,Jost,"luxury, minimalist, high-end, sophisticated, refined, premium","Luxury minimalist brands, high-end fashion, premium products","https://fonts.google.com/share?selection.family=Bodoni+Moda:wght@400;500;600;700|Jost:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@400;500;600;700&family=Jost:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Bodoni Moda', 'serif'], sans: ['Jost', 'sans-serif'] }","Bodoni's high contrast elegance. Jost for geometric body."
51,Tech/HUD Mono,"Mono + Mono",Share Tech Mono,Fira Code,"tech, futuristic, hud, sci-fi, data, monospaced, precise","Sci-fi interfaces, developer tools, cybersecurity, dashboards","https://fonts.google.com/share?selection.family=Fira+Code:wght@300;400;500;600;700|Share+Tech+Mono","@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500;600;700&family=Share+Tech+Mono&display=swap');","fontFamily: { hud: ['Share Tech Mono', 'monospace'], code: ['Fira Code', 'monospace'] }","Share Tech Mono has that classic sci-fi look."
52,Pixel Retro,"Display + Sans",Press Start 2P,VT323,"pixel, retro, gaming, 8-bit, nostalgic, arcade","Pixel art games, retro websites, creative portfolios","https://fonts.google.com/share?selection.family=Press+Start+2P|VT323","@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&family=VT323&display=swap');","fontFamily: { pixel: ['Press Start 2P', 'cursive'], terminal: ['VT323', 'monospace'] }","Press Start 2P is very wide/large. VT323 is better for body text."
53,Neubrutalist Bold,"Display + Sans",Lexend Mega,Public Sans,"bold, neubrutalist, loud, strong, geometric, quirky","Neubrutalist designs, Gen Z brands, bold marketing","https://fonts.google.com/share?selection.family=Lexend+Mega:wght@100..900|Public+Sans:wght@100..900","@import url('https://fonts.googleapis.com/css2?family=Lexend+Mega:wght@100..900&family=Public+Sans:wght@100..900&display=swap');","fontFamily: { mega: ['Lexend Mega', 'sans-serif'], body: ['Public Sans', 'sans-serif'] }","Lexend Mega has distinct character and variable weight."
54,Academic/Archival,"Serif + Serif",EB Garamond,Crimson Text,"academic, old-school, university, research, serious, traditional","University sites, archives, research papers, history","https://fonts.google.com/share?selection.family=Crimson+Text:wght@400;600;700|EB+Garamond:wght@400;500;600;700;800","@import url('https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600;700&family=EB+Garamond:wght@400;500;600;700;800&display=swap');","fontFamily: { classic: ['EB Garamond', 'serif'], text: ['Crimson Text', 'serif'] }","Classic academic aesthetic. Very legible."
55,Spatial Clear,"Sans + Sans",Inter,Inter,"spatial, legible, glass, system, clean, neutral","Spatial computing, AR/VR, glassmorphism interfaces","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","Optimized for readability on dynamic backgrounds."
56,Kinetic Motion,"Display + Mono",Syncopate,Space Mono,"kinetic, motion, futuristic, speed, wide, tech","Music festivals, automotive, high-energy brands","https://fonts.google.com/share?selection.family=Space+Mono:wght@400;700|Syncopate:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syncopate:wght@400;700&display=swap');","fontFamily: { display: ['Syncopate', 'sans-serif'], mono: ['Space Mono', 'monospace'] }","Syncopate's wide stance works well with motion effects."
57,Gen Z Brutal,"Display + Sans",Anton,Epilogue,"brutal, loud, shouty, meme, internet, bold","Gen Z marketing, streetwear, viral campaigns","https://fonts.google.com/share?selection.family=Anton|Epilogue:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Anton&family=Epilogue:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Anton', 'sans-serif'], body: ['Epilogue', 'sans-serif'] }","Anton is impactful and condensed. Good for stickers/badges."57,Bauhaus Geometric,"Geometric Sans + Single Weight","Outfit","Outfit","bauhaus, geometric, constructivist, bold, uppercase, architectural, mechanical, poster, tactile","Bauhaus mobile apps, bold editorial mobile, design-forward branding apps, art/culture platforms","https://fonts.google.com/share?selection.family=Outfit:wght@400;500;700;900","@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;700;900&display=swap');","fontFamily: { display: ['Outfit', 'sans-serif'], body: ['Outfit', 'sans-serif'] }","Single-family system: Outfit 900 uppercase tracking-tighter for heroes; Outfit 700 uppercase for buttons/nav; Outfit 500 for body. Scale aggressively: text-4xltext-5xl headlines on mobile."
58,Minimalist Monochrome Editorial,"Serif + Serif + Mono (Triple Stack)",Playfair Display,Source Serif 4,"monochrome, editorial, austere, typographic, pocket manifesto, luxury, high contrast, brutalist mobile","Luxury fashion mobile apps, editorial publications, digital exhibitions, portfolio apps, high-contrast e-reader aesthetics","https://fonts.google.com/share?selection.family=JetBrains+Mono:wght@400;500|Playfair+Display:ital,wght@0,400;0,700;0,900;1,400|Source+Serif+4:ital,wght@0,300;0,400;0,600;1,300","@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&family=Source+Serif+4:ital,wght@0,300;0,400;0,600;1,300&display=swap');","fontFamily: { display: ['Playfair Display', 'serif'], body: ['Source Serif 4', 'serif'], mono: ['JetBrains Mono', 'monospace'] }","Triple stack: Playfair Display 900 tracking-tighter leading-[0.9] for heroes (text-5xltext-6xl breaks words graphically). Source Serif 4 300600 for body legibility. JetBrains Mono 400500 uppercase tracking-widest for tags/dates/labels. NO UI sans-serif — 100% serif/mono."
59,Modern Dark Cinema (Inter System),"Sans + Mono",Inter,Inter,"dark, cinematic, technical, precision, clean, premium, developer, professional, high-end utility","Developer tools, fintech/trading, AI dashboards, streaming platforms, high-end productivity apps","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","Single-family precision system: Inter 700 (-1.5 tracking) for Display 48pt; Inter 600 (-0.5 tracking) for H1 32pt / H2 24pt; Inter 400 for body 16pt; Inter 500 uppercase +1.2 tracking for labels/mono. Gradient text via mask-view + react-native-linear-gradient (#FFFFFF → rgba(255,255,255,0.7)) on major headers."
60,SaaS Mobile Boutique (Calistoga + Inter),"Display Serif + Sans + Mono",Calistoga,Inter,"saas, boutique, electric, warm, editorial, bold, premium, fintech, business, dual font, human warmth","B2B SaaS mobile, fintech apps, analytics dashboards, marketing tools, operations platforms","https://fonts.google.com/share?selection.family=Calistoga:ital@0;1|Inter:wght@300;400;500;600;700|JetBrains+Mono:wght@400;500","@import url('https://fonts.googleapis.com/css2?family=Calistoga:ital@0;1&family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');","fontFamily: { display: ['Calistoga', 'serif'], body: ['Inter', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Calistoga (adds human warmth) for heroes 3642pt leading-1.1; Inter 400600 for body/UI 1618pt; JetBrains Mono 12pt uppercase tracking-[1.5] for data labels and section badges. Scale: Hero 3642pt, Section H2 2832pt, Body 1618pt, Label 12pt. Avoid italic Calistoga except editorial callouts."
61,Terminal CLI Monospace,"Mono + Mono (Single Family)",JetBrains Mono,JetBrains Mono,"terminal, cli, hacker, monospace, matrix, developer, retro-future, command line, precision, OLED","Developer tools, Web3/blockchain apps, hacker aesthetic, sci-fi games, ARG, security tools, geek-culture portfolios","https://fonts.google.com/share?selection.family=JetBrains+Mono:ital,wght@0,400;0,500;1,400","@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,500;1,400&display=swap');","fontFamily: { mono: ['JetBrains Mono', 'monospace'] }","Single monospace system: use ONLY JetBrains Mono (or SpaceMono-Regular as system fallback). Strict sizes: 12pt / 14pt / 16pt only — no in-between. Weight: 400 normal (bold ruins mono character). Line height: 1.2x font size for information density. Letter spacing: normal (monospaced auto-spacing). All UI labels uppercase. ASCII borders and text-based progress bars."
62,Kinetic Brutalism (Space Grotesk),"Geometric Sans (Single Dominant)",Space Grotesk,Space Grotesk,"kinetic, brutalist, aggressive, uppercase, oversized, display, motion, street, bold, high-energy, zine","Music/culture apps, sports platforms, brand flagship mobile, performance dashboards, underground product drops","https://fonts.google.com/share?selection.family=Space+Grotesk:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Space Grotesk', 'sans-serif'], body: ['Space Grotesk', 'sans-serif'] }","Dominant single-family system: Space Grotesk 700900 for ALL display. Scale: Hero 60120pt (windowWidth/375*size), Section 4050pt, Card titles 2832pt, Body 1820pt, Labels 12pt. ALL display/buttons/nav: UPPERCASE, letterSpacing -1 (large) / +2 (labels), lineHeight 0.91.1x. Use Inter as fallback. Font scale must use PixelRatio helper for responsive sizing."
63,Flat Design Mobile (System Bold),"Sans + Sans",Inter,Inter,"flat, clean, system, bold, geometric, cross-platform, icon, poster, minimal, functional, responsive","Cross-platform apps, dashboards, system UI, onboarding, marketing pages, informational apps, icon-heavy interfaces","https://fonts.google.com/share?selection.family=Inter:wght@400;600;700;800","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","System-first strategy: Inter as primary, falls back to system SF/Roboto on iOS/Android. Scale: Headlines fontWeight 800 letterSpacing -0.5; Subheadings fontWeight 600 fontSize 18; Body fontWeight 400 lineHeight 24; Labels fontWeight 700 uppercase letterSpacing 1. Thick weights carry all hierarchy since there are no shadows. Use aggressive size contrast (poster rule: body 16pt vs headline 40pt+). Avoid italic."
64,Material You MD3 (Roboto System),"Sans (System Default)",Roboto,Roboto,"material design 3, md3, android, google, tonal, friendly, rounded, accessible, adaptive","Android apps, cross-platform tools, productivity software, data-heavy B2B dashboards, enterprise mobile","https://fonts.google.com/share?selection.family=Roboto:ital,wght@0,300;0,400;0,500;0,700;1,400","@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;0,700;1,400&display=swap');","fontFamily: { sans: ['Roboto', 'sans-serif'] }","MD3 type scale: Display Large 56px/400/64px. Headline Large 32px/500/40px. Title Large 22px/500/28px. Body Large 16px/400/24px. Label Medium 12px/500/16px. Buttons and Labels: letterSpacing 0.1px. Use system Roboto on Android; load from Google Fonts for iOS parity. Never use custom weights beyond 300700."
65,Neo Brutalism Mobile (Space Grotesk Heavy),"Geometric Sans (Bold-Only)",Space Grotesk,Space Grotesk,"neo brutalism, pop art, loud, bold, heavy, stickers, mechanical, high contrast, cream, gen-z","Creative tools, Gen-Z marketing, e-commerce for youth culture, content portfolios, collage-style apps","https://fonts.google.com/share?selection.family=Space+Grotesk:wght@700","@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@700&display=swap');","fontFamily: { display: ['Space Grotesk', 'sans-serif'], body: ['Space Grotesk', 'sans-serif'] }","Strictly 700 (Bold) and 900 (Black/Heavy) ONLY — never Regular or Light. Display: 4864px. Heading: 2432px. Body: 1820px (stays heavy for brutalist density). Labels: 14px ALL CAPS letterSpacing 2. All buttons and navigation: uppercase. System bold as fallback. No italic, no thin weights."
66,Bold Typography Mobile (Inter-Tight Poster),"Sans + Serif (Display) + Mono","Inter","Playfair Display","bold typography, editorial, poster, near-black, vermillion, luxury, type-as-hero, manifesto, high-contrast","Creative brand flagships, reading platforms, event apps, flash pages, luxury mobile experiences","https://fonts.google.com/share?selection.family=Inter:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400|JetBrains+Mono:wght@400|Playfair+Display:ital@1","@import url('https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400&family=JetBrains+Mono:wght@400&family=Playfair+Display:ital@1&display=swap');","fontFamily: { display: ['Inter', 'sans-serif'], quote: ['Playfair Display', 'serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Inter 600800 for all UI (letterSpacing -1.5px heroes, -0.5px subheads). Playfair Display Italic ONLY for pull quotes. JetBrains Mono for labels and stats. Scale: 12px labels, 16px body, 22px sub, 32px section, 40px H2, 56px H1, 72px Hero Statement. 5:1 ratio H1:Body is mandatory. lineHeight 1.1 headlines, 1.6 body. Underlines (23pt accent) replace buttons for interactions."
67,Academia Mobile (Cormorant + Crimson + Cinzel),"Serif + Book Serif + Engraved (Triple Stack)","Cormorant Garamond","Crimson Pro","academia, library, mahogany, parchment, brass, scholarly, prestige, antique, victorian, leather","Knowledge management apps, scholarly reading tools, personal brand portfolios, RPG games, cultural community platforms","https://fonts.google.com/share?selection.family=Cinzel:wght@400;500;600|Cormorant+Garamond:ital,wght@0,300;0,500;0,700;1,300;1,500|Crimson+Pro:ital,wght@0,300;0,400;0,600;1,300;1,400","@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Cormorant+Garamond:ital,wght@0,300;0,500;0,700;1,300;1,500&family=Crimson+Pro:ital,wght@0,300;0,400;0,600;1,300;1,400&display=swap');","fontFamily: { heading: ['Cormorant Garamond', 'serif'], body: ['Crimson Pro', 'serif'], display: ['Cinzel', 'serif'] }","Triple-stack: Cormorant Garamond Medium for all headings (3240px tight leading). Crimson Pro Regular for body reading text (1618px, lineHeight 2426px). Cinzel SemiBold for ALL-CAPS labels, overlines, section prefixes (1012px, letterSpacing 23px). Drop caps: first letter 60px Cinzel in Brass #C9A962. Section prefix: VOLUME I/II/III in Cinzel 10px. NO sans-serif anywhere."
68,Cyberpunk Mobile (Orbitron + JetBrains Mono),"Tech Display + Mono","Orbitron","JetBrains Mono","cyberpunk, neon, glitch, hud, sci-fi, dark, matrix green, magenta, chamfered, tactical","Gaming companion apps, fintech/crypto, data visualization, dark brand apps, cyberpunk narrative games","https://fonts.google.com/share?selection.family=JetBrains+Mono:wght@400;500|Orbitron:wght@700;900","@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Orbitron:wght@700;900&display=swap');","fontFamily: { heading: ['Orbitron', 'sans-serif'], body: ['JetBrains Mono', 'monospace'] }","Dual-stack: Orbitron 700900 for H1 (42px uppercase letterSpacing 4, fontWeight 900). JetBrains Mono 400500 for all body/data text (14px letterSpacing 1). Labels: 10px uppercase opacity 0.7. Heading scale aggressive: H1 42px, H2 28px, Section 20px. Body 14px monospace only. NO mixed sans-serif. Fallback: monospace system font. Orbitron requires loading — use NativeWind or useFonts hook."
69,Web3 Bitcoin DeFi (Space Grotesk + Inter + Mono),"Geometric Sans + Sans + Mono (Triple)","Space Grotesk","Inter","web3, bitcoin, defi, digital gold, fintech, crypto, trustless, luminescent, precision, dark","DeFi protocols and wallets, NFT platforms, metaverse social apps, high-tech brand landing pages","https://fonts.google.com/share?selection.family=Inter:wght@400;500;600;700|JetBrains+Mono:wght@400;500|Space+Grotesk:wght@500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Space+Grotesk:wght@500;600;700&display=swap');","fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['Inter', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Space Grotesk 600700 for headings (geometric, technical character). Inter 400600 for all body and UI text (high legibility). JetBrains Mono Medium for all data/stats/prices/hashes (technical accuracy). Buttons: Inter Bold uppercase letterSpacing 1.5. Balance figures use MaskedView gradient text (orange→gold). Heading scale: H1 3642px, H2 2428px, body 1618px, mono labels 1214px."
70,Claymorphism Mobile (Nunito + DM Sans),"Display Rounded + Geometric Sans","Nunito","DM Sans","claymorphism, clay, rounded, playful, candy, bubbly, soft, 3d, children, education, tactile, spring, nunito, dm sans","Children education apps, teen social, brand mascot apps, creative tools, fintech gamification","https://fonts.google.com/share?selection.family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400|Nunito:ital,wght@0,700;0,800;0,900;1,700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400&family=Nunito:ital,wght@0,700;0,800;0,900;1,700&display=swap');","fontFamily: { display: ['Nunito', 'sans-serif'], body: ['DM Sans', 'sans-serif'] }","Dual-stack: Nunito Black (900) or ExtraBold (800) for ALL headings — rounded terminals are mandatory. DM Sans Medium (500) for body text — clean and geometric. Scale: Hero 48px lineHeight 52 letterSpacing -1. Section Title 32px lineHeight 38. Card Title 22px lineHeight 28. Body 16px lineHeight 24. Never use Nunito for body text (too decorative at small sizes). Never use weights below 700 for any heading. includeFontPadding: false on all Nunito Text components for vertical centering in rounded buttons."
71,Enterprise SaaS Mobile (Plus Jakarta Sans),"Geometric Sans (Single Family)","Plus Jakarta Sans","Plus Jakarta Sans","enterprise, saas, b2b, professional, indigo, modern, approachable, legible, ios dynamic type, android scaling","B2B SaaS apps, productivity tools, government and finance mobile apps, admin dashboards, enterprise onboarding","https://fonts.google.com/share?selection.family=Plus+Jakarta+Sans:ital,wght@0,400;0,600;0,700;0,800;1,400","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,600;0,700;0,800;1,400&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single-family system: Plus Jakarta Sans balances professional authority with mobile approachability. Weight scale: ExtraBold 800 for screen titles/hero (line height 1.11.2). Bold 700 for section headers. SemiBold 600 for card titles and buttons. Regular 400 for body text (line height 1.41.5). Must support iOS Dynamic Type and Android font scaling — never hardcode pixel sizes without respecting system font scale. Button text: uppercase, letterSpacing 0.5. Caption: 12px Regular. Muted: Slate 500 #64748B."
72,Sketch Hand-Drawn Mobile (Kalam + Patrick Hand),"Handwritten + Handwritten (Dual)","Kalam","Patrick Hand","sketch, hand-drawn, handwriting, human, imperfect, organic, paper, kalam, patrick hand, education, journal, creative","Journaling apps, prototype tools, children's picturebook apps, creative platforms, gamified puzzle apps","https://fonts.google.com/share?selection.family=Kalam:wght@400;700|Patrick+Hand","@import url('https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&family=Patrick+Hand&display=swap');","fontFamily: { heading: ['Kalam', 'cursive'], body: ['Patrick Hand', 'cursive'] }","Dual handwritten stack: Kalam Bold (700) for all headings — high visual weight, felt-tip marker aesthetic, conveys intentional messiness. Patrick Hand Regular for all body text — highly legible at mobile sizes while remaining distinctly human. Scale: Heading 2836px with lineHeight adjusted for descenders. Body 1618px lineHeight 1.5. Labels 14px. Vary font sizes slightly between adjacent elements for spontaneous feel. Avoid alignment: 'center' for long body text — left-aligned reads more naturally. Both fonts require useFonts loading in Expo. Never use these fonts for financial figures or legal text."
73,Neumorphism Mobile (Plus Jakarta Sans + System),"Geometric Sans (System Fallback)","Plus Jakarta Sans","Plus Jakarta Sans","neumorphism, soft ui, monochromatic, cool grey, minimal, physical, depth, ceramic, system font, utility","Smart home controls, minimal tools, aesthetic dashboards, health monitors, brand showcase pages","https://fonts.google.com/share?selection.family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,700;1,400","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,700;1,400&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single-family or System fallback: Plus Jakarta Sans Bold/Medium pairs beautifully with the monochromatic #E0E5EC surface — subtle geometry without competing with the depth effect. Heading: 2432px Bold (700), letterSpacing -0.5 for modern premium feel. Body: 16px Medium (500), lineHeight 1.4. Caption: 12px Regular (400). Use Text Primary #3D4852 (7.5:1 contrast against #E0E5EC) for all primary text. Use Text Muted #6B7280 (4.6:1 contrast) for secondary text. Accent color #6C63FF only on active labels or focus indicators. Never use italic or thin weights — they lose legibility against the embossed background. System (SF Pro / Roboto) is an acceptable fallback for performance-sensitive implementations."
1,Classic Elegant,Serif + Sans,Playfair Display,Inter,"elegant, luxury, sophisticated, timeless, premium, editorial","Luxury brands, fashion, spa, beauty, editorial, magazines, high-end e-commerce",https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap');,"fontFamily: { serif: ['Playfair Display', 'serif'], sans: ['Inter', 'sans-serif'] }",High contrast between elegant heading and clean body. Perfect for luxury/premium.
2,Modern Professional,Sans + Sans,Poppins,Open Sans,"modern, professional, clean, corporate, friendly, approachable","SaaS, corporate sites, business apps, startups, professional services",https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap');,"fontFamily: { heading: ['Poppins', 'sans-serif'], body: ['Open Sans', 'sans-serif'] }","Geometric Poppins for headings, humanist Open Sans for readability."
3,Tech Startup,Sans + Sans,Space Grotesk,DM Sans,"tech, startup, modern, innovative, bold, futuristic","Tech companies, startups, SaaS, developer tools, AI products",https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Grotesk:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');,"fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['DM Sans', 'sans-serif'] }","Space Grotesk has unique character, DM Sans is highly readable."
4,Editorial Classic,Serif + Serif,Cormorant Garamond,Libre Baskerville,"editorial, classic, literary, traditional, refined, bookish","Publishing, blogs, news sites, literary magazines, book covers",https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Libre+Baskerville:wght@400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Libre+Baskerville:wght@400;700&display=swap');,"fontFamily: { heading: ['Cormorant Garamond', 'serif'], body: ['Libre Baskerville', 'serif'] }",All-serif pairing for traditional editorial feel.
5,Minimal Swiss,Sans + Sans,Inter,Inter,"minimal, clean, swiss, functional, neutral, professional","Dashboards, admin panels, documentation, enterprise apps, design systems",https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');,"fontFamily: { sans: ['Inter', 'sans-serif'] }",Single font family with weight variations. Ultimate simplicity.
6,Playful Creative,Display + Sans,Fredoka,Nunito,"playful, friendly, fun, creative, warm, approachable","Children's apps, educational, gaming, creative tools, entertainment",https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Nunito:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Nunito:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Fredoka', 'sans-serif'], body: ['Nunito', 'sans-serif'] }","Rounded, friendly fonts perfect for playful UIs."
7,Bold Statement,Display + Sans,Bebas Neue,Source Sans 3,"bold, impactful, strong, dramatic, modern, headlines","Marketing sites, portfolios, agencies, event pages, sports",https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Source+Sans+3:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');,"fontFamily: { display: ['Bebas Neue', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }",Bebas Neue for large headlines only. All-caps display font.
8,Wellness Calm,Serif + Sans,Lora,Raleway,"calm, wellness, health, relaxing, natural, organic","Health apps, wellness, spa, meditation, yoga, organic brands",https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&family=Raleway:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&family=Raleway:wght@300;400;500;600;700&display=swap');,"fontFamily: { serif: ['Lora', 'serif'], sans: ['Raleway', 'sans-serif'] }",Lora's organic curves with Raleway's elegant simplicity.
9,Developer Mono,Mono + Sans,JetBrains Mono,IBM Plex Sans,"code, developer, technical, precise, functional, hacker","Developer tools, documentation, code editors, tech blogs, CLI apps",https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap');,"fontFamily: { mono: ['JetBrains Mono', 'monospace'], sans: ['IBM Plex Sans', 'sans-serif'] }","JetBrains for code, IBM Plex for UI. Developer-focused."
10,Retro Vintage,Display + Serif,Abril Fatface,Merriweather,"retro, vintage, nostalgic, dramatic, decorative, bold","Vintage brands, breweries, restaurants, creative portfolios, posters",https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Merriweather:wght@300;400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Merriweather:wght@300;400;700&display=swap');,"fontFamily: { display: ['Abril Fatface', 'serif'], body: ['Merriweather', 'serif'] }",Abril Fatface for hero headlines only. High-impact vintage feel.
11,Geometric Modern,Sans + Sans,Outfit,Work Sans,"geometric, modern, clean, balanced, contemporary, versatile","General purpose, portfolios, agencies, modern brands, landing pages",https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Work+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Work+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Work Sans', 'sans-serif'] }",Both geometric but Outfit more distinctive for headings.
12,Luxury Serif,Serif + Sans,Cormorant,Montserrat,"luxury, high-end, fashion, elegant, refined, premium","Fashion brands, luxury e-commerce, jewelry, high-end services",https://fonts.googleapis.com/css2?family=Cormorant:wght@400;500;600;700&family=Montserrat:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Cormorant:wght@400;500;600;700&family=Montserrat:wght@300;400;500;600;700&display=swap');,"fontFamily: { serif: ['Cormorant', 'serif'], sans: ['Montserrat', 'sans-serif'] }",Cormorant's elegance with Montserrat's geometric precision.
13,Friendly SaaS,Sans + Sans,Plus Jakarta Sans,Plus Jakarta Sans,"friendly, modern, saas, clean, approachable, professional","SaaS products, web apps, dashboards, B2B, productivity tools",https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }",Single versatile font. Modern alternative to Inter.
14,News Editorial,Serif + Sans,Newsreader,Roboto,"news, editorial, journalism, trustworthy, readable, informative","News sites, blogs, magazines, journalism, content-heavy sites",https://fonts.googleapis.com/css2?family=Newsreader:wght@400;500;600;700&family=Roboto:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Newsreader:wght@400;500;600;700&family=Roboto:wght@300;400;500;700&display=swap');,"fontFamily: { serif: ['Newsreader', 'serif'], sans: ['Roboto', 'sans-serif'] }",Newsreader designed for long-form reading. Roboto for UI.
15,Handwritten Charm,Script + Sans,Caveat,Quicksand,"handwritten, personal, friendly, casual, warm, charming","Personal blogs, invitations, creative portfolios, lifestyle brands",https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Quicksand:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Quicksand:wght@300;400;500;600;700&display=swap');,"fontFamily: { script: ['Caveat', 'cursive'], sans: ['Quicksand', 'sans-serif'] }",Use Caveat sparingly for accents. Quicksand for body.
16,Corporate Trust,Sans + Sans,Lexend,Source Sans 3,"corporate, trustworthy, accessible, readable, professional, clean","Enterprise, government, healthcare, finance, accessibility-focused",https://fonts.googleapis.com/css2?family=Lexend:wght@300;400;500;600;700&family=Source+Sans+3:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@300;400;500;600;700&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Lexend', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }",Lexend designed for readability. Excellent accessibility.
17,Brutalist Raw,Mono + Mono,Space Mono,Space Mono,"brutalist, raw, technical, monospace, minimal, stark","Brutalist designs, developer portfolios, experimental, tech art",https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');,"fontFamily: { mono: ['Space Mono', 'monospace'] }",All-mono for raw brutalist aesthetic. Limited weights.
18,Fashion Forward,Sans + Sans,Syne,Manrope,"fashion, avant-garde, creative, bold, artistic, edgy","Fashion brands, creative agencies, art galleries, design studios",https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&family=Syne:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&family=Syne:wght@400;500;600;700&display=swap');,"fontFamily: { heading: ['Syne', 'sans-serif'], body: ['Manrope', 'sans-serif'] }",Syne's unique character for headlines. Manrope for readability.
19,Soft Rounded,Sans + Sans,Varela Round,Nunito Sans,"soft, rounded, friendly, approachable, warm, gentle","Children's products, pet apps, friendly brands, wellness, soft UI",https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Varela+Round&display=swap,@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Varela+Round&display=swap');,"fontFamily: { heading: ['Varela Round', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }",Both rounded and friendly. Perfect for soft UI designs.
20,Premium Sans,Sans + Sans,Satoshi,General Sans,"premium, modern, clean, sophisticated, versatile, balanced","Premium brands, modern agencies, SaaS, portfolios, startups",https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap');,"fontFamily: { sans: ['DM Sans', 'sans-serif'] }",Note: Satoshi/General Sans on Fontshare. DM Sans as Google alternative.
21,Vietnamese Friendly,Sans + Sans,Be Vietnam Pro,Noto Sans,"vietnamese, international, readable, clean, multilingual, accessible","Vietnamese sites, multilingual apps, international products",https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { sans: ['Be Vietnam Pro', 'Noto Sans', 'sans-serif'] }",Be Vietnam Pro excellent Vietnamese support. Noto as fallback.
22,Japanese Elegant,Serif + Sans,Noto Serif JP,Noto Sans JP,"japanese, elegant, traditional, modern, multilingual, readable","Japanese sites, Japanese restaurants, cultural sites, anime/manga",https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&family=Noto+Serif+JP:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&family=Noto+Serif+JP:wght@400;500;600;700&display=swap');,"fontFamily: { serif: ['Noto Serif JP', 'serif'], sans: ['Noto Sans JP', 'sans-serif'] }",Noto fonts excellent Japanese support. Traditional + modern feel.
23,Korean Modern,Sans + Sans,Noto Sans KR,Noto Sans KR,"korean, modern, clean, professional, multilingual, readable","Korean sites, K-beauty, K-pop, Korean businesses, multilingual",https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap');,"fontFamily: { sans: ['Noto Sans KR', 'sans-serif'] }",Clean Korean typography. Single font with weight variations.
24,Chinese Traditional,Serif + Sans,Noto Serif TC,Noto Sans TC,"chinese, traditional, elegant, cultural, multilingual, readable","Traditional Chinese sites, cultural content, Taiwan/Hong Kong markets",https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&family=Noto+Serif+TC:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&family=Noto+Serif+TC:wght@400;500;600;700&display=swap');,"fontFamily: { serif: ['Noto Serif TC', 'serif'], sans: ['Noto Sans TC', 'sans-serif'] }",Traditional Chinese character support. Elegant pairing.
25,Chinese Simplified,Sans + Sans,Noto Sans SC,Noto Sans SC,"chinese, simplified, modern, professional, multilingual, readable","Simplified Chinese sites, mainland China market, business apps",https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');,"fontFamily: { sans: ['Noto Sans SC', 'sans-serif'] }",Simplified Chinese support. Clean modern look.
26,Arabic Elegant,Serif + Sans,Noto Naskh Arabic,Noto Sans Arabic,"arabic, elegant, traditional, cultural, RTL, readable","Arabic sites, Middle East market, Islamic content, bilingual sites",https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;500;600;700&family=Noto+Sans+Arabic:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;500;600;700&family=Noto+Sans+Arabic:wght@300;400;500;700&display=swap');,"fontFamily: { serif: ['Noto Naskh Arabic', 'serif'], sans: ['Noto Sans Arabic', 'sans-serif'] }","RTL support. Naskh for traditional, Sans for modern Arabic."
27,Thai Modern,Sans + Sans,Noto Sans Thai,Noto Sans Thai,"thai, modern, readable, clean, multilingual, accessible","Thai sites, Southeast Asia, tourism, Thai restaurants",https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;700&display=swap');,"fontFamily: { sans: ['Noto Sans Thai', 'sans-serif'] }",Clean Thai typography. Excellent readability.
28,Hebrew Modern,Sans + Sans,Noto Sans Hebrew,Noto Sans Hebrew,"hebrew, modern, RTL, clean, professional, readable","Hebrew sites, Israeli market, Jewish content, bilingual sites",https://fonts.googleapis.com/css2?family=Noto+Sans+Hebrew:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Hebrew:wght@300;400;500;700&display=swap');,"fontFamily: { sans: ['Noto Sans Hebrew', 'sans-serif'] }",RTL support. Clean modern Hebrew typography.
29,Legal Professional,Serif + Sans,EB Garamond,Lato,"legal, professional, traditional, trustworthy, formal, authoritative","Law firms, legal services, contracts, formal documents, government",https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500;600;700&family=Lato:wght@300;400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500;600;700&family=Lato:wght@300;400;700&display=swap');,"fontFamily: { serif: ['EB Garamond', 'serif'], sans: ['Lato', 'sans-serif'] }",EB Garamond for authority. Lato for clean body text.
30,Medical Clean,Sans + Sans,Figtree,Noto Sans,"medical, clean, accessible, professional, healthcare, trustworthy","Healthcare, medical clinics, pharma, health apps, accessibility",https://fonts.googleapis.com/css2?family=Figtree:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;700&display=swap');,"fontFamily: { heading: ['Figtree', 'sans-serif'], body: ['Noto Sans', 'sans-serif'] }","Clean, accessible fonts for medical contexts."
31,Financial Trust,Sans + Sans,IBM Plex Sans,IBM Plex Sans,"financial, trustworthy, professional, corporate, banking, serious","Banks, finance, insurance, investment, fintech, enterprise",https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { sans: ['IBM Plex Sans', 'sans-serif'] }",IBM Plex conveys trust and professionalism. Excellent for data.
32,Real Estate Luxury,Serif + Sans,Cinzel,Josefin Sans,"real estate, luxury, elegant, sophisticated, property, premium","Real estate, luxury properties, architecture, interior design",https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600;700&family=Josefin+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600;700&family=Josefin+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { serif: ['Cinzel', 'serif'], sans: ['Josefin Sans', 'sans-serif'] }",Cinzel's elegance for headlines. Josefin for modern body.
33,Restaurant Menu,Serif + Sans,Playfair Display SC,Karla,"restaurant, menu, culinary, elegant, foodie, hospitality","Restaurants, cafes, food blogs, culinary, hospitality",https://fonts.googleapis.com/css2?family=Karla:wght@300;400;500;600;700&family=Playfair+Display+SC:wght@400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Karla:wght@300;400;500;600;700&family=Playfair+Display+SC:wght@400;700&display=swap');,"fontFamily: { display: ['Playfair Display SC', 'serif'], sans: ['Karla', 'sans-serif'] }",Small caps Playfair for menu headers. Karla for descriptions.
34,Art Deco,Display + Sans,Poiret One,Didact Gothic,"art deco, vintage, 1920s, elegant, decorative, gatsby","Vintage events, art deco themes, luxury hotels, classic cocktails",https://fonts.googleapis.com/css2?family=Didact+Gothic&family=Poiret+One&display=swap,@import url('https://fonts.googleapis.com/css2?family=Didact+Gothic&family=Poiret+One&display=swap');,"fontFamily: { display: ['Poiret One', 'sans-serif'], sans: ['Didact Gothic', 'sans-serif'] }",Poiret One for art deco headlines only. Didact for body.
35,Magazine Style,Serif + Sans,Libre Bodoni,Public Sans,"magazine, editorial, publishing, refined, journalism, print","Magazines, online publications, editorial content, journalism",https://fonts.googleapis.com/css2?family=Libre+Bodoni:wght@400;500;600;700&family=Public+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Libre+Bodoni:wght@400;500;600;700&family=Public+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { serif: ['Libre Bodoni', 'serif'], sans: ['Public Sans', 'sans-serif'] }",Bodoni's editorial elegance. Public Sans for clean UI.
36,Crypto/Web3,Sans + Sans,Orbitron,Exo 2,"crypto, web3, futuristic, tech, blockchain, digital","Crypto platforms, NFT, blockchain, web3, futuristic tech",https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700&display=swap');,"fontFamily: { display: ['Orbitron', 'sans-serif'], body: ['Exo 2', 'sans-serif'] }",Orbitron for futuristic headers. Exo 2 for readable body.
37,Gaming Bold,Display + Sans,Russo One,Chakra Petch,"gaming, bold, action, esports, competitive, energetic","Gaming, esports, action games, competitive sports, entertainment",https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@300;400;500;600;700&family=Russo+One&display=swap,@import url('https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@300;400;500;600;700&family=Russo+One&display=swap');,"fontFamily: { display: ['Russo One', 'sans-serif'], body: ['Chakra Petch', 'sans-serif'] }",Russo One for impact. Chakra Petch for techy body text.
38,Indie/Craft,Display + Sans,Amatic SC,Cabin,"indie, craft, handmade, artisan, organic, creative","Craft brands, indie products, artisan, handmade, organic products",https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Cabin:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Cabin:wght@400;500;600;700&display=swap');,"fontFamily: { display: ['Amatic SC', 'sans-serif'], sans: ['Cabin', 'sans-serif'] }",Amatic for handwritten feel. Cabin for readable body.
39,Startup Bold,Sans + Sans,Clash Display,Satoshi,"startup, bold, modern, innovative, confident, dynamic","Startups, pitch decks, product launches, bold brands",https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Rubik', 'sans-serif'] }",Note: Clash Display on Fontshare. Outfit as Google alternative.
40,E-commerce Clean,Sans + Sans,Rubik,Nunito Sans,"ecommerce, clean, shopping, product, retail, conversion","E-commerce, online stores, product pages, retail, shopping",https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Rubik', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }",Clean readable fonts perfect for product descriptions.
41,Academic/Research,Serif + Sans,Crimson Pro,Atkinson Hyperlegible,"academic, research, scholarly, accessible, readable, educational","Universities, research papers, academic journals, educational",https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&family=Crimson+Pro:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&family=Crimson+Pro:wght@400;500;600;700&display=swap');,"fontFamily: { serif: ['Crimson Pro', 'serif'], sans: ['Atkinson Hyperlegible', 'sans-serif'] }",Crimson for scholarly headlines. Atkinson for accessibility.
42,Dashboard Data,Mono + Sans,Fira Code,Fira Sans,"dashboard, data, analytics, code, technical, precise","Dashboards, analytics, data visualization, admin panels",https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600;700&family=Fira+Sans:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600;700&family=Fira+Sans:wght@300;400;500;600;700&display=swap');,"fontFamily: { mono: ['Fira Code', 'monospace'], sans: ['Fira Sans', 'sans-serif'] }","Fira family cohesion. Code for data, Sans for labels."
43,Music/Entertainment,Display + Sans,Righteous,Poppins,"music, entertainment, fun, energetic, bold, performance","Music platforms, entertainment, events, festivals, performers",https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Righteous&display=swap,@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Righteous&display=swap');,"fontFamily: { display: ['Righteous', 'sans-serif'], sans: ['Poppins', 'sans-serif'] }",Righteous for bold entertainment headers. Poppins for body.
44,Minimalist Portfolio,Sans + Sans,Archivo,Space Grotesk,"minimal, portfolio, designer, creative, clean, artistic","Design portfolios, creative professionals, minimalist brands",https://fonts.googleapis.com/css2?family=Archivo:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Archivo:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap');,"fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['Archivo', 'sans-serif'] }",Space Grotesk for distinctive headers. Archivo for clean body.
45,Kids/Education,Display + Sans,Baloo 2,Comic Neue,"kids, education, playful, friendly, colorful, learning","Children's apps, educational games, kid-friendly content",https://fonts.googleapis.com/css2?family=Baloo+2:wght@400;500;600;700&family=Comic+Neue:wght@300;400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Baloo+2:wght@400;500;600;700&family=Comic+Neue:wght@300;400;700&display=swap');,"fontFamily: { display: ['Baloo 2', 'sans-serif'], sans: ['Comic Neue', 'sans-serif'] }","Fun, playful fonts for children. Comic Neue is readable comic style."
46,Wedding/Romance,Script + Serif,Great Vibes,Cormorant Infant,"wedding, romance, elegant, script, invitation, feminine","Wedding sites, invitations, romantic brands, bridal",https://fonts.googleapis.com/css2?family=Cormorant+Infant:wght@300;400;500;600;700&family=Great+Vibes&display=swap,@import url('https://fonts.googleapis.com/css2?family=Cormorant+Infant:wght@300;400;500;600;700&family=Great+Vibes&display=swap');,"fontFamily: { script: ['Great Vibes', 'cursive'], serif: ['Cormorant Infant', 'serif'] }",Great Vibes for elegant accents. Cormorant for readable text.
47,Science/Tech,Sans + Sans,Exo,Roboto Mono,"science, technology, research, data, futuristic, precise","Science, research, tech documentation, data-heavy sites",https://fonts.googleapis.com/css2?family=Exo:wght@300;400;500;600;700&family=Roboto+Mono:wght@300;400;500;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Exo:wght@300;400;500;600;700&family=Roboto+Mono:wght@300;400;500;700&display=swap');,"fontFamily: { sans: ['Exo', 'sans-serif'], mono: ['Roboto Mono', 'monospace'] }",Exo for modern tech feel. Roboto Mono for code/data.
48,Accessibility First,Sans + Sans,Atkinson Hyperlegible,Atkinson Hyperlegible,"accessible, readable, inclusive, WCAG, dyslexia-friendly, clear","Accessibility-critical sites, government, healthcare, inclusive design",https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap');,"fontFamily: { sans: ['Atkinson Hyperlegible', 'sans-serif'] }",Designed for maximum legibility. Excellent for accessibility.
49,Sports/Fitness,Sans + Sans,Barlow Condensed,Barlow,"sports, fitness, athletic, energetic, condensed, action","Sports, fitness, gyms, athletic brands, competition",https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600;700&family=Barlow:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600;700&family=Barlow:wght@300;400;500;600;700&display=swap');,"fontFamily: { display: ['Barlow Condensed', 'sans-serif'], body: ['Barlow', 'sans-serif'] }",Condensed for impact headlines. Regular Barlow for body.
50,Luxury Minimalist,Serif + Sans,Bodoni Moda,Jost,"luxury, minimalist, high-end, sophisticated, refined, premium","Luxury minimalist brands, high-end fashion, premium products",https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@400;500;600;700&family=Jost:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@400;500;600;700&family=Jost:wght@300;400;500;600;700&display=swap');,"fontFamily: { serif: ['Bodoni Moda', 'serif'], sans: ['Jost', 'sans-serif'] }",Bodoni's high contrast elegance. Jost for geometric body.
51,Tech/HUD Mono,Mono + Mono,Share Tech Mono,Fira Code,"tech, futuristic, hud, sci-fi, data, monospaced, precise","Sci-fi interfaces, developer tools, cybersecurity, dashboards",https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500;600;700&family=Share+Tech+Mono&display=swap,@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500;600;700&family=Share+Tech+Mono&display=swap');,"fontFamily: { hud: ['Share Tech Mono', 'monospace'], code: ['Fira Code', 'monospace'] }",Share Tech Mono has that classic sci-fi look.
52,Pixel Retro,Display + Sans,Press Start 2P,VT323,"pixel, retro, gaming, 8-bit, nostalgic, arcade","Pixel art games, retro websites, creative portfolios",https://fonts.googleapis.com/css2?family=Press+Start+2P&family=VT323&display=swap,@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&family=VT323&display=swap');,"fontFamily: { pixel: ['Press Start 2P', 'cursive'], terminal: ['VT323', 'monospace'] }",Press Start 2P is very wide/large. VT323 is better for body text.
53,Neubrutalist Bold,Display + Sans,Lexend Mega,Public Sans,"bold, neubrutalist, loud, strong, geometric, quirky","Neubrutalist designs, Gen Z brands, bold marketing",https://fonts.googleapis.com/css2?family=Lexend+Mega:wght@100..900&family=Public+Sans:wght@100..900&display=swap,@import url('https://fonts.googleapis.com/css2?family=Lexend+Mega:wght@100..900&family=Public+Sans:wght@100..900&display=swap');,"fontFamily: { mega: ['Lexend Mega', 'sans-serif'], body: ['Public Sans', 'sans-serif'] }",Lexend Mega has distinct character and variable weight.
54,Academic/Archival,Serif + Serif,EB Garamond,Crimson Text,"academic, old-school, university, research, serious, traditional","University sites, archives, research papers, history",https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600;700&family=EB+Garamond:wght@400;500;600;700;800&display=swap,@import url('https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600;700&family=EB+Garamond:wght@400;500;600;700;800&display=swap');,"fontFamily: { classic: ['EB Garamond', 'serif'], text: ['Crimson Text', 'serif'] }",Classic academic aesthetic. Very legible.
55,Spatial Clear,Sans + Sans,Inter,Inter,"spatial, legible, glass, system, clean, neutral","Spatial computing, AR/VR, glassmorphism interfaces",https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');,"fontFamily: { sans: ['Inter', 'sans-serif'] }",Optimized for readability on dynamic backgrounds.
56,Kinetic Motion,Display + Mono,Syncopate,Space Mono,"kinetic, motion, futuristic, speed, wide, tech","Music festivals, automotive, high-energy brands",https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syncopate:wght@400;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syncopate:wght@400;700&display=swap');,"fontFamily: { display: ['Syncopate', 'sans-serif'], mono: ['Space Mono', 'monospace'] }",Syncopate's wide stance works well with motion effects.
57,Gen Z Brutal,Display + Sans,Anton,Epilogue,"brutal, loud, shouty, meme, internet, bold","Gen Z marketing, streetwear, viral campaigns",https://fonts.googleapis.com/css2?family=Anton&family=Epilogue:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Anton&family=Epilogue:wght@400;500;600;700&display=swap');,"fontFamily: { display: ['Anton', 'sans-serif'], body: ['Epilogue', 'sans-serif'] }",Anton is impactful and condensed. Good for stickers/badges.
58,Bauhaus Geometric,Geometric Sans + Single Weight,Outfit,Outfit,"bauhaus, geometric, constructivist, bold, uppercase, architectural, mechanical, poster, tactile","Bauhaus mobile apps, bold editorial mobile, design-forward branding apps, art/culture platforms",https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;700;900&display=swap,@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;700;900&display=swap');,"fontFamily: { display: ['Outfit', 'sans-serif'], body: ['Outfit', 'sans-serif'] }",Single-family system: Outfit 900 uppercase tracking-tighter for heroes; Outfit 700 uppercase for buttons/nav; Outfit 500 for body. Scale aggressively: text-4xltext-5xl headlines on mobile.
59,Minimalist Monochrome Editorial,Serif + Serif + Mono (Triple Stack),Playfair Display,Source Serif 4,"monochrome, editorial, austere, typographic, pocket manifesto, luxury, high contrast, brutalist mobile","Luxury fashion mobile apps, editorial publications, digital exhibitions, portfolio apps, high-contrast e-reader aesthetics","https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400|Source+Serif+4:ital,wght@0,300;0,400;0,600;1,300","@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&family=Source+Serif+4:ital,wght@0,300;0,400;0,600;1,300&display=swap');","fontFamily: { display: ['Playfair Display', 'serif'], body: ['Source Serif 4', 'serif'], mono: ['JetBrains Mono', 'monospace'] }",Triple stack: Playfair Display 900 tracking-tighter leading-[0.9] for heroes (text-5xltext-6xl breaks words graphically). Source Serif 4 300600 for body legibility. JetBrains Mono 400500 uppercase tracking-widest for tags/dates/labels. NO UI sans-serif — 100% serif/mono.
60,Modern Dark Cinema (Inter System),Sans + Mono,Inter,Inter,"dark, cinematic, technical, precision, clean, premium, developer, professional, high-end utility","Developer tools, fintech/trading, AI dashboards, streaming platforms, high-end productivity apps",https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');,"fontFamily: { sans: ['Inter', 'sans-serif'] }","Single-family precision system: Inter 700 (-1.5 tracking) for Display 48pt; Inter 600 (-0.5 tracking) for H1 32pt / H2 24pt; Inter 400 for body 16pt; Inter 500 uppercase +1.2 tracking for labels/mono. Gradient text via mask-view + react-native-linear-gradient (#FFFFFF → rgba(255,255,255,0.7)) on major headers."
61,SaaS Mobile Boutique (Calistoga + Inter),Display Serif + Sans + Mono,Calistoga,Inter,"saas, boutique, electric, warm, editorial, bold, premium, fintech, business, dual font, human warmth","B2B SaaS mobile, fintech apps, analytics dashboards, marketing tools, operations platforms",https://fonts.googleapis.com/css2?family=Calistoga:ital@0;1&family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap,@import url('https://fonts.googleapis.com/css2?family=Calistoga:ital@0;1&family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');,"fontFamily: { display: ['Calistoga', 'serif'], body: ['Inter', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Calistoga (adds human warmth) for heroes 3642pt leading-1.1; Inter 400600 for body/UI 1618pt; JetBrains Mono 12pt uppercase tracking-[1.5] for data labels and section badges. Scale: Hero 3642pt, Section H2 2832pt, Body 1618pt, Label 12pt. Avoid italic Calistoga except editorial callouts."
62,Terminal CLI Monospace,Mono + Mono (Single Family),JetBrains Mono,JetBrains Mono,"terminal, cli, hacker, monospace, matrix, developer, retro-future, command line, precision, OLED","Developer tools, Web3/blockchain apps, hacker aesthetic, sci-fi games, ARG, security tools, geek-culture portfolios","https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,500;1,400","@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,500;1,400&display=swap');","fontFamily: { mono: ['JetBrains Mono', 'monospace'] }",Single monospace system: use ONLY JetBrains Mono (or SpaceMono-Regular as system fallback). Strict sizes: 12pt / 14pt / 16pt only — no in-between. Weight: 400 normal (bold ruins mono character). Line height: 1.2x font size for information density. Letter spacing: normal (monospaced auto-spacing). All UI labels uppercase. ASCII borders and text-based progress bars.
63,Kinetic Brutalism (Space Grotesk),Geometric Sans (Single Dominant),Space Grotesk,Space Grotesk,"kinetic, brutalist, aggressive, uppercase, oversized, display, motion, street, bold, high-energy, zine","Music/culture apps, sports platforms, brand flagship mobile, performance dashboards, underground product drops",https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap');,"fontFamily: { display: ['Space Grotesk', 'sans-serif'], body: ['Space Grotesk', 'sans-serif'] }","Dominant single-family system: Space Grotesk 700900 for ALL display. Scale: Hero 60120pt (windowWidth/375*size), Section 4050pt, Card titles 2832pt, Body 1820pt, Labels 12pt. ALL display/buttons/nav: UPPERCASE, letterSpacing -1 (large) / +2 (labels), lineHeight 0.91.1x. Use Inter as fallback. Font scale must use PixelRatio helper for responsive sizing."
64,Flat Design Mobile (System Bold),Sans + Sans,Inter,Inter,"flat, clean, system, bold, geometric, cross-platform, icon, poster, minimal, functional, responsive","Cross-platform apps, dashboards, system UI, onboarding, marketing pages, informational apps, icon-heavy interfaces",https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');,"fontFamily: { sans: ['Inter', 'sans-serif'] }","System-first strategy: Inter as primary, falls back to system SF/Roboto on iOS/Android. Scale: Headlines fontWeight 800 letterSpacing -0.5; Subheadings fontWeight 600 fontSize 18; Body fontWeight 400 lineHeight 24; Labels fontWeight 700 uppercase letterSpacing 1. Thick weights carry all hierarchy since there are no shadows. Use aggressive size contrast (poster rule: body 16pt vs headline 40pt+). Avoid italic."
65,Material You MD3 (Roboto System),Sans (System Default),Roboto,Roboto,"material design 3, md3, android, google, tonal, friendly, rounded, accessible, adaptive","Android apps, cross-platform tools, productivity software, data-heavy B2B dashboards, enterprise mobile","https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;0,700;1,400","@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;0,700;1,400&display=swap');","fontFamily: { sans: ['Roboto', 'sans-serif'] }",MD3 type scale: Display Large 56px/400/64px. Headline Large 32px/500/40px. Title Large 22px/500/28px. Body Large 16px/400/24px. Label Medium 12px/500/16px. Buttons and Labels: letterSpacing 0.1px. Use system Roboto on Android; load from Google Fonts for iOS parity. Never use custom weights beyond 300700.
66,Neo Brutalism Mobile (Space Grotesk Heavy),Geometric Sans (Bold-Only),Space Grotesk,Space Grotesk,"neo brutalism, pop art, loud, bold, heavy, stickers, mechanical, high contrast, cream, gen-z","Creative tools, Gen-Z marketing, e-commerce for youth culture, content portfolios, collage-style apps",https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@700&display=swap');,"fontFamily: { display: ['Space Grotesk', 'sans-serif'], body: ['Space Grotesk', 'sans-serif'] }","Strictly 700 (Bold) and 900 (Black/Heavy) ONLY — never Regular or Light. Display: 4864px. Heading: 2432px. Body: 1820px (stays heavy for brutalist density). Labels: 14px ALL CAPS letterSpacing 2. All buttons and navigation: uppercase. System bold as fallback. No italic, no thin weights."
67,Bold Typography Mobile (Inter-Tight Poster),Sans + Serif (Display) + Mono,Inter,Playfair Display,"bold typography, editorial, poster, near-black, vermillion, luxury, type-as-hero, manifesto, high-contrast","Creative brand flagships, reading platforms, event apps, flash pages, luxury mobile experiences","https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400|JetBrains+Mono:wght@400|Playfair+Display:ital@1","@import url('https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400&family=JetBrains+Mono:wght@400&family=Playfair+Display:ital@1&display=swap');","fontFamily: { display: ['Inter', 'sans-serif'], quote: ['Playfair Display', 'serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Inter 600800 for all UI (letterSpacing -1.5px heroes, -0.5px subheads). Playfair Display Italic ONLY for pull quotes. JetBrains Mono for labels and stats. Scale: 12px labels, 16px body, 22px sub, 32px section, 40px H2, 56px H1, 72px Hero Statement. 5:1 ratio H1:Body is mandatory. lineHeight 1.1 headlines, 1.6 body. Underlines (23pt accent) replace buttons for interactions."
68,Academia Mobile (Cormorant + Crimson + Cinzel),Serif + Book Serif + Engraved (Triple Stack),Cormorant Garamond,Crimson Pro,"academia, library, mahogany, parchment, brass, scholarly, prestige, antique, victorian, leather","Knowledge management apps, scholarly reading tools, personal brand portfolios, RPG games, cultural community platforms","https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Cormorant+Garamond:ital,wght@0,300;0,500;0,700;1,300;1,500|Crimson+Pro:ital,wght@0,300;0,400;0,600;1,300;1,400","@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Cormorant+Garamond:ital,wght@0,300;0,500;0,700;1,300;1,500&family=Crimson+Pro:ital,wght@0,300;0,400;0,600;1,300;1,400&display=swap');","fontFamily: { heading: ['Cormorant Garamond', 'serif'], body: ['Crimson Pro', 'serif'], display: ['Cinzel', 'serif'] }","Triple-stack: Cormorant Garamond Medium for all headings (3240px tight leading). Crimson Pro Regular for body reading text (1618px, lineHeight 2426px). Cinzel SemiBold for ALL-CAPS labels, overlines, section prefixes (1012px, letterSpacing 23px). Drop caps: first letter 60px Cinzel in Brass #C9A962. Section prefix: VOLUME I/II/III in Cinzel 10px. NO sans-serif anywhere."
69,Cyberpunk Mobile (Orbitron + JetBrains Mono),Tech Display + Mono,Orbitron,JetBrains Mono,"cyberpunk, neon, glitch, hud, sci-fi, dark, matrix green, magenta, chamfered, tactical","Gaming companion apps, fintech/crypto, data visualization, dark brand apps, cyberpunk narrative games",https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Orbitron:wght@700;900&display=swap,@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Orbitron:wght@700;900&display=swap');,"fontFamily: { heading: ['Orbitron', 'sans-serif'], body: ['JetBrains Mono', 'monospace'] }","Dual-stack: Orbitron 700900 for H1 (42px uppercase letterSpacing 4, fontWeight 900). JetBrains Mono 400500 for all body/data text (14px letterSpacing 1). Labels: 10px uppercase opacity 0.7. Heading scale aggressive: H1 42px, H2 28px, Section 20px. Body 14px monospace only. NO mixed sans-serif. Fallback: monospace system font. Orbitron requires loading — use NativeWind or useFonts hook."
70,Web3 Bitcoin DeFi (Space Grotesk + Inter + Mono),Geometric Sans + Sans + Mono (Triple),Space Grotesk,Inter,"web3, bitcoin, defi, digital gold, fintech, crypto, trustless, luminescent, precision, dark","DeFi protocols and wallets, NFT platforms, metaverse social apps, high-tech brand landing pages",https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Space+Grotesk:wght@500;600;700&display=swap,@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Space+Grotesk:wght@500;600;700&display=swap');,"fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['Inter', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'] }","Tri-stack: Space Grotesk 600700 for headings (geometric, technical character). Inter 400600 for all body and UI text (high legibility). JetBrains Mono Medium for all data/stats/prices/hashes (technical accuracy). Buttons: Inter Bold uppercase letterSpacing 1.5. Balance figures use MaskedView gradient text (orange→gold). Heading scale: H1 3642px, H2 2428px, body 1618px, mono labels 1214px."
71,Claymorphism Mobile (Nunito + DM Sans),Display Rounded + Geometric Sans,Nunito,DM Sans,"claymorphism, clay, rounded, playful, candy, bubbly, soft, 3d, children, education, tactile, spring, nunito, dm sans","Children education apps, teen social, brand mascot apps, creative tools, fintech gamification","https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400|Nunito:ital,wght@0,700;0,800;0,900;1,700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400&family=Nunito:ital,wght@0,700;0,800;0,900;1,700&display=swap');","fontFamily: { display: ['Nunito', 'sans-serif'], body: ['DM Sans', 'sans-serif'] }",Dual-stack: Nunito Black (900) or ExtraBold (800) for ALL headings — rounded terminals are mandatory. DM Sans Medium (500) for body text — clean and geometric. Scale: Hero 48px lineHeight 52 letterSpacing -1. Section Title 32px lineHeight 38. Card Title 22px lineHeight 28. Body 16px lineHeight 24. Never use Nunito for body text (too decorative at small sizes). Never use weights below 700 for any heading. includeFontPadding: false on all Nunito Text components for vertical centering in rounded buttons.
72,Enterprise SaaS Mobile (Plus Jakarta Sans),Geometric Sans (Single Family),Plus Jakarta Sans,Plus Jakarta Sans,"enterprise, saas, b2b, professional, indigo, modern, approachable, legible, ios dynamic type, android scaling","B2B SaaS apps, productivity tools, government and finance mobile apps, admin dashboards, enterprise onboarding","https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,600;0,700;0,800;1,400","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,600;0,700;0,800;1,400&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single-family system: Plus Jakarta Sans balances professional authority with mobile approachability. Weight scale: ExtraBold 800 for screen titles/hero (line height 1.11.2). Bold 700 for section headers. SemiBold 600 for card titles and buttons. Regular 400 for body text (line height 1.41.5). Must support iOS Dynamic Type and Android font scaling — never hardcode pixel sizes without respecting system font scale. Button text: uppercase, letterSpacing 0.5. Caption: 12px Regular. Muted: Slate 500 #64748B."
73,Sketch Hand-Drawn Mobile (Kalam + Patrick Hand),Handwritten + Handwritten (Dual),Kalam,Patrick Hand,"sketch, hand-drawn, handwriting, human, imperfect, organic, paper, kalam, patrick hand, education, journal, creative","Journaling apps, prototype tools, children's picturebook apps, creative platforms, gamified puzzle apps",https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&family=Patrick+Hand&display=swap,@import url('https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&family=Patrick+Hand&display=swap');,"fontFamily: { heading: ['Kalam', 'cursive'], body: ['Patrick Hand', 'cursive'] }","Dual handwritten stack: Kalam Bold (700) for all headings — high visual weight, felt-tip marker aesthetic, conveys intentional messiness. Patrick Hand Regular for all body text — highly legible at mobile sizes while remaining distinctly human. Scale: Heading 2836px with lineHeight adjusted for descenders. Body 1618px lineHeight 1.5. Labels 14px. Vary font sizes slightly between adjacent elements for spontaneous feel. Avoid alignment: 'center' for long body text — left-aligned reads more naturally. Both fonts require useFonts loading in Expo. Never use these fonts for financial figures or legal text."
74,Neumorphism Mobile (Plus Jakarta Sans + System),Geometric Sans (System Fallback),Plus Jakarta Sans,Plus Jakarta Sans,"neumorphism, soft ui, monochromatic, cool grey, minimal, physical, depth, ceramic, system font, utility","Smart home controls, minimal tools, aesthetic dashboards, health monitors, brand showcase pages","https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,700;1,400","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,700;1,400&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single-family or System fallback: Plus Jakarta Sans Bold/Medium pairs beautifully with the monochromatic #E0E5EC surface — subtle geometry without competing with the depth effect. Heading: 2432px Bold (700), letterSpacing -0.5 for modern premium feel. Body: 16px Medium (500), lineHeight 1.4. Caption: 12px Regular (400). Use Text Primary #3D4852 (7.5:1 contrast against #E0E5EC) for all primary text. Use Text Muted #6B7280 (4.6:1 contrast) for secondary text. Accent color #6C63FF only on active labels or focus indicators. Never use italic or thin weights — they lose legibility against the embossed background. System (SF Pro / Roboto) is an acceptable fallback for performance-sensitive implementations."

Can't render this file because it contains an unexpected character in line 58 and column 487.

View File

@ -0,0 +1,109 @@
# Common Rules for Professional UI + Pre-Delivery Checklist
Load this file before final delivery of native/mobile app UI (iOS/Android/React Native/Flutter), or when the user reports the UI "doesn't look professional" and the cause isn't obvious from the priority table in SKILL.md.
**Scope notice:** everything below targets native/mobile app UI. For web/desktop interaction patterns, use `references/quick-reference.md` (stack-agnostic) instead — these tables assume touch targets, safe areas, and platform gesture conventions that don't apply 1:1 to desktop web.
These are frequently overlooked issues that make UI look unprofessional.
## Icons & Visual Elements
| Rule | Standard | Avoid | Why It Matters |
|------|----------|--------|----------------|
| **No Emoji as Structural Icons** | Use vector-based icons (e.g., Lucide, react-native-vector-icons, @expo/vector-icons). | Using emojis (🎨 🚀 ⚙️) for navigation, settings, or system controls. | Emojis are font-dependent, inconsistent across platforms, and cannot be controlled via design tokens. |
| **Vector-Only Assets** | Use SVG or platform vector icons that scale cleanly and support theming. | Raster PNG icons that blur or pixelate. | Ensures scalability, crisp rendering, and dark/light mode adaptability. |
| **Stable Interaction States** | Use color, opacity, or elevation transitions for press states without changing layout bounds. | Layout-shifting transforms that move surrounding content or trigger visual jitter. | Prevents unstable interactions and preserves smooth motion/perceived quality on mobile. |
| **Correct Brand Logos** | Use official brand assets and follow their usage guidelines (spacing, color, clear space). | Guessing logo paths, recoloring unofficially, or modifying proportions. | Prevents brand misuse and ensures legal/platform compliance. |
| **Consistent Icon Sizing** | Define icon sizes as design tokens (e.g., icon-sm, icon-md = 24pt, icon-lg). | Mixing arbitrary values like 20pt / 24pt / 28pt randomly. | Maintains rhythm and visual hierarchy across the interface. |
| **Stroke Consistency** | Use a consistent stroke width within the same visual layer (e.g., 1.5px or 2px). | Mixing thick and thin stroke styles arbitrarily. | Inconsistent strokes reduce perceived polish and cohesion. |
| **Filled vs Outline Discipline** | Use one icon style per hierarchy level. | Mixing filled and outline icons at the same hierarchy level. | Maintains semantic clarity and stylistic coherence. |
| **Touch Target Minimum** | Minimum 44×44pt interactive area (use hitSlop if icon is smaller). | Small icons without expanded tap area. | Meets accessibility and platform usability standards. |
| **Icon Alignment** | Align icons to text baseline and maintain consistent padding. | Misaligned icons or inconsistent spacing around them. | Prevents subtle visual imbalance that reduces perceived quality. |
| **Icon Contrast** | Follow WCAG contrast standards: 4.5:1 for small elements, 3:1 minimum for larger UI glyphs. | Low-contrast icons that blend into the background. | Ensures accessibility in both light and dark modes. |
## Interaction (App)
| Rule | Do | Don't |
|------|----|----- |
| **Tap feedback** | Provide clear pressed feedback (ripple/opacity/elevation) within 80-150ms | No visual response on tap |
| **Animation timing** | Keep micro-interactions around 150-300ms with platform-native easing | Instant transitions or slow animations (>500ms) |
| **Accessibility focus** | Ensure screen reader focus order matches visual order and labels are descriptive | Unlabeled controls or confusing focus traversal |
| **Disabled state clarity** | Use disabled semantics (`disabled`/native disabled props), reduced emphasis, and no tap action | Controls that look tappable but do nothing |
| **Touch target minimum** | Keep tap areas >=44x44pt (iOS) or >=48x48dp (Android), expand hit area when icon is smaller | Tiny tap targets or icon-only hit areas without padding |
| **Gesture conflict prevention** | Keep one primary gesture per region and avoid nested tap/drag conflicts | Overlapping gestures causing accidental actions |
| **Semantic native controls** | Prefer native interactive primitives (`Button`, `Pressable`, platform equivalents) with proper accessibility roles | Generic containers used as primary controls without semantics |
## Light/Dark Mode Contrast
| Rule | Do | Don't |
|------|----|----- |
| **Surface readability (light)** | Keep cards/surfaces clearly separated from background with sufficient opacity/elevation | Overly transparent surfaces that blur hierarchy |
| **Text contrast (light)** | Maintain body text contrast >=4.5:1 against light surfaces | Low-contrast gray body text |
| **Text contrast (dark)** | Maintain primary text contrast >=4.5:1 and secondary text >=3:1 on dark surfaces | Dark mode text that blends into background |
| **Border and divider visibility** | Ensure separators are visible in both themes (not just light mode) | Theme-specific borders disappearing in one mode |
| **State contrast parity** | Keep pressed/focused/disabled states equally distinguishable in light and dark themes | Defining interaction states for one theme only |
| **Token-driven theming** | Use semantic color tokens mapped per theme across app surfaces/text/icons | Hardcoded per-screen hex values |
| **Scrim and modal legibility** | Use a modal scrim strong enough to isolate foreground content (typically 40-60% black) | Weak scrim that leaves background visually competing |
## Layout & Spacing
| Rule | Do | Don't |
|------|----|----- |
| **Safe-area compliance** | Respect top/bottom safe areas for all fixed headers, tab bars, and CTA bars | Placing fixed UI under notch, status bar, or gesture area |
| **System bar clearance** | Add spacing for status/navigation bars and gesture home indicator | Let tappable content collide with OS chrome |
| **Consistent content width** | Keep predictable content width per device class (phone/tablet) | Mixing arbitrary widths between screens |
| **8dp spacing rhythm** | Use a consistent 4/8dp spacing system for padding/gaps/section spacing | Random spacing increments with no rhythm |
| **Readable text measure** | Keep long-form text readable on large devices (avoid edge-to-edge paragraphs on tablets) | Full-width long text that hurts readability |
| **Section spacing hierarchy** | Define clear vertical rhythm tiers (e.g., 16/24/32/48) by hierarchy | Similar UI levels with inconsistent spacing |
| **Adaptive gutters by breakpoint** | Increase horizontal insets on larger widths and in landscape | Same narrow gutter on all device sizes/orientations |
| **Scroll and fixed element coexistence** | Add bottom/top content insets so lists are not hidden behind fixed bars | Scroll content obscured by sticky headers/footers |
---
## Pre-Delivery Checklist (canonical — the only one)
Before delivering app UI code, verify every item below. Start with the process steps, then the per-area checkboxes.
### Process
- [ ] Ran `--domain ux "animation accessibility z-index loading"` as a validation pass before implementation
- [ ] Reviewed `quick-reference.md` §1§3 (CRITICAL + HIGH) as a final pass
- [ ] Tested on 375px (small phone) and in landscape orientation
- [ ] Verified behavior with **reduced-motion** enabled and **Dynamic Type**/largest system text size
- [ ] Checked dark mode contrast independently (never assume light-mode values carry over)
- [ ] Confirmed all touch targets ≥44pt and no content hidden behind safe areas
### Visual Quality
- [ ] No emojis used as icons (use SVG instead)
- [ ] All icons come from a consistent icon family and style
- [ ] Official brand assets are used with correct proportions and clear space
- [ ] Pressed-state visuals do not shift layout bounds or cause jitter
- [ ] Semantic theme tokens are used consistently (no ad-hoc per-screen hardcoded colors)
### Interaction
- [ ] All tappable elements provide clear pressed feedback (ripple/opacity/elevation)
- [ ] Touch targets meet minimum size (>=44x44pt iOS, >=48x48dp Android)
- [ ] Micro-interaction timing stays in the 150-300ms range with native-feeling easing
- [ ] Disabled states are visually clear and non-interactive
- [ ] Screen reader focus order matches visual order, and interactive labels are descriptive
- [ ] Gesture regions avoid nested/conflicting interactions (tap/drag/back-swipe conflicts)
### Light/Dark Mode
- [ ] Primary text contrast >=4.5:1 in both light and dark mode
- [ ] Secondary text contrast >=3:1 in both light and dark mode
- [ ] Dividers/borders and interaction states are distinguishable in both modes
- [ ] Modal/drawer scrim opacity is strong enough to preserve foreground legibility (typically 40-60% black)
- [ ] Both themes are tested before delivery (not inferred from a single theme)
### Layout
- [ ] Safe areas are respected for headers, tab bars, and bottom CTA bars
- [ ] Scroll content is not hidden behind fixed/sticky bars
- [ ] Verified on small phone, large phone, and tablet (portrait + landscape)
- [ ] Horizontal insets/gutters adapt correctly by device size and orientation
- [ ] 4/8dp spacing rhythm is maintained across component, section, and page levels
- [ ] Long-form text measure remains readable on larger devices (no edge-to-edge paragraphs)
### Accessibility
- [ ] All meaningful images/icons have accessibility labels
- [ ] Form fields have labels, hints, and clear error messages
- [ ] Color is not the only indicator
- [ ] Reduced motion and dynamic text size are supported without layout breakage

View File

@ -0,0 +1,240 @@
# Quick Reference — Full Rule Set (all 10 categories)
Load this file when doing a UI review/audit pass, or when you need the full checklist for a category beyond the priority table in SKILL.md. Each rule is also present verbatim in `data/ux-guidelines.csv` / `data/app-interface.csv` and is reachable via `--domain ux` / `--domain web` search — this file is a static index for quick scanning without a search round-trip.
## Quick Reference
### 1. Accessibility (CRITICAL)
- `color-contrast` - Minimum 4.5:1 ratio for normal text (large text 3:1); Material Design
- `focus-states` - Visible focus rings on interactive elements (24px; Apple HIG, MD)
- `alt-text` - Descriptive alt text for meaningful images
- `aria-labels` - aria-label for icon-only buttons; accessibilityLabel in native (Apple HIG)
- `keyboard-nav` - Tab order matches visual order; full keyboard support (Apple HIG)
- `form-labels` - Use label with for attribute
- `skip-links` - Skip to main content for keyboard users
- `heading-hierarchy` - Sequential h1→h6, no level skip
- `color-not-only` - Don't convey info by color alone (add icon/text)
- `dynamic-type` - Support system text scaling; avoid truncation as text grows (Apple Dynamic Type, MD)
- `reduced-motion` - Respect prefers-reduced-motion; reduce/disable animations when requested (Apple Reduced Motion API, MD)
- `voiceover-sr` - Meaningful accessibilityLabel/accessibilityHint; logical reading order for VoiceOver/screen readers (Apple HIG, MD)
- `escape-routes` - Provide cancel/back in modals and multi-step flows (Apple HIG)
- `keyboard-shortcuts` - Preserve system and a11y shortcuts; offer keyboard alternatives for drag-and-drop (Apple HIG)
### 2. Touch & Interaction (CRITICAL)
- `touch-target-size` - Min 44×44pt (Apple) / 48×48dp (Material); extend hit area beyond visual bounds if needed
- `touch-spacing` - Minimum 8px/8dp gap between touch targets (Apple HIG, MD)
- `hover-vs-tap` - Use click/tap for primary interactions; don't rely on hover alone
- `loading-buttons` - Disable button during async operations; show spinner or progress
- `error-feedback` - Clear error messages near problem
- `cursor-pointer` - Add cursor-pointer to clickable elements (Web)
- `gesture-conflicts` - Avoid horizontal swipe on main content; prefer vertical scroll
- `tap-delay` - Use touch-action: manipulation to reduce 300ms delay (Web)
- `standard-gestures` - Use platform standard gestures consistently; don't redefine (e.g. swipe-back, pinch-zoom) (Apple HIG)
- `system-gestures` - Don't block system gestures (Control Center, back swipe, etc.) (Apple HIG)
- `press-feedback` - Visual feedback on press (ripple/highlight; MD state layers)
- `haptic-feedback` - Use haptic for confirmations and important actions; avoid overuse (Apple HIG)
- `gesture-alternative` - Don't rely on gesture-only interactions; always provide visible controls for critical actions
- `safe-area-awareness` - Keep primary touch targets away from notch, Dynamic Island, gesture bar and screen edges
- `no-precision-required` - Avoid requiring pixel-perfect taps on small icons or thin edges
- `swipe-clarity` - Swipe actions must show clear affordance or hint (chevron, label, tutorial)
- `drag-threshold` - Use a movement threshold before starting drag to avoid accidental drags
### 3. Performance (HIGH)
- `image-optimization` - Use WebP/AVIF, responsive images (srcset/sizes), lazy load non-critical assets
- `image-dimension` - Declare width/height or use aspect-ratio to prevent layout shift (Core Web Vitals: CLS)
- `font-loading` - Use font-display: swap/optional to avoid invisible text (FOIT); reserve space to reduce layout shift (MD)
- `font-preload` - Preload only critical fonts; avoid overusing preload on every variant
- `critical-css` - Prioritize above-the-fold CSS (inline critical CSS or early-loaded stylesheet)
- `lazy-loading` - Lazy load non-hero components via dynamic import / route-level splitting
- `bundle-splitting` - Split code by route/feature (React Suspense / Next.js dynamic) to reduce initial load and TTI
- `third-party-scripts` - Load third-party scripts async/defer; audit and remove unnecessary ones (MD)
- `reduce-reflows` - Avoid frequent layout reads/writes; batch DOM reads then writes
- `content-jumping` - Reserve space for async content to avoid layout jumps (Core Web Vitals: CLS)
- `lazy-load-below-fold` - Use loading="lazy" for below-the-fold images and heavy media
- `virtualize-lists` - Virtualize lists with 50+ items to improve memory efficiency and scroll performance
- `main-thread-budget` - Keep per-frame work under ~16ms for 60fps; move heavy tasks off main thread (HIG, MD)
- `progressive-loading` - Use skeleton screens / shimmer instead of long blocking spinners for >1s operations (Apple HIG)
- `input-latency` - Keep input latency under ~100ms for taps/scrolls (Material responsiveness standard)
- `tap-feedback-speed` - Provide visual feedback within 100ms of tap (Apple HIG)
- `debounce-throttle` - Use debounce/throttle for high-frequency events (scroll, resize, input)
- `offline-support` - Provide offline state messaging and basic fallback (PWA / mobile)
- `network-fallback` - Offer degraded modes for slow networks (lower-res images, fewer animations)
### 4. Style Selection (HIGH)
- `style-match` - Match style to product type (use `--design-system` for recommendations)
- `consistency` - Use same style across all pages
- `no-emoji-icons` - Use SVG icons (Heroicons, Lucide), not emojis
- `color-palette-from-product` - Choose palette from product/industry (search `--domain color`)
- `effects-match-style` - Shadows, blur, radius aligned with chosen style (glass / flat / clay etc.)
- `platform-adaptive` - Respect platform idioms (iOS HIG vs Material): navigation, controls, typography, motion
- `state-clarity` - Make hover/pressed/disabled states visually distinct while staying on-style (Material state layers)
- `elevation-consistent` - Use a consistent elevation/shadow scale for cards, sheets, modals; avoid random shadow values
- `dark-mode-pairing` - Design light/dark variants together to keep brand, contrast, and style consistent
- `icon-style-consistent` - Use one icon set/visual language (stroke width, corner radius) across the product
- `system-controls` - Prefer native/system controls over fully custom ones; only customize when branding requires it (Apple HIG)
- `blur-purpose` - Use blur to indicate background dismissal (modals, sheets), not as decoration (Apple HIG)
- `primary-action` - Each screen should have only one primary CTA; secondary actions visually subordinate (Apple HIG)
### 5. Layout & Responsive (HIGH)
- `viewport-meta` - width=device-width initial-scale=1 (never disable zoom)
- `mobile-first` - Design mobile-first, then scale up to tablet and desktop
- `breakpoint-consistency` - Use systematic breakpoints (e.g. 375 / 768 / 1024 / 1440)
- `readable-font-size` - Minimum 16px body text on mobile (avoids iOS auto-zoom)
- `line-length-control` - Mobile 3560 chars per line; desktop 6075 chars
- `horizontal-scroll` - No horizontal scroll on mobile; ensure content fits viewport width
- `spacing-scale` - Use 4pt/8dp incremental spacing system (Material Design)
- `touch-density` - Keep component spacing comfortable for touch: not cramped, not causing mis-taps
- `container-width` - Consistent max-width on desktop (max-w-6xl / 7xl)
- `z-index-management` - Define layered z-index scale (e.g. 0 / 10 / 20 / 40 / 100 / 1000)
- `fixed-element-offset` - Fixed navbar/bottom bar must reserve safe padding for underlying content
- `scroll-behavior` - Avoid nested scroll regions that interfere with the main scroll experience
- `viewport-units` - Prefer min-h-dvh over 100vh on mobile
- `orientation-support` - Keep layout readable and operable in landscape mode
- `content-priority` - Show core content first on mobile; fold or hide secondary content
- `visual-hierarchy` - Establish hierarchy via size, spacing, contrast — not color alone
### 6. Typography & Color (MEDIUM)
- `line-height` - Use 1.5-1.75 for body text
- `line-length` - Limit to 65-75 characters per line
- `font-pairing` - Match heading/body font personalities
- `font-scale` - Consistent type scale (e.g. 12 14 16 18 24 32)
- `contrast-readability` - Darker text on light backgrounds (e.g. slate-900 on white)
- `text-styles-system` - Use platform type system: iOS 11 Dynamic Type styles / Material 5 type roles (display, headline, title, body, label) (HIG, MD)
- `weight-hierarchy` - Use font-weight to reinforce hierarchy: Bold headings (600700), Regular body (400), Medium labels (500) (MD)
- `color-semantic` - Define semantic color tokens (primary, secondary, error, surface, on-surface) not raw hex in components (Material color system)
- `color-dark-mode` - Dark mode uses desaturated / lighter tonal variants, not inverted colors; test contrast separately (HIG, MD)
- `color-accessible-pairs` - Foreground/background pairs must meet 4.5:1 (AA) or 7:1 (AAA); use tools to verify (WCAG, MD)
- `color-not-decorative-only` - Functional color (error red, success green) must include icon/text; avoid color-only meaning (HIG, MD)
- `truncation-strategy` - Prefer wrapping over truncation; when truncating use ellipsis and provide full text via tooltip/expand (Apple HIG)
- `letter-spacing` - Respect default letter-spacing per platform; avoid tight tracking on body text (HIG, MD)
- `number-tabular` - Use tabular/monospaced figures for data columns, prices, and timers to prevent layout shift
- `whitespace-balance` - Use whitespace intentionally to group related items and separate sections; avoid visual clutter (Apple HIG)
### 7. Animation (MEDIUM)
- `duration-timing` - Use 150300ms for micro-interactions; complex transitions ≤400ms; avoid >500ms (MD)
- `transform-performance` - Use transform/opacity only; avoid animating width/height/top/left
- `loading-states` - Show skeleton or progress indicator when loading exceeds 300ms
- `excessive-motion` - Animate 1-2 key elements per view max
- `easing` - Use ease-out for entering, ease-in for exiting; avoid linear for UI transitions
- `motion-meaning` - Every animation must express a cause-effect relationship, not just be decorative (Apple HIG)
- `state-transition` - State changes (hover / active / expanded / collapsed / modal) should animate smoothly, not snap
- `continuity` - Page/screen transitions should maintain spatial continuity (shared element, directional slide) (Apple HIG)
- `parallax-subtle` - Use parallax sparingly; must respect reduced-motion and not cause disorientation (Apple HIG)
- `spring-physics` - Prefer spring/physics-based curves over linear or cubic-bezier for natural feel (Apple HIG fluid animations)
- `exit-faster-than-enter` - Exit animations shorter than enter (~6070% of enter duration) to feel responsive (MD motion)
- `stagger-sequence` - Stagger list/grid item entrance by 3050ms per item; avoid all-at-once or too-slow reveals (MD)
- `shared-element-transition` - Use shared element / hero transitions for visual continuity between screens (MD, HIG)
- `interruptible` - Animations must be interruptible; user tap/gesture cancels in-progress animation immediately (Apple HIG)
- `no-blocking-animation` - Never block user input during an animation; UI must stay interactive (Apple HIG)
- `fade-crossfade` - Use crossfade for content replacement within the same container (MD)
- `scale-feedback` - Subtle scale (0.951.05) on press for tappable cards/buttons; restore on release (HIG, MD)
- `gesture-feedback` - Drag, swipe, and pinch must provide real-time visual response tracking the finger (MD Motion)
- `hierarchy-motion` - Use translate/scale direction to express hierarchy: enter from below = deeper, exit upward = back (MD)
- `motion-consistency` - Unify duration/easing tokens globally; all animations share the same rhythm and feel
- `opacity-threshold` - Fading elements should not linger below opacity 0.2; either fade fully or remain visible
- `modal-motion` - Modals/sheets should animate from their trigger source (scale+fade or slide-in) for spatial context (HIG, MD)
- `navigation-direction` - Forward navigation animates left/up; backward animates right/down — keep direction logically consistent (HIG)
- `layout-shift-avoid` - Animations must not cause layout reflow or CLS; use transform for position changes
### 8. Forms & Feedback (MEDIUM)
- `input-labels` - Visible label per input (not placeholder-only)
- `error-placement` - Show error below the related field
- `submit-feedback` - Loading then success/error state on submit
- `required-indicators` - Mark required fields (e.g. asterisk)
- `empty-states` - Helpful message and action when no content
- `toast-dismiss` - Auto-dismiss toasts in 3-5s
- `confirmation-dialogs` - Confirm before destructive actions
- `input-helper-text` - Provide persistent helper text below complex inputs, not just placeholder (Material Design)
- `disabled-states` - Disabled elements use reduced opacity (0.380.5) + cursor change + semantic attribute (MD)
- `progressive-disclosure` - Reveal complex options progressively; don't overwhelm users upfront (Apple HIG)
- `inline-validation` - Validate on blur (not keystroke); show error only after user finishes input (MD)
- `input-type-keyboard` - Use semantic input types (email, tel, number) to trigger the correct mobile keyboard (HIG, MD)
- `password-toggle` - Provide show/hide toggle for password fields (MD)
- `autofill-support` - Use autocomplete / textContentType attributes so the system can autofill (HIG, MD)
- `undo-support` - Allow undo for destructive or bulk actions (e.g. "Undo delete" toast) (Apple HIG)
- `success-feedback` - Confirm completed actions with brief visual feedback (checkmark, toast, color flash) (MD)
- `error-recovery` - Error messages must include a clear recovery path (retry, edit, help link) (HIG, MD)
- `multi-step-progress` - Multi-step flows show step indicator or progress bar; allow back navigation (MD)
- `form-autosave` - Long forms should auto-save drafts to prevent data loss on accidental dismissal (Apple HIG)
- `sheet-dismiss-confirm` - Confirm before dismissing a sheet/modal with unsaved changes (Apple HIG)
- `error-clarity` - Error messages must state cause + how to fix (not just "Invalid input") (HIG, MD)
- `field-grouping` - Group related fields logically (fieldset/legend or visual grouping) (MD)
- `read-only-distinction` - Read-only state should be visually and semantically different from disabled (MD)
- `focus-management` - After submit error, auto-focus the first invalid field (WCAG, MD)
- `error-summary` - For multiple errors, show summary at top with anchor links to each field (WCAG)
- `touch-friendly-input` - Mobile input height ≥44px to meet touch target requirements (Apple HIG)
- `destructive-emphasis` - Destructive actions use semantic danger color (red) and are visually separated from primary actions (HIG, MD)
- `toast-accessibility` - Toasts must not steal focus; use aria-live="polite" for screen reader announcement (WCAG)
- `aria-live-errors` - Form errors use aria-live region or role="alert" to notify screen readers (WCAG)
- `contrast-feedback` - Error and success state colors must meet 4.5:1 contrast ratio (WCAG, MD)
- `timeout-feedback` - Request timeout must show clear feedback with retry option (MD)
### 9. Navigation Patterns (HIGH)
- `bottom-nav-limit` - Bottom navigation max 5 items; use labels with icons (Material Design)
- `drawer-usage` - Use drawer/sidebar for secondary navigation, not primary actions (Material Design)
- `back-behavior` - Back navigation must be predictable and consistent; preserve scroll/state (Apple HIG, MD)
- `deep-linking` - All key screens must be reachable via deep link / URL for sharing and notifications (Apple HIG, MD)
- `tab-bar-ios` - iOS: use bottom Tab Bar for top-level navigation (Apple HIG)
- `top-app-bar-android` - Android: use Top App Bar with navigation icon for primary structure (Material Design)
- `nav-label-icon` - Navigation items must have both icon and text label; icon-only nav harms discoverability (MD)
- `nav-state-active` - Current location must be visually highlighted (color, weight, indicator) in navigation (HIG, MD)
- `nav-hierarchy` - Primary nav (tabs/bottom bar) vs secondary nav (drawer/settings) must be clearly separated (MD)
- `modal-escape` - Modals and sheets must offer a clear close/dismiss affordance; swipe-down to dismiss on mobile (Apple HIG)
- `search-accessible` - Search must be easily reachable (top bar or tab); provide recent/suggested queries (MD)
- `breadcrumb-web` - Web: use breadcrumbs for 3+ level deep hierarchies to aid orientation (MD)
- `state-preservation` - Navigating back must restore previous scroll position, filter state, and input (HIG, MD)
- `gesture-nav-support` - Support system gesture navigation (iOS swipe-back, Android predictive back) without conflict (HIG, MD)
- `tab-badge` - Use badges on nav items sparingly to indicate unread/pending; clear after user visits (HIG, MD)
- `overflow-menu` - When actions exceed available space, use overflow/more menu instead of cramming (MD)
- `bottom-nav-top-level` - Bottom nav is for top-level screens only; never nest sub-navigation inside it (MD)
- `adaptive-navigation` - Large screens (≥1024px) prefer sidebar; small screens use bottom/top nav (Material Adaptive)
- `back-stack-integrity` - Never silently reset the navigation stack or unexpectedly jump to home (HIG, MD)
- `navigation-consistency` - Navigation placement must stay the same across all pages; don't change by page type
- `avoid-mixed-patterns` - Don't mix Tab + Sidebar + Bottom Nav at the same hierarchy level
- `modal-vs-navigation` - Modals must not be used for primary navigation flows; they break the user's path (HIG)
- `focus-on-route-change` - After page transition, move focus to main content region for screen reader users (WCAG)
- `persistent-nav` - Core navigation must remain reachable from deep pages; don't hide it entirely in sub-flows (HIG, MD)
- `destructive-nav-separation` - Dangerous actions (delete account, logout) must be visually and spatially separated from normal nav items (HIG, MD)
- `empty-nav-state` - When a nav destination is unavailable, explain why instead of silently hiding it (MD)
### 10. Charts & Data (LOW)
- `chart-type` - Match chart type to data type (trend → line, comparison → bar, proportion → pie/donut)
- `color-guidance` - Use accessible color palettes; avoid red/green only pairs for colorblind users (WCAG, MD)
- `data-table` - Provide table alternative for accessibility; charts alone are not screen-reader friendly (WCAG)
- `pattern-texture` - Supplement color with patterns, textures, or shapes so data is distinguishable without color (WCAG, MD)
- `legend-visible` - Always show legend; position near the chart, not detached below a scroll fold (MD)
- `tooltip-on-interact` - Provide tooltips/data labels on hover (Web) or tap (mobile) showing exact values (HIG, MD)
- `axis-labels` - Label axes with units and readable scale; avoid truncated or rotated labels on mobile
- `responsive-chart` - Charts must reflow or simplify on small screens (e.g. horizontal bar instead of vertical, fewer ticks)
- `empty-data-state` - Show meaningful empty state when no data exists ("No data yet" + guidance), not a blank chart (MD)
- `loading-chart` - Use skeleton or shimmer placeholder while chart data loads; don't show an empty axis frame
- `animation-optional` - Chart entrance animations must respect prefers-reduced-motion; data should be readable immediately (HIG)
- `large-dataset` - For 1000+ data points, aggregate or sample; provide drill-down for detail instead of rendering all (MD)
- `number-formatting` - Use locale-aware formatting for numbers, dates, currencies on axes and labels (HIG, MD)
- `touch-target-chart` - Interactive chart elements (points, segments) must have ≥44pt tap area or expand on touch (Apple HIG)
- `no-pie-overuse` - Avoid pie/donut for >5 categories; switch to bar chart for clarity
- `contrast-data` - Data lines/bars vs background ≥3:1; data text labels ≥4.5:1 (WCAG)
- `legend-interactive` - Legends should be clickable to toggle series visibility (MD)
- `direct-labeling` - For small datasets, label values directly on the chart to reduce eye travel
- `tooltip-keyboard` - Tooltip content must be keyboard-reachable and not rely on hover alone (WCAG)
- `sortable-table` - Data tables must support sorting with aria-sort indicating current sort state (WCAG)
- `axis-readability` - Axis ticks must not be cramped; maintain readable spacing, auto-skip on small screens
- `data-density` - Limit information density per chart to avoid cognitive overload; split into multiple charts if needed
- `trend-emphasis` - Emphasize data trends over decoration; avoid heavy gradients/shadows that obscure the data
- `gridline-subtle` - Grid lines should be low-contrast (e.g. gray-200) so they don't compete with data
- `focusable-elements` - Interactive chart elements (points, bars, slices) must be keyboard-navigable (WCAG)
- `screen-reader-summary` - Provide a text summary or aria-label describing the chart's key insight for screen readers (WCAG)
- `error-state-chart` - Data load failure must show error message with retry action, not a broken/empty chart
- `export-option` - For data-heavy products, offer CSV/image export of chart data
- `drill-down-consistency` - Drill-down interactions must maintain a clear back-path and hierarchy breadcrumb
- `time-scale-clarity` - Time series charts must clearly label time granularity (day/week/month) and allow switching

272
.claude/skills/ui-ux-pro-max/scripts/core.py Executable file → Normal file
View File

@ -77,6 +77,14 @@ CSV_CONFIG = {
}
}
# Output columns whose content (code samples, checklists) must never be
# hard-truncated for display -- truncating mid-snippet destroys the value.
UNTRUNCATED_COLS = {
"Code Example Good", "Code Example Bad", "Code Good", "Code Bad",
"Implementation Checklist", "Design System Variables", "CSS Import",
"Tailwind Config", "GSAP Snippet",
}
STACK_CONFIG = {
"react": {"file": "stacks/react.csv"},
"nextjs": {"file": "stacks/nextjs.csv"},
@ -111,6 +119,44 @@ _STACK_COLS = {
AVAILABLE_STACKS = list(STACK_CONFIG.keys())
# ============ TOKENIZATION ============
# Common two-letter/three-letter words that add noise without adding search
# signal. Deliberately short -- domain-relevant short tokens (ui, ux, ai,
# css, 3d, js, os, md, gsap) must stay searchable, which is why we don't
# filter purely by length.
_STOPWORDS = {
"to", "in", "on", "at", "is", "of", "by", "or", "an", "if", "no", "so",
"do", "be", "we", "it", "as", "the", "and", "for", "are", "was",
}
# Query/corpus normalization so common spelling variants match each other.
# Keep this a plain dict (stdlib only, no fuzzy-matching dependency).
_SYNONYMS = {
"e-commerce": "ecommerce",
"dark-mode": "dark",
"darkmode": "dark",
"light-mode": "light",
"lightmode": "light",
"a11y": "accessibility",
"nav": "navigation",
"sign-up": "signup",
"log-in": "login",
"colour": "color",
"colours": "colors",
"customisation": "customization",
"organisation": "organization",
"behaviour": "behavior",
"ux/ui": "ux ui",
}
def _normalize(text):
"""Apply synonym substitution before tokenizing."""
for variant, canonical in _SYNONYMS.items():
text = text.replace(variant, canonical)
return text
# ============ BM25 IMPLEMENTATION ============
class BM25:
"""BM25 ranking algorithm for text search"""
@ -124,11 +170,13 @@ class BM25:
self.idf = {}
self.doc_freqs = defaultdict(int)
self.N = 0
self._term_freqs = [] # precomputed per-doc term frequencies
def tokenize(self, text):
"""Lowercase, split, remove punctuation, filter short words"""
text = re.sub(r'[^\w\s]', ' ', str(text).lower())
return [w for w in text.split() if len(w) >= 2]
"""Lowercase, normalize synonyms, split, remove punctuation, filter stopwords"""
text = _normalize(str(text).lower())
text = re.sub(r'[^\w\s]', ' ', text)
return [w for w in text.split() if len(w) >= 2 and w not in _STOPWORDS]
def fit(self, documents):
"""Build BM25 index from documents"""
@ -139,12 +187,14 @@ class BM25:
self.doc_lengths = [len(doc) for doc in self.corpus]
self.avgdl = sum(self.doc_lengths) / self.N
self._term_freqs = []
for doc in self.corpus:
seen = set()
tf = defaultdict(int)
for word in doc:
if word not in seen:
self.doc_freqs[word] += 1
seen.add(word)
tf[word] += 1
self._term_freqs.append(tf)
for word in tf:
self.doc_freqs[word] += 1
for word, freq in self.doc_freqs.items():
self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
@ -154,16 +204,14 @@ class BM25:
query_tokens = self.tokenize(query)
scores = []
for idx, doc in enumerate(self.corpus):
for idx in range(self.N):
score = 0
doc_len = self.doc_lengths[idx]
term_freqs = defaultdict(int)
for word in doc:
term_freqs[word] += 1
term_freqs = self._term_freqs[idx]
for token in query_tokens:
if token in self.idf:
tf = term_freqs[token]
tf = term_freqs.get(token, 0)
idf = self.idf[token]
numerator = tf * (self.k1 + 1)
denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
@ -173,48 +221,139 @@ class BM25:
return sorted(scores, key=lambda x: x[1], reverse=True)
def vocabulary(self):
"""All indexed terms, for suggestion/typo-recovery purposes."""
return list(self.idf.keys())
# ============ CSV / INDEX CACHE ============
# Data files are small and reused across multiple domain searches within a
# single --design-system run; avoid re-reading + re-indexing the same file
# repeatedly in one process.
_csv_cache = {} # filepath -> (mtime, rows)
_bm25_cache = {} # (filepath, tuple(search_cols)) -> (mtime, BM25 instance)
# ============ SEARCH FUNCTIONS ============
def _load_csv(filepath):
"""Load CSV and return list of dicts"""
"""Load CSV and return list of dicts, with mtime-based caching."""
mtime = filepath.stat().st_mtime
cached = _csv_cache.get(filepath)
if cached and cached[0] == mtime:
return cached[1]
with open(filepath, 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
rows = list(csv.DictReader(f))
_csv_cache[filepath] = (mtime, rows)
return rows
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25"""
if not filepath.exists():
return []
def _get_bm25(filepath, search_cols, data):
"""Fitted BM25 index for this file+columns, with mtime-based caching."""
key = (filepath, tuple(search_cols))
mtime = filepath.stat().st_mtime
cached = _bm25_cache.get(key)
if cached and cached[0] == mtime:
return cached[1]
data = _load_csv(filepath)
# Build documents from search columns
documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
# BM25 search
bm25 = BM25()
bm25.fit(documents)
_bm25_cache[key] = (mtime, bm25)
return bm25
# ============ SEARCH FUNCTIONS ============
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25. Returns (results, bm25_or_none)."""
if not filepath.exists():
return [], None
try:
data = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError) as e:
return [{"_error": f"Failed to read {filepath.name}: {e}"}], None
if not data:
return [], None
bm25 = _get_bm25(filepath, search_cols, data)
ranked = bm25.score(query)
# Get top results with score > 0
results = []
for idx, score in ranked[:max_results]:
if score > 0:
row = data[idx]
results.append({col: row.get(col, "") for col in output_cols if col in row})
return results
return results, bm25
def detect_domain(query):
"""Auto-detect the most relevant domain from query"""
query_lower = query.lower()
def _suggest_terms(bm25, query, limit=6):
"""Nearest known vocabulary terms for a query that returned 0 hits,
so the caller can retry instead of silently reporting nothing."""
if bm25 is None:
return []
query_tokens = set(bm25.tokenize(query))
if not query_tokens:
return []
domain_keywords = {
candidates = []
for term in bm25.vocabulary():
for qt in query_tokens:
if term.startswith(qt[:3]) or qt.startswith(term[:3]):
candidates.append(term)
break
# Stable de-dup, most frequent terms first (doc_freqs available via idf keys only,
# so just de-dup preserving discovery order).
seen = set()
ordered = []
for term in candidates:
if term not in seen:
seen.add(term)
ordered.append(term)
return ordered[:limit]
# Load the product-domain keyword list from products.csv at import time so
# it stays in sync with the data instead of needing manual updates to a
# hardcoded list. Falls back to a small built-in seed if the file is
# missing (e.g. package built without data/).
def _load_product_keywords():
seed = ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming",
"portfolio", "crypto", "dashboard", "fitness", "marketplace"]
filepath = DATA_DIR / CSV_CONFIG["product"]["file"]
if not filepath.exists():
return seed
try:
rows = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError):
return seed
keywords = set(seed)
for row in rows:
raw = row.get("Keywords", "")
for kw in re.split(r"[,;]", raw):
kw = kw.strip().lower()
if kw and len(kw) >= 3:
keywords.add(kw)
return sorted(keywords, key=len, reverse=True)
_DOMAIN_KEYWORDS = None
def _domain_keywords():
global _DOMAIN_KEYWORDS
if _DOMAIN_KEYWORDS is not None:
return _DOMAIN_KEYWORDS
_DOMAIN_KEYWORDS = {
"color": ["color", "palette", "hex", "#", "rgb", "token", "semantic", "accent", "destructive", "muted", "foreground"],
"chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
"landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
"product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard", "fitness", "restaurant", "hotel", "travel", "music", "education", "learning", "legal", "insurance", "medical", "beauty", "pharmacy", "dental", "pet", "dating", "wedding", "recipe", "delivery", "ride", "booking", "calendar", "timer", "tracker", "diary", "note", "chat", "messenger", "crm", "invoice", "parking", "transit", "vpn", "alarm", "weather", "sleep", "meditation", "fasting", "habit", "grocery", "meme", "wardrobe", "plant care", "reading", "flashcard", "puzzle", "trivia", "arcade", "photography", "streaming", "podcast", "newsletter", "marketplace", "freelancer", "coworking", "airline", "museum", "theater", "church", "non-profit", "charity", "kindergarten", "daycare", "senior care", "veterinary", "florist", "bakery", "brewery", "construction", "automotive", "real estate", "logistics", "agriculture", "coding bootcamp"],
"product": _load_product_keywords(),
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"],
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
"typography": ["font pairing", "typography pairing", "heading font", "body font"],
@ -224,16 +363,57 @@ def detect_domain(query):
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
}
return _DOMAIN_KEYWORDS
scores = {domain: sum(1 for kw in keywords if re.search(r'\b' + re.escape(kw) + r'\b', query_lower)) for domain, keywords in domain_keywords.items()}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else "style"
# Domains checked in this fixed order when scores tie, so results are
# deterministic instead of depending on dict/hash ordering.
_DOMAIN_TIEBREAK_ORDER = [
"ux", "product", "style", "color", "typography", "google-fonts",
"chart", "landing", "icons", "gsap", "react", "web",
]
def detect_domain(query, return_scores=False):
"""Auto-detect the most relevant domain from query.
Matches are weighted by keyword length (multi-word/longer phrases are
more specific and score higher than short generic words). Ties are
broken by a fixed domain priority order, not dict/insertion order.
"""
query_lower = query.lower()
domain_keywords = _domain_keywords()
scores = {}
for domain, keywords in domain_keywords.items():
total = 0.0
for kw in keywords:
if re.search(r'\b' + re.escape(kw) + r'\b', query_lower):
# weight = 1 point per word in the keyword phrase
total += max(1, len(kw.split()))
scores[domain] = total
ranked = sorted(
scores.items(),
key=lambda item: (item[1], -_DOMAIN_TIEBREAK_ORDER.index(item[0])
if item[0] in _DOMAIN_TIEBREAK_ORDER else -999),
reverse=True,
)
best_domain, best_score = ranked[0]
result = best_domain if best_score > 0 else "style"
if return_scores:
runner_up = ranked[1][0] if len(ranked) > 1 and ranked[1][1] > 0 else None
return result, runner_up
return result
def search(query, domain=None, max_results=MAX_RESULTS):
"""Main search function with auto-domain detection"""
auto_detected = domain is None
runner_up = None
if domain is None:
domain = detect_domain(query)
domain, runner_up = detect_domain(query, return_scores=True)
config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
filepath = DATA_DIR / config["file"]
@ -241,15 +421,22 @@ def search(query, domain=None, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"File not found: {filepath}", "domain": domain}
results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
return {
out = {
"domain": domain,
"query": query,
"file": config["file"],
"count": len(results),
"results": results
"results": results,
}
if auto_detected:
out["auto_detected"] = True
if runner_up:
out["runner_up_domain"] = runner_up
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out
def search_stack(query, stack, max_results=MAX_RESULTS):
@ -262,13 +449,16 @@ def search_stack(query, stack, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"Stack file not found: {filepath}", "stack": stack}
results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
return {
out = {
"domain": "stack",
"stack": stack,
"query": query,
"file": STACK_CONFIG[stack]["file"],
"count": len(results),
"results": results
"results": results,
}
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out

View File

@ -7,10 +7,12 @@ to generate comprehensive design system recommendations.
Usage:
from design_system import generate_design_system
result = generate_design_system("SaaS dashboard", "My Project")
print(result["text"])
# With persistence (Master + Overrides pattern)
result = generate_design_system("SaaS dashboard", "My Project", persist=True)
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")
result = generate_design_system("SaaS dashboard", "My Project", persist=True, output_dir="/path/to/project")
result["persistence"] # {"status": "success"|"skipped_exists", "created_files": [...], ...}
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard", output_dir="/path/to/project")
"""
import csv
@ -665,7 +667,8 @@ def format_markdown(design_system: dict) -> str:
# ============ MAIN ENTRY POINT ============
def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None) -> str:
variance: int = None, motion: int = None, density: int = None,
force: bool = False) -> dict:
"""
Main entry point for design system generation.
@ -679,20 +682,28 @@ def generate_design_system(query: str, project_name: str = None, output_format:
variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
Returns:
Formatted design system string
dict with keys: "text" (formatted design system string), "design_system"
(raw dict, useful for --json callers), and "persistence" (result of
persist_design_system(), or None if persist=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
# Persist to files if requested
persistence_result = None
if persist:
persist_design_system(design_system, page, output_dir, query)
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
if output_format == "markdown":
return format_markdown(design_system)
return format_ascii_box(design_system)
text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system)
return {
"text": text,
"design_system": design_system,
"persistence": persistence_result,
}
# ============ PERSISTENCE FUNCTIONS ============
@ -707,42 +718,61 @@ def safe_slug(name, fallback: str = "default") -> str:
return slug or fallback
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict:
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
page_query: str = None, force: bool = False) -> dict:
"""
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
Args:
design_system: The generated design system dictionary
page: Optional page name for page-specific override file
output_dir: Optional output directory (defaults to current working directory)
page_query: Optional query string for intelligent page override generation
force: If True, overwrite an existing MASTER.md. If False (default) and
MASTER.md already exists, persistence is skipped so prior design
decisions aren't silently discarded.
Returns:
dict with created file paths and status
dict with created file paths and status. status is "skipped_exists" if
MASTER.md already existed and force was not set.
"""
base_dir = Path(output_dir) if output_dir else Path.cwd()
# Use project name for project-specific folder. Coalesce falsy values
# (missing key, explicit None, or "") so slugification can't crash.
project_slug = safe_slug(design_system.get("project_name") or "default")
# (missing key, explicit None, or "") so the .lower() below can't crash.
project_name = design_system.get("project_name") or "default"
project_slug = safe_slug(project_name)
design_system_dir = base_dir / "design-system" / project_slug
pages_dir = design_system_dir / "pages"
master_file = design_system_dir / "MASTER.md"
if master_file.exists() and not force:
return {
"status": "skipped_exists",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": [],
"message": (
f"{master_file} already exists and was not modified. "
"Read it first to check for prior design decisions, then "
"re-run with force=True / --force to overwrite."
),
}
created_files = []
# Create directories
design_system_dir.mkdir(parents=True, exist_ok=True)
pages_dir.mkdir(parents=True, exist_ok=True)
master_file = design_system_dir / "MASTER.md"
# Generate and write MASTER.md
master_content = format_master_md(design_system)
with open(master_file, 'w', encoding='utf-8') as f:
f.write(master_content)
created_files.append(str(master_file))
# If page is specified, create page override file with intelligent content
if page:
page_file = pages_dir / f"{safe_slug(page, 'page')}.md"
@ -750,10 +780,11 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
with open(page_file, 'w', encoding='utf-8') as f:
f.write(page_content)
created_files.append(str(page_file))
return {
"status": "success",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": created_files
}
@ -1337,4 +1368,4 @@ if __name__ == "__main__":
args = parser.parse_args()
result = generate_design_system(args.query, args.project_name, args.format)
print(result)
print(result["text"])

View File

@ -1,127 +1,162 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
python search.py "<query>" --design-system --variance 8 --motion 9 --density 7
Domains: style, prompt, color, chart, landing, product, ux, typography, google-fonts, gsap
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui, html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel, javafx, wpf, winui, avalonia, uno, uwp
Design dials (1-10, only with --design-system):
--variance DESIGN_VARIANCE: 1=centered/minimal, 10=bold/asymmetric
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/MASTER.md
--page Also create a page-specific override file in design-system/pages/
"""
import argparse
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system, persist_design_system, safe_slug
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def format_output(result):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append(f"## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append(f"## UI Pro Max Search Results")
output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if len(value_str) > 300:
value_str = value_str[:300] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
return "\n".join(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UI Pro Max Search")
parser.add_argument("query", help="Search query")
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
# Design dials (1-10), only applied with --design-system
parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)")
parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)")
parser.add_argument("--density", type=int, choices=range(1, 11), metavar="1-10", help="VISUAL_DENSITY dial: 1=spacious, 10=dense/dashboard; overrides the spacing scale (only with --design-system)")
args = parser.parse_args()
# Design system takes priority
if args.design_system:
result = generate_design_system(
args.query,
args.project_name,
args.format,
persist=args.persist,
page=args.page,
output_dir=args.output_dir,
variance=args.variance,
motion=args.motion,
density=args.density
)
print(result)
# Print persistence confirmation
if args.persist:
project_slug = safe_slug(args.project_name or args.query.upper())
print("\n" + "=" * 60)
print(f"✅ Design system persisted to design-system/{project_slug}/")
print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
if args.page:
page_filename = safe_slug(args.page, 'page')
print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
print("")
print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
python search.py "<query>" --design-system --variance 8 --motion 9 --density 7
Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui,
html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel
Design dials (1-10, only with --design-system):
--variance DESIGN_VARIANCE: 1=centered/minimal, 10=bold/asymmetric
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/<project-slug>/MASTER.md
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
always pass this explicitly, pointed at the project root)
--page Also create a page-specific override file in design-system/<project-slug>/pages/
--force Overwrite an existing MASTER.md (without this, persistence is skipped
if MASTER.md already exists, so prior design decisions aren't lost)
"""
import argparse
import json as json_module
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, UNTRUNCATED_COLS, search, search_stack
from design_system import generate_design_system
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
TRUNCATE_AT = 300
def format_output(result, full=False):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append("## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append("## UI Pro Max Search Results")
domain_note = result['domain']
if result.get("auto_detected"):
domain_note += " (auto-detected"
if result.get("runner_up_domain"):
domain_note += f", runner-up: {result['runner_up_domain']}"
domain_note += ")"
output.append(f"**Domain:** {domain_note} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
if result['count'] == 0:
output.append(
"No matches. This is not a match with an empty value -- the query "
"did not hit the database. Retry with broader/different keywords "
"before falling back to general defaults, and say explicitly that "
"no database match was found if you do fall back."
)
suggestions = result.get("suggestions") or []
if suggestions:
output.append(f"**Closest known terms:** {', '.join(suggestions)}")
return "\n".join(output)
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if not full and key not in UNTRUNCATED_COLS and len(value_str) > TRUNCATE_AT:
value_str = value_str[:TRUNCATE_AT] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
return "\n".join(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UI Pro Max Search")
parser.add_argument("query", help="Search query")
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
parser.add_argument("--full", action="store_true", help="Do not truncate long field values in text output")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system (ignored if --json)")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/<project-slug>/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/<project-slug>/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
# Design dials (1-10), only applied with --design-system
parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)")
parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)")
parser.add_argument("--density", type=int, choices=range(1, 11), metavar="1-10", help="VISUAL_DENSITY dial: 1=spacious, 10=dense/dashboard; overrides the spacing scale (only with --design-system)")
args = parser.parse_args()
# Design system takes priority
if args.design_system:
result = generate_design_system(
args.query,
args.project_name,
args.format,
persist=args.persist,
page=args.page,
output_dir=args.output_dir,
variance=args.variance,
motion=args.motion,
density=args.density,
force=args.force,
)
if args.json:
print(json_module.dumps(
{"design_system": result["design_system"], "persistence": result["persistence"]},
indent=2, ensure_ascii=False,
))
else:
print(result["text"])
if args.persist:
persistence = result["persistence"] or {}
print("\n" + "=" * 60)
if persistence.get("status") == "skipped_exists":
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
else:
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
print(f"✅ Design system persisted to {ds_dir}/")
for f in persistence.get("created_files", []):
print(f" 📄 {f}")
print("")
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.")
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result, full=args.full))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result, full=args.full))

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stdlib-only regression tests for core.py / design_system.py (unittest, not
pytest -- this project ships with zero external dependencies and the tests
shouldn't add one).
Run with:
python -m unittest discover -s scripts/tests -v
or directly:
python scripts/tests/test_core.py
"""
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPTS_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SCRIPTS_DIR))
from core import BM25, detect_domain, search, search_stack, CSV_CONFIG, AVAILABLE_STACKS
from design_system import generate_design_system, persist_design_system, DesignSystemGenerator
class TestTokenizer(unittest.TestCase):
def test_short_domain_terms_are_kept(self):
bm25 = BM25()
tokens = bm25.tokenize("UI and UX design with 3D and AI")
self.assertIn("ui", tokens)
self.assertIn("3d", tokens)
self.assertIn("ai", tokens)
def test_stopwords_removed(self):
bm25 = BM25()
tokens = bm25.tokenize("this is for the team to do")
for stopword in ("is", "for", "the", "to", "do"):
self.assertNotIn(stopword, tokens)
def test_synonym_normalization(self):
bm25 = BM25()
self.assertEqual(bm25.tokenize("e-commerce store"), bm25.tokenize("ecommerce store"))
self.assertEqual(bm25.tokenize("dark-mode toggle"), bm25.tokenize("dark toggle"))
class TestSearchDomains(unittest.TestCase):
"""Known query -> expected top-domain sanity checks (not exact-row pinning,
since data can grow; these assert the engine still finds *something*
relevant for each domain's core vocabulary)."""
def test_ui_is_searchable_in_style_domain(self):
result = search("ui minimalism", domain="style", max_results=1)
self.assertGreater(result["count"], 0, "literal 'ui' token must be searchable, not filtered by tokenizer")
def test_accessibility_query_hits_ux(self):
result = search("accessibility contrast wcag keyboard", domain="ux", max_results=3)
self.assertGreater(result["count"], 0)
def test_zero_result_query_reports_suggestions_not_error(self):
result = search("zzqqxx totally made up gibberish", domain="ux", max_results=2)
self.assertEqual(result["count"], 0)
self.assertIn("suggestions", result)
self.assertNotIn("error", result)
def test_every_configured_domain_file_exists_and_is_searchable(self):
for domain, config in CSV_CONFIG.items():
with self.subTest(domain=domain):
result = search("design", domain=domain, max_results=1)
self.assertNotIn("error", result, f"domain '{domain}' failed: {result.get('error')}")
def test_every_stack_file_exists_and_is_searchable(self):
for stack in AVAILABLE_STACKS:
with self.subTest(stack=stack):
result = search_stack("performance", stack, max_results=1)
self.assertNotIn("error", result, f"stack '{stack}' failed: {result.get('error')}")
class TestDomainDetection(unittest.TestCase):
def test_style_keywords_route_to_style(self):
self.assertEqual(detect_domain("glassmorphism dark ui"), "style")
def test_accessibility_keywords_route_to_ux(self):
self.assertEqual(detect_domain("accessibility contrast wcag"), "ux")
def test_ambiguous_query_returns_runner_up(self):
domain, runner_up = detect_domain("font pairing elegant crypto", return_scores=True)
self.assertIsNotNone(domain)
# runner_up may be None if the winning domain has no close second --
# this just verifies the call shape works without raising.
def test_empty_query_falls_back_to_style(self):
self.assertEqual(detect_domain("...!!!???"), "style")
class TestPersistence(unittest.TestCase):
def test_persist_then_skip_then_force(self):
with tempfile.TemporaryDirectory() as tmp:
result = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result["persistence"]["status"], "success")
master = Path(result["persistence"]["master_file"])
self.assertTrue(master.exists())
original_content = master.read_text(encoding="utf-8")
# Second persist without force must not overwrite.
result2 = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result2["persistence"]["status"], "skipped_exists")
self.assertEqual(master.read_text(encoding="utf-8"), original_content)
# With force=True it must overwrite.
result3 = generate_design_system("ecommerce luxury", "Test Project", persist=True, output_dir=tmp, force=True)
self.assertEqual(result3["persistence"]["status"], "success")
def test_persist_writes_only_under_output_dir(self):
with tempfile.TemporaryDirectory() as tmp:
generate_design_system("saas dashboard", "Scoped Project", persist=True, output_dir=tmp)
expected = Path(tmp) / "design-system" / "scoped-project" / "MASTER.md"
self.assertTrue(expected.exists())
class TestReasoningMatch(unittest.TestCase):
def test_known_category_matches_exactly(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("SaaS (General)")
self.assertTrue(rule, "exact-match category lookup should not fall through to fuzzy matching")
def test_unknown_category_falls_back_gracefully(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("Totally Unknown Category XYZ")
# Should not raise; may return {} which _apply_reasoning handles with defaults.
self.assertIsInstance(rule, dict)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Data integrity guardrail for ui-ux-pro-max. Stdlib-only, no pytest dependency,
so it can run as a standalone pre-publish/CI check:
python validate_data.py
Checks, per configured domain/stack CSV:
- file exists
- header row contains every column referenced in search_cols/output_cols
- no duplicate primary-key values (first column) within a file
- any "Decision_Rules"-style JSON column parses as JSON
Exits 0 with no output on success; exits 1 and prints every problem found
on failure (fail-fast is the wrong call here -- a data change can break
several files at once, so we want the full list in one run).
"""
import csv
import json
import sys
from pathlib import Path
from core import CSV_CONFIG, STACK_CONFIG, _STACK_COLS, DATA_DIR
# REASONING_FILE lives in design_system.py, not core.py -- redeclared here to
# avoid a circular import (design_system.py imports core.py).
REASONING_FILE = "ui-reasoning.csv"
JSON_COLUMNS = {"Decision_Rules"}
def _read_rows(filepath):
with open(filepath, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
return reader.fieldnames or [], list(reader)
def _check_file(label, filepath, search_cols, output_cols, problems):
if not filepath.exists():
problems.append(f"[{label}] missing file: {filepath}")
return
try:
headers, rows = _read_rows(filepath)
except (csv.Error, UnicodeDecodeError, OSError) as e:
problems.append(f"[{label}] failed to parse {filepath.name}: {e}")
return
header_set = set(headers)
for col in set(search_cols) | set(output_cols):
if col not in header_set:
problems.append(f"[{label}] {filepath.name}: expected column '{col}' not found in header")
# Only check for duplicates against an actual identifier column ("No" is
# the sequential-index convention used across this dataset). The first
# CSV column is not reliably a unique key -- e.g. stack files use
# "Category", which legitimately repeats across many guideline rows.
if "No" in header_set:
seen = {}
for i, row in enumerate(rows, start=2): # +1 header, +1 to be 1-indexed
key = row.get("No", "")
if key in seen:
problems.append(
f"[{label}] {filepath.name}: duplicate 'No' value '{key}' on rows {seen[key]} and {i}"
)
else:
seen[key] = i
elif label.startswith("stack:"):
problems.append(
f"[{label}] {filepath.name}: missing 'No' index column present in other stack files "
"(schema drift -- harmless for search, but inconsistent with the rest of data/stacks/)"
)
for row_idx, row in enumerate(rows, start=2):
for col in JSON_COLUMNS:
if col in row and row[col]:
try:
json.loads(row[col])
except json.JSONDecodeError as e:
problems.append(
f"[{label}] {filepath.name} row {row_idx}: column '{col}' is not valid JSON: {e}"
)
def main():
problems = []
for domain, config in CSV_CONFIG.items():
_check_file(f"domain:{domain}", DATA_DIR / config["file"],
config["search_cols"], config["output_cols"], problems)
for stack, config in STACK_CONFIG.items():
_check_file(f"stack:{stack}", DATA_DIR / config["file"],
_STACK_COLS["search_cols"], _STACK_COLS["output_cols"], problems)
reasoning_path = DATA_DIR / REASONING_FILE
if reasoning_path.exists():
_check_file("reasoning", reasoning_path, ["UI_Category"], ["UI_Category", "Decision_Rules"], problems)
else:
problems.append(f"[reasoning] missing file: {reasoning_path}")
if problems:
print(f"FAILED: {len(problems)} data integrity issue(s) found:\n")
for p in problems:
print(f" - {p}")
sys.exit(1)
print(f"OK: validated {len(CSV_CONFIG)} domain files, {len(STACK_CONFIG)} stack files, and ui-reasoning.csv")
sys.exit(0)
if __name__ == "__main__":
main()

View File

@ -5,6 +5,8 @@ on:
paths:
- "src/ui-ux-pro-max/**"
- "cli/assets/**"
- ".claude/skills/ui-ux-pro-max/data/**"
- ".claude/skills/ui-ux-pro-max/scripts/**"
- "cli/scripts/sync-assets.mjs"
- ".github/workflows/check-asset-sync.yml"
push:
@ -12,10 +14,12 @@ on:
paths:
- "src/ui-ux-pro-max/**"
- "cli/assets/**"
- ".claude/skills/ui-ux-pro-max/data/**"
- ".claude/skills/ui-ux-pro-max/scripts/**"
jobs:
check-assets:
name: cli/assets must match src/ui-ux-pro-max
name: cli/assets and .claude/skills/ui-ux-pro-max must match src/ui-ux-pro-max
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -24,6 +28,9 @@ jobs:
node-version: 20
# check:assets runs `node scripts/sync-assets.mjs --check`, which uses only
# node builtins (no npm install needed) and normalizes CRLF/LF before
# hashing, so it compares content rather than line endings.
- name: Check CLI assets are in sync with source of truth
# hashing, so it compares content rather than line endings. It checks
# both cli/assets/ AND .claude/skills/ui-ux-pro-max/{data,scripts} --
# the latter is what Claude Code actually loads when this repo is
# installed as a plugin, and previously had no sync check at all.
- name: Check assets are in sync with source of truth
run: npm --prefix cli run check:assets

View File

@ -57,14 +57,14 @@ cli/ # CLI installer (ui-ux-pro-max-cli on npm)
├── src/
│ ├── commands/init.ts # Install command with template generation
│ └── utils/template.ts # Template rendering engine
├── scripts/sync-assets.mjs # Mirrors src/ -> cli/assets/ AND src/ -> .claude/skills/ui-ux-pro-max/
└── assets/ # Bundled assets (~564KB)
├── data/ # Copy of src/ui-ux-pro-max/data/
├── scripts/ # Copy of src/ui-ux-pro-max/scripts/
└── templates/ # Copy of src/ui-ux-pro-max/templates/
.claude/skills/ui-ux-pro-max/ # Claude Code skill (symlinks to src/)
.factory/skills/ui-ux-pro-max/ # Droid (Factory) skill (symlinks to src/)
.shared/ui-ux-pro-max/ # Symlink to src/ui-ux-pro-max/
.claude/skills/ui-ux-pro-max/ # Claude Code skill: hand-authored SKILL.md +
# data/, scripts/ mirrored from src/ (see Sync Rules)
.claude-plugin/ # Claude Marketplace publishing
```
@ -74,24 +74,31 @@ The search engine uses BM25 ranking combined with regex matching. Domain auto-de
**Source of Truth:** `src/ui-ux-pro-max/`
There are no symlinks in this repo (git-on-Windows checks them out as plain
text files pointing at a path, which silently breaks the skill) -- every
mirrored copy below is a real, independently-committed file kept in sync by
`cli/scripts/sync-assets.mjs`, enforced by the "Check asset sync" CI workflow.
When modifying files:
1. **Data & Scripts** - Edit in `src/ui-ux-pro-max/`:
- `data/*.csv` and `data/stacks/*.csv`
- `scripts/*.py`
- Changes automatically available via symlinks in `.claude/`, `.factory/`, `.shared/`
- Then run the sync below -- changes are NOT automatically reflected anywhere else.
2. **Templates** - Edit in `src/ui-ux-pro-max/templates/`:
- `base/skill-content.md` - Common SKILL.md content
- `base/quick-reference.md` - Quick reference section (Claude only)
- `platforms/*.json` - Platform-specific configs
3. **CLI Assets** - Run sync before publishing:
3. **Sync before publishing / committing data or script changes:**
```bash
cd cli
npm run sync:assets
npm run check:assets
npm run sync:assets # mirrors src/ -> cli/assets/ AND src/ -> .claude/skills/ui-ux-pro-max/{data,scripts}
npm run check:assets # verify, no npm install required
```
`.claude/skills/ui-ux-pro-max/SKILL.md` itself is hand-authored, not
mirrored or template-generated -- edit it directly.
4. **Reference Folders** - No manual sync needed. The CLI generates these from templates during `uipro init`.

View File

@ -8,7 +8,7 @@
<p align="center">
<a href="https://github.com/nextlevelbuilder/ui-ux-pro-max-skill/releases"><img src="https://img.shields.io/github/v/release/nextlevelbuilder/ui-ux-pro-max-skill?style=for-the-badge&color=blue" alt="GitHub Release"></a>
<img src="https://img.shields.io/badge/reasoning_rules-161-green?style=for-the-badge" alt="161 Reasoning Rules">
<img src="https://img.shields.io/badge/UI_styles-67-purple?style=for-the-badge" alt="67 UI Styles">
<img src="https://img.shields.io/badge/UI_styles-84-purple?style=for-the-badge" alt="84 UI Styles">
<img src="https://img.shields.io/badge/python-3.x-yellow?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.x">
<a href="https://github.com/nextlevelbuilder/ui-ux-pro-max-skill/blob/main/LICENSE"><img src="https://img.shields.io/github/license/nextlevelbuilder/ui-ux-pro-max-skill?style=for-the-badge&color=green" alt="License"></a>
</p>
@ -106,11 +106,11 @@ The flagship feature of v2.0 is the **Design System Generator** - an AI-powered
┌─────────────────────────────────────────────────────────────────┐
│ 2. MULTI-DOMAIN SEARCH (5 parallel searches) │
│ • Product type matching (161 categories) │
│ • Style recommendations (67 styles) │
│ • Color palette selection (161 palettes) │
│ • Landing page patterns (24 patterns) │
│ • Typography pairing (57 font combinations) │
│ • Product type matching (192 categories) │
│ • Style recommendations (84 styles) │
│ • Color palette selection (192 palettes) │
│ • Landing page patterns (34 patterns) │
│ • Typography pairing (74 font combinations) │
└─────────────────────────────────────────────────────────────────┘
@ -155,12 +155,12 @@ Each rule includes:
## Features
- **67 UI Styles** - Glassmorphism, Claymorphism, Minimalism, Brutalism, Neumorphism, Bento Grid, Dark Mode, AI-Native UI, and more
- **161 Color Palettes** - Industry-specific palettes aligned 1:1 with the 161 product types
- **57 Font Pairings** - Curated typography combinations with Google Fonts imports
- **84 UI Styles** - Glassmorphism, Claymorphism, Minimalism, Brutalism, Neumorphism, Bento Grid, Dark Mode, AI-Native UI, and more
- **192 Color Palettes** - Industry-specific palettes aligned 1:1 with the 192 product types
- **74 Font Pairings** - Curated typography combinations with Google Fonts imports
- **25 Chart Types** - Recommendations for dashboards and analytics
- **22 Tech Stacks** - React, Next.js, Astro, Vue, Nuxt.js, Nuxt UI, Svelte, SwiftUI, React Native, Flutter, HTML+Tailwind, shadcn/ui, Jetpack Compose, Angular, Laravel, Three.js, JavaFX, WPF, WinUI 3, UWP, Avalonia, Uno Platform
- **99 UX Guidelines** - Best practices, anti-patterns, and accessibility rules
- **98 UX Guidelines** - Best practices, anti-patterns, and accessibility rules
- **161 Reasoning Rules** - Industry-specific design system generation (NEW in v2.0)
### Available Styles (67)
@ -262,7 +262,7 @@ Many users ask about the differences between the open-source and premium version
### 🟢 Basic Version (This Repository)
* **Fully Open Source:** Perfect for individual developers, hobbyists, and standard projects.
* **Core UI/UX Intelligence:** Full access to 67 UI styles, 161 product types, color palettes, and curated font pairings.
* **Core UI/UX Intelligence:** Full access to 84 UI styles, 192 product types, color palettes, and curated font pairings.
* **Smart Recommendations:** Built-in BM25 search engine for highly accurate design matching.
* **Cross-Platform Support:** Stack-specific guidelines supporting 22 major frameworks (React, Vue, Tailwind, iOS, Android, etc.).
* **Design System Generation:** Instantly generate tailored UI rules, patterns, and logic via CLI.

View File

@ -1,54 +1,54 @@
Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,"// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag","<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime","function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color","renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });","// No resize handler — scene stretches to fill a wider window without correcting the projection",High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));","// No position or lookAt set — subject at y:2 is behind or above the default camera view",Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,"function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); }","scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });","const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit",Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material","for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials",High,https://threejs.org/docs/#api/en/materials/Material
Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,"const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();","const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload",High,https://threejs.org/docs/#api/en/textures/Texture.dispose
Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;","dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags","for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,"mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED","mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored",Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes","const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children",High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,"if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; }","raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.","Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame","Call clock.getDelta() more than once per frame or inside a helper called from animate()","const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz }",High,https://threejs.org/docs/#api/en/core/Clock
Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,"// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);","// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing",Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });","let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps",High,https://gsap.com/docs/v3/GSAP/Timeline/
Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';","import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js",Critical,https://gsap.com/docs/v3/Installation
GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,"renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128","const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context","const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear","// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame",Low,https://threejs.org/docs/#api/en/scenes/FogExp2
Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,"const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);","const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone",High,https://threejs.org/docs/#api/en/objects/Points
Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,"// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload","// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move",Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.","Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value","Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes","const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }","const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely",High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);","document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing",Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,"npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';","<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);","scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera",Medium,https://threejs.org/docs/#api/en/objects/LOD
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
2,Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
3,Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
4,Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
5,Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag,"<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
6,Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime",function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile,Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
7,Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
8,Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color",renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
9,Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });",// No resize handler — scene stretches to fill a wider window without correcting the projection,High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
10,Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11,Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));",// No position or lookAt set — subject at y:2 is behind or above the default camera view,Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
12,Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
13,Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
14,Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
15,Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); },scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever,Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
16,Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
17,Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
18,Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });",const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit,Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
19,Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material",for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials,High,https://threejs.org/docs/#api/en/materials/Material
20,Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();,const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload,High,https://threejs.org/docs/#api/en/textures/Texture.dispose
21,Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
22,Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;,dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
23,Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags,for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24,Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
25,Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
26,Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored,Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
27,Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
28,Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes",const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children,High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
29,Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; },"raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
30,Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
31,Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.",Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame,Call clock.getDelta() more than once per frame or inside a helper called from animate(),"const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }",function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz },High,https://threejs.org/docs/#api/en/core/Clock
32,Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);,// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing,Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
33,Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });",let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps,High,https://gsap.com/docs/v3/GSAP/Timeline/
34,Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
35,GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';",import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js,Critical,https://gsap.com/docs/v3/Installation
36,GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
37,GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
38,GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
39,Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
40,Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128,const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
41,Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context",const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
42,Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear",// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame,Low,https://threejs.org/docs/#api/en/scenes/FogExp2
43,Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
44,Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);,const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone,High,https://threejs.org/docs/#api/en/objects/Points
45,Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload,// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move,Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
46,Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
47,Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
48,Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
49,Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.",Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value,Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes,"const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }",const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely,High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
50,Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);",document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing,Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
51,Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';,"<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
52,Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
53,Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);",scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera,Medium,https://threejs.org/docs/#api/en/objects/LOD

1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 Setup CDN Version Lock Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning. Pin to the exact r128 cdnjs URL in every HTML file Use unpkg@latest or any unversioned CDN URL that can silently update <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://unpkg.com/three@latest"></script> Critical https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
3 2 Setup CapsuleGeometry Does Not Exist in r128 THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead. Build a capsule from CylinderGeometry plus two SphereGeometry end caps Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap); const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128 Critical https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
4 3 Setup OrbitControls Must Be Loaded Separately OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it. Load the OrbitControls script from cdnjs examples path before your scene script Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script <!-- Load AFTER core Three.js script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js"></script> <!-- Core only loaded — OrbitControls undefined --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> Critical https://cdnjs.com/libraries/three.js/r128
5 4 Setup Custom Drag Orbit Fallback When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly. Rotate camera in spherical coordinates so both axes respond correctly to drag Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere High https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
6 5 Setup ESM vs CDN Import When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors. Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages Mix a CDN script tag with an ES module import in the same file // Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag <!-- CDN script --> <script src="r128.cdn"></script> <script type="module"> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script> Critical https://threejs.org/docs/#manual/en/introduction/Installation
7 6 Setup Single Renderer Per Page Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (8–16 contexts) and cause context-lost errors especially on mobile. Reuse a single renderer and swap scene content instead of recreating the renderer Create a new renderer on each component mount or scene transition const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer
8 7 Setup Pixel Ratio Cap at 2 Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance. Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3 Pass window.devicePixelRatio directly without any cap renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
9 8 Setup Alpha Canvas Plus CSS Background Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it. Set alpha:true on renderer and let body or a parent div provide the background color Set a solid renderer clear color when the canvas must composite over HTML behind it const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
10 9 Camera Aspect Ratio on Resize Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally. Update camera.aspect then call updateProjectionMatrix() on every resize Let aspect ratio become stale after the browser window changes size window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); }); // No resize handler — scene stretches to fill a wider window without correcting the projection High https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11 10 Camera FOV Range 45 to 75 Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges. Start at 75 for general interactive scenes; use 45–55 for product close-ups Use FOV above 90 or below 30 without a deliberate artistic reason const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges Medium https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
12 11 Camera Explicit Position and lookAt Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny. Set camera.position.set() and camera.lookAt() to frame the subject before the first render Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0)); // No position or lookAt set — subject at y:2 is behind or above the default camera view Medium https://threejs.org/docs/#api/en/cameras/Camera.lookAt
13 12 Camera OrbitControls vs GSAP Camera Rig Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed. Match camera control approach to the UX intent of the scene Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes // Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate() // Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes High https://threejs.org/docs/#examples/en/controls/OrbitControls
14 13 Geometry Never Create Geometry Per Frame Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame. Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed Call any new XxxGeometry() constructor inside the animation loop const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
15 14 Geometry Share Geometry Across Meshes When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer. Create one geometry and pass the same reference to every Mesh constructor Create a separate identical geometry inside a loop for each object const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); } for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
16 15 Geometry dispose on Scene Removal Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed. Dispose of geometry + material + every texture map before calling scene.remove() Call scene.remove() alone without any dispose calls function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); } scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever Critical https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
17 16 Geometry Segment Count Budget Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 32–64 segments. Background objects: 8–16. Particle stand-ins: 6–8. High counts on background geometry waste GPU draw calls with zero visible benefit. Apply a tiered segment budget based on the visual priority of each object in the scene Default every sphere and cylinder to 64+ segments regardless of its role const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw Medium https://threejs.org/docs/#api/en/geometries/SphereGeometry
18 17 Geometry BufferGeometry for Custom Vertex Data For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128. Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data Reference or instantiate the removed THREE.Geometry class const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3)); const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128 High https://threejs.org/docs/#api/en/core/BufferGeometry
19 18 Materials MeshBasicMaterial vs MeshStandardMaterial MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices. Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 }); const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit Medium https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
20 19 Materials Share Material Instances Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM. Assign the same material reference to all meshes with identical visual properties Create a new material inside a loop for objects that look identical const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials High https://threejs.org/docs/#api/en/materials/Material
21 20 Materials Dispose Textures Explicitly Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically. Track all loaded textures and call dispose() on each one during scene teardown or on object removal Load textures without any cleanup path — they persist in VRAM for the entire page lifetime const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose(); const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload High https://threejs.org/docs/#api/en/textures/Texture.dispose
22 21 Lighting Ambient Plus Directional Minimum Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it. Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used Use MeshStandardMaterial without adding any lights to the scene scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight); const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene Critical https://threejs.org/docs/#api/en/lights/DirectionalLight
23 22 Lighting Enable shadowMap Before castShadow renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored. Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true; dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24 23 Lighting Selective Shadow Casting Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane. Enable shadows only on the key light and the most important meshes Enable castShadow and receiveShadow on every object in the scene including particles renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
25 24 Lighting Skip Lights for MeshBasicMaterial MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect. Omit lights entirely when every material in the scene is MeshBasicMaterial Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial // Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely Low https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
26 25 Raycasting Single Shared Raycaster Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event. Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate() Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate() window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec }); Critical https://threejs.org/docs/#api/en/core/Raycaster
27 26 Raycasting NDC Mouse Coordinates Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects. Apply the full NDC formula — including the negation on the Y axis Forget to negate Y — raycasting appears to work but hits objects mirrored vertically mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored Critical https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
28 27 Raycasting setFromCamera and intersectObjects in animate Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction. Call setFromCamera then intersectObjects in order inside every animate() frame Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); } Critical https://threejs.org/docs/#api/en/core/Raycaster
29 28 Raycasting Recursive Flag for Groups and GLTF Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty. Use intersectObjects(targets true) for Groups or any loaded model Raycast against a parent Group without the recursive flag const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children High https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
30 29 Raycasting Cursor Feedback on Hover Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive. Update cursor to pointer on hit; reset to auto on miss in the same animate loop block Run raycasting and read hits without ever updating the cursor style if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive Medium https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
31 30 Animation requestAnimationFrame Loop Only Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery. Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver Use setInterval or setTimeout for render timing function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate(); setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
32 31 Animation THREE.Clock for Delta Time Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it. Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame Call clock.getDelta() more than once per frame or inside a helper called from animate() const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz } High https://threejs.org/docs/#api/en/core/Clock
33 32 Animation Lerp for Smooth Pointer Follow Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.03–0.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP. Apply the lerp formula each frame with a small alpha for smooth organic motion Snap a value directly to the target producing an instant jarring jump // In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position); // In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing Medium https://threejs.org/docs/#api/en/math/MathUtils.lerp
34 33 Animation GSAP for Multi-Step Sequences Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines. Use GSAP timelines for sequences with more than two steps and for scroll-driven animations Implement multi-step sequences with boolean flags and manual frame counters const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 }); let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps High https://gsap.com/docs/v3/GSAP/Timeline/
35 34 Animation Pause Render Loop on Tab Hidden Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit. Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); }); function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery High https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
36 35 GSAP Load GSAP Before Scene Script Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package. Load GSAP CDN before the scene script; or npm install gsap and import separately Import gsap from three or expect it to be defined without a separate load <!-- CDN: load GSAP before your scene script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js Critical https://gsap.com/docs/v3/Installation
37 36 GSAP Register ScrollTrigger Before Use Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately. Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger Include scrollTrigger config in gsap.to() calls without first registering the plugin gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } }); gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered Critical https://gsap.com/docs/v3/Plugins/ScrollTrigger/
38 37 GSAP Tween Three.js Properties Directly GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts. Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity Use a plain proxy object then manually copy values to Three.js properties every frame gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 }); const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper Medium https://gsap.com/docs/v3/GSAP/gsap.to()
39 38 GSAP scrub for Scroll-Driven Camera Path Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 0–1 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path. Use scrub:1 for any scroll-controlled camera movement Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } }); gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub High https://gsap.com/docs/v3/Plugins/ScrollTrigger/
40 39 Performance InstancedMesh for Repeated Objects Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically. Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material Create 50+ separate Mesh objects with the same geometry and material const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/InstancedMesh
41 40 Performance Tone Mapping and sRGB Encoding Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately. Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes Leave tone mapping and output encoding at defaults when the scene targets realistic visuals renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128 const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
42 41 Performance antialias Set at Construction Only The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating. Set antialias:true inside the WebGLRenderer constructor options object Construct the renderer without antialias then try to enable it by assigning the property const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased High https://threejs.org/docs/#api/en/renderers/WebGLRenderer
43 42 Performance FogExp2 for Depth and Far Culling Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances. Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear // far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame Low https://threejs.org/docs/#api/en/scenes/FogExp2
44 43 Particles BufferGeometry Plus Points for Particle Systems Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance. Use Points plus BufferGeometry for all particle effects Create hundreds of individual Mesh objects to simulate a particle system const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/Points
45 44 Particles Particle Count Ceiling Start particle systems at 1000–3000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1. Start at 3000 particles and profile on actual mobile hardware before raising the limit Set particle count at 100000 or higher without any mobile profiling const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3); const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone High https://threejs.org/docs/#api/en/objects/Points
46 45 Particles needsUpdate After Buffer Mutation After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen. Set needsUpdate = true on the position attribute after every per-frame mutation of the array Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU // In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload // In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move Critical https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
47 46 Responsive Canvas Dimensions Not Window Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport. Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
48 47 Responsive ResizeObserver Over window resize Event Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing. Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement); window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs Medium https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
49 48 Responsive Touch Events for Mobile Interaction Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault. Handle both mouse and touch input for any interactive 3D scene Add only mouse event listeners and leave touch users with no interaction canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false }); canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction Medium https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
50 49 Accessibility prefers-reduced-motion Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime. Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; } const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely High https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
51 50 Accessibility Canvas aria-label Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users. Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it Append the canvas to the DOM with no accessibility attributes — invisible to screen readers renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement); document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing Medium https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
52 51 Production Bundler Stack for Production For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support. Use npm install three plus Vite or Webpack for any production client-facing project Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; <!-- In a Vite/React production build: --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> // no tree-shaking — entire Three.js ships Medium https://threejs.org/docs/#manual/en/introduction/Installation
53 52 Production GLTFLoader with scene traverse Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration. Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); }); loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children }); Medium https://threejs.org/docs/#examples/en/loaders/GLTFLoader
54 53 Production LOD for Distance-Based Detail Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range. Use THREE.LOD to reduce triangle count on distant objects automatically Render the same high-polygon geometry for every object regardless of its distance from the camera const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 15–50 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod); scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera Medium https://threejs.org/docs/#api/en/objects/LOD

View File

@ -77,6 +77,14 @@ CSV_CONFIG = {
}
}
# Output columns whose content (code samples, checklists) must never be
# hard-truncated for display -- truncating mid-snippet destroys the value.
UNTRUNCATED_COLS = {
"Code Example Good", "Code Example Bad", "Code Good", "Code Bad",
"Implementation Checklist", "Design System Variables", "CSS Import",
"Tailwind Config", "GSAP Snippet",
}
STACK_CONFIG = {
"react": {"file": "stacks/react.csv"},
"nextjs": {"file": "stacks/nextjs.csv"},
@ -111,6 +119,44 @@ _STACK_COLS = {
AVAILABLE_STACKS = list(STACK_CONFIG.keys())
# ============ TOKENIZATION ============
# Common two-letter/three-letter words that add noise without adding search
# signal. Deliberately short -- domain-relevant short tokens (ui, ux, ai,
# css, 3d, js, os, md, gsap) must stay searchable, which is why we don't
# filter purely by length.
_STOPWORDS = {
"to", "in", "on", "at", "is", "of", "by", "or", "an", "if", "no", "so",
"do", "be", "we", "it", "as", "the", "and", "for", "are", "was",
}
# Query/corpus normalization so common spelling variants match each other.
# Keep this a plain dict (stdlib only, no fuzzy-matching dependency).
_SYNONYMS = {
"e-commerce": "ecommerce",
"dark-mode": "dark",
"darkmode": "dark",
"light-mode": "light",
"lightmode": "light",
"a11y": "accessibility",
"nav": "navigation",
"sign-up": "signup",
"log-in": "login",
"colour": "color",
"colours": "colors",
"customisation": "customization",
"organisation": "organization",
"behaviour": "behavior",
"ux/ui": "ux ui",
}
def _normalize(text):
"""Apply synonym substitution before tokenizing."""
for variant, canonical in _SYNONYMS.items():
text = text.replace(variant, canonical)
return text
# ============ BM25 IMPLEMENTATION ============
class BM25:
"""BM25 ranking algorithm for text search"""
@ -124,11 +170,13 @@ class BM25:
self.idf = {}
self.doc_freqs = defaultdict(int)
self.N = 0
self._term_freqs = [] # precomputed per-doc term frequencies
def tokenize(self, text):
"""Lowercase, split, remove punctuation, filter short words"""
text = re.sub(r'[^\w\s]', ' ', str(text).lower())
return [w for w in text.split() if len(w) >= 2]
"""Lowercase, normalize synonyms, split, remove punctuation, filter stopwords"""
text = _normalize(str(text).lower())
text = re.sub(r'[^\w\s]', ' ', text)
return [w for w in text.split() if len(w) >= 2 and w not in _STOPWORDS]
def fit(self, documents):
"""Build BM25 index from documents"""
@ -139,12 +187,14 @@ class BM25:
self.doc_lengths = [len(doc) for doc in self.corpus]
self.avgdl = sum(self.doc_lengths) / self.N
self._term_freqs = []
for doc in self.corpus:
seen = set()
tf = defaultdict(int)
for word in doc:
if word not in seen:
self.doc_freqs[word] += 1
seen.add(word)
tf[word] += 1
self._term_freqs.append(tf)
for word in tf:
self.doc_freqs[word] += 1
for word, freq in self.doc_freqs.items():
self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
@ -154,16 +204,14 @@ class BM25:
query_tokens = self.tokenize(query)
scores = []
for idx, doc in enumerate(self.corpus):
for idx in range(self.N):
score = 0
doc_len = self.doc_lengths[idx]
term_freqs = defaultdict(int)
for word in doc:
term_freqs[word] += 1
term_freqs = self._term_freqs[idx]
for token in query_tokens:
if token in self.idf:
tf = term_freqs[token]
tf = term_freqs.get(token, 0)
idf = self.idf[token]
numerator = tf * (self.k1 + 1)
denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
@ -173,48 +221,139 @@ class BM25:
return sorted(scores, key=lambda x: x[1], reverse=True)
def vocabulary(self):
"""All indexed terms, for suggestion/typo-recovery purposes."""
return list(self.idf.keys())
# ============ CSV / INDEX CACHE ============
# Data files are small and reused across multiple domain searches within a
# single --design-system run; avoid re-reading + re-indexing the same file
# repeatedly in one process.
_csv_cache = {} # filepath -> (mtime, rows)
_bm25_cache = {} # (filepath, tuple(search_cols)) -> (mtime, BM25 instance)
# ============ SEARCH FUNCTIONS ============
def _load_csv(filepath):
"""Load CSV and return list of dicts"""
"""Load CSV and return list of dicts, with mtime-based caching."""
mtime = filepath.stat().st_mtime
cached = _csv_cache.get(filepath)
if cached and cached[0] == mtime:
return cached[1]
with open(filepath, 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
rows = list(csv.DictReader(f))
_csv_cache[filepath] = (mtime, rows)
return rows
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25"""
if not filepath.exists():
return []
def _get_bm25(filepath, search_cols, data):
"""Fitted BM25 index for this file+columns, with mtime-based caching."""
key = (filepath, tuple(search_cols))
mtime = filepath.stat().st_mtime
cached = _bm25_cache.get(key)
if cached and cached[0] == mtime:
return cached[1]
data = _load_csv(filepath)
# Build documents from search columns
documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
# BM25 search
bm25 = BM25()
bm25.fit(documents)
_bm25_cache[key] = (mtime, bm25)
return bm25
# ============ SEARCH FUNCTIONS ============
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25. Returns (results, bm25_or_none)."""
if not filepath.exists():
return [], None
try:
data = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError) as e:
return [{"_error": f"Failed to read {filepath.name}: {e}"}], None
if not data:
return [], None
bm25 = _get_bm25(filepath, search_cols, data)
ranked = bm25.score(query)
# Get top results with score > 0
results = []
for idx, score in ranked[:max_results]:
if score > 0:
row = data[idx]
results.append({col: row.get(col, "") for col in output_cols if col in row})
return results
return results, bm25
def detect_domain(query):
"""Auto-detect the most relevant domain from query"""
query_lower = query.lower()
def _suggest_terms(bm25, query, limit=6):
"""Nearest known vocabulary terms for a query that returned 0 hits,
so the caller can retry instead of silently reporting nothing."""
if bm25 is None:
return []
query_tokens = set(bm25.tokenize(query))
if not query_tokens:
return []
domain_keywords = {
candidates = []
for term in bm25.vocabulary():
for qt in query_tokens:
if term.startswith(qt[:3]) or qt.startswith(term[:3]):
candidates.append(term)
break
# Stable de-dup, most frequent terms first (doc_freqs available via idf keys only,
# so just de-dup preserving discovery order).
seen = set()
ordered = []
for term in candidates:
if term not in seen:
seen.add(term)
ordered.append(term)
return ordered[:limit]
# Load the product-domain keyword list from products.csv at import time so
# it stays in sync with the data instead of needing manual updates to a
# hardcoded list. Falls back to a small built-in seed if the file is
# missing (e.g. package built without data/).
def _load_product_keywords():
seed = ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming",
"portfolio", "crypto", "dashboard", "fitness", "marketplace"]
filepath = DATA_DIR / CSV_CONFIG["product"]["file"]
if not filepath.exists():
return seed
try:
rows = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError):
return seed
keywords = set(seed)
for row in rows:
raw = row.get("Keywords", "")
for kw in re.split(r"[,;]", raw):
kw = kw.strip().lower()
if kw and len(kw) >= 3:
keywords.add(kw)
return sorted(keywords, key=len, reverse=True)
_DOMAIN_KEYWORDS = None
def _domain_keywords():
global _DOMAIN_KEYWORDS
if _DOMAIN_KEYWORDS is not None:
return _DOMAIN_KEYWORDS
_DOMAIN_KEYWORDS = {
"color": ["color", "palette", "hex", "#", "rgb", "token", "semantic", "accent", "destructive", "muted", "foreground"],
"chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
"landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
"product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard", "fitness", "restaurant", "hotel", "travel", "music", "education", "learning", "legal", "insurance", "medical", "beauty", "pharmacy", "dental", "pet", "dating", "wedding", "recipe", "delivery", "ride", "booking", "calendar", "timer", "tracker", "diary", "note", "chat", "messenger", "crm", "invoice", "parking", "transit", "vpn", "alarm", "weather", "sleep", "meditation", "fasting", "habit", "grocery", "meme", "wardrobe", "plant care", "reading", "flashcard", "puzzle", "trivia", "arcade", "photography", "streaming", "podcast", "newsletter", "marketplace", "freelancer", "coworking", "airline", "museum", "theater", "church", "non-profit", "charity", "kindergarten", "daycare", "senior care", "veterinary", "florist", "bakery", "brewery", "construction", "automotive", "real estate", "logistics", "agriculture", "coding bootcamp"],
"product": _load_product_keywords(),
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"],
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
"typography": ["font pairing", "typography pairing", "heading font", "body font"],
@ -224,16 +363,57 @@ def detect_domain(query):
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
}
return _DOMAIN_KEYWORDS
scores = {domain: sum(1 for kw in keywords if re.search(r'\b' + re.escape(kw) + r'\b', query_lower)) for domain, keywords in domain_keywords.items()}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else "style"
# Domains checked in this fixed order when scores tie, so results are
# deterministic instead of depending on dict/hash ordering.
_DOMAIN_TIEBREAK_ORDER = [
"ux", "product", "style", "color", "typography", "google-fonts",
"chart", "landing", "icons", "gsap", "react", "web",
]
def detect_domain(query, return_scores=False):
"""Auto-detect the most relevant domain from query.
Matches are weighted by keyword length (multi-word/longer phrases are
more specific and score higher than short generic words). Ties are
broken by a fixed domain priority order, not dict/insertion order.
"""
query_lower = query.lower()
domain_keywords = _domain_keywords()
scores = {}
for domain, keywords in domain_keywords.items():
total = 0.0
for kw in keywords:
if re.search(r'\b' + re.escape(kw) + r'\b', query_lower):
# weight = 1 point per word in the keyword phrase
total += max(1, len(kw.split()))
scores[domain] = total
ranked = sorted(
scores.items(),
key=lambda item: (item[1], -_DOMAIN_TIEBREAK_ORDER.index(item[0])
if item[0] in _DOMAIN_TIEBREAK_ORDER else -999),
reverse=True,
)
best_domain, best_score = ranked[0]
result = best_domain if best_score > 0 else "style"
if return_scores:
runner_up = ranked[1][0] if len(ranked) > 1 and ranked[1][1] > 0 else None
return result, runner_up
return result
def search(query, domain=None, max_results=MAX_RESULTS):
"""Main search function with auto-domain detection"""
auto_detected = domain is None
runner_up = None
if domain is None:
domain = detect_domain(query)
domain, runner_up = detect_domain(query, return_scores=True)
config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
filepath = DATA_DIR / config["file"]
@ -241,15 +421,22 @@ def search(query, domain=None, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"File not found: {filepath}", "domain": domain}
results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
return {
out = {
"domain": domain,
"query": query,
"file": config["file"],
"count": len(results),
"results": results
"results": results,
}
if auto_detected:
out["auto_detected"] = True
if runner_up:
out["runner_up_domain"] = runner_up
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out
def search_stack(query, stack, max_results=MAX_RESULTS):
@ -262,13 +449,16 @@ def search_stack(query, stack, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"Stack file not found: {filepath}", "stack": stack}
results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
return {
out = {
"domain": "stack",
"stack": stack,
"query": query,
"file": STACK_CONFIG[stack]["file"],
"count": len(results),
"results": results
"results": results,
}
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out

View File

@ -7,10 +7,12 @@ to generate comprehensive design system recommendations.
Usage:
from design_system import generate_design_system
result = generate_design_system("SaaS dashboard", "My Project")
print(result["text"])
# With persistence (Master + Overrides pattern)
result = generate_design_system("SaaS dashboard", "My Project", persist=True)
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")
result = generate_design_system("SaaS dashboard", "My Project", persist=True, output_dir="/path/to/project")
result["persistence"] # {"status": "success"|"skipped_exists", "created_files": [...], ...}
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard", output_dir="/path/to/project")
"""
import csv
@ -665,7 +667,8 @@ def format_markdown(design_system: dict) -> str:
# ============ MAIN ENTRY POINT ============
def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None) -> str:
variance: int = None, motion: int = None, density: int = None,
force: bool = False) -> dict:
"""
Main entry point for design system generation.
@ -679,20 +682,28 @@ def generate_design_system(query: str, project_name: str = None, output_format:
variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
Returns:
Formatted design system string
dict with keys: "text" (formatted design system string), "design_system"
(raw dict, useful for --json callers), and "persistence" (result of
persist_design_system(), or None if persist=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
# Persist to files if requested
persistence_result = None
if persist:
persist_design_system(design_system, page, output_dir, query)
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
if output_format == "markdown":
return format_markdown(design_system)
return format_ascii_box(design_system)
text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system)
return {
"text": text,
"design_system": design_system,
"persistence": persistence_result,
}
# ============ PERSISTENCE FUNCTIONS ============
@ -707,42 +718,61 @@ def safe_slug(name, fallback: str = "default") -> str:
return slug or fallback
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict:
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
page_query: str = None, force: bool = False) -> dict:
"""
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
Args:
design_system: The generated design system dictionary
page: Optional page name for page-specific override file
output_dir: Optional output directory (defaults to current working directory)
page_query: Optional query string for intelligent page override generation
force: If True, overwrite an existing MASTER.md. If False (default) and
MASTER.md already exists, persistence is skipped so prior design
decisions aren't silently discarded.
Returns:
dict with created file paths and status
dict with created file paths and status. status is "skipped_exists" if
MASTER.md already existed and force was not set.
"""
base_dir = Path(output_dir) if output_dir else Path.cwd()
# Use project name for project-specific folder. Coalesce falsy values
# (missing key, explicit None, or "") so slugification can't crash.
project_slug = safe_slug(design_system.get("project_name") or "default")
# (missing key, explicit None, or "") so the .lower() below can't crash.
project_name = design_system.get("project_name") or "default"
project_slug = safe_slug(project_name)
design_system_dir = base_dir / "design-system" / project_slug
pages_dir = design_system_dir / "pages"
master_file = design_system_dir / "MASTER.md"
if master_file.exists() and not force:
return {
"status": "skipped_exists",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": [],
"message": (
f"{master_file} already exists and was not modified. "
"Read it first to check for prior design decisions, then "
"re-run with force=True / --force to overwrite."
),
}
created_files = []
# Create directories
design_system_dir.mkdir(parents=True, exist_ok=True)
pages_dir.mkdir(parents=True, exist_ok=True)
master_file = design_system_dir / "MASTER.md"
# Generate and write MASTER.md
master_content = format_master_md(design_system)
with open(master_file, 'w', encoding='utf-8') as f:
f.write(master_content)
created_files.append(str(master_file))
# If page is specified, create page override file with intelligent content
if page:
page_file = pages_dir / f"{safe_slug(page, 'page')}.md"
@ -750,10 +780,11 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
with open(page_file, 'w', encoding='utf-8') as f:
f.write(page_content)
created_files.append(str(page_file))
return {
"status": "success",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": created_files
}
@ -1337,4 +1368,4 @@ if __name__ == "__main__":
args = parser.parse_args()
result = generate_design_system(args.query, args.project_name, args.format)
print(result)
print(result["text"])

View File

@ -4,11 +4,12 @@
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
python search.py "<query>" --design-system --variance 8 --motion 9 --density 7
Domains: style, prompt, color, chart, landing, product, ux, typography, google-fonts, gsap
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui, html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel, javafx, wpf, winui, avalonia, uno, uwp
Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui,
html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel
Design dials (1-10, only with --design-system):
--variance DESIGN_VARIANCE: 1=centered/minimal, 10=bold/asymmetric
@ -16,15 +17,20 @@ Design dials (1-10, only with --design-system):
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/MASTER.md
--page Also create a page-specific override file in design-system/pages/
--persist Save design system to design-system/<project-slug>/MASTER.md
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
always pass this explicitly, pointed at the project root)
--page Also create a page-specific override file in design-system/<project-slug>/pages/
--force Overwrite an existing MASTER.md (without this, persistence is skipped
if MASTER.md already exists, so prior design decisions aren't lost)
"""
import argparse
import json as json_module
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system, persist_design_system, safe_slug
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, UNTRUNCATED_COLS, search, search_stack
from design_system import generate_design_system
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
@ -32,27 +38,47 @@ if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
TRUNCATE_AT = 300
def format_output(result):
def format_output(result, full=False):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append(f"## UI Pro Max Stack Guidelines")
output.append("## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append(f"## UI Pro Max Search Results")
output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
output.append("## UI Pro Max Search Results")
domain_note = result['domain']
if result.get("auto_detected"):
domain_note += " (auto-detected"
if result.get("runner_up_domain"):
domain_note += f", runner-up: {result['runner_up_domain']}"
domain_note += ")"
output.append(f"**Domain:** {domain_note} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
if result['count'] == 0:
output.append(
"No matches. This is not a match with an empty value -- the query "
"did not hit the database. Retry with broader/different keywords "
"before falling back to general defaults, and say explicitly that "
"no database match was found if you do fall back."
)
suggestions = result.get("suggestions") or []
if suggestions:
output.append(f"**Closest known terms:** {', '.join(suggestions)}")
return "\n".join(output)
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if len(value_str) > 300:
value_str = value_str[:300] + "..."
if not full and key not in UNTRUNCATED_COLS and len(value_str) > TRUNCATE_AT:
value_str = value_str[:TRUNCATE_AT] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
@ -66,14 +92,16 @@ if __name__ == "__main__":
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
parser.add_argument("--full", action="store_true", help="Do not truncate long field values in text output")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system (ignored if --json)")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/<project-slug>/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/<project-slug>/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
# Design dials (1-10), only applied with --design-system
parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)")
parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)")
@ -92,36 +120,43 @@ if __name__ == "__main__":
output_dir=args.output_dir,
variance=args.variance,
motion=args.motion,
density=args.density
density=args.density,
force=args.force,
)
print(result)
# Print persistence confirmation
if args.persist:
project_slug = safe_slug(args.project_name or args.query.upper())
print("\n" + "=" * 60)
print(f"✅ Design system persisted to design-system/{project_slug}/")
print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
if args.page:
page_filename = safe_slug(args.page, 'page')
print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
print("")
print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
if args.json:
print(json_module.dumps(
{"design_system": result["design_system"], "persistence": result["persistence"]},
indent=2, ensure_ascii=False,
))
else:
print(result["text"])
if args.persist:
persistence = result["persistence"] or {}
print("\n" + "=" * 60)
if persistence.get("status") == "skipped_exists":
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
else:
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
print(f"✅ Design system persisted to {ds_dir}/")
for f in persistence.get("created_files", []):
print(f" 📄 {f}")
print("")
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.")
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
print(format_output(result, full=args.full))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
print(format_output(result, full=args.full))

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stdlib-only regression tests for core.py / design_system.py (unittest, not
pytest -- this project ships with zero external dependencies and the tests
shouldn't add one).
Run with:
python -m unittest discover -s scripts/tests -v
or directly:
python scripts/tests/test_core.py
"""
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPTS_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SCRIPTS_DIR))
from core import BM25, detect_domain, search, search_stack, CSV_CONFIG, AVAILABLE_STACKS
from design_system import generate_design_system, persist_design_system, DesignSystemGenerator
class TestTokenizer(unittest.TestCase):
def test_short_domain_terms_are_kept(self):
bm25 = BM25()
tokens = bm25.tokenize("UI and UX design with 3D and AI")
self.assertIn("ui", tokens)
self.assertIn("3d", tokens)
self.assertIn("ai", tokens)
def test_stopwords_removed(self):
bm25 = BM25()
tokens = bm25.tokenize("this is for the team to do")
for stopword in ("is", "for", "the", "to", "do"):
self.assertNotIn(stopword, tokens)
def test_synonym_normalization(self):
bm25 = BM25()
self.assertEqual(bm25.tokenize("e-commerce store"), bm25.tokenize("ecommerce store"))
self.assertEqual(bm25.tokenize("dark-mode toggle"), bm25.tokenize("dark toggle"))
class TestSearchDomains(unittest.TestCase):
"""Known query -> expected top-domain sanity checks (not exact-row pinning,
since data can grow; these assert the engine still finds *something*
relevant for each domain's core vocabulary)."""
def test_ui_is_searchable_in_style_domain(self):
result = search("ui minimalism", domain="style", max_results=1)
self.assertGreater(result["count"], 0, "literal 'ui' token must be searchable, not filtered by tokenizer")
def test_accessibility_query_hits_ux(self):
result = search("accessibility contrast wcag keyboard", domain="ux", max_results=3)
self.assertGreater(result["count"], 0)
def test_zero_result_query_reports_suggestions_not_error(self):
result = search("zzqqxx totally made up gibberish", domain="ux", max_results=2)
self.assertEqual(result["count"], 0)
self.assertIn("suggestions", result)
self.assertNotIn("error", result)
def test_every_configured_domain_file_exists_and_is_searchable(self):
for domain, config in CSV_CONFIG.items():
with self.subTest(domain=domain):
result = search("design", domain=domain, max_results=1)
self.assertNotIn("error", result, f"domain '{domain}' failed: {result.get('error')}")
def test_every_stack_file_exists_and_is_searchable(self):
for stack in AVAILABLE_STACKS:
with self.subTest(stack=stack):
result = search_stack("performance", stack, max_results=1)
self.assertNotIn("error", result, f"stack '{stack}' failed: {result.get('error')}")
class TestDomainDetection(unittest.TestCase):
def test_style_keywords_route_to_style(self):
self.assertEqual(detect_domain("glassmorphism dark ui"), "style")
def test_accessibility_keywords_route_to_ux(self):
self.assertEqual(detect_domain("accessibility contrast wcag"), "ux")
def test_ambiguous_query_returns_runner_up(self):
domain, runner_up = detect_domain("font pairing elegant crypto", return_scores=True)
self.assertIsNotNone(domain)
# runner_up may be None if the winning domain has no close second --
# this just verifies the call shape works without raising.
def test_empty_query_falls_back_to_style(self):
self.assertEqual(detect_domain("...!!!???"), "style")
class TestPersistence(unittest.TestCase):
def test_persist_then_skip_then_force(self):
with tempfile.TemporaryDirectory() as tmp:
result = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result["persistence"]["status"], "success")
master = Path(result["persistence"]["master_file"])
self.assertTrue(master.exists())
original_content = master.read_text(encoding="utf-8")
# Second persist without force must not overwrite.
result2 = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result2["persistence"]["status"], "skipped_exists")
self.assertEqual(master.read_text(encoding="utf-8"), original_content)
# With force=True it must overwrite.
result3 = generate_design_system("ecommerce luxury", "Test Project", persist=True, output_dir=tmp, force=True)
self.assertEqual(result3["persistence"]["status"], "success")
def test_persist_writes_only_under_output_dir(self):
with tempfile.TemporaryDirectory() as tmp:
generate_design_system("saas dashboard", "Scoped Project", persist=True, output_dir=tmp)
expected = Path(tmp) / "design-system" / "scoped-project" / "MASTER.md"
self.assertTrue(expected.exists())
class TestReasoningMatch(unittest.TestCase):
def test_known_category_matches_exactly(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("SaaS (General)")
self.assertTrue(rule, "exact-match category lookup should not fall through to fuzzy matching")
def test_unknown_category_falls_back_gracefully(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("Totally Unknown Category XYZ")
# Should not raise; may return {} which _apply_reasoning handles with defaults.
self.assertIsInstance(rule, dict)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Data integrity guardrail for ui-ux-pro-max. Stdlib-only, no pytest dependency,
so it can run as a standalone pre-publish/CI check:
python validate_data.py
Checks, per configured domain/stack CSV:
- file exists
- header row contains every column referenced in search_cols/output_cols
- no duplicate primary-key values (first column) within a file
- any "Decision_Rules"-style JSON column parses as JSON
Exits 0 with no output on success; exits 1 and prints every problem found
on failure (fail-fast is the wrong call here -- a data change can break
several files at once, so we want the full list in one run).
"""
import csv
import json
import sys
from pathlib import Path
from core import CSV_CONFIG, STACK_CONFIG, _STACK_COLS, DATA_DIR
# REASONING_FILE lives in design_system.py, not core.py -- redeclared here to
# avoid a circular import (design_system.py imports core.py).
REASONING_FILE = "ui-reasoning.csv"
JSON_COLUMNS = {"Decision_Rules"}
def _read_rows(filepath):
with open(filepath, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
return reader.fieldnames or [], list(reader)
def _check_file(label, filepath, search_cols, output_cols, problems):
if not filepath.exists():
problems.append(f"[{label}] missing file: {filepath}")
return
try:
headers, rows = _read_rows(filepath)
except (csv.Error, UnicodeDecodeError, OSError) as e:
problems.append(f"[{label}] failed to parse {filepath.name}: {e}")
return
header_set = set(headers)
for col in set(search_cols) | set(output_cols):
if col not in header_set:
problems.append(f"[{label}] {filepath.name}: expected column '{col}' not found in header")
# Only check for duplicates against an actual identifier column ("No" is
# the sequential-index convention used across this dataset). The first
# CSV column is not reliably a unique key -- e.g. stack files use
# "Category", which legitimately repeats across many guideline rows.
if "No" in header_set:
seen = {}
for i, row in enumerate(rows, start=2): # +1 header, +1 to be 1-indexed
key = row.get("No", "")
if key in seen:
problems.append(
f"[{label}] {filepath.name}: duplicate 'No' value '{key}' on rows {seen[key]} and {i}"
)
else:
seen[key] = i
elif label.startswith("stack:"):
problems.append(
f"[{label}] {filepath.name}: missing 'No' index column present in other stack files "
"(schema drift -- harmless for search, but inconsistent with the rest of data/stacks/)"
)
for row_idx, row in enumerate(rows, start=2):
for col in JSON_COLUMNS:
if col in row and row[col]:
try:
json.loads(row[col])
except json.JSONDecodeError as e:
problems.append(
f"[{label}] {filepath.name} row {row_idx}: column '{col}' is not valid JSON: {e}"
)
def main():
problems = []
for domain, config in CSV_CONFIG.items():
_check_file(f"domain:{domain}", DATA_DIR / config["file"],
config["search_cols"], config["output_cols"], problems)
for stack, config in STACK_CONFIG.items():
_check_file(f"stack:{stack}", DATA_DIR / config["file"],
_STACK_COLS["search_cols"], _STACK_COLS["output_cols"], problems)
reasoning_path = DATA_DIR / REASONING_FILE
if reasoning_path.exists():
_check_file("reasoning", reasoning_path, ["UI_Category"], ["UI_Category", "Decision_Rules"], problems)
else:
problems.append(f"[reasoning] missing file: {reasoning_path}")
if problems:
print(f"FAILED: {len(problems)} data integrity issue(s) found:\n")
for p in problems:
print(f" - {p}")
sys.exit(1)
print(f"OK: validated {len(CSV_CONFIG)} domain files, {len(STACK_CONFIG)} stack files, and ui-reasoning.csv")
sys.exit(0)
if __name__ == "__main__":
main()

View File

@ -27,6 +27,16 @@ const skillsSourceRoot = join(repoRoot, '.claude', 'skills');
const skillsAssetRoot = join(assetRoot, 'skills');
const subSkills = ['banner-design', 'brand', 'design', 'design-system', 'slides', 'ui-styling'];
// The repo's own .claude/skills/ui-ux-pro-max/{data,scripts} is a second,
// independent copy of src/ui-ux-pro-max/{data,scripts} -- it's what Claude
// Code actually loads when this repo is installed as a plugin. Nothing
// previously checked it against src/, so it silently drifted (missing stack
// CSVs, stale content in several data files). SKILL.md there is hand-authored
// (not template-rendered like the CLI's copy), so only data/ and scripts/
// are mirrored -- never templates/ or SKILL.md itself.
const orchestratorSkillTargetRoot = join(skillsSourceRoot, 'ui-ux-pro-max');
const orchestratorDirsToSync = ['data', 'scripts'];
// ponytail: only text is bundled. Excludes (a) heavy binary assets — the
// canvas fonts are ~5.8MB and a skill registers from its SKILL.md, not its
// fonts — and (b) Python build cruft (__pycache__/*.pyc, .coverage) that would
@ -79,74 +89,81 @@ async function fileHash(path) {
return createHash('sha256').update(content).digest('hex');
}
// Compares one source dir against one target dir; pushes human-readable
// drift descriptions (prefixed with `label`) onto `drift`.
async function diffDir(sourceDir, targetDir, label, drift) {
if (!(await exists(sourceDir))) {
drift.push(`missing source directory: ${relative(repoRoot, sourceDir)}`);
return;
}
if (!(await exists(targetDir))) {
drift.push(`missing asset directory: ${relative(repoRoot, targetDir)}`);
return;
}
const sourceFiles = (await listFiles(sourceDir)).filter((f) => !isExcludedAssetFile(f));
const targetFiles = (await listFiles(targetDir)).filter((f) => !isExcludedAssetFile(f));
const allFiles = [...new Set([...sourceFiles, ...targetFiles])].sort();
for (const file of allFiles) {
const sourcePath = join(sourceDir, file);
const targetPath = join(targetDir, file);
if (!sourceFiles.includes(file)) {
drift.push(`extra asset file: ${label}/${file}`);
} else if (!targetFiles.includes(file)) {
drift.push(`missing asset file: ${label}/${file}`);
} else if ((await fileHash(sourcePath)) !== (await fileHash(targetPath))) {
drift.push(`stale asset file: ${label}/${file}`);
}
}
}
// Mirrors sourceDir -> targetDir (deletes targetDir first, so removed
// source files don't linger as orphans in the target).
async function syncDir(sourceDir, targetDir) {
if (!(await exists(sourceDir))) {
throw new Error(`Source directory does not exist: ${sourceDir}`);
}
const resolvedTarget = assertInsideRepo(targetDir);
if (await exists(resolvedTarget)) {
await rm(resolvedTarget, { recursive: true, force: true });
}
for (const file of await listFiles(sourceDir)) {
if (isExcludedAssetFile(file)) continue;
const targetPath = assertInsideRepo(join(resolvedTarget, file));
await mkdir(dirname(targetPath), { recursive: true });
await writeFile(targetPath, toLF(await readFile(join(sourceDir, file), 'utf8')));
}
}
async function checkAssets() {
const drift = [];
for (const dir of dirsToSync) {
const sourceDir = join(sourceRoot, dir);
const targetDir = join(assetRoot, dir);
if (!(await exists(sourceDir))) {
drift.push(`missing source directory: ${relative(repoRoot, sourceDir)}`);
continue;
}
if (!(await exists(targetDir))) {
drift.push(`missing asset directory: ${relative(repoRoot, targetDir)}`);
continue;
}
const sourceFiles = (await listFiles(sourceDir)).filter((f) => !isExcludedAssetFile(f));
const targetFiles = (await listFiles(targetDir)).filter((f) => !isExcludedAssetFile(f));
const allFiles = [...new Set([...sourceFiles, ...targetFiles])].sort();
for (const file of allFiles) {
const sourcePath = join(sourceDir, file);
const targetPath = join(targetDir, file);
if (!sourceFiles.includes(file)) {
drift.push(`extra asset file: ${dir}/${file}`);
} else if (!targetFiles.includes(file)) {
drift.push(`missing asset file: ${dir}/${file}`);
} else if ((await fileHash(sourcePath)) !== (await fileHash(targetPath))) {
drift.push(`stale asset file: ${dir}/${file}`);
}
}
await diffDir(join(sourceRoot, dir), join(assetRoot, dir), dir, drift);
}
// Sub-skills (text content only; fonts/binaries intentionally excluded)
for (const name of subSkills) {
const sourceDir = join(skillsSourceRoot, name);
const targetDir = join(skillsAssetRoot, name);
await diffDir(join(skillsSourceRoot, name), join(skillsAssetRoot, name), `skills/${name}`, drift);
}
if (!(await exists(sourceDir))) {
drift.push(`missing source sub-skill: ${relative(repoRoot, sourceDir)}`);
continue;
}
if (!(await exists(targetDir))) {
drift.push(`missing asset sub-skill: skills/${name}`);
continue;
}
const sourceFiles = (await listFiles(sourceDir)).filter((f) => !isExcludedAssetFile(f));
const targetFiles = (await listFiles(targetDir)).filter((f) => !isExcludedAssetFile(f));
const allFiles = [...new Set([...sourceFiles, ...targetFiles])].sort();
for (const file of allFiles) {
const sourcePath = join(sourceDir, file);
const targetPath = join(targetDir, file);
if (!sourceFiles.includes(file)) {
drift.push(`extra asset file: skills/${name}/${file}`);
} else if (!targetFiles.includes(file)) {
drift.push(`missing asset file: skills/${name}/${file}`);
} else if ((await fileHash(sourcePath)) !== (await fileHash(targetPath))) {
drift.push(`stale asset file: skills/${name}/${file}`);
}
}
// Orchestrator skill's own data/scripts copy under .claude/skills/ui-ux-pro-max/
// (the copy Claude Code actually loads when this repo is a plugin).
for (const dir of orchestratorDirsToSync) {
await diffDir(
join(sourceRoot, dir),
join(orchestratorSkillTargetRoot, dir),
`.claude/skills/ui-ux-pro-max/${dir}`,
drift,
);
}
if (drift.length > 0) {
console.error('CLI assets are out of sync with src/ui-ux-pro-max:');
console.error('Assets are out of sync with src/ui-ux-pro-max:');
for (const item of drift) {
console.error(` - ${item}`);
}
@ -154,7 +171,7 @@ async function checkAssets() {
process.exit(1);
}
console.log('CLI assets are in sync.');
console.log('Assets are in sync.');
}
async function syncAssets() {
@ -162,23 +179,7 @@ async function syncAssets() {
await mkdir(assetRoot, { recursive: true });
for (const dir of dirsToSync) {
const sourceDir = join(sourceRoot, dir);
const targetDir = assertInsideRepo(join(assetRoot, dir));
if (!(await exists(sourceDir))) {
throw new Error(`Source directory does not exist: ${sourceDir}`);
}
if (await exists(targetDir)) {
await rm(targetDir, { recursive: true, force: true });
}
for (const file of await listFiles(sourceDir)) {
if (isExcludedAssetFile(file)) continue;
const targetPath = assertInsideRepo(join(targetDir, file));
await mkdir(dirname(targetPath), { recursive: true });
await writeFile(targetPath, toLF(await readFile(join(sourceDir, file), 'utf8')));
}
await syncDir(join(sourceRoot, dir), join(assetRoot, dir));
}
// Sub-skills: copy text content only (fonts/binaries excluded) so all 7
@ -188,19 +189,15 @@ async function syncAssets() {
await rm(skillsTarget, { recursive: true, force: true });
}
for (const name of subSkills) {
const sourceDir = join(skillsSourceRoot, name);
if (!(await exists(sourceDir))) {
throw new Error(`Source sub-skill does not exist: ${sourceDir}`);
}
for (const file of await listFiles(sourceDir)) {
if (isExcludedAssetFile(file)) continue;
const targetPath = assertInsideRepo(join(skillsTarget, name, file));
await mkdir(dirname(targetPath), { recursive: true });
await writeFile(targetPath, toLF(await readFile(join(sourceDir, file), 'utf8')));
}
await syncDir(join(skillsSourceRoot, name), join(skillsTarget, name));
}
console.log('Synced CLI assets from src/ui-ux-pro-max + 6 sub-skills (normalized to LF).');
// Orchestrator skill's own data/scripts copy under .claude/skills/ui-ux-pro-max/.
for (const dir of orchestratorDirsToSync) {
await syncDir(join(sourceRoot, dir), join(orchestratorSkillTargetRoot, dir));
}
console.log('Synced CLI assets + .claude/skills/ui-ux-pro-max data/scripts from src/ui-ux-pro-max, and 6 sub-skills (normalized to LF).');
}
if (checkOnly) {

View File

@ -1,54 +1,54 @@
Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,"// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag","<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime","function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color","renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });","// No resize handler — scene stretches to fill a wider window without correcting the projection",High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));","// No position or lookAt set — subject at y:2 is behind or above the default camera view",Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,"function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); }","scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });","const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit",Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material","for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials",High,https://threejs.org/docs/#api/en/materials/Material
Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,"const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();","const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload",High,https://threejs.org/docs/#api/en/textures/Texture.dispose
Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;","dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,"renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags","for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,"mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED","mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored",Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes","const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children",High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,"if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; }","raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.","Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame","Call clock.getDelta() more than once per frame or inside a helper called from animate()","const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz }",High,https://threejs.org/docs/#api/en/core/Clock
Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,"// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);","// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing",Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });","let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps",High,https://gsap.com/docs/v3/GSAP/Timeline/
Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';","import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js",Critical,https://gsap.com/docs/v3/Installation
GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,"renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128","const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect",Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context","const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear","// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame",Low,https://threejs.org/docs/#api/en/scenes/FogExp2
Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,"const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);","const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone",High,https://threejs.org/docs/#api/en/objects/Points
Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,"// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload","// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move",Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.","Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value","Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes","const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }","const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely",High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);","document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing",Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,"npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';","<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);","scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera",Medium,https://threejs.org/docs/#api/en/objects/LOD
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
1,Setup,CDN Version Lock,Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning.,Pin to the exact r128 cdnjs URL in every HTML file,Use unpkg@latest or any unversioned CDN URL that can silently update,"<script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>","<script src=""https://unpkg.com/three@latest""></script>",Critical,https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
2,Setup,CapsuleGeometry Does Not Exist in r128,THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead.,Build a capsule from CylinderGeometry plus two SphereGeometry end caps,Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately,"const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap);","const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128",Critical,https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
3,Setup,OrbitControls Must Be Loaded Separately,OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it.,Load the OrbitControls script from cdnjs examples path before your scene script,Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script,"<!-- Load AFTER core Three.js script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js""></script>","<!-- Core only loaded — OrbitControls undefined --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script>",Critical,https://cdnjs.com/libraries/three.js/r128
4,Setup,Custom Drag Orbit Fallback,When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly.,Rotate camera in spherical coordinates so both axes respond correctly to drag,Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect,"let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; });","let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere",High,https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
5,Setup,ESM vs CDN Import,When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors.,Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages,Mix a CDN script tag with an ES module import in the same file,// Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag,"<!-- CDN script --> <script src=""r128.cdn""></script> <script type=""module""> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script>",Critical,https://threejs.org/docs/#manual/en/introduction/Installation
6,Setup,Single Renderer Per Page,Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (816 contexts) and cause context-lost errors especially on mobile.,Reuse a single renderer and swap scene content instead of recreating the renderer,Create a new renderer on each component mount or scene transition,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime",function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile,Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
7,Setup,Pixel Ratio Cap at 2,Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance.,"Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3",Pass window.devicePixelRatio directly without any cap,"renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));",renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
8,Setup,Alpha Canvas Plus CSS Background,Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it.,Set alpha:true on renderer and let body or a parent div provide the background color,Set a solid renderer clear color when the canvas must composite over HTML behind it,"const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color",renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
9,Camera,Aspect Ratio on Resize,Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally.,Update camera.aspect then call updateProjectionMatrix() on every resize,Let aspect ratio become stale after the browser window changes size,"window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); });",// No resize handler — scene stretches to fill a wider window without correcting the projection,High,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
10,Camera,FOV Range 45 to 75,Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges.,Start at 75 for general interactive scenes; use 4555 for product close-ups,Use FOV above 90 or below 30 without a deliberate artistic reason,"const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot","const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges",Medium,https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11,Camera,Explicit Position and lookAt,Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny.,Set camera.position.set() and camera.lookAt() to frame the subject before the first render,Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic,"camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0));",// No position or lookAt set — subject at y:2 is behind or above the default camera view,Medium,https://threejs.org/docs/#api/en/cameras/Camera.lookAt
12,Camera,OrbitControls vs GSAP Camera Rig,Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed.,Match camera control approach to the UX intent of the scene,Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes,"// Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate()","// Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes",High,https://threejs.org/docs/#examples/en/controls/OrbitControls
13,Geometry,Never Create Geometry Per Frame,Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame.,Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed,Call any new XxxGeometry() constructor inside the animation loop,"const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
14,Geometry,Share Geometry Across Meshes,When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer.,Create one geometry and pass the same reference to every Mesh constructor,Create a separate identical geometry inside a loop for each object,"const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); }","for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); }",Critical,https://threejs.org/docs/#api/en/core/BufferGeometry
15,Geometry,dispose on Scene Removal,Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed.,Dispose of geometry + material + every texture map before calling scene.remove(),Call scene.remove() alone without any dispose calls,function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); },scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever,Critical,https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
16,Geometry,Segment Count Budget,Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 3264 segments. Background objects: 816. Particle stand-ins: 68. High counts on background geometry waste GPU draw calls with zero visible benefit.,Apply a tiered segment budget based on the visual priority of each object in the scene,Default every sphere and cylinder to 64+ segments regardless of its role,"const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product","const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw",Medium,https://threejs.org/docs/#api/en/geometries/SphereGeometry
17,Geometry,BufferGeometry for Custom Vertex Data,For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128.,Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data,Reference or instantiate the removed THREE.Geometry class,"const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));","const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128",High,https://threejs.org/docs/#api/en/core/BufferGeometry
18,Materials,MeshBasicMaterial vs MeshStandardMaterial,MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices.,Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects,Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them,"const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 });",const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit,Medium,https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
19,Materials,Share Material Instances,Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM.,Assign the same material reference to all meshes with identical visual properties,Create a new material inside a loop for objects that look identical,"const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material",for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials,High,https://threejs.org/docs/#api/en/materials/Material
20,Materials,Dispose Textures Explicitly,Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically.,Track all loaded textures and call dispose() on each one during scene teardown or on object removal,Load textures without any cleanup path — they persist in VRAM for the entire page lifetime,const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose();,const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload,High,https://threejs.org/docs/#api/en/textures/Texture.dispose
21,Lighting,Ambient Plus Directional Minimum,Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it.,Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used,Use MeshStandardMaterial without adding any lights to the scene,"scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight);","const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene",Critical,https://threejs.org/docs/#api/en/lights/DirectionalLight
22,Lighting,Enable shadowMap Before castShadow,renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored.,Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes,Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true;,dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
23,Lighting,Selective Shadow Casting,Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane.,Enable shadows only on the key light and the most important meshes,Enable castShadow and receiveShadow on every object in the scene including particles,renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags,for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24,Lighting,Skip Lights for MeshBasicMaterial,MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect.,Omit lights entirely when every material in the scene is MeshBasicMaterial,Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial,"// Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition","scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely",Low,https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
25,Raycasting,Single Shared Raycaster,Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event.,Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate(),Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener,"const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate()","window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec });",Critical,https://threejs.org/docs/#api/en/core/Raycaster
26,Raycasting,NDC Mouse Coordinates,Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects.,Apply the full NDC formula — including the negation on the Y axis,Forget to negate Y — raycasting appears to work but hits objects mirrored vertically,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED,mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored,Critical,https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
27,Raycasting,setFromCamera and intersectObjects in animate,Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction.,Call setFromCamera then intersectObjects in order inside every animate() frame,Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray,"function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); }","function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); }",Critical,https://threejs.org/docs/#api/en/core/Raycaster
28,Raycasting,Recursive Flag for Groups and GLTF,Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty.,Use intersectObjects(targets true) for Groups or any loaded model,Raycast against a parent Group without the recursive flag,"const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes",const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children,High,https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
29,Raycasting,Cursor Feedback on Hover,Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive.,Update cursor to pointer on hit; reset to auto on miss in the same animate loop block,Run raycasting and read hits without ever updating the cursor style,if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; },"raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive",Medium,https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
30,Animation,requestAnimationFrame Loop Only,Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery.,Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver,Use setInterval or setTimeout for render timing,"function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();","setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden",Critical,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
31,Animation,THREE.Clock for Delta Time,"Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it.",Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame,Call clock.getDelta() more than once per frame or inside a helper called from animate(),"const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); }",function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz },High,https://threejs.org/docs/#api/en/core/Clock
32,Animation,Lerp for Smooth Pointer Follow,Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.030.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP.,Apply the lerp formula each frame with a small alpha for smooth organic motion,Snap a value directly to the target producing an instant jarring jump,// In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position);,// In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing,Medium,https://threejs.org/docs/#api/en/math/MathUtils.lerp
33,Animation,GSAP for Multi-Step Sequences,Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines.,Use GSAP timelines for sequences with more than two steps and for scroll-driven animations,Implement multi-step sequences with boolean flags and manual frame counters,"const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 });",let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps,High,https://gsap.com/docs/v3/GSAP/Timeline/
34,Animation,Pause Render Loop on Tab Hidden,Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit.,Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange,Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden,"renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); });","function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery",High,https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
35,GSAP,Load GSAP Before Scene Script,Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package.,Load GSAP CDN before the scene script; or npm install gsap and import separately,Import gsap from three or expect it to be defined without a separate load,"<!-- CDN: load GSAP before your scene script --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js""></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger';",import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js,Critical,https://gsap.com/docs/v3/Installation
36,GSAP,Register ScrollTrigger Before Use,Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately.,Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger,Include scrollTrigger config in gsap.to() calls without first registering the plugin,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } });","gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered",Critical,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
37,GSAP,Tween Three.js Properties Directly,GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts.,Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity,Use a plain proxy object then manually copy values to Three.js properties every frame,"gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 });","const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper",Medium,https://gsap.com/docs/v3/GSAP/gsap.to()
38,GSAP,scrub for Scroll-Driven Camera Path,Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 01 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path.,Use scrub:1 for any scroll-controlled camera movement,Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing,"gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } });","gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub",High,https://gsap.com/docs/v3/Plugins/ScrollTrigger/
39,Performance,InstancedMesh for Repeated Objects,Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically.,Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material,Create 50+ separate Mesh objects with the same geometry and material,"const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/InstancedMesh
40,Performance,Tone Mapping and sRGB Encoding,Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately.,Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes,Leave tone mapping and output encoding at defaults when the scene targets realistic visuals,renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128,const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect,Medium,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
41,Performance,antialias Set at Construction Only,The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating.,Set antialias:true inside the WebGLRenderer constructor options object,Construct the renderer without antialias then try to enable it by assigning the property,"const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context",const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased,High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer
42,Performance,FogExp2 for Depth and Far Culling,Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances.,Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling,Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call,"scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear",// far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame,Low,https://threejs.org/docs/#api/en/scenes/FogExp2
43,Particles,BufferGeometry Plus Points for Particle Systems,Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance.,Use Points plus BufferGeometry for all particle effects,Create hundreds of individual Mesh objects to simulate a particle system,"const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles);","for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame",High,https://threejs.org/docs/#api/en/objects/Points
44,Particles,Particle Count Ceiling,Start particle systems at 10003000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1.,Start at 3000 particles and profile on actual mobile hardware before raising the limit,Set particle count at 100000 or higher without any mobile profiling,const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3);,const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone,High,https://threejs.org/docs/#api/en/objects/Points
45,Particles,needsUpdate After Buffer Mutation,After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen.,Set needsUpdate = true on the position attribute after every per-frame mutation of the array,Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU,// In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload,// In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move,Critical,https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
46,Responsive,Canvas Dimensions Not Window,Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport.,Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing,Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container,"renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix();","renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column",High,https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
47,Responsive,ResizeObserver Over window resize Event,Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing.,Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection,Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen,"const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement);","window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs",Medium,https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
48,Responsive,Touch Events for Mobile Interaction,Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault.,Handle both mouse and touch input for any interactive 3D scene,Add only mouse event listeners and leave touch users with no interaction,"canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false });","canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction",Medium,https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
49,Accessibility,prefers-reduced-motion,"Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime.",Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value,Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes,"const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; }",const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely,High,https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
50,Accessibility,Canvas aria-label,Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users.,Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it,Append the canvas to the DOM with no accessibility attributes — invisible to screen readers,"renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement);",document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing,Medium,https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
51,Production,Bundler Stack for Production,For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support.,Use npm install three plus Vite or Webpack for any production client-facing project,Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript,npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';,"<!-- In a Vite/React production build: --> <script src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js""></script> // no tree-shaking — entire Three.js ships",Medium,https://threejs.org/docs/#manual/en/introduction/Installation
52,Production,GLTFLoader with scene traverse,Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration.,Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child,Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes,"import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); });","loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children });",Medium,https://threejs.org/docs/#examples/en/loaders/GLTFLoader
53,Production,LOD for Distance-Based Detail,Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range.,Use THREE.LOD to reduce triangle count on distant objects automatically,Render the same high-polygon geometry for every object regardless of its distance from the camera,"const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 1550 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod);",scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera,Medium,https://threejs.org/docs/#api/en/objects/LOD

1 No Category Guideline Description Do Don't Code Good Code Bad Severity Docs URL
2 1 Setup CDN Version Lock Always use Three.js r128 from cdnjs. It is the stable CDN baseline. Never use a floating 'latest' URL — it silently breaks when the CDN updates without warning. Pin to the exact r128 cdnjs URL in every HTML file Use unpkg@latest or any unversioned CDN URL that can silently update <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://unpkg.com/three@latest"></script> Critical https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
3 2 Setup CapsuleGeometry Does Not Exist in r128 THREE.CapsuleGeometry was introduced in r142. Using it on the r128 CDN throws 'CapsuleGeometry is not a constructor' and crashes the entire scene. Build a capsule from primitives instead. Build a capsule from CylinderGeometry plus two SphereGeometry end caps Call THREE.CapsuleGeometry on r128 — it is undefined and throws immediately const body = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), mat); const topCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); const botCap = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 8), mat); topCap.position.y = 0.5; botCap.position.y = -0.5; const group = new THREE.Group(); group.add(body, topCap, botCap); const cap = new THREE.CapsuleGeometry(0.5, 1, 4, 8); // TypeError: CapsuleGeometry is not a constructor on r128 Critical https://threejs.org/docs/#api/en/geometries/CapsuleGeometry
4 3 Setup OrbitControls Must Be Loaded Separately OrbitControls is NOT bundled in the core Three.js r128 CDN file. It lives in examples/js and must be loaded from a separate cdnjs script tag. THREE.OrbitControls is undefined without it. Load the OrbitControls script from cdnjs examples path before your scene script Expect THREE.OrbitControls to exist after loading only the core Three.js CDN script <!-- Load AFTER core Three.js script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/controls/OrbitControls.min.js"></script> <!-- Core only loaded — OrbitControls undefined --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> Critical https://cdnjs.com/libraries/three.js/r128
5 4 Setup Custom Drag Orbit Fallback When OrbitControls cannot be loaded implement spherical orbit using mousedown/mousemove/mouseup. The key is rotating in spherical coordinates so both horizontal AND vertical drag work correctly. Rotate camera in spherical coordinates so both axes respond correctly to drag Move camera.position.x directly — vertical drag is silently ignored and the orbit is incorrect let dragging = false; let prev = { x: 0, y: 0 }; const radius = camera.position.length(); let theta = 0; let phi = Math.PI / 2; canvas.addEventListener('mousedown', () => dragging = true); canvas.addEventListener('mouseup', () => dragging = false); canvas.addEventListener('mousemove', e => { if (!dragging) return; theta -= (e.clientX - prev.x) * 0.005; phi = Math.max(0.1, Math.min(Math.PI - 0.1, phi - (e.clientY - prev.y) * 0.005)); camera.position.set(radius * Math.sin(phi) * Math.sin(theta), radius * Math.cos(phi), radius * Math.sin(phi) * Math.cos(theta)); camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); let dragging = false; let prev = { x: 0, y: 0 }; canvas.addEventListener('mousemove', e => { if (!dragging) return; camera.position.x += (e.clientX - prev.x) * 0.005; camera.lookAt(scene.position); prev = { x: e.clientX, y: e.clientY }; }); // BUG: Y-drag ignored; orbit is a horizontal slide not a sphere High https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
6 5 Setup ESM vs CDN Import When using a bundler import Three.js as an ES module. When using CDN the THREE global is already available — do not import it again. Mixing both loads Three.js twice and causes subtle runtime errors. Match import style to build environment: ESM import for bundlers; rely on the window.THREE global for CDN pages Mix a CDN script tag with an ES module import in the same file // Bundler project (Vite / webpack): import * as THREE from 'three'; // CDN project — no import needed; THREE is already global after the script tag <!-- CDN script --> <script src="r128.cdn"></script> <script type="module"> import * as THREE from 'three'; // loads Three.js twice — version mismatch risk </script> Critical https://threejs.org/docs/#manual/en/introduction/Installation
7 6 Setup Single Renderer Per Page Create one WebGLRenderer instance for the lifetime of the page. Multiple renderers compete for the browser GPU context limit (8–16 contexts) and cause context-lost errors especially on mobile. Reuse a single renderer and swap scene content instead of recreating the renderer Create a new renderer on each component mount or scene transition const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(canvas.clientWidth, canvas.clientHeight); // renderer lives for the page lifetime function showScene() { const renderer = new THREE.WebGLRenderer(); document.body.appendChild(renderer.domElement); } showScene(); showScene(); // two GPU contexts — crashes on mobile Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer
8 7 Setup Pixel Ratio Cap at 2 Cap devicePixelRatio at 2. Retina displays report 3x or higher. Going from 2x to 3x multiplies pixel count by 2.25x with no visible quality improvement at normal viewing distance. Apply Math.min(window.devicePixelRatio, 2) — cap is at 2 not at 3 Pass window.devicePixelRatio directly without any cap renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setPixelRatio(window.devicePixelRatio); // 3x display = 9 pixels per CSS pixel = 2.25x GPU cost for zero quality gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setPixelRatio
9 8 Setup Alpha Canvas Plus CSS Background Set alpha:true on the renderer and control the background color through CSS rather than a renderer clear color. This composites the canvas correctly over any HTML content behind it. Set alpha:true on renderer and let body or a parent div provide the background color Set a solid renderer clear color when the canvas must composite over HTML behind it const renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setClearColor(0x000000, 0); // fully transparent canvas // body { background: #0d0d0d; } handles the visible color renderer.setClearColor(0x111827); // fully opaque — HTML behind the canvas is blocked Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setClearColor
10 9 Camera Aspect Ratio on Resize Always update camera.aspect and call camera.updateProjectionMatrix() inside every resize handler. A stale aspect ratio causes the entire scene to appear stretched or squashed horizontally. Update camera.aspect then call updateProjectionMatrix() on every resize Let aspect ratio become stale after the browser window changes size window.addEventListener('resize', () => { camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(canvas.clientWidth, canvas.clientHeight); }); // No resize handler — scene stretches to fill a wider window without correcting the projection High https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
11 10 Camera FOV Range 45 to 75 Use a field of view between 45 and 75 degrees. Below 45 creates compressed telephoto distortion. Above 90 creates visible fisheye distortion at frame edges. Start at 75 for general interactive scenes; use 45–55 for product close-ups Use FOV above 90 or below 30 without a deliberate artistic reason const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000); // general const camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000); // product shot const camera = new THREE.PerspectiveCamera(120, aspect, 0.1, 1000); // fisheye distortion at all edges Medium https://threejs.org/docs/#api/en/cameras/PerspectiveCamera
12 11 Camera Explicit Position and lookAt Always set an explicit camera position and call camera.lookAt() before the first render. The default camera at the origin pointing down -Z makes subjects at arbitrary coordinates invisible or tiny. Set camera.position.set() and camera.lookAt() to frame the subject before the first render Leave the camera at default position (0 0 0) with no lookAt — subject may be behind the camera or microscopic camera.position.set(0, 1.5, 5); camera.lookAt(new THREE.Vector3(0, 0, 0)); // No position or lookAt set — subject at y:2 is behind or above the default camera view Medium https://threejs.org/docs/#api/en/cameras/Camera.lookAt
13 12 Camera OrbitControls vs GSAP Camera Rig Use OrbitControls for model viewers and exploratory scenes where the user needs free-look. Use a GSAP scroll-driven camera rig for product reveals or storytelling where the camera path must stay fixed. Match camera control approach to the UX intent of the scene Use OrbitControls for a scripted reveal — users can orbit away from the reveal before it completes // Scroll storytelling — GSAP controls the path: gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.scene', scrub: 1 } }); // Free-look model viewer — OrbitControls: const controls = new THREE.OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // call controls.update() in animate() // Scripted product reveal: const controls = new THREE.OrbitControls(camera, renderer.domElement); // user can rotate away before the animation completes High https://threejs.org/docs/#examples/en/controls/OrbitControls
14 13 Geometry Never Create Geometry Per Frame Creating a new geometry inside animate() allocates a fresh GPU buffer every frame and exhausts VRAM within seconds. Create all geometry exactly once before the loop starts. Use attribute mutation if positions must change per frame. Create all geometry before the animation loop; mutate BufferAttribute arrays in-place if needed Call any new XxxGeometry() constructor inside the animation loop const geo = new THREE.SphereGeometry(1, 32, 32); // created once const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); mesh.rotation.y += clock.getDelta() * 0.8; // delta time renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const geo = new THREE.BoxGeometry(1, 1, 1); // NEW GPU buffer every frame — VRAM exhaustion } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
15 14 Geometry Share Geometry Across Meshes When multiple objects share the same shape create one geometry instance and pass it to every Mesh. Each Mesh gets its own transform and material while all share a single GPU buffer. Create one geometry and pass the same reference to every Mesh constructor Create a separate identical geometry inside a loop for each object const geo = new THREE.BoxGeometry(1, 1, 1); // one GPU buffer for (let i = 0; i < 200; i++) { const m = new THREE.Mesh(geo, mat); m.position.set(Math.random() * 10, 0, Math.random() * 10); scene.add(m); } for (let i = 0; i < 200; i++) { const geo = new THREE.BoxGeometry(1, 1, 1); // 200 separate GPU buffers scene.add(new THREE.Mesh(geo, mat)); } Critical https://threejs.org/docs/#api/en/core/BufferGeometry
16 15 Geometry dispose on Scene Removal Call geometry.dispose() and material.dispose() and texture.dispose() for every texture map when removing objects from the scene. Three.js never releases GPU resources automatically — they stay in VRAM until explicitly freed. Dispose of geometry + material + every texture map before calling scene.remove() Call scene.remove() alone without any dispose calls function removeMesh(mesh) { scene.remove(mesh); mesh.geometry.dispose(); if (mesh.material.map) mesh.material.map.dispose(); if (mesh.material.normalMap) mesh.material.normalMap.dispose(); mesh.material.dispose(); } scene.remove(mesh); // geometry and all texture maps stay in GPU VRAM forever Critical https://threejs.org/docs/#api/en/core/BufferGeometry.dispose
17 16 Geometry Segment Count Budget Use the minimum segment count that achieves the desired silhouette quality. Hero objects: 32–64 segments. Background objects: 8–16. Particle stand-ins: 6–8. High counts on background geometry waste GPU draw calls with zero visible benefit. Apply a tiered segment budget based on the visual priority of each object in the scene Default every sphere and cylinder to 64+ segments regardless of its role const bgSphere = new THREE.SphereGeometry(0.5, 8, 8); // background const heroSphere = new THREE.SphereGeometry(1, 64, 64); // foreground product const particleSphere = new THREE.SphereGeometry(0.1, 64, 64); // 64 segments × 1000 particles = massive overdraw Medium https://threejs.org/docs/#api/en/geometries/SphereGeometry
18 17 Geometry BufferGeometry for Custom Vertex Data For any custom shape use BufferGeometry with setAttribute('position' ...) and a Float32Array. The legacy THREE.Geometry class was removed in r125 and throws ReferenceError in r128. Use THREE.BufferGeometry with a Float32Array position attribute for custom vertex data Reference or instantiate the removed THREE.Geometry class const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3)); geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3)); const geo = new THREE.Geometry(); geo.vertices.push(new THREE.Vector3(0, 0, 0)); // ReferenceError: Geometry is not defined in r128 High https://threejs.org/docs/#api/en/core/BufferGeometry
19 18 Materials MeshBasicMaterial vs MeshStandardMaterial MeshBasicMaterial ignores all lights and is significantly cheaper — use it for UI overlays HUDs and flat-colored decorative elements. MeshStandardMaterial is PBR-accurate and requires lights. Never use StandardMaterial where BasicMaterial suffices. Use MeshBasicMaterial for any object that does not need lighting; use MeshStandardMaterial for physical objects Apply MeshStandardMaterial to flat UI elements that never receive light — lights still run for them const uiMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); // no lighting cost const physMat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.4, metalness: 0.6 }); const mat = new THREE.MeshStandardMaterial({ color: 0xffffff }); // on a 2D HUD card — lighting calculation runs with no visual benefit Medium https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
20 19 Materials Share Material Instances Share one material instance across all meshes that have identical properties. Call mat.clone() only when individual meshes genuinely need different property values. Duplicate materials waste GPU VRAM. Assign the same material reference to all meshes with identical visual properties Create a new material inside a loop for objects that look identical const mat = new THREE.MeshStandardMaterial({ color: 0x4f46e5, roughness: 0.5 }); meshA.material = mat; meshB.material = mat; meshC.material = mat; // one GPU material for (const m of meshes) { m.material = new THREE.MeshStandardMaterial({ color: 0x4f46e5 }); } // N redundant GPU materials High https://threejs.org/docs/#api/en/materials/Material
21 20 Materials Dispose Textures Explicitly Textures are the single largest consumer of GPU VRAM in most Three.js scenes. Call texture.dispose() when switching scenes or removing objects — Three.js does not garbage-collect GPU resources automatically. Track all loaded textures and call dispose() on each one during scene teardown or on object removal Load textures without any cleanup path — they persist in VRAM for the entire page lifetime const tex = new THREE.TextureLoader().load('img.jpg'); mesh.material.map = tex; // on teardown: tex.dispose(); mesh.material.dispose(); const tex = new THREE.TextureLoader().load('img.jpg'); scene.remove(mesh); // tex occupies GPU VRAM until page reload High https://threejs.org/docs/#api/en/textures/Texture.dispose
22 21 Lighting Ambient Plus Directional Minimum Any scene using MeshStandardMaterial or MeshPhongMaterial requires at minimum one AmbientLight (fill) and one DirectionalLight (shading direction). Without both the objects render as solid black — the material is there but no light reaches it. Add AmbientLight for fill and DirectionalLight for shading whenever PBR or Phong materials are used Use MeshStandardMaterial without adding any lights to the scene scene.add(new THREE.AmbientLight(0xffffff, 0.4)); const dirLight = new THREE.DirectionalLight(0xffffff, 1.0); dirLight.position.set(5, 10, 7.5); scene.add(dirLight); const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x4f46e5 })); scene.add(mesh); // renders completely black — no lights in scene Critical https://threejs.org/docs/#api/en/lights/DirectionalLight
23 22 Lighting Enable shadowMap Before castShadow renderer.shadowMap.enabled = true must be set before any castShadow or receiveShadow flags. Without it the shadow map is never allocated and all shadow flags are silently ignored. Set renderer.shadowMap.enabled = true first then set castShadow and receiveShadow on lights and meshes Set castShadow on a light or mesh without enabling renderer.shadowMap.enabled — shadows never render renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; heroMesh.castShadow = true; ground.receiveShadow = true; dirLight.castShadow = true; heroMesh.castShadow = true; // renderer.shadowMap.enabled never set — shadows silently do not render High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
24 23 Lighting Selective Shadow Casting Shadow map rendering redraws the entire scene from the light's perspective every frame. Enable castShadow only on the primary directional light and receiveShadow only on hero meshes and the ground plane. Enable shadows only on the key light and the most important meshes Enable castShadow and receiveShadow on every object in the scene including particles renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; dirLight.castShadow = true; heroMesh.castShadow = true; ground.receiveShadow = true; // particles and background meshes: no shadow flags for (const m of allMeshes) { m.castShadow = true; m.receiveShadow = true; } // shadow map pass over particle system — expensive with no visible gain High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
25 24 Lighting Skip Lights for MeshBasicMaterial MeshBasicMaterial completely ignores all scene lights. Adding lights solely to illuminate BasicMaterial objects wastes a light pass on every frame with zero visible effect. Omit lights entirely when every material in the scene is MeshBasicMaterial Add AmbientLight and DirectionalLight to a scene that uses only MeshBasicMaterial // Scene uses only MeshBasicMaterial — no lights needed const mat = new THREE.MeshBasicMaterial({ color: 0x00ffff }); const mesh = new THREE.Mesh(geo, mat); scene.add(mesh); // MeshBasicMaterial is always fully lit by definition scene.add(new THREE.AmbientLight(0xffffff, 1.0)); // wasted per-frame light pass — BasicMaterial ignores it entirely Low https://threejs.org/docs/#api/en/materials/MeshBasicMaterial
26 25 Raycasting Single Shared Raycaster Create exactly one Raycaster instance outside all event handlers. Store mouse coordinates in pointermove (cheap). Call setFromCamera and intersectObjects together inside the animate() loop — once per frame instead of once per mouse event. Create one Raycaster; store mouse in pointermove; call setFromCamera + intersectObjects inside animate() Create a new THREE.Raycaster() inside a mousemove handler or call setFromCamera inside the event listener const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); canvas.addEventListener('pointermove', e => { // only store coords — no raycasting here mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; }); // setFromCamera and intersectObjects run once per frame in animate() window.addEventListener('mousemove', e => { const rc = new THREE.Raycaster(); // new allocation per event rc.setFromCamera(mouse, camera); rc.intersectObjects(targets, true); // fires 200+ times/sec }); Critical https://threejs.org/docs/#api/en/core/Raycaster
27 26 Raycasting NDC Mouse Coordinates Raycasting requires mouse in Normalized Device Coordinates: X from -1 (left) to +1 (right) and Y from +1 (top) to -1 (bottom). The Y axis is inverted relative to screen space. A missing negation on Y causes all raycasts to miss or hit the wrong objects. Apply the full NDC formula — including the negation on the Y axis Forget to negate Y — raycasting appears to work but hits objects mirrored vertically mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(e.clientY / canvas.clientHeight) * 2 + 1; // Y is INVERTED mouse.x = (e.clientX / canvas.clientWidth) * 2 - 1; mouse.y = (e.clientY / canvas.clientHeight) * 2 - 1; // BUG: Y not negated — raycasting is mirrored Critical https://threejs.org/docs/#api/en/core/Raycaster.setFromCamera
28 27 Raycasting setFromCamera and intersectObjects in animate Call raycaster.setFromCamera(mouse camera) and then raycaster.intersectObjects(targets true) inside the animate() loop. setFromCamera must come before intersectObjects every frame — without it the raycaster uses a stale ray direction. Call setFromCamera then intersectObjects in order inside every animate() frame Call intersectObjects without calling setFromCamera first — the raycaster uses a stale or zero ray function animate() { requestAnimationFrame(animate); raycaster.setFromCamera(mouse, camera); // update ray direction first const hits = raycaster.intersectObjects(targets, true); // then test intersections if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); const hits = raycaster.intersectObjects(targets, true); // BUG: setFromCamera never called — stale ray — hits is always empty renderer.render(scene, camera); } Critical https://threejs.org/docs/#api/en/core/Raycaster
29 28 Raycasting Recursive Flag for Groups and GLTF Pass true as the second argument to intersectObjects when testing Groups or GLTF loaded models. Geometry lives on child Mesh objects — without recursive:true the parent group is tested but has no geometry and hits is always empty. Use intersectObjects(targets true) for Groups or any loaded model Raycast against a parent Group without the recursive flag const hits = raycaster.intersectObjects(scene.children, true); // catches all descendant meshes const hits = raycaster.intersectObjects([modelGroup]); // recursive defaults to false — misses all children High https://threejs.org/docs/#api/en/core/Raycaster.intersectObjects
30 29 Raycasting Cursor Feedback on Hover Set document.body.style.cursor = 'pointer' when intersections are found and reset to 'auto' when none are found. Without cursor feedback users cannot discover that 3D objects are interactive. Update cursor to pointer on hit; reset to auto on miss in the same animate loop block Run raycasting and read hits without ever updating the cursor style if (hits.length > 0) { document.body.style.cursor = 'pointer'; } else { document.body.style.cursor = 'auto'; } raycaster.setFromCamera(mouse, camera); raycaster.intersectObjects(targets, true); // hits ignored — cursor never changes — objects feel non-interactive Medium https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
31 30 Animation requestAnimationFrame Loop Only Drive the render loop exclusively with requestAnimationFrame or renderer.setAnimationLoop(). Never use setInterval or setTimeout — they are not synchronized to the display refresh rate and keep running when the tab is hidden draining battery. Use requestAnimationFrame or renderer.setAnimationLoop() as the sole render loop driver Use setInterval or setTimeout for render timing function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate(); setInterval(() => renderer.render(scene, camera), 16); // not display-synced; runs at full speed even when tab is hidden Critical https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setAnimationLoop
32 31 Animation THREE.Clock for Delta Time Use THREE.Clock and clock.getDelta() for all time-based motion. A hardcoded increment like += 0.01 runs at 2x speed on 120Hz displays and at unpredictable speed when frames drop under load. CRITICAL: call getDelta() exactly ONCE per animate() frame and store the result in a local dt variable. getDelta() resets the internal clock on every call — a second call in the same frame always returns ~0, silently breaking any animation block that uses it. Call clock.getDelta() once at the top of animate(); store result in dt; reuse dt everywhere in that frame Call clock.getDelta() more than once per frame or inside a helper called from animate() const clock = new THREE.Clock(); function animate() { requestAnimationFrame(animate); const dt = clock.getDelta(); // called ONCE — reuse dt below mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; // reuse dt, not a second getDelta() renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); mesh.rotation.y += 0.01; // 0.01 rad/frame — runs 2x faster on 120Hz than on 60Hz } High https://threejs.org/docs/#api/en/core/Clock
33 32 Animation Lerp for Smooth Pointer Follow Use value += (target - value) * alpha each frame to smoothly interpolate toward a moving target. An alpha of 0.03–0.1 produces organic easing for camera follow pointer-tracking and hover scale effects without requiring GSAP. Apply the lerp formula each frame with a small alpha for smooth organic motion Snap a value directly to the target producing an instant jarring jump // In animate(): cameraTargetX = mouse.x * 3; camera.position.x += (cameraTargetX - camera.position.x) * 0.05; camera.position.y += (cameraTargetY - camera.position.y) * 0.05; camera.lookAt(scene.position); // In animate(): camera.position.x = mouse.x * 3; // instant snap — jarring with no easing Medium https://threejs.org/docs/#api/en/math/MathUtils.lerp
34 33 Animation GSAP for Multi-Step Sequences Use GSAP timelines for any animation with more than two sequential steps or for scroll-linked camera paths. GSAP timelines can be paused reversed and scrubbed — far more maintainable than boolean state machines. Use GSAP timelines for sequences with more than two steps and for scroll-driven animations Implement multi-step sequences with boolean flags and manual frame counters const tl = gsap.timeline({ defaults: { ease: 'power2.out' } }); tl.from(mesh.position, { y: -3, duration: 1 }) .to(mesh.rotation, { y: Math.PI, duration: 1 }, '-=0.3') .to(camera.position, { z: 2, duration: 1.5 }); let step = 0; let t = 0; function animate() { if (step === 0 && (t += 0.01) >= 1) step = 1; } // grows unmanageable with 3+ steps High https://gsap.com/docs/v3/GSAP/Timeline/
35 34 Animation Pause Render Loop on Tab Hidden Use renderer.setAnimationLoop() as the loop driver so you can pass null to pause and a function to resume. Continuous rendering in a hidden tab wastes CPU GPU and battery with no user benefit. Use renderer.setAnimationLoop(animate) to drive the loop; pass null to pause on visibilitychange Drive with internal requestAnimationFrame and never stop the loop when the tab is hidden renderer.setAnimationLoop(animate); // use setAnimationLoop as the driver — not requestAnimationFrame inside animate function animate() { const dt = clock.getDelta(); renderer.render(scene, camera); } document.addEventListener('visibilitychange', () => { if (document.hidden) renderer.setAnimationLoop(null); else renderer.setAnimationLoop(animate); }); function animate() { requestAnimationFrame(animate); // self-referencing RAF cannot be stopped externally renderer.render(scene, camera); } animate(); // runs forever in background tab — drains battery High https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
36 35 GSAP Load GSAP Before Scene Script Load GSAP from its own CDN script tag before your scene script. In bundler projects install via npm and import. GSAP is a completely separate library from Three.js — never try to import it from the Three.js package. Load GSAP CDN before the scene script; or npm install gsap and import separately Import gsap from three or expect it to be defined without a separate load <!-- CDN: load GSAP before your scene script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script> <!-- Bundler: --> // import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; import gsap from 'three'; // undefined — GSAP has nothing to do with Three.js Critical https://gsap.com/docs/v3/Installation
37 36 GSAP Register ScrollTrigger Before Use Call gsap.registerPlugin(ScrollTrigger) once at the top of your script before any scrollTrigger config object. Without registration the ScrollTrigger name is undefined and the tween throws immediately. Call gsap.registerPlugin(ScrollTrigger) as the first line before any gsap.to/from/timeline with scrollTrigger Include scrollTrigger config in gsap.to() calls without first registering the plugin gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { z: 2, scrollTrigger: { trigger: '.hero-section', scrub: 1 } }); gsap.to(mesh.position, { scrollTrigger: { trigger: '.section', scrub: true } }); // TypeError: ScrollTrigger is not a constructor — not registered Critical https://gsap.com/docs/v3/Plugins/ScrollTrigger/
38 37 GSAP Tween Three.js Properties Directly GSAP can tween any numeric JavaScript property including mesh.position.x mesh.rotation.y and material.opacity. No wrapper or adaptor is needed. Note: to tween material.opacity the material must have transparent:true set before the tween starts. Pass Three.js object properties directly to gsap.to(); set transparent:true before tweening opacity Use a plain proxy object then manually copy values to Three.js properties every frame gsap.to(mesh.rotation, { y: Math.PI * 2, duration: 2, ease: 'power1.inOut' }); mesh.material.transparent = true; // required before tweening opacity gsap.to(mesh.material, { opacity: 0, duration: 1 }); const tw = { v: 0 }; gsap.to(tw, { v: Math.PI * 2, onUpdate: () => mesh.rotation.y = tw.v }); // unnecessary proxy wrapper Medium https://gsap.com/docs/v3/GSAP/gsap.to()
39 38 GSAP scrub for Scroll-Driven Camera Path Use scrub:true or scrub:1 to link camera movement continuously to scroll position as a 0–1 ratio. scrub:1 adds a 1-second lag for cinematic smoothness. onEnter/onLeave fire only once and create jarring snaps — not the right tool for a camera path. Use scrub:1 for any scroll-controlled camera movement Use onEnter or onLeave callbacks for camera motion — they snap instead of scrubbing gsap.registerPlugin(ScrollTrigger); gsap.to(camera.position, { x: 5, y: 2, z: 0, ease: 'none', scrollTrigger: { trigger: '.canvas-wrapper', start: 'top top', end: 'bottom bottom', scrub: 1 } }); gsap.to(camera.position, { z: 0, scrollTrigger: { trigger: '.section', onEnter: () => {} } }); // fires once at scroll threshold — not a continuous scrub High https://gsap.com/docs/v3/Plugins/ScrollTrigger/
40 39 Performance InstancedMesh for Repeated Objects Use THREE.InstancedMesh when rendering 50 or more identical objects. It submits all N transforms in one draw call instead of N draw calls and reduces CPU-GPU communication overhead dramatically. Use InstancedMesh for any group of 50+ meshes sharing the same geometry and material Create 50+ separate Mesh objects with the same geometry and material const COUNT = 500; const iMesh = new THREE.InstancedMesh(geo, mat, COUNT); const matrix = new THREE.Matrix4(); for (let i = 0; i < COUNT; i++) { matrix.setPosition(Math.random()*10, Math.random()*10, Math.random()*10); iMesh.setMatrixAt(i, matrix); } iMesh.instanceMatrix.needsUpdate = true; scene.add(iMesh); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(geo, mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/InstancedMesh
41 40 Performance Tone Mapping and sRGB Encoding Enable ACESFilmicToneMapping and sRGBEncoding on the renderer for accurate perceptual color. Without tone mapping colors appear washed out or over-saturated. These are renderer properties set after construction and take effect immediately. Set renderer.toneMapping and renderer.outputEncoding after construction for all production scenes Leave tone mapping and output encoding at defaults when the scene targets realistic visuals renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0; renderer.outputEncoding = THREE.sRGBEncoding; // correct for r128 const renderer = new THREE.WebGLRenderer(); // defaults: NoToneMapping + LinearEncoding — colors appear flat and incorrect Medium https://threejs.org/docs/#api/en/renderers/WebGLRenderer.toneMapping
42 41 Performance antialias Set at Construction Only The antialias option can only be set at WebGLRenderer construction time. Setting renderer.antialias after construction has absolutely no effect — the WebGL context is already created without it. Decide before instantiating. Set antialias:true inside the WebGLRenderer constructor options object Construct the renderer without antialias then try to enable it by assigning the property const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // antialias baked into the WebGL context const renderer = new THREE.WebGLRenderer(); renderer.antialias = true; // no effect — context created without AA — edges remain aliased High https://threejs.org/docs/#api/en/renderers/WebGLRenderer
43 42 Performance FogExp2 for Depth and Far Culling Use scene.fog to create atmospheric depth. As a secondary benefit objects that disappear into fog before the far plane stop contributing to draw calls — useful in scenes with large view distances. Add FogExp2 to scenes with view distances above 100 units for both visual atmosphere and implicit far culling Ignore fog in scenes with far:1000+ and many distant objects that contribute tiny pixels per draw call scene.fog = new THREE.FogExp2(0x0a0a0a, 0.02); // exponential — density feels more natural than linear // far: 2000 with no fog — hundreds of distant objects too small to see still cost draw calls per frame Low https://threejs.org/docs/#api/en/scenes/FogExp2
44 43 Particles BufferGeometry Plus Points for Particle Systems Build all particle systems with BufferGeometry plus a Float32Array position attribute rendered as Points. Never use individual Mesh objects as particles — they cannot scale past a few hundred with good performance. Use Points plus BufferGeometry for all particle effects Create hundreds of individual Mesh objects to simulate a particle system const COUNT = 3000; const geo = new THREE.BufferGeometry(); const pos = new Float32Array(COUNT * 3); for (let i = 0; i < COUNT * 3; i++) pos[i] = (Math.random() - 0.5) * 20; geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); const particles = new THREE.Points(geo, new THREE.PointsMaterial({ size: 0.05, color: 0xffffff })); scene.add(particles); for (let i = 0; i < 500; i++) { scene.add(new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8), mat)); } // 500 separate draw calls per frame High https://threejs.org/docs/#api/en/objects/Points
45 44 Particles Particle Count Ceiling Start particle systems at 1000–3000 particles. Beyond 50000 causes sustained frame drops on mid-range mobile. Always test on a real device before increasing the count — desktop and mobile GPU performance ratios can be 10:1. Start at 3000 particles and profile on actual mobile hardware before raising the limit Set particle count at 100000 or higher without any mobile profiling const COUNT = 3000; // safe mobile baseline — profile before going higher const pos = new Float32Array(COUNT * 3); const COUNT = 150000; // 60fps on desktop — 8fps on a mid-range Android phone High https://threejs.org/docs/#api/en/objects/Points
46 45 Particles needsUpdate After Buffer Mutation After mutating any BufferAttribute array values per frame you must set geometry.attributes.position.needsUpdate = true so Three.js re-uploads the changed buffer to the GPU. Without it the GPU still uses the old data and particles appear completely frozen. Set needsUpdate = true on the position attribute after every per-frame mutation of the array Mutate the Float32Array values without flagging needsUpdate — positions update in JS but not on the GPU // In animate(): const pos = geo.attributes.position.array; for (let i = 0; i < pos.length; i += 3) { pos[i + 1] += Math.sin(clock.getElapsedTime() + i) * 0.001; // Y component } geo.attributes.position.needsUpdate = true; // GPU re-upload // In animate(): pos[1] += 0.001; // JS array updated — GPU buffer is stale — particles do not move Critical https://threejs.org/docs/#api/en/core/BufferAttribute.needsUpdate
47 46 Responsive Canvas Dimensions Not Window Size the renderer and camera to the canvas element's clientWidth and clientHeight — not window.innerWidth and innerHeight. This is correct when the canvas is inside a flex or grid container that does not fill the full viewport. Use canvas.clientWidth and canvas.clientHeight for all renderer and camera sizing Hardcode renderer size to window.innerWidth/innerHeight when the canvas may be inside a container renderer.setSize(canvas.clientWidth, canvas.clientHeight); camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); // wrong when canvas lives inside a sidebar or grid column High https://threejs.org/docs/#api/en/renderers/WebGLRenderer.setSize
48 47 Responsive ResizeObserver Over window resize Event Use ResizeObserver on the canvas container instead of the window resize event. ResizeObserver fires when the container element changes size independently of the browser window — common in split-pane layouts and sidebar collapsing. Attach ResizeObserver to the canvas parent element for accurate container-aware resize detection Use only window.addEventListener('resize') for canvas sizing when the canvas is not fullscreen const ro = new ResizeObserver(entries => { const { width, height } = entries[0].contentRect; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); ro.observe(canvas.parentElement); window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); }); // misses container-only resize events in split-pane UIs Medium https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
49 48 Responsive Touch Events for Mobile Interaction Add touchstart and touchmove listeners alongside mouse events so the scene remains interactive on mobile. Normalize touch coordinates to the same NDC range as mouse events and pass passive:false on touchmove if you call preventDefault. Handle both mouse and touch input for any interactive 3D scene Add only mouse event listeners and leave touch users with no interaction canvas.addEventListener('touchmove', e => { e.preventDefault(); const t = e.touches[0]; mouse.x = (t.clientX / canvas.clientWidth) * 2 - 1; mouse.y = -(t.clientY / canvas.clientHeight) * 2 + 1; }, { passive: false }); canvas.addEventListener('touchstart', e => { e.preventDefault(); }, { passive: false }); canvas.addEventListener('mousemove', handleMouse); // touch events unhandled — mobile users get no interaction Medium https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
50 49 Accessibility prefers-reduced-motion Check window.matchMedia('(prefers-reduced-motion: reduce)') before starting any auto-rotation, particle animation, or camera movement. Users who enable this OS preference have motion sickness or vestibular disorders. IMPORTANT: reading .matches once at page load is a one-time snapshot — if the user changes their OS accessibility setting mid-session the scene will not react. Attach a 'change' listener to the MediaQueryList so noMotion stays in sync at runtime. Use matchMedia.addEventListener('change') to keep noMotion reactive; gate all auto-animation on the live value Read .matches once at startup and never update it — the scene ignores mid-session OS setting changes const mq = window.matchMedia('(prefers-reduced-motion: reduce)'); let noMotion = mq.matches; mq.addEventListener('change', e => { noMotion = e.matches; }); // In animate(): if (!noMotion) { mesh.rotation.y += dt * 0.8; particles.rotation.y += dt * 0.1; } const noMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; // one-time snapshot — mid-session OS change is ignored entirely High https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
51 50 Accessibility Canvas aria-label Add role='img' and a descriptive aria-label to renderer.domElement after appending it to the DOM. Screen readers receive no information from a WebGL canvas — the aria-label is the only description they can announce to users. Set role='img' and a meaningful aria-label on renderer.domElement before or after appending it Append the canvas to the DOM with no accessibility attributes — invisible to screen readers renderer.domElement.setAttribute('role', 'img'); renderer.domElement.setAttribute('aria-label', 'Interactive 3D product viewer. Drag to rotate. Scroll to zoom.'); document.body.appendChild(renderer.domElement); document.body.appendChild(renderer.domElement); // bare canvas — screen readers announce nothing Medium https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#accessibility_concerns
52 51 Production Bundler Stack for Production For production use Three.js via npm plus Vite. You get full tree-shaking reduced bundle size access to the complete examples/jsm library including OrbitControls GLTFLoader and EffectComposer and TypeScript support. Use npm install three plus Vite or Webpack for any production client-facing project Serve raw CDN script tags in a production application that needs tree-shaking or TypeScript npm install three gsap // then in your JS: import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; <!-- In a Vite/React production build: --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> // no tree-shaking — entire Three.js ships Medium https://threejs.org/docs/#manual/en/introduction/Installation
53 52 Production GLTFLoader with scene traverse Load 3D models using GLTFLoader and traverse gltf.scene to configure castShadow receiveShadow and material overrides on all child Mesh nodes. Calling scene.add(gltf.scene) alone silently skips all shadow and material configuration. Use GLTFLoader and traverse the entire gltf.scene graph to set up shadows and materials on every Mesh child Load a GLTF model and pass gltf.scene directly to scene.add without traversing child meshes import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; const loader = new GLTFLoader(); loader.load('model.glb', gltf => { gltf.scene.traverse(child => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(gltf.scene); }); loader.load('model.glb', gltf => { scene.add(gltf.scene); // shadows and material setup silently skipped on all children }); Medium https://threejs.org/docs/#examples/en/loaders/GLTFLoader
54 53 Production LOD for Distance-Based Detail Use THREE.LOD to automatically swap high-detail and low-detail geometry as objects move closer or farther from the camera. This maintains frame rate in scenes with many objects spread across a large depth range. Use THREE.LOD to reduce triangle count on distant objects automatically Render the same high-polygon geometry for every object regardless of its distance from the camera const lod = new THREE.LOD(); lod.addLevel(highDetailMesh, 0); // used when < 15 units away lod.addLevel(medDetailMesh, 15); // 15–50 units lod.addLevel(lowDetailMesh, 50); // 50+ units scene.add(lod); scene.add(highDetailMesh); // 64k-triangle mesh rendered at full cost whether 1 unit or 100 units from camera Medium https://threejs.org/docs/#api/en/objects/LOD

View File

@ -77,6 +77,14 @@ CSV_CONFIG = {
}
}
# Output columns whose content (code samples, checklists) must never be
# hard-truncated for display -- truncating mid-snippet destroys the value.
UNTRUNCATED_COLS = {
"Code Example Good", "Code Example Bad", "Code Good", "Code Bad",
"Implementation Checklist", "Design System Variables", "CSS Import",
"Tailwind Config", "GSAP Snippet",
}
STACK_CONFIG = {
"react": {"file": "stacks/react.csv"},
"nextjs": {"file": "stacks/nextjs.csv"},
@ -111,6 +119,44 @@ _STACK_COLS = {
AVAILABLE_STACKS = list(STACK_CONFIG.keys())
# ============ TOKENIZATION ============
# Common two-letter/three-letter words that add noise without adding search
# signal. Deliberately short -- domain-relevant short tokens (ui, ux, ai,
# css, 3d, js, os, md, gsap) must stay searchable, which is why we don't
# filter purely by length.
_STOPWORDS = {
"to", "in", "on", "at", "is", "of", "by", "or", "an", "if", "no", "so",
"do", "be", "we", "it", "as", "the", "and", "for", "are", "was",
}
# Query/corpus normalization so common spelling variants match each other.
# Keep this a plain dict (stdlib only, no fuzzy-matching dependency).
_SYNONYMS = {
"e-commerce": "ecommerce",
"dark-mode": "dark",
"darkmode": "dark",
"light-mode": "light",
"lightmode": "light",
"a11y": "accessibility",
"nav": "navigation",
"sign-up": "signup",
"log-in": "login",
"colour": "color",
"colours": "colors",
"customisation": "customization",
"organisation": "organization",
"behaviour": "behavior",
"ux/ui": "ux ui",
}
def _normalize(text):
"""Apply synonym substitution before tokenizing."""
for variant, canonical in _SYNONYMS.items():
text = text.replace(variant, canonical)
return text
# ============ BM25 IMPLEMENTATION ============
class BM25:
"""BM25 ranking algorithm for text search"""
@ -124,11 +170,13 @@ class BM25:
self.idf = {}
self.doc_freqs = defaultdict(int)
self.N = 0
self._term_freqs = [] # precomputed per-doc term frequencies
def tokenize(self, text):
"""Lowercase, split, remove punctuation, filter short words"""
text = re.sub(r'[^\w\s]', ' ', str(text).lower())
return [w for w in text.split() if len(w) >= 2]
"""Lowercase, normalize synonyms, split, remove punctuation, filter stopwords"""
text = _normalize(str(text).lower())
text = re.sub(r'[^\w\s]', ' ', text)
return [w for w in text.split() if len(w) >= 2 and w not in _STOPWORDS]
def fit(self, documents):
"""Build BM25 index from documents"""
@ -139,12 +187,14 @@ class BM25:
self.doc_lengths = [len(doc) for doc in self.corpus]
self.avgdl = sum(self.doc_lengths) / self.N
self._term_freqs = []
for doc in self.corpus:
seen = set()
tf = defaultdict(int)
for word in doc:
if word not in seen:
self.doc_freqs[word] += 1
seen.add(word)
tf[word] += 1
self._term_freqs.append(tf)
for word in tf:
self.doc_freqs[word] += 1
for word, freq in self.doc_freqs.items():
self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
@ -154,16 +204,14 @@ class BM25:
query_tokens = self.tokenize(query)
scores = []
for idx, doc in enumerate(self.corpus):
for idx in range(self.N):
score = 0
doc_len = self.doc_lengths[idx]
term_freqs = defaultdict(int)
for word in doc:
term_freqs[word] += 1
term_freqs = self._term_freqs[idx]
for token in query_tokens:
if token in self.idf:
tf = term_freqs[token]
tf = term_freqs.get(token, 0)
idf = self.idf[token]
numerator = tf * (self.k1 + 1)
denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
@ -173,48 +221,139 @@ class BM25:
return sorted(scores, key=lambda x: x[1], reverse=True)
def vocabulary(self):
"""All indexed terms, for suggestion/typo-recovery purposes."""
return list(self.idf.keys())
# ============ CSV / INDEX CACHE ============
# Data files are small and reused across multiple domain searches within a
# single --design-system run; avoid re-reading + re-indexing the same file
# repeatedly in one process.
_csv_cache = {} # filepath -> (mtime, rows)
_bm25_cache = {} # (filepath, tuple(search_cols)) -> (mtime, BM25 instance)
# ============ SEARCH FUNCTIONS ============
def _load_csv(filepath):
"""Load CSV and return list of dicts"""
"""Load CSV and return list of dicts, with mtime-based caching."""
mtime = filepath.stat().st_mtime
cached = _csv_cache.get(filepath)
if cached and cached[0] == mtime:
return cached[1]
with open(filepath, 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
rows = list(csv.DictReader(f))
_csv_cache[filepath] = (mtime, rows)
return rows
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25"""
if not filepath.exists():
return []
def _get_bm25(filepath, search_cols, data):
"""Fitted BM25 index for this file+columns, with mtime-based caching."""
key = (filepath, tuple(search_cols))
mtime = filepath.stat().st_mtime
cached = _bm25_cache.get(key)
if cached and cached[0] == mtime:
return cached[1]
data = _load_csv(filepath)
# Build documents from search columns
documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
# BM25 search
bm25 = BM25()
bm25.fit(documents)
_bm25_cache[key] = (mtime, bm25)
return bm25
# ============ SEARCH FUNCTIONS ============
def _search_csv(filepath, search_cols, output_cols, query, max_results):
"""Core search function using BM25. Returns (results, bm25_or_none)."""
if not filepath.exists():
return [], None
try:
data = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError) as e:
return [{"_error": f"Failed to read {filepath.name}: {e}"}], None
if not data:
return [], None
bm25 = _get_bm25(filepath, search_cols, data)
ranked = bm25.score(query)
# Get top results with score > 0
results = []
for idx, score in ranked[:max_results]:
if score > 0:
row = data[idx]
results.append({col: row.get(col, "") for col in output_cols if col in row})
return results
return results, bm25
def detect_domain(query):
"""Auto-detect the most relevant domain from query"""
query_lower = query.lower()
def _suggest_terms(bm25, query, limit=6):
"""Nearest known vocabulary terms for a query that returned 0 hits,
so the caller can retry instead of silently reporting nothing."""
if bm25 is None:
return []
query_tokens = set(bm25.tokenize(query))
if not query_tokens:
return []
domain_keywords = {
candidates = []
for term in bm25.vocabulary():
for qt in query_tokens:
if term.startswith(qt[:3]) or qt.startswith(term[:3]):
candidates.append(term)
break
# Stable de-dup, most frequent terms first (doc_freqs available via idf keys only,
# so just de-dup preserving discovery order).
seen = set()
ordered = []
for term in candidates:
if term not in seen:
seen.add(term)
ordered.append(term)
return ordered[:limit]
# Load the product-domain keyword list from products.csv at import time so
# it stays in sync with the data instead of needing manual updates to a
# hardcoded list. Falls back to a small built-in seed if the file is
# missing (e.g. package built without data/).
def _load_product_keywords():
seed = ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming",
"portfolio", "crypto", "dashboard", "fitness", "marketplace"]
filepath = DATA_DIR / CSV_CONFIG["product"]["file"]
if not filepath.exists():
return seed
try:
rows = _load_csv(filepath)
except (csv.Error, OSError, UnicodeDecodeError):
return seed
keywords = set(seed)
for row in rows:
raw = row.get("Keywords", "")
for kw in re.split(r"[,;]", raw):
kw = kw.strip().lower()
if kw and len(kw) >= 3:
keywords.add(kw)
return sorted(keywords, key=len, reverse=True)
_DOMAIN_KEYWORDS = None
def _domain_keywords():
global _DOMAIN_KEYWORDS
if _DOMAIN_KEYWORDS is not None:
return _DOMAIN_KEYWORDS
_DOMAIN_KEYWORDS = {
"color": ["color", "palette", "hex", "#", "rgb", "token", "semantic", "accent", "destructive", "muted", "foreground"],
"chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
"landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
"product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard", "fitness", "restaurant", "hotel", "travel", "music", "education", "learning", "legal", "insurance", "medical", "beauty", "pharmacy", "dental", "pet", "dating", "wedding", "recipe", "delivery", "ride", "booking", "calendar", "timer", "tracker", "diary", "note", "chat", "messenger", "crm", "invoice", "parking", "transit", "vpn", "alarm", "weather", "sleep", "meditation", "fasting", "habit", "grocery", "meme", "wardrobe", "plant care", "reading", "flashcard", "puzzle", "trivia", "arcade", "photography", "streaming", "podcast", "newsletter", "marketplace", "freelancer", "coworking", "airline", "museum", "theater", "church", "non-profit", "charity", "kindergarten", "daycare", "senior care", "veterinary", "florist", "bakery", "brewery", "construction", "automotive", "real estate", "logistics", "agriculture", "coding bootcamp"],
"product": _load_product_keywords(),
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"],
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
"typography": ["font pairing", "typography pairing", "heading font", "body font"],
@ -224,16 +363,57 @@ def detect_domain(query):
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
}
return _DOMAIN_KEYWORDS
scores = {domain: sum(1 for kw in keywords if re.search(r'\b' + re.escape(kw) + r'\b', query_lower)) for domain, keywords in domain_keywords.items()}
best = max(scores, key=scores.get)
return best if scores[best] > 0 else "style"
# Domains checked in this fixed order when scores tie, so results are
# deterministic instead of depending on dict/hash ordering.
_DOMAIN_TIEBREAK_ORDER = [
"ux", "product", "style", "color", "typography", "google-fonts",
"chart", "landing", "icons", "gsap", "react", "web",
]
def detect_domain(query, return_scores=False):
"""Auto-detect the most relevant domain from query.
Matches are weighted by keyword length (multi-word/longer phrases are
more specific and score higher than short generic words). Ties are
broken by a fixed domain priority order, not dict/insertion order.
"""
query_lower = query.lower()
domain_keywords = _domain_keywords()
scores = {}
for domain, keywords in domain_keywords.items():
total = 0.0
for kw in keywords:
if re.search(r'\b' + re.escape(kw) + r'\b', query_lower):
# weight = 1 point per word in the keyword phrase
total += max(1, len(kw.split()))
scores[domain] = total
ranked = sorted(
scores.items(),
key=lambda item: (item[1], -_DOMAIN_TIEBREAK_ORDER.index(item[0])
if item[0] in _DOMAIN_TIEBREAK_ORDER else -999),
reverse=True,
)
best_domain, best_score = ranked[0]
result = best_domain if best_score > 0 else "style"
if return_scores:
runner_up = ranked[1][0] if len(ranked) > 1 and ranked[1][1] > 0 else None
return result, runner_up
return result
def search(query, domain=None, max_results=MAX_RESULTS):
"""Main search function with auto-domain detection"""
auto_detected = domain is None
runner_up = None
if domain is None:
domain = detect_domain(query)
domain, runner_up = detect_domain(query, return_scores=True)
config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
filepath = DATA_DIR / config["file"]
@ -241,15 +421,22 @@ def search(query, domain=None, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"File not found: {filepath}", "domain": domain}
results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
return {
out = {
"domain": domain,
"query": query,
"file": config["file"],
"count": len(results),
"results": results
"results": results,
}
if auto_detected:
out["auto_detected"] = True
if runner_up:
out["runner_up_domain"] = runner_up
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out
def search_stack(query, stack, max_results=MAX_RESULTS):
@ -262,13 +449,16 @@ def search_stack(query, stack, max_results=MAX_RESULTS):
if not filepath.exists():
return {"error": f"Stack file not found: {filepath}", "stack": stack}
results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
results, bm25 = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
return {
out = {
"domain": "stack",
"stack": stack,
"query": query,
"file": STACK_CONFIG[stack]["file"],
"count": len(results),
"results": results
"results": results,
}
if not results:
out["suggestions"] = _suggest_terms(bm25, query)
return out

View File

@ -7,10 +7,12 @@ to generate comprehensive design system recommendations.
Usage:
from design_system import generate_design_system
result = generate_design_system("SaaS dashboard", "My Project")
print(result["text"])
# With persistence (Master + Overrides pattern)
result = generate_design_system("SaaS dashboard", "My Project", persist=True)
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")
result = generate_design_system("SaaS dashboard", "My Project", persist=True, output_dir="/path/to/project")
result["persistence"] # {"status": "success"|"skipped_exists", "created_files": [...], ...}
result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard", output_dir="/path/to/project")
"""
import csv
@ -665,7 +667,8 @@ def format_markdown(design_system: dict) -> str:
# ============ MAIN ENTRY POINT ============
def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
persist: bool = False, page: str = None, output_dir: str = None,
variance: int = None, motion: int = None, density: int = None) -> str:
variance: int = None, motion: int = None, density: int = None,
force: bool = False) -> dict:
"""
Main entry point for design system generation.
@ -679,20 +682,28 @@ def generate_design_system(query: str, project_name: str = None, output_format:
variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
force: If True, overwrite an existing MASTER.md; otherwise persistence
is skipped (with a status message) when one already exists
Returns:
Formatted design system string
dict with keys: "text" (formatted design system string), "design_system"
(raw dict, useful for --json callers), and "persistence" (result of
persist_design_system(), or None if persist=False)
"""
generator = DesignSystemGenerator()
design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
# Persist to files if requested
persistence_result = None
if persist:
persist_design_system(design_system, page, output_dir, query)
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
if output_format == "markdown":
return format_markdown(design_system)
return format_ascii_box(design_system)
text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system)
return {
"text": text,
"design_system": design_system,
"persistence": persistence_result,
}
# ============ PERSISTENCE FUNCTIONS ============
@ -707,42 +718,61 @@ def safe_slug(name, fallback: str = "default") -> str:
return slug or fallback
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict:
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
page_query: str = None, force: bool = False) -> dict:
"""
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
Args:
design_system: The generated design system dictionary
page: Optional page name for page-specific override file
output_dir: Optional output directory (defaults to current working directory)
page_query: Optional query string for intelligent page override generation
force: If True, overwrite an existing MASTER.md. If False (default) and
MASTER.md already exists, persistence is skipped so prior design
decisions aren't silently discarded.
Returns:
dict with created file paths and status
dict with created file paths and status. status is "skipped_exists" if
MASTER.md already existed and force was not set.
"""
base_dir = Path(output_dir) if output_dir else Path.cwd()
# Use project name for project-specific folder. Coalesce falsy values
# (missing key, explicit None, or "") so slugification can't crash.
project_slug = safe_slug(design_system.get("project_name") or "default")
# (missing key, explicit None, or "") so the .lower() below can't crash.
project_name = design_system.get("project_name") or "default"
project_slug = safe_slug(project_name)
design_system_dir = base_dir / "design-system" / project_slug
pages_dir = design_system_dir / "pages"
master_file = design_system_dir / "MASTER.md"
if master_file.exists() and not force:
return {
"status": "skipped_exists",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": [],
"message": (
f"{master_file} already exists and was not modified. "
"Read it first to check for prior design decisions, then "
"re-run with force=True / --force to overwrite."
),
}
created_files = []
# Create directories
design_system_dir.mkdir(parents=True, exist_ok=True)
pages_dir.mkdir(parents=True, exist_ok=True)
master_file = design_system_dir / "MASTER.md"
# Generate and write MASTER.md
master_content = format_master_md(design_system)
with open(master_file, 'w', encoding='utf-8') as f:
f.write(master_content)
created_files.append(str(master_file))
# If page is specified, create page override file with intelligent content
if page:
page_file = pages_dir / f"{safe_slug(page, 'page')}.md"
@ -750,10 +780,11 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
with open(page_file, 'w', encoding='utf-8') as f:
f.write(page_content)
created_files.append(str(page_file))
return {
"status": "success",
"design_system_dir": str(design_system_dir),
"master_file": str(master_file),
"created_files": created_files
}
@ -1337,4 +1368,4 @@ if __name__ == "__main__":
args = parser.parse_args()
result = generate_design_system(args.query, args.project_name, args.format)
print(result)
print(result["text"])

View File

@ -1,127 +1,162 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
python search.py "<query>" --design-system --variance 8 --motion 9 --density 7
Domains: style, prompt, color, chart, landing, product, ux, typography, google-fonts, gsap
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui, html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel, javafx, wpf, winui, avalonia, uno, uwp
Design dials (1-10, only with --design-system):
--variance DESIGN_VARIANCE: 1=centered/minimal, 10=bold/asymmetric
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/MASTER.md
--page Also create a page-specific override file in design-system/pages/
"""
import argparse
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system, persist_design_system, safe_slug
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
def format_output(result):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append(f"## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append(f"## UI Pro Max Search Results")
output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if len(value_str) > 300:
value_str = value_str[:300] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
return "\n".join(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UI Pro Max Search")
parser.add_argument("query", help="Search query")
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
# Design dials (1-10), only applied with --design-system
parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)")
parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)")
parser.add_argument("--density", type=int, choices=range(1, 11), metavar="1-10", help="VISUAL_DENSITY dial: 1=spacious, 10=dense/dashboard; overrides the spacing scale (only with --design-system)")
args = parser.parse_args()
# Design system takes priority
if args.design_system:
result = generate_design_system(
args.query,
args.project_name,
args.format,
persist=args.persist,
page=args.page,
output_dir=args.output_dir,
variance=args.variance,
motion=args.motion,
density=args.density
)
print(result)
# Print persistence confirmation
if args.persist:
project_slug = safe_slug(args.project_name or args.query.upper())
print("\n" + "=" * 60)
print(f"✅ Design system persisted to design-system/{project_slug}/")
print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
if args.page:
page_filename = safe_slug(args.page, 'page')
print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
print("")
print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
import json
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result))
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
python search.py "<query>" --design-system [-p "Project Name"]
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
python search.py "<query>" --design-system --variance 8 --motion 9 --density 7
Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web
Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui,
html-tailwind, shadcn, jetpack-compose, threejs, angular, laravel
Design dials (1-10, only with --design-system):
--variance DESIGN_VARIANCE: 1=centered/minimal, 10=bold/asymmetric
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
Persistence (Master + Overrides pattern):
--persist Save design system to design-system/<project-slug>/MASTER.md
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
always pass this explicitly, pointed at the project root)
--page Also create a page-specific override file in design-system/<project-slug>/pages/
--force Overwrite an existing MASTER.md (without this, persistence is skipped
if MASTER.md already exists, so prior design decisions aren't lost)
"""
import argparse
import json as json_module
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, UNTRUNCATED_COLS, search, search_stack
from design_system import generate_design_system
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
TRUNCATE_AT = 300
def format_output(result, full=False):
"""Format results for Claude consumption (token-optimized)"""
if "error" in result:
return f"Error: {result['error']}"
output = []
if result.get("stack"):
output.append("## UI Pro Max Stack Guidelines")
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
else:
output.append("## UI Pro Max Search Results")
domain_note = result['domain']
if result.get("auto_detected"):
domain_note += " (auto-detected"
if result.get("runner_up_domain"):
domain_note += f", runner-up: {result['runner_up_domain']}"
domain_note += ")"
output.append(f"**Domain:** {domain_note} | **Query:** {result['query']}")
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
if result['count'] == 0:
output.append(
"No matches. This is not a match with an empty value -- the query "
"did not hit the database. Retry with broader/different keywords "
"before falling back to general defaults, and say explicitly that "
"no database match was found if you do fall back."
)
suggestions = result.get("suggestions") or []
if suggestions:
output.append(f"**Closest known terms:** {', '.join(suggestions)}")
return "\n".join(output)
for i, row in enumerate(result['results'], 1):
output.append(f"### Result {i}")
for key, value in row.items():
value_str = str(value)
if not full and key not in UNTRUNCATED_COLS and len(value_str) > TRUNCATE_AT:
value_str = value_str[:TRUNCATE_AT] + "..."
output.append(f"- **{key}:** {value_str}")
output.append("")
return "\n".join(output)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UI Pro Max Search")
parser.add_argument("query", help="Search query")
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
parser.add_argument("--json", action="store_true", help="Output as JSON")
parser.add_argument("--full", action="store_true", help="Do not truncate long field values in text output")
# Design system generation
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system (ignored if --json)")
# Persistence (Master + Overrides pattern)
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/<project-slug>/MASTER.md (creates hierarchical structure)")
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/<project-slug>/pages/")
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)")
parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)")
# Design dials (1-10), only applied with --design-system
parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)")
parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)")
parser.add_argument("--density", type=int, choices=range(1, 11), metavar="1-10", help="VISUAL_DENSITY dial: 1=spacious, 10=dense/dashboard; overrides the spacing scale (only with --design-system)")
args = parser.parse_args()
# Design system takes priority
if args.design_system:
result = generate_design_system(
args.query,
args.project_name,
args.format,
persist=args.persist,
page=args.page,
output_dir=args.output_dir,
variance=args.variance,
motion=args.motion,
density=args.density,
force=args.force,
)
if args.json:
print(json_module.dumps(
{"design_system": result["design_system"], "persistence": result["persistence"]},
indent=2, ensure_ascii=False,
))
else:
print(result["text"])
if args.persist:
persistence = result["persistence"] or {}
print("\n" + "=" * 60)
if persistence.get("status") == "skipped_exists":
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
else:
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
print(f"✅ Design system persisted to {ds_dir}/")
for f in persistence.get("created_files", []):
print(f" 📄 {f}")
print("")
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.")
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
print("=" * 60)
# Stack search
elif args.stack:
result = search_stack(args.query, args.stack, args.max_results)
if args.json:
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result, full=args.full))
# Domain search
else:
result = search(args.query, args.domain, args.max_results)
if args.json:
print(json_module.dumps(result, indent=2, ensure_ascii=False))
else:
print(format_output(result, full=args.full))

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stdlib-only regression tests for core.py / design_system.py (unittest, not
pytest -- this project ships with zero external dependencies and the tests
shouldn't add one).
Run with:
python -m unittest discover -s scripts/tests -v
or directly:
python scripts/tests/test_core.py
"""
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPTS_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(SCRIPTS_DIR))
from core import BM25, detect_domain, search, search_stack, CSV_CONFIG, AVAILABLE_STACKS
from design_system import generate_design_system, persist_design_system, DesignSystemGenerator
class TestTokenizer(unittest.TestCase):
def test_short_domain_terms_are_kept(self):
bm25 = BM25()
tokens = bm25.tokenize("UI and UX design with 3D and AI")
self.assertIn("ui", tokens)
self.assertIn("3d", tokens)
self.assertIn("ai", tokens)
def test_stopwords_removed(self):
bm25 = BM25()
tokens = bm25.tokenize("this is for the team to do")
for stopword in ("is", "for", "the", "to", "do"):
self.assertNotIn(stopword, tokens)
def test_synonym_normalization(self):
bm25 = BM25()
self.assertEqual(bm25.tokenize("e-commerce store"), bm25.tokenize("ecommerce store"))
self.assertEqual(bm25.tokenize("dark-mode toggle"), bm25.tokenize("dark toggle"))
class TestSearchDomains(unittest.TestCase):
"""Known query -> expected top-domain sanity checks (not exact-row pinning,
since data can grow; these assert the engine still finds *something*
relevant for each domain's core vocabulary)."""
def test_ui_is_searchable_in_style_domain(self):
result = search("ui minimalism", domain="style", max_results=1)
self.assertGreater(result["count"], 0, "literal 'ui' token must be searchable, not filtered by tokenizer")
def test_accessibility_query_hits_ux(self):
result = search("accessibility contrast wcag keyboard", domain="ux", max_results=3)
self.assertGreater(result["count"], 0)
def test_zero_result_query_reports_suggestions_not_error(self):
result = search("zzqqxx totally made up gibberish", domain="ux", max_results=2)
self.assertEqual(result["count"], 0)
self.assertIn("suggestions", result)
self.assertNotIn("error", result)
def test_every_configured_domain_file_exists_and_is_searchable(self):
for domain, config in CSV_CONFIG.items():
with self.subTest(domain=domain):
result = search("design", domain=domain, max_results=1)
self.assertNotIn("error", result, f"domain '{domain}' failed: {result.get('error')}")
def test_every_stack_file_exists_and_is_searchable(self):
for stack in AVAILABLE_STACKS:
with self.subTest(stack=stack):
result = search_stack("performance", stack, max_results=1)
self.assertNotIn("error", result, f"stack '{stack}' failed: {result.get('error')}")
class TestDomainDetection(unittest.TestCase):
def test_style_keywords_route_to_style(self):
self.assertEqual(detect_domain("glassmorphism dark ui"), "style")
def test_accessibility_keywords_route_to_ux(self):
self.assertEqual(detect_domain("accessibility contrast wcag"), "ux")
def test_ambiguous_query_returns_runner_up(self):
domain, runner_up = detect_domain("font pairing elegant crypto", return_scores=True)
self.assertIsNotNone(domain)
# runner_up may be None if the winning domain has no close second --
# this just verifies the call shape works without raising.
def test_empty_query_falls_back_to_style(self):
self.assertEqual(detect_domain("...!!!???"), "style")
class TestPersistence(unittest.TestCase):
def test_persist_then_skip_then_force(self):
with tempfile.TemporaryDirectory() as tmp:
result = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result["persistence"]["status"], "success")
master = Path(result["persistence"]["master_file"])
self.assertTrue(master.exists())
original_content = master.read_text(encoding="utf-8")
# Second persist without force must not overwrite.
result2 = generate_design_system("saas dashboard", "Test Project", persist=True, output_dir=tmp)
self.assertEqual(result2["persistence"]["status"], "skipped_exists")
self.assertEqual(master.read_text(encoding="utf-8"), original_content)
# With force=True it must overwrite.
result3 = generate_design_system("ecommerce luxury", "Test Project", persist=True, output_dir=tmp, force=True)
self.assertEqual(result3["persistence"]["status"], "success")
def test_persist_writes_only_under_output_dir(self):
with tempfile.TemporaryDirectory() as tmp:
generate_design_system("saas dashboard", "Scoped Project", persist=True, output_dir=tmp)
expected = Path(tmp) / "design-system" / "scoped-project" / "MASTER.md"
self.assertTrue(expected.exists())
class TestReasoningMatch(unittest.TestCase):
def test_known_category_matches_exactly(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("SaaS (General)")
self.assertTrue(rule, "exact-match category lookup should not fall through to fuzzy matching")
def test_unknown_category_falls_back_gracefully(self):
gen = DesignSystemGenerator()
rule = gen._find_reasoning_rule("Totally Unknown Category XYZ")
# Should not raise; may return {} which _apply_reasoning handles with defaults.
self.assertIsInstance(rule, dict)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Data integrity guardrail for ui-ux-pro-max. Stdlib-only, no pytest dependency,
so it can run as a standalone pre-publish/CI check:
python validate_data.py
Checks, per configured domain/stack CSV:
- file exists
- header row contains every column referenced in search_cols/output_cols
- no duplicate primary-key values (first column) within a file
- any "Decision_Rules"-style JSON column parses as JSON
Exits 0 with no output on success; exits 1 and prints every problem found
on failure (fail-fast is the wrong call here -- a data change can break
several files at once, so we want the full list in one run).
"""
import csv
import json
import sys
from pathlib import Path
from core import CSV_CONFIG, STACK_CONFIG, _STACK_COLS, DATA_DIR
# REASONING_FILE lives in design_system.py, not core.py -- redeclared here to
# avoid a circular import (design_system.py imports core.py).
REASONING_FILE = "ui-reasoning.csv"
JSON_COLUMNS = {"Decision_Rules"}
def _read_rows(filepath):
with open(filepath, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
return reader.fieldnames or [], list(reader)
def _check_file(label, filepath, search_cols, output_cols, problems):
if not filepath.exists():
problems.append(f"[{label}] missing file: {filepath}")
return
try:
headers, rows = _read_rows(filepath)
except (csv.Error, UnicodeDecodeError, OSError) as e:
problems.append(f"[{label}] failed to parse {filepath.name}: {e}")
return
header_set = set(headers)
for col in set(search_cols) | set(output_cols):
if col not in header_set:
problems.append(f"[{label}] {filepath.name}: expected column '{col}' not found in header")
# Only check for duplicates against an actual identifier column ("No" is
# the sequential-index convention used across this dataset). The first
# CSV column is not reliably a unique key -- e.g. stack files use
# "Category", which legitimately repeats across many guideline rows.
if "No" in header_set:
seen = {}
for i, row in enumerate(rows, start=2): # +1 header, +1 to be 1-indexed
key = row.get("No", "")
if key in seen:
problems.append(
f"[{label}] {filepath.name}: duplicate 'No' value '{key}' on rows {seen[key]} and {i}"
)
else:
seen[key] = i
elif label.startswith("stack:"):
problems.append(
f"[{label}] {filepath.name}: missing 'No' index column present in other stack files "
"(schema drift -- harmless for search, but inconsistent with the rest of data/stacks/)"
)
for row_idx, row in enumerate(rows, start=2):
for col in JSON_COLUMNS:
if col in row and row[col]:
try:
json.loads(row[col])
except json.JSONDecodeError as e:
problems.append(
f"[{label}] {filepath.name} row {row_idx}: column '{col}' is not valid JSON: {e}"
)
def main():
problems = []
for domain, config in CSV_CONFIG.items():
_check_file(f"domain:{domain}", DATA_DIR / config["file"],
config["search_cols"], config["output_cols"], problems)
for stack, config in STACK_CONFIG.items():
_check_file(f"stack:{stack}", DATA_DIR / config["file"],
_STACK_COLS["search_cols"], _STACK_COLS["output_cols"], problems)
reasoning_path = DATA_DIR / REASONING_FILE
if reasoning_path.exists():
_check_file("reasoning", reasoning_path, ["UI_Category"], ["UI_Category", "Decision_Rules"], problems)
else:
problems.append(f"[reasoning] missing file: {reasoning_path}")
if problems:
print(f"FAILED: {len(problems)} data integrity issue(s) found:\n")
for p in problems:
print(f" - {p}")
sys.exit(1)
print(f"OK: validated {len(CSV_CONFIG)} domain files, {len(STACK_CONFIG)} stack files, and ui-reasoning.csv")
sys.exit(0)
if __name__ == "__main__":
main()