Silence render-disposed spam, unbreak bundled skills, drop board wake
Three independently ugly bugs that all fed the same log flood:
* Electron's `WebFrameMain.send` writes every "Render frame was disposed"
to stderr via `console.error`. When the worker fans a second
agent-event past a reloading renderer, we produced thousands of
identical lines and stalled the main loop on stderr I/O. Added a
`mainFrame.detached` guard so the send is short-circuited before
Electron's own catch block fires, and installed a targeted filter in
`suppress-warnings.ts` (now actually imported from the entry point)
so the specific `console.error("Error sending from webFrameMain:"…)`
noise never reaches the terminal. Any other payload still surfaces.
* `dispatchAgentMessage` accepted the human-reader sentinel as a wake
target when an agent replied to `__board__` — `wakeAgentIfPossible`
then called `db.getAgent("__board__")`, threw, and the dispatcher
kept repeating on every send. Strip `HUMAN_SENDER_ID` at
`resolveMessageWakeTargets`, and keep a defense-in-depth guard in the
heartbeat so a stray caller (future automation fan-out) cannot
reintroduce the crash.
* Pi's skills loader rejects any SKILL.md whose frontmatter `name`
diverges from its parent directory. The four bundled `my-writing-style`
copies declared `name: writing-style-skill`, so every install emitted
a warning and dropped the skill. They also lived as orphan gitlinks
(mode 160000 without .gitmodules), and the global `*.md` gitignore
hid every other SKILL.md from version control. Fixed the frontmatter
to match the dir, converted the dangling submodules to plain trees,
and allowlisted `builtin-skills/**/*.md` so a fresh clone carries the
catalogue instead of silently losing it.
This commit is contained in:
1 parent
7a9a6779b0
commit
e74dafcd36
287 files changed
+59858
-10
No files matched your search
@@ -0,0 +1,130 @@
|
||||
---
|
||||
name: canvas-design
|
||||
description: Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
These are instructions for creating design philosophies - aesthetic movements that are then EXPRESSED VISUALLY. Output only .md files, .pdf files, and .png files.
|
||||
|
||||
Complete this in two steps:
|
||||
1. Design Philosophy Creation (.md file)
|
||||
2. Express by creating it on a canvas (.pdf file or .png file)
|
||||
|
||||
First, undertake this task:
|
||||
|
||||
## DESIGN PHILOSOPHY CREATION
|
||||
|
||||
To begin, create a VISUAL PHILOSOPHY (not layouts or templates) that will be interpreted through:
|
||||
- Form, space, color, composition
|
||||
- Images, graphics, shapes, patterns
|
||||
- Minimal text as visual accent
|
||||
|
||||
### THE CRITICAL UNDERSTANDING
|
||||
- What is received: Some subtle input or instructions by the user that should be taken into account, but used as a foundation; it should not constrain creative freedom.
|
||||
- What is created: A design philosophy/aesthetic movement.
|
||||
- What happens next: Then, the same version receives the philosophy and EXPRESSES IT VISUALLY - creating artifacts that are 90% visual design, 10% essential text.
|
||||
|
||||
Consider this approach:
|
||||
- Write a manifesto for an art movement
|
||||
- The next phase involves making the artwork
|
||||
|
||||
The philosophy must emphasize: Visual expression. Spatial communication. Artistic interpretation. Minimal words.
|
||||
|
||||
### HOW TO GENERATE A VISUAL PHILOSOPHY
|
||||
|
||||
**Name the movement** (1-2 words): "Brutalist Joy" / "Chromatic Silence" / "Metabolist Dreams"
|
||||
|
||||
**Articulate the philosophy** (4-6 paragraphs - concise but complete):
|
||||
|
||||
To capture the VISUAL essence, express how the philosophy manifests through:
|
||||
- Space and form
|
||||
- Color and material
|
||||
- Scale and rhythm
|
||||
- Composition and balance
|
||||
- Visual hierarchy
|
||||
|
||||
**CRITICAL GUIDELINES:**
|
||||
- **Avoid redundancy**: Each design aspect should be mentioned once. Avoid repeating points about color theory, spatial relationships, or typographic principles unless adding new depth.
|
||||
- **Emphasize craftsmanship REPEATEDLY**: The philosophy MUST stress multiple times that the final work should appear as though it took countless hours to create, was labored over with care, and comes from someone at the absolute top of their field. This framing is essential - repeat phrases like "meticulously crafted," "the product of deep expertise," "painstaking attention," "master-level execution."
|
||||
- **Leave creative space**: Remain specific about the aesthetic direction, but concise enough that the next Claude has room to make interpretive choices also at a extremely high level of craftmanship.
|
||||
|
||||
The philosophy must guide the next version to express ideas VISUALLY, not through text. Information lives in design, not paragraphs.
|
||||
|
||||
### PHILOSOPHY EXAMPLES
|
||||
|
||||
**"Concrete Poetry"**
|
||||
Philosophy: Communication through monumental form and bold geometry.
|
||||
Visual expression: Massive color blocks, sculptural typography (huge single words, tiny labels), Brutalist spatial divisions, Polish poster energy meets Le Corbusier. Ideas expressed through visual weight and spatial tension, not explanation. Text as rare, powerful gesture - never paragraphs, only essential words integrated into the visual architecture. Every element placed with the precision of a master craftsman.
|
||||
|
||||
**"Chromatic Language"**
|
||||
Philosophy: Color as the primary information system.
|
||||
Visual expression: Geometric precision where color zones create meaning. Typography minimal - small sans-serif labels letting chromatic fields communicate. Think Josef Albers' interaction meets data visualization. Information encoded spatially and chromatically. Words only to anchor what color already shows. The result of painstaking chromatic calibration.
|
||||
|
||||
**"Analog Meditation"**
|
||||
Philosophy: Quiet visual contemplation through texture and breathing room.
|
||||
Visual expression: Paper grain, ink bleeds, vast negative space. Photography and illustration dominate. Typography whispered (small, restrained, serving the visual). Japanese photobook aesthetic. Images breathe across pages. Text appears sparingly - short phrases, never explanatory blocks. Each composition balanced with the care of a meditation practice.
|
||||
|
||||
**"Organic Systems"**
|
||||
Philosophy: Natural clustering and modular growth patterns.
|
||||
Visual expression: Rounded forms, organic arrangements, color from nature through architecture. Information shown through visual diagrams, spatial relationships, iconography. Text only for key labels floating in space. The composition tells the story through expert spatial orchestration.
|
||||
|
||||
**"Geometric Silence"**
|
||||
Philosophy: Pure order and restraint.
|
||||
Visual expression: Grid-based precision, bold photography or stark graphics, dramatic negative space. Typography precise but minimal - small essential text, large quiet zones. Swiss formalism meets Brutalist material honesty. Structure communicates, not words. Every alignment the work of countless refinements.
|
||||
|
||||
*These are condensed examples. The actual design philosophy should be 4-6 substantial paragraphs.*
|
||||
|
||||
### ESSENTIAL PRINCIPLES
|
||||
- **VISUAL PHILOSOPHY**: Create an aesthetic worldview to be expressed through design
|
||||
- **MINIMAL TEXT**: Always emphasize that text is sparse, essential-only, integrated as visual element - never lengthy
|
||||
- **SPATIAL EXPRESSION**: Ideas communicate through space, form, color, composition - not paragraphs
|
||||
- **ARTISTIC FREEDOM**: The next Claude interprets the philosophy visually - provide creative room
|
||||
- **PURE DESIGN**: This is about making ART OBJECTS, not documents with decoration
|
||||
- **EXPERT CRAFTSMANSHIP**: Repeatedly emphasize the final work must look meticulously crafted, labored over with care, the product of countless hours by someone at the top of their field
|
||||
|
||||
**The design philosophy should be 4-6 paragraphs long.** Fill it with poetic design philosophy that brings together the core vision. Avoid repeating the same points. Keep the design philosophy generic without mentioning the intention of the art, as if it can be used wherever. Output the design philosophy as a .md file.
|
||||
|
||||
---
|
||||
|
||||
## DEDUCING THE SUBTLE REFERENCE
|
||||
|
||||
**CRITICAL STEP**: Before creating the canvas, identify the subtle conceptual thread from the original request.
|
||||
|
||||
**THE ESSENTIAL PRINCIPLE**:
|
||||
The topic is a **subtle, niche reference embedded within the art itself** - not always literal, always sophisticated. Someone familiar with the subject should feel it intuitively, while others simply experience a masterful abstract composition. The design philosophy provides the aesthetic language. The deduced topic provides the soul - the quiet conceptual DNA woven invisibly into form, color, and composition.
|
||||
|
||||
This is **VERY IMPORTANT**: The reference must be refined so it enhances the work's depth without announcing itself. Think like a jazz musician quoting another song - only those who know will catch it, but everyone appreciates the music.
|
||||
|
||||
---
|
||||
|
||||
## CANVAS CREATION
|
||||
|
||||
With both the philosophy and the conceptual framework established, express it on a canvas. Take a moment to gather thoughts and clear the mind. Use the design philosophy created and the instructions below to craft a masterpiece, embodying all aspects of the philosophy with expert craftsmanship.
|
||||
|
||||
**IMPORTANT**: For any type of content, even if the user requests something for a movie/game/book, the approach should still be sophisticated. Never lose sight of the idea that this should be art, not something that's cartoony or amateur.
|
||||
|
||||
To create museum or magazine quality work, use the design philosophy as the foundation. Create one single page, highly visual, design-forward PDF or PNG output (unless asked for more pages). Generally use repeating patterns and perfect shapes. Treat the abstract philosophical design as if it were a scientific bible, borrowing the visual language of systematic observation—dense accumulation of marks, repeated elements, or layered patterns that build meaning through patient repetition and reward sustained viewing. Add sparse, clinical typography and systematic reference markers that suggest this could be a diagram from an imaginary discipline, treating the invisible subject with the same reverence typically reserved for documenting observable phenomena. Anchor the piece with simple phrase(s) or details positioned subtly, using a limited color palette that feels intentional and cohesive. Embrace the paradox of using analytical visual language to express ideas about human experience: the result should feel like an artifact that proves something ephemeral can be studied, mapped, and understood through careful attention. This is true art.
|
||||
|
||||
**Text as a contextual element**: Text is always minimal and visual-first, but let context guide whether that means whisper-quiet labels or bold typographic gestures. A punk venue poster might have larger, more aggressive type than a minimalist ceramics studio identity. Most of the time, font should be thin. All use of fonts must be design-forward and prioritize visual communication. Regardless of text scale, nothing falls off the page and nothing overlaps. Every element must be contained within the canvas boundaries with proper margins. Check carefully that all text, graphics, and visual elements have breathing room and clear separation. This is non-negotiable for professional execution. **IMPORTANT: Use different fonts if writing text. Search the `./canvas-fonts` directory. Regardless of approach, sophistication is non-negotiable.**
|
||||
|
||||
Download and use whatever fonts are needed to make this a reality. Get creative by making the typography actually part of the art itself -- if the art is abstract, bring the font onto the canvas, not typeset digitally.
|
||||
|
||||
To push boundaries, follow design instinct/intuition while using the philosophy as a guiding principle. Embrace ultimate design freedom and choice. Push aesthetics and design to the frontier.
|
||||
|
||||
**CRITICAL**: To achieve human-crafted quality (not AI-generated), create work that looks like it took countless hours. Make it appear as though someone at the absolute top of their field labored over every detail with painstaking care. Ensure the composition, spacing, color choices, typography - everything screams expert-level craftsmanship. Double-check that nothing overlaps, formatting is flawless, every detail perfect. Create something that could be shown to people to prove expertise and rank as undeniably impressive.
|
||||
|
||||
Output the final result as a single, downloadable .pdf or .png file, alongside the design philosophy used as a .md file.
|
||||
|
||||
---
|
||||
|
||||
## FINAL STEP
|
||||
|
||||
**IMPORTANT**: The user ALREADY said "It isn't perfect enough. It must be pristine, a masterpiece if craftsmanship, as if it were about to be displayed in a museum."
|
||||
|
||||
**CRITICAL**: To refine the work, avoid adding more graphics; instead refine what has been created and make it extremely crisp, respecting the design philosophy and the principles of minimalism entirely. Rather than adding a fun filter or refactoring a font, consider how to make the existing composition more cohesive with the art. If the instinct is to call a new function or draw a new shape, STOP and instead ask: "How can I make what's already here more of a piece of art?"
|
||||
|
||||
Take a second pass. Go back to the code and refine/polish further to make this a philosophically designed masterpiece.
|
||||
|
||||
## MULTI-PAGE OPTION
|
||||
|
||||
To create additional pages when requested, create more creative pages along the same lines as the design philosophy but distinctly different as well. Bundle those pages in the same .pdf or many .pngs. Treat the first page as just a single page in a whole coffee table book waiting to be filled. Make the next pages unique twists and memories of the original. Have them almost tell a story in a very tasteful way. Exercise full creative freedom.
|
||||
@@ -0,0 +1,109 @@
|
||||
<h1 align="center">design-dna</h1>
|
||||
|
||||

|
||||
|
||||
|
||||
https://github.com/user-attachments/assets/00e0a28d-42ce-4a08-a0c0-1ecf8b9f7e97
|
||||
|
||||
|
||||
<h3 align="center">Other cases</h3>
|
||||
|
||||
https://github.com/user-attachments/assets/80793608-930d-42ca-951f-eb21ac188d54
|
||||
|
||||
https://github.com/user-attachments/assets/cd4cba94-cd2c-480f-8efa-4ac86e00ae1f
|
||||
|
||||
English | [中文](README.zh-CN.md)
|
||||
|
||||
An agent skill for extracting, structuring, and applying visual design identity as machine-readable "Design DNA" across three dimensions: design tokens, qualitative style, and visual effects.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [Node.js](https://nodejs.org/) environment installed
|
||||
- Ability to run `npx` commands
|
||||
|
||||
## Installation
|
||||
|
||||
### Quick Install (Recommended)
|
||||
|
||||
```bash
|
||||
npx skills add zanwei/design-dna
|
||||
```
|
||||
|
||||
### Install to Specific Agent
|
||||
|
||||
```bash
|
||||
# Cursor only, non-interactive, global install
|
||||
npx skills add zanwei/design-dna -a cursor -g -y
|
||||
|
||||
# Claude Code only
|
||||
npx skills add zanwei/design-dna -a claude-code -g -y
|
||||
```
|
||||
|
||||
### Install from Local Clone
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zanwei/design-dna.git
|
||||
npx skills add ./design-dna -y
|
||||
```
|
||||
|
||||
### List Available Skills
|
||||
|
||||
```bash
|
||||
npx skills add zanwei/design-dna --list
|
||||
```
|
||||
|
||||
## What It Does
|
||||
|
||||
| Dimension | Role |
|
||||
|-----------|------|
|
||||
| **Design System** | Measurable tokens: color, typography, spacing, layout, shape, elevation, motion, components |
|
||||
| **Design Style** | Qualitative perception: mood, visual language, composition, imagery, interaction feel, brand voice |
|
||||
| **Visual Effects** | Beyond plain CSS: Canvas, WebGL, 3D, particles, shaders, scroll-driven motion, cursor effects, SVG animation, glassmorphism, etc. |
|
||||
|
||||
The skill drives a **three-phase** workflow:
|
||||
|
||||
1. **Structure** — Surface the full schema and field meanings (see `references/schema.md`).
|
||||
2. **Analyze** — From screenshots, images, or URLs, produce a complete JSON profile (every field filled; conflicts noted).
|
||||
3. **Generate** — Given DNA JSON plus content, implement the design (default: self-contained HTML/CSS/JS), following `references/generation-guide.md`.
|
||||
|
||||
Phases can be used alone or chained (e.g. Analyze → Generate).
|
||||
|
||||
## How It Works
|
||||
|
||||
Pipeline at a glance ([Mermaid](https://github.blog/news-insights/product-news/github-now-supports-mermaid-diagrams-in-markdown/) renders on GitHub):
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["Reference designs<br/>Screenshots · URLs · images<br/><br/>Any design you admire"]
|
||||
B["Design DNA JSON<br/>Quantified spec<br/><br/>Structured profile"]
|
||||
C["Final output<br/>Faithful implementation<br/><br/>Production-ready UI"]
|
||||
|
||||
A -->|"Analyze — extract every visual property"| B
|
||||
B -->|"Generate — apply DNA to your content"| C
|
||||
B -.-> D["Save · reuse · version control"]
|
||||
```
|
||||
|
||||
**Step 1 — Curate references.** Collect screenshots, images, or live URLs of designs whose visual identity you want to capture. Multiple references can be combined; the skill identifies dominant patterns and notes variants.
|
||||
|
||||
**Step 2 — Extract DNA.** Feed the references to the agent. It inspects every visual property across all three dimensions and outputs a complete, quantified Design DNA JSON — no empty fields, no guesswork. This JSON becomes a portable, reusable design specification.
|
||||
|
||||
**Step 3 — Generate from DNA.** Provide the DNA JSON together with your own content. The agent produces implementations that faithfully reproduce the original design language while adapting to your material.
|
||||
|
||||
The DNA JSON is the key artifact. Once extracted, it can be **committed to version control**, **shared across teams**, **reused across projects**, and **iteratively refined** — turning subjective "make it look like that site" into a precise, reproducible specification that any agent can consume.
|
||||
|
||||
> [!TIP]
|
||||
> **Refining visual richness.** If the first pass still feels visually thin or under-detailed next to your references, run a deliberate **polish iteration**: re-attach the **same URLs or screenshots**. This narrows the gap between a workable draft and a reference-faithful, visually rich result without starting over.
|
||||
>
|
||||
> **Prompt:** **Against the reference, audit hierarchy, ornamentation, typographic rhythm, motion, materiality, and overall UI—then merge your conclusions back into the current implementation.**
|
||||
|
||||
## Compatibility
|
||||
|
||||
Follows the [Agent Skills specification](https://agentskills.io). Installable via [`skills` CLI](https://github.com/vercel-labs/skills) to all [supported agents](https://github.com/vercel-labs/skills#supported-agents) including Cursor, Claude Code, Codex, GitHub Copilot, and [39 more](https://github.com/vercel-labs/skills#supported-agents).
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests are welcome. For substantive behavior changes, update `SKILL.md` and any affected files under `references/` so the skill stays internally consistent.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,99 @@
|
||||
<h1 align="center">design-dna</h1>
|
||||
|
||||

|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
面向编程智能体的技能,用于提取、结构化并应用视觉设计身份(Design DNA),覆盖三个维度:设计系统(可度量 token)、设计风格(定性感受)与视觉特效。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 已安装 [Node.js](https://nodejs.org/) 环境
|
||||
- 能够运行 `npx` 命令
|
||||
|
||||
## 安装
|
||||
|
||||
### 快速安装(推荐)
|
||||
|
||||
```bash
|
||||
npx skills add zanwei/design-dna
|
||||
```
|
||||
|
||||
### 安装到指定智能体
|
||||
|
||||
```bash
|
||||
# 仅 Cursor,非交互,全局安装
|
||||
npx skills add zanwei/design-dna -a cursor -g -y
|
||||
|
||||
# 仅 Claude Code
|
||||
npx skills add zanwei/design-dna -a claude-code -g -y
|
||||
```
|
||||
|
||||
### 从本地克隆安装
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zanwei/design-dna.git
|
||||
npx skills add ./design-dna -y
|
||||
```
|
||||
|
||||
### 列出可用技能
|
||||
|
||||
```bash
|
||||
npx skills add zanwei/design-dna --list
|
||||
```
|
||||
|
||||
## 功能说明
|
||||
|
||||
| 维度 | 说明 |
|
||||
|------|------|
|
||||
| **设计系统** | 可度量 token:色彩、字体、间距、版式、形状、层级、动效、组件等 |
|
||||
| **设计风格** | 定性描述:情绪、视觉语言、构图、图像风格、交互气质、品牌语气等 |
|
||||
| **视觉特效** | 超出普通 CSS 的实现:Canvas、WebGL、3D、粒子、着色器、滚动驱动动效、光标效果、SVG 动画、玻璃拟态等 |
|
||||
|
||||
技能内置 **三阶段** 工作流:
|
||||
|
||||
1. **结构** — 展示完整 schema 与各字段含义(见 `references/schema.md`)。
|
||||
2. **分析** — 根据截图、图片或 URL,输出字段齐全的 JSON 画像(无空字段;多参考冲突时注明主方案与变体)。
|
||||
3. **生成** — 在已有 DNA JSON + 内容的前提下落地实现(默认:自包含 HTML/CSS/JS),并遵循 `references/generation-guide.md` 中的质量检查。
|
||||
|
||||
各阶段可单独使用,也可串联(例如:分析 → 生成)。
|
||||
|
||||
## 工作原理
|
||||
|
||||
流程一览(GitHub 会渲染下方 [Mermaid](https://github.blog/news-insights/product-news/github-now-supports-mermaid-diagrams-in-markdown/) 图):
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["参考设计<br/>截图 · 网址 · 图片<br/><br/>任何你喜欢的设计"]
|
||||
B["Design DNA JSON<br/>量化规格<br/><br/>结构化画像"]
|
||||
C["最终产出<br/>忠实还原的实现<br/><br/>可交付界面"]
|
||||
|
||||
A -->|"分析 — 逐项提取视觉属性"| B
|
||||
B -->|"生成 — 将 DNA 应用到你的内容"| C
|
||||
B -.-> D["保存 · 复用 · 版本管理"]
|
||||
```
|
||||
|
||||
**第一步 — 收集参考。** 准备你欣赏的设计截图、图片或线上页面链接。可以同时提供多份参考,技能会识别主导模式并标注差异。
|
||||
|
||||
**第二步 — 提取 DNA。** 将参考素材交给智能体,它会逐项检视三个维度的每一项视觉属性,输出一份完整且量化的 Design DNA JSON — 没有空字段、没有猜测。这份 JSON 就是一份可移植、可复用的设计规格。
|
||||
|
||||
**第三步 — 基于 DNA 生成。** 将 DNA JSON 与你自己的内容一同提供,智能体会生成忠实还原原始设计语言的实现,同时适配你的素材与文案。
|
||||
|
||||
DNA JSON 是核心产物。一旦提取完成,它可以**提交到版本控制**、**跨团队共享**、**在多个项目中复用**,也可以**持续迭代微调** — 把主观的「照着那个网站做」变成一份精确、可复现的规格定义,任何智能体都能据此稳定输出一致的设计。
|
||||
|
||||
> [!TIP]
|
||||
> **视觉精修提示。** 若首轮产出相对参考仍显单薄或细节不足,可将**同一批参考链接或截图**再次提供给智能体,发起明确的**精修轮次**;可在保留初稿的前提下显著拉近与「高保真参照」的差距,无需从零重做。
|
||||
>
|
||||
> **Prompt:** **请其对照参考复审界面层级与点缀、字阶与留白、动效与材质及整体 UI,并将结论回填至当前实现。**
|
||||
|
||||
## 兼容性
|
||||
|
||||
符合 [Agent Skills 规范](https://agentskills.io)。可通过 [`skills` CLI](https://github.com/vercel-labs/skills) 安装到所有[支持的智能体](https://github.com/vercel-labs/skills#supported-agents),包括 Cursor、Claude Code、Codex、GitHub Copilot 等 [40+ 款](https://github.com/vercel-labs/skills#supported-agents)。
|
||||
|
||||
## 贡献
|
||||
|
||||
欢迎提 Issue 与 Pull Request。若修改技能行为,请同步更新 `SKILL.md` 及 `references/` 下相关文件,保持文档与行为一致。
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
name: design-dna
|
||||
description: >-
|
||||
Extract, define, and apply design DNA across three dimensions: design system
|
||||
(tokens), design style (qualitative feel), and visual effects (Canvas, WebGL,
|
||||
3D, particles, shaders, scroll effects, etc.). Use this skill when: (1) a user
|
||||
wants to see the full 3-dimension design structure/schema, (2) a user provides
|
||||
images, screenshots, or URLs of reference designs and wants them analyzed into
|
||||
a structured JSON profile covering all three dimensions, (3) a user has a
|
||||
Design DNA JSON and content and wants a design generated from it, or (4) any
|
||||
combination of these phases. Triggers on "design DNA", "extract design style",
|
||||
"analyze design", "design tokens from reference", "generate design from JSON",
|
||||
"design system from screenshot", "design profile", "style guide JSON",
|
||||
"visual effects analysis", "design with effects", "3d design analysis".
|
||||
---
|
||||
|
||||
# Design DNA
|
||||
|
||||
A 3-phase workflow for extracting, structuring, and applying design identity across three dimensions:
|
||||
|
||||
1. **Design System** — measurable tokens (color, typography, spacing, layout, shape, elevation, motion, components)
|
||||
2. **Design Style** — qualitative perception (mood, visual language, composition, imagery, interaction feel, brand voice)
|
||||
3. **Visual Effects** — special rendering (Canvas, WebGL, 3D, particles, shaders, scroll effects, cursor effects, SVG animations, glassmorphism, etc.)
|
||||
|
||||
## Phases
|
||||
|
||||
### Phase 1: Structure — Output the Schema
|
||||
|
||||
When the user asks for the structural dimensions or schema:
|
||||
|
||||
1. Read [references/schema.md](references/schema.md)
|
||||
2. Present the full schema with field descriptions
|
||||
3. Explain the three dimensions and their roles:
|
||||
- **design_system**: What you can measure — exact hex values, pixel sizes, rem scales
|
||||
- **design_style**: What you can feel — mood, personality, composition strategy
|
||||
- **visual_effects**: What you can see but can't express in CSS alone — WebGL scenes, particle systems, shader distortions, scroll-driven animations
|
||||
4. Ask if the user wants to customize or extend any dimensions
|
||||
|
||||
### Phase 2: Analyze — Extract DNA from References
|
||||
|
||||
When the user provides images, screenshots, or links representing a target design style:
|
||||
|
||||
1. Read [references/schema.md](references/schema.md) for the full field list
|
||||
2. For each reference provided:
|
||||
- If image/screenshot: analyze visual properties directly
|
||||
- If URL: fetch and analyze the page's visual design
|
||||
3. For every field in the schema, extract or infer a value from the references
|
||||
4. When multiple references conflict, note the dominant pattern and mention variants
|
||||
5. Output a complete Design DNA JSON — every field populated, no empty strings
|
||||
6. After output, ask: "Want to adjust any values before using this for generation?"
|
||||
|
||||
**Analysis approach per dimension:**
|
||||
|
||||
#### Dimension 1: design_system
|
||||
- **color**: Extract dominant palette via visual sampling. Primary by area dominance, secondary by supporting role, accent by CTA usage. Map neutral scale from lightest background to darkest text.
|
||||
- **typography**: Identify font families by visual characteristics (geometric, humanist, serif class). Estimate scale ratios from heading/body size relationships.
|
||||
- **spacing**: Assess density by element proximity. Measure rhythm by section gap consistency.
|
||||
- **layout**: Identify grid by content alignment patterns. Note max-width, column count, asymmetry.
|
||||
- **shape**: Measure border-radius by comparing to element height. Note border and divider presence.
|
||||
- **elevation**: Classify shadow softness, spread, and layering approach.
|
||||
- **motion**: If observable (video/interactive), note easing curves and duration feel.
|
||||
|
||||
#### Dimension 2: design_style
|
||||
- Synthesize holistic impressions — mood, personality, composition strategy
|
||||
- Compare against genre archetypes (SaaS, editorial, brutalist, etc.)
|
||||
- Note ornamentation level and whitespace philosophy
|
||||
|
||||
#### Dimension 3: visual_effects
|
||||
- **From code**: Scan for `<canvas>`, WebGL contexts, Three.js/Pixi.js imports, GSAP/Lottie usage, custom shaders, IntersectionObserver scroll triggers, SVG `<animate>` elements
|
||||
- **From screenshots**: Describe visible effects that go beyond standard CSS — glowing particles, 3D object renders, noise textures, gradient animations, parallax depth, cursor trails, text distortions, glassmorphic surfaces. Note these in `composite_notes` when exact implementation can't be determined.
|
||||
- **From video/interaction demos**: Note scroll behaviors, hover distortions, transition choreography, loading sequences
|
||||
- Set `enabled: false` for any effect category not present in the reference
|
||||
- Rate `overview.effect_intensity` and `overview.performance_tier` based on what's observed
|
||||
|
||||
### Phase 3: Generate — Apply DNA to Content
|
||||
|
||||
When the user provides DNA JSON + content to design:
|
||||
|
||||
1. Read [references/generation-guide.md](references/generation-guide.md)
|
||||
2. Parse the DNA JSON and extract all tokens across three dimensions
|
||||
3. Build CSS custom properties from `design_system` values
|
||||
4. Apply `design_style` qualitative fields to guide subjective design decisions
|
||||
5. When the design needs assets or source materials, fetch them from the original source whenever possible. If the user provided a URL, retrieve the real asset from that URL instead of recreating, approximating, or substituting it.
|
||||
6. Implement `visual_effects` using appropriate technologies:
|
||||
- Lightweight effects → CSS animations, SVG, vanilla JS
|
||||
- Medium effects → Canvas 2D, GSAP, Lottie
|
||||
- Heavy effects → Three.js, custom GLSL shaders, Pixi.js
|
||||
7. Generate the design output (default: self-contained HTML with inline CSS/JS)
|
||||
8. Run quality checks from the generation guide
|
||||
|
||||
**If the user provides only content without DNA JSON**, ask whether to:
|
||||
- Analyze a reference first (go to Phase 2)
|
||||
- Use a described style (extract DNA from description, then generate)
|
||||
|
||||
## Phase Combinations
|
||||
|
||||
Users may invoke any combination:
|
||||
- **Phase 1 only**: "Show me the design structure/schema"
|
||||
- **Phase 2 only**: "Analyze this design" (with images/links)
|
||||
- **Phase 2 → 3**: "Analyze this design and build me a landing page in the same style"
|
||||
- **Phase 1 → 2 → 3**: Full pipeline
|
||||
- **Phase 3 only**: User already has DNA JSON
|
||||
|
||||
Detect which phase(s) are needed from context and execute accordingly.
|
||||
@@ -0,0 +1,209 @@
|
||||
# Generation Guide
|
||||
|
||||
How to use a completed Design DNA JSON to generate designs in Phase 3. Covers all three dimensions.
|
||||
|
||||
## Priority Order
|
||||
|
||||
When generating a design from DNA JSON + content:
|
||||
|
||||
1. **Color & Typography** — define 80% of visual identity
|
||||
2. **Spacing & Layout** — structural rhythm
|
||||
3. **Shape & Elevation** — surface treatment
|
||||
4. **Design Style qualitative fields** — mood, personality, composition approach
|
||||
5. **Visual Effects** — special rendering layer (Canvas, WebGL, shaders, etc.)
|
||||
6. **Motion & Interaction** — enhance after static layout and effects are solid
|
||||
|
||||
## Dimension 1: design_system → Code
|
||||
|
||||
### Tailwind CSS / Utility-First
|
||||
```
|
||||
color.primary.hex → --color-primary / bg-[hex]
|
||||
typography.font_families → font-family config
|
||||
spacing.scale → spacing config values
|
||||
shape.border_radius → rounded-{sm|md|lg|full}
|
||||
elevation.levels → shadow-{sm|md|lg}
|
||||
```
|
||||
|
||||
### Plain CSS / CSS Variables
|
||||
Generate a `:root` block with all design tokens:
|
||||
```css
|
||||
:root {
|
||||
--color-primary: {color.primary.hex};
|
||||
--color-secondary: {color.secondary.hex};
|
||||
--color-accent: {color.accent.hex};
|
||||
--font-heading: {typography.font_families.heading};
|
||||
--font-body: {typography.font_families.body};
|
||||
--radius-sm: {shape.border_radius.small};
|
||||
--radius-md: {shape.border_radius.medium};
|
||||
--radius-lg: {shape.border_radius.large};
|
||||
--shadow-low: {elevation.levels.low};
|
||||
--shadow-med: {elevation.levels.medium};
|
||||
--shadow-high: {elevation.levels.high};
|
||||
--ease: {motion.easing};
|
||||
--duration-micro: {motion.duration_scale.micro};
|
||||
--duration-normal: {motion.duration_scale.normal};
|
||||
--duration-macro: {motion.duration_scale.macro};
|
||||
/* ... map all tokens */
|
||||
}
|
||||
```
|
||||
|
||||
### Component Decisions
|
||||
- `components.button_style` → button classes and variants
|
||||
- `components.card_style` → card container treatment
|
||||
- `components.navigation_pattern` → nav component choice
|
||||
- `interaction_feel.hover_behavior` → :hover / :focus states
|
||||
- `motion.easing` + `motion.duration_scale` → transition properties
|
||||
|
||||
## Dimension 2: design_style → Subjective Decisions
|
||||
|
||||
| DNA Field | Guides |
|
||||
|---|---|
|
||||
| aesthetic.mood | Overall emotional feeling — warm tones, cool precision, etc. |
|
||||
| visual_language.whitespace_usage | padding/margin generosity |
|
||||
| visual_language.contrast_level | How much elements pop vs. blend |
|
||||
| composition.hierarchy_method | What tool to use for emphasis |
|
||||
| composition.balance_type | Symmetric layout vs. dynamic asymmetry |
|
||||
| imagery.graphic_elements | Decorative SVGs, gradients, patterns |
|
||||
| brand_voice_in_ui.tone | Microcopy phrasing |
|
||||
| interaction_feel.microinteraction_density | How many hover/click effects |
|
||||
|
||||
## Dimension 3: visual_effects → Special Rendering
|
||||
|
||||
### Technology Selection by Performance Tier
|
||||
|
||||
| Tier | Technologies | When to Use |
|
||||
|---|---|---|
|
||||
| **lightweight** | CSS animations, SVG SMIL, vanilla JS | `overview.performance_tier` = "lightweight" |
|
||||
| **medium** | Canvas 2D, GSAP, Lottie, anime.js | `overview.performance_tier` = "medium" |
|
||||
| **heavy** | Three.js, custom GLSL, Pixi.js, WebGL | `overview.performance_tier` = "heavy" |
|
||||
|
||||
### Implementation Patterns
|
||||
|
||||
#### Background Effects
|
||||
```
|
||||
"none" → skip
|
||||
"gradient-animation" → CSS @keyframes on linear-gradient or conic-gradient
|
||||
"noise-field" → Canvas 2D with Perlin/simplex noise
|
||||
"mesh-gradient" → SVG <mesh> or canvas interpolation
|
||||
"video-bg" → <video autoplay muted loop> with poster fallback
|
||||
"generative-art" → Canvas 2D or WebGL generative algorithms
|
||||
```
|
||||
|
||||
#### Particle Systems
|
||||
When `particle_systems.enabled: true`:
|
||||
- For `count` < 100 and no complex physics → vanilla JS + Canvas 2D
|
||||
- For `count` >= 100 or complex interaction → consider Pixi.js or Three.js Points
|
||||
- Map `interaction` ("mouse-repel", "mouse-attract") to pointer event handlers
|
||||
- Use `requestAnimationFrame` loop; include destroy/cleanup on unmount
|
||||
|
||||
#### 3D Elements
|
||||
When `3d_elements.enabled: true`:
|
||||
- Default to Three.js unless DNA specifies otherwise
|
||||
- Apply `lighting`, `camera`, `materials` from params
|
||||
- Add `post_processing` effects via EffectComposer
|
||||
- Handle resize with `ResizeObserver`
|
||||
- Load via CDN: `https://cdn.jsdelivr.net/npm/three@latest/build/three.module.js`
|
||||
|
||||
#### Shader Effects
|
||||
When `shader_effects.enabled: true`:
|
||||
- Create vertex/fragment shaders based on `type`
|
||||
- Pass `uniforms` from params (time, resolution, mouse position)
|
||||
- For "noise-distortion": use noise functions matching `noise_type`
|
||||
- Animate via `requestAnimationFrame` updating `u_time` uniform
|
||||
|
||||
#### Scroll Effects
|
||||
- **Parallax**: Use `transform: translateY()` with scroll offset × layer speed
|
||||
- **Scroll-triggered**: Use `IntersectionObserver` with `threshold` array
|
||||
- **Scrub behavior**: If "scrubbed", animation progress = scroll progress. If "triggered", play once on enter.
|
||||
|
||||
#### Text Effects
|
||||
```
|
||||
"split-letter-animate" → Split text into <span> per char/word, stagger CSS animation
|
||||
"typewriter" → CSS steps() or JS interval revealing chars
|
||||
"glitch" → Layered clip-path + color offset animation
|
||||
"gradient-fill" → background-clip: text with animated gradient
|
||||
"3d-extrude" → text-shadow stack or WebGL text geometry
|
||||
```
|
||||
|
||||
#### Cursor Effects
|
||||
When `cursor_effects.enabled: true`:
|
||||
- Hide default cursor: `cursor: none`
|
||||
- Create custom cursor element following `pointermove`
|
||||
- "magnetic-buttons": Apply transform pull on hover proximity
|
||||
- "spotlight": Radial gradient mask following cursor
|
||||
- "trail": Spawn fading elements on move
|
||||
|
||||
#### Glassmorphism / Neumorphism
|
||||
```
|
||||
"glass" → backdrop-filter: blur({blur_radius}); background: rgba(..., {transparency})
|
||||
"neumorphic-light" → Dual box-shadow (light + dark offset) on light bg
|
||||
"neumorphic-dark" → Dual box-shadow (inverted) on dark bg
|
||||
"frosted-layers" → Stacked blur layers with varying opacity
|
||||
```
|
||||
|
||||
#### Canvas Drawings
|
||||
When `canvas_drawings.enabled: true`:
|
||||
- Initialize canvas with `width/height` matching container
|
||||
- Use `draw_method` to select rendering approach
|
||||
- Animate with `requestAnimationFrame`
|
||||
- Handle `responsiveness` via ResizeObserver
|
||||
|
||||
#### SVG Animations
|
||||
When `svg_animations.enabled: true`:
|
||||
- "path-draw": Animate `stroke-dashoffset` from path length to 0
|
||||
- "morph-shapes": Interpolate `d` attribute between two paths
|
||||
- "stroke-animation": Animate stroke properties (dasharray, width, color)
|
||||
|
||||
### Fallback Strategy
|
||||
|
||||
Always implement the fallback defined in `overview.fallback_strategy`:
|
||||
|
||||
```js
|
||||
// Example: reduce to CSS on low-end devices
|
||||
const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const isLowEnd = navigator.hardwareConcurrency <= 2;
|
||||
if (prefersReduced || isLowEnd) {
|
||||
// Apply fallback: static CSS version, disable canvas/WebGL
|
||||
}
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
Generate output as a single self-contained HTML file with inline CSS and JS (unless user specifies a framework). Include:
|
||||
|
||||
1. CSS custom properties block from `design_system` tokens
|
||||
2. Component styles from `design_system.components` + `design_style`
|
||||
3. Layout structure per `design_system.layout`
|
||||
4. Content populated from user-provided content
|
||||
5. Visual effects implemented per `visual_effects` specification
|
||||
6. Animations/transitions if `design_system.motion.philosophy` is not "none"
|
||||
7. Fallback handling for effects
|
||||
|
||||
For heavy effects requiring external libraries, load via CDN `<script>` tags:
|
||||
```html
|
||||
<!-- Three.js -->
|
||||
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@latest/build/three.module.js"}}</script>
|
||||
|
||||
<!-- GSAP -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@latest/dist/gsap.min.js"></script>
|
||||
|
||||
<!-- Lottie -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/lottie-web@latest/build/player/lottie.min.js"></script>
|
||||
```
|
||||
|
||||
## Quality Checks
|
||||
|
||||
Before delivering, verify:
|
||||
- [ ] Every color in output traces back to DNA palette
|
||||
- [ ] Font families match DNA specification
|
||||
- [ ] Spacing rhythm matches DNA scale
|
||||
- [ ] Border radius matches DNA shape tokens
|
||||
- [ ] Overall mood matches `design_style.aesthetic.mood`
|
||||
- [ ] Component patterns match DNA `components` descriptions
|
||||
- [ ] Contrast ratios meet WCAG AA minimum (4.5:1 body text, 3:1 large text)
|
||||
- [ ] Visual effects match `visual_effects` specification (type, technology, params)
|
||||
- [ ] Fallback strategy is implemented for effects
|
||||
- [ ] `prefers-reduced-motion` is respected
|
||||
- [ ] No effects render when their `enabled` flag is `false`
|
||||
- [ ] Canvas/WebGL contexts are properly sized and handle resize
|
||||
- [ ] Animation loops use `requestAnimationFrame` (no `setInterval`)
|
||||
@@ -0,0 +1,366 @@
|
||||
# Design DNA Schema
|
||||
|
||||
Three-dimensional design profile:
|
||||
- **design_system** — measurable tokens
|
||||
- **design_style** — qualitative perception
|
||||
- **visual_effects** — special rendering such as Canvas, WebGL, 3D, particles, shaders, scroll effects, cursor effects, SVG animation, and glassmorphism
|
||||
|
||||
Every field below must appear in the final JSON output.
|
||||
|
||||
## Top-Level Structure
|
||||
|
||||
### `meta`
|
||||
- `name`
|
||||
- `description`
|
||||
- `source_references`
|
||||
- `created_at`
|
||||
|
||||
### `design_system`
|
||||
The structural and measurable layer.
|
||||
|
||||
#### `design_system.color`
|
||||
- `palette_type`
|
||||
- `primary.hex`
|
||||
- `primary.role`
|
||||
- `secondary.hex`
|
||||
- `secondary.role`
|
||||
- `accent.hex`
|
||||
- `accent.role`
|
||||
- `neutral.scale`
|
||||
- `neutral.usage`
|
||||
- `semantic.success`
|
||||
- `semantic.warning`
|
||||
- `semantic.error`
|
||||
- `semantic.info`
|
||||
- `surface.background`
|
||||
- `surface.card`
|
||||
- `surface.elevated`
|
||||
- `contrast_strategy`
|
||||
|
||||
#### `design_system.typography`
|
||||
- `type_scale.display.size`
|
||||
- `type_scale.display.weight`
|
||||
- `type_scale.display.line_height`
|
||||
- `type_scale.display.tracking`
|
||||
- `type_scale.heading_1.size`
|
||||
- `type_scale.heading_1.weight`
|
||||
- `type_scale.heading_1.line_height`
|
||||
- `type_scale.heading_1.tracking`
|
||||
- `type_scale.heading_2.size`
|
||||
- `type_scale.heading_2.weight`
|
||||
- `type_scale.heading_2.line_height`
|
||||
- `type_scale.heading_2.tracking`
|
||||
- `type_scale.heading_3.size`
|
||||
- `type_scale.heading_3.weight`
|
||||
- `type_scale.heading_3.line_height`
|
||||
- `type_scale.heading_3.tracking`
|
||||
- `type_scale.body.size`
|
||||
- `type_scale.body.weight`
|
||||
- `type_scale.body.line_height`
|
||||
- `type_scale.body.tracking`
|
||||
- `type_scale.body_small.size`
|
||||
- `type_scale.body_small.weight`
|
||||
- `type_scale.body_small.line_height`
|
||||
- `type_scale.body_small.tracking`
|
||||
- `type_scale.caption.size`
|
||||
- `type_scale.caption.weight`
|
||||
- `type_scale.caption.line_height`
|
||||
- `type_scale.caption.tracking`
|
||||
- `type_scale.overline.size`
|
||||
- `type_scale.overline.weight`
|
||||
- `type_scale.overline.line_height`
|
||||
- `type_scale.overline.tracking`
|
||||
- `font_families.heading`
|
||||
- `font_families.body`
|
||||
- `font_families.mono`
|
||||
- `font_style_notes`
|
||||
|
||||
#### `design_system.spacing`
|
||||
- `base_unit`
|
||||
- `scale`
|
||||
- `content_density`
|
||||
- `section_rhythm`
|
||||
|
||||
#### `design_system.layout`
|
||||
- `grid_system`
|
||||
- `max_content_width`
|
||||
- `columns`
|
||||
- `gutter`
|
||||
- `breakpoints`
|
||||
- `alignment_tendency`
|
||||
|
||||
#### `design_system.shape`
|
||||
- `border_radius.small`
|
||||
- `border_radius.medium`
|
||||
- `border_radius.large`
|
||||
- `border_radius.pill`
|
||||
- `border_usage`
|
||||
- `divider_style`
|
||||
|
||||
#### `design_system.elevation`
|
||||
- `shadow_style`
|
||||
- `levels.low`
|
||||
- `levels.medium`
|
||||
- `levels.high`
|
||||
- `depth_cues`
|
||||
|
||||
#### `design_system.iconography`
|
||||
- `style`
|
||||
- `stroke_weight`
|
||||
- `size_scale`
|
||||
- `preferred_set`
|
||||
|
||||
#### `design_system.motion`
|
||||
- `easing`
|
||||
- `duration_scale.micro`
|
||||
- `duration_scale.normal`
|
||||
- `duration_scale.macro`
|
||||
- `entrance_pattern`
|
||||
- `exit_pattern`
|
||||
- `philosophy`
|
||||
|
||||
#### `design_system.components`
|
||||
- `button_style`
|
||||
- `input_style`
|
||||
- `card_style`
|
||||
- `navigation_pattern`
|
||||
- `modal_style`
|
||||
- `list_style`
|
||||
- `component_notes`
|
||||
|
||||
### `design_style`
|
||||
The qualitative and perceptual layer.
|
||||
|
||||
#### `design_style.aesthetic`
|
||||
- `mood`
|
||||
- `visual_metaphor`
|
||||
- `era_influence`
|
||||
- `genre`
|
||||
- `personality_traits`
|
||||
- `adjectives`
|
||||
|
||||
#### `design_style.visual_language`
|
||||
- `complexity`
|
||||
- `ornamentation`
|
||||
- `whitespace_usage`
|
||||
- `visual_weight_distribution`
|
||||
- `focal_strategy`
|
||||
- `contrast_level`
|
||||
- `texture_usage`
|
||||
|
||||
#### `design_style.composition`
|
||||
- `hierarchy_method`
|
||||
- `balance_type`
|
||||
- `flow_direction`
|
||||
- `grouping_strategy`
|
||||
- `negative_space_role`
|
||||
|
||||
#### `design_style.imagery`
|
||||
- `photo_treatment`
|
||||
- `illustration_style`
|
||||
- `graphic_elements`
|
||||
- `pattern_usage`
|
||||
- `image_shape`
|
||||
|
||||
#### `design_style.interaction_feel`
|
||||
- `feedback_style`
|
||||
- `hover_behavior`
|
||||
- `transition_personality`
|
||||
- `loading_style`
|
||||
- `microinteraction_density`
|
||||
|
||||
#### `design_style.brand_voice_in_ui`
|
||||
- `tone`
|
||||
- `formality`
|
||||
- `cta_style`
|
||||
- `empty_state_approach`
|
||||
- `error_tone`
|
||||
|
||||
### `visual_effects`
|
||||
The special rendering and advanced visual behavior layer.
|
||||
|
||||
#### `visual_effects.overview`
|
||||
- `effect_intensity`
|
||||
- `performance_tier`
|
||||
- `fallback_strategy`
|
||||
- `primary_technology`
|
||||
|
||||
#### `visual_effects.background_effects`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.color_palette`
|
||||
- `params.speed`
|
||||
- `params.density`
|
||||
- `params.opacity`
|
||||
- `params.blend_mode`
|
||||
|
||||
#### `visual_effects.particle_systems`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.count`
|
||||
- `params.shape`
|
||||
- `params.size_range`
|
||||
- `params.movement_pattern`
|
||||
- `params.color_behavior`
|
||||
- `params.interaction`
|
||||
- `params.spawn_area`
|
||||
|
||||
#### `visual_effects.3d_elements`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.renderer`
|
||||
- `params.lighting`
|
||||
- `params.camera`
|
||||
- `params.materials`
|
||||
- `params.geometry`
|
||||
- `params.post_processing`
|
||||
- `params.interaction_model`
|
||||
|
||||
#### `visual_effects.shader_effects`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.uniforms`
|
||||
- `params.vertex_manipulation`
|
||||
- `params.fragment_output`
|
||||
- `params.noise_type`
|
||||
- `params.distortion`
|
||||
|
||||
#### `visual_effects.scroll_effects.parallax`
|
||||
- `enabled`
|
||||
- `layers`
|
||||
- `depth_range`
|
||||
- `speed_curve`
|
||||
|
||||
#### `visual_effects.scroll_effects.scroll_triggered_animations`
|
||||
- `enabled`
|
||||
- `trigger_points`
|
||||
- `animation_type`
|
||||
- `scrub_behavior`
|
||||
|
||||
#### `visual_effects.scroll_effects.scroll_morphing`
|
||||
- `enabled`
|
||||
- `description`
|
||||
|
||||
#### `visual_effects.text_effects`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.split_strategy`
|
||||
- `params.animation_per_unit`
|
||||
- `params.stagger`
|
||||
- `params.effect_style`
|
||||
|
||||
#### `visual_effects.cursor_effects`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `params.shape`
|
||||
- `params.size`
|
||||
- `params.blend_mode`
|
||||
- `params.trail`
|
||||
- `params.interaction_zone`
|
||||
|
||||
#### `visual_effects.image_effects`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.filter_pipeline`
|
||||
- `params.hover_transform`
|
||||
- `params.reveal_animation`
|
||||
- `params.distortion_type`
|
||||
|
||||
#### `visual_effects.glassmorphism_neumorphism`
|
||||
- `enabled`
|
||||
- `style`
|
||||
- `params.blur_radius`
|
||||
- `params.transparency`
|
||||
- `params.border_treatment`
|
||||
- `params.shadow_type`
|
||||
- `params.light_source_angle`
|
||||
|
||||
#### `visual_effects.canvas_drawings`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `technology`
|
||||
- `params.draw_method`
|
||||
- `params.animation_loop`
|
||||
- `params.color_scheme`
|
||||
- `params.responsiveness`
|
||||
- `params.interaction`
|
||||
|
||||
#### `visual_effects.svg_animations`
|
||||
- `enabled`
|
||||
- `type`
|
||||
- `description`
|
||||
- `params.animation_method`
|
||||
- `params.path_morphing`
|
||||
- `params.stroke_animation`
|
||||
- `params.filter_effects`
|
||||
|
||||
#### `visual_effects.composite_notes`
|
||||
- Free-text notes for layered effects, implementation ambiguity, performance trade-offs, or screenshot-only observations
|
||||
|
||||
## Field Guidance
|
||||
|
||||
### `design_system` (Dimension 1: Structural / Measurable)
|
||||
Concrete, token-level values. Extract exact values where visible; estimate from visual inspection otherwise.
|
||||
|
||||
- **`color.palette_type`**: "monochromatic", "complementary", "analogous", "triadic", "split-complementary"
|
||||
- **`color.contrast_strategy`**: How text/background contrast is managed — "high contrast", "subtle layers", "dark-on-light dominant"
|
||||
- **`typography.font_style_notes`**: e.g. "geometric sans with humanist touches"
|
||||
- **`spacing.content_density`**: "compact", "comfortable", "spacious"
|
||||
- **`spacing.section_rhythm`**: How vertical spacing varies between sections
|
||||
- **`layout.alignment_tendency`**: "strict grid", "centered", "asymmetric", "mixed"
|
||||
- **`shape.border_usage`**: "none", "subtle 1px", "bold borders", "only on inputs"
|
||||
- **`elevation.shadow_style`**: "none", "soft diffused", "hard drop", "layered"
|
||||
- **`elevation.depth_cues`**: "shadows", "overlapping layers", "blur/glass", "color intensity"
|
||||
- **`motion.philosophy`**: "minimal functional", "playful bouncy", "cinematic", "none"
|
||||
- **`components`**: Describe observed patterns — e.g. "ghost buttons with thick borders, rounded inputs with inner shadow"
|
||||
|
||||
### `design_style` (Dimension 2: Qualitative / Perceptual)
|
||||
Subjective assessments. Use descriptive language.
|
||||
|
||||
- **`aesthetic.mood`**: Array of 3–5 mood words, e.g. ["calm", "professional", "warm"]
|
||||
- **`aesthetic.genre`**: e.g. "corporate SaaS", "indie creative", "luxury editorial", "neo-brutalist"
|
||||
- **`aesthetic.personality_traits`**: As if the design were a person, e.g. ["confident", "approachable", "meticulous"]
|
||||
- **`visual_language.complexity`**: "minimal", "moderate", "rich", "maximal"
|
||||
- **`visual_language.ornamentation`**: "none", "subtle accents", "decorative", "heavily ornamented"
|
||||
- **`visual_language.focal_strategy`**: "single hero element", "distributed interest", "progressive reveal"
|
||||
- **`composition.hierarchy_method`**: "scale contrast", "color weight", "spatial isolation", "typographic hierarchy"
|
||||
- **`composition.balance_type`**: "symmetric", "asymmetric", "radial", "mosaic"
|
||||
- **`interaction_feel.transition_personality`**: "snappy", "smooth glide", "bouncy elastic", "fade-subtle"
|
||||
- **`brand_voice_in_ui.cta_style`**: "direct imperative", "friendly invitation", "urgent scarcity", "subtle suggestion"
|
||||
|
||||
### `visual_effects` (Dimension 3: Special Rendering / Visual Wizardry)
|
||||
Effects beyond standard CSS. These often require Canvas, WebGL, SVG animation, shader programs, or JS animation libraries. When not directly observable from static code, describe them from screenshots or video.
|
||||
|
||||
- **`overview.effect_intensity`**: "none", "subtle-accent", "moderate", "heavy-immersive"
|
||||
- **`overview.performance_tier`**: "lightweight" (CSS + simple JS), "medium" (Canvas 2D, SVG anim), "heavy" (WebGL, Three.js, shaders)
|
||||
- **`overview.fallback_strategy`**: What happens on low-end devices — "disable effects", "reduce to CSS", "static snapshot"
|
||||
- **`overview.primary_technology`**: "CSS only", "Canvas 2D", "WebGL/Three.js", "GSAP", "Lottie", "SVG SMIL", "Pixi.js"
|
||||
- **`background_effects.type`**: "gradient-animation", "noise-field", "mesh-gradient", "video-bg", "generative-art", "none"
|
||||
- **`particle_systems.type`**: "floating-dots", "confetti", "snow", "fireflies", "connected-nodes", "custom"
|
||||
- **`particle_systems.params.interaction`**: "mouse-repel", "mouse-attract", "click-burst", "none"
|
||||
- **`3d_elements.type`**: "hero-model", "product-viewer", "scene-bg", "text-extrusion", "abstract-geometry"
|
||||
- **`3d_elements.params.post_processing`**: e.g. ["bloom", "FXAA", "depth-of-field", "chromatic-aberration"]
|
||||
- **`shader_effects.type`**: "noise-distortion", "wave", "morph", "color-shift", "custom-GLSL"
|
||||
- **`shader_effects.params.noise_type`**: "perlin", "simplex", "worley", "fbm"
|
||||
- **`scroll_effects.parallax.layers`**: Number of depth layers, e.g. "3"
|
||||
- **`scroll_effects.scroll_triggered_animations.animation_type`**: "fade-up", "scale-in", "clip-reveal", "counter", "draw-SVG"
|
||||
- **`text_effects.type`**: "split-letter-animate", "typewriter", "glitch", "gradient-fill", "3d-extrude", "none"
|
||||
- **`text_effects.params.split_strategy`**: "by-char", "by-word", "by-line"
|
||||
- **`cursor_effects.type`**: "custom-cursor", "magnetic-buttons", "spotlight", "trail", "none"
|
||||
- **`image_effects.type`**: "hover-distortion", "reveal-clip", "parallax-tilt", "rgb-shift", "none"
|
||||
- **`image_effects.params.distortion_type`**: "barrel", "wave", "liquid", "glitch"
|
||||
- **`glassmorphism_neumorphism.style`**: "glass", "neumorphic-light", "neumorphic-dark", "frosted-layers", "none"
|
||||
- **`canvas_drawings.type`**: "generative-lines", "interactive-blobs", "data-visualization", "pattern-fill", "none"
|
||||
- **`svg_animations.type`**: "path-draw", "morph-shapes", "logo-reveal", "decorative-loop", "none"
|
||||
- **`composite_notes`**: Free-text description of how multiple effects layer together, performance trade-offs, or effects visible only in screenshots that cannot be fully captured in structured fields
|
||||
@@ -0,0 +1,226 @@
|
||||
---
|
||||
name: design-taste-frontend
|
||||
description: Senior UI/UX Engineer. Architect digital interfaces overriding default LLM biases. Enforces metric-based rules, strict component architecture, CSS hardware acceleration, and balanced design engineering.
|
||||
---
|
||||
|
||||
# High-Agency Frontend Skill
|
||||
|
||||
## 1. ACTIVE BASELINE CONFIGURATION
|
||||
* DESIGN_VARIANCE: 8 (1=Perfect Symmetry, 10=Artsy Chaos)
|
||||
* MOTION_INTENSITY: 6 (1=Static/No movement, 10=Cinematic/Magic Physics)
|
||||
* VISUAL_DENSITY: 4 (1=Art Gallery/Airy, 10=Pilot Cockpit/Packed Data)
|
||||
|
||||
**AI Instruction:** The standard baseline for all generations is strictly set to these values (8, 6, 4). Do not ask the user to edit this file. Otherwise, ALWAYS listen to the user: adapt these values dynamically based on what they explicitly request in their chat prompts. Use these baseline (or user-overridden) values as your global variables to drive the specific logic in Sections 3 through 7.
|
||||
|
||||
## 2. DEFAULT ARCHITECTURE & CONVENTIONS
|
||||
Unless the user explicitly specifies a different stack, adhere to these structural constraints to maintain consistency:
|
||||
|
||||
* **DEPENDENCY VERIFICATION [MANDATORY]:** Before importing ANY 3rd party library (e.g. `framer-motion`, `lucide-react`, `zustand`), you MUST check `package.json`. If the package is missing, you MUST output the installation command (e.g. `npm install package-name`) before providing the code. **Never** assume a library exists.
|
||||
* **Framework & Interactivity:** React or Next.js. Default to Server Components (`RSC`).
|
||||
* **RSC SAFETY:** Global state works ONLY in Client Components. In Next.js, wrap providers in a `"use client"` component.
|
||||
* **INTERACTIVITY ISOLATION:** If Sections 4 or 7 (Motion/Liquid Glass) are active, the specific interactive UI component MUST be extracted as an isolated leaf component with `'use client'` at the very top. Server Components must exclusively render static layouts.
|
||||
* **State Management:** Use local `useState`/`useReducer` for isolated UI. Use global state strictly for deep prop-drilling avoidance.
|
||||
* **Styling Policy:** Use Tailwind CSS (v3/v4) for 90% of styling.
|
||||
* **TAILWIND VERSION LOCK:** Check `package.json` first. Do not use v4 syntax in v3 projects.
|
||||
* **T4 CONFIG GUARD:** For v4, do NOT use `tailwindcss` plugin in `postcss.config.js`. Use `@tailwindcss/postcss` or the Vite plugin.
|
||||
* **ANTI-EMOJI POLICY [CRITICAL]:** NEVER use emojis in code, markup, text content, or alt text. Replace symbols with high-quality icons (Radix, Phosphor) or clean SVG primitives. Emojis are BANNED.
|
||||
* **Responsiveness & Spacing:**
|
||||
* Standardize breakpoints (`sm`, `md`, `lg`, `xl`).
|
||||
* Contain page layouts using `max-w-[1400px] mx-auto` or `max-w-7xl`.
|
||||
* **Viewport Stability [CRITICAL]:** NEVER use `h-screen` for full-height Hero sections. ALWAYS use `min-h-[100dvh]` to prevent catastrophic layout jumping on mobile browsers (iOS Safari).
|
||||
* **Grid over Flex-Math:** NEVER use complex flexbox percentage math (`w-[calc(33%-1rem)]`). ALWAYS use CSS Grid (`grid grid-cols-1 md:grid-cols-3 gap-6`) for reliable structures.
|
||||
* **Icons:** You MUST use exactly `@phosphor-icons/react` or `@radix-ui/react-icons` as the import paths (check installed version). Standardize `strokeWidth` globally (e.g., exclusively use `1.5` or `2.0`).
|
||||
|
||||
|
||||
## 3. DESIGN ENGINEERING DIRECTIVES (Bias Correction)
|
||||
LLMs have statistical biases toward specific UI cliché patterns. Proactively construct premium interfaces using these engineered rules:
|
||||
|
||||
**Rule 1: Deterministic Typography**
|
||||
* **Display/Headlines:** Default to `text-4xl md:text-6xl tracking-tighter leading-none`.
|
||||
* **ANTI-SLOP:** Discourage `Inter` for "Premium" or "Creative" vibes. Force unique character using `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
|
||||
* **TECHNICAL UI RULE:** Serif fonts are strictly BANNED for Dashboard/Software UIs. For these contexts, use exclusively high-end Sans-Serif pairings (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`).
|
||||
* **Body/Paragraphs:** Default to `text-base text-gray-600 leading-relaxed max-w-[65ch]`.
|
||||
|
||||
**Rule 2: Color Calibration**
|
||||
* **Constraint:** Max 1 Accent Color. Saturation < 80%.
|
||||
* **THE LILA BAN:** The "AI Purple/Blue" aesthetic is strictly BANNED. No purple button glows, no neon gradients. Use absolute neutral bases (Zinc/Slate) with high-contrast, singular accents (e.g. Emerald, Electric Blue, or Deep Rose).
|
||||
* **COLOR CONSISTENCY:** Stick to one palette for the entire output. Do not fluctuate between warm and cool grays within the same project.
|
||||
|
||||
**Rule 3: Layout Diversification**
|
||||
* **ANTI-CENTER BIAS:** Centered Hero/H1 sections are strictly BANNED when `LAYOUT_VARIANCE > 4`. Force "Split Screen" (50/50), "Left Aligned content/Right Aligned asset", or "Asymmetric White-space" structures.
|
||||
|
||||
**Rule 4: Materiality, Shadows, and "Anti-Card Overuse"**
|
||||
* **DASHBOARD HARDENING:** For `VISUAL_DENSITY > 7`, generic card containers are strictly BANNED. Use logic-grouping via `border-t`, `divide-y`, or purely negative space. Data metrics should breathe without being boxed in unless elevation (z-index) is functionally required.
|
||||
* **Execution:** Use cards ONLY when elevation communicates hierarchy. When a shadow is used, tint it to the background hue.
|
||||
|
||||
**Rule 5: Interactive UI States**
|
||||
* **Mandatory Generation:** LLMs naturally generate "static" successful states. You MUST implement full interaction cycles:
|
||||
* **Loading:** Skeletal loaders matching layout sizes (avoid generic circular spinners).
|
||||
* **Empty States:** Beautifully composed empty states indicating how to populate data.
|
||||
* **Error States:** Clear, inline error reporting (e.g., forms).
|
||||
* **Tactile Feedback:** On `:active`, use `-translate-y-[1px]` or `scale-[0.98]` to simulate a physical push indicating success/action.
|
||||
|
||||
**Rule 6: Data & Form Patterns**
|
||||
* **Forms:** Label MUST sit above input. Helper text is optional but should exist in markup. Error text below input. Use a standard `gap-2` for input blocks.
|
||||
|
||||
## 4. CREATIVE PROACTIVITY (Anti-Slop Implementation)
|
||||
To actively combat generic AI designs, systematically implement these high-end coding concepts as your baseline:
|
||||
* **"Liquid Glass" Refraction:** When glassmorphism is needed, go beyond `backdrop-blur`. Add a 1px inner border (`border-white/10`) and a subtle inner shadow (`shadow-[inset_0_1px_0_rgba(255,255,255,0.1)]`) to simulate physical edge refraction.
|
||||
* **Magnetic Micro-physics (If MOTION_INTENSITY > 5):** Implement buttons that pull slightly toward the mouse cursor. **CRITICAL:** NEVER use React `useState` for magnetic hover or continuous animations. Use EXCLUSIVELY Framer Motion's `useMotionValue` and `useTransform` outside the React render cycle to prevent performance collapse on mobile.
|
||||
* **Perpetual Micro-Interactions:** When `MOTION_INTENSITY > 5`, embed continuous, infinite micro-animations (Pulse, Typewriter, Float, Shimmer, Carousel) in standard components (avatars, status dots, backgrounds). Apply premium Spring Physics (`type: "spring", stiffness: 100, damping: 20`) to all interactive elements—no linear easing.
|
||||
* **Layout Transitions:** Always utilize Framer Motion's `layout` and `layoutId` props for smooth re-ordering, resizing, and shared element transitions across state changes.
|
||||
* **Staggered Orchestration:** Do not mount lists or grids instantly. Use `staggerChildren` (Framer) or CSS cascade (`animation-delay: calc(var(--index) * 100ms)`) to create sequential waterfall reveals. **CRITICAL:** For `staggerChildren`, the Parent (`variants`) and Children MUST reside in the identical Client Component tree. If data is fetched asynchronously, pass the data as props into a centralized Parent Motion wrapper.
|
||||
|
||||
## 5. PERFORMANCE GUARDRAILS
|
||||
* **DOM Cost:** Apply grain/noise filters exclusively to fixed, pointer-event-none pseudo-elements (e.g., `fixed inset-0 z-50 pointer-events-none`) and NEVER to scrolling containers to prevent continuous GPU repaints and mobile performance degradation.
|
||||
* **Hardware Acceleration:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`.
|
||||
* **Z-Index Restraint:** NEVER spam arbitrary `z-50` or `z-10` unprompted. Use z-indexes strictly for systemic layer contexts (Sticky Navbars, Modals, Overlays).
|
||||
|
||||
## 6. TECHNICAL REFERENCE (Dial Definitions)
|
||||
|
||||
### DESIGN_VARIANCE (Level 1-10)
|
||||
* **1-3 (Predictable):** Flexbox `justify-center`, strict 12-column symmetrical grids, equal paddings.
|
||||
* **4-7 (Offset):** Use `margin-top: -2rem` overlapping, varied image aspect ratios (e.g., 4:3 next to 16:9), left-aligned headers over center-aligned data.
|
||||
* **8-10 (Asymmetric):** Masonry layouts, CSS Grid with fractional units (e.g., `grid-template-columns: 2fr 1fr 1fr`), massive empty zones (`padding-left: 20vw`).
|
||||
* **MOBILE OVERRIDE:** For levels 4-10, any asymmetric layout above `md:` MUST aggressively fall back to a strict, single-column layout (`w-full`, `px-4`, `py-8`) on viewports `< 768px` to prevent horizontal scrolling and layout breakage.
|
||||
|
||||
### MOTION_INTENSITY (Level 1-10)
|
||||
* **1-3 (Static):** No automatic animations. CSS `:hover` and `:active` states only.
|
||||
* **4-7 (Fluid CSS):** Use `transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1)`. Use `animation-delay` cascades for load-ins. Focus strictly on `transform` and `opacity`. Use `will-change: transform` sparingly.
|
||||
* **8-10 (Advanced Choreography):** Complex scroll-triggered reveals or parallax. Use Framer Motion hooks. NEVER use `window.addEventListener('scroll')`.
|
||||
|
||||
### VISUAL_DENSITY (Level 1-10)
|
||||
* **1-3 (Art Gallery Mode):** Lots of white space. Huge section gaps. Everything feels very expensive and clean.
|
||||
* **4-7 (Daily App Mode):** Normal spacing for standard web apps.
|
||||
* **8-10 (Cockpit Mode):** Tiny paddings. No card boxes; just 1px lines to separate data. Everything is packed. **Mandatory:** Use Monospace (`font-mono`) for all numbers.
|
||||
|
||||
## 7. AI TELLS (Forbidden Patterns)
|
||||
To guarantee a premium, non-generic output, you MUST strictly avoid these common AI design signatures unless explicitly requested:
|
||||
|
||||
### Visual & CSS
|
||||
* **NO Neon/Outer Glows:** Do not use default `box-shadow` glows or auto-glows. Use inner borders or subtle tinted shadows.
|
||||
* **NO Pure Black:** Never use `#000000`. Use Off-Black, Zinc-950, or Charcoal.
|
||||
* **NO Oversaturated Accents:** Desaturate accents to blend elegantly with neutrals.
|
||||
* **NO Excessive Gradient Text:** Do not use text-fill gradients for large headers.
|
||||
* **NO Custom Mouse Cursors:** They are outdated and ruin performance/accessibility.
|
||||
|
||||
### Typography
|
||||
* **NO Inter Font:** Banned. Use `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`.
|
||||
* **NO Oversized H1s:** The first heading should not scream. Control hierarchy with weight and color, not just massive scale.
|
||||
* **Serif Constraints:** Use Serif fonts ONLY for creative/editorial designs. **NEVER** use Serif on clean Dashboards.
|
||||
|
||||
### Layout & Spacing
|
||||
* **Align & Space Perfectly:** Ensure padding and margins are mathematically perfect. Avoid floating elements with awkward gaps.
|
||||
* **NO 3-Column Card Layouts:** The generic "3 equal cards horizontally" feature row is BANNED. Use a 2-column Zig-Zag, asymmetric grid, or horizontal scrolling approach instead.
|
||||
|
||||
### Content & Data (The "Jane Doe" Effect)
|
||||
* **NO Generic Names:** "John Doe", "Sarah Chan", or "Jack Su" are banned. Use highly creative, realistic-sounding names.
|
||||
* **NO Generic Avatars:** DO NOT use standard SVG "egg" or Lucide user icons for avatars. Use creative, believable photo placeholders or specific styling.
|
||||
* **NO Fake Numbers:** Avoid predictable outputs like `99.99%`, `50%`, or basic phone numbers (`1234567`). Use organic, messy data (`47.2%`, `+1 (312) 847-1928`).
|
||||
* **NO Startup Slop Names:** "Acme", "Nexus", "SmartFlow". Invent premium, contextual brand names.
|
||||
* **NO Filler Words:** Avoid AI copywriting clichés like "Elevate", "Seamless", "Unleash", or "Next-Gen". Use concrete verbs.
|
||||
|
||||
### External Resources & Components
|
||||
* **NO Broken Unsplash Links:** Do not use Unsplash. Use absolute, reliable placeholders like `https://picsum.photos/seed/{random_string}/800/600` or SVG UI Avatars.
|
||||
* **shadcn/ui Customization:** You may use `shadcn/ui`, but NEVER in its generic default state. You MUST customize the radii, colors, and shadows to match the high-end project aesthetic.
|
||||
* **Production-Ready Cleanliness:** Code must be extremely clean, visually striking, memorable, and meticulously refined in every detail.
|
||||
|
||||
## 8. THE CREATIVE ARSENAL (High-End Inspiration)
|
||||
Do not default to generic UI. Pull from this library of advanced concepts to ensure the output is visually striking and memorable. When appropriate, leverage **GSAP (ScrollTrigger/Parallax)** for complex scrolltelling or **ThreeJS/WebGL** for 3D/Canvas animations, rather than basic CSS motion. **CRITICAL:** Never mix GSAP/ThreeJS with Framer Motion in the same component tree. Default to Framer Motion for UI/Bento interactions. Use GSAP/ThreeJS EXCLUSIVELY for isolated full-page scrolltelling or canvas backgrounds, wrapped in strict useEffect cleanup blocks.
|
||||
|
||||
### The Standard Hero Paradigm
|
||||
* Stop doing centered text over a dark image. Try asymmetric Hero sections: Text cleanly aligned to the left or right. The background should feature a high-quality, relevant image with a subtle stylistic fade (darkening or lightening gracefully into the background color depending on if it is Light or Dark mode).
|
||||
|
||||
### Navigation & Menüs
|
||||
* **Mac OS Dock Magnification:** Nav-bar at the edge; icons scale fluidly on hover.
|
||||
* **Magnetic Button:** Buttons that physically pull toward the cursor.
|
||||
* **Gooey Menu:** Sub-items detach from the main button like a viscous liquid.
|
||||
* **Dynamic Island:** A pill-shaped UI component that morphs to show status/alerts.
|
||||
* **Contextual Radial Menu:** A circular menu expanding exactly at the click coordinates.
|
||||
* **Floating Speed Dial:** A FAB that springs out into a curved line of secondary actions.
|
||||
* **Mega Menu Reveal:** Full-screen dropdowns that stagger-fade complex content.
|
||||
|
||||
### Layout & Grids
|
||||
* **Bento Grid:** Asymmetric, tile-based grouping (e.g., Apple Control Center).
|
||||
* **Masonry Layout:** Staggered grid without fixed row heights (e.g., Pinterest).
|
||||
* **Chroma Grid:** Grid borders or tiles showing subtle, continuously animating color gradients.
|
||||
* **Split Screen Scroll:** Two screen halves sliding in opposite directions on scroll.
|
||||
* **Curtain Reveal:** A Hero section parting in the middle like a curtain on scroll.
|
||||
|
||||
### Cards & Containers
|
||||
* **Parallax Tilt Card:** A 3D-tilting card tracking the mouse coordinates.
|
||||
* **Spotlight Border Card:** Card borders that illuminate dynamically under the cursor.
|
||||
* **Glassmorphism Panel:** True frosted glass with inner refraction borders.
|
||||
* **Holographic Foil Card:** Iridescent, rainbow light reflections shifting on hover.
|
||||
* **Tinder Swipe Stack:** A physical stack of cards the user can swipe away.
|
||||
* **Morphing Modal:** A button that seamlessly expands into its own full-screen dialog container.
|
||||
|
||||
### Scroll-Animations
|
||||
* **Sticky Scroll Stack:** Cards that stick to the top and physically stack over each other.
|
||||
* **Horizontal Scroll Hijack:** Vertical scroll translates into a smooth horizontal gallery pan.
|
||||
* **Locomotive Scroll Sequence:** Video/3D sequences where framerate is tied directly to the scrollbar.
|
||||
* **Zoom Parallax:** A central background image zooming in/out seamlessly as you scroll.
|
||||
* **Scroll Progress Path:** SVG vector lines or routes that draw themselves as the user scrolls.
|
||||
* **Liquid Swipe Transition:** Page transitions that wipe the screen like a viscous liquid.
|
||||
|
||||
### Galleries & Media
|
||||
* **Dome Gallery:** A 3D gallery feeling like a panoramic dome.
|
||||
* **Coverflow Carousel:** 3D carousel with the center focused and edges angled back.
|
||||
* **Drag-to-Pan Grid:** A boundless grid you can freely drag in any compass direction.
|
||||
* **Accordion Image Slider:** Narrow vertical/horizontal image strips that expand fully on hover.
|
||||
* **Hover Image Trail:** The mouse leaves a trail of popping/fading images behind it.
|
||||
* **Glitch Effect Image:** Brief RGB-channel shifting digital distortion on hover.
|
||||
|
||||
### Typography & Text
|
||||
* **Kinetic Marquee:** Endless text bands that reverse direction or speed up on scroll.
|
||||
* **Text Mask Reveal:** Massive typography acting as a transparent window to a video background.
|
||||
* **Text Scramble Effect:** Matrix-style character decoding on load or hover.
|
||||
* **Circular Text Path:** Text curved along a spinning circular path.
|
||||
* **Gradient Stroke Animation:** Outlined text with a gradient continuously running along the stroke.
|
||||
* **Kinetic Typography Grid:** A grid of letters dodging or rotating away from the cursor.
|
||||
|
||||
### Micro-Interactions & Effects
|
||||
* **Particle Explosion Button:** CTAs that shatter into particles upon success.
|
||||
* **Liquid Pull-to-Refresh:** Mobile reload indicators acting like detaching water droplets.
|
||||
* **Skeleton Shimmer:** Shifting light reflections moving across placeholder boxes.
|
||||
* **Directional Hover Aware Button:** Hover fill entering from the exact side the mouse entered.
|
||||
* **Ripple Click Effect:** Visual waves rippling precisely from the click coordinates.
|
||||
* **Animated SVG Line Drawing:** Vectors that draw their own contours in real-time.
|
||||
* **Mesh Gradient Background:** Organic, lava-lamp-like animated color blobs.
|
||||
* **Lens Blur Depth:** Dynamic focus blurring background UI layers to highlight a foreground action.
|
||||
|
||||
## 9. THE "MOTION-ENGINE" BENTO PARADIGM
|
||||
When generating modern SaaS dashboards or feature sections, you MUST utilize the following "Bento 2.0" architecture and motion philosophy. This goes beyond static cards and enforces a "Vercel-core meets Dribbble-clean" aesthetic heavily reliant on perpetual physics.
|
||||
|
||||
### A. Core Design Philosophy
|
||||
* **Aesthetic:** High-end, minimal, and functional.
|
||||
* **Palette:** Background in `#f9fafb`. Cards are pure white (`#ffffff`) with a 1px border of `border-slate-200/50`.
|
||||
* **Surfaces:** Use `rounded-[2.5rem]` for all major containers. Apply a "diffusion shadow" (a very light, wide-spreading shadow, e.g., `shadow-[0_20px_40px_-15px_rgba(0,0,0,0.05)]`) to create depth without clutter.
|
||||
* **Typography:** Strict `Geist`, `Satoshi`, or `Cabinet Grotesk` font stack. Use subtle tracking (`tracking-tight`) for headers.
|
||||
* **Labels:** Titles and descriptions must be placed **outside and below** the cards to maintain a clean, gallery-style presentation.
|
||||
* **Pixel-Perfection:** Use generous `p-8` or `p-10` padding inside cards.
|
||||
|
||||
### B. The Animation Engine Specs (Perpetual Motion)
|
||||
All cards must contain **"Perpetual Micro-Interactions."** Use the following Framer Motion principles:
|
||||
* **Spring Physics:** No linear easing. Use `type: "spring", stiffness: 100, damping: 20` for a premium, weighty feel.
|
||||
* **Layout Transitions:** Heavily utilize the `layout` and `layoutId` props to ensure smooth re-ordering, resizing, and shared element state transitions.
|
||||
* **Infinite Loops:** Every card must have an "Active State" that loops infinitely (Pulse, Typewriter, Float, or Carousel) to ensure the dashboard feels "alive".
|
||||
* **Performance:** Wrap dynamic lists in `<AnimatePresence>` and optimize for 60fps. **PERFORMANCE CRITICAL:** Any perpetual motion or infinite loop MUST be memoized (React.memo) and completely isolated in its own microscopic Client Component. Never trigger re-renders in the parent layout.
|
||||
|
||||
### C. The 5-Card Archetypes (Micro-Animation Specs)
|
||||
Implement these specific micro-animations when constructing Bento grids (e.g., Row 1: 3 cols | Row 2: 2 cols split 70/30):
|
||||
1. **The Intelligent List:** A vertical stack of items with an infinite auto-sorting loop. Items swap positions using `layoutId`, simulating an AI prioritizing tasks in real-time.
|
||||
2. **The Command Input:** A search/AI bar with a multi-step Typewriter Effect. It cycles through complex prompts, including a blinking cursor and a "processing" state with a shimmering loading gradient.
|
||||
3. **The Live Status:** A scheduling interface with "breathing" status indicators. Include a pop-up notification badge that emerges with an "Overshoot" spring effect, stays for 3 seconds, and vanishes.
|
||||
4. **The Wide Data Stream:** A horizontal "Infinite Carousel" of data cards or metrics. Ensure the loop is seamless (using `x: ["0%", "-100%"]`) with a speed that feels effortless.
|
||||
5. **The Contextual UI (Focus Mode):** A document view that animates a staggered highlight of a text block, followed by a "Float-in" of a floating action toolbar with micro-icons.
|
||||
|
||||
## 10. FINAL PRE-FLIGHT CHECK
|
||||
Evaluate your code against this matrix before outputting. This is the **last** filter you apply to your logic.
|
||||
- [ ] Is global state used appropriately to avoid deep prop-drilling rather than arbitrarily?
|
||||
- [ ] Is mobile layout collapse (`w-full`, `px-4`, `max-w-7xl mx-auto`) guaranteed for high-variance designs?
|
||||
- [ ] Do full-height sections safely use `min-h-[100dvh]` instead of the bugged `h-screen`?
|
||||
- [ ] Do `useEffect` animations contain strict cleanup functions?
|
||||
- [ ] Are empty, loading, and error states provided?
|
||||
- [ ] Are cards omitted in favor of spacing where possible?
|
||||
- [ ] Did you strictly isolate CPU-heavy perpetual animations in their own Client Components?
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: frontend-design
|
||||
description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.
|
||||
|
||||
The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints.
|
||||
|
||||
## Design Thinking
|
||||
|
||||
Before coding, understand the context and commit to a BOLD aesthetic direction:
|
||||
- **Purpose**: What problem does this interface solve? Who uses it?
|
||||
- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction.
|
||||
- **Constraints**: Technical requirements (framework, performance, accessibility).
|
||||
- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember?
|
||||
|
||||
**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity.
|
||||
|
||||
Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:
|
||||
- Production-grade and functional
|
||||
- Visually striking and memorable
|
||||
- Cohesive with a clear aesthetic point-of-view
|
||||
- Meticulously refined in every detail
|
||||
|
||||
## Frontend Aesthetics Guidelines
|
||||
|
||||
Focus on:
|
||||
- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font.
|
||||
- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
|
||||
- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise.
|
||||
- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
|
||||
- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.
|
||||
|
||||
NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character.
|
||||
|
||||
Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.
|
||||
|
||||
**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
|
||||
|
||||
Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
name: high-end-visual-design
|
||||
description: Teaches the AI to design like a high-end agency. Defines the exact fonts, spacing, shadows, card structures, and animations that make a website feel expensive. Blocks all the common defaults that make AI designs look cheap or generic.
|
||||
---
|
||||
|
||||
# Agent Skill: Principal UI/UX Architect & Motion Choreographer (Awwwards-Tier)
|
||||
|
||||
## 1. Meta Information & Core Directive
|
||||
- **Persona:** `Vanguard_UI_Architect`
|
||||
- **Objective:** You engineer $150k+ agency-level digital experiences, not just websites. Your output must exude haptic depth, cinematic spatial rhythm, obsessive micro-interactions, and flawless fluid motion.
|
||||
- **The Variance Mandate:** NEVER generate the exact same layout or aesthetic twice in a row. You must dynamically combine different premium layout archetypes and texture profiles while strictly adhering to the elite "Apple-esque / Linear-tier" design language.
|
||||
|
||||
## 2. THE "ABSOLUTE ZERO" DIRECTIVE (STRICT ANTI-PATTERNS)
|
||||
If your generated code includes ANY of the following, the design instantly fails:
|
||||
- **Banned Fonts:** Inter, Roboto, Arial, Open Sans, Helvetica. (Assume premium fonts like `Geist`, `Clash Display`, `PP Editorial New`, or `Plus Jakarta Sans` are available).
|
||||
- **Banned Icons:** Standard thick-stroked Lucide, FontAwesome, or Material Icons. Use only ultra-light, precise lines (e.g., Phosphor Light, Remix Line).
|
||||
- **Banned Borders & Shadows:** Generic 1px solid gray borders. Harsh, dark drop shadows (`shadow-md`, `rgba(0,0,0,0.3)`).
|
||||
- **Banned Layouts:** Edge-to-edge sticky navbars glued to the top. Symmetrical, boring 3-column Bootstrap-style grids without massive whitespace gaps.
|
||||
- **Banned Motion:** Standard `linear` or `ease-in-out` transitions. Instant state changes without interpolation.
|
||||
|
||||
## 3. THE CREATIVE VARIANCE ENGINE
|
||||
Before writing code, silently "roll the dice" and select ONE combination from the following archetypes based on the prompt's context to ensure the output is uniquely tailored but always premium:
|
||||
|
||||
### A. Vibe & Texture Archetypes (Pick 1)
|
||||
1. **Ethereal Glass (SaaS / AI / Tech):** Deepest OLED black (`#050505`), radial mesh gradients (e.g., subtle glowing purple/emerald orbs) in the background. Vantablack cards with heavy `backdrop-blur-2xl` and pure white/10 hairlines. Wide geometric Grotesk typography.
|
||||
2. **Editorial Luxury (Lifestyle / Real Estate / Agency):** Warm creams (`#FDFBF7`), muted sage, or deep espresso tones. High-contrast Variable Serif fonts for massive headings. Subtle CSS noise/film-grain overlay (`opacity-[0.03]`) for a physical paper feel.
|
||||
3. **Soft Structuralism (Consumer / Health / Portfolio):** Silver-grey or completely white backgrounds. Massive bold Grotesk typography. Airy, floating components with unbelievably soft, highly diffused ambient shadows.
|
||||
|
||||
### B. Layout Archetypes (Pick 1)
|
||||
1. **The Asymmetrical Bento:** A masonry-like CSS Grid of varying card sizes (e.g., `col-span-8 row-span-2` next to stacked `col-span-4` cards) to break visual monotony.
|
||||
- **Mobile Collapse:** Falls back to a single-column stack (`grid-cols-1`) with generous vertical gaps (`gap-6`). All `col-span` overrides reset to `col-span-1`.
|
||||
2. **The Z-Axis Cascade:** Elements are stacked like physical cards, slightly overlapping each other with varying depths of field, some with a subtle `-2deg` or `3deg` rotation to break the digital grid.
|
||||
- **Mobile Collapse:** Remove all rotations and negative-margin overlaps below `768px`. Stack vertically with standard spacing. Overlapping elements cause touch-target conflicts on mobile.
|
||||
3. **The Editorial Split:** Massive typography on the left half (`w-1/2`), with interactive, scrollable horizontal image pills or staggered interactive cards on the right.
|
||||
- **Mobile Collapse:** Converts to a full-width vertical stack (`w-full`). Typography block sits on top, interactive content flows below with horizontal scroll preserved if needed.
|
||||
|
||||
**Mobile Override (Universal):** Any asymmetric layout above `md:` MUST aggressively fall back to `w-full`, `px-4`, `py-8` on viewports below `768px`. Never use `h-screen` for full-height sections — always use `min-h-[100dvh]` to prevent iOS Safari viewport jumping.
|
||||
|
||||
## 4. HAPTIC MICRO-AESTHETICS (COMPONENT MASTERY)
|
||||
|
||||
### A. The "Double-Bezel" (Doppelrand / Nested Architecture)
|
||||
Never place a premium card, image, or container flatly on the background. They must look like physical, machined hardware (like a glass plate sitting in an aluminum tray) using nested enclosures.
|
||||
- **Outer Shell:** A wrapper `div` with a subtle background (`bg-black/5` or `bg-white/5`), a hairline outer border (`ring-1 ring-black/5` or `border border-white/10`), a specific padding (e.g., `p-1.5` or `p-2`), and a large outer radius (`rounded-[2rem]`).
|
||||
- **Inner Core:** The actual content container inside the shell. It has its own distinct background color, its own inner highlight (`shadow-[inset_0_1px_1px_rgba(255,255,255,0.15)]`), and a mathematically calculated smaller radius (e.g., `rounded-[calc(2rem-0.375rem)]`) for concentric curves.
|
||||
|
||||
### B. Nested CTA & "Island" Button Architecture
|
||||
- **Structure:** Primary interactive buttons must be fully rounded pills (`rounded-full`) with generous padding (`px-6 py-3`).
|
||||
- **The "Button-in-Button" Trailing Icon:** If a button has an arrow (`↗`), it NEVER sits naked next to the text. It must be nested inside its own distinct circular wrapper (e.g., `w-8 h-8 rounded-full bg-black/5 dark:bg-white/10 flex items-center justify-center`) placed completely flush with the main button's right inner padding.
|
||||
|
||||
### C. Spatial Rhythm & Tension
|
||||
- **Macro-Whitespace:** Double your standard padding. Use `py-24` to `py-40` for sections. Allow the design to breathe heavily.
|
||||
- **Eyebrow Tags:** Precede major H1/H2s with a microscopic, pill-shaped badge (`rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.2em] font-medium`).
|
||||
|
||||
## 5. MOTION CHOREOGRAPHY (FLUID DYNAMICS)
|
||||
Never use default transitions. All motion must simulate real-world mass and spring physics. Use custom cubic-beziers (e.g., `transition-all duration-700 ease-[cubic-bezier(0.32,0.72,0,1)]`).
|
||||
|
||||
### A. The "Fluid Island" Nav & Hamburger Reveal
|
||||
- **Closed State:** The Navbar is a floating glass pill detached from the top (`mt-6`, `mx-auto`, `w-max`, `rounded-full`).
|
||||
- **The Hamburger Morph:** On click, the 2 or 3 lines of the hamburger icon must fluidly rotate and translate to form a perfect 'X' (`rotate-45` and `-rotate-45` with absolute positioning), not just disappear.
|
||||
- **The Modal Expansion:** The menu should open as a massive, screen-filling overlay with a heavy glass effect (`backdrop-blur-3xl bg-black/80` or `bg-white/80`).
|
||||
- **Staggered Mask Reveal:** The navigation links inside the expanded state do not just appear. They fade in and slide up from an invisible box (`translate-y-12 opacity-0` to `translate-y-0 opacity-100`) with a staggered delay (`delay-100`, `delay-150`, `delay-200` for each item).
|
||||
|
||||
### B. Magnetic Button Hover Physics
|
||||
- Use the `group` utility. On hover, do not just change the background color.
|
||||
- Scale the entire button down slightly (`active:scale-[0.98]`) to simulate physical pressing.
|
||||
- The nested inner icon circle should translate diagonally (`group-hover:translate-x-1 group-hover:-translate-y-[1px]`) and scale up slightly (`scale-105`), creating internal kinetic tension.
|
||||
|
||||
### C. Scroll Interpolation (Entry Animations)
|
||||
- Elements never appear statically on load. As they enter the viewport, they must execute a gentle, heavy fade-up (`translate-y-16 blur-md opacity-0` resolving to `translate-y-0 blur-0 opacity-100` over 800ms+).
|
||||
- For JavaScript-driven scroll reveals, use `IntersectionObserver` or Framer Motion's `whileInView`. Never use `window.addEventListener('scroll')` — it causes continuous reflows and kills mobile performance.
|
||||
|
||||
## 6. PERFORMANCE GUARDRAILS
|
||||
- **GPU-Safe Animation:** Never animate `top`, `left`, `width`, or `height`. Animate exclusively via `transform` and `opacity`. Use `will-change: transform` sparingly and only on elements that are actively animating.
|
||||
- **Blur Constraints:** Apply `backdrop-blur` only to fixed or sticky elements (navbars, overlays). Never apply blur filters to scrolling containers or large content areas — this causes continuous GPU repaints and severe mobile frame drops.
|
||||
- **Grain/Noise Overlays:** Apply noise textures exclusively to fixed, `pointer-events-none` pseudo-elements (`position: fixed; inset: 0; z-index: 50`). Never attach them to scrolling containers.
|
||||
- **Z-Index Discipline:** Do not use arbitrary `z-50` or `z-[9999]`. Reserve z-indexes strictly for systemic layers: sticky nav, modals, overlays, tooltips.
|
||||
|
||||
## 7. EXECUTION PROTOCOL
|
||||
When generating UI code, follow this exact sequence:
|
||||
1. **[SILENT THOUGHT]** Roll the Variance Engine (Section 3). Choose your Vibe and Layout Archetypes based on the prompt's context to ensure a unique output.
|
||||
2. **[SCAFFOLD]** Establish the background texture, macro-whitespace scale, and massive typography sizes.
|
||||
3. **[ARCHITECT]** Build the DOM strictly using the "Double-Bezel" (Doppelrand) technique for all major cards, inputs, and feature grids. Use exaggerated squircle radii (`rounded-[2rem]`).
|
||||
4. **[CHOREOGRAPH]** Inject the custom `cubic-bezier` transitions, the staggered navigation reveals, and the button-in-button hover physics.
|
||||
5. **[OUTPUT]** Deliver flawless, pixel-perfect React/Tailwind/HTML code. Do not include basic, generic fallbacks.
|
||||
|
||||
## 8. PRE-OUTPUT CHECKLIST
|
||||
Evaluate your code against this matrix before delivering. This is the last filter.
|
||||
- [ ] No banned fonts, icons, borders, shadows, layouts, or motion patterns from Section 2 are present
|
||||
- [ ] A Vibe Archetype and Layout Archetype from Section 3 were consciously selected and applied
|
||||
- [ ] All major cards and containers use the Double-Bezel nested architecture (outer shell + inner core)
|
||||
- [ ] CTA buttons use the Button-in-Button trailing icon pattern where applicable
|
||||
- [ ] Section padding is at minimum `py-24` — the layout breathes heavily
|
||||
- [ ] All transitions use custom cubic-bezier curves — no `linear` or `ease-in-out`
|
||||
- [ ] Scroll entry animations are present — no element appears statically
|
||||
- [ ] Layout collapses gracefully below `768px` to single-column with `w-full` and `px-4`
|
||||
- [ ] All animations use only `transform` and `opacity` — no layout-triggering properties
|
||||
- [ ] `backdrop-blur` is only applied to fixed/sticky elements, never to scrolling content
|
||||
- [ ] The overall impression reads as "$150k agency build", not "template with nice fonts"
|
||||
@@ -0,0 +1,473 @@
|
||||
---
|
||||
name: "senior-frontend"
|
||||
description: Frontend development skill for React, Next.js, TypeScript, and Tailwind CSS applications. Use when building React components, optimizing Next.js performance, analyzing bundle sizes, scaffolding frontend projects, implementing accessibility, or reviewing frontend code quality.
|
||||
---
|
||||
|
||||
# Senior Frontend
|
||||
|
||||
Frontend development patterns, performance optimization, and automation tools for React/Next.js applications.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Project Scaffolding](#project-scaffolding)
|
||||
- [Component Generation](#component-generation)
|
||||
- [Bundle Analysis](#bundle-analysis)
|
||||
- [React Patterns](#react-patterns)
|
||||
- [Next.js Optimization](#nextjs-optimization)
|
||||
- [Accessibility and Testing](#accessibility-and-testing)
|
||||
|
||||
---
|
||||
|
||||
## Project Scaffolding
|
||||
|
||||
Generate a new Next.js or React project with TypeScript, Tailwind CSS, and best practice configurations.
|
||||
|
||||
### Workflow: Create New Frontend Project
|
||||
|
||||
1. Run the scaffolder with your project name and template:
|
||||
```bash
|
||||
python scripts/frontend_scaffolder.py my-app --template nextjs
|
||||
```
|
||||
|
||||
2. Add optional features (auth, api, forms, testing, storybook):
|
||||
```bash
|
||||
python scripts/frontend_scaffolder.py dashboard --template nextjs --features auth,api
|
||||
```
|
||||
|
||||
3. Navigate to the project and install dependencies:
|
||||
```bash
|
||||
cd my-app && npm install
|
||||
```
|
||||
|
||||
4. Start the development server:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Scaffolder Options
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| `--template nextjs` | Next.js 14+ with App Router and Server Components |
|
||||
| `--template react` | React + Vite with TypeScript |
|
||||
| `--features auth` | Add NextAuth.js authentication |
|
||||
| `--features api` | Add React Query + API client |
|
||||
| `--features forms` | Add React Hook Form + Zod validation |
|
||||
| `--features testing` | Add Vitest + Testing Library |
|
||||
| `--dry-run` | Preview files without creating them |
|
||||
|
||||
### Generated Structure (Next.js)
|
||||
|
||||
```
|
||||
my-app/
|
||||
├── app/
|
||||
│ ├── layout.tsx # Root layout with fonts
|
||||
│ ├── page.tsx # Home page
|
||||
│ ├── globals.css # Tailwind + CSS variables
|
||||
│ └── api/health/route.ts
|
||||
├── components/
|
||||
│ ├── ui/ # Button, Input, Card
|
||||
│ └── layout/ # Header, Footer, Sidebar
|
||||
├── hooks/ # useDebounce, useLocalStorage
|
||||
├── lib/ # utils (cn), constants
|
||||
├── types/ # TypeScript interfaces
|
||||
├── tailwind.config.ts
|
||||
├── next.config.js
|
||||
└── package.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Component Generation
|
||||
|
||||
Generate React components with TypeScript, tests, and Storybook stories.
|
||||
|
||||
### Workflow: Create a New Component
|
||||
|
||||
1. Generate a client component:
|
||||
```bash
|
||||
python scripts/component_generator.py Button --dir src/components/ui
|
||||
```
|
||||
|
||||
2. Generate a server component:
|
||||
```bash
|
||||
python scripts/component_generator.py ProductCard --type server
|
||||
```
|
||||
|
||||
3. Generate with test and story files:
|
||||
```bash
|
||||
python scripts/component_generator.py UserProfile --with-test --with-story
|
||||
```
|
||||
|
||||
4. Generate a custom hook:
|
||||
```bash
|
||||
python scripts/component_generator.py FormValidation --type hook
|
||||
```
|
||||
|
||||
### Generator Options
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| `--type client` | Client component with 'use client' (default) |
|
||||
| `--type server` | Async server component |
|
||||
| `--type hook` | Custom React hook |
|
||||
| `--with-test` | Include test file |
|
||||
| `--with-story` | Include Storybook story |
|
||||
| `--flat` | Create in output dir without subdirectory |
|
||||
| `--dry-run` | Preview without creating files |
|
||||
|
||||
### Generated Component Example
|
||||
|
||||
```tsx
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ButtonProps {
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Button({ className, children }: ButtonProps) {
|
||||
return (
|
||||
<div className={cn('', className)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Bundle Analysis
|
||||
|
||||
Analyze package.json and project structure for bundle optimization opportunities.
|
||||
|
||||
### Workflow: Optimize Bundle Size
|
||||
|
||||
1. Run the analyzer on your project:
|
||||
```bash
|
||||
python scripts/bundle_analyzer.py /path/to/project
|
||||
```
|
||||
|
||||
2. Review the health score and issues:
|
||||
```
|
||||
Bundle Health Score: 75/100 (C)
|
||||
|
||||
HEAVY DEPENDENCIES:
|
||||
moment (290KB)
|
||||
Alternative: date-fns (12KB) or dayjs (2KB)
|
||||
|
||||
lodash (71KB)
|
||||
Alternative: lodash-es with tree-shaking
|
||||
```
|
||||
|
||||
3. Apply the recommended fixes by replacing heavy dependencies.
|
||||
|
||||
4. Re-run with verbose mode to check import patterns:
|
||||
```bash
|
||||
python scripts/bundle_analyzer.py . --verbose
|
||||
```
|
||||
|
||||
### Bundle Score Interpretation
|
||||
|
||||
| Score | Grade | Action |
|
||||
|-------|-------|--------|
|
||||
| 90-100 | A | Bundle is well-optimized |
|
||||
| 80-89 | B | Minor optimizations available |
|
||||
| 70-79 | C | Replace heavy dependencies |
|
||||
| 60-69 | D | Multiple issues need attention |
|
||||
| 0-59 | F | Critical bundle size problems |
|
||||
|
||||
### Heavy Dependencies Detected
|
||||
|
||||
The analyzer identifies these common heavy packages:
|
||||
|
||||
| Package | Size | Alternative |
|
||||
|---------|------|-------------|
|
||||
| moment | 290KB | date-fns (12KB) or dayjs (2KB) |
|
||||
| lodash | 71KB | lodash-es with tree-shaking |
|
||||
| axios | 14KB | Native fetch or ky (3KB) |
|
||||
| jquery | 87KB | Native DOM APIs |
|
||||
| @mui/material | Large | shadcn/ui or Radix UI |
|
||||
|
||||
---
|
||||
|
||||
## React Patterns
|
||||
|
||||
Reference: `references/react_patterns.md`
|
||||
|
||||
### Compound Components
|
||||
|
||||
Share state between related components:
|
||||
|
||||
```tsx
|
||||
const Tabs = ({ children }) => {
|
||||
const [active, setActive] = useState(0);
|
||||
return (
|
||||
<TabsContext.Provider value={{ active, setActive }}>
|
||||
{children}
|
||||
</TabsContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
Tabs.List = TabList;
|
||||
Tabs.Panel = TabPanel;
|
||||
|
||||
// Usage
|
||||
<Tabs>
|
||||
<Tabs.List>
|
||||
<Tabs.Tab>One</Tabs.Tab>
|
||||
<Tabs.Tab>Two</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
<Tabs.Panel>Content 1</Tabs.Panel>
|
||||
<Tabs.Panel>Content 2</Tabs.Panel>
|
||||
</Tabs>
|
||||
```
|
||||
|
||||
### Custom Hooks
|
||||
|
||||
Extract reusable logic:
|
||||
|
||||
```tsx
|
||||
function useDebounce<T>(value: T, delay = 500): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedValue(value), delay);
|
||||
return () => clearTimeout(timer);
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
|
||||
// Usage
|
||||
const debouncedSearch = useDebounce(searchTerm, 300);
|
||||
```
|
||||
|
||||
### Render Props
|
||||
|
||||
Share rendering logic:
|
||||
|
||||
```tsx
|
||||
function DataFetcher({ url, render }) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
|
||||
}, [url]);
|
||||
|
||||
return render({ data, loading });
|
||||
}
|
||||
|
||||
// Usage
|
||||
<DataFetcher
|
||||
url="/api/users"
|
||||
render={({ data, loading }) =>
|
||||
loading ? <Spinner /> : <UserList users={data} />
|
||||
}
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Next.js Optimization
|
||||
|
||||
Reference: `references/nextjs_optimization_guide.md`
|
||||
|
||||
### Server vs Client Components
|
||||
|
||||
Use Server Components by default. Add 'use client' only when you need:
|
||||
- Event handlers (onClick, onChange)
|
||||
- State (useState, useReducer)
|
||||
- Effects (useEffect)
|
||||
- Browser APIs
|
||||
|
||||
```tsx
|
||||
// Server Component (default) - no 'use client'
|
||||
async function ProductPage({ params }) {
|
||||
const product = await getProduct(params.id); // Server-side fetch
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{product.name}</h1>
|
||||
<AddToCartButton productId={product.id} /> {/* Client component */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Client Component
|
||||
'use client';
|
||||
function AddToCartButton({ productId }) {
|
||||
const [adding, setAdding] = useState(false);
|
||||
return <button onClick={() => addToCart(productId)}>Add</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Image Optimization
|
||||
|
||||
```tsx
|
||||
import Image from 'next/image';
|
||||
|
||||
// Above the fold - load immediately
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
width={1200}
|
||||
height={600}
|
||||
priority
|
||||
/>
|
||||
|
||||
// Responsive image with fill
|
||||
<div className="relative aspect-video">
|
||||
<Image
|
||||
src="/product.jpg"
|
||||
alt="Product"
|
||||
fill
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Data Fetching Patterns
|
||||
|
||||
```tsx
|
||||
// Parallel fetching
|
||||
async function Dashboard() {
|
||||
const [user, stats] = await Promise.all([
|
||||
getUser(),
|
||||
getStats()
|
||||
]);
|
||||
return <div>...</div>;
|
||||
}
|
||||
|
||||
// Streaming with Suspense
|
||||
async function ProductPage({ params }) {
|
||||
return (
|
||||
<div>
|
||||
<ProductDetails id={params.id} />
|
||||
<Suspense fallback={<ReviewsSkeleton />}>
|
||||
<Reviews productId={params.id} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Accessibility and Testing
|
||||
|
||||
Reference: `references/frontend_best_practices.md`
|
||||
|
||||
### Accessibility Checklist
|
||||
|
||||
1. **Semantic HTML**: Use proper elements (`<button>`, `<nav>`, `<main>`)
|
||||
2. **Keyboard Navigation**: All interactive elements focusable
|
||||
3. **ARIA Labels**: Provide labels for icons and complex widgets
|
||||
4. **Color Contrast**: Minimum 4.5:1 for normal text
|
||||
5. **Focus Indicators**: Visible focus states
|
||||
|
||||
```tsx
|
||||
// Accessible button
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Close dialog"
|
||||
onClick={onClose}
|
||||
className="focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<XIcon aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
// Skip link for keyboard users
|
||||
<a href="#main-content" className="sr-only focus:not-sr-only">
|
||||
Skip to main content
|
||||
</a>
|
||||
```
|
||||
|
||||
### Testing Strategy
|
||||
|
||||
```tsx
|
||||
// Component test with React Testing Library
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
test('button triggers action on click', async () => {
|
||||
const onClick = vi.fn();
|
||||
render(<Button onClick={onClick}>Click me</Button>);
|
||||
|
||||
await userEvent.click(screen.getByRole('button'));
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Test accessibility
|
||||
test('dialog is accessible', async () => {
|
||||
render(<Dialog open={true} title="Confirm" />);
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
expect(screen.getByRole('dialog')).toHaveAttribute('aria-labelledby');
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Common Next.js Config
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
const nextConfig = {
|
||||
images: {
|
||||
remotePatterns: [{ hostname: "cdnexamplecom" }],
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
},
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@heroicons/react'],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Tailwind CSS Utilities
|
||||
|
||||
```tsx
|
||||
// Conditional classes with cn()
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
<button className={cn(
|
||||
'px-4 py-2 rounded',
|
||||
variant === 'primary' && 'bg-blue-500 text-white',
|
||||
disabled && 'opacity-50 cursor-not-allowed'
|
||||
)} />
|
||||
```
|
||||
|
||||
### TypeScript Patterns
|
||||
|
||||
```tsx
|
||||
// Props with children
|
||||
interface CardProps {
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
// Generic component
|
||||
interface ListProps<T> {
|
||||
items: T[];
|
||||
renderItem: (item: T) => React.ReactNode;
|
||||
}
|
||||
|
||||
function List<T>({ items, renderItem }: ListProps<T>) {
|
||||
return <ul>{items.map(renderItem)}</ul>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
- React Patterns: `references/react_patterns.md`
|
||||
- Next.js Optimization: `references/nextjs_optimization_guide.md`
|
||||
- Best Practices: `references/frontend_best_practices.md`
|
||||
@@ -0,0 +1,806 @@
|
||||
# Frontend Best Practices
|
||||
|
||||
Modern frontend development standards for accessibility, testing, TypeScript, and Tailwind CSS.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Accessibility (a11y)](#accessibility-a11y)
|
||||
- [Testing Strategies](#testing-strategies)
|
||||
- [TypeScript Patterns](#typescript-patterns)
|
||||
- [Tailwind CSS](#tailwind-css)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Security](#security)
|
||||
|
||||
---
|
||||
|
||||
## Accessibility (a11y)
|
||||
|
||||
### Semantic HTML
|
||||
|
||||
```tsx
|
||||
// BAD - Divs for everything
|
||||
<div onClick={handleClick}>Click me</div>
|
||||
<div class="header">...</div>
|
||||
<div class="nav">...</div>
|
||||
|
||||
// GOOD - Semantic elements
|
||||
<button onClick={handleClick}>Click me</button>
|
||||
<header>...</header>
|
||||
<nav>...</nav>
|
||||
<main>...</main>
|
||||
<article>...</article>
|
||||
<aside>...</aside>
|
||||
<footer>...</footer>
|
||||
```
|
||||
|
||||
### Keyboard Navigation
|
||||
|
||||
```tsx
|
||||
// Ensure all interactive elements are keyboard accessible
|
||||
function Modal({ isOpen, onClose, children }: ModalProps) {
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// Focus first focusable element
|
||||
const focusable = modalRef.current?.querySelectorAll(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
(focusable?.[0] as HTMLElement)?.focus();
|
||||
|
||||
// Trap focus within modal
|
||||
const handleTab = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Tab' && focusable) {
|
||||
const first = focusable[0] as HTMLElement;
|
||||
const last = focusable[focusable.length - 1] as HTMLElement;
|
||||
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleTab);
|
||||
return () => document.removeEventListener('keydown', handleTab);
|
||||
}
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={modalRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="modal-title"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### ARIA Attributes
|
||||
|
||||
```tsx
|
||||
// Live regions for dynamic content
|
||||
<div aria-live="polite" aria-atomic="true">
|
||||
{status && <p>{status}</p>}
|
||||
</div>
|
||||
|
||||
// Loading states
|
||||
<button disabled={isLoading} aria-busy={isLoading}>
|
||||
{isLoading ? 'Loading...' : 'Submit'}
|
||||
</button>
|
||||
|
||||
// Form labels
|
||||
<label htmlFor="email">Email address</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
aria-required="true"
|
||||
aria-invalid={!!errors.email}
|
||||
aria-describedby={errors.email ? 'email-error' : undefined}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p id="email-error" role="alert">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
|
||||
// Navigation
|
||||
<nav aria-label="Main navigation">
|
||||
<ul>
|
||||
<li><a href="/" aria-current={isHome ? 'page' : undefined}>Home</a></li>
|
||||
<li><a href="/about" aria-current={isAbout ? 'page' : undefined}>About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
// Toggle buttons
|
||||
<button
|
||||
aria-pressed={isEnabled}
|
||||
onClick={() => setIsEnabled(!isEnabled)}
|
||||
>
|
||||
{isEnabled ? 'Enabled' : 'Disabled'}
|
||||
</button>
|
||||
|
||||
// Expandable sections
|
||||
<button
|
||||
aria-expanded={isOpen}
|
||||
aria-controls="content-panel"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
>
|
||||
Show details
|
||||
</button>
|
||||
<div id="content-panel" hidden={!isOpen}>
|
||||
Content here
|
||||
</div>
|
||||
```
|
||||
|
||||
### Color Contrast
|
||||
|
||||
```tsx
|
||||
// Ensure 4.5:1 contrast ratio for text (WCAG AA)
|
||||
// Use tools like @axe-core/react for testing
|
||||
|
||||
// tailwind.config.js - Define accessible colors
|
||||
module.exports = {
|
||||
theme: {
|
||||
colors: {
|
||||
// Primary with proper contrast
|
||||
primary: {
|
||||
DEFAULT: '#2563eb', // Blue 600
|
||||
foreground: '#ffffff',
|
||||
},
|
||||
// Error state
|
||||
error: {
|
||||
DEFAULT: '#dc2626', // Red 600
|
||||
foreground: '#ffffff',
|
||||
},
|
||||
// Text colors with proper contrast
|
||||
foreground: '#0f172a', // Slate 900
|
||||
muted: '#64748b', // Slate 500 - minimum 4.5:1 on white
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Never rely on color alone
|
||||
<span className="text-red-600">
|
||||
<ErrorIcon aria-hidden="true" />
|
||||
<span>Error: Invalid input</span>
|
||||
</span>
|
||||
```
|
||||
|
||||
### Screen Reader Only Content
|
||||
|
||||
```tsx
|
||||
// Visually hidden but accessible to screen readers
|
||||
const srOnly = 'absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0';
|
||||
|
||||
// Skip link for keyboard users
|
||||
<a href="#main-content" className={srOnly + ' focus:not-sr-only focus:absolute focus:top-0'}>
|
||||
Skip to main content
|
||||
</a>
|
||||
|
||||
// Icon buttons need labels
|
||||
<button aria-label="Close menu">
|
||||
<XIcon aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
// Or use visually hidden text
|
||||
<button>
|
||||
<XIcon aria-hidden="true" />
|
||||
<span className={srOnly}>Close menu</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategies
|
||||
|
||||
### Component Testing with Testing Library
|
||||
|
||||
```tsx
|
||||
// Button.test.tsx
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Button } from './Button';
|
||||
|
||||
describe('Button', () => {
|
||||
it('renders with correct text', () => {
|
||||
render(<Button>Click me</Button>);
|
||||
expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onClick when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleClick = jest.fn();
|
||||
|
||||
render(<Button onClick={handleClick}>Click me</Button>);
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('is disabled when loading', () => {
|
||||
render(<Button isLoading>Submit</Button>);
|
||||
expect(screen.getByRole('button')).toBeDisabled();
|
||||
expect(screen.getByRole('button')).toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('shows loading text when loading', () => {
|
||||
render(<Button isLoading loadingText="Submitting...">Submit</Button>);
|
||||
expect(screen.getByText('Submitting...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Hook Testing
|
||||
|
||||
```tsx
|
||||
// useCounter.test.ts
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useCounter } from './useCounter';
|
||||
|
||||
describe('useCounter', () => {
|
||||
it('initializes with default value', () => {
|
||||
const { result } = renderHook(() => useCounter());
|
||||
expect(result.current.count).toBe(0);
|
||||
});
|
||||
|
||||
it('initializes with custom value', () => {
|
||||
const { result } = renderHook(() => useCounter(10));
|
||||
expect(result.current.count).toBe(10);
|
||||
});
|
||||
|
||||
it('increments count', () => {
|
||||
const { result } = renderHook(() => useCounter());
|
||||
|
||||
act(() => {
|
||||
result.current.increment();
|
||||
});
|
||||
|
||||
expect(result.current.count).toBe(1);
|
||||
});
|
||||
|
||||
it('resets to initial value', () => {
|
||||
const { result } = renderHook(() => useCounter(5));
|
||||
|
||||
act(() => {
|
||||
result.current.increment();
|
||||
result.current.increment();
|
||||
result.current.reset();
|
||||
});
|
||||
|
||||
expect(result.current.count).toBe(5);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Integration Testing
|
||||
|
||||
```tsx
|
||||
// LoginForm.test.tsx
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { LoginForm } from './LoginForm';
|
||||
import { AuthProvider } from '@/contexts/AuthContext';
|
||||
|
||||
const mockLogin = jest.fn();
|
||||
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
login: (...args: unknown[]) => mockLogin(...args),
|
||||
}));
|
||||
|
||||
describe('LoginForm', () => {
|
||||
beforeEach(() => {
|
||||
mockLogin.mockReset();
|
||||
});
|
||||
|
||||
it('submits form with valid credentials', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockLogin.mockResolvedValueOnce({ user: { id: '1', name: 'Test' } });
|
||||
|
||||
render(
|
||||
<AuthProvider>
|
||||
<LoginForm />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
await user.type(screen.getByLabelText(/email/i), 'test@example.com');
|
||||
await user.type(screen.getByLabelText(/password/i), 'password123');
|
||||
await user.click(screen.getByRole('button', { name: /sign in/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLogin).toHaveBeenCalledWith('test@example.com', 'password123');
|
||||
});
|
||||
});
|
||||
|
||||
it('shows validation errors for empty fields', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<AuthProvider>
|
||||
<LoginForm />
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /sign in/i }));
|
||||
|
||||
expect(await screen.findByText(/email is required/i)).toBeInTheDocument();
|
||||
expect(await screen.findByText(/password is required/i)).toBeInTheDocument();
|
||||
expect(mockLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### E2E Testing with Playwright
|
||||
|
||||
```typescript
|
||||
// e2e/checkout.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Checkout flow', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await page.click('[data-testid="product-1"] button');
|
||||
await page.click('[data-testid="cart-button"]');
|
||||
});
|
||||
|
||||
test('completes checkout with valid payment', async ({ page }) => {
|
||||
await page.click('text=Proceed to Checkout');
|
||||
|
||||
// Fill shipping info
|
||||
await page.fill('[name="email"]', 'test@example.com');
|
||||
await page.fill('[name="address"]', '123 Test St');
|
||||
await page.fill('[name="city"]', 'Test City');
|
||||
await page.selectOption('[name="state"]', 'CA');
|
||||
await page.fill('[name="zip"]', '90210');
|
||||
|
||||
await page.click('text=Continue to Payment');
|
||||
await page.click('text=Place Order');
|
||||
|
||||
// Verify success
|
||||
await expect(page).toHaveURL(/\/order\/confirmation/);
|
||||
await expect(page.locator('h1')).toHaveText('Order Confirmed!');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TypeScript Patterns
|
||||
|
||||
### Component Props
|
||||
|
||||
```tsx
|
||||
// Use interface for component props
|
||||
interface ButtonProps {
|
||||
variant?: 'primary' | 'secondary' | 'ghost';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
isLoading?: boolean;
|
||||
children: React.ReactNode;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
// Extend HTML attributes
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary';
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
function Button({ variant = 'primary', isLoading, children, ...props }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
{...props}
|
||||
disabled={props.disabled || isLoading}
|
||||
className={cn(variants[variant], props.className)}
|
||||
>
|
||||
{isLoading ? <Spinner /> : children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Polymorphic components
|
||||
type PolymorphicProps<E extends React.ElementType> = {
|
||||
as?: E;
|
||||
} & React.ComponentPropsWithoutRef<E>;
|
||||
|
||||
function Box<E extends React.ElementType = 'div'>({
|
||||
as,
|
||||
children,
|
||||
...props
|
||||
}: PolymorphicProps<E>) {
|
||||
const Component = as || 'div';
|
||||
return <Component {...props}>{children}</Component>;
|
||||
}
|
||||
|
||||
// Usage
|
||||
<Box as="section" id="hero">Content</Box>
|
||||
<Box as="article">Article content</Box>
|
||||
```
|
||||
|
||||
### Discriminated Unions
|
||||
|
||||
```tsx
|
||||
// State machines with exhaustive type checking
|
||||
type AsyncState<T> =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'success'; data: T }
|
||||
| { status: 'error'; error: Error };
|
||||
|
||||
function DataDisplay<T>({ state, render }: {
|
||||
state: AsyncState<T>;
|
||||
render: (data: T) => React.ReactNode;
|
||||
}) {
|
||||
switch (state.status) {
|
||||
case 'idle':
|
||||
return null;
|
||||
case 'loading':
|
||||
return <Spinner />;
|
||||
case 'success':
|
||||
return <>{render(state.data)}</>;
|
||||
case 'error':
|
||||
return <ErrorMessage error={state.error} />;
|
||||
// TypeScript ensures all cases are handled
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Generic Components
|
||||
|
||||
```tsx
|
||||
// Generic list component
|
||||
interface ListProps<T> {
|
||||
items: T[];
|
||||
renderItem: (item: T, index: number) => React.ReactNode;
|
||||
keyExtractor: (item: T) => string;
|
||||
emptyMessage?: string;
|
||||
}
|
||||
|
||||
function List<T>({ items, renderItem, keyExtractor, emptyMessage }: ListProps<T>) {
|
||||
if (items.length === 0) {
|
||||
return <p className="text-muted">{emptyMessage || 'No items'}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul>
|
||||
{items.map((item, index) => (
|
||||
<li key={keyExtractor(item)}>{renderItem(item, index)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
// Usage
|
||||
<List
|
||||
items={users}
|
||||
keyExtractor={(user) => user.id}
|
||||
renderItem={(user) => <UserCard user={user} />}
|
||||
/>
|
||||
```
|
||||
|
||||
### Type Guards
|
||||
|
||||
```tsx
|
||||
// User-defined type guards
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface Admin extends User {
|
||||
role: 'admin';
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
function isAdmin(user: User): user is Admin {
|
||||
return 'role' in user && user.role === 'admin';
|
||||
}
|
||||
|
||||
function UserBadge({ user }: { user: User }) {
|
||||
if (isAdmin(user)) {
|
||||
// TypeScript knows user is Admin here
|
||||
return <Badge variant="admin">Admin ({user.permissions.length} perms)</Badge>;
|
||||
}
|
||||
|
||||
return <Badge>User</Badge>;
|
||||
}
|
||||
|
||||
// API response type guards
|
||||
interface ApiSuccess<T> {
|
||||
success: true;
|
||||
data: T;
|
||||
}
|
||||
|
||||
interface ApiError {
|
||||
success: false;
|
||||
error: string;
|
||||
}
|
||||
|
||||
type ApiResponse<T> = ApiSuccess<T> | ApiError;
|
||||
|
||||
function isApiSuccess<T>(response: ApiResponse<T>): response is ApiSuccess<T> {
|
||||
return response.success === true;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tailwind CSS
|
||||
|
||||
### Component Variants with CVA
|
||||
|
||||
```tsx
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
// Base styles
|
||||
'inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus-visible:ring-blue-500',
|
||||
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200 focus-visible:ring-gray-500',
|
||||
ghost: 'hover:bg-gray-100 hover:text-gray-900',
|
||||
destructive: 'bg-red-600 text-white hover:bg-red-700 focus-visible:ring-red-500',
|
||||
},
|
||||
size: {
|
||||
sm: 'h-8 px-3 text-sm',
|
||||
md: 'h-10 px-4 text-sm',
|
||||
lg: 'h-12 px-6 text-base',
|
||||
icon: 'h-10 w-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'primary',
|
||||
size: 'md',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {}
|
||||
|
||||
function Button({ className, variant, size, ...props }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={cn(buttonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Usage
|
||||
<Button variant="primary" size="lg">Large Primary</Button>
|
||||
<Button variant="ghost" size="icon"><MenuIcon /></Button>
|
||||
```
|
||||
|
||||
### Responsive Design
|
||||
|
||||
```tsx
|
||||
// Mobile-first responsive design
|
||||
<div className="
|
||||
grid
|
||||
grid-cols-1 {/* Mobile: 1 column */}
|
||||
sm:grid-cols-2 {/* 640px+: 2 columns */}
|
||||
lg:grid-cols-3 {/* 1024px+: 3 columns */}
|
||||
xl:grid-cols-4 {/* 1280px+: 4 columns */}
|
||||
gap-4
|
||||
sm:gap-6
|
||||
lg:gap-8
|
||||
">
|
||||
{products.map(product => <ProductCard key={product.id} product={product} />)}
|
||||
</div>
|
||||
|
||||
// Container with responsive padding
|
||||
<div className="container mx-auto px-4 sm:px-6 lg:px-8">
|
||||
Content
|
||||
</div>
|
||||
|
||||
// Hide/show based on breakpoint
|
||||
<nav className="hidden md:flex">Desktop nav</nav>
|
||||
<button className="md:hidden">Mobile menu</button>
|
||||
```
|
||||
|
||||
### Animation Utilities
|
||||
|
||||
```tsx
|
||||
// Skeleton loading
|
||||
<div className="animate-pulse space-y-4">
|
||||
<div className="h-4 bg-gray-200 rounded w-3/4" />
|
||||
<div className="h-4 bg-gray-200 rounded w-1/2" />
|
||||
</div>
|
||||
|
||||
// Transitions
|
||||
<button className="
|
||||
transition-all
|
||||
duration-200
|
||||
ease-in-out
|
||||
hover:scale-105
|
||||
active:scale-95
|
||||
">
|
||||
Hover me
|
||||
</button>
|
||||
|
||||
// Custom animations in tailwind.config.js
|
||||
module.exports = {
|
||||
theme: {
|
||||
extend: {
|
||||
animation: {
|
||||
'fade-in': 'fadeIn 0.3s ease-out',
|
||||
'slide-up': 'slideUp 0.3s ease-out',
|
||||
'spin-slow': 'spin 3s linear infinite',
|
||||
},
|
||||
keyframes: {
|
||||
fadeIn: {
|
||||
'0%': { opacity: '0' },
|
||||
'100%': { opacity: '1' },
|
||||
},
|
||||
slideUp: {
|
||||
'0%': { transform: 'translateY(10px)', opacity: '0' },
|
||||
'100%': { transform: 'translateY(0)', opacity: '1' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Usage
|
||||
<div className="animate-fade-in">Fading in</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Feature-Based Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Next.js App Router
|
||||
│ ├── (auth)/ # Auth route group
|
||||
│ │ ├── login/
|
||||
│ │ └── register/
|
||||
│ ├── dashboard/
|
||||
│ │ ├── page.tsx
|
||||
│ │ └── layout.tsx
|
||||
│ └── layout.tsx
|
||||
├── components/
|
||||
│ ├── ui/ # Shared UI components
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Input.tsx
|
||||
│ │ └── index.ts
|
||||
│ └── features/ # Feature-specific components
|
||||
│ ├── auth/
|
||||
│ │ ├── LoginForm.tsx
|
||||
│ │ └── RegisterForm.tsx
|
||||
│ └── dashboard/
|
||||
│ ├── StatsCard.tsx
|
||||
│ └── RecentActivity.tsx
|
||||
├── hooks/ # Custom React hooks
|
||||
│ ├── useAuth.ts
|
||||
│ ├── useDebounce.ts
|
||||
│ └── useLocalStorage.ts
|
||||
├── lib/ # Utilities and configs
|
||||
│ ├── utils.ts
|
||||
│ ├── api.ts
|
||||
│ └── constants.ts
|
||||
├── types/ # TypeScript types
|
||||
│ ├── user.ts
|
||||
│ └── api.ts
|
||||
└── styles/
|
||||
└── globals.css
|
||||
```
|
||||
|
||||
### Barrel Exports
|
||||
|
||||
```tsx
|
||||
// components/ui/index.ts
|
||||
export { Button } from './Button';
|
||||
export { Input } from './Input';
|
||||
export { Card, CardHeader, CardContent, CardFooter } from './Card';
|
||||
export { Dialog, DialogTrigger, DialogContent } from './Dialog';
|
||||
|
||||
// Usage
|
||||
import { Button, Input, Card } from '@/components/ui';
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
### XSS Prevention
|
||||
|
||||
React escapes content by default, which prevents most XSS attacks. When you need to render HTML content:
|
||||
|
||||
1. **Avoid rendering raw HTML** when possible
|
||||
2. **Sanitize with DOMPurify** for trusted content sources
|
||||
3. **Use allow-lists** for permitted tags and attributes
|
||||
|
||||
```tsx
|
||||
// React escapes by default - this is safe
|
||||
<div>{userInput}</div>
|
||||
|
||||
// When you must render HTML, sanitize first
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
function SafeHTML({ html }: { html: string }) {
|
||||
const sanitized = DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
|
||||
ALLOWED_ATTR: ['href'],
|
||||
});
|
||||
|
||||
return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
|
||||
}
|
||||
```
|
||||
|
||||
### Input Validation
|
||||
|
||||
```tsx
|
||||
import { z } from 'zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email('Invalid email address'),
|
||||
password: z.string()
|
||||
.min(8, 'Password must be at least 8 characters')
|
||||
.regex(/[A-Z]/, 'Password must contain uppercase letter')
|
||||
.regex(/[0-9]/, 'Password must contain number'),
|
||||
confirmPassword: z.string(),
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords do not match',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof schema>;
|
||||
|
||||
function RegisterForm() {
|
||||
const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Input {...register('email')} error={errors.email?.message} />
|
||||
<Input type="password" {...register('password')} error={errors.password?.message} />
|
||||
<Input type="password" {...register('confirmPassword')} error={errors.confirmPassword?.message} />
|
||||
<Button type="submit">Register</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Secure API Calls
|
||||
|
||||
```tsx
|
||||
// Use environment variables for API endpoints
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
|
||||
// Never include secrets in client code - use server-side API routes
|
||||
// app/api/data/route.ts
|
||||
export async function GET() {
|
||||
const response = await fetch('https://api.example.com/data', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${process.env.API_SECRET}`, // Server-side only
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json(await response.json());
|
||||
}
|
||||
```
|
||||
+724
@@ -0,0 +1,724 @@
|
||||
# Next.js Optimization Guide
|
||||
|
||||
Performance optimization techniques for Next.js 14+ applications.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Rendering Strategies](#rendering-strategies)
|
||||
- [Image Optimization](#image-optimization)
|
||||
- [Code Splitting](#code-splitting)
|
||||
- [Data Fetching](#data-fetching)
|
||||
- [Caching Strategies](#caching-strategies)
|
||||
- [Bundle Optimization](#bundle-optimization)
|
||||
- [Core Web Vitals](#core-web-vitals)
|
||||
|
||||
---
|
||||
|
||||
## Rendering Strategies
|
||||
|
||||
### Server Components (Default)
|
||||
|
||||
Server Components render on the server and send HTML to the client. Use for data-heavy, non-interactive content.
|
||||
|
||||
```tsx
|
||||
// app/products/page.tsx - Server Component (default)
|
||||
async function ProductsPage() {
|
||||
// This runs on the server - no client bundle impact
|
||||
const products = await db.products.findMany();
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{products.map(product => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Client Components
|
||||
|
||||
Use `'use client'` only when you need:
|
||||
- Event handlers (onClick, onChange)
|
||||
- State (useState, useReducer)
|
||||
- Effects (useEffect)
|
||||
- Browser APIs (window, document)
|
||||
|
||||
```tsx
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
function AddToCartButton({ productId }: { productId: string }) {
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
|
||||
async function handleClick() {
|
||||
setIsAdding(true);
|
||||
await addToCart(productId);
|
||||
setIsAdding(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<button onClick={handleClick} disabled={isAdding}>
|
||||
{isAdding ? 'Adding...' : 'Add to Cart'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Mixing Server and Client Components
|
||||
|
||||
```tsx
|
||||
// app/products/[id]/page.tsx - Server Component
|
||||
async function ProductPage({ params }: { params: { id: string } }) {
|
||||
const product = await getProduct(params.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Server-rendered content */}
|
||||
<h1>{product.name}</h1>
|
||||
<p>{product.description}</p>
|
||||
|
||||
{/* Client component for interactivity */}
|
||||
<AddToCartButton productId={product.id} />
|
||||
|
||||
{/* Server component for reviews */}
|
||||
<ProductReviews productId={product.id} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Static vs Dynamic Rendering
|
||||
|
||||
```tsx
|
||||
// Force static generation at build time
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
// Force dynamic rendering at request time
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Revalidate every 60 seconds (ISR)
|
||||
export const revalidate = 60;
|
||||
|
||||
// Revalidate on-demand
|
||||
import { revalidatePath, revalidateTag } from 'next/cache';
|
||||
|
||||
async function updateProduct(id: string, data: ProductData) {
|
||||
await db.products.update({ where: { id }, data });
|
||||
|
||||
// Revalidate specific path
|
||||
revalidatePath(`/products/${id}`);
|
||||
|
||||
// Or revalidate by tag
|
||||
revalidateTag('products');
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Image Optimization
|
||||
|
||||
### Next.js Image Component
|
||||
|
||||
```tsx
|
||||
import Image from 'next/image';
|
||||
|
||||
// Basic optimized image
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero image"
|
||||
width={1200}
|
||||
height={600}
|
||||
priority // Load immediately for LCP
|
||||
/>
|
||||
|
||||
// Responsive image
|
||||
<Image
|
||||
src="/product.jpg"
|
||||
alt="Product"
|
||||
fill
|
||||
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
|
||||
className="object-cover"
|
||||
/>
|
||||
|
||||
// With placeholder blur
|
||||
import productImage from '@/public/product.jpg';
|
||||
|
||||
<Image
|
||||
src={productImage}
|
||||
alt="Product"
|
||||
placeholder="blur" // Uses imported image data
|
||||
/>
|
||||
```
|
||||
|
||||
### Remote Images Configuration
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
module.exports = {
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'cdn.example.com',
|
||||
pathname: '/images/**',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: '*.cloudinary.com',
|
||||
},
|
||||
],
|
||||
// Image formats (webp is default)
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
// Device sizes for srcset
|
||||
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
|
||||
// Image sizes for srcset
|
||||
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Lazy Loading Patterns
|
||||
|
||||
```tsx
|
||||
// Images below the fold - lazy load (default)
|
||||
<Image
|
||||
src="/gallery/photo1.jpg"
|
||||
alt="Gallery photo"
|
||||
width={400}
|
||||
height={300}
|
||||
loading="lazy" // Default behavior
|
||||
/>
|
||||
|
||||
// Above the fold - load immediately
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
width={1200}
|
||||
height={600}
|
||||
priority
|
||||
loading="eager"
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Splitting
|
||||
|
||||
### Dynamic Imports
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
// Basic dynamic import
|
||||
const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
|
||||
loading: () => <ChartSkeleton />,
|
||||
});
|
||||
|
||||
// Disable SSR for client-only components
|
||||
const MapComponent = dynamic(() => import('@/components/Map'), {
|
||||
ssr: false,
|
||||
loading: () => <div className="h-[400px] bg-gray-100" />,
|
||||
});
|
||||
|
||||
// Named exports
|
||||
const Modal = dynamic(() =>
|
||||
import('@/components/ui').then(mod => mod.Modal)
|
||||
);
|
||||
|
||||
// With suspense
|
||||
const DashboardCharts = dynamic(() => import('@/components/DashboardCharts'), {
|
||||
loading: () => <Suspense fallback={<ChartsSkeleton />} />,
|
||||
});
|
||||
```
|
||||
|
||||
### Route-Based Splitting
|
||||
|
||||
```tsx
|
||||
// app/dashboard/analytics/page.tsx
|
||||
// This page only loads when /dashboard/analytics is visited
|
||||
import { Suspense } from 'react';
|
||||
import AnalyticsCharts from './AnalyticsCharts';
|
||||
|
||||
export default function AnalyticsPage() {
|
||||
return (
|
||||
<Suspense fallback={<AnalyticsSkeleton />}>
|
||||
<AnalyticsCharts />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Parallel Routes for Code Splitting
|
||||
|
||||
```
|
||||
app/
|
||||
├── dashboard/
|
||||
│ ├── @analytics/
|
||||
│ │ └── page.tsx # Loaded in parallel
|
||||
│ ├── @metrics/
|
||||
│ │ └── page.tsx # Loaded in parallel
|
||||
│ ├── layout.tsx
|
||||
│ └── page.tsx
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/dashboard/layout.tsx
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
analytics,
|
||||
metrics,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
analytics: React.ReactNode;
|
||||
metrics: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{children}
|
||||
<Suspense fallback={<AnalyticsSkeleton />}>{analytics}</Suspense>
|
||||
<Suspense fallback={<MetricsSkeleton />}>{metrics}</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Fetching
|
||||
|
||||
### Server-Side Data Fetching
|
||||
|
||||
```tsx
|
||||
// Parallel data fetching
|
||||
async function Dashboard() {
|
||||
// Start both requests simultaneously
|
||||
const [user, stats, notifications] = await Promise.all([
|
||||
getUser(),
|
||||
getStats(),
|
||||
getNotifications(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<UserHeader user={user} />
|
||||
<StatsPanel stats={stats} />
|
||||
<NotificationList notifications={notifications} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming with Suspense
|
||||
|
||||
```tsx
|
||||
import { Suspense } from 'react';
|
||||
|
||||
async function ProductPage({ params }: { params: { id: string } }) {
|
||||
const product = await getProduct(params.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Immediate content */}
|
||||
<h1>{product.name}</h1>
|
||||
<p>{product.description}</p>
|
||||
|
||||
{/* Stream reviews - don't block page */}
|
||||
<Suspense fallback={<ReviewsSkeleton />}>
|
||||
<Reviews productId={params.id} />
|
||||
</Suspense>
|
||||
|
||||
{/* Stream recommendations */}
|
||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||
<Recommendations productId={params.id} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Slow data component
|
||||
async function Reviews({ productId }: { productId: string }) {
|
||||
const reviews = await getReviews(productId); // Slow query
|
||||
return <ReviewList reviews={reviews} />;
|
||||
}
|
||||
```
|
||||
|
||||
### Request Memoization
|
||||
|
||||
```tsx
|
||||
// Next.js automatically dedupes identical requests
|
||||
async function Layout({ children }) {
|
||||
const user = await getUser(); // Request 1
|
||||
return <div>{children}</div>;
|
||||
}
|
||||
|
||||
async function Header() {
|
||||
const user = await getUser(); // Same request - cached!
|
||||
return <div>Hello, {user.name}</div>;
|
||||
}
|
||||
|
||||
// Both components call getUser() but only one request is made
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Caching Strategies
|
||||
|
||||
### Fetch Cache Options
|
||||
|
||||
```tsx
|
||||
// Cache indefinitely (default for static)
|
||||
fetch('https://api.example.com/data');
|
||||
|
||||
// No cache - always fresh
|
||||
fetch('https://api.example.com/data', { cache: 'no-store' });
|
||||
|
||||
// Revalidate after time
|
||||
fetch('https://api.example.com/data', {
|
||||
next: { revalidate: 3600 } // 1 hour
|
||||
});
|
||||
|
||||
// Tag-based revalidation
|
||||
fetch('https://api.example.com/products', {
|
||||
next: { tags: ['products'] }
|
||||
});
|
||||
|
||||
// Later, revalidate by tag
|
||||
import { revalidateTag } from 'next/cache';
|
||||
revalidateTag('products');
|
||||
```
|
||||
|
||||
### Route Segment Config
|
||||
|
||||
```tsx
|
||||
// app/products/page.tsx
|
||||
|
||||
// Revalidate every hour
|
||||
export const revalidate = 3600;
|
||||
|
||||
// Or force dynamic
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Generate static params at build
|
||||
export async function generateStaticParams() {
|
||||
const products = await getProducts();
|
||||
return products.map(p => ({ id: p.id }));
|
||||
}
|
||||
```
|
||||
|
||||
### unstable_cache for Custom Caching
|
||||
|
||||
```tsx
|
||||
import { unstable_cache } from 'next/cache';
|
||||
|
||||
const getCachedUser = unstable_cache(
|
||||
async (userId: string) => {
|
||||
const user = await db.users.findUnique({ where: { id: userId } });
|
||||
return user;
|
||||
},
|
||||
['user-cache'],
|
||||
{
|
||||
revalidate: 3600, // 1 hour
|
||||
tags: ['users'],
|
||||
}
|
||||
);
|
||||
|
||||
// Usage
|
||||
const user = await getCachedUser(userId);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Bundle Optimization
|
||||
|
||||
### Analyze Bundle Size
|
||||
|
||||
```bash
|
||||
# Install analyzer
|
||||
npm install @next/bundle-analyzer
|
||||
|
||||
# Update next.config.js
|
||||
const withBundleAnalyzer = require('@next/bundle-analyzer')({
|
||||
enabled: process.env.ANALYZE === 'true',
|
||||
});
|
||||
|
||||
module.exports = withBundleAnalyzer({
|
||||
// config
|
||||
});
|
||||
|
||||
# Run analysis
|
||||
ANALYZE=true npm run build
|
||||
```
|
||||
|
||||
### Tree Shaking Imports
|
||||
|
||||
```tsx
|
||||
// BAD - Imports entire library
|
||||
import _ from 'lodash';
|
||||
const result = _.debounce(fn, 300);
|
||||
|
||||
// GOOD - Import only what you need
|
||||
import debounce from 'lodash/debounce';
|
||||
const result = debounce(fn, 300);
|
||||
|
||||
// GOOD - Named imports (tree-shakeable)
|
||||
import { debounce } from 'lodash-es';
|
||||
```
|
||||
|
||||
### Optimize Dependencies
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
module.exports = {
|
||||
// Transpile specific packages
|
||||
transpilePackages: ['ui-library', 'shared-utils'],
|
||||
|
||||
// Optimize package imports
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@heroicons/react'],
|
||||
},
|
||||
|
||||
// External packages for server
|
||||
serverExternalPackages: ['sharp', 'bcrypt'],
|
||||
};
|
||||
```
|
||||
|
||||
### Font Optimization
|
||||
|
||||
```tsx
|
||||
// app/layout.tsx
|
||||
import { Inter, Roboto_Mono } from 'next/font/google';
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ['latin'],
|
||||
display: 'swap',
|
||||
variable: '--font-inter',
|
||||
});
|
||||
|
||||
const robotoMono = Roboto_Mono({
|
||||
subsets: ['latin'],
|
||||
display: 'swap',
|
||||
variable: '--font-roboto-mono',
|
||||
});
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html lang="en" className={`${inter.variable} ${robotoMono.variable}`}>
|
||||
<body className="font-sans">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Web Vitals
|
||||
|
||||
### Largest Contentful Paint (LCP)
|
||||
|
||||
```tsx
|
||||
// Optimize LCP hero image
|
||||
import Image from 'next/image';
|
||||
|
||||
export default function Hero() {
|
||||
return (
|
||||
<section className="relative h-[600px]">
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
fill
|
||||
priority // Preload for LCP
|
||||
sizes="100vw"
|
||||
className="object-cover"
|
||||
/>
|
||||
<div className="relative z-10">
|
||||
<h1>Welcome</h1>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Preload critical resources in layout
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<link rel="preload" href="/hero.jpg" as="image" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
</head>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Cumulative Layout Shift (CLS)
|
||||
|
||||
```tsx
|
||||
// Prevent CLS with explicit dimensions
|
||||
<Image
|
||||
src="/product.jpg"
|
||||
alt="Product"
|
||||
width={400}
|
||||
height={300}
|
||||
/>
|
||||
|
||||
// Or use aspect ratio
|
||||
<div className="aspect-video relative">
|
||||
<Image src="/video-thumb.jpg" alt="Video" fill />
|
||||
</div>
|
||||
|
||||
// Skeleton placeholders
|
||||
function ProductCard({ product }: { product?: Product }) {
|
||||
if (!product) {
|
||||
return (
|
||||
<div className="animate-pulse">
|
||||
<div className="h-48 bg-gray-200 rounded" />
|
||||
<div className="h-4 bg-gray-200 rounded mt-2 w-3/4" />
|
||||
<div className="h-4 bg-gray-200 rounded mt-1 w-1/2" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Image src={product.image} alt={product.name} width={300} height={200} />
|
||||
<h3>{product.name}</h3>
|
||||
<p>{product.price}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### First Input Delay (FID) / Interaction to Next Paint (INP)
|
||||
|
||||
```tsx
|
||||
// Defer non-critical JavaScript
|
||||
import Script from 'next/script';
|
||||
|
||||
export default function Layout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
|
||||
{/* Load analytics after page is interactive */}
|
||||
<Script
|
||||
src="https://analytics.example.com/script.js"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
|
||||
{/* Load chat widget when idle */}
|
||||
<Script
|
||||
src="https://chat.example.com/widget.js"
|
||||
strategy="lazyOnload"
|
||||
/>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
// Use web workers for heavy computation
|
||||
// app/components/DataProcessor.tsx
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
function DataProcessor({ data }: { data: number[] }) {
|
||||
const [result, setResult] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const worker = new Worker(new URL('../workers/processor.js', import.meta.url));
|
||||
|
||||
worker.postMessage(data);
|
||||
worker.onmessage = (e) => setResult(e.data);
|
||||
|
||||
return () => worker.terminate();
|
||||
}, [data]);
|
||||
|
||||
return <div>Result: {result}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Measuring Performance
|
||||
|
||||
```tsx
|
||||
// app/components/PerformanceMonitor.tsx
|
||||
'use client';
|
||||
|
||||
import { useReportWebVitals } from 'next/web-vitals';
|
||||
|
||||
export function PerformanceMonitor() {
|
||||
useReportWebVitals((metric) => {
|
||||
switch (metric.name) {
|
||||
case 'LCP':
|
||||
console.log('LCP:', metric.value);
|
||||
break;
|
||||
case 'FID':
|
||||
console.log('FID:', metric.value);
|
||||
break;
|
||||
case 'CLS':
|
||||
console.log('CLS:', metric.value);
|
||||
break;
|
||||
case 'TTFB':
|
||||
console.log('TTFB:', metric.value);
|
||||
break;
|
||||
}
|
||||
|
||||
// Send to analytics
|
||||
analytics.track('web-vital', {
|
||||
name: metric.name,
|
||||
value: metric.value,
|
||||
id: metric.id,
|
||||
});
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Performance Checklist
|
||||
|
||||
| Area | Optimization | Impact |
|
||||
|------|-------------|--------|
|
||||
| Images | Use next/image with priority for LCP | High |
|
||||
| Fonts | Use next/font with display: swap | Medium |
|
||||
| Code | Dynamic imports for heavy components | High |
|
||||
| Data | Parallel fetching with Promise.all | High |
|
||||
| Render | Server Components by default | High |
|
||||
| Cache | Configure revalidate appropriately | Medium |
|
||||
| Bundle | Tree-shake imports, analyze size | Medium |
|
||||
|
||||
### Config Template
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
images: {
|
||||
remotePatterns: [{ hostname: 'cdn.example.com' }],
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
},
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react'],
|
||||
},
|
||||
headers: async () => [
|
||||
{
|
||||
source: '/(.*)',
|
||||
headers: [
|
||||
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
||||
{ key: 'X-Frame-Options', value: 'DENY' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
@@ -0,0 +1,746 @@
|
||||
# React Patterns
|
||||
|
||||
Production-ready patterns for building scalable React applications with TypeScript.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Component Composition](#component-composition)
|
||||
- [Custom Hooks](#custom-hooks)
|
||||
- [State Management](#state-management)
|
||||
- [Performance Patterns](#performance-patterns)
|
||||
- [Error Boundaries](#error-boundaries)
|
||||
- [Anti-Patterns](#anti-patterns)
|
||||
|
||||
---
|
||||
|
||||
## Component Composition
|
||||
|
||||
### Compound Components
|
||||
|
||||
Use compound components when building reusable UI components with multiple related parts.
|
||||
|
||||
```tsx
|
||||
// Compound component pattern for a Select
|
||||
interface SelectContextType {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
const SelectContext = createContext<SelectContextType | null>(null);
|
||||
|
||||
function Select({ children, value, onChange }: {
|
||||
children: React.ReactNode;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<SelectContext.Provider value={{ value, onChange }}>
|
||||
<div className="relative">{children}</div>
|
||||
</SelectContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectTrigger({ children }: { children: React.ReactNode }) {
|
||||
const context = useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectTrigger must be used within Select');
|
||||
|
||||
return (
|
||||
<button className="flex items-center gap-2 px-4 py-2 border rounded">
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectOption({ value, children }: { value: string; children: React.ReactNode }) {
|
||||
const context = useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectOption must be used within Select');
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={() => context.onChange(value)}
|
||||
className={`px-4 py-2 cursor-pointer hover:bg-gray-100 ${
|
||||
context.value === value ? 'bg-blue-50' : ''
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Attach sub-components
|
||||
Select.Trigger = SelectTrigger;
|
||||
Select.Option = SelectOption;
|
||||
|
||||
// Usage
|
||||
<Select value={selected} onChange={setSelected}>
|
||||
<Select.Trigger>Choose option</Select.Trigger>
|
||||
<Select.Option value="a">Option A</Select.Option>
|
||||
<Select.Option value="b">Option B</Select.Option>
|
||||
</Select>
|
||||
```
|
||||
|
||||
### Render Props
|
||||
|
||||
Use render props when you need to share behavior with flexible rendering.
|
||||
|
||||
```tsx
|
||||
interface MousePosition {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function MouseTracker({ render }: { render: (pos: MousePosition) => React.ReactNode }) {
|
||||
const [position, setPosition] = useState<MousePosition>({ x: 0, y: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
setPosition({ x: e.clientX, y: e.clientY });
|
||||
};
|
||||
window.addEventListener('mousemove', handleMouseMove);
|
||||
return () => window.removeEventListener('mousemove', handleMouseMove);
|
||||
}, []);
|
||||
|
||||
return <>{render(position)}</>;
|
||||
}
|
||||
|
||||
// Usage
|
||||
<MouseTracker
|
||||
render={({ x, y }) => (
|
||||
<div>Mouse position: {x}, {y}</div>
|
||||
)}
|
||||
/>
|
||||
```
|
||||
|
||||
### Higher-Order Components (HOC)
|
||||
|
||||
Use HOCs for cross-cutting concerns like authentication or logging.
|
||||
|
||||
```tsx
|
||||
function withAuth<P extends object>(WrappedComponent: React.ComponentType<P>) {
|
||||
return function AuthenticatedComponent(props: P) {
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
if (isLoading) return <LoadingSpinner />;
|
||||
if (!user) return <Navigate to="/login" />;
|
||||
|
||||
return <WrappedComponent {...props} />;
|
||||
};
|
||||
}
|
||||
|
||||
// Usage
|
||||
const ProtectedDashboard = withAuth(Dashboard);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom Hooks
|
||||
|
||||
### useAsync - Handle async operations
|
||||
|
||||
```tsx
|
||||
interface AsyncState<T> {
|
||||
data: T | null;
|
||||
error: Error | null;
|
||||
status: 'idle' | 'loading' | 'success' | 'error';
|
||||
}
|
||||
|
||||
function useAsync<T>(asyncFn: () => Promise<T>, deps: any[] = []) {
|
||||
const [state, setState] = useState<AsyncState<T>>({
|
||||
data: null,
|
||||
error: null,
|
||||
status: 'idle',
|
||||
});
|
||||
|
||||
const execute = useCallback(async () => {
|
||||
setState({ data: null, error: null, status: 'loading' });
|
||||
try {
|
||||
const data = await asyncFn();
|
||||
setState({ data, error: null, status: 'success' });
|
||||
} catch (error) {
|
||||
setState({ data: null, error: error as Error, status: 'error' });
|
||||
}
|
||||
}, deps);
|
||||
|
||||
useEffect(() => {
|
||||
execute();
|
||||
}, [execute]);
|
||||
|
||||
return { ...state, refetch: execute };
|
||||
}
|
||||
|
||||
// Usage
|
||||
function UserProfile({ userId }: { userId: string }) {
|
||||
const { data: user, status, error, refetch } = useAsync(
|
||||
() => fetchUser(userId),
|
||||
[userId]
|
||||
);
|
||||
|
||||
if (status === 'loading') return <Spinner />;
|
||||
if (status === 'error') return <Error message={error?.message} />;
|
||||
if (!user) return null;
|
||||
|
||||
return <Profile user={user} />;
|
||||
}
|
||||
```
|
||||
|
||||
### useDebounce - Debounce values
|
||||
|
||||
```tsx
|
||||
function useDebounce<T>(value: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedValue(value), delay);
|
||||
return () => clearTimeout(timer);
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
|
||||
// Usage
|
||||
function SearchInput() {
|
||||
const [query, setQuery] = useState('');
|
||||
const debouncedQuery = useDebounce(query, 300);
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedQuery) {
|
||||
searchAPI(debouncedQuery);
|
||||
}
|
||||
}, [debouncedQuery]);
|
||||
|
||||
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
|
||||
}
|
||||
```
|
||||
|
||||
### useLocalStorage - Persist state
|
||||
|
||||
```tsx
|
||||
function useLocalStorage<T>(key: string, initialValue: T) {
|
||||
const [storedValue, setStoredValue] = useState<T>(() => {
|
||||
if (typeof window === 'undefined') return initialValue;
|
||||
try {
|
||||
const item = window.localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : initialValue;
|
||||
} catch {
|
||||
return initialValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue = useCallback((value: T | ((val: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
||||
setStoredValue(valueToStore);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving to localStorage:', error);
|
||||
}
|
||||
}, [key, storedValue]);
|
||||
|
||||
return [storedValue, setValue] as const;
|
||||
}
|
||||
|
||||
// Usage
|
||||
const [theme, setTheme] = useLocalStorage('theme', 'light');
|
||||
```
|
||||
|
||||
### useMediaQuery - Responsive design
|
||||
|
||||
```tsx
|
||||
function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
setMatches(media.matches);
|
||||
|
||||
const listener = (e: MediaQueryListEvent) => setMatches(e.matches);
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
// Usage
|
||||
function ResponsiveNav() {
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
return isMobile ? <MobileNav /> : <DesktopNav />;
|
||||
}
|
||||
```
|
||||
|
||||
### usePrevious - Track previous values
|
||||
|
||||
```tsx
|
||||
function usePrevious<T>(value: T): T | undefined {
|
||||
const ref = useRef<T>();
|
||||
|
||||
useEffect(() => {
|
||||
ref.current = value;
|
||||
}, [value]);
|
||||
|
||||
return ref.current;
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
const prevCount = usePrevious(count);
|
||||
|
||||
return (
|
||||
<div>
|
||||
Current: {count}, Previous: {prevCount}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## State Management
|
||||
|
||||
### Context with Reducer
|
||||
|
||||
For complex state that multiple components need to access.
|
||||
|
||||
```tsx
|
||||
// types.ts
|
||||
interface CartItem {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CartState {
|
||||
items: CartItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
type CartAction =
|
||||
| { type: 'ADD_ITEM'; payload: CartItem }
|
||||
| { type: 'REMOVE_ITEM'; payload: string }
|
||||
| { type: 'UPDATE_QUANTITY'; payload: { id: string; quantity: number } }
|
||||
| { type: 'CLEAR_CART' };
|
||||
|
||||
// reducer.ts
|
||||
function cartReducer(state: CartState, action: CartAction): CartState {
|
||||
switch (action.type) {
|
||||
case 'ADD_ITEM': {
|
||||
const existingItem = state.items.find(i => i.id === action.payload.id);
|
||||
if (existingItem) {
|
||||
return {
|
||||
...state,
|
||||
items: state.items.map(item =>
|
||||
item.id === action.payload.id
|
||||
? { ...item, quantity: item.quantity + 1 }
|
||||
: item
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
items: [...state.items, { ...action.payload, quantity: 1 }],
|
||||
};
|
||||
}
|
||||
case 'REMOVE_ITEM':
|
||||
return {
|
||||
...state,
|
||||
items: state.items.filter(i => i.id !== action.payload),
|
||||
};
|
||||
case 'UPDATE_QUANTITY':
|
||||
return {
|
||||
...state,
|
||||
items: state.items.map(item =>
|
||||
item.id === action.payload.id
|
||||
? { ...item, quantity: action.payload.quantity }
|
||||
: item
|
||||
),
|
||||
};
|
||||
case 'CLEAR_CART':
|
||||
return { items: [], total: 0 };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// context.tsx
|
||||
const CartContext = createContext<{
|
||||
state: CartState;
|
||||
dispatch: React.Dispatch<CartAction>;
|
||||
} | null>(null);
|
||||
|
||||
function CartProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
|
||||
|
||||
// Compute total whenever items change
|
||||
const stateWithTotal = useMemo(() => ({
|
||||
...state,
|
||||
total: state.items.reduce((sum, item) => sum + item.price * item.quantity, 0),
|
||||
}), [state.items]);
|
||||
|
||||
return (
|
||||
<CartContext.Provider value={{ state: stateWithTotal, dispatch }}>
|
||||
{children}
|
||||
</CartContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function useCart() {
|
||||
const context = useContext(CartContext);
|
||||
if (!context) throw new Error('useCart must be used within CartProvider');
|
||||
return context;
|
||||
}
|
||||
```
|
||||
|
||||
### Zustand (Lightweight Alternative)
|
||||
|
||||
```tsx
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
interface AuthStore {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const useAuthStore = create<AuthStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
user: null,
|
||||
token: null,
|
||||
login: async (email, password) => {
|
||||
const { user, token } = await authAPI.login(email, password);
|
||||
set({ user, token });
|
||||
},
|
||||
logout: () => set({ user: null, token: null }),
|
||||
}),
|
||||
{ name: 'auth-storage' }
|
||||
)
|
||||
);
|
||||
|
||||
// Usage
|
||||
function Profile() {
|
||||
const { user, logout } = useAuthStore();
|
||||
return user ? <div>{user.name} <button onClick={logout}>Logout</button></div> : null;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Patterns
|
||||
|
||||
### React.memo with Custom Comparison
|
||||
|
||||
```tsx
|
||||
interface ListItemProps {
|
||||
item: { id: string; name: string; count: number };
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const ListItem = React.memo(
|
||||
function ListItem({ item, onSelect }: ListItemProps) {
|
||||
return (
|
||||
<div onClick={() => onSelect(item.id)}>
|
||||
{item.name} ({item.count})
|
||||
</div>
|
||||
);
|
||||
},
|
||||
(prevProps, nextProps) => {
|
||||
// Only re-render if item data changed
|
||||
return (
|
||||
prevProps.item.id === nextProps.item.id &&
|
||||
prevProps.item.name === nextProps.item.name &&
|
||||
prevProps.item.count === nextProps.item.count
|
||||
);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### useMemo for Expensive Calculations
|
||||
|
||||
```tsx
|
||||
function DataTable({ data, sortColumn, filterText }: {
|
||||
data: Item[];
|
||||
sortColumn: string;
|
||||
filterText: string;
|
||||
}) {
|
||||
const processedData = useMemo(() => {
|
||||
// Filter
|
||||
let result = data.filter(item =>
|
||||
item.name.toLowerCase().includes(filterText.toLowerCase())
|
||||
);
|
||||
|
||||
// Sort
|
||||
result = [...result].sort((a, b) => {
|
||||
const aVal = a[sortColumn as keyof Item];
|
||||
const bVal = b[sortColumn as keyof Item];
|
||||
return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [data, sortColumn, filterText]);
|
||||
|
||||
return (
|
||||
<table>
|
||||
{processedData.map(item => (
|
||||
<tr key={item.id}>{/* ... */}</tr>
|
||||
))}
|
||||
</table>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### useCallback for Stable References
|
||||
|
||||
```tsx
|
||||
function ParentComponent() {
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
|
||||
// Stable reference - won't cause child re-renders
|
||||
const handleItemClick = useCallback((id: string) => {
|
||||
setItems(prev => prev.map(item =>
|
||||
item.id === id ? { ...item, selected: !item.selected } : item
|
||||
));
|
||||
}, []);
|
||||
|
||||
const handleAddItem = useCallback((newItem: Item) => {
|
||||
setItems(prev => [...prev, newItem]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ItemList items={items} onItemClick={handleItemClick} />
|
||||
<AddItemForm onAdd={handleAddItem} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Virtualization for Long Lists
|
||||
|
||||
```tsx
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
|
||||
function VirtualList({ items }: { items: Item[] }) {
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: items.length,
|
||||
getScrollElement: () => parentRef.current,
|
||||
estimateSize: () => 50, // estimated row height
|
||||
overscan: 5,
|
||||
});
|
||||
|
||||
return (
|
||||
<div ref={parentRef} className="h-[400px] overflow-auto">
|
||||
<div
|
||||
style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map(virtualRow => (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: `${virtualRow.size}px`,
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
>
|
||||
{items[virtualRow.index].name}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Boundaries
|
||||
|
||||
### Class-Based Error Boundary
|
||||
|
||||
```tsx
|
||||
interface ErrorBoundaryProps {
|
||||
children: React.ReactNode;
|
||||
fallback?: React.ReactNode;
|
||||
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||
state: ErrorBoundaryState = { hasError: false, error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||
this.props.onError?.(error, errorInfo);
|
||||
// Log to error reporting service
|
||||
console.error('Error caught:', error, errorInfo);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback || (
|
||||
<div className="p-4 bg-red-50 border border-red-200 rounded">
|
||||
<h2 className="text-red-800 font-bold">Something went wrong</h2>
|
||||
<p className="text-red-600">{this.state.error?.message}</p>
|
||||
<button
|
||||
onClick={() => this.setState({ hasError: false, error: null })}
|
||||
className="mt-2 px-4 py-2 bg-red-600 text-white rounded"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
<ErrorBoundary
|
||||
fallback={<ErrorFallback />}
|
||||
onError={(error) => trackError(error)}
|
||||
>
|
||||
<MyComponent />
|
||||
</ErrorBoundary>
|
||||
```
|
||||
|
||||
### Suspense with Error Boundary
|
||||
|
||||
```tsx
|
||||
function DataComponent() {
|
||||
return (
|
||||
<ErrorBoundary fallback={<ErrorMessage />}>
|
||||
<Suspense fallback={<LoadingSpinner />}>
|
||||
<AsyncDataLoader />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
### Avoid: Inline Object/Array Creation in JSX
|
||||
|
||||
```tsx
|
||||
// BAD - Creates new object every render, causes re-renders
|
||||
<Component style={{ color: 'red' }} items={[1, 2, 3]} />
|
||||
|
||||
// GOOD - Define outside or use useMemo
|
||||
const style = { color: 'red' };
|
||||
const items = [1, 2, 3];
|
||||
<Component style={style} items={items} />
|
||||
|
||||
// Or with useMemo for dynamic values
|
||||
const style = useMemo(() => ({ color: theme.primary }), [theme.primary]);
|
||||
```
|
||||
|
||||
### Avoid: Index as Key for Dynamic Lists
|
||||
|
||||
```tsx
|
||||
// BAD - Index keys break with reordering/filtering
|
||||
{items.map((item, index) => (
|
||||
<Item key={index} data={item} />
|
||||
))}
|
||||
|
||||
// GOOD - Use stable unique ID
|
||||
{items.map(item => (
|
||||
<Item key={item.id} data={item} />
|
||||
))}
|
||||
```
|
||||
|
||||
### Avoid: Prop Drilling
|
||||
|
||||
```tsx
|
||||
// BAD - Passing props through many levels
|
||||
<App user={user}>
|
||||
<Layout user={user}>
|
||||
<Sidebar user={user}>
|
||||
<UserInfo user={user} />
|
||||
</Sidebar>
|
||||
</Layout>
|
||||
</App>
|
||||
|
||||
// GOOD - Use Context
|
||||
const UserContext = createContext<User | null>(null);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<UserContext.Provider value={user}>
|
||||
<Layout>
|
||||
<Sidebar>
|
||||
<UserInfo />
|
||||
</Sidebar>
|
||||
</Layout>
|
||||
</UserContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function UserInfo() {
|
||||
const user = useContext(UserContext);
|
||||
return <div>{user?.name}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### Avoid: Mutating State Directly
|
||||
|
||||
```tsx
|
||||
// BAD - Mutates state directly
|
||||
const addItem = (item: Item) => {
|
||||
items.push(item); // WRONG
|
||||
setItems(items); // Won't trigger re-render
|
||||
};
|
||||
|
||||
// GOOD - Create new array
|
||||
const addItem = (item: Item) => {
|
||||
setItems(prev => [...prev, item]);
|
||||
};
|
||||
|
||||
// GOOD - For objects
|
||||
const updateUser = (field: string, value: string) => {
|
||||
setUser(prev => ({ ...prev, [field]: value }));
|
||||
};
|
||||
```
|
||||
|
||||
### Avoid: useEffect for Derived State
|
||||
|
||||
```tsx
|
||||
// BAD - Unnecessary effect and extra render
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
setTotal(items.reduce((sum, item) => sum + item.price, 0));
|
||||
}, [items]);
|
||||
|
||||
// GOOD - Compute during render
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const total = items.reduce((sum, item) => sum + item.price, 0);
|
||||
|
||||
// Or useMemo for expensive calculations
|
||||
const total = useMemo(
|
||||
() => items.reduce((sum, item) => sum + item.price, 0),
|
||||
[items]
|
||||
);
|
||||
```
|
||||
@@ -0,0 +1,121 @@
|
||||
# Design System: Taste Standard
|
||||
**Skill:** stitch-design-taste
|
||||
|
||||
---
|
||||
|
||||
## Configuration — Set Your Style
|
||||
Adjust these dials before using this design system. They control how creative, dense, and animated the output should be. Pick the level that fits your project.
|
||||
|
||||
| Dial | Level | Description |
|
||||
|------|-------|-------------|
|
||||
| **Creativity** | `8` | `1` = Ultra-minimal, Swiss, silent, monochrome. `5` = Balanced, clean but with personality. `10` = Expressive, editorial, bold typography experiments, inline images in headlines, strong asymmetry. Default: `8` |
|
||||
| **Density** | `4` | `1` = Gallery-airy, massive whitespace. `5` = Balanced sections. `10` = Cockpit-dense, data-heavy. Default: `4` |
|
||||
| **Variance** | `8` | `1` = Predictable, symmetric grids. `5` = Subtle offsets. `10` = Artsy chaotic, no two sections alike. Default: `8` |
|
||||
| **Motion Intent** | `6` | `1` = Static, no animation noted. `5` = Subtle hover/entrance cues. `10` = Cinematic orchestration noted in every component. Default: `6` |
|
||||
|
||||
> **How to use:** Change the numbers above to match your project's vibe. At **Creativity 1–3**, the system produces clean, quiet, Notion-like interfaces. At **Creativity 7–10**, expect inline image typography, dramatic scale contrast, and strong editorial layouts. The rest of the rules below adapt to your chosen levels.
|
||||
|
||||
---
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
A restrained, gallery-airy interface with confident asymmetric layouts and fluid spring-physics motion. The atmosphere is clinical yet warm — like a well-lit architecture studio where every element earns its place through function. Density is balanced (Level 4), variance runs high (Level 8) to prevent symmetrical boredom, and motion is fluid but never theatrical (Level 6). The overall impression: expensive, intentional, alive.
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
- **Canvas White** (#F9FAFB) — Primary background surface. Warm-neutral, never clinical blue-white
|
||||
- **Pure Surface** (#FFFFFF) — Card and container fill. Used with whisper shadow for elevation
|
||||
- **Charcoal Ink** (#18181B) — Primary text. Zinc-950 depth — never pure black
|
||||
- **Steel Secondary** (#71717A) — Body text, descriptions, metadata. Zinc-500 warmth
|
||||
- **Muted Slate** (#94A3B8) — Tertiary text, timestamps, disabled states
|
||||
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, structural 1px lines. Semi-transparent for depth
|
||||
- **Diffused Shadow** (rgba(0,0,0,0.05)) — Card elevation. Wide-spreading, 40px blur, -15px offset. Never harsh
|
||||
|
||||
### Accent Selection (Pick ONE per project)
|
||||
- **Emerald Signal** (#10B981) — For growth, success, positive data dashboards
|
||||
- **Electric Blue** (#3B82F6) — For productivity, SaaS, developer tools
|
||||
- **Deep Rose** (#E11D48) — For creative, editorial, fashion-adjacent projects
|
||||
- **Amber Warmth** (#F59E0B) — For community, social, warm-toned products
|
||||
|
||||
### Banned Colors
|
||||
- Purple/Violet neon gradients — the "AI Purple" aesthetic
|
||||
- Pure Black (#000000) — always Off-Black or Zinc-950
|
||||
- Oversaturated accents above 80% saturation
|
||||
- Mixed warm/cool gray systems within one project
|
||||
|
||||
## 3. Typography Rules
|
||||
- **Display:** `Geist`, `Satoshi`, `Cabinet Grotesk`, or `Outfit` — Track-tight (`-0.025em`), controlled fluid scale, weight-driven hierarchy (700–900). Not screaming. Leading compressed (`1.1`). Alternatives forced — `Inter` is BANNED for premium contexts
|
||||
- **Body:** Same family at weight 400 — Relaxed leading (`1.65`), 65ch max-width, Steel Secondary color (#71717A)
|
||||
- **Mono:** `Geist Mono` or `JetBrains Mono` — For code blocks, metadata, timestamps. When density exceeds Level 7, all numbers switch to monospace
|
||||
- **Scale:** Display at `clamp(2.25rem, 5vw, 3.75rem)`. Body at `1rem/1.125rem`. Mono metadata at `0.8125rem`
|
||||
|
||||
### Banned Fonts
|
||||
- `Inter` — banned everywhere in premium/creative contexts
|
||||
- Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) — BANNED. If serif is needed for editorial/creative, use only distinctive modern serifs like `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Never use default browser serif stacks. Serif is always BANNED in dashboards or software UIs regardless
|
||||
|
||||
## 4. Component Stylings
|
||||
* **Buttons:** Flat surface, no outer glow. Primary: accent fill with white text. Secondary: ghost/outline. Active state: `-1px translateY` or `scale(0.98)` for tactile push. Hover: subtle background shift, never glow
|
||||
* **Cards/Containers:** Generously rounded corners (`2.5rem`). Pure white fill. Whisper border (`1px`, semi-transparent). Diffused shadow (`0 20px 40px -15px rgba(0,0,0,0.05)`). Internal padding `2rem–2.5rem`. Used ONLY when elevation communicates hierarchy — high-density layouts replace cards with `border-top` dividers or negative space
|
||||
* **Inputs/Forms:** Label positioned above input. Helper text optional. Error text below in Deep Rose. Focus ring in accent color, `2px` offset. No floating labels. Standard `0.5rem` gap between label-input-error stack
|
||||
* **Navigation:** Sleek, sticky. Icons scale on hover (Dock Magnification optional). No hamburger on desktop. Clean horizontal with generous spacing
|
||||
* **Loaders:** Skeletal shimmer matching exact layout dimensions and rounded corners. Shifting light reflection across placeholder shapes. Never circular spinners
|
||||
* **Empty States:** Composed illustration or icon composition with guidance text. Never just "No data found"
|
||||
* **Error States:** Inline, contextual. Red accent underline or border. Clear recovery action
|
||||
|
||||
## 5. Hero Section
|
||||
The Hero is the first impression — it must be striking, creative, and never generic.
|
||||
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Example: "We build [photo of hands typing] digital [photo of screen] products" — images sit inline at type-height, rounded, acting as visual punctuation between words. This is the signature creative technique
|
||||
- **No Overlapping Elements:** Text must never overlap images or other text. Every element has its own clear spatial zone. No z-index stacking of content layers, no absolute-positioned headlines over images. Clean separation always
|
||||
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons, and any instructional UI chrome are BANNED. The user knows how to scroll. Let the content pull them in naturally
|
||||
- **Asymmetric Structure:** Centered Hero layouts are BANNED at this variance level. Use Split Screen (50/50), Left-Aligned text / Right visual, or Asymmetric Whitespace with large empty zones
|
||||
- **CTA Restraint:** Maximum one primary CTA button. No secondary "Learn more" links. No redundant micro-copy below the headline
|
||||
|
||||
## 6. Layout Principles
|
||||
- **Grid-First:** CSS Grid for all structural layouts. Never flexbox percentage math (`calc(33% - 1rem)` is BANNED)
|
||||
- **No Overlapping:** Elements must never overlap each other. No absolute-positioned layers stacking content on content. Every element occupies its own grid cell or flow position. Clean, separated spatial zones
|
||||
- **Feature Sections:** The "3 equal cards in a row" pattern is BANNED. Use 2-column Zig-Zag, asymmetric Bento grids (2fr 1fr 1fr), or horizontal scroll galleries
|
||||
- **Containment:** All content within `max-width: 1400px`, centered. Generous horizontal padding (`1rem` mobile, `2rem` tablet, `4rem` desktop)
|
||||
- **Full-Height:** Use `min-height: 100dvh` — never `height: 100vh` (iOS Safari address bar jump)
|
||||
- **Bento Architecture:** For feature grids, use Row 1: 3 columns | Row 2: 2 columns (70/30 split). Each tile contains a perpetual micro-animation
|
||||
|
||||
## 7. Responsive Rules
|
||||
Every screen must work flawlessly across all viewports. **Responsive is not optional — it is a hard requirement. Every single element must be tested at 375px, 768px, and 1440px.**
|
||||
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to a strict single column. `width: 100%`, `padding: 1rem`, `gap: 1.5rem`. No exceptions
|
||||
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure. All elements must fit within viewport width. If any element causes horizontal scroll, the design is broken
|
||||
- **Typography Scaling:** Headlines scale down gracefully via `clamp()`. Body text stays `1rem` minimum. Never shrink body below `14px`. Headlines must remain readable on 375px screens
|
||||
- **Touch Targets:** All interactive elements minimum `44px` tap target. Generous spacing between clickable items. Buttons must be full-width on mobile
|
||||
- **Image Behavior:** Hero and inline images scale proportionally. Inline typography images (photos between words) stack below the headline on mobile instead of inline
|
||||
- **Navigation:** Desktop horizontal nav collapses to a clean mobile menu (slide-in or full-screen overlay). No tiny hamburger icons without labels
|
||||
- **Cards & Grids:** Bento grids and asymmetric layouts revert to stacked single-column cards with full-width. Maintain internal padding (`1rem`)
|
||||
- **Spacing Consistency:** Vertical section gaps reduce proportionally on mobile (`clamp(3rem, 8vw, 6rem)`). Never cramped, never excessively airy
|
||||
- **Testing Viewports:** Designs must be verified at: `375px` (iPhone SE), `390px` (iPhone 14), `768px` (iPad), `1024px` (small laptop), `1440px` (desktop)
|
||||
|
||||
## 8. Motion & Interaction (Code-Phase Intent)
|
||||
> **Note:** Stitch generates static screens — it does not animate. This section documents the **intended motion behavior** so that the coding agent (Antigravity, Cursor, etc.) knows exactly how to implement animations when building the exported design into a live product.
|
||||
|
||||
- **Physics Engine:** Spring-based exclusively. `stiffness: 100, damping: 20`. No linear easing anywhere. Premium, weighty feel on all interactive elements
|
||||
- **Perpetual Micro-Loops:** Every active dashboard component has an infinite-loop state — Pulse on status dots, Typewriter on search bars, Float on feature icons, Shimmer on loading states
|
||||
- **Staggered Orchestration:** Lists and grids mount with cascaded delays (`animation-delay: calc(var(--index) * 100ms)`). Waterfall reveals, never instant mount
|
||||
- **Layout Transitions:** Smooth re-ordering via shared element IDs. Items swap positions with physics, simulating real-time intelligence
|
||||
- **Hardware Rules:** Animate ONLY `transform` and `opacity`. Never `top`, `left`, `width`, `height`. Grain/noise filters on fixed, pointer-events-none pseudo-elements only
|
||||
- **Performance:** CPU-heavy perpetual animations isolated in microscopic leaf components. Never trigger parent re-renders. Target 60fps minimum
|
||||
|
||||
## 9. Anti-Patterns (Banned)
|
||||
- No emojis — anywhere in UI, code, or alt text
|
||||
- No `Inter` font — use `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`
|
||||
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — if serif is needed, use distinctive modern serifs only (`Fraunces`, `Instrument Serif`)
|
||||
- No pure black (`#000000`) — Off-Black or Zinc-950 only
|
||||
- No neon outer glows or default box-shadow glows
|
||||
- No oversaturated accent colors above 80%
|
||||
- No excessive gradient text on large headers
|
||||
- No custom mouse cursors
|
||||
- No overlapping elements — text never overlaps images or other content. Clean spatial separation always
|
||||
- No 3-column equal card layouts for features
|
||||
- No centered Hero sections (at this variance level)
|
||||
- No filler UI text: "Scroll to explore", "Swipe down", "Discover more below", scroll arrows, bouncing chevrons — all BANNED
|
||||
- No generic names: "John Doe", "Sarah Chan", "Acme", "Nexus", "SmartFlow"
|
||||
- No fake round numbers: `99.99%`, `50%`, `1234567` — use organic data: `47.2%`, `+1 (312) 847-1928`
|
||||
- No AI copywriting clichés: "Elevate", "Seamless", "Unleash", "Next-Gen", "Revolutionize"
|
||||
- No broken Unsplash links — use `picsum.photos/seed/{id}/800/600` or SVG UI Avatars
|
||||
- No generic `shadcn/ui` defaults — customize radii, colors, shadows to match this system
|
||||
- No `z-index` spam — use only for Navbar, Modal, Overlay layer contexts
|
||||
- No `h-screen` — always `min-h-[100dvh]`
|
||||
- No circular loading spinners — skeletal shimmer only
|
||||
@@ -0,0 +1,184 @@
|
||||
---
|
||||
name: stitch-design-taste
|
||||
description: Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance.
|
||||
---
|
||||
|
||||
# Stitch Design Taste — Semantic Design System Skill
|
||||
|
||||
## Overview
|
||||
This skill generates `DESIGN.md` files optimized for Google Stitch screen generation. It translates the battle-tested anti-slop frontend engineering directives into Stitch's native semantic design language — descriptive, natural-language rules paired with precise values that Stitch's AI agent can interpret to produce premium, non-generic interfaces.
|
||||
|
||||
The generated `DESIGN.md` serves as the **single source of truth** for prompting Stitch to generate new screens that align with a curated, high-agency design language. Stitch interprets design through **"Visual Descriptions"** supported by specific color values, typography specs, and component behaviors.
|
||||
|
||||
## Prerequisites
|
||||
- Access to Google Stitch via [labs.google.com/stitch](https://labs.google.com/stitch)
|
||||
- Optionally: Stitch MCP Server for programmatic integration with Cursor, Antigravity, or Gemini CLI
|
||||
|
||||
## The Goal
|
||||
Generate a `DESIGN.md` file that encodes:
|
||||
1. **Visual atmosphere** — the mood, density, and design philosophy
|
||||
2. **Color calibration** — neutrals, accents, and banned patterns with hex codes
|
||||
3. **Typographic architecture** — font stacks, scale hierarchy, and anti-patterns
|
||||
4. **Component behaviors** — buttons, cards, inputs with interaction states
|
||||
5. **Layout principles** — grid systems, spacing philosophy, responsive strategy
|
||||
6. **Motion philosophy** — animation engine specs, spring physics, perpetual micro-interactions
|
||||
7. **Anti-patterns** — explicit list of banned AI design clichés
|
||||
|
||||
## Analysis & Synthesis Instructions
|
||||
|
||||
### 1. Define the Atmosphere
|
||||
Evaluate the target project's intent. Use evocative adjectives from the taste spectrum:
|
||||
- **Density:** "Art Gallery Airy" (1–3) → "Daily App Balanced" (4–7) → "Cockpit Dense" (8–10)
|
||||
- **Variance:** "Predictable Symmetric" (1–3) → "Offset Asymmetric" (4–7) → "Artsy Chaotic" (8–10)
|
||||
- **Motion:** "Static Restrained" (1–3) → "Fluid CSS" (4–7) → "Cinematic Choreography" (8–10)
|
||||
|
||||
Default baseline: Variance 8, Motion 6, Density 4. Adapt dynamically based on user's vibe description.
|
||||
|
||||
### 2. Map the Color Palette
|
||||
For each color provide: **Descriptive Name** + **Hex Code** + **Functional Role**.
|
||||
|
||||
**Mandatory constraints:**
|
||||
- Maximum 1 accent color. Saturation below 80%
|
||||
- The "AI Purple/Blue Neon" aesthetic is strictly BANNED — no purple button glows, no neon gradients
|
||||
- Use absolute neutral bases (Zinc/Slate) with high-contrast singular accents
|
||||
- Stick to one palette for the entire output — no warm/cool gray fluctuation
|
||||
- Never use pure black (`#000000`) — use Off-Black, Zinc-950, or Charcoal
|
||||
|
||||
### 3. Establish Typography Rules
|
||||
- **Display/Headlines:** Track-tight, controlled scale. Not screaming. Hierarchy through weight and color, not just massive size
|
||||
- **Body:** Relaxed leading, max 65 characters per line
|
||||
- **Font Selection:** `Inter` is BANNED for premium/creative contexts. Force unique character: `Geist`, `Outfit`, `Cabinet Grotesk`, or `Satoshi`
|
||||
- **Serif Ban:** Generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`, `Palatino`) are BANNED. If serif is needed for editorial/creative contexts, use only distinctive modern serifs: `Fraunces`, `Gambarino`, `Editorial New`, or `Instrument Serif`. Serif is always BANNED in dashboards or software UIs
|
||||
- **Dashboard Constraint:** Use Sans-Serif pairings exclusively (`Geist` + `Geist Mono` or `Satoshi` + `JetBrains Mono`)
|
||||
- **High-Density Override:** When density exceeds 7, all numbers must use Monospace
|
||||
|
||||
### 4. Define the Hero Section
|
||||
The Hero is the first impression and must be creative, striking, and never generic:
|
||||
- **Inline Image Typography:** Embed small, contextual photos or visuals directly between words or letters in the headline. Images sit inline at type-height, rounded, acting as visual punctuation. This is the signature creative technique
|
||||
- **No Overlapping:** Text must never overlap images or other text. Every element occupies its own clean spatial zone
|
||||
- **No Filler Text:** "Scroll to explore", "Swipe down", scroll arrow icons, bouncing chevrons are BANNED. The content should pull users in naturally
|
||||
- **Asymmetric Structure:** Centered Hero layouts BANNED when variance exceeds 4
|
||||
- **CTA Restraint:** Maximum one primary CTA. No secondary "Learn more" links
|
||||
|
||||
### 5. Describe Component Stylings
|
||||
For each component type, describe shape, color, shadow depth, and interaction behavior:
|
||||
- **Buttons:** Tactile push feedback on active state. No neon outer glows. No custom mouse cursors
|
||||
- **Cards:** Use ONLY when elevation communicates hierarchy. Tint shadows to background hue. For high-density layouts, replace cards with border-top dividers or negative space
|
||||
- **Inputs/Forms:** Label above input, helper text optional, error text below. Standard gap spacing
|
||||
- **Loading States:** Skeletal loaders matching layout dimensions — no generic circular spinners
|
||||
- **Empty States:** Composed compositions indicating how to populate data
|
||||
- **Error States:** Clear, inline error reporting
|
||||
|
||||
### 6. Define Layout Principles
|
||||
- No overlapping elements — every element occupies its own clear spatial zone. No absolute-positioned content stacking
|
||||
- Centered Hero sections are BANNED when variance exceeds 4 — force Split Screen, Left-Aligned, or Asymmetric Whitespace
|
||||
- The generic "3 equal cards horizontally" feature row is BANNED — use 2-column Zig-Zag, asymmetric grid, or horizontal scroll
|
||||
- CSS Grid over Flexbox math — never use `calc()` percentage hacks
|
||||
- Contain layouts using max-width constraints (e.g., 1400px centered)
|
||||
- Full-height sections must use `min-h-[100dvh]` — never `h-screen` (iOS Safari catastrophic jump)
|
||||
|
||||
### 7. Define Responsive Rules
|
||||
Every design must work across all viewports:
|
||||
- **Mobile-First Collapse (< 768px):** All multi-column layouts collapse to single column. No exceptions
|
||||
- **No Horizontal Scroll:** Horizontal overflow on mobile is a critical failure
|
||||
- **Typography Scaling:** Headlines scale via `clamp()`. Body text minimum `1rem`/`14px`
|
||||
- **Touch Targets:** All interactive elements minimum `44px` tap target
|
||||
- **Image Behavior:** Inline typography images (photos between words) stack below headline on mobile
|
||||
- **Navigation:** Desktop horizontal nav collapses to clean mobile menu
|
||||
- **Spacing:** Vertical section gaps reduce proportionally (`clamp(3rem, 8vw, 6rem)`)
|
||||
|
||||
### 8. Encode Motion Philosophy
|
||||
- **Spring Physics default:** `stiffness: 100, damping: 20` — premium, weighty feel. No linear easing
|
||||
- **Perpetual Micro-Interactions:** Every active component should have an infinite loop state (Pulse, Typewriter, Float, Shimmer)
|
||||
- **Staggered Orchestration:** Never mount lists instantly — use cascade delays for waterfall reveals
|
||||
- **Performance:** Animate exclusively via `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. Grain/noise filters on fixed pseudo-elements only
|
||||
|
||||
### 9. List Anti-Patterns (AI Tells)
|
||||
Encode these as explicit "NEVER DO" rules in the DESIGN.md:
|
||||
- No emojis anywhere
|
||||
- No `Inter` font
|
||||
- No generic serif fonts (`Times New Roman`, `Georgia`, `Garamond`) — distinctive modern serifs only if needed
|
||||
- No pure black (`#000000`)
|
||||
- No neon/outer glow shadows
|
||||
- No oversaturated accents
|
||||
- No excessive gradient text on large headers
|
||||
- No custom mouse cursors
|
||||
- No overlapping elements — clean spatial separation always
|
||||
- No 3-column equal card layouts
|
||||
- No generic names ("John Doe", "Acme", "Nexus")
|
||||
- No fake round numbers (`99.99%`, `50%`)
|
||||
- No AI copywriting clichés ("Elevate", "Seamless", "Unleash", "Next-Gen")
|
||||
- No filler UI text: "Scroll to explore", "Swipe down", scroll arrows, bouncing chevrons
|
||||
- No broken Unsplash links — use `picsum.photos` or SVG avatars
|
||||
- No centered Hero sections (for high-variance projects)
|
||||
|
||||
## Output Format (DESIGN.md Structure)
|
||||
|
||||
```markdown
|
||||
# Design System: [Project Title]
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
(Evocative description of the mood, density, variance, and motion intensity.
|
||||
Example: "A restrained, gallery-airy interface with confident asymmetric layouts
|
||||
and fluid spring-physics motion. The atmosphere is clinical yet warm — like a
|
||||
well-lit architecture studio.")
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
- **Canvas White** (#F9FAFB) — Primary background surface
|
||||
- **Pure Surface** (#FFFFFF) — Card and container fill
|
||||
- **Charcoal Ink** (#18181B) — Primary text, Zinc-950 depth
|
||||
- **Muted Steel** (#71717A) — Secondary text, descriptions, metadata
|
||||
- **Whisper Border** (rgba(226,232,240,0.5)) — Card borders, 1px structural lines
|
||||
- **[Accent Name]** (#XXXXXX) — Single accent for CTAs, active states, focus rings
|
||||
(Max 1 accent. Saturation < 80%. No purple/neon.)
|
||||
|
||||
## 3. Typography Rules
|
||||
- **Display:** [Font Name] — Track-tight, controlled scale, weight-driven hierarchy
|
||||
- **Body:** [Font Name] — Relaxed leading, 65ch max-width, neutral secondary color
|
||||
- **Mono:** [Font Name] — For code, metadata, timestamps, high-density numbers
|
||||
- **Banned:** Inter, generic system fonts for premium contexts. Serif fonts banned in dashboards.
|
||||
|
||||
## 4. Component Stylings
|
||||
* **Buttons:** Flat, no outer glow. Tactile -1px translate on active. Accent fill for primary, ghost/outline for secondary.
|
||||
* **Cards:** Generously rounded corners (2.5rem). Diffused whisper shadow. Used only when elevation serves hierarchy. High-density: replace with border-top dividers.
|
||||
* **Inputs:** Label above, error below. Focus ring in accent color. No floating labels.
|
||||
* **Loaders:** Skeletal shimmer matching exact layout dimensions. No circular spinners.
|
||||
* **Empty States:** Composed, illustrated compositions — not just "No data" text.
|
||||
|
||||
## 5. Layout Principles
|
||||
(Grid-first responsive architecture. Asymmetric splits for Hero sections.
|
||||
Strict single-column collapse below 768px. Max-width containment.
|
||||
No flexbox percentage math. Generous internal padding.)
|
||||
|
||||
## 6. Motion & Interaction
|
||||
(Spring physics for all interactive elements. Staggered cascade reveals.
|
||||
Perpetual micro-loops on active dashboard components. Hardware-accelerated
|
||||
transforms only. Isolated Client Components for CPU-heavy animations.)
|
||||
|
||||
## 7. Anti-Patterns (Banned)
|
||||
(Explicit list of forbidden patterns: no emojis, no Inter, no pure black,
|
||||
no neon glows, no 3-column equal grids, no AI copywriting clichés,
|
||||
no generic placeholder names, no broken image links.)
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
- **Be Descriptive:** "Deep Charcoal Ink (#18181B)" — not just "dark text"
|
||||
- **Be Functional:** Explain what each element is used for
|
||||
- **Be Consistent:** Same terminology throughout the document
|
||||
- **Be Precise:** Include exact hex codes, rem values, pixel values in parentheses
|
||||
- **Be Opinionated:** This is not a neutral template — it enforces a specific, premium aesthetic
|
||||
|
||||
## Tips for Success
|
||||
1. Start with the atmosphere — understand the vibe before detailing tokens
|
||||
2. Look for patterns — identify consistent spacing, sizing, and styling
|
||||
3. Think semantically — name colors by purpose, not just appearance
|
||||
4. Consider hierarchy — document how visual weight communicates importance
|
||||
5. Encode the bans — anti-patterns are as important as the rules themselves
|
||||
|
||||
## Common Pitfalls to Avoid
|
||||
- Using technical jargon without translation ("rounded-xl" instead of "generously rounded corners")
|
||||
- Omitting hex codes or using only descriptive names
|
||||
- Forgetting functional roles of design elements
|
||||
- Being too vague in atmosphere descriptions
|
||||
- Ignoring the anti-pattern list — these are what make the output premium
|
||||
- Defaulting to generic "safe" designs instead of enforcing the curated aesthetic
|
||||
Reference in new issue
Block a user