Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
feat: add service period fields to the ui (#241)
Vlad Sazonau5665ba2d20cb
diff --git a/.agents/skills/vercel-composition-patterns/AGENTS.md b/.agents/skills/vercel-composition-patterns/AGENTS.mdnew file mode 100644index 0000000..7c3202d--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/AGENTS.md@@ -0,0 +1,951 @@+# React Composition Patterns++**Version 1.0.0**+Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React codebases using composition. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.++---++## Table of Contents++1. [Component Architecture](#1-component-architecture) — **HIGH**+ - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)+ - 1.2 [Use Compound Components](#12-use-compound-components)+2. [State Management](#2-state-management) — **MEDIUM**+ - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)+ - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)+ - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)+3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**+ - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)+ - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)+4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**+ - 4.1 [React 19 API Changes](#41-react-19-api-changes)++---++## 1. Component Architecture++**Impact: HIGH**++Fundamental patterns for structuring components to avoid prop+proliferation and enable flexible composition.++### 1.1 Avoid Boolean Prop Proliferation++**Impact: CRITICAL (prevents unmaintainable component variants)**++Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize++component behavior. Each boolean doubles possible states and creates++unmaintainable conditional logic. Use composition instead.++**Incorrect: boolean props create exponential complexity**++```tsx+function Composer({+ onSubmit,+ isThread,+ channelId,+ isDMThread,+ dmId,+ isEditing,+ isForwarding,+}: Props) {+ return (+ <form>+ <Header />+ <Input />+ {isDMThread ? (+ <AlsoSendToDMField id={dmId} />+ ) : isThread ? (+ <AlsoSendToChannelField id={channelId} />+ ) : null}+ {isEditing ? (+ <EditActions />+ ) : isForwarding ? (+ <ForwardActions />+ ) : (+ <DefaultActions />+ )}+ <Footer onSubmit={onSubmit} />+ </form>+ );+}+```++**Correct: composition eliminates conditionals**++```tsx+// Channel composer+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Attachments />+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Thread composer - adds "also send to channel" field+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <AlsoSendToChannelField id={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Edit composer - different footer actions+function EditComposer() {+ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ );+}+```++Each variant is explicit about what it renders. We can share internals without++sharing a single monolithic parent.++### 1.2 Use Compound Components++**Impact: HIGH (enables flexible composition without prop drilling)**++Structure complex components as compound components with a shared context. Each++subcomponent accesses shared state via context, not props. Consumers compose the++pieces they need.++**Incorrect: monolithic component with render props**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+ showAttachments,+ showFormatting,+ showEmojis,+}: Props) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {showAttachments && <Attachments />}+ {renderFooter ? (+ renderFooter()+ ) : (+ <Footer>+ {showFormatting && <Formatting />}+ {showEmojis && <Emojis />}+ {renderActions?.()}+ </Footer>+ )}+ </form>+ );+}+```++**Correct: compound components with shared context**++```tsx+const ComposerContext = createContext<ComposerContextValue | null>(null);++function ComposerProvider({ children, state, actions, meta }: ProviderProps) {+ return (+ <ComposerContext value={{ state, actions, meta }}>+ {children}+ </ComposerContext>+ );+}++function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>;+}++function ComposerInput() {+ const {+ state,+ actions: { update },+ meta: { inputRef },+ } = use(ComposerContext);+ return (+ <TextInput+ ref={inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ );+}++function ComposerSubmit() {+ const {+ actions: { submit },+ } = use(ComposerContext);+ return <Button onPress={submit}>Send</Button>;+}++// Export as compound component+const Composer = {+ Provider: ComposerProvider,+ Frame: ComposerFrame,+ Input: ComposerInput,+ Submit: ComposerSubmit,+ Header: ComposerHeader,+ Footer: ComposerFooter,+ Attachments: ComposerAttachments,+ Formatting: ComposerFormatting,+ Emojis: ComposerEmojis,+};+```++**Usage:**++```tsx+<Composer.Provider state={state} actions={actions} meta={meta}>+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+</Composer.Provider>+```++Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.++---++## 2. State Management++**Impact: MEDIUM**++Patterns for lifting state and managing shared context across+composed components.++### 2.1 Decouple State Management from UI++**Impact: MEDIUM (enables swapping state implementations without changing UI)**++The provider component should be the only place that knows how state is managed.++UI components consume the context interface—they don't know if state comes from++useState, Zustand, or a server sync.++**Incorrect: UI coupled to state implementation**++```tsx+function ChannelComposer({ channelId }: { channelId: string }) {+ // UI component knows about global state implementation+ const state = useGlobalChannelState(channelId);+ const { submit, updateInput } = useChannelSync(channelId);++ return (+ <Composer.Frame>+ <Composer.Input+ value={state.input}+ onChange={(text) => sync.updateInput(text)}+ />+ <Composer.Submit onPress={() => sync.submit()} />+ </Composer.Frame>+ );+}+```++**Correct: state management isolated in provider**++```tsx+// Provider handles all state management details+function ChannelProvider({+ channelId,+ children,+}: {+ channelId: string;+ children: React.ReactNode;+}) {+ const { state, update, submit } = useGlobalChannel(channelId);+ const inputRef = useRef(null);++ return (+ <Composer.Provider+ state={state}+ actions={{ update, submit }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ );+}++// UI component only knows about the context interface+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Usage+function Channel({ channelId }: { channelId: string }) {+ return (+ <ChannelProvider channelId={channelId}>+ <ChannelComposer />+ </ChannelProvider>+ );+}+```++**Different providers, same UI:**++```tsx+// Local state for ephemeral forms+function ForwardMessageProvider({ children }) {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ >+ {children}+ </Composer.Provider>+ );+}++// Global synced state for channels+function ChannelProvider({ channelId, children }) {+ const { state, update, submit } = useGlobalChannel(channelId);++ return (+ <Composer.Provider state={state} actions={{ update, submit }}>+ {children}+ </Composer.Provider>+ );+}+```++The same `Composer.Input` component works with both providers because it only++depends on the context interface, not the implementation.++### 2.2 Define Generic Context Interfaces for Dependency Injection++**Impact: HIGH (enables dependency-injectable state across use-cases)**++Define a **generic interface** for your component context with three parts:++`state`, `actions`, and `meta`. This interface is a contract that any provider++can implement—enabling the same UI components to work with completely different++state implementations.++**Core principle:** Lift state, compose internals, make state++dependency-injectable.++**Incorrect: UI coupled to specific state implementation**++```tsx+function ComposerInput() {+ // Tightly coupled to a specific hook+ const { input, setInput } = useChannelComposerState();+ return <TextInput value={input} onChangeText={setInput} />;+}+```++**Correct: generic interface enables dependency injection**++```tsx+// Define a GENERIC interface that any provider can implement+interface ComposerState {+ input: string;+ attachments: Attachment[];+ isSubmitting: boolean;+}++interface ComposerActions {+ update: (updater: (state: ComposerState) => ComposerState) => void;+ submit: () => void;+}++interface ComposerMeta {+ inputRef: React.RefObject<TextInput>;+}++interface ComposerContextValue {+ state: ComposerState;+ actions: ComposerActions;+ meta: ComposerMeta;+}++const ComposerContext = createContext<ComposerContextValue | null>(null);+```++**UI components consume the interface, not the implementation:**++```tsx+function ComposerInput() {+ const {+ state,+ actions: { update },+ meta,+ } = use(ComposerContext);++ // This component works with ANY provider that implements the interface+ return (+ <TextInput+ ref={meta.inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ );+}+```++**Different providers implement the same interface:**++```tsx+// Provider A: Local state for ephemeral forms+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState);+ const inputRef = useRef(null);+ const submit = useForwardMessage();++ return (+ <ComposerContext+ value={{+ state,+ actions: { update: setState, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ );+}++// Provider B: Global synced state for channels+function ChannelProvider({ channelId, children }: Props) {+ const { state, update, submit } = useGlobalChannel(channelId);+ const inputRef = useRef(null);++ return (+ <ComposerContext+ value={{+ state,+ actions: { update, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ );+}+```++**The same composed UI works with both:**++```tsx+// Works with ForwardMessageProvider (local state)+<ForwardMessageProvider>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ForwardMessageProvider>++// Works with ChannelProvider (global synced state)+<ChannelProvider channelId="abc">+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ChannelProvider>+```++**Custom UI outside the component can access state and actions:**++```tsx+function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ {/* The composer UI */}+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ </Composer.Footer>+ </Composer.Frame>++ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}+ <MessagePreview />++ {/* Actions at the bottom of the dialog */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ );+}++// This button lives OUTSIDE Composer.Frame but can still submit based on its context!+function ForwardButton() {+ const {+ actions: { submit },+ } = use(ComposerContext);+ return <Button onPress={submit}>Forward</Button>;+}++// This preview lives OUTSIDE Composer.Frame but can read composer's state!+function MessagePreview() {+ const { state } = use(ComposerContext);+ return <Preview message={state.input} attachments={state.attachments} />;+}+```++The provider boundary is what matters—not the visual nesting. Components that++need shared state don't have to be inside the `Composer.Frame`. They just need++to be within the provider.++The `ForwardButton` and `MessagePreview` are not visually inside the composer++box, but they can still access its state and actions. This is the power of++lifting state into providers.++The UI is reusable bits you compose together. The state is dependency-injected++by the provider. Swap the provider, keep the UI.++### 2.3 Lift State into Provider Components++**Impact: HIGH (enables state sharing outside component boundaries)**++Move state management into dedicated provider components. This allows sibling++components outside the main UI to access and modify state without prop drilling++or awkward refs.++**Incorrect: state trapped inside component**++```tsx+function ForwardMessageComposer() {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();++ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer />+ </Composer.Frame>+ );+}++// Problem: How does this button access composer state?+function ForwardMessageDialog() {+ return (+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Needs composer state */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Needs to call submit */}+ </DialogActions>+ </Dialog>+ );+}+```++**Incorrect: useEffect to sync state up**++```tsx+function ForwardMessageDialog() {+ const [input, setInput] = useState("");+ return (+ <Dialog>+ <ForwardMessageComposer onInputChange={setInput} />+ <MessagePreview input={input} />+ </Dialog>+ );+}++function ForwardMessageComposer({ onInputChange }) {+ const [state, setState] = useState(initialState);+ useEffect(() => {+ onInputChange(state.input); // Sync on every change 😬+ }, [state.input]);+}+```++**Incorrect: reading state from ref on submit**++```tsx+function ForwardMessageDialog() {+ const stateRef = useRef(null);+ return (+ <Dialog>+ <ForwardMessageComposer stateRef={stateRef} />+ <ForwardButton onPress={() => submit(stateRef.current)} />+ </Dialog>+ );+}+```++**Correct: state lifted to provider**++```tsx+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();+ const inputRef = useRef(null);++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ );+}++function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview />{" "}+ {/* Custom components can access state and actions */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />{" "}+ {/* Custom components can access state and actions */}+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ );+}++function ForwardButton() {+ const { actions } = use(Composer.Context);+ return <Button onPress={actions.submit}>Forward</Button>;+}+```++The ForwardButton lives outside the Composer.Frame but still has access to the++submit action because it's within the provider. Even though it's a one-off++component, it can still access the composer's state and actions from outside the++UI itself.++**Key insight:** Components that need shared state don't have to be visually++nested inside each other—they just need to be within the same provider.++---++## 3. Implementation Patterns++**Impact: MEDIUM**++Specific techniques for implementing compound components and+context providers.++### 3.1 Create Explicit Component Variants++**Impact: MEDIUM (self-documenting code, no hidden conditionals)**++Instead of one component with many boolean props, create explicit variant++components. Each variant composes the pieces it needs. The code documents++itself.++**Incorrect: one component, many modes**++```tsx+// What does this component actually render?+<Composer+ isThread+ isEditing={false}+ channelId="abc"+ showAttachments+ showFormatting={false}+/>+```++**Correct: explicit variants**++```tsx+// Immediately clear what this renders+<ThreadComposer channelId="abc" />++// Or+<EditMessageComposer messageId="xyz" />++// Or+<ForwardMessageComposer messageId="123" />+```++Each implementation is unique, explicit and self-contained. Yet they can each++use shared parts.++**Implementation:**++```tsx+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <ThreadProvider channelId={channelId}>+ <Composer.Frame>+ <Composer.Input />+ <AlsoSendToChannelField channelId={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ </ThreadProvider>+ );+}++function EditMessageComposer({ messageId }: { messageId: string }) {+ return (+ <EditMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ </EditMessageProvider>+ );+}++function ForwardMessageComposer({ messageId }: { messageId: string }) {+ return (+ <ForwardMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Mentions />+ </Composer.Footer>+ </Composer.Frame>+ </ForwardMessageProvider>+ );+}+```++Each variant is explicit about:++- What provider/state it uses++- What UI elements it includes++- What actions are available++No boolean prop combinations to reason about. No impossible states.++### 3.2 Prefer Composing Children Over Render Props++**Impact: MEDIUM (cleaner composition, better readability)**++Use `children` for composition instead of `renderX` props. Children are more++readable, compose naturally, and don't require understanding callback++signatures.++**Incorrect: render props**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+}: {+ renderHeader?: () => React.ReactNode;+ renderFooter?: () => React.ReactNode;+ renderActions?: () => React.ReactNode;+}) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {renderFooter ? renderFooter() : <DefaultFooter />}+ {renderActions?.()}+ </form>+ );+}++// Usage is awkward and inflexible+return (+ <Composer+ renderHeader={() => <CustomHeader />}+ renderFooter={() => (+ <>+ <Formatting />+ <Emojis />+ </>+ )}+ renderActions={() => <SubmitButton />}+ />+);+```++**Correct: compound components with children**++```tsx+function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>;+}++function ComposerFooter({ children }: { children: React.ReactNode }) {+ return <footer className="flex">{children}</footer>;+}++// Usage is flexible+return (+ <Composer.Frame>+ <CustomHeader />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <SubmitButton />+ </Composer.Footer>+ </Composer.Frame>+);+```++**When render props are appropriate:**++```tsx+// Render props work well when you need to pass data back+<List+ data={items}+ renderItem={({ item, index }) => <Item item={item} index={index} />}+/>+```++Use render props when the parent needs to provide data or state to the child.++Use children when composing static structure.++---++## 4. React 19 APIs++**Impact: MEDIUM**++React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.++### 4.1 React 19 API Changes++**Impact: MEDIUM (cleaner component definitions and context usage)**++> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.++In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.++**Incorrect: forwardRef in React 19**++```tsx+const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {+ return <TextInput ref={ref} {...props} />;+});+```++**Correct: ref as a regular prop**++```tsx+function ComposerInput({+ ref,+ ...props+}: Props & { ref?: React.Ref<TextInput> }) {+ return <TextInput ref={ref} {...props} />;+}+```++**Incorrect: useContext in React 19**++```tsx+const value = useContext(MyContext);+```++**Correct: use instead of useContext**++```tsx+const value = use(MyContext);+```++`use()` can also be called conditionally, unlike `useContext()`.++---++## References++1. [https://react.dev](https://react.dev)+2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)+3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)diff --git a/.agents/skills/vercel-composition-patterns/README.md b/.agents/skills/vercel-composition-patterns/README.mdnew file mode 100644index 0000000..01f359b--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/README.md@@ -0,0 +1,60 @@+# React Composition Patterns++A structured repository for React composition patterns that scale. These+patterns help avoid boolean prop proliferation by using compound components,+lifting state, and composing internals.++## Structure++- `rules/` - Individual rule files (one per rule)+ - `_sections.md` - Section metadata (titles, impacts, descriptions)+ - `_template.md` - Template for creating new rules+ - `area-description.md` - Individual rule files+- `metadata.json` - Document metadata (version, organization, abstract)+- **`AGENTS.md`** - Compiled output (generated)++## Rules++### Component Architecture (CRITICAL)++- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize+ behavior+- `architecture-compound-components.md` - Structure as compound components with+ shared context++### State Management (HIGH)++- `state-lift-state.md` - Lift state into provider components+- `state-context-interface.md` - Define clear context interfaces+ (state/actions/meta)+- `state-decouple-implementation.md` - Decouple state management from UI++### Implementation Patterns (MEDIUM)++- `patterns-children-over-render-props.md` - Prefer children over renderX props+- `patterns-explicit-variants.md` - Create explicit component variants++## Core Principles++1. **Composition over configuration** — Instead of adding props, let consumers+ compose+2. **Lift your state** — State in providers, not trapped in components+3. **Compose your internals** — Subcomponents access context, not props+4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer+ with isThread++## Creating a New Rule++1. Copy `rules/_template.md` to `rules/area-description.md`+2. Choose the appropriate area prefix:+ - `architecture-` for Component Architecture+ - `state-` for State Management+ - `patterns-` for Implementation Patterns+3. Fill in the frontmatter and content+4. Ensure you have clear examples with explanations++## Impact Levels++- `CRITICAL` - Foundational patterns, prevents unmaintainable code+- `HIGH` - Significant maintainability improvements+- `MEDIUM` - Good practices for cleaner codediff --git a/.agents/skills/vercel-composition-patterns/SKILL.md b/.agents/skills/vercel-composition-patterns/SKILL.mdnew file mode 100644index 0000000..d8a4672--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/SKILL.md@@ -0,0 +1,89 @@+---+name: vercel-composition-patterns+description:+ React composition patterns that scale. Use when refactoring components with+ boolean prop proliferation, building flexible component libraries, or+ designing reusable APIs. Triggers on tasks involving compound components,+ render props, context providers, or component architecture. Includes React 19+ API changes.+license: MIT+metadata:+ author: vercel+ version: "1.0.0"+---++# React Composition Patterns++Composition patterns for building flexible, maintainable React components. Avoid+boolean prop proliferation by using compound components, lifting state, and+composing internals. These patterns make codebases easier for both humans and AI+agents to work with as they scale.++## When to Apply++Reference these guidelines when:++- Refactoring components with many boolean props+- Building reusable component libraries+- Designing flexible component APIs+- Reviewing component architecture+- Working with compound components or context providers++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+| -------- | ----------------------- | ------ | --------------- |+| 1 | Component Architecture | HIGH | `architecture-` |+| 2 | State Management | MEDIUM | `state-` |+| 3 | Implementation Patterns | MEDIUM | `patterns-` |+| 4 | React 19 APIs | MEDIUM | `react19-` |++## Quick Reference++### 1. Component Architecture (HIGH)++- `architecture-avoid-boolean-props` - Don't add boolean props to customize+ behavior; use composition+- `architecture-compound-components` - Structure complex components with shared+ context++### 2. State Management (MEDIUM)++- `state-decouple-implementation` - Provider is the only place that knows how+ state is managed+- `state-context-interface` - Define generic interface with state, actions, meta+ for dependency injection+- `state-lift-state` - Move state into provider components for sibling access++### 3. Implementation Patterns (MEDIUM)++- `patterns-explicit-variants` - Create explicit variant components instead of+ boolean modes+- `patterns-children-over-render-props` - Use children for composition instead+ of renderX props++### 4. React 19 APIs (MEDIUM)++> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.++- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/architecture-avoid-boolean-props.md+rules/state-context-interface.md+```++Each rule file contains:++- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-composition-patterns/metadata.json b/.agents/skills/vercel-composition-patterns/metadata.jsonnew file mode 100644index 0000000..3470b74--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/metadata.json@@ -0,0 +1,11 @@+{+ "version": "1.0.0",+ "organization": "Engineering",+ "date": "January 2026",+ "abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",+ "references": [+ "https://react.dev",+ "https://react.dev/learn/passing-data-deeply-with-context",+ "https://react.dev/reference/react/use"+ ]+}diff --git a/.agents/skills/vercel-composition-patterns/rules/_sections.md b/.agents/skills/vercel-composition-patterns/rules/_sections.mdnew file mode 100644index 0000000..f921dd4--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/_sections.md@@ -0,0 +1,29 @@+# Sections++This file defines all sections, their ordering, impact levels, and descriptions.+The section ID (in parentheses) is the filename prefix used to group rules.++---++## 1. Component Architecture (architecture)++**Impact:** HIGH+**Description:** Fundamental patterns for structuring components to avoid prop+proliferation and enable flexible composition.++## 2. State Management (state)++**Impact:** MEDIUM+**Description:** Patterns for lifting state and managing shared context across+composed components.++## 3. Implementation Patterns (patterns)++**Impact:** MEDIUM+**Description:** Specific techniques for implementing compound components and+context providers.++## 4. React 19 APIs (react19)++**Impact:** MEDIUM+**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.diff --git a/.agents/skills/vercel-composition-patterns/rules/_template.md b/.agents/skills/vercel-composition-patterns/rules/_template.mdnew file mode 100644index 0000000..119a301--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/_template.md@@ -0,0 +1,24 @@+---+title: Rule Title Here+impact: MEDIUM+impactDescription: brief description of impact+tags: composition, components+---++## Rule Title Here++Brief explanation of the rule and why it matters.++**Incorrect:**++```tsx+// Bad code example+```++**Correct:**++```tsx+// Good code example+```++Reference: [Link](https://example.com)diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.mdnew file mode 100644index 0000000..48ff5c1--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md@@ -0,0 +1,100 @@+---+title: Avoid Boolean Prop Proliferation+impact: CRITICAL+impactDescription: prevents unmaintainable component variants+tags: composition, props, architecture+---++## Avoid Boolean Prop Proliferation++Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize+component behavior. Each boolean doubles possible states and creates+unmaintainable conditional logic. Use composition instead.++**Incorrect (boolean props create exponential complexity):**++```tsx+function Composer({+ onSubmit,+ isThread,+ channelId,+ isDMThread,+ dmId,+ isEditing,+ isForwarding,+}: Props) {+ return (+ <form>+ <Header />+ <Input />+ {isDMThread ? (+ <AlsoSendToDMField id={dmId} />+ ) : isThread ? (+ <AlsoSendToChannelField id={channelId} />+ ) : null}+ {isEditing ? (+ <EditActions />+ ) : isForwarding ? (+ <ForwardActions />+ ) : (+ <DefaultActions />+ )}+ <Footer onSubmit={onSubmit} />+ </form>+ );+}+```++**Correct (composition eliminates conditionals):**++```tsx+// Channel composer+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Attachments />+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Thread composer - adds "also send to channel" field+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <AlsoSendToChannelField id={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Edit composer - different footer actions+function EditComposer() {+ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ );+}+```++Each variant is explicit about what it renders. We can share internals without+sharing a single monolithic parent.diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.mdnew file mode 100644index 0000000..65c784b--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md@@ -0,0 +1,112 @@+---+title: Use Compound Components+impact: HIGH+impactDescription: enables flexible composition without prop drilling+tags: composition, compound-components, architecture+---++## Use Compound Components++Structure complex components as compound components with a shared context. Each+subcomponent accesses shared state via context, not props. Consumers compose the+pieces they need.++**Incorrect (monolithic component with render props):**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+ showAttachments,+ showFormatting,+ showEmojis,+}: Props) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {showAttachments && <Attachments />}+ {renderFooter ? (+ renderFooter()+ ) : (+ <Footer>+ {showFormatting && <Formatting />}+ {showEmojis && <Emojis />}+ {renderActions?.()}+ </Footer>+ )}+ </form>+ );+}+```++**Correct (compound components with shared context):**++```tsx+const ComposerContext = createContext<ComposerContextValue | null>(null);++function ComposerProvider({ children, state, actions, meta }: ProviderProps) {+ return (+ <ComposerContext value={{ state, actions, meta }}>+ {children}+ </ComposerContext>+ );+}++function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>;+}++function ComposerInput() {+ const {+ state,+ actions: { update },+ meta: { inputRef },+ } = use(ComposerContext);+ return (+ <TextInput+ ref={inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ );+}++function ComposerSubmit() {+ const {+ actions: { submit },+ } = use(ComposerContext);+ return <Button onPress={submit}>Send</Button>;+}++// Export as compound component+const Composer = {+ Provider: ComposerProvider,+ Frame: ComposerFrame,+ Input: ComposerInput,+ Submit: ComposerSubmit,+ Header: ComposerHeader,+ Footer: ComposerFooter,+ Attachments: ComposerAttachments,+ Formatting: ComposerFormatting,+ Emojis: ComposerEmojis,+};+```++**Usage:**++```tsx+<Composer.Provider state={state} actions={actions} meta={meta}>+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+</Composer.Provider>+```++Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.mdnew file mode 100644index 0000000..129a249--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md@@ -0,0 +1,87 @@+---+title: Prefer Composing Children Over Render Props+impact: MEDIUM+impactDescription: cleaner composition, better readability+tags: composition, children, render-props+---++## Prefer Children Over Render Props++Use `children` for composition instead of `renderX` props. Children are more+readable, compose naturally, and don't require understanding callback+signatures.++**Incorrect (render props):**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+}: {+ renderHeader?: () => React.ReactNode;+ renderFooter?: () => React.ReactNode;+ renderActions?: () => React.ReactNode;+}) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {renderFooter ? renderFooter() : <DefaultFooter />}+ {renderActions?.()}+ </form>+ );+}++// Usage is awkward and inflexible+return (+ <Composer+ renderHeader={() => <CustomHeader />}+ renderFooter={() => (+ <>+ <Formatting />+ <Emojis />+ </>+ )}+ renderActions={() => <SubmitButton />}+ />+);+```++**Correct (compound components with children):**++```tsx+function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>;+}++function ComposerFooter({ children }: { children: React.ReactNode }) {+ return <footer className="flex">{children}</footer>;+}++// Usage is flexible+return (+ <Composer.Frame>+ <CustomHeader />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <SubmitButton />+ </Composer.Footer>+ </Composer.Frame>+);+```++**When render props are appropriate:**++```tsx+// Render props work well when you need to pass data back+<List+ data={items}+ renderItem={({ item, index }) => <Item item={item} index={index} />}+/>+```++Use render props when the parent needs to provide data or state to the child.+Use children when composing static structure.diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.mdnew file mode 100644index 0000000..509e360--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md@@ -0,0 +1,100 @@+---+title: Create Explicit Component Variants+impact: MEDIUM+impactDescription: self-documenting code, no hidden conditionals+tags: composition, variants, architecture+---++## Create Explicit Component Variants++Instead of one component with many boolean props, create explicit variant+components. Each variant composes the pieces it needs. The code documents+itself.++**Incorrect (one component, many modes):**++```tsx+// What does this component actually render?+<Composer+ isThread+ isEditing={false}+ channelId="abc"+ showAttachments+ showFormatting={false}+/>+```++**Correct (explicit variants):**++```tsx+// Immediately clear what this renders+<ThreadComposer channelId="abc" />++// Or+<EditMessageComposer messageId="xyz" />++// Or+<ForwardMessageComposer messageId="123" />+```++Each implementation is unique, explicit and self-contained. Yet they can each+use shared parts.++**Implementation:**++```tsx+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <ThreadProvider channelId={channelId}>+ <Composer.Frame>+ <Composer.Input />+ <AlsoSendToChannelField channelId={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ </ThreadProvider>+ );+}++function EditMessageComposer({ messageId }: { messageId: string }) {+ return (+ <EditMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ </EditMessageProvider>+ );+}++function ForwardMessageComposer({ messageId }: { messageId: string }) {+ return (+ <ForwardMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Mentions />+ </Composer.Footer>+ </Composer.Frame>+ </ForwardMessageProvider>+ );+}+```++Each variant is explicit about:++- What provider/state it uses+- What UI elements it includes+- What actions are available++No boolean prop combinations to reason about. No impossible states.diff --git a/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md b/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.mdnew file mode 100644index 0000000..b1aaf76--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md@@ -0,0 +1,45 @@+---+title: React 19 API Changes+impact: MEDIUM+impactDescription: cleaner component definitions and context usage+tags: react19, refs, context, hooks+---++## React 19 API Changes++> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.++In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.++**Incorrect (forwardRef in React 19):**++```tsx+const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {+ return <TextInput ref={ref} {...props} />;+});+```++**Correct (ref as a regular prop):**++```tsx+function ComposerInput({+ ref,+ ...props+}: Props & { ref?: React.Ref<TextInput> }) {+ return <TextInput ref={ref} {...props} />;+}+```++**Incorrect (useContext in React 19):**++```tsx+const value = useContext(MyContext);+```++**Correct (use instead of useContext):**++```tsx+const value = use(MyContext);+```++`use()` can also be called conditionally, unlike `useContext()`.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.mdnew file mode 100644index 0000000..6a680ea--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md@@ -0,0 +1,191 @@+---+title: Define Generic Context Interfaces for Dependency Injection+impact: HIGH+impactDescription: enables dependency-injectable state across use-cases+tags: composition, context, state, typescript, dependency-injection+---++## Define Generic Context Interfaces for Dependency Injection++Define a **generic interface** for your component context with three parts:+`state`, `actions`, and `meta`. This interface is a contract that any provider+can implement—enabling the same UI components to work with completely different+state implementations.++**Core principle:** Lift state, compose internals, make state+dependency-injectable.++**Incorrect (UI coupled to specific state implementation):**++```tsx+function ComposerInput() {+ // Tightly coupled to a specific hook+ const { input, setInput } = useChannelComposerState();+ return <TextInput value={input} onChangeText={setInput} />;+}+```++**Correct (generic interface enables dependency injection):**++```tsx+// Define a GENERIC interface that any provider can implement+interface ComposerState {+ input: string;+ attachments: Attachment[];+ isSubmitting: boolean;+}++interface ComposerActions {+ update: (updater: (state: ComposerState) => ComposerState) => void;+ submit: () => void;+}++interface ComposerMeta {+ inputRef: React.RefObject<TextInput>;+}++interface ComposerContextValue {+ state: ComposerState;+ actions: ComposerActions;+ meta: ComposerMeta;+}++const ComposerContext = createContext<ComposerContextValue | null>(null);+```++**UI components consume the interface, not the implementation:**++```tsx+function ComposerInput() {+ const {+ state,+ actions: { update },+ meta,+ } = use(ComposerContext);++ // This component works with ANY provider that implements the interface+ return (+ <TextInput+ ref={meta.inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ );+}+```++**Different providers implement the same interface:**++```tsx+// Provider A: Local state for ephemeral forms+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState);+ const inputRef = useRef(null);+ const submit = useForwardMessage();++ return (+ <ComposerContext+ value={{+ state,+ actions: { update: setState, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ );+}++// Provider B: Global synced state for channels+function ChannelProvider({ channelId, children }: Props) {+ const { state, update, submit } = useGlobalChannel(channelId);+ const inputRef = useRef(null);++ return (+ <ComposerContext+ value={{+ state,+ actions: { update, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ );+}+```++**The same composed UI works with both:**++```tsx+// Works with ForwardMessageProvider (local state)+<ForwardMessageProvider>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ForwardMessageProvider>++// Works with ChannelProvider (global synced state)+<ChannelProvider channelId="abc">+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ChannelProvider>+```++**Custom UI outside the component can access state and actions:**++The provider boundary is what matters—not the visual nesting. Components that+need shared state don't have to be inside the `Composer.Frame`. They just need+to be within the provider.++```tsx+function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ {/* The composer UI */}+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ </Composer.Footer>+ </Composer.Frame>++ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}+ <MessagePreview />++ {/* Actions at the bottom of the dialog */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ );+}++// This button lives OUTSIDE Composer.Frame but can still submit based on its context!+function ForwardButton() {+ const {+ actions: { submit },+ } = use(ComposerContext);+ return <Button onPress={submit}>Forward</Button>;+}++// This preview lives OUTSIDE Composer.Frame but can read composer's state!+function MessagePreview() {+ const { state } = use(ComposerContext);+ return <Preview message={state.input} attachments={state.attachments} />;+}+```++The `ForwardButton` and `MessagePreview` are not visually inside the composer+box, but they can still access its state and actions. This is the power of+lifting state into providers.++The UI is reusable bits you compose together. The state is dependency-injected+by the provider. Swap the provider, keep the UI.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.mdnew file mode 100644index 0000000..d67fd12--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md@@ -0,0 +1,113 @@+---+title: Decouple State Management from UI+impact: MEDIUM+impactDescription: enables swapping state implementations without changing UI+tags: composition, state, architecture+---++## Decouple State Management from UI++The provider component should be the only place that knows how state is managed.+UI components consume the context interface—they don't know if state comes from+useState, Zustand, or a server sync.++**Incorrect (UI coupled to state implementation):**++```tsx+function ChannelComposer({ channelId }: { channelId: string }) {+ // UI component knows about global state implementation+ const state = useGlobalChannelState(channelId);+ const { submit, updateInput } = useChannelSync(channelId);++ return (+ <Composer.Frame>+ <Composer.Input+ value={state.input}+ onChange={(text) => sync.updateInput(text)}+ />+ <Composer.Submit onPress={() => sync.submit()} />+ </Composer.Frame>+ );+}+```++**Correct (state management isolated in provider):**++```tsx+// Provider handles all state management details+function ChannelProvider({+ channelId,+ children,+}: {+ channelId: string;+ children: React.ReactNode;+}) {+ const { state, update, submit } = useGlobalChannel(channelId);+ const inputRef = useRef(null);++ return (+ <Composer.Provider+ state={state}+ actions={{ update, submit }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ );+}++// UI component only knows about the context interface+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ );+}++// Usage+function Channel({ channelId }: { channelId: string }) {+ return (+ <ChannelProvider channelId={channelId}>+ <ChannelComposer />+ </ChannelProvider>+ );+}+```++**Different providers, same UI:**++```tsx+// Local state for ephemeral forms+function ForwardMessageProvider({ children }) {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ >+ {children}+ </Composer.Provider>+ );+}++// Global synced state for channels+function ChannelProvider({ channelId, children }) {+ const { state, update, submit } = useGlobalChannel(channelId);++ return (+ <Composer.Provider state={state} actions={{ update, submit }}>+ {children}+ </Composer.Provider>+ );+}+```++The same `Composer.Input` component works with both providers because it only+depends on the context interface, not the implementation.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.mdnew file mode 100644index 0000000..d683ec1--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md@@ -0,0 +1,127 @@+---+title: Lift State into Provider Components+impact: HIGH+impactDescription: enables state sharing outside component boundaries+tags: composition, state, context, providers+---++## Lift State into Provider Components++Move state management into dedicated provider components. This allows sibling+components outside the main UI to access and modify state without prop drilling+or awkward refs.++**Incorrect (state trapped inside component):**++```tsx+function ForwardMessageComposer() {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();++ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer />+ </Composer.Frame>+ );+}++// Problem: How does this button access composer state?+function ForwardMessageDialog() {+ return (+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Needs composer state */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Needs to call submit */}+ </DialogActions>+ </Dialog>+ );+}+```++**Incorrect (useEffect to sync state up):**++```tsx+function ForwardMessageDialog() {+ const [input, setInput] = useState("");+ return (+ <Dialog>+ <ForwardMessageComposer onInputChange={setInput} />+ <MessagePreview input={input} />+ </Dialog>+ );+}++function ForwardMessageComposer({ onInputChange }) {+ const [state, setState] = useState(initialState);+ useEffect(() => {+ onInputChange(state.input); // Sync on every change 😬+ }, [state.input]);+}+```++**Incorrect (reading state from ref on submit):**++```tsx+function ForwardMessageDialog() {+ const stateRef = useRef(null);+ return (+ <Dialog>+ <ForwardMessageComposer stateRef={stateRef} />+ <ForwardButton onPress={() => submit(stateRef.current)} />+ </Dialog>+ );+}+```++**Correct (state lifted to provider):**++```tsx+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState);+ const forwardMessage = useForwardMessage();+ const inputRef = useRef(null);++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ );+}++function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview />{" "}+ {/* Custom components can access state and actions */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />{" "}+ {/* Custom components can access state and actions */}+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ );+}++function ForwardButton() {+ const { actions } = use(Composer.Context);+ return <Button onPress={actions.submit}>Forward</Button>;+}+```++The ForwardButton lives outside the Composer.Frame but still has access to the+submit action because it's within the provider. Even though it's a one-off+component, it can still access the composer's state and actions from outside the+UI itself.++**Key insight:** Components that need shared state don't have to be visually+nested inside each other—they just need to be within the same provider.diff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.mdindex b953808..55f6420 100644--- a/.agents/skills/vercel-react-best-practices/AGENTS.md+++ b/.agents/skills/vercel-react-best-practices/AGENTS.md@@ -21,26 +21,30 @@ Comprehensive performance optimization guide for React and Next.js applications,## Table of Contents1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**- - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed)- - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization)- - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes)- - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations)- - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries)+ - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags)+ - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed)+ - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization)+ - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes)+ - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations)+ - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries)2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**- 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)- 2.2 [Conditional Module Loading](#22-conditional-module-loading)- 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)- 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)- - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent)+ - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths)+ - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent)3. [Server-Side Performance](#3-server-side-performance) — **HIGH**- 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)- 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)- - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching)- - 3.4 [Hoist Static I/O to Module Level](#34-hoist-static-io-to-module-level)- - 3.5 [Minimize Serialization at RSC Boundaries](#35-minimize-serialization-at-rsc-boundaries)- - 3.6 [Parallel Data Fetching with Component Composition](#36-parallel-data-fetching-with-component-composition)- - 3.7 [Per-Request Deduplication with React.cache()](#37-per-request-deduplication-with-reactcache)- - 3.8 [Use after() for Non-Blocking Operations](#38-use-after-for-non-blocking-operations)+ - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data)+ - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching)+ - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level)+ - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries)+ - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition)+ - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching)+ - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache)+ - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations)4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**- 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)- 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)@@ -50,15 +54,18 @@ Comprehensive performance optimization guide for React and Next.js applications,- 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)- 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)- 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)- - 5.4 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#54-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)- - 5.5 [Extract to Memoized Components](#55-extract-to-memoized-components)- - 5.6 [Narrow Effect Dependencies](#56-narrow-effect-dependencies)- - 5.7 [Put Interaction Logic in Event Handlers](#57-put-interaction-logic-in-event-handlers)- - 5.8 [Subscribe to Derived State](#58-subscribe-to-derived-state)- - 5.9 [Use Functional setState Updates](#59-use-functional-setstate-updates)- - 5.10 [Use Lazy State Initialization](#510-use-lazy-state-initialization)- - 5.11 [Use Transitions for Non-Urgent Updates](#511-use-transitions-for-non-urgent-updates)- - 5.12 [Use useRef for Transient Values](#512-use-useref-for-transient-values)+ - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components)+ - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)+ - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components)+ - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies)+ - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers)+ - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations)+ - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state)+ - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates)+ - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization)+ - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates)+ - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders)+ - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values)6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**- 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)- 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)@@ -67,8 +74,10 @@ Comprehensive performance optimization guide for React and Next.js applications,- 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)- 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)- 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)- - 6.8 [Use Explicit Conditional Rendering](#68-use-explicit-conditional-rendering)- - 6.9 [Use useTransition Over Manual Loading States](#69-use-usetransition-over-manual-loading-states)+ - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags)+ - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering)+ - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints)+ - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states)7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**- 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)- 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)@@ -76,16 +85,19 @@ Comprehensive performance optimization guide for React and Next.js applications,- 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)- 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)- 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)- - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons)- - 7.8 [Early Return from Functions](#78-early-return-from-functions)- - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation)- - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort)- - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups)- - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability)+ - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback)+ - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons)+ - 7.9 [Early Return from Functions](#79-early-return-from-functions)+ - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation)+ - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass)+ - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort)+ - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups)+ - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability)8. [Advanced Patterns](#8-advanced-patterns) — **LOW**- - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount)- - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs)- - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs)+ - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays)+ - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount)+ - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs)+ - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs)---@@ -95,7 +107,40 @@ Comprehensive performance optimization guide for React and Next.js applications,Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.-### 1.1 Defer Await Until Needed+### 1.1 Check Cheap Conditions Before Async Flags++**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)**++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag();++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag();+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.++### 1.2 Defer Await Until Needed**Impact: HIGH (avoids blocking unused code paths)**@@ -171,7 +216,9 @@ async function updateResource(resourceId: string, userId: string) {This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.-### 1.2 Dependency-Based Parallelization+For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).++### 1.3 Dependency-Based Parallelization**Impact: CRITICAL (2-10× improvement)**@@ -219,7 +266,7 @@ We can also create all the promises first, and do `Promise.all()` at the end.Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)-### 1.3 Prevent Waterfall Chains in API Routes+### 1.4 Prevent Waterfall Chains in API Routes**Impact: CRITICAL (2-10× improvement)**@@ -253,7 +300,7 @@ export async function GET(request: Request) {For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).-### 1.4 Promise.all() for Independent Operations+### 1.5 Promise.all() for Independent Operations**Impact: CRITICAL (2-10× improvement)**@@ -277,7 +324,7 @@ const [user, posts, comments] = await Promise.all([]);```-### 1.5 Strategic Suspense Boundaries+### 1.6 Strategic Suspense Boundaries**Impact: HIGH (faster initial paint)**@@ -404,35 +451,27 @@ import { Button, TextField } from "@mui/material";// Loads 2,225 modules, takes ~4.2s extra in dev```-**Correct: imports only what you need**+**Correct - Next.js 13.5+ (recommended):**```tsx-import Check from "lucide-react/dist/esm/icons/check";-import X from "lucide-react/dist/esm/icons/x";-import Menu from "lucide-react/dist/esm/icons/menu";-// Loads only 3 modules (~2KB vs ~1MB)+// Keep the standard imports - Next.js transforms them to direct imports+import { Check, X, Menu } from "lucide-react";+// Full TypeScript support, no manual path wrangling+```+This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsximport Button from "@mui/material/Button";import TextField from "@mui/material/TextField";// Loads only what you use```-**Alternative: Next.js 13.5+**+> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.-```js-// next.config.js - use optimizePackageImports-module.exports = {- experimental: {- optimizePackageImports: ["lucide-react", "@mui/material"],- },-};--// Then you can keep the ergonomic barrel imports:-import { Check, X, Menu } from "lucide-react";-// Automatically transformed to direct imports at build time-```--Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.+These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.@@ -547,7 +586,66 @@ function CodePanel({ code }: { code: string }) {}```-### 2.5 Preload Based on User Intent+### 2.5 Prefer Statically Analyzable Paths++**Impact: HIGH (avoids accidental broad bundles and file traces)**++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:++- Larger server bundles++- Slower builds++- Worse cold starts++- More memory use++**Incorrect: the bundler cannot tell what may be imported**++```ts+const PAGE_MODULES = {+ home: "./pages/home",+ settings: "./pages/settings",+} as const;++const Page = await import(PAGE_MODULES[pageName]);+```++**Correct: use an explicit map of allowed modules**++```ts+const PAGE_MODULES = {+ home: () => import("./pages/home"),+ settings: () => import("./pages/settings"),+} as const;++const Page = await PAGE_MODULES[pageName]();+```++**Incorrect: a 2-value enum still hides the final path from static analysis**++```ts+const baseDir = path.join(process.cwd(), "content/" + contentKind);+```++**Correct: make each final path literal at the callsite**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), "content/blog")+ : path.join(process.cwd(), "content/docs");+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/)++### 2.6 Preload Based on User Intent**Impact: MEDIUM (reduces perceived latency)**@@ -748,7 +846,55 @@ Deduplication works recursively. Impact varies by data type:**Exception:** Pass derived data when transformation is expensive or client doesn't need original.-### 3.3 Cross-Request LRU Caching+### 3.3 Avoid Shared Module State for Request Data++**Impact: HIGH (prevents concurrency bugs and request data leaks)**++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect: request data leaks across concurrent renders**++```tsx+let currentUser: User | null = null;++export default async function Page() {+ currentUser = await auth();+ return <Dashboard />;+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>;+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct: keep request data local to the render tree**++```tsx+export default async function Page() {+ const user = await auth();+ return <Dashboard user={user} />;+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>;+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope++- Shared caches intentionally designed for cross-request reuse and keyed correctly++- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).++### 3.4 Cross-Request LRU Caching**Impact: HIGH (caches across requests)**@@ -785,7 +931,7 @@ Use when sequential user actions hit multiple endpoints needing the same data wiReference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)-### 3.4 Hoist Static I/O to Module Level+### 3.5 Hoist Static I/O to Module Level**Impact: HIGH (avoids repeated file/network I/O per request)**@@ -793,13 +939,119 @@ When loading static assets (fonts, logos, images, config files) in route handler**Incorrect: reads font file on every request**+```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++export async function GET(request: Request) {+ // Runs on EVERY request - expensive!+ const fontData = await fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+ ).then(res => res.arrayBuffer())++ const logoData = await fetch(+ new URL('./images/logo.png', import.meta.url)+ ).then(res => res.arrayBuffer())++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```+**Correct: loads once at module initialization**-**Alternative: synchronous file reads with Node.js fs**+```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'-**General Node.js example: loading config or templates**+// Module-level: runs ONCE when module is first imported+const fontData = fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+).then(res => res.arrayBuffer())++const logoData = fetch(+ new URL('./images/logo.png', import.meta.url)+).then(res => res.arrayBuffer())++export async function GET(request: Request) {+ // Await the already-started promises+ const [font, logo] = await Promise.all([fontData, logoData])++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logo} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: font }] }+ )+}+```++**Correct: synchronous fs at module level**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'+import { readFileSync } from 'fs'+import { join } from 'path'++// Synchronous read at module level - blocks only during module init+const fontData = readFileSync(+ join(process.cwd(), 'public/fonts/Inter.ttf')+)++const logoData = readFileSync(+ join(process.cwd(), 'public/images/logo.png')+)++export async function GET(request: Request) {+ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```-**When to use this pattern:**+**Incorrect: reads config on every call**++```typescript+import fs from "node:fs/promises";++export async function processRequest(data: Data) {+ const config = JSON.parse(await fs.readFile("./config.json", "utf-8"));+ const template = await fs.readFile("./template.html", "utf-8");++ return render(template, data, config);+}+```++**Correct: hoists config and template to module level**++```typescript+import fs from "node:fs/promises";++const configPromise = fs.readFile("./config.json", "utf-8").then(JSON.parse);+const templatePromise = fs.readFile("./template.html", "utf-8");++export async function processRequest(data: Data) {+ const [config, template] = await Promise.all([+ configPromise,+ templatePromise,+ ]);++ return render(template, data, config);+}+```++When to use this pattern:- Loading fonts for OG image generation@@ -811,7 +1063,7 @@ When loading static assets (fonts, logos, images, config files) in route handler- Any static asset that's the same across all requests-**When NOT to use this pattern:**+When not to use this pattern:- Assets that vary per request or user@@ -821,11 +1073,11 @@ When loading static assets (fonts, logos, images, config files) in route handler- Sensitive data that shouldn't persist in memory-**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** Module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.+With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.-**In traditional serverless:** Each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.+In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.-### 3.5 Minimize Serialization at RSC Boundaries+### 3.6 Minimize Serialization at RSC Boundaries**Impact: HIGH (reduces data transfer size)**@@ -859,7 +1111,7 @@ function Profile({ name }: { name: string }) {}```-### 3.6 Parallel Data Fetching with Component Composition+### 3.7 Parallel Data Fetching with Component Composition**Impact: CRITICAL (eliminates server-side waterfalls)**@@ -938,7 +1190,35 @@ export default function Page() {}```-### 3.7 Per-Request Deduplication with React.cache()+### 3.8 Parallel Nested Data Fetching++**Impact: CRITICAL (eliminates server-side waterfalls)**++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect: a single slow item blocks all nested fetches**++```tsx+const chats = await Promise.all(chatIds.map((id) => getChat(id)));++const chatAuthors = await Promise.all(+ chats.map((chat) => getUser(chat.author)),+);+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct: each item chains its own nested fetch**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map((id) => getChat(id).then((chat) => getUser(chat.author))),+);+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.++### 3.9 Per-Request Deduplication with React.cache()**Impact: MEDIUM (deduplicates within request)**@@ -1004,7 +1284,7 @@ Use `React.cache()` to deduplicate these operations across your component tree.Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)-### 3.8 Use after() for Non-Blocking Operations+### 3.10 Use after() for Non-Blocking Operations**Impact: MEDIUM (faster response times)**@@ -1441,7 +1721,87 @@ function Header({ user, notifications }: Props) {}```-### 5.4 Extract Default Non-primitive Parameter Value from Memoized Component to Constant+### 5.4 Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect: remounts on every render**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === "dark" ? "avatar-dark" : "avatar-light"}+ />+ );++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ );++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ );+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct: pass props instead**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === "dark" ? "avatar-dark" : "avatar-light"}+ />+ );+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ );+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ );+}+```++**Symptoms of this bug:**++- Input fields lose focus on every keystroke++- Animations restart unexpectedly++- `useEffect` cleanup/setup runs on every parent render++- Scroll position resets inside the component++### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant**Impact: MEDIUM (restores memoization by using a constant for default value)**@@ -1473,7 +1833,7 @@ const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () =<UserAvatar />```-### 5.5 Extract to Memoized Components+### 5.6 Extract to Memoized Components**Impact: MEDIUM (enables early returns)**@@ -1513,7 +1873,7 @@ function Profile({ user, loading }: Props) {**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.-### 5.6 Narrow Effect Dependencies+### 5.7 Narrow Effect Dependencies**Impact: LOW (minimizes effect re-runs)**@@ -1554,7 +1914,7 @@ useEffect(() => {}, [isMobile]);```-### 5.7 Put Interaction Logic in Event Handlers+### 5.8 Put Interaction Logic in Event Handlers**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**@@ -1595,7 +1955,67 @@ function Form() {Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)-### 5.8 Subscribe to Derived State+### 5.9 Split Combined Hook Computations++**Impact: MEDIUM (avoids recomputing independent steps)**++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect: changing `sortOrder` recomputes filtering**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category);+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price,+ );+ return sorted;+}, [products, category, sortOrder]);+```++**Correct: filtering only recomputes when products or category change**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category],+);++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price,+ ),+ [filteredProducts, sortOrder],+);+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect: both effects run when either dependency changes**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname);+ document.title = `${pageTitle} | My App`;+}, [pathname, pageTitle]);+```++**Correct: effects run independently**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname);+}, [pathname]);++useEffect(() => {+ document.title = `${pageTitle} | My App`;+}, [pageTitle]);+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.++### 5.10 Subscribe to Derived State**Impact: MEDIUM (reduces re-render frequency)**@@ -1620,7 +2040,7 @@ function Sidebar() {}```-### 5.9 Use Functional setState Updates+### 5.11 Use Functional setState Updates**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**@@ -1701,7 +2121,7 @@ function TodoList() {**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.-### 5.10 Use Lazy State Initialization+### 5.12 Use Lazy State Initialization**Impact: MEDIUM (wasted computation on every render)**@@ -1755,7 +2175,7 @@ Use lazy initialization when computing initial values from localStorage/sessionSFor simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.-### 5.11 Use Transitions for Non-Urgent Updates+### 5.13 Use Transitions for Non-Urgent Updates**Impact: MEDIUM (maintains UI responsiveness)**@@ -1791,7 +2211,64 @@ function ScrollTracker() {}```-### 5.12 Use useRef for Transient Values+### 5.14 Use useDeferredValue for Expensive Derived Renders++**Impact: MEDIUM (keeps input responsive during heavy computation)**++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect: input feels laggy while filtering**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState("");+ const filtered = items.filter((item) => fuzzyMatch(item, query));++ return (+ <>+ <input value={query} onChange={(e) => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ );+}+```++**Correct: input stays snappy, results render when ready**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState("");+ const deferredQuery = useDeferredValue(query);+ const filtered = useMemo(+ () => items.filter((item) => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery],+ );+ const isStale = query !== deferredQuery;++ return (+ <>+ <input value={query} onChange={(e) => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ );+}+```++**When to use:**++- Filtering/searching large lists++- Expensive visualizations (charts, graphs) reacting to input++- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [https://react.dev/reference/react/useDeferredValue](https://react.dev/reference/react/useDeferredValue)++### 5.15 Use useRef for Transient Values**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**@@ -2104,7 +2581,57 @@ function Dropdown({ isOpen }: Props) {Avoids expensive re-renders and state loss.-### 6.8 Use Explicit Conditional Rendering+### 6.8 Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order++- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect: blocks rendering**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ );+}+```++**Correct: non-blocking**++```tsx+import Script from "next/script";++export default function Page() {+ return (+ <>+ <Script+ src="https://example.com/analytics.js"+ strategy="afterInteractive"+ />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ );+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++Reference: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)++### 6.9 Use Explicit Conditional Rendering**Impact: LOW (prevents rendering 0 or NaN)**@@ -2132,7 +2659,102 @@ function Badge({ count }: { count: number }) {// When count = 5, renders: <div><span class="badge">5</span></div>```-### 6.9 Use useTransition Over Manual Loading States+### 6.10 Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to++- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server++- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon++- **`preloadModule(href)`**: Fetch an ES module you'll use soon++- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script++- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example: preconnect to third-party APIs**++```tsx+import { preconnect, prefetchDNS } from "react-dom";++export default function App() {+ prefetchDNS("https://analytics.example.com");+ preconnect("https://api.example.com");++ return <main>{/* content */}</main>;+}+```++**Example: preload critical fonts and styles**++```tsx+import { preload, preinit } from "react-dom";++export default function RootLayout({ children }) {+ // Preload font file+ preload("/fonts/inter.woff2", {+ as: "font",+ type: "font/woff2",+ crossOrigin: "anonymous",+ });++ // Fetch and apply critical stylesheet immediately+ preinit("/styles/critical.css", { as: "style" });++ return (+ <html>+ <body>{children}</body>+ </html>+ );+}+```++**Example: preload modules for code-split routes**++```tsx+import { preloadModule, preinitModule } from "react-dom";++function Navigation() {+ const preloadDashboard = () => {+ preloadModule("/dashboard.js", { as: "script" });+ };++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ );+}+```++**When to use each:**++| API | Use case |++|-----|----------|++| `prefetchDNS` | Third-party domains you'll connect to later |++| `preconnect` | APIs or CDNs you'll fetch from immediately |++| `preload` | Critical resources needed for current page |++| `preloadModule` | JS modules for likely next navigation |++| `preinit` | Stylesheets/scripts that must execute early |++| `preinitModule` | ES modules that must execute early |++Reference: [https://react.dev/reference/react-dom#resource-preloading-apis](https://react.dev/reference/react-dom#resource-preloading-apis)++### 6.11 Use useTransition Over Manual Loading States**Impact: LOW (reduces re-renders and improves code clarity)**@@ -2526,7 +3148,113 @@ for (const user of users) {}```-### 7.7 Early Length Check for Array Comparisons+### 7.7 Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect: blocks main thread during user interaction**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query);+ setResults(results);++ // These block the main thread immediately+ analytics.track("search", { query });+ saveToRecentSearches(query);+ prefetchTopResults(results.slice(0, 3));+}+```++**Correct: defers non-critical work to idle time**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query);+ setResults(results);++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track("search", { query });+ });++ requestIdleCallback(() => {+ saveToRecentSearches(query);+ });++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3));+ });+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track("page_view", { path: location.pathname }),+ { timeout: 2000 },+);+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0;++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index]);+ index++;+ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk);+ }+ }++ requestIdleCallback(processChunk);+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork =+ window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1));++scheduleIdleWork(() => {+ // Non-critical work+});+```++**When to use:**++- Analytics and telemetry++- Saving state to localStorage/IndexedDB++- Prefetching resources for likely next actions++- Processing non-urgent data transformations++- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback++- Rendering updates the user is waiting for++- Time-sensitive operations++### 7.8 Early Length Check for Array Comparisons**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**@@ -2575,7 +3303,7 @@ This new approach is more efficient because:- It returns early when a difference is found-### 7.8 Early Return from Functions+### 7.9 Early Return from Functions**Impact: LOW-MEDIUM (avoids unnecessary computation)**@@ -2621,7 +3349,7 @@ function validateUsers(users: User[]) {}```-### 7.9 Hoist RegExp Creation+### 7.10 Hoist RegExp Creation**Impact: LOW-MEDIUM (avoids recreation)**@@ -2662,7 +3390,58 @@ regex.test("foo"); // false, lastIndex = 0Global regex (`/g`) has mutable `lastIndex` state:-### 7.10 Use Loop for Min/Max Instead of Sort+### 7.11 Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect: 2 iterations, intermediate array**++```typescript+const userNames = users+ .map((user) => (user.isActive ? user.name : null))+ .filter(Boolean);+```++**Correct: 1 iteration, no intermediate array**++```typescript+const userNames = users.flatMap((user) => (user.isActive ? [user.name] : []));+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map((r) => (r.success ? r.data.email : null))+ .filter(Boolean);++// After+const emails = responses.flatMap((r) => (r.success ? [r.data.email] : []));++// Parse and filter valid numbers+// Before+const numbers = strings.map((s) => parseInt(s, 10)).filter((n) => !isNaN(n));++// After+const numbers = strings.flatMap((s) => {+ const n = parseInt(s, 10);+ return isNaN(n) ? [] : [n];+});+```++**When to use:**++- Transforming items while filtering some out++- Conditional mapping where some inputs produce no output++- Parsing/validating where invalid inputs should be skipped++### 7.12 Use Loop for Min/Max Instead of Sort**Impact: LOW (O(n) instead of O(n log n))**@@ -2740,7 +3519,7 @@ const max = Math.max(...numbers);This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.-### 7.11 Use Set/Map for O(1) Lookups+### 7.13 Use Set/Map for O(1) Lookups**Impact: LOW-MEDIUM (O(n) to O(1))**@@ -2760,7 +3539,7 @@ const allowedIds = new Set(['a', 'b', 'c', ...])items.filter(item => allowedIds.has(item.id))```-### 7.12 Use toSorted() Instead of sort() for Immutability+### 7.14 Use toSorted() Instead of sort() for Immutability**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**@@ -2825,7 +3604,65 @@ const sorted = [...items].sort((a, b) => a.value - b.value);Advanced patterns for specific cases that require careful implementation.-### 8.1 Initialize App Once, Not Per Mount+### 8.1 Do Not Put Effect Events in Dependency Arrays++**Impact: LOW (avoids unnecessary effect re-runs and lint errors)**++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect: Effect Event added as a dependency**++```tsx+import { useEffect, useEffectEvent } from "react";++function ChatRoom({+ roomId,+ onConnected,+}: {+ roomId: string;+ onConnected: () => void;+}) {+ const handleConnected = useEffectEvent(onConnected);++ useEffect(() => {+ const connection = createConnection(roomId);+ connection.on("connected", handleConnected);+ connection.connect();++ return () => connection.disconnect();+ }, [roomId, handleConnected]);+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct: depend on reactive values, not the Effect Event**++```tsx+import { useEffect, useEffectEvent } from "react";++function ChatRoom({+ roomId,+ onConnected,+}: {+ roomId: string;+ onConnected: () => void;+}) {+ const handleConnected = useEffectEvent(onConnected);++ useEffect(() => {+ const connection = createConnection(roomId);+ connection.on("connected", handleConnected);+ connection.connect();++ return () => connection.disconnect();+ }, [roomId]);+}+```++Reference: [https://react.dev/reference/react/useEffectEvent#effect-event-in-deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)++### 8.2 Initialize App Once, Not Per Mount**Impact: LOW-MEDIUM (avoids duplicate init in development)**@@ -2863,7 +3700,7 @@ function Comp() {Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)-### 8.2 Store Event Handlers in Refs+### 8.3 Store Event Handlers in Refs**Impact: LOW (stable subscriptions)**@@ -2899,7 +3736,7 @@ function useWindowEvent(event: string, handler: (e) => void) {`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.-### 8.3 useEffectEvent for Stable Callback Refs+### 8.4 useEffectEvent for Stable Callback Refs**Impact: LOW (prevents effect re-runs)**diff --git a/.agents/skills/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.mdindex 75e0be3..c1b007e 100644--- a/.agents/skills/vercel-react-best-practices/SKILL.md+++ b/.agents/skills/vercel-react-best-practices/SKILL.md@@ -9,7 +9,7 @@ metadata:# Vercel React Best Practices-Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 58 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.+Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.## When to Apply@@ -38,6 +38,7 @@ Reference these guidelines when:### 1. Eliminating Waterfalls (CRITICAL)+- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values- `async-defer-await` - Move await into branches where actually used- `async-parallel` - Use Promise.all() for independent operations- `async-dependencies` - Use better-all for partial dependencies@@ -47,6 +48,7 @@ Reference these guidelines when:### 2. Bundle Size Optimization (CRITICAL)- `bundle-barrel-imports` - Import directly, avoid barrel files+- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces- `bundle-dynamic-imports` - Use next/dynamic for heavy components- `bundle-defer-third-party` - Load analytics/logging after hydration- `bundle-conditional` - Load modules only when feature is activated@@ -59,8 +61,10 @@ Reference these guidelines when:- `server-cache-lru` - Use LRU cache for cross-request caching- `server-dedup-props` - Avoid duplicate serialization in RSC props- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level+- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR- `server-serialization` - Minimize data passed to client components- `server-parallel-fetching` - Restructure components to parallelize fetches+- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all- `server-after-nonblocking` - Use after() for non-blocking operations### 4. Client-Side Data Fetching (MEDIUM-HIGH)@@ -81,9 +85,12 @@ Reference these guidelines when:- `rerender-functional-setstate` - Use functional setState for stable callbacks- `rerender-lazy-state-init` - Pass function to useState for expensive values- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives+- `rerender-split-combined-hooks` - Split hooks with independent dependencies- `rerender-move-effect-to-event` - Put interaction logic in event handlers- `rerender-transitions` - Use startTransition for non-urgent updates+- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive- `rerender-use-ref-transient-values` - Use refs for transient frequent values+- `rerender-no-inline-components` - Don't define components inside components### 6. Rendering Performance (MEDIUM)@@ -96,6 +103,8 @@ Reference these guidelines when:- `rendering-activity` - Use Activity component for show/hide- `rendering-conditional-render` - Use ternary, not && for conditionals- `rendering-usetransition-loading` - Prefer useTransition for loading state+- `rendering-resource-hints` - Use React DOM resource hints for preloading+- `rendering-script-defer-async` - Use defer or async on script tags### 7. JavaScript Performance (LOW-MEDIUM)@@ -111,9 +120,12 @@ Reference these guidelines when:- `js-min-max-loop` - Use loop for min/max instead of sort- `js-set-map-lookups` - Use Set/Map for O(1) lookups- `js-tosorted-immutable` - Use toSorted() for immutability+- `js-flatmap-filter` - Use flatMap to map and filter in one pass+- `js-request-idle-callback` - Defer non-critical work to browser idle time### 8. Advanced Patterns (LOW)+- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps- `advanced-event-handler-refs` - Store event handlers in refs- `advanced-init-once` - Initialize app once per app load- `advanced-use-latest` - useLatest for stable callback refsdiff --git a/.agents/skills/vercel-react-best-practices/metadata.json b/.agents/skills/vercel-react-best-practices/metadata.jsonnew file mode 100644index 0000000..3bec38b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/metadata.json@@ -0,0 +1,15 @@+{+ "version": "1.0.0",+ "organization": "Vercel Engineering",+ "date": "January 2026",+ "abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",+ "references": [+ "https://react.dev",+ "https://nextjs.org",+ "https://swr.vercel.app",+ "https://github.com/shuding/better-all",+ "https://github.com/isaacs/node-lru-cache",+ "https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",+ "https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"+ ]+}diff --git a/.agents/skills/vercel-react-best-practices/rules/_sections.md b/.agents/skills/vercel-react-best-practices/rules/_sections.mdnew file mode 100644index 0000000..4d20c14--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/_sections.md@@ -0,0 +1,46 @@+# Sections++This file defines all sections, their ordering, impact levels, and descriptions.+The section ID (in parentheses) is the filename prefix used to group rules.++---++## 1. Eliminating Waterfalls (async)++**Impact:** CRITICAL+**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++## 2. Bundle Size Optimization (bundle)++**Impact:** CRITICAL+**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++## 3. Server-Side Performance (server)++**Impact:** HIGH+**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++## 4. Client-Side Data Fetching (client)++**Impact:** MEDIUM-HIGH+**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++## 5. Re-render Optimization (rerender)++**Impact:** MEDIUM+**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++## 6. Rendering Performance (rendering)++**Impact:** MEDIUM+**Description:** Optimizing the rendering process reduces the work the browser needs to do.++## 7. JavaScript Performance (js)++**Impact:** LOW-MEDIUM+**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.++## 8. Advanced Patterns (advanced)++**Impact:** LOW+**Description:** Advanced patterns for specific cases that require careful implementation.diff --git a/.agents/skills/vercel-react-best-practices/rules/_template.md b/.agents/skills/vercel-react-best-practices/rules/_template.mdnew file mode 100644index 0000000..77535dc--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/_template.md@@ -0,0 +1,28 @@+---+title: Rule Title Here+impact: MEDIUM+impactDescription: Optional description of impact (e.g., "20-50% improvement")+tags: tag1, tag2+---++## Rule Title Here++**Impact: MEDIUM (optional impact description)**++Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.++**Incorrect (description of what's wrong):**++```typescript+// Bad code example here+const bad = example();+```++**Correct (description of what's right):**++```typescript+// Good code example here+const good = example();+```++Reference: [Link to documentation or resource](https://example.com)diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.mdnew file mode 100644index 0000000..8bea3b8--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md@@ -0,0 +1,62 @@+---+title: Do Not Put Effect Events in Dependency Arrays+impact: LOW+impactDescription: avoids unnecessary effect re-runs and lint errors+tags: advanced, hooks, useEffectEvent, dependencies, effects+---++## Do Not Put Effect Events in Dependency Arrays++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect (Effect Event added as a dependency):**++```tsx+import { useEffect, useEffectEvent } from "react";++function ChatRoom({+ roomId,+ onConnected,+}: {+ roomId: string;+ onConnected: () => void;+}) {+ const handleConnected = useEffectEvent(onConnected);++ useEffect(() => {+ const connection = createConnection(roomId);+ connection.on("connected", handleConnected);+ connection.connect();++ return () => connection.disconnect();+ }, [roomId, handleConnected]);+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct (depend on reactive values, not the Effect Event):**++```tsx+import { useEffect, useEffectEvent } from "react";++function ChatRoom({+ roomId,+ onConnected,+}: {+ roomId: string;+ onConnected: () => void;+}) {+ const handleConnected = useEffectEvent(onConnected);++ useEffect(() => {+ const connection = createConnection(roomId);+ connection.on("connected", handleConnected);+ connection.connect();++ return () => connection.disconnect();+ }, [roomId]);+}+```++Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)diff --git a/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.mdnew file mode 100644index 0000000..d9491a5--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md@@ -0,0 +1,37 @@+---+title: Check Cheap Conditions Before Async Flags+impact: HIGH+impactDescription: avoids unnecessary async work when a synchronous guard already fails+tags: async, await, feature-flags, short-circuit, conditional+---++## Check Cheap Conditions Before Async Flags++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag();++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag();+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.diff --git a/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.mdindex 2b4d821..29f1a85 100644--- a/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md+++ b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md@@ -78,3 +78,5 @@ async function updateResource(resourceId: string, userId: string) {```This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.mdnew file mode 100644index 0000000..ad78bcc--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md@@ -0,0 +1,64 @@+---+title: Prefer Statically Analyzable Paths+impact: HIGH+impactDescription: avoids accidental broad bundles and file traces+tags: bundle, nextjs, vite, webpack, rollup, esbuild, path+---++## Prefer Statically Analyzable Paths++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:++- Larger server bundles+- Slower builds+- Worse cold starts+- More memory use++### Import Paths++**Incorrect (the bundler cannot tell what may be imported):**++```ts+const PAGE_MODULES = {+ home: "./pages/home",+ settings: "./pages/settings",+} as const;++const Page = await import(PAGE_MODULES[pageName]);+```++**Correct (use an explicit map of allowed modules):**++```ts+const PAGE_MODULES = {+ home: () => import("./pages/home"),+ settings: () => import("./pages/settings"),+} as const;++const Page = await PAGE_MODULES[pageName]();+```++### File-System Paths++**Incorrect (a 2-value enum still hides the final path from static analysis):**++```ts+const baseDir = path.join(process.cwd(), "content/" + contentKind);+```++**Correct (make each final path literal at the callsite):**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), "content/blog")+ : path.join(process.cwd(), "content/docs");+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mdindex 8b038a5..93f7660 100644--- a/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md@@ -24,35 +24,36 @@ import { Button, TextField } from "@mui/material";// Loads 2,225 modules, takes ~4.2s extra in dev```-**Correct (imports only what you need):**--```tsx-import Check from "lucide-react/dist/esm/icons/check";-import X from "lucide-react/dist/esm/icons/x";-import Menu from "lucide-react/dist/esm/icons/menu";-// Loads only 3 modules (~2KB vs ~1MB)--import Button from "@mui/material/Button";-import TextField from "@mui/material/TextField";-// Loads only what you use-```--**Alternative (Next.js 13.5+):**+**Correct - Next.js 13.5+ (recommended):**```js-// next.config.js - use optimizePackageImports+// next.config.js - automatically optimizes barrel imports at build timemodule.exports = {experimental: {optimizePackageImports: ["lucide-react", "@mui/material"],},};+```-// Then you can keep the ergonomic barrel imports:+```tsx+// Keep the standard imports - Next.js transforms them to direct importsimport { Check, X, Menu } from "lucide-react";-// Automatically transformed to direct imports at build time+// Full TypeScript support, no manual path wrangling```-Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.+This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsx+import Button from "@mui/material/Button";+import TextField from "@mui/material/TextField";+// Loads only what you use+```++> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.++These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.mdnew file mode 100644index 0000000..64533c4--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md@@ -0,0 +1,55 @@+---+title: Use flatMap to Map and Filter in One Pass+impact: LOW-MEDIUM+impactDescription: eliminates intermediate array+tags: javascript, arrays, flatMap, filter, performance+---++## Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect (2 iterations, intermediate array):**++```typescript+const userNames = users+ .map((user) => (user.isActive ? user.name : null))+ .filter(Boolean);+```++**Correct (1 iteration, no intermediate array):**++```typescript+const userNames = users.flatMap((user) => (user.isActive ? [user.name] : []));+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map((r) => (r.success ? r.data.email : null))+ .filter(Boolean);++// After+const emails = responses.flatMap((r) => (r.success ? [r.data.email] : []));++// Parse and filter valid numbers+// Before+const numbers = strings.map((s) => parseInt(s, 10)).filter((n) => !isNaN(n));++// After+const numbers = strings.flatMap((s) => {+ const n = parseInt(s, 10);+ return isNaN(n) ? [] : [n];+});+```++**When to use:**++- Transforming items while filtering some out+- Conditional mapping where some inputs produce no output+- Parsing/validating where invalid inputs should be skippeddiff --git a/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.mdnew file mode 100644index 0000000..0337fd7--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md@@ -0,0 +1,106 @@+---+title: Defer Non-Critical Work with requestIdleCallback+impact: MEDIUM+impactDescription: keeps UI responsive during background tasks+tags: javascript, performance, idle, scheduling, analytics+---++## Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect (blocks main thread during user interaction):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query);+ setResults(results);++ // These block the main thread immediately+ analytics.track("search", { query });+ saveToRecentSearches(query);+ prefetchTopResults(results.slice(0, 3));+}+```++**Correct (defers non-critical work to idle time):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query);+ setResults(results);++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track("search", { query });+ });++ requestIdleCallback(() => {+ saveToRecentSearches(query);+ });++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3));+ });+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track("page_view", { path: location.pathname }),+ { timeout: 2000 },+);+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0;++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index]);+ index++;+ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk);+ }+ }++ requestIdleCallback(processChunk);+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork =+ window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1));++scheduleIdleWork(() => {+ // Non-critical work+});+```++**When to use:**++- Analytics and telemetry+- Saving state to localStorage/IndexedDB+- Prefetching resources for likely next actions+- Processing non-urgent data transformations+- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback+- Rendering updates the user is waiting for+- Time-sensitive operationsdiff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.mdnew file mode 100644index 0000000..b020f2c--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md@@ -0,0 +1,89 @@+---+title: Use React DOM Resource Hints+impact: HIGH+impactDescription: reduces load time for critical resources+tags: rendering, preload, preconnect, prefetch, resource-hints+---++## Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon+- **`preloadModule(href)`**: Fetch an ES module you'll use soon+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script+- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example (preconnect to third-party APIs):**++```tsx+import { preconnect, prefetchDNS } from "react-dom";++export default function App() {+ prefetchDNS("https://analytics.example.com");+ preconnect("https://api.example.com");++ return <main>{/* content */}</main>;+}+```++**Example (preload critical fonts and styles):**++```tsx+import { preload, preinit } from "react-dom";++export default function RootLayout({ children }) {+ // Preload font file+ preload("/fonts/inter.woff2", {+ as: "font",+ type: "font/woff2",+ crossOrigin: "anonymous",+ });++ // Fetch and apply critical stylesheet immediately+ preinit("/styles/critical.css", { as: "style" });++ return (+ <html>+ <body>{children}</body>+ </html>+ );+}+```++**Example (preload modules for code-split routes):**++```tsx+import { preloadModule, preinitModule } from "react-dom";++function Navigation() {+ const preloadDashboard = () => {+ preloadModule("/dashboard.js", { as: "script" });+ };++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ );+}+```++**When to use each:**++| API | Use case |+| --------------- | ------------------------------------------- |+| `prefetchDNS` | Third-party domains you'll connect to later |+| `preconnect` | APIs or CDNs you'll fetch from immediately |+| `preload` | Critical resources needed for current page |+| `preloadModule` | JS modules for likely next navigation |+| `preinit` | Stylesheets/scripts that must execute early |+| `preinitModule` | ES modules that must execute early |++Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.mdnew file mode 100644index 0000000..5111f35--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md@@ -0,0 +1,71 @@+---+title: Use defer or async on Script Tags+impact: HIGH+impactDescription: eliminates render-blocking+tags: rendering, script, defer, async, performance+---++## Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect (blocks rendering):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ );+}+```++**Correct (non-blocking):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ {/* Independent script - use async */}+ <script src="https://example.com/analytics.js" async />+ {/* DOM-dependent script - use defer */}+ <script src="/scripts/utils.js" defer />+ </head>+ <body>{/* content */}</body>+ </html>+ );+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++```tsx+import Script from "next/script";++export default function Page() {+ return (+ <>+ <Script+ src="https://example.com/analytics.js"+ strategy="afterInteractive"+ />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ );+}+```++Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.mdnew file mode 100644index 0000000..682a7a8--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md@@ -0,0 +1,83 @@+---+title: Don't Define Components Inside Components+impact: HIGH+impactDescription: prevents remount on every render+tags: rerender, components, remount, performance+---++## Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect (remounts on every render):**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === "dark" ? "avatar-dark" : "avatar-light"}+ />+ );++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ );++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ );+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct (pass props instead):**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === "dark" ? "avatar-dark" : "avatar-light"}+ />+ );+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ );+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ );+}+```++**Symptoms of this bug:**++- Input fields lose focus on every keystroke+- Animations restart unexpectedly+- `useEffect` cleanup/setup runs on every parent render+- Scroll position resets inside the componentdiff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.mdnew file mode 100644index 0000000..bc19644--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md@@ -0,0 +1,64 @@+---+title: Split Combined Hook Computations+impact: MEDIUM+impactDescription: avoids recomputing independent steps+tags: rerender, useMemo, useEffect, dependencies, optimization+---++## Split Combined Hook Computations++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect (changing `sortOrder` recomputes filtering):**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category);+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price,+ );+ return sorted;+}, [products, category, sortOrder]);+```++**Correct (filtering only recomputes when products or category change):**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category],+);++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price,+ ),+ [filteredProducts, sortOrder],+);+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect (both effects run when either dependency changes):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname);+ document.title = `${pageTitle} | My App`;+}, [pathname, pageTitle]);+```++**Correct (effects run independently):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname);+}, [pathname]);++useEffect(() => {+ document.title = `${pageTitle} | My App`;+}, [pageTitle]);+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.mdnew file mode 100644index 0000000..bac40fe--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md@@ -0,0 +1,59 @@+---+title: Use useDeferredValue for Expensive Derived Renders+impact: MEDIUM+impactDescription: keeps input responsive during heavy computation+tags: rerender, useDeferredValue, optimization, concurrent+---++## Use useDeferredValue for Expensive Derived Renders++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect (input feels laggy while filtering):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState("");+ const filtered = items.filter((item) => fuzzyMatch(item, query));++ return (+ <>+ <input value={query} onChange={(e) => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ );+}+```++**Correct (input stays snappy, results render when ready):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState("");+ const deferredQuery = useDeferredValue(query);+ const filtered = useMemo(+ () => items.filter((item) => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery],+ );+ const isStale = query !== deferredQuery;++ return (+ <>+ <input value={query} onChange={(e) => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ );+}+```++**When to use:**++- Filtering/searching large lists+- Expensive visualizations (charts, graphs) reacting to input+- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.mdindex 892eab3..737056a 100644--- a/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md+++ b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md@@ -11,7 +11,7 @@ tags: server, io, performance, next.js, route-handlers, og-imageWhen loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.-**Incorrect: reads font file on every request**+**Incorrect (reads font file on every request):**```typescript// app/api/og/route.tsx@@ -37,7 +37,7 @@ export async function GET(request: Request) {}```-**Correct: loads once at module initialization**+**Correct (loads once at module initialization):**```typescript// app/api/og/route.tsx@@ -66,7 +66,7 @@ export async function GET(request: Request) {}```-**Alternative: synchronous file reads with Node.js fs**+**Correct (synchronous fs at module level):**```typescript// app/api/og/route.tsx@@ -94,18 +94,24 @@ export async function GET(request: Request) {}```-**General Node.js example: loading config or templates**+**Incorrect (reads config on every call):**```typescript-// Incorrect: reads config on every call+import fs from "node:fs/promises";+export async function processRequest(data: Data) {const config = JSON.parse(await fs.readFile("./config.json", "utf-8"));const template = await fs.readFile("./template.html", "utf-8");return render(template, data, config);}+```++**Correct (hoists config and template to module level):**++```typescript+import fs from "node:fs/promises";-// Correct: loads once at module levelconst configPromise = fs.readFile("./config.json", "utf-8").then(JSON.parse);const templatePromise = fs.readFile("./template.html", "utf-8");@@ -119,7 +125,7 @@ export async function processRequest(data: Data) {}```-**When to use this pattern:**+When to use this pattern:- Loading fonts for OG image generation- Loading static logos, icons, or watermarks@@ -127,13 +133,13 @@ export async function processRequest(data: Data) {- Loading email templates or other static templates- Any static asset that's the same across all requests-**When NOT to use this pattern:**+When not to use this pattern:- Assets that vary per request or user- Files that may change during runtime (use caching with TTL instead)- Large files that would consume too much memory if kept loaded- Sensitive data that shouldn't persist in memory-**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** Module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.+With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.-**In traditional serverless:** Each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.+In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.diff --git a/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.mdnew file mode 100644index 0000000..3c20ef9--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md@@ -0,0 +1,50 @@+---+title: Avoid Shared Module State for Request Data+impact: HIGH+impactDescription: prevents concurrency bugs and request data leaks+tags: server, rsc, ssr, concurrency, security, state+---++## Avoid Shared Module State for Request Data++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect (request data leaks across concurrent renders):**++```tsx+let currentUser: User | null = null;++export default async function Page() {+ currentUser = await auth();+ return <Dashboard />;+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>;+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct (keep request data local to the render tree):**++```tsx+export default async function Page() {+ const user = await auth();+ return <Dashboard user={user} />;+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>;+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope+- Shared caches intentionally designed for cross-request reuse and keyed correctly+- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.mdnew file mode 100644index 0000000..2e2a0fd--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md@@ -0,0 +1,32 @@+---+title: Parallel Nested Data Fetching+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, promise-chaining+---++## Parallel Nested Data Fetching++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect (a single slow item blocks all nested fetches):**++```tsx+const chats = await Promise.all(chatIds.map((id) => getChat(id)));++const chatAuthors = await Promise.all(+ chats.map((chat) => getUser(chat.author)),+);+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct (each item chains its own nested fetch):**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map((id) => getChat(id).then((chat) => getUser(chat.author))),+);+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.diff --git a/.agents/skills/vercel-react-view-transitions/AGENTS.md b/.agents/skills/vercel-react-view-transitions/AGENTS.mdnew file mode 100644index 0000000..a60a84e--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/AGENTS.md@@ -0,0 +1,1086 @@+# React View Transitions++**Version 1.0.0**+Vercel Engineering+March 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when implementing+> view transitions in React applications. Humans may also find it useful,+> but guidance here is optimized for automation and consistency by+> AI-assisted workflows.++---++## Abstract++Guide for implementing smooth, native-feeling animations using React's View Transition API. Covers the `<ViewTransition>` component, `addTransitionType`, CSS view transition pseudo-elements, shared element transitions, Suspense reveals, list reorder, directional navigation, and Next.js integration. Includes a step-by-step implementation workflow, ready-to-use CSS animation recipes, and common mistake warnings.++---++## Table of Contents++1. [Core Reference](#when-to-animate)+ - [When to Animate](#when-to-animate)+ - [Availability](#availability)+ - [Core Concepts](#core-concepts)+ - [Styling with View Transition Classes](#styling-with-view-transition-classes)+ - [Transition Types](#transition-types)+ - [Shared Element Transitions](#shared-element-transitions)+ - [Common Patterns](#common-patterns)+ - [How Multiple VTs Interact](#how-multiple-vts-interact)+ - [Next.js Integration](#nextjs-integration)+ - [Accessibility](#accessibility)+2. [Implementation Workflow](#implementation-workflow)+ - [Step 1: Audit the App](#step-1-audit-the-app)+ - [Step 2: Add CSS Recipes](#step-2-add-css-recipes)+ - [Step 3: Isolate Persistent Elements](#step-3-isolate-persistent-elements)+ - [Step 4: Add Directional Page Transitions](#step-4-add-directional-page-transitions)+ - [Step 5: Add Suspense Reveals](#step-5-add-suspense-reveals)+ - [Step 6: Add Shared Element Transitions](#step-6-add-shared-element-transitions)+ - [Step 7: Verify Each Navigation Path](#step-7-verify-each-navigation-path)+ - [Common Mistakes](#common-mistakes)+3. [Patterns and Guidelines](#patterns-and-guidelines)+4. [CSS Animation Recipes](#css-animation-recipes)+5. [View Transitions in Next.js](#view-transitions-in-nextjs)++---++Animate between UI states using the browser's native `document.startViewTransition`. Declare _what_ with `<ViewTransition>`, trigger _when_ with `startTransition` / `useDeferredValue` / `Suspense`, control _how_ with CSS classes. Unsupported browsers skip animations gracefully.++## When to Animate++Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it.++Implement **all** applicable patterns from this list, in this order:++| Priority | Pattern | What it communicates |+| -------- | ---------------------------------- | -------------------------------- |+| 1 | **Shared element** (`name`) | "Same thing — going deeper" |+| 2 | **Suspense reveal** | "Data loaded" |+| 3 | **List identity** (per-item `key`) | "Same items, new arrangement" |+| 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" |+| 5 | **Route change** (layout-level) | "Going to a new place" |++This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it.++### Choosing Animation Style++| Context | Animation | Why |+| --------------------------------------- | -------------------------------------------------- | ---------------------------- |+| Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth |+| Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate |+| Suspense reveal | `enter`/`exit` string props | Content arriving |+| Revalidation / background refresh | `default="none"` | Silent — no animation needed |++Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth.++---++## Availability++- **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected.+- **Without Next.js:** Install `react@canary react-dom@canary` (`ViewTransition` is not in stable React).+- Browser support: Chromium 111+, Firefox 144+, Safari 18.2+. Graceful degradation.++---++## Core Concepts++### The `<ViewTransition>` Component++```jsx+import { ViewTransition } from "react";++<ViewTransition>+ <Component />+</ViewTransition>;+```++React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself.++### Animation Triggers++| Trigger | When it fires |+| ---------- | --------------------------------------------------------------------------------- |+| **enter** | VT first inserted during a Transition |+| **exit** | VT first removed during a Transition |+| **update** | DOM mutations inside a VT. With nested VTs, mutation applies to the innermost one |+| **share** | Named VT unmounts and another with same `name` mounts in same Transition |++Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate.++### Critical Placement Rule++VT only activates enter/exit if it appears **before any DOM nodes**:++```jsx+// Works+<ViewTransition enter="auto" exit="auto"><div>Content</div></ViewTransition>++// Broken — div wraps the VT+<div><ViewTransition enter="auto" exit="auto"><div>Content</div></ViewTransition></div>+```++---++## Styling with View Transition Classes++Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations.++```jsx+<ViewTransition+ default="none"+ enter="slide-in"+ exit="slide-out"+ share="morph"+/>+```++If `default` is `"none"`, all triggers are off unless explicitly listed.++### CSS Pseudo-Elements++- `::view-transition-old(.class)` — outgoing snapshot+- `::view-transition-new(.class)` — incoming snapshot+- `::view-transition-group(.class)` — container+- `::view-transition-image-pair(.class)` — old + new pair++---++## Transition Types++Tag transitions with `addTransitionType` so VTs can pick different animations. Call it multiple times to stack types — different VTs in the tree react to different types:++```jsx+startTransition(() => {+ addTransitionType("nav-forward");+ addTransitionType("select-item");+ router.push("/detail/1");+});+```++Map types to CSS classes. Works on `enter`, `exit`, **and** `share`:++```jsx+<ViewTransition+ enter={{+ "nav-forward": "slide-from-right",+ "nav-back": "slide-from-left",+ default: "none",+ }}+ exit={{+ "nav-forward": "slide-to-left",+ "nav-back": "slide-to-right",+ default: "none",+ }}+ share={{+ "nav-forward": "morph-forward",+ "nav-back": "morph-back",+ default: "morph",+ }}+ default="none"+>+ <Page />+</ViewTransition>+```++`enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally:++```jsx+<ViewTransition+ enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }}+ exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ default="none"+>+```++**TypeScript:** `ViewTransitionClassPerType` requires a `default` key.++### `router.back()` and Browser Back Button++`router.back()` and the browser's back/forward buttons do **not** trigger view transitions (`popstate` is synchronous, incompatible with `startViewTransition`). Use `router.push()` with an explicit URL instead.++### Types and Suspense++Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals.++---++## Shared Element Transitions++Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph:++```jsx+<ViewTransition name="hero-image">+ <img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} />+</ViewTransition>++// Other view — same name+<ViewTransition name="hero-image">+ <img src="/full.jpg" />+</ViewTransition>+```++- Only one VT with a given `name` can be mounted at a time — use unique names. Watch for reusable components: if a component with a named VT is rendered in both a modal/popover _and_ a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer.+- `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no pair forms, `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths.+- Never use fade-out exit on pages with shared morphs — use directional slide.++---++## Common Patterns++### Enter/Exit++```jsx+{+ show && (+ <ViewTransition enter="fade-in" exit="fade-out">+ <Panel />+ </ViewTransition>+ );+}+```++### List Reorder++```jsx+{+ items.map((item) => (+ <ViewTransition key={item.id}>+ <ItemCard item={item} />+ </ViewTransition>+ ));+}+```++Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT.++### Composing Shared Elements with List Identity++Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element, use two nested `<ViewTransition>` boundaries:++```jsx+{+ items.map((item) => (+ <ViewTransition key={item.id}>+ {" "}+ {/* list identity */}+ <Link href={`/items/${item.id}`}>+ <ViewTransition name={`item-image-${item.id}`} share="morph">+ {" "}+ {/* shared element */}+ <Image src={item.image} />+ </ViewTransition>+ <p>{item.name}</p>+ </Link>+ </ViewTransition>+ ));+}+```++The outer VT handles list reorder/enter. The inner VT handles cross-route shared element morph. Missing either layer means that animation silently doesn't happen.++### Force Re-Enter with `key`++```jsx+<ViewTransition key={searchParams.toString()} enter="slide-up" default="none">+ <ResultsGrid />+</ViewTransition>+```++**Caution:** Wrapping `<Suspense>` with key remounts the boundary and refetches.++### Suspense Fallback to Content++Simple cross-fade:++```jsx+<ViewTransition>+ <Suspense fallback={<Skeleton />}>+ <Content />+ </Suspense>+</ViewTransition>+```++Directional reveal:++```jsx+<Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+>+ <ViewTransition enter="slide-up" default="none">+ <Content />+ </ViewTransition>+</Suspense>+```++---++## How Multiple VTs Interact++Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions don't compete.++### Use `default="none"` Liberally++Without it, every VT fires the browser cross-fade on **every** transition. Always use `default="none"` and explicitly enable only desired triggers.++### Two Patterns Coexist++**Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation.+**Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type).++They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts.++### Nested VT Limitation++When a parent VT exits, nested VTs inside it do **not** fire their own enter/exit — only the outermost VT animates. Per-item staggered animations during page navigation are not possible today. See [react#36135](https://github.com/facebook/react/pull/36135) for an experimental opt-in fix.++---++## Next.js Integration++See the [View Transitions in Next.js](#view-transitions-in-nextjs) section below.++---++## Accessibility++Always add reduced motion CSS to your global stylesheet:++```css+@media (prefers-reduced-motion: reduce) {+ ::view-transition-old(*),+ ::view-transition-new(*),+ ::view-transition-group(*) {+ animation-duration: 0s !important;+ animation-delay: 0s !important;+ }+}+```++---++# Implementation Workflow++**Follow these steps in order.** Start with the audit — do not skip it. Copy the CSS recipes from the CSS Recipes section below — do not write your own animation CSS.++## Step 1: Audit the App++Before writing any code, scan the codebase thoroughly. Search for:++- **Every `<Link>` and `router.push`** — open every file that contains one+- **Every `<Suspense>` boundary** — check what its fallback renders+- **Every page/route component** — each needs a VT placement decision+- **Persistent elements** (headers, navbars, sidebars) — need `viewTransitionName` isolation+- **Shared visual elements** on both source and target views+- **Skeleton-to-content control pairs** — if a fallback renders a control that also exists in the real content, both need a matching `viewTransitionName`++Then classify every navigation and produce a navigation map:++```+| Route | Navigates to | Direction | VT pattern |+|-----------------|----------------------|--------------|-----------------------|+| / | /detail/[id] | forward | directional slide |+| /detail/[id] | / | back | directional slide |+| /detail/[id] | /detail/[other] | sequential | directional slide (ordered prev/next) or key+share crossfade |+| /tab/[a] | /tab/[b] | lateral | key+share crossfade |+| (Suspense) | (content loads) | — | slide-up reveal |+```++For each shared element (`name` prop), note where a pair forms and where it doesn't — this determines whether you need `enter`/`exit` as a fallback alongside `share`.++## Step 2: Add CSS Recipes++Copy the **complete** CSS recipe set from the CSS Animation Recipes section below into your global stylesheet. Don't write your own — the recipes handle staggered timing, motion blur, and reduced motion.++## Step 3: Isolate Persistent Elements++```jsx+<header style={{ viewTransitionName: "site-header" }}>...</header>+```++```css+::view-transition-group(site-header) {+ animation: none;+ z-index: 100;+}+```++For `backdrop-blur`/`backdrop-filter`, use the backdrop-blur workaround instead.++## Step 4: Add Directional Page Transitions++```jsx+startTransition(() => {+ addTransitionType("nav-forward");+ router.push("/detail/1");+});+```++Wrap each **page component** (not layout) in a type-keyed VT:++```jsx+<ViewTransition+ enter={{+ "nav-forward": "nav-forward",+ "nav-back": "nav-back",+ default: "none",+ }}+ exit={{+ "nav-forward": "nav-forward",+ "nav-back": "nav-back",+ default: "none",+ }}+ default="none"+>+ <div>...page content...</div>+</ViewTransition>+```++Extract into a reusable component so every page doesn't repeat the type map:++```jsx+export function DirectionalTransition({ children }: { children: React.ReactNode }) {+ return (+ <ViewTransition+ enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ default="none"+ >+ {children}+ </ViewTransition>+ );+}+```++**Rules:** Always pair `enter` with `exit`. Always include `default: "none"`. Place in page components, not layouts. Only use directional slides for hierarchical navigation or ordered sequences (prev/next).++## Step 5: Add Suspense Reveals++```jsx+<Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+>+ <ViewTransition enter="slide-up" default="none">+ <AsyncContent />+ </ViewTransition>+</Suspense>+```++Use `default="none"` on content VT. Use simple string props (not type maps) — Suspense resolves have no type.++## Step 6: Add Shared Element Transitions++```jsx+// Source view+<ViewTransition name={`photo-${photo.id}`} share="morph" default="none">+ <Image src={photo.src} ... />+</ViewTransition>++// Target view — same name+<ViewTransition name={`photo-${photo.id}`} share="morph">+ <Image src={photo.src} ... />+</ViewTransition>+```++When list items contain shared elements, compose both patterns — two independent layers:++```jsx+{items.map(item => (+ <ViewTransition key={item.id}> {/* list identity */}+ <Link href={`/detail/${item.id}`}>+ <ViewTransition name={`item-${item.id}`} share="morph" default="none"> {/* shared element */}+ <Image src={item.image} ... />+ </ViewTransition>+ </Link>+ </ViewTransition>+))}+```++The outer VT handles list reorder/enter. The inner VT handles cross-route shared element morph. Missing either layer means that animation silently doesn't happen.++**Rules:** Names must be globally unique. Add `default="none"` on list-side shared elements.++## Step 7: Verify Each Navigation Path++Walk through every row in the navigation map from Step 1:++- Does the VT mount/unmount, or stay mounted (same-route)?+- For named VTs: does a shared pair form? If not, does `enter`/`exit` provide a fallback?+- Does `default="none"` block an animation you actually want?+- Do persistent elements stay static?+- Do Suspense reveals animate independently from directional navigations?++---++## Common Mistakes++- **Bare VT without `default="none"`** — fires cross-fade on every transition+- **Directional VT in a layout** — layouts persist, enter/exit won't fire on route changes+- **Fade-out exit with shared morphs** — conflicts with morph, use directional slide+- **Writing custom animation CSS** — use the recipes+- **Missing `default: "none"` in type-keyed objects** — TypeScript requires it, fallback is `"auto"`+- **Type maps on Suspense reveals** — Suspense resolves have no type, use string props+- **Raw `viewTransitionName` CSS to trigger animations** — React only starts view transitions when `<ViewTransition>` components are in the tree. Bare `viewTransitionName` is for isolating elements, not triggering animations.+- **`update` trigger for same-route navigations** — nested VTs steal the mutation from the parent. Use `key` + `name` + `share` instead.+- **Named VT in a reusable component** — if a component with a named VT is rendered in both a modal/popover _and_ a page, both mount simultaneously and break the morph. Make the name conditional or move it to the specific consumer.+- **`router.back()` for back navigation** — `router.back()` triggers synchronous `popstate`, incompatible with view transitions. Use `router.push()` with an explicit URL.++For Next.js-specific steps, see the Next.js section below.++---++# Patterns and Guidelines++## Searchable Grid with `useDeferredValue`++```tsx+"use client";++import { useDeferredValue, useState, ViewTransition, Suspense } from "react";++export default function SearchableGrid({ itemsPromise }) {+ const [search, setSearch] = useState("");+ const deferredSearch = useDeferredValue(search);++ return (+ <>+ <input+ value={search}+ onChange={(e) => setSearch(e.currentTarget.value)}+ />+ <ViewTransition>+ <Suspense fallback={<GridSkeleton />}>+ <ItemGrid itemsPromise={itemsPromise} search={deferredSearch} />+ </Suspense>+ </ViewTransition>+ </>+ );+}+```++Per-item named VTs in deferred lists trigger cross-fades on every keystroke. Fix with `default="none"`.++## Card Expand/Collapse with `startTransition`++```tsx+"use client";++import { useState, useRef, startTransition, ViewTransition } from "react";++export default function ItemGrid({ items }) {+ const [expandedId, setExpandedId] = useState(null);+ const scrollRef = useRef(0);++ return expandedId ? (+ <ViewTransition enter="slide-in" name={`item-${expandedId}`}>+ <ItemDetail+ item={items.find((i) => i.id === expandedId)}+ onClose={() => {+ startTransition(() => {+ setExpandedId(null);+ setTimeout(+ () =>+ window.scrollTo({ behavior: "smooth", top: scrollRef.current }),+ 100,+ );+ });+ }}+ />+ </ViewTransition>+ ) : (+ <div className="grid grid-cols-3 gap-4">+ {items.map((item) => (+ <ViewTransition key={item.id} name={`item-${item.id}`}>+ <ItemCard+ item={item}+ onSelect={() => {+ scrollRef.current = window.scrollY;+ startTransition(() => setExpandedId(item.id));+ }}+ />+ </ViewTransition>+ ))}+ </div>+ );+}+```++## Cross-Fade Without Remount++Omit `key` to trigger update (cross-fade) instead of exit + enter. Avoids Suspense remount:++```jsx+<ViewTransition>+ <TabPanel tab={activeTab} />+</ViewTransition>+```++## Isolate Elements from Parent Animations++Persistent elements get captured in page's transition snapshot. Fix with `viewTransitionName`:++```jsx+<nav style={{ viewTransitionName: "persistent-nav" }}>{/* ... */}</nav>+```++```css+::view-transition-group(persistent-nav) {+ animation: none;+ z-index: 100;+}+```++Same for floating elements (popovers, tooltips). Global fix: `::view-transition-group(*) { z-index: 100; }`++## Shared Controls Between Skeleton and Content++Give matching controls the same `viewTransitionName`. Don't put manual `viewTransitionName` on root DOM node inside `<ViewTransition>`.++## Reusable Animated Collapse++```jsx+function AnimatedCollapse({ open, children }) {+ if (!open) return null;+ return (+ <ViewTransition enter="expand-in" exit="collapse-out">+ {children}+ </ViewTransition>+ );+}+```++## Preserve State with Activity++```jsx+<Activity mode={isVisible ? "visible" : "hidden"}>+ <ViewTransition enter="slide-in" exit="slide-out">+ <Sidebar />+ </ViewTransition>+</Activity>+```++## Exclude Elements with `useOptimistic`++`useOptimistic` values update before snapshot, excluding them from animation. Use for controls; use committed state for animated content.++---++## View Transition Events++Imperative control via `onEnter`, `onExit`, `onUpdate`, `onShare`. Always return cleanup. `onShare` takes precedence.++```jsx+<ViewTransition+ onEnter={(instance, types) => {+ const anim = instance.new.animate(+ [+ { transform: "scale(0.8)", opacity: 0 },+ { transform: "scale(1)", opacity: 1 },+ ],+ { duration: 300, easing: "ease-out" },+ );+ return () => anim.cancel();+ }}+>+ <Component />+</ViewTransition>+```++`instance`: `.old`, `.new`, `.group`, `.imagePair`, `.name`++---++## Animation Timing++| Interaction | Duration |+| -------------------- | --------- |+| Direct toggle | 100–200ms |+| Route transition | 150–250ms |+| Suspense reveal | 200–400ms |+| Shared element morph | 300–500ms |++---++## Troubleshooting++**VT not activating:** Ensure VT comes before any DOM node. Ensure `startTransition`.++**"Two VTs with same name":** Names must be globally unique. Use IDs.++**`router.back()` and browser back/forward skip animation:** Use `router.push()` with an explicit URL instead.++**Only updates animate:** Without `<Suspense>`, React treats swaps as updates. Conditionally render the VT itself, or wrap in `<Suspense>`.++**Layout VT prevents page VTs from animating:** Nested VTs never fire enter/exit inside a parent VT. If your layout has a VT wrapping `{children}`, page-level enter/exit will silently not work. Remove the layout VT.++**TS error "Property 'default' is missing":** Type-keyed objects require a `default` key.++**Backdrop-blur flickers:** `::view-transition-old(name) { display: none }` + `::view-transition-new(name) { animation: none }`.++**`border-radius` lost:** Apply `border-radius` directly to captured element.++**Batching:** Multiple updates during animation are batched (A→B→C→D becomes B→D).++---++# CSS Animation Recipes++Ready-to-use CSS for `<ViewTransition>` props. Copy into global stylesheet.++## Timing Variables++```css+:root {+ --duration-exit: 150ms;+ --duration-enter: 210ms;+ --duration-move: 400ms;+}+```++### Shared Keyframes++```css+@keyframes fade {+ from {+ filter: blur(3px);+ opacity: 0;+ }+ to {+ filter: blur(0);+ opacity: 1;+ }+}++@keyframes slide {+ from {+ translate: var(--slide-offset);+ }+ to {+ translate: 0;+ }+}++@keyframes slide-y {+ from {+ transform: translateY(var(--slide-y-offset, 10px));+ }+ to {+ transform: translateY(0);+ }+}+```++## Fade++```css+::view-transition-old(.fade-out) {+ animation: var(--duration-exit) ease-in fade reverse;+}+::view-transition-new(.fade-in) {+ animation: var(--duration-enter) ease-out var(--duration-exit) both fade;+}+```++## Slide (Vertical)++```css+::view-transition-old(.slide-down) {+ animation:+ var(--duration-exit) ease-out both fade reverse,+ var(--duration-exit) ease-out both slide-y reverse;+}+::view-transition-new(.slide-up) {+ animation:+ var(--duration-enter) ease-in var(--duration-exit) both fade,+ var(--duration-move) ease-in both slide-y;+}+```++## Directional Navigation++### Single-Class Approach++```css+::view-transition-old(.nav-forward) {+ --slide-offset: -60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+::view-transition-new(.nav-forward) {+ --slide-offset: 60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}++::view-transition-old(.nav-back) {+ --slide-offset: 60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+::view-transition-new(.nav-back) {+ --slide-offset: -60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+```++### Separate Enter/Exit Classes++```css+::view-transition-new(.slide-from-right) {+ --slide-offset: 60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+::view-transition-old(.slide-to-left) {+ --slide-offset: -60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}++::view-transition-new(.slide-from-left) {+ --slide-offset: -60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+::view-transition-old(.slide-to-right) {+ --slide-offset: 60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+```++## Shared Element Morph++```css+::view-transition-group(.morph) {+ animation-duration: var(--duration-move);+}+::view-transition-image-pair(.morph) {+ animation-name: via-blur;+}+@keyframes via-blur {+ 30% {+ filter: blur(3px);+ }+}+```++**Note:** Shared element transitions take raster snapshots. For text with significant size differences (e.g., `<h3>` → `<h1>`), the old snapshot gets scaled up, producing a visible ghost artifact. Use `text-morph` for text shared elements.++## Text Morph++Avoids raster scaling artifacts on text by hiding the old snapshot and showing the new text at full resolution:++```css+::view-transition-group(.text-morph) {+ animation-duration: var(--duration-move);+}+::view-transition-old(.text-morph) {+ display: none;+}+::view-transition-new(.text-morph) {+ animation: none;+ object-fit: none;+ object-position: left top;+}+```++## Scale++```css+::view-transition-old(.scale-out) {+ animation: var(--duration-exit) ease-in scale-down;+}+::view-transition-new(.scale-in) {+ animation: var(--duration-enter) ease-out var(--duration-exit) both scale-up;+}+@keyframes scale-down {+ from {+ transform: scale(1);+ opacity: 1;+ }+ to {+ transform: scale(0.85);+ opacity: 0;+ }+}+@keyframes scale-up {+ from {+ transform: scale(0.85);+ opacity: 0;+ }+ to {+ transform: scale(1);+ opacity: 1;+ }+}+```++## Persistent Element Isolation++```css+::view-transition-group(persistent-nav) {+ animation: none;+ z-index: 100;+}+```++### Backdrop-Blur Workaround++```css+::view-transition-old(persistent-nav) {+ display: none;+}+::view-transition-new(persistent-nav) {+ animation: none;+}+```++## Reduced Motion++```css+@media (prefers-reduced-motion: reduce) {+ ::view-transition-old(*),+ ::view-transition-new(*),+ ::view-transition-group(*) {+ animation-duration: 0s !important;+ animation-delay: 0s !important;+ }+}+```++---++# View Transitions in Next.js++## Setup++```js+// next.config.js+experimental: {+ viewTransition: true;+}+```++Wraps every `<Link>` navigation in `document.startViewTransition`. Use `default="none"` to prevent competing animations. Do **not** install `react@canary` — the App Router already bundles it.++## Next.js Implementation Additions++**After Step 2:** Enable the experimental flag.++**Step 4:** Use `transitionTypes` on `<Link>` (if available — see availability note below):++```tsx+<Link href="/photo/1" transitionTypes={["nav-forward"]}>View</Link>+<Link href="/" transitionTypes={["nav-back"]}>Back</Link>+```++**After Step 6:** For same-route dynamic segments, use `key` + `name` + `share` pattern.++## Layout-Level ViewTransition++Don't add a layout-level VT wrapping `{children}` if pages have their own VTs — nested VTs never fire enter/exit inside a parent VT, so page-level enter/exit will silently not work. Remove the layout VT entirely. A bare VT in layout works only if pages have no VTs of their own. Layouts persist across navigations — don't use type-keyed maps in layouts.++## The `transitionTypes` Prop++Works in Server Components, no wrapper needed:++```tsx+<Link href="/products/1" transitionTypes={["nav-forward"]}>+ View+</Link>+```++**Availability:** Requires `experimental.viewTransition: true`. Available in Next.js 15+ canary builds and Next.js 16+. If unavailable, use `startTransition` + `addTransitionType` + `router.push()`. To check: `grep -r "transitionTypes" node_modules/next/dist/`. Reserve manual `startTransition` for non-link interactions.++## `loading.tsx` as Suspense Boundary++Next.js `loading.tsx` files are implicit `<Suspense>` boundaries. Wrap the skeleton in `<ViewTransition exit="...">` in `loading.tsx`, and the content in `<ViewTransition enter="..." default="none">` in the page. This is the Next.js-idiomatic equivalent of explicit `<Suspense fallback={...}>`. Same rules apply: use simple string props (not type maps) since Suspense reveals fire without transition types.++## Server-Side Filtering with `router.replace`++For search/sort/filter that re-renders on the server (via URL params), use `startTransition` + `router.replace`. VTs activate because the update is inside `startTransition`. List items wrapped in `<ViewTransition key={item.id}>` animate reorder. This is the server-component alternative to the client-side `useDeferredValue` pattern.++## Two-Layer Pattern (Directional + Suspense)++Directional slides + Suspense reveals coexist because they fire at different moments. Place the directional VT in the **page component** (not layout):++```tsx+<ViewTransition+ enter={{ "nav-forward": "slide-from-right", default: "none" }}+ exit={{ "nav-forward": "slide-to-left", default: "none" }}+ default="none"+>+ <div>+ <Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+ >+ <ViewTransition enter="slide-up" default="none">+ <Content />+ </ViewTransition>+ </Suspense>+ </div>+</ViewTransition>+```++## Shared Elements Across Routes++```tsx+// List page+<Link href={`/products/${product.id}`} transitionTypes={['nav-forward']}>+ <ViewTransition name={`product-${product.id}`}>+ <Image src={product.image} alt={product.name} width={400} height={300} />+ </ViewTransition>+</Link>++// Detail page — same name+<ViewTransition name={`product-${product.id}`}>+ <Image src={product.image} alt={product.name} width={800} height={600} />+</ViewTransition>+```++## Same-Route Dynamic Segment Transitions++Page stays mounted on dynamic segment change — enter/exit never fire. Use `key` + `name` + `share`:++```tsx+<Suspense fallback={<Skeleton />}>+ <ViewTransition+ key={slug}+ name={`collection-${slug}`}+ share="auto"+ default="none"+ >+ <Content slug={slug} />+ </ViewTransition>+</Suspense>+```++## Server Components++- `<ViewTransition>` works in Server and Client Components+- `<Link transitionTypes>` works in Server Components+- `addTransitionType` and programmatic nav require Client Componentsdiff --git a/.agents/skills/vercel-react-view-transitions/README.md b/.agents/skills/vercel-react-view-transitions/README.mdnew file mode 100644index 0000000..9f29bed--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/README.md@@ -0,0 +1,42 @@+# React View Transitions Skill++An agent skill for implementing smooth, native-feeling animations using React's View Transition API.++## What This Skill Covers++- **`<ViewTransition>` component** — animation triggers (enter, exit, update, share), placement rules, View Transition Classes+- **`addTransitionType`** — tagging transitions for directional or context-specific animations+- **Shared element transitions** — morphing elements across different views+- **View Transition Events** — imperative JavaScript animations via the Web Animations API+- **CSS pseudo-elements** — `::view-transition-old`, `::view-transition-new`, `::view-transition-group`+- **Next.js integration** — `experimental.viewTransition`, the `transitionTypes` prop on `next/link`, App Router patterns+- **Accessibility** — `prefers-reduced-motion` handling+- **Ready-to-use CSS recipes** — fade, slide, scale, directional navigation++## Skill Structure++```+react-view-transitions/+├── SKILL.md # Core skill (always loaded)+├── AGENTS.md # Full compiled document (all references expanded)+└── references/+ ├── implementation.md # Step-by-step implementation workflow+ ├── patterns.md # Real-world patterns, events API, troubleshooting+ ├── nextjs.md # Next.js-specific patterns+ └── css-recipes.md # Copy-paste CSS animations+```++## Installation++Install via [skills.sh](https://skills.sh):++```bash+npx skills install https://github.com/vercel-labs/react-view-transitions-skill+```++## Resources++- [React `<ViewTransition>` docs](https://react.dev/reference/react/ViewTransition)+- [React `addTransitionType` docs](https://react.dev/reference/react/addTransitionType)+- [Next.js `viewTransition` config](https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition)+- [Next.js App Router Playground (view transitions)](https://github.com/vercel/next-app-router-playground/tree/main/app/view-transitions) — Vercel's reference implementationdiff --git a/.agents/skills/vercel-react-view-transitions/SKILL.md b/.agents/skills/vercel-react-view-transitions/SKILL.mdnew file mode 100644index 0000000..b3ac469--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/SKILL.md@@ -0,0 +1,363 @@+---+name: vercel-react-view-transitions+description: Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.+license: MIT+metadata:+ author: vercel+ version: "1.0.0"+---++# React View Transitions++Animate between UI states using the browser's native `document.startViewTransition`. Declare _what_ with `<ViewTransition>`, trigger _when_ with `startTransition` / `useDeferredValue` / `Suspense`, control _how_ with CSS classes. Unsupported browsers skip animations gracefully.++## When to Animate++Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it.++Implement **all** applicable patterns from this list, in this order:++| Priority | Pattern | What it communicates |+| -------- | ---------------------------------- | -------------------------------- |+| 1 | **Shared element** (`name`) | "Same thing — going deeper" |+| 2 | **Suspense reveal** | "Data loaded" |+| 3 | **List identity** (per-item `key`) | "Same items, new arrangement" |+| 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" |+| 5 | **Route change** (layout-level) | "Going to a new place" |++This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it.++### Choosing Animation Style++| Context | Animation | Why |+| --------------------------------------- | -------------------------------------------------- | ---------------------------- |+| Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth |+| Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate |+| Suspense reveal | `enter`/`exit` string props | Content arriving |+| Revalidation / background refresh | `default="none"` | Silent — no animation needed |++Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth.++---++## Availability++- **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected.+- **Without Next.js:** Install `react@canary react-dom@canary` (`ViewTransition` is not in stable React).+- Browser support: Chromium 111+, Firefox 144+, Safari 18.2+. Graceful degradation on unsupported browsers.++---++## Implementation Workflow++When adding view transitions to an existing app, **follow `references/implementation.md` step by step.** Start with the audit — do not skip it. Copy the CSS recipes from `references/css-recipes.md` into the global stylesheet — do not write your own animation CSS.++---++## Core Concepts++### The `<ViewTransition>` Component++```jsx+import { ViewTransition } from "react";++<ViewTransition>+ <Component />+</ViewTransition>;+```++React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself.++### Animation Triggers++| Trigger | When it fires |+| ---------- | ------------------------------------------------------------------------------------------------- |+| **enter** | `<ViewTransition>` first inserted during a Transition |+| **exit** | `<ViewTransition>` first removed during a Transition |+| **update** | DOM mutations inside a `<ViewTransition>`. With nested VTs, mutation applies to the innermost one |+| **share** | Named VT unmounts and another with same `name` mounts in the same Transition |++Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate.++### Critical Placement Rule++`<ViewTransition>` only activates enter/exit if it appears **before any DOM nodes**:++```jsx+// Works+<ViewTransition enter="auto" exit="auto">+ <div>Content</div>+</ViewTransition>++// Broken — div wraps the VT, suppressing enter/exit+<div>+ <ViewTransition enter="auto" exit="auto">+ <div>Content</div>+ </ViewTransition>+</div>+```++---++## Styling with View Transition Classes++### Props++Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations.++```jsx+<ViewTransition+ default="none"+ enter="slide-in"+ exit="slide-out"+ share="morph"+/>+```++If `default` is `"none"`, all triggers are off unless explicitly listed.++### CSS Pseudo-Elements++- `::view-transition-old(.class)` — outgoing snapshot+- `::view-transition-new(.class)` — incoming snapshot+- `::view-transition-group(.class)` — container+- `::view-transition-image-pair(.class)` — old + new pair++See `references/css-recipes.md` for ready-to-use animation recipes.++---++## Transition Types++Tag transitions with `addTransitionType` so VTs can pick different animations based on context. Call it multiple times to stack types — different VTs in the tree react to different types:++```jsx+startTransition(() => {+ addTransitionType("nav-forward");+ addTransitionType("select-item");+ router.push("/detail/1");+});+```++Pass an object to map types to CSS classes. Works on `enter`, `exit`, **and** `share`:++```jsx+<ViewTransition+ enter={{+ "nav-forward": "slide-from-right",+ "nav-back": "slide-from-left",+ default: "none",+ }}+ exit={{+ "nav-forward": "slide-to-left",+ "nav-back": "slide-to-right",+ default: "none",+ }}+ share={{+ "nav-forward": "morph-forward",+ "nav-back": "morph-back",+ default: "morph",+ }}+ default="none"+>+ <Page />+</ViewTransition>+```++`enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally:++```jsx+<ViewTransition+ enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }}+ exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ default="none"+>+```++**TypeScript:** `ViewTransitionClassPerType` requires a `default` key in the object.++For apps with multiple pages, extract the type-keyed VT into a reusable wrapper:++```jsx+export function DirectionalTransition({ children }: { children: React.ReactNode }) {+ return (+ <ViewTransition+ enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ default="none"+ >+ {children}+ </ViewTransition>+ );+}+```++### `router.back()` and Browser Back Button++`router.back()` and the browser's back/forward buttons do **not** trigger view transitions (`popstate` is synchronous, incompatible with `startViewTransition`). Use `router.push()` with an explicit URL instead.++### Types and Suspense++Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals.++---++## Shared Element Transitions++Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph:++```jsx+<ViewTransition name="hero-image">+ <img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} />+</ViewTransition>++// On the other view — same name+<ViewTransition name="hero-image">+ <img src="/full.jpg" />+</ViewTransition>+```++- Only one VT with a given `name` can be mounted at a time — use unique names (`photo-${id}`). Watch for reusable components: if a component with a named VT is rendered in both a modal/popover _and_ a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer.+- `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no matching pair forms (e.g., the target page doesn't have the same name), `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths.+- Never use a fade-out exit on pages with shared morphs — use a directional slide instead.++---++## Common Patterns++### Enter/Exit++```jsx+{+ show && (+ <ViewTransition enter="fade-in" exit="fade-out">+ <Panel />+ </ViewTransition>+ );+}+```++### List Reorder++```jsx+{+ items.map((item) => (+ <ViewTransition key={item.id}>+ <ItemCard item={item} />+ </ViewTransition>+ ));+}+```++Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT.++### Composing Shared Elements with List Identity++Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element (e.g., an image that morphs into a detail view), use two nested `<ViewTransition>` boundaries:++```jsx+{+ items.map((item) => (+ <ViewTransition key={item.id}>+ {" "}+ {/* list identity */}+ <Link href={`/items/${item.id}`}>+ <ViewTransition name={`item-image-${item.id}`} share="morph">+ {" "}+ {/* shared element */}+ <Image src={item.image} />+ </ViewTransition>+ <p>{item.name}</p>+ </Link>+ </ViewTransition>+ ));+}+```++The outer VT handles list reorder/enter animations. The inner VT handles the cross-route shared element morph. Missing either layer means that animation silently doesn't happen.++### Force Re-Enter with `key`++```jsx+<ViewTransition key={searchParams.toString()} enter="slide-up" default="none">+ <ResultsGrid />+</ViewTransition>+```++**Caution:** If wrapping `<Suspense>`, changing `key` remounts the boundary and refetches.++### Suspense Fallback to Content++Simple cross-fade:++```jsx+<ViewTransition>+ <Suspense fallback={<Skeleton />}>+ <Content />+ </Suspense>+</ViewTransition>+```++Directional reveal:++```jsx+<Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+>+ <ViewTransition enter="slide-up" default="none">+ <Content />+ </ViewTransition>+</Suspense>+```++For more patterns, see `references/patterns.md`.++---++## How Multiple VTs Interact++Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions (navigation vs later Suspense resolve) don't compete.++### Use `default="none"` Liberally++Without it, every VT fires the browser cross-fade on **every** transition — Suspense resolves, `useDeferredValue` updates, background revalidations. Always use `default="none"` and explicitly enable only desired triggers.++### Two Patterns Coexist++**Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation.+**Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type).++They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts.++### Nested VT Limitation++When a parent VT exits, nested VTs inside it do **not** fire their own enter/exit — only the outermost VT animates. Per-item staggered animations during page navigation are not possible today. See [react#36135](https://github.com/facebook/react/pull/36135) for an experimental opt-in fix.++---++## Next.js Integration++For Next.js setup (`experimental.viewTransition` flag, `transitionTypes` prop on `next/link`, App Router patterns, Server Components), see `references/nextjs.md`.++---++## Accessibility++Always add the reduced motion CSS from `references/css-recipes.md` to your global stylesheet.++---++## Reference Files++- **`references/implementation.md`** — Step-by-step implementation workflow.+- **`references/patterns.md`** — Patterns, animation timing, events API, troubleshooting.+- **`references/css-recipes.md`** — Ready-to-use CSS animation recipes.+- **`references/nextjs.md`** — Next.js App Router patterns and Server Component details.++## Full Compiled Document++For the complete guide with all reference files expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-react-view-transitions/metadata.json b/.agents/skills/vercel-react-view-transitions/metadata.jsonnew file mode 100644index 0000000..aabe3e1--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/metadata.json@@ -0,0 +1,12 @@+{+ "version": "1.0.0",+ "organization": "Vercel Engineering",+ "date": "March 2026",+ "abstract": "Guide for implementing smooth, native-feeling animations using React's View Transition API. Covers the <ViewTransition> component, addTransitionType, CSS view transition pseudo-elements, shared element transitions, JavaScript animations via Web Animations API, and Next.js integration including the transitionTypes prop on next/link. Includes ready-to-use CSS animation recipes and real-world patterns from production Next.js apps.",+ "references": [+ "https://react.dev/reference/react/ViewTransition",+ "https://react.dev/reference/react/addTransitionType",+ "https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition",+ "https://github.com/vercel/next-app-router-playground/tree/main/app/view-transitions"+ ]+}diff --git a/.agents/skills/vercel-react-view-transitions/references/css-recipes.md b/.agents/skills/vercel-react-view-transitions/references/css-recipes.mdnew file mode 100644index 0000000..ec7ba69--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/references/css-recipes.md@@ -0,0 +1,279 @@+# CSS Animation Recipes++Ready-to-use CSS for `<ViewTransition>` props. Copy into your global stylesheet.++---++## Timing Variables++```css+:root {+ --duration-exit: 150ms;+ --duration-enter: 210ms;+ --duration-move: 400ms;+}+```++### Shared Keyframes++```css+@keyframes fade {+ from {+ filter: blur(3px);+ opacity: 0;+ }+ to {+ filter: blur(0);+ opacity: 1;+ }+}++@keyframes slide {+ from {+ translate: var(--slide-offset);+ }+ to {+ translate: 0;+ }+}++@keyframes slide-y {+ from {+ transform: translateY(var(--slide-y-offset, 10px));+ }+ to {+ transform: translateY(0);+ }+}+```++---++## Fade++```css+::view-transition-old(.fade-out) {+ animation: var(--duration-exit) ease-in fade reverse;+}+::view-transition-new(.fade-in) {+ animation: var(--duration-enter) ease-out var(--duration-exit) both fade;+}+```++Usage: `<ViewTransition enter="fade-in" exit="fade-out" />`++---++## Slide (Vertical)++```css+::view-transition-old(.slide-down) {+ animation:+ var(--duration-exit) ease-out both fade reverse,+ var(--duration-exit) ease-out both slide-y reverse;+}+::view-transition-new(.slide-up) {+ animation:+ var(--duration-enter) ease-in var(--duration-exit) both fade,+ var(--duration-move) ease-in both slide-y;+}+```++Usage:++```jsx+<Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+>+ <ViewTransition default="none" enter="slide-up">+ <Content />+ </ViewTransition>+</Suspense>+```++---++## Directional Navigation++### Separate Enter/Exit Classes++```css+::view-transition-new(.slide-from-right) {+ --slide-offset: 60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+::view-transition-old(.slide-to-left) {+ --slide-offset: -60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}++::view-transition-new(.slide-from-left) {+ --slide-offset: -60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+::view-transition-old(.slide-to-right) {+ --slide-offset: 60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+```++### Single-Class Approach++```css+::view-transition-old(.nav-forward) {+ --slide-offset: -60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+::view-transition-new(.nav-forward) {+ --slide-offset: 60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}++::view-transition-old(.nav-back) {+ --slide-offset: 60px;+ animation:+ var(--duration-exit) ease-in both fade reverse,+ var(--duration-move) ease-in-out both slide reverse;+}+::view-transition-new(.nav-back) {+ --slide-offset: -60px;+ animation:+ var(--duration-enter) ease-out var(--duration-exit) both fade,+ var(--duration-move) ease-in-out both slide;+}+```++---++## Shared Element Morph++```css+::view-transition-group(.morph) {+ animation-duration: var(--duration-move);+}++::view-transition-image-pair(.morph) {+ animation-name: via-blur;+}++@keyframes via-blur {+ 30% {+ filter: blur(3px);+ }+}+```++Usage: `<ViewTransition name={`product-${id}`} share="morph" />`++**Note:** Shared element transitions take raster snapshots. For text with significant size differences (e.g., `<h3>` → `<h1>`), the old snapshot gets scaled up, producing a visible ghost artifact. Use `text-morph` for text shared elements.++## Text Morph++Avoids raster scaling artifacts on text by hiding the old snapshot and showing the new text at full resolution:++```css+::view-transition-group(.text-morph) {+ animation-duration: var(--duration-move);+}+::view-transition-old(.text-morph) {+ display: none;+}+::view-transition-new(.text-morph) {+ animation: none;+ object-fit: none;+ object-position: left top;+}+```++Usage: `<ViewTransition name={`title-${id}`} share="text-morph" />`++---++## Scale++```css+::view-transition-old(.scale-out) {+ animation: var(--duration-exit) ease-in scale-down;+}+::view-transition-new(.scale-in) {+ animation: var(--duration-enter) ease-out var(--duration-exit) both scale-up;+}++@keyframes scale-down {+ from {+ transform: scale(1);+ opacity: 1;+ }+ to {+ transform: scale(0.85);+ opacity: 0;+ }+}+@keyframes scale-up {+ from {+ transform: scale(0.85);+ opacity: 0;+ }+ to {+ transform: scale(1);+ opacity: 1;+ }+}+```++Usage: `<ViewTransition enter="scale-in" exit="scale-out" />`++---++## Persistent Element Isolation++```css+::view-transition-group(persistent-nav) {+ animation: none;+ z-index: 100;+}+```++### Backdrop-Blur Workaround++For elements with `backdrop-filter`, hide the old snapshot to avoid flash:++```css+::view-transition-old(persistent-nav) {+ display: none;+}+::view-transition-new(persistent-nav) {+ animation: none;+}+```++---++## Reduced Motion++```css+@media (prefers-reduced-motion: reduce) {+ ::view-transition-old(*),+ ::view-transition-new(*),+ ::view-transition-group(*) {+ animation-duration: 0s !important;+ animation-delay: 0s !important;+ }+}+```diff --git a/.agents/skills/vercel-react-view-transitions/references/implementation.md b/.agents/skills/vercel-react-view-transitions/references/implementation.mdnew file mode 100644index 0000000..b58fe3e--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/references/implementation.md@@ -0,0 +1,185 @@+# Implementation Workflow++Follow these steps in order when adding view transitions to an app. Each step builds on the previous one.++## Step 1: Audit the App++Before writing any code, scan the codebase thoroughly. Search for:++- **Every `<Link>` and `router.push`** — these are your navigation triggers. Open every file that contains one.+- **Every `<Suspense>` boundary** — each one is a candidate for a reveal animation. Check what its fallback renders.+- **Every page/route component** — list them all. Each page needs a VT placement decision.+- **Persistent elements** — headers, navbars, sidebars, sticky controls that stay on screen across navigations. These need `viewTransitionName` isolation.+- **Shared visual elements** — images, cards, or avatars that appear on both a source and target view (e.g., a thumbnail in a list and the same image on a detail page).+- **Skeleton-to-content control pairs** — if a Suspense fallback renders a control (search input, tab bar) that also exists in the real content, both need a matching `viewTransitionName`.++Then classify every navigation and produce a navigation map:++```+| Route | Navigates to | Direction | VT pattern |+|-----------------|----------------------|--------------|-----------------------|+| / | /detail/[id] | forward | directional slide |+| /detail/[id] | / | back | directional slide |+| /detail/[id] | /detail/[other] | sequential | directional slide (ordered prev/next) or key+share crossfade |+| /tab/[a] | /tab/[b] | lateral | key+share crossfade |+| (Suspense) | (content loads) | — | slide-up reveal |+```++For each shared element (`name` prop), note every navigation where a pair forms and where it doesn't — this determines whether you need `enter`/`exit` as a fallback alongside `share`.++## Step 2: Add CSS Recipes++Copy the **complete** CSS recipe set from `css-recipes.md` into your global stylesheet. This includes timing variables, shared keyframes, fade, slide (vertical), directional navigation (forward/back), shared element morph, persistent element isolation, and reduced motion.++Do not write your own animation CSS — the recipes handle staggered timing, motion blur on morphs, and reduced motion that are easy to get wrong. You can customize timing variables (`--duration-exit`, `--duration-enter`, `--duration-move`) after the initial setup.++## Step 3: Isolate Persistent Elements++For every persistent element identified in Step 1, add a `viewTransitionName` style to pull it out of the page content's transition snapshot:++```jsx+<header style={{ viewTransitionName: "site-header" }}>...</header>+```++Then add the persistent element isolation CSS from `css-recipes.md` (prevents the element from animating during page transitions). If the element uses `backdrop-blur` or `backdrop-filter`, use the backdrop-blur workaround from `css-recipes.md` instead.++If a Suspense fallback mirrors a persistent control (e.g., a skeleton search input), give both the real control and the skeleton the same `viewTransitionName` so they morph in place.++## Step 4: Add Directional Page Transitions++For hierarchical navigations identified in Step 1, tag the navigation direction using `addTransitionType` inside `startTransition`:++```jsx+startTransition(() => {+ addTransitionType("nav-forward");+ router.push("/detail/1");+});+```++Then wrap each **page component** (not layout) in a type-keyed `<ViewTransition>`:++```jsx+<ViewTransition+ enter={{+ "nav-forward": "nav-forward",+ "nav-back": "nav-back",+ default: "none",+ }}+ exit={{+ "nav-forward": "nav-forward",+ "nav-back": "nav-back",+ default: "none",+ }}+ default="none"+>+ <div>...page content...</div>+</ViewTransition>+```++The `nav-forward` and `nav-back` CSS classes from `css-recipes.md` produce horizontal slides. For simpler apps where directional motion isn't needed, a bare `<ViewTransition default="none">` wrapper with `enter="fade-in"` / `exit="fade-out"` works too.++Extract this into a reusable component so every page doesn't repeat the verbose type map:++```jsx+export function DirectionalTransition({ children }: { children: React.ReactNode }) {+ return (+ <ViewTransition+ enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }}+ default="none"+ >+ {children}+ </ViewTransition>+ );+}+```++This also becomes the single place to adjust if you add new transition types later.++**Rules:**++- Always pair `enter` with `exit` — without an exit animation, the old page disappears instantly while the new one animates in.+- Always include `default: "none"` in type map objects and `default="none"` on the component — otherwise it fires on every transition.+- Place the directional `<ViewTransition>` in each page component, not in a layout. Layouts persist across navigations and never trigger enter/exit.+- Only use directional slides for hierarchical navigation or ordered sequences (prev/next). Lateral/sibling navigation (tab-to-tab) should use a bare `<ViewTransition>` (cross-fade) or `default="none"`.++## Step 5: Add Suspense Reveals++For every `<Suspense>` boundary identified in Step 1, wrap the fallback and content in separate `<ViewTransition>`s:++```jsx+<Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+>+ <ViewTransition enter="slide-up" default="none">+ <AsyncContent />+ </ViewTransition>+</Suspense>+```++This example uses `slide-down` / `slide-up` for directional vertical motion. For a simpler reveal, a bare `<ViewTransition>` around the `<Suspense>` gives a cross-fade with zero configuration. Choose based on the spatial meaning — consult the "Choosing the Right Animation Style" table in the main skill file.++**Rules:**++- Always use `default="none"` on the content `<ViewTransition>` to prevent re-animation on revalidation or unrelated transitions.+- Use simple string props (not type maps) on Suspense `<ViewTransition>`s — Suspense resolves fire as separate transitions with no type, so type-keyed props won't match.++## Step 6: Add Shared Element Transitions++For every shared visual element identified in Step 1, add matching named `<ViewTransition>` wrappers on both the source and target views:++```jsx+// On the source view (e.g., list/grid page)+<ViewTransition name={`photo-${photo.id}`} share="morph" default="none">+ <Image src={photo.src} ... />+</ViewTransition>++// On the target view (e.g., detail page) — same name+<ViewTransition name={`photo-${photo.id}`} share="morph">+ <Image src={photo.src} ... />+</ViewTransition>+```++The `share="morph"` class uses the morph recipe from `css-recipes.md` (controlled duration + motion blur). For a simpler cross-fade, use `share="auto"` (browser default).++When list items contain shared elements, compose both patterns with two nested `<ViewTransition>` layers — see "Composing Shared Elements with List Identity" in `SKILL.md`.++**Rules:**++- Names must be globally unique — use prefixes like `photo-${id}`.+- Add `default="none"` on list-side shared elements to prevent per-item cross-fades on filter/search updates.++## Step 7: Verify Each Navigation Path++Walk through every row in the navigation map from Step 1 and confirm:++- Does the VT mount/unmount on this navigation, or does it stay mounted (same-route)?+- For named VTs: does a shared pair form? If not, does `enter`/`exit` provide a fallback?+- Does `default="none"` block an animation you actually want?+- Do persistent elements stay static (not sliding with page content)?+- Do Suspense reveals animate independently from directional navigations?++If any path produces no animation or competing animations, revisit the relevant step.++---++## Common Mistakes++- **Bare `<ViewTransition>` without props** — without `default="none"`, it fires the browser's default cross-fade on every transition (every navigation, every Suspense resolve, every revalidation). Always set `default="none"` and explicitly enable only the triggers you want.+- **Directional `<ViewTransition>` in a layout** — layouts persist across navigations and never unmount/remount. `enter`/`exit` props won't fire on route changes. Place the outer type-keyed `<ViewTransition>` in each page component.+- **Fade-out exit with shared element morphs** — the page dissolving conflicts with the morph. Use a directional slide exit instead.+- **Writing custom animation CSS** — the recipes in `css-recipes.md` handle staggered timing, motion blur on morphs, and reduced motion. Copy them; don't reinvent them.+- **Missing `default: "none"` in type-keyed objects** — TypeScript requires a `default` key, and without it the fallback is `"auto"` which fires on every transition.+- **Type maps on Suspense reveals** — Suspense resolves fire as separate transitions with no type. Type-keyed props won't match — use simple string props instead.+- **Raw `viewTransitionName` CSS to trigger animations** — React only calls `document.startViewTransition` when `<ViewTransition>` components are in the tree. A bare `viewTransitionName` style is for isolating elements from a parent's snapshot, not for triggering animations.+- **`update` trigger for same-route navigations** — nested VTs inside the content steal the mutation from the parent, so `update` never fires on the outer VT. Use `key` + `name` + `share` instead.+- **Named VT in a reusable component** — if a component with a named VT is rendered in both a modal/popover _and_ a page, both mount simultaneously and break the morph. Make the name conditional or move it to the specific consumer.+- **`router.back()` for back navigation** — `router.back()` triggers synchronous `popstate`, incompatible with view transitions. Use `router.push()` with an explicit URL.++---++For Next.js-specific implementation steps (config flag, `transitionTypes` on `<Link>`, same-route dynamic segments), see `nextjs.md`.diff --git a/.agents/skills/vercel-react-view-transitions/references/nextjs.md b/.agents/skills/vercel-react-view-transitions/references/nextjs.mdnew file mode 100644index 0000000..cfeb43a--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/references/nextjs.md@@ -0,0 +1,202 @@+# View Transitions in Next.js++## Setup++`<ViewTransition>` works out of the box for `startTransition`/`Suspense` updates. To also animate `<Link>` navigations:++```js+// next.config.js+const nextConfig = {+ experimental: { viewTransition: true },+};+module.exports = nextConfig;+```++This wraps every `<Link>` navigation in `document.startViewTransition`. Any VT with `default="auto"` fires on **every** link click — use `default="none"` to prevent competing animations.++Do **not** install `react@canary` — see SKILL.md "Availability" for details.++---++## Next.js Implementation Additions++When following `implementation.md`, apply these additions:++**After Step 2:** Enable the experimental flag above.++**Step 4:** Use `transitionTypes` on `<Link>` — see "The `transitionTypes` Prop" section below for usage and availability.++**After Step 6:** For same-route dynamic segments (e.g., `/collection/[slug]`), use the `key` + `name` + `share` pattern — see Same-Route Dynamic Segment Transitions below.++---++## Layout-Level ViewTransition++**Do NOT add a layout-level VT wrapping `{children}` if pages have their own VTs.** Nested VTs never fire enter/exit when inside a parent VT — page-level enter/exit will silently not work. Remove the layout VT entirely.++A bare `<ViewTransition>` in layout works only if pages have **no** VTs of their own.++**Layouts persist across navigations** — `enter`/`exit` only fire on initial mount, not on route changes. Don't use type-keyed maps in layouts.++---++## The `transitionTypes` Prop on `next/link`++No wrapper component needed, works in Server Components:++```tsx+<Link href="/products/1" transitionTypes={["transition-to-detail"]}>+ View Product+</Link>+```++Replaces the manual pattern of `onNavigate` + `startTransition` + `addTransitionType` + `router.push()`. Reserve manual `startTransition` for non-link interactions (buttons, forms).++**Availability:** `transitionTypes` requires `experimental.viewTransition: true` and is available in Next.js 15+ canary builds and Next.js 16+. If unavailable, use `startTransition` + `addTransitionType` + `router.push()` (see Programmatic Navigation below). To check: `grep -r "transitionTypes" node_modules/next/dist/` — if no results, fall back to programmatic navigation.++---++## Programmatic Navigation++```tsx+"use client";++import { useRouter } from "next/navigation";+import { startTransition, addTransitionType } from "react";++function handleNavigate(href: string) {+ const router = useRouter();+ startTransition(() => {+ addTransitionType("nav-forward");+ router.push(href);+ });+}+```++---++## Server-Side Filtering with `router.replace`++For search/sort/filter that re-renders on the server (via URL params), use `startTransition` + `router.replace`. VTs activate because the state update is inside `startTransition`:++```tsx+"use client";++import { useRouter } from "next/navigation";+import { startTransition } from "react";++function handleSort(sort: string) {+ const router = useRouter();+ startTransition(() => {+ router.replace(`?sort=${sort}`);+ });+}+```++List items wrapped in `<ViewTransition key={item.id}>` will animate reorder. This is the server-component alternative to the client-side `useDeferredValue` pattern in `patterns.md`.++---++## Two-Layer Pattern (Directional + Suspense)++Directional slides + Suspense reveals coexist because they fire at different moments. Place the directional VT in the **page component** (not layout):++```tsx+<ViewTransition+ enter={{ "nav-forward": "slide-from-right", default: "none" }}+ exit={{ "nav-forward": "slide-to-left", default: "none" }}+ default="none"+>+ <div>+ <Suspense+ fallback={+ <ViewTransition exit="slide-down">+ <Skeleton />+ </ViewTransition>+ }+ >+ <ViewTransition enter="slide-up" default="none">+ <Content />+ </ViewTransition>+ </Suspense>+ </div>+</ViewTransition>+```++---++## `loading.tsx` as Suspense Boundary++Next.js `loading.tsx` is an implicit `<Suspense>` boundary. Wrap the skeleton in `<ViewTransition exit="...">` in `loading.tsx`, and the content in `<ViewTransition enter="..." default="none">` in the page:++```tsx+// loading.tsx+<ViewTransition exit="slide-down"><PhotoGridSkeleton /></ViewTransition>++// page.tsx+<ViewTransition enter="slide-up" default="none"><PhotoGrid photos={photos} /></ViewTransition>+```++Same rules as explicit `<Suspense>`: use simple string props (not type maps) since Suspense reveals fire without transition types.++---++## Shared Elements Across Routes++```tsx+// List page+{+ products.map((product) => (+ <Link+ key={product.id}+ href={`/products/${product.id}`}+ transitionTypes={["nav-forward"]}+ >+ <ViewTransition name={`product-${product.id}`}>+ <Image+ src={product.image}+ alt={product.name}+ width={400}+ height={300}+ />+ </ViewTransition>+ </Link>+ ));+}++// Detail page — same name+<ViewTransition name={`product-${product.id}`}>+ <Image src={product.image} alt={product.name} width={800} height={600} />+</ViewTransition>;+```++---++## Same-Route Dynamic Segment Transitions++When navigating between dynamic segments of the same route (e.g., `/collection/[slug]`), the page stays mounted — enter/exit never fire. Use `key` + `name` + `share`:++```tsx+<Suspense fallback={<Skeleton />}>+ <ViewTransition+ key={slug}+ name={`collection-${slug}`}+ share="auto"+ default="none"+ >+ <Content slug={slug} />+ </ViewTransition>+</Suspense>+```++- `key={slug}` forces unmount/remount on change+- `name` + `share="auto"` creates a shared element crossfade+- VT inside `<Suspense>` (without keying Suspense) keeps old content visible during loading++---++## Server Components++- `<ViewTransition>` works in both Server and Client Components+- `<Link transitionTypes>` works in Server Components — no `'use client'` needed+- `addTransitionType` and `startTransition` for programmatic nav require Client Componentsdiff --git a/.agents/skills/vercel-react-view-transitions/references/patterns.md b/.agents/skills/vercel-react-view-transitions/references/patterns.mdnew file mode 100644index 0000000..b6cff81--- /dev/null+++ b/.agents/skills/vercel-react-view-transitions/references/patterns.md@@ -0,0 +1,304 @@+# Patterns and Guidelines++## Searchable Grid with `useDeferredValue`++`useDeferredValue` makes filter updates a transition, activating `<ViewTransition>`:++```tsx+"use client";++import { useDeferredValue, useState, ViewTransition, Suspense } from "react";++export default function SearchableGrid({ itemsPromise }) {+ const [search, setSearch] = useState("");+ const deferredSearch = useDeferredValue(search);++ return (+ <>+ <input+ value={search}+ onChange={(e) => setSearch(e.currentTarget.value)}+ />+ <ViewTransition>+ <Suspense fallback={<GridSkeleton />}>+ <ItemGrid itemsPromise={itemsPromise} search={deferredSearch} />+ </Suspense>+ </ViewTransition>+ </>+ );+}+```++Per-item `<ViewTransition name={...}>` inside a deferred list triggers cross-fades on every keystroke. Fix with `default="none"`:++```tsx+{+ filteredItems.map((item) => (+ <ViewTransition+ key={item.id}+ name={`item-${item.id}`}+ share="morph"+ default="none"+ >+ <ItemCard item={item} />+ </ViewTransition>+ ));+}+```++## Card Expand/Collapse with `startTransition`++Toggle between grid and detail view with shared element morph:++```tsx+"use client";++import { useState, useRef, startTransition, ViewTransition } from "react";++export default function ItemGrid({ items }) {+ const [expandedId, setExpandedId] = useState(null);+ const scrollRef = useRef(0);++ return expandedId ? (+ <ViewTransition enter="slide-in" name={`item-${expandedId}`}>+ <ItemDetail+ item={items.find((i) => i.id === expandedId)}+ onClose={() => {+ startTransition(() => {+ setExpandedId(null);+ setTimeout(+ () =>+ window.scrollTo({ behavior: "smooth", top: scrollRef.current }),+ 100,+ );+ });+ }}+ />+ </ViewTransition>+ ) : (+ <div className="grid grid-cols-3 gap-4">+ {items.map((item) => (+ <ViewTransition key={item.id} name={`item-${item.id}`}>+ <ItemCard+ item={item}+ onSelect={() => {+ scrollRef.current = window.scrollY;+ startTransition(() => setExpandedId(item.id));+ }}+ />+ </ViewTransition>+ ))}+ </div>+ );+}+```++## Type-Safe Transition Helpers++Use `as const` arrays and derived types to prevent ID clashes:++```tsx+const transitionTypes = [+ "default",+ "transition-to-detail",+ "transition-to-list",+] as const;+const animationTypes = [+ "auto",+ "none",+ "animate-slide-from-left",+ "animate-slide-from-right",+] as const;++type TransitionType = (typeof transitionTypes)[number];+type AnimationType = (typeof animationTypes)[number];+type TransitionMap = { default: AnimationType } & Partial<+ Record<Exclude<TransitionType, "default">, AnimationType>+>;++export function HorizontalTransition({+ children,+ enter,+ exit,+}: {+ children: React.ReactNode;+ enter: TransitionMap;+ exit: TransitionMap;+}) {+ return (+ <ViewTransition enter={enter} exit={exit}>+ {children}+ </ViewTransition>+ );+}+```++## Cross-Fade Without Remount++Omit `key` to trigger an update (cross-fade) instead of exit + enter. Avoids Suspense remount/refetch:++```jsx+<ViewTransition>+ <TabPanel tab={activeTab} />+</ViewTransition>+```++Use `key` when content identity changes (state resets). Omit for cross-fades (tabs, panels, carousel).++## Isolate Elements from Parent Animations++### Persistent Layout Elements++Persistent elements (headers, navbars, sidebars) get captured in the page's transition snapshot. Fix with `viewTransitionName`:++```jsx+<nav style={{ viewTransitionName: "persistent-nav" }}>{/* ... */}</nav>+```++Then add the persistent element isolation CSS from `css-recipes.md`. For `backdrop-blur`/`backdrop-filter`, use the backdrop-blur workaround from `css-recipes.md`.++### Floating Elements++Give popovers/tooltips their own `viewTransitionName`:++```jsx+<SelectPopover style={{ viewTransitionName: "popover" }}>+ {options}+</SelectPopover>+```++Global fix: see persistent element isolation in `css-recipes.md`.++## Shared Controls Between Skeleton and Content++Give matching controls in fallback and content the same `viewTransitionName`:++```jsx+// Fallback+<input disabled placeholder="Search..." style={{ viewTransitionName: 'search-input' }} />+// Content+<input placeholder="Search..." style={{ viewTransitionName: 'search-input' }} />+```++Don't put manual `viewTransitionName` on the root DOM node inside `<ViewTransition>` — React's auto-generated name overrides it.++## Reusable Animated Collapse++```jsx+function AnimatedCollapse({ open, children }) {+ if (!open) return null;+ return (+ <ViewTransition enter="expand-in" exit="collapse-out">+ {children}+ </ViewTransition>+ );+}++// Usage: toggle with startTransition+<button onClick={() => startTransition(() => setOpen(o => !o))}>Toggle</button>+<AnimatedCollapse open={open}><SectionContent /></AnimatedCollapse>+```++## Preserve State with Activity++```jsx+<Activity mode={isVisible ? "visible" : "hidden"}>+ <ViewTransition enter="slide-in" exit="slide-out">+ <Sidebar />+ </ViewTransition>+</Activity>+```++## Exclude Elements with `useOptimistic`++`useOptimistic` values update before the transition snapshot, excluding them from animation. Use for controls (labels); use committed state for animated content:++```tsx+const [sort, setSort] = useState("newest");+const [optimisticSort, setOptimisticSort] = useOptimistic(sort);++function cycleSort() {+ const nextSort = getNextSort(optimisticSort);+ startTransition(() => {+ setOptimisticSort(nextSort); // before snapshot — no animation+ setSort(nextSort); // between snapshots — animates+ });+}++<button>Sort: {LABELS[optimisticSort]}</button>;+{+ items.sort(comparators[sort]).map((item) => (+ <ViewTransition key={item.id}>+ <ItemCard item={item} />+ </ViewTransition>+ ));+}+```++---++## View Transition Events++Imperative control via `onEnter`, `onExit`, `onUpdate`, `onShare`. Always return a cleanup function. `onShare` takes precedence over `onEnter`/`onExit`.++```jsx+<ViewTransition+ onEnter={(instance, types) => {+ const anim = instance.new.animate(+ [+ { transform: "scale(0.8)", opacity: 0 },+ { transform: "scale(1)", opacity: 1 },+ ],+ { duration: 300, easing: "ease-out" },+ );+ return () => anim.cancel();+ }}+>+ <Component />+</ViewTransition>+```++The `instance` object: `instance.old`, `instance.new`, `instance.group`, `instance.imagePair`, `instance.name`.++The `types` array (second argument) lets you vary animation based on transition type.++---++## Animation Timing++| Interaction | Duration |+| ------------------------------------ | --------- |+| Direct toggle (expand/collapse) | 100–200ms |+| Route transition (slide) | 150–250ms |+| Suspense reveal (skeleton → content) | 200–400ms |+| Shared element morph | 300–500ms |++---++## Troubleshooting++**VT not activating:** Ensure `<ViewTransition>` comes before any DOM node. Ensure state update is inside `startTransition`.++**"Two ViewTransition components with the same name":** Names must be globally unique. Use IDs: `name={`hero-${item.id}`}`.++**`router.back()` and browser back/forward skip animation:** Use `router.push()` with an explicit URL instead. See SKILL.md "router.back() and Browser Back Button."++**`flushSync` skips animations:** Use `startTransition` instead.++**Only updates animate (no enter/exit):** Without `<Suspense>`, React treats swaps as updates. Conditionally render the VT itself, or wrap in `<Suspense>`.++**Layout VT prevents page VTs from animating:** Nested VTs never fire enter/exit inside a parent VT. If your layout has a VT wrapping `{children}`, page-level enter/exit will silently not work. Remove the layout VT.++**List reorder not animating with `useOptimistic`:** Optimistic values resolve before snapshot. Use committed state for list order.++**TS error "Property 'default' is missing":** Type-keyed objects require a `default` key.++**Hash fragments cause scroll jumps:** Navigate without hash; scroll programmatically after navigation.++**Backdrop-blur flickers:** Use the backdrop-blur workaround from `css-recipes.md`.++**`border-radius` lost during transitions:** Apply `border-radius` directly to the captured element.++**Skeleton controls slide away:** Give matching controls the same `viewTransitionName`.++**Batching:** Multiple updates during animation are batched. A→B→C→D becomes B→D.diff --git a/.agents/skills/writing-guidelines/SKILL.md b/.agents/skills/writing-guidelines/SKILL.mdnew file mode 100644index 0000000..1918eaa--- /dev/null+++ b/.agents/skills/writing-guidelines/SKILL.md@@ -0,0 +1,40 @@+---+name: writing-guidelines+description: Review docs/prose for Writing Guidelines compliance. Use when asked to "review my docs", "check writing style", "audit prose", "review docs voice and tone", or "check this page against the writing handbook".+metadata:+ author: vercel+ version: "1.0.0"+ argument-hint: <file-or-pattern>+---++# Writing Guidelines++Review files for compliance with Writing Guidelines.++## How It Works++1. Fetch the latest guidelines from the source URL below+2. Read the specified files (or prompt user for files/pattern)+3. Check against all rules in the fetched guidelines+4. Output findings in the terse `file:line` format++## Guidelines Source++Fetch fresh guidelines before each review:++```+https://raw.githubusercontent.com/vercel-labs/writing-guidelines/main/command.md+```++Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.++## Usage++When a user provides a file or pattern argument:++1. Fetch guidelines from the source URL above+2. Read the specified files+3. Apply all rules from the fetched guidelines+4. Output findings using the format specified in the guidelines++If no files specified, ask the user which files to review.diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 7a33b4a..07bd805 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -18,7 +18,7 @@ jobs:if: github.event_name == 'deployment_status' && github.event.deployment_status.state == 'success'name: Run e2e tests via ${{ github.event_name == 'deployment_status' && 'Vercel deployment' }}- timeout-minutes: 45+ timeout-minutes: 50# we use macos-latest because I am using mac os locally and generating snapshots (screenshots) for the PDF tests locally, so we need to use the same OS on the CI. https://docs.github.com/en/actions/how-tos/write-workflows/choose-where-workflows-run/choose-the-runner-for-a-job#choosing-github-hosted-runnersruns-on: macos-latestenv:diff --git a/.github/workflows/monthly-recurring-invoice.yml b/.github/workflows/monthly-recurring-invoice.ymlindex 5204ff3..2a9c205 100644--- a/.github/workflows/monthly-recurring-invoice.yml+++ b/.github/workflows/monthly-recurring-invoice.yml@@ -5,14 +5,14 @@ concurrency:cancel-in-progress: falseon:+ workflow_dispatch:schedule:# Run every day from the 10th to the 12th.# We need this range because:# - if the 10th is a weekday -> run on 10th# - if the 10th is Saturday -> run on Monday 12th# - if the 10th is Sunday -> run on Monday 11th- - cron: "0 15 10-12 * *"- timezone: Europe/Warsaw+ - cron: "5 14 10-12 * *"jobs:recurring-invoice:@@ -94,7 +94,8 @@ jobs:`weekday=${weekday}\n` +`target_day=${targetDay}\n` +`today=${today}\n` +- `today_weekday=${todayWeekday}\n`+ `today_weekday=${todayWeekday}\n` ++ `today_weekday_name=${getPart('weekday')}\n`)EOF)@@ -105,6 +106,9 @@ jobs:WEEKDAY: ${{ steps.date-check.outputs.weekday }}TARGET_DAY: ${{ steps.date-check.outputs.target_day }}SHOULD_RUN: ${{ steps.date-check.outputs.should_run }}+ TODAY_WEEKDAY_NAME: ${{ steps.date-check.outputs.today_weekday_name }}+ TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}+ TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}run: |WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"@@ -113,10 +117,9 @@ jobs:WEEKDAY_NAMES=("Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday")WEEKDAY_NAME="${WEEKDAY_NAMES[$WEEKDAY]}"- # Build weekend explanation if 10th fell on Saturday or SundayWEEKEND_LINE=""if [ "$WEEKDAY" == "0" ] || [ "$WEEKDAY" == "6" ]; then- WEEKEND_LINE="10th was a weekend ($WEEKDAY_NAME), so execution moved to Monday ($TARGET_DAY).%0A%0A"+ WEEKEND_LINE=$'10th was a weekend ('"$WEEKDAY_NAME"$'), so execution moved to Monday ('"$TARGET_DAY"$').\n\n'fiif [ "$SHOULD_RUN" == "true" ]; then@@ -125,60 +128,71 @@ jobs:STATUS="⏭️ Status: Skipped (awaiting correct date)"fi- MESSAGE="📅 Monthly Invoice Workflow%0A%0A"- MESSAGE+="🕒 $NOW%0A%0A"- MESSAGE+="<b>Billing period:</b> $BILLING_PERIOD%0A%0A"- MESSAGE+="$WEEKEND_LINE"- MESSAGE+="$STATUS%0A%0A"- MESSAGE+="🔗 <a href=\"$WORKFLOW_URL\">View Workflow</a>"-- curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \- -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \- -d text="$MESSAGE" \- -d parse_mode="HTML" > /dev/null+ export TEXT=$'📅 Monthly Invoice Workflow\n\n'"🕒 ${NOW} (${TODAY_WEEKDAY_NAME})"$'\n\n<b>Billing period:</b> '"${BILLING_PERIOD}"$'\n\n'"${WEEKEND_LINE}${STATUS}"$'\n\n🔗 <a href="'"${WORKFLOW_URL}"$'">View Workflow</a>'++ node <<'EOF'+ ;(async () => {+ const text = process.env.TEXT+ const payload = {+ chat_id: process.env.TELEGRAM_CHAT_ID,+ text,+ parse_mode: "HTML",+ disable_web_page_preview: true,+ }++ const response = await fetch(+ `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ },+ )+ const body = await response.text()+ if (!response.ok) {+ console.error("Telegram API error:", body)+ process.exit(1)+ }+ console.log("Telegram notification sent:", body)+ })().catch((error) => {+ console.error(error)+ process.exit(1)+ })+ EOF- name: Generate monthly recurring invoice+ id: generate-invoice# Execute only if date-check step decided# that today is the correct execution day.if: steps.date-check.outputs.should_run == 'true'run: |+ INVOICE_API_URL='https://easyinvoicepdf.com/api/generate-invoice'++ echo "✅ [monthly-recurring-invoice github actions workflow] Generating monthly recurring invoice at $(date '+%Y-%m-%d %H:%M:%S %Z')"+ echo "👉 [monthly-recurring-invoice github actions workflow] GET ${INVOICE_API_URL}"+curl --fail-with-body \--silent \--show-error \-X GET \--max-time 60 \-H "Authorization: Bearer ${{ secrets.INVOICE_AUTH_TOKEN }}" \- https://easyinvoicepdf.com/api/generate-invoice-- - name: Send success notification to Telegram- if: steps.date-check.outputs.should_run == 'true' && success()- run: |- WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"- NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"-- MESSAGE="📅 Monthly Invoice Workflow%0A%0A"- MESSAGE+="🕒 $NOW%0A%0A"- MESSAGE+="✅ Status: Invoice generated successfully%0A%0A"- MESSAGE+="🔗 <a href=\"$WORKFLOW_URL\">View Workflow</a>"+ "${INVOICE_API_URL}"- curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \- -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \- -d text="$MESSAGE" \- -d parse_mode="HTML" > /dev/null-- - name: Send failure notification to Telegram+ - name: 📧 Send emailif: failure()- run: |- WORKFLOW_URL="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"- NOW="$(date '+%d.%m.%Y %H:%M:%S %Z')"-- MESSAGE="📅 Monthly Invoice Workflow%0A%0A"- MESSAGE+="🕒 $NOW%0A%0A"- MESSAGE+="🚨 Status: Invoice generation failed%0A"- MESSAGE+="Please check the workflow for details%0A%0A"- MESSAGE+="🔗 <a href=\"$WORKFLOW_URL\">View Workflow</a>"-- curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_GITHUB_ACTIONS_BOT_TOKEN }}/sendMessage" \- -d chat_id="${{ secrets.TELEGRAM_GITHUB_ACTIONS_CHAT_ID }}" \- -d text="$MESSAGE" \- -d parse_mode="HTML" > /dev/null+ # https://github.com/dawidd6/action-send-mail+ uses: dawidd6/action-send-mail@d38f3f7cd391cdebfe0d38efc3998b935e951c4f # v16+ with:+ server_address: smtp.gmail.com+ server_port: 587+ from: "GitHub Actions (no-reply) <${{ secrets.EMAIL_USERNAME }}>"+ to: ${{ secrets.EMAIL_USERNAME }}+ username: ${{ secrets.EMAIL_USERNAME }}+ password: ${{ secrets.EMAIL_PASSWORD }}+ subject: ❌ Monthly Recurring Invoice Failed for ${{ github.repository }}+ body: |+ Monthly recurring invoice workflow for ${{ github.repository }} has failed.++ For more details, please check:+ - GitHub Actions run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.tsindex 19bdbf5..7b0314a 100644--- a/e2e/default-invoice-template/default-invoice-template.test.ts+++ b/e2e/default-invoice-template/default-invoice-template.test.ts@@ -1933,4 +1933,373 @@ test.describe("Default Invoice Template", () => {"email-visible-in-pdf-default-template.png",);});++ test("displays service period in PDF when enabled and hides it when toggled off", async ({+ page,+ browserName,+ downloadDir,+ }, testInfo) => {+ const SERVICE_PERIOD_TEST_DATA = {+ start: "2025-12-14",+ end: "2025-12-20",+ } as const;++ const CUSTOM_SERVICE_PERIOD_LABEL = "Billing period";++ await expect(page).toHaveURL("/?template=default");++ const generalInfoSection = page.getByTestId("general-information-section");+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(servicePeriodFieldset).toBeVisible();++ const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ });+ await expect(servicePeriodLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.en.servicePeriod,+ );++ const servicePeriodSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ });++ // Service period start and end dates+ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period start" })+ .fill(SERVICE_PERIOD_TEST_DATA.start);++ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period end" })+ .fill(SERVICE_PERIOD_TEST_DATA.end);++ // Custom service period label+ await servicePeriodLabelInput.fill(CUSTOM_SERVICE_PERIOD_LABEL);++ await expect(servicePeriodLabelInput).toHaveValue(+ CUSTOM_SERVICE_PERIOD_LABEL,+ );++ // Check that "Switch to default label ("Service period")" text is displayed+ await expect(+ servicePeriodFieldset.getByRole("button", {+ name: 'Switch to default label ("Service period")',+ }),+ ).toBeVisible();++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.start);+ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.end);+ await expect(servicePeriodSwitch).toBeChecked();++ const finalSection = page.getByTestId("final-section");+ await finalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(`Test: ${testInfo.title} (${testInfo.project.name})`);++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const downloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ await expect(downloadPdfEnglishButton).toBeVisible();+ await expect(downloadPdfEnglishButton).toBeEnabled();++ const [download] = await Promise.all([+ page.waitForEvent("download"),+ downloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath = path.join(+ downloadDir,+ `${browserName}-${download.suggestedFilename()}`,+ );++ await download.saveAs(pdfFilePath);++ const absolutePath = path.resolve(pdfFilePath);+ await expect.poll(() => fs.existsSync(absolutePath)).toBe(true);++ const pdfBytes = fs.readFileSync(absolutePath);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytes);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "displays-service-period-in-pdf-default-template.png",+ );++ await page.goto("/");+ await expect(page).toHaveURL("/?template=default");++ const newGeneralInfoSection = page.getByTestId(+ "general-information-section",+ );+ const newServicePeriodFieldset = newGeneralInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(newServicePeriodFieldset).toBeVisible();++ const newServicePeriodSwitch = newServicePeriodFieldset.getByRole(+ "switch",+ {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ },+ );++ await expect(newServicePeriodSwitch).toBeChecked();++ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ }),+ ).toHaveValue(CUSTOM_SERVICE_PERIOD_LABEL);++ await newServicePeriodSwitch.click();+ await expect(newServicePeriodSwitch).not.toBeChecked();++ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.start);+ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.end);+ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ }),+ ).toHaveValue(CUSTOM_SERVICE_PERIOD_LABEL);++ const newFinalSection = page.getByTestId("final-section");+ await newFinalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(+ `Test: ${testInfo.title} - service period hidden in PDF (${testInfo.project.name})`,+ );++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const newDownloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ const [downloadWithoutServicePeriod] = await Promise.all([+ page.waitForEvent("download"),+ newDownloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath2 = path.join(+ downloadDir,+ `${browserName}-${downloadWithoutServicePeriod.suggestedFilename()}`,+ );++ await downloadWithoutServicePeriod.saveAs(pdfFilePath2);++ const pdfBytesWithoutServicePeriod = fs.readFileSync(pdfFilePath2);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytesWithoutServicePeriod);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "service-period-hidden-in-pdf-default-template.png",+ );+ });++ test("displays date of sales in PDF when enabled and hides it when toggled off", async ({+ page,+ browserName,+ downloadDir,+ }, testInfo) => {+ const CUSTOM_DATE_OF_SALES_LABEL = "Sale date";++ await expect(page).toHaveURL("/?template=default");++ const generalInfoSection = page.getByTestId("general-information-section");+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(servicePeriodFieldset).toBeVisible();++ const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Date of sales PDF label",+ });++ await expect(dateOfServiceLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.en.dateOfService,+ );++ // Custom date of sales label+ await dateOfServiceLabelInput.fill(CUSTOM_DATE_OF_SALES_LABEL);++ await expect(dateOfServiceLabelInput).toHaveValue(+ CUSTOM_DATE_OF_SALES_LABEL,+ );++ // Check that "Switch to default label ("Date of sales")" text is displayed+ await expect(+ servicePeriodFieldset.getByRole("button", {+ name: 'Switch to default label ("Date of sales/of executing the service")',+ }),+ ).toBeVisible();++ const dateOfServiceSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Date of sales/of executing the service" field in the PDF',+ });++ await expect(dateOfServiceSwitch).toBeChecked();++ const finalSection = page.getByTestId("final-section");+ await finalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(`Test: ${testInfo.title} (${testInfo.project.name})`);++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const downloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ await expect(downloadPdfEnglishButton).toBeVisible();+ await expect(downloadPdfEnglishButton).toBeEnabled();++ const [download] = await Promise.all([+ page.waitForEvent("download"),+ downloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath = path.join(+ downloadDir,+ `${browserName}-${download.suggestedFilename()}`,+ );++ await download.saveAs(pdfFilePath);++ const absolutePath = path.resolve(pdfFilePath);+ await expect.poll(() => fs.existsSync(absolutePath)).toBe(true);++ const pdfBytes = fs.readFileSync(absolutePath);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytes);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "date-of-sales-visible-in-pdf-default-template.png",+ );++ await page.goto("/");+ await expect(page).toHaveURL("/?template=default");++ const newGeneralInfoSection = page.getByTestId(+ "general-information-section",+ );+ const newServicePeriodFieldset = newGeneralInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(newServicePeriodFieldset).toBeVisible();++ const newDateOfServiceLabelInput = newServicePeriodFieldset.getByRole(+ "textbox",+ {+ name: "Date of sales PDF label",+ },+ );+ await expect(newDateOfServiceLabelInput).toHaveValue(+ CUSTOM_DATE_OF_SALES_LABEL,+ );++ const newDateOfServiceSwitch = newServicePeriodFieldset.getByRole(+ "switch",+ {+ name: 'Show the "Date of sales/of executing the service" field in the PDF',+ },+ );++ await expect(newDateOfServiceSwitch).toBeChecked();++ await newDateOfServiceSwitch.click();+ await expect(newDateOfServiceSwitch).not.toBeChecked();++ await expect(newDateOfServiceLabelInput).toHaveValue(+ CUSTOM_DATE_OF_SALES_LABEL,+ );++ const newFinalSection = page.getByTestId("final-section");+ await newFinalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(+ `Test: ${testInfo.title} - date of sales hidden in PDF (${testInfo.project.name})`,+ );++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const newDownloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ const [downloadWithoutDateOfSales] = await Promise.all([+ page.waitForEvent("download"),+ newDownloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath2 = path.join(+ downloadDir,+ `${browserName}-${downloadWithoutDateOfSales.suggestedFilename()}`,+ );++ await downloadWithoutDateOfSales.saveAs(pdfFilePath2);++ const pdfBytesWithoutDateOfSales = fs.readFileSync(pdfFilePath2);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytesWithoutDateOfSales);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "date-of-sales-hidden-in-pdf-default-template.png",+ );+ });});diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..dd504fbBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..5d9b1ccBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..6aa7bafBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-hidden-in-pdf-default-template-Mobile-Safari-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..e12cf33Binary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..eb0a5b5Binary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..ceba97dBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/date-of-sales-visible-in-pdf-default-template-Mobile-Safari-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..450f71dBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..ff32d49Binary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..f6f021bBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-default-template-Mobile-Safari-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Desktop-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..4327f89Binary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Chrome-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..8d8056dBinary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Safari-darwin.png b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..43a2fa0Binary files /dev/null and b/e2e/default-invoice-template/default-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-default-template-Mobile-Safari-darwin.png differdiff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.tsindex 1cb3877..c1da9d4 100644--- a/e2e/invoice-form.test.ts+++ b/e2e/invoice-form.test.ts@@ -13,6 +13,7 @@ import {} from "@/app/schema";import { expect, test } from "@playwright/test";import dayjs from "dayjs";+import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";import { INITIAL_INVOICE_DATA } from "../src/app/constants";import {GITHUB_URL,@@ -307,11 +308,69 @@ test.describe("Invoice Generator Page", () => {generalInfoSection.getByRole("textbox", { name: "Date of Issue" }),).toHaveValue(INITIAL_INVOICE_DATA.dateOfIssue);- // Date of Service+ // Service period+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });++ await expect(servicePeriodFieldset).toBeVisible();++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ }),+ ).toHaveValue(INITIAL_INVOICE_DATA.servicePeriodLabelText);++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Date of sales PDF label",+ }),+ ).toHaveValue(INITIAL_INVOICE_DATA.dateOfServiceLabelText);++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue(INITIAL_INVOICE_DATA.dateOfServiceStart);+await expect(- generalInfoSection.getByRole("textbox", { name: "Date of Service" }),+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),).toHaveValue(INITIAL_INVOICE_DATA.dateOfService);+ // Check that info icon is visible+ await expect(+ servicePeriodFieldset.getByTestId("service-period-end-info-icon"),+ ).toBeVisible();++ await expect(+ servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ }),+ ).not.toBeChecked();++ // by default, date of sales is visible in PDF+ const dateOfServiceSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Date of sales/of executing the service" field in the PDF',+ });++ await expect(dateOfServiceSwitch).toBeChecked();+ await dateOfServiceSwitch.click();+ await expect(dateOfServiceSwitch).not.toBeChecked();++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toBeEditable();++ await expect(+ servicePeriodFieldset.getByRole("button", {+ name: 'Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"',+ }),+ ).toBeVisible();+// Invoice Typeawait expect(generalInfoSection.getByRole("textbox", { name: "Header Notes" }),@@ -583,6 +642,54 @@ test.describe("Invoice Generator Page", () => {).toBeVisible();});+ test("updates service period PDF labels on language change and allows customization", async ({+ page,+ }) => {+ const generalInfoSection = page.getByTestId("general-information-section");+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });++ const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ });+ const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Date of sales PDF label",+ });++ await servicePeriodLabelInput.fill("Custom service period label");+ await dateOfServiceLabelInput.fill("Custom date of sales label");++ const languageSelect = generalInfoSection.getByRole("combobox", {+ name: "Invoice PDF Language",+ });+ await languageSelect.selectOption("pl");++ await expect(servicePeriodLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.pl.servicePeriod,+ );+ await expect(dateOfServiceLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.pl.dateOfService,+ );++ await servicePeriodLabelInput.fill("My custom period");+ await expect(+ servicePeriodFieldset.getByRole("button", {+ name: `Switch to default label ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,+ }),+ ).toBeVisible();++ await servicePeriodFieldset+ .getByRole("button", {+ name: `Switch to default label ("${INVOICE_PDF_TRANSLATIONS.pl.servicePeriod}")`,+ })+ .click();++ await expect(servicePeriodLabelInput).toHaveValue(+ INVOICE_PDF_TRANSLATIONS.pl.servicePeriod,+ );+ });+test("can add and remove invoice items and recalculates totals correctly", async ({page,}) => {@@ -1178,48 +1285,49 @@ test.describe("Invoice Generator Page", () => {// Test invalid valuesawait amountInput.fill("-1");await expect(- invoiceItemsSection.getByText("Amount must be positive"),+ invoiceItemsSection.getByText("Amount must be >= 0"),).toBeVisible();// Check that notification is also visibleawait expect(- page- .getByLabel("Notifications alt+T")- .getByText("Amount must be positive"),- ).toBeVisible();-- await amountInput.fill("0");- await expect(- invoiceItemsSection.getByText("Amount must be positive"),+ page.getByLabel("Notifications alt+T").getByText("Amount must be >= 0"),).toBeVisible();- await amountInput.fill("1000000000000"); // 1 trillion+ await amountInput.fill("1000000"); // Exceeds max of 999 999.99await expect(- invoiceItemsSection.getByText("Amount must not exceed 9 999 999 999.99"),+ invoiceItemsSection.getByText("Amount must not exceed 999 999.99"),).toBeVisible();// Check that notification is also visibleawait expect(page.getByLabel("Notifications alt+T")- .getByText("Amount must not exceed 9 999 999 999.99"),+ .getByText("Amount must not exceed 999 999.99"),).toBeVisible();// Test valid values+ await amountInput.fill("0");+ await expect(+ invoiceItemsSection.getByText("Amount must be >= 0"),+ ).toBeHidden();+ await expect(+ invoiceItemsSection.getByText("Amount must not exceed 999 999.99"),+ ).toBeHidden();+await amountInput.fill("1");await expect(- invoiceItemsSection.getByText("Amount must be positive"),+ invoiceItemsSection.getByText("Amount must be >= 0"),).toBeHidden();await expect(- invoiceItemsSection.getByText("Amount must not exceed 9 999 999 999.99"),+ invoiceItemsSection.getByText("Amount must not exceed 999 999.99"),).toBeHidden();- await amountInput.fill("9999999999.99"); // Maximum valid value+ await amountInput.fill("999999.99"); // Maximum valid valueawait expect(- invoiceItemsSection.getByText("Amount must be positive"),+ invoiceItemsSection.getByText("Amount must be >= 0"),).toBeHidden();await expect(- invoiceItemsSection.getByText("Amount must not exceed 9 999 999 999.99"),+ invoiceItemsSection.getByText("Amount must not exceed 999 999.99"),).toBeHidden();// **NET PRICE FIELD**@@ -1244,14 +1352,14 @@ test.describe("Invoice Generator Page", () => {// Test exceeding maximum valueawait netPriceInput.fill("1000000000000"); // 1 trillionawait expect(- invoiceItemsSection.getByText("Net price must not exceed 100 billion"),+ invoiceItemsSection.getByText("Net price must not exceed 1 billion"),).toBeVisible();// Check that notification is also visibleawait expect(page.getByLabel("Notifications alt+T")- .getByText("Net price must not exceed 100 billion"),+ .getByText("Net price must not exceed 1 billion"),).toBeVisible();// Test zero value@@ -1266,7 +1374,15 @@ test.describe("Invoice Generator Page", () => {invoiceItemsSection.getByText("Net price must be >= 0"),).toBeHidden();await expect(- invoiceItemsSection.getByText("Net price must not exceed 100 billion"),+ invoiceItemsSection.getByText("Net price must not exceed 1 billion"),+ ).toBeHidden();++ await netPriceInput.fill("1000000000"); // Maximum valid value+ await expect(+ invoiceItemsSection.getByText("Net price must be >= 0"),+ ).toBeHidden();+ await expect(+ invoiceItemsSection.getByText("Net price must not exceed 1 billion"),).toBeHidden();// **VAT FIELD**@@ -1341,6 +1457,12 @@ test.describe("Invoice Generator Page", () => {netPrice: "100",expected: { net: "300.00", vatAmount: "0.00", total: "300.00" },},+ {+ vat: "23",+ amount: "0",+ netPrice: "100",+ expected: { net: "0.00", vatAmount: "0.00", total: "0.00" },+ },] as const satisfies {vat: string;amount: string;@@ -1419,14 +1541,27 @@ test.describe("Invoice Generator Page", () => {generalInfoSection.getByText("Date of issue is not today"),).toBeVisible();- // Set date of service to a date that's not the last day of current month- const dateOfServiceInput = generalInfoSection.getByLabel("Date of Service");+ // Set service period end to a date that's not the last day of current month+ const dateOfServiceStartInput = generalInfoSection.getByRole("textbox", {+ name: "Service period start",+ });+ const dateOfServiceInput = generalInfoSection.getByRole("textbox", {+ name: "Service period end",+ });+ await dateOfServiceStartInput.fill("2025-06-14");await dateOfServiceInput.fill("2024-01-20");- // Verify per-field "Date of service is not the last day of the current month" inline helper message+ // Verify per-field service period start helper message+ await expect(+ generalInfoSection.getByText(+ "Service period start is not in the current month",+ ),+ ).toBeVisible();++ // Verify per-field service period end helper messageawait expect(generalInfoSection.getByText(- "Date of service is not the last day of the current month",+ "Service period end is not the last day of the current month",),).toBeVisible();@@ -1457,7 +1592,7 @@ test.describe("Invoice Generator Page", () => {// Verify the header shows the correct count of stale fieldsawait expect(- outOfDateHelper.getByText("4 fields are out of date"),+ outOfDateHelper.getByText("5 fields are out of date"),).toBeVisible();// Verify each stale field appears as a row in the table@@ -1465,7 +1600,10 @@ test.describe("Invoice Generator Page", () => {outOfDateHelper.getByText("Date of issue", { exact: true }),).toBeVisible();await expect(- outOfDateHelper.getByText("Date of service", { exact: true }),+ outOfDateHelper.getByText("Service period start", { exact: true }),+ ).toBeVisible();+ await expect(+ outOfDateHelper.getByText("Service period end", { exact: true }),).toBeVisible();await expect(outOfDateHelper.getByText("Invoice number", { exact: true }),@@ -1474,19 +1612,38 @@ test.describe("Invoice Generator Page", () => {outOfDateHelper.getByText("Payment due", { exact: true }),).toBeVisible();- // Verify the table shows old → new values for date fields- await expect(outOfDateHelper.getByText("2024-01-15")).toBeVisible();- await expect(outOfDateHelper.getByText("2024-01-20")).toBeVisible();- await expect(outOfDateHelper.getByText("2025-12-01")).toBeVisible();- await expect(outOfDateHelper.getByText("2025-12-31")).toBeVisible();+ // Verify the table shows old → new values per row (avoids strict mode when targets match)+ const dateOfIssueRow = outOfDateHelper+ .getByRole("row")+ .filter({ hasText: "Date of issue" });++ await expect(dateOfIssueRow.getByText("2024-01-15")).toBeVisible();+ await expect(dateOfIssueRow.getByText("2025-12-01")).toBeVisible();++ const servicePeriodStartRow = outOfDateHelper+ .getByRole("row")+ .filter({ hasText: "Service period start" });++ await expect(servicePeriodStartRow.getByText("2025-06-14")).toBeVisible();+ await expect(servicePeriodStartRow.getByText("2025-12-01")).toBeVisible();++ const servicePeriodEndRow = outOfDateHelper+ .getByRole("row")+ .filter({ hasText: "Service period end" });+ await expect(servicePeriodEndRow.getByText("2024-01-20")).toBeVisible();+ await expect(servicePeriodEndRow.getByText("2025-12-31")).toBeVisible();- // Verify old and new invoice number values in the table- await expect(outOfDateHelper.getByText("1/01-2024")).toBeVisible();- await expect(outOfDateHelper.getByText("1/12-2025")).toBeVisible();+ const invoiceNumberRow = outOfDateHelper+ .getByRole("row")+ .filter({ hasText: "Invoice number" });+ await expect(invoiceNumberRow.getByText("1/01-2024")).toBeVisible();+ await expect(invoiceNumberRow.getByText("1/12-2025")).toBeVisible();- // Verify old and new payment due values in the table- await expect(outOfDateHelper.getByText("2024-01-16")).toBeVisible();- await expect(outOfDateHelper.getByText("2025-12-15")).toBeVisible();+ const paymentDueRow = outOfDateHelper+ .getByRole("row")+ .filter({ hasText: "Payment due" });+ await expect(paymentDueRow.getByText("2024-01-16")).toBeVisible();+ await expect(paymentDueRow.getByText("2025-12-15")).toBeVisible();// Verify the "Update All Dates" button is visibleconst updateAllDatesButton = outOfDateHelper.getByRole("button", {@@ -1511,14 +1668,190 @@ test.describe("Invoice Generator Page", () => {).toBeHidden();await expect(generalInfoSection.getByText(- "Date of service is not the last day of the current month",+ "Service period end is not the last day of the current month",+ ),+ ).toBeHidden();+ await expect(+ generalInfoSection.getByText(+ "Service period start is not in the current month",),).toBeHidden();// Verify all fields were updated to correct valuesawait expect(dateOfIssueInput).toHaveValue("2025-12-01");+ await expect(dateOfServiceStartInput).toHaveValue("2025-12-01");await expect(dateOfServiceInput).toHaveValue("2025-12-31");await expect(invoiceNumberInput).toHaveValue("1/12-2025");await expect(paymentDueInput).toHaveValue("2025-12-15");});++ test("allows setting date of issue to today from inline helper", async ({+ page,+ }) => {+ await page.clock.setSystemTime(new Date("2025-12-01T00:00:00Z"));++ await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");++ const generalInfoSection = page.getByRole("region", {+ name: "General Information",+ });+ const dateOfIssueInput = generalInfoSection.getByLabel("Date of Issue");++ await dateOfIssueInput.fill("2024-01-15");++ await expect(+ generalInfoSection.getByText("Date of issue is not today"),+ ).toBeVisible();++ await generalInfoSection+ .getByRole("button", { name: /Set date of issue to today/ })+ .click();++ await expect(dateOfIssueInput).toHaveValue("2025-12-01");+ await expect(+ generalInfoSection.getByText("Date of issue is not today"),+ ).toBeHidden();+ await expect(page.getByLabel("Payment Due")).toHaveValue("2025-12-15");+ });++ test("allows switching service period PDF label to default from inline helper", async ({+ page,+ }) => {+ const generalInfoSection = page.getByRole("region", {+ name: "General Information",+ });+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ const servicePeriodLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ });+ const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.servicePeriod;+ const switchToDefaultButton = servicePeriodFieldset.getByRole("button", {+ name: `Switch to default label ("${defaultLabel}")`,+ });++ await servicePeriodLabelInput.fill("Custom service period label");++ await expect(switchToDefaultButton).toBeVisible();++ await switchToDefaultButton.click();++ await expect(servicePeriodLabelInput).toHaveValue(defaultLabel);+ await expect(switchToDefaultButton).toBeHidden();+ });++ test("allows switching date of sales PDF label to default from inline helper", async ({+ page,+ }) => {+ const generalInfoSection = page.getByRole("region", {+ name: "General Information",+ });+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ const dateOfServiceLabelInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Date of sales PDF label",+ });+ const defaultLabel = INVOICE_PDF_TRANSLATIONS.en.dateOfService;+ const switchToDefaultButton = servicePeriodFieldset.getByRole("button", {+ name: `Switch to default label ("${defaultLabel}")`,+ });++ await dateOfServiceLabelInput.fill("Custom date of sales label");++ await expect(switchToDefaultButton).toBeVisible();++ await switchToDefaultButton.click();++ await expect(dateOfServiceLabelInput).toHaveValue(defaultLabel);+ await expect(switchToDefaultButton).toBeHidden();+ });++ test("allows setting a partial service period", async ({ page }) => {+ await page.clock.setSystemTime(new Date("2025-06-15T12:00:00Z"));++ await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");++ const generalInfoSection = page.getByRole("region", {+ name: "General Information",+ });++ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });++ const servicePeriodSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ });++ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period start" })+ .fill("2025-06-14");+ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period end" })+ .fill("2025-06-20");++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue("2025-06-14");+ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toHaveValue("2025-06-20");++ await expect(servicePeriodSwitch).toBeChecked();++ await servicePeriodSwitch.click();+ await expect(servicePeriodSwitch).not.toBeChecked();++ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period start" })+ .fill("2025-06-15");+ await expect(servicePeriodSwitch).toBeChecked();+ });++ test("does not auto-enable service period PDF field when start is the first day of its month", async ({+ page,+ }) => {+ await page.clock.setSystemTime(new Date("2025-06-15T12:00:00Z"));++ await page.goto("/?template=default");+ await expect(page).toHaveURL("/?template=default");++ const generalInfoSection = page.getByRole("region", {+ name: "General Information",+ });+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ const servicePeriodStartInput = servicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ });+ const servicePeriodSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ });++ await expect(servicePeriodSwitch).not.toBeChecked();++ // First day of the current month should not auto-enable the PDF field.+ await servicePeriodStartInput.fill("2025-06-01");+ await expect(servicePeriodStartInput).toHaveValue("2025-06-01");+ await expect(servicePeriodSwitch).not.toBeChecked();++ // First day of a different month should also stay off (regression for current-month check).+ await servicePeriodStartInput.fill("2025-05-01");+ await expect(servicePeriodStartInput).toHaveValue("2025-05-01");+ await expect(servicePeriodSwitch).not.toBeChecked();++ // Partial month start should still auto-enable the PDF field.+ await servicePeriodStartInput.fill("2025-05-11");+ await expect(servicePeriodStartInput).toHaveValue("2025-05-11");+ await expect(servicePeriodSwitch).toBeChecked();+ });});diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts b/e2e/stripe-invoice-template/stripe-invoice-template.test.tsindex cd9c9d8..4fac815 100644--- a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts+++ b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts@@ -1193,6 +1193,189 @@ test.describe("Stripe Invoice Template", () => {);});+ test("displays service period in PDF when enabled and hides it when toggled off", async ({+ page,+ browserName,+ downloadDir,+ }, testInfo) => {+ const SERVICE_PERIOD_TEST_DATA = {+ start: "2025-12-14",+ end: "2025-12-20",+ } as const;++ await page+ .getByRole("combobox", { name: "Invoice Template" })+ .selectOption("stripe");++ await page.waitForURL("/?template=stripe");+ await expect(page).toHaveURL("/?template=stripe");++ const generalInfoSection = page.getByTestId("general-information-section");+ const servicePeriodFieldset = generalInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(servicePeriodFieldset).toBeVisible();++ // these fields are hidden by default for the STRIPE template (we don't show them on stripe pdf template)+ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period PDF label",+ }),+ ).toBeHidden();++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Date of sales PDF label",+ }),+ ).toBeHidden();++ const servicePeriodSwitch = servicePeriodFieldset.getByRole("switch", {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ });++ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period start" })+ .fill(SERVICE_PERIOD_TEST_DATA.start);++ await servicePeriodFieldset+ .getByRole("textbox", { name: "Service period end" })+ .fill(SERVICE_PERIOD_TEST_DATA.end);++ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.start);+ await expect(+ servicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.end);+ await expect(servicePeriodSwitch).toBeChecked();++ const finalSection = page.getByTestId("final-section");+ await finalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(`Test: ${testInfo.title} (${testInfo.project.name})`);++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const downloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ await expect(downloadPdfEnglishButton).toBeVisible();+ await expect(downloadPdfEnglishButton).toBeEnabled();++ const [download] = await Promise.all([+ page.waitForEvent("download"),+ downloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath = path.join(+ downloadDir,+ `${browserName}-${download.suggestedFilename()}`,+ );++ await download.saveAs(pdfFilePath);++ const absolutePath = path.resolve(pdfFilePath);+ await expect.poll(() => fs.existsSync(absolutePath)).toBe(true);++ const pdfBytes = fs.readFileSync(absolutePath);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytes);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "displays-service-period-in-pdf-stripe-template.png",+ );++ await page.goto("/");+ await expect(page).toHaveURL("/?template=stripe");++ const newGeneralInfoSection = page.getByTestId(+ "general-information-section",+ );+ const newServicePeriodFieldset = newGeneralInfoSection.getByRole("group", {+ name: "Service period",+ });+ await expect(newServicePeriodFieldset).toBeVisible();++ const newServicePeriodSwitch = newServicePeriodFieldset.getByRole(+ "switch",+ {+ name: 'Show the "Service period" (Service period start and end) field in the PDF',+ },+ );++ await expect(newServicePeriodSwitch).toBeChecked();++ await newServicePeriodSwitch.click();+ await expect(newServicePeriodSwitch).not.toBeChecked();++ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period start",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.start);+ await expect(+ newServicePeriodFieldset.getByRole("textbox", {+ name: "Service period end",+ }),+ ).toHaveValue(SERVICE_PERIOD_TEST_DATA.end);++ const newFinalSection = page.getByTestId("final-section");+ await newFinalSection+ .getByRole("textbox", { name: "Notes", exact: true })+ .fill(+ `Test: ${testInfo.title} - service period hidden in PDF (${testInfo.project.name})`,+ );++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(700);++ const newDownloadPdfEnglishButton = page.getByRole("link", {+ name: "Download PDF in English",+ });++ const [downloadWithoutServicePeriod] = await Promise.all([+ page.waitForEvent("download"),+ newDownloadPdfEnglishButton.click(),+ ]);++ const pdfFilePath2 = path.join(+ downloadDir,+ `${browserName}-${downloadWithoutServicePeriod.suggestedFilename()}`,+ );++ await downloadWithoutServicePeriod.saveAs(pdfFilePath2);++ const pdfBytesWithoutServicePeriod = fs.readFileSync(pdfFilePath2);++ await page.goto("about:blank");++ await renderPdfOnCanvas(page, pdfBytesWithoutServicePeriod);++ await page.waitForFunction(+ () =>+ (window as unknown as { __PDF_RENDERED__: boolean })+ .__PDF_RENDERED__ === true,+ );++ await expect(page.locator("canvas")).toHaveScreenshot(+ "service-period-hidden-in-pdf-stripe-template.png",+ );+ });+test("generates multi-page PDF when invoice has many items", async ({page,browserName,diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Desktop-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..df0f59bBinary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..35a9ca4Binary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Safari-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..3af6b54Binary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/displays-service-period-in-pdf-stripe-template-Mobile-Safari-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Desktop-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..bba098bBinary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Chrome-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Chrome-darwin.pngnew file mode 100644index 0000000..67d02e2Binary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Chrome-darwin.png differdiff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Safari-darwin.png b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Safari-darwin.pngnew file mode 100644index 0000000..2c74376Binary files /dev/null and b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts-snapshots/service-period-hidden-in-pdf-stripe-template-Mobile-Safari-darwin.png differdiff --git a/e2e/utils/extended-playwright-test.ts b/e2e/utils/extended-playwright-test.tsindex 21c567d..132ce74 100644--- a/e2e/utils/extended-playwright-test.ts+++ b/e2e/utils/extended-playwright-test.ts@@ -4,7 +4,7 @@ import path from "node:path";import { test as base } from "@playwright/test";/**- * Extended Playwright test fixture with additional capabilities beyond the default `test` from `@playwright/test`.+ * **Extended Playwright test fixture** with additional capabilities beyond the default `test` from `@playwright/test`.** Provides a temporary download directory for each test:* 1. Creates a unique temp directory in the OS temp folder before the test runsdiff --git a/eslint.config.mjs b/eslint.config.mjsindex b2cecae..f817a94 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -63,6 +63,7 @@ export default tseslint.config(},],"@next/next/no-img-element": "off",+ "react/jsx-no-leaked-render": "warn",},},{diff --git a/playwright.config.ts b/playwright.config.tsindex 83cdb12..c6d236c 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -33,7 +33,7 @@ export default defineConfig({workers: process.env.CI ? 1 : undefined, // IMPORTANT: if tests are flaky locally, make `workers: 1` or `workers: 2`/* timeout for expect assertions */expect: {- timeout: isLocal ? 15_000 : 35_000,+ timeout: isLocal ? 25_000 : 35_000,},// /* timeout for test execution */diff --git a/skills-lock.json b/skills-lock.jsonindex 23e31b4..b5b3c01 100644--- a/skills-lock.json+++ b/skills-lock.json@@ -39,15 +39,35 @@"skillPath": "skills/seo-audit/SKILL.md","computedHash": "ddd028951738fcbcdebf0f9bd90b708c55d1b9370a31603e0c13e5b262d8b8bb"},+ "vercel-composition-patterns": {+ "source": "vercel-labs/agent-skills",+ "sourceType": "github",+ "skillPath": "skills/composition-patterns/SKILL.md",+ "computedHash": "575757e3e25761c8c562d6e395d29f0b76c98b1273c0bd72d88e6ab1bc9c7d42"+ },"vercel-react-best-practices": {"source": "vercel-labs/agent-skills","sourceType": "github",- "computedHash": "3462ec83f862abb2d532953df33a4dbf87f4616849da5d4b5cc7c13601aaf997"+ "skillPath": "skills/react-best-practices/SKILL.md",+ "computedHash": "ca7b0c0c6e5f2750043f7f0cd72d16ac4e2abc48f9b5500d047a4b77a2506212"+ },+ "vercel-react-view-transitions": {+ "source": "vercel-labs/agent-skills",+ "sourceType": "github",+ "skillPath": "skills/react-view-transitions/SKILL.md",+ "computedHash": "c8952fc9127fa0564d0cb71dccb4215a5608ac933b5831104f09173a97a46f85"},"web-design-guidelines": {"source": "vercel-labs/agent-skills","sourceType": "github",- "computedHash": "a6a44d5498f7e8f68289902f3dedfc6f38ae0cee1e96527c80724cf27f727c2a"+ "skillPath": "skills/web-design-guidelines/SKILL.md",+ "computedHash": "f3bc47f890f42a44db1007ab390709ec368e4b8c089baee6b0007182236ac474"+ },+ "writing-guidelines": {+ "source": "vercel-labs/agent-skills",+ "sourceType": "github",+ "skillPath": "skills/writing-guidelines/SKILL.md",+ "computedHash": "25aa3a33a97bddbcb1847ce4a6169106ec25e5b19b15b99c66e75ab383866ef2"}}}diff --git a/src/app/(app)/components/invoice-form/common.tsx b/src/app/(app)/components/invoice-form/common.tsxindex b8cc800..4840a69 100644--- a/src/app/(app)/components/invoice-form/common.tsx+++ b/src/app/(app)/components/invoice-form/common.tsx@@ -1,5 +1,11 @@import { AlertTriangle } from "lucide-react";+export function inputErrorClassName(hasError?: boolean) {+ return hasError+ ? "border-red-500 focus-visible:outline-red-500 focus-visible:ring-red-500 placeholder:text-red-500"+ : "";+}+export const ErrorMessage = ({ children }: { children: React.ReactNode }) => {return <p className="mt-1 text-xs text-red-600">{children}</p>;};diff --git a/src/app/(app)/components/invoice-form/sections/buyer-information.tsx b/src/app/(app)/components/invoice-form/sections/buyer-information.tsxindex 4f6101c..974e232 100644--- a/src/app/(app)/components/invoice-form/sections/buyer-information.tsx+++ b/src/app/(app)/components/invoice-form/sections/buyer-information.tsx@@ -1,6 +1,8 @@"use client";+import { inputErrorClassName } from "@/app/(app)/components/invoice-form/common";import { type BuyerData, type InvoiceData } from "@/app/schema";+import { cn } from "@/lib/utils";import { BuyerManagement } from "@/app/(app)/components/invoice-form/sections/components/buyer/buyer-management";import { AccordionContent } from "@/components/ui/accordion";import { Input } from "@/components/ui/input";@@ -88,7 +90,12 @@ export const BuyerInformation = memo(function BuyerInformation({name="buyer.name"control={control}render={({ field }) => (- <Textarea {...field} id="buyerName" rows={3} />+ <Textarea+ {...field}+ id="buyerName"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.name)}+ />)}/>{errors.buyer?.name && (@@ -104,7 +111,12 @@ export const BuyerInformation = memo(function BuyerInformation({name="buyer.address"control={control}render={({ field }) => (- <Textarea {...field} id="buyerAddress" rows={3} />+ <Textarea+ {...field}+ id="buyerAddress"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.address)}+ />)}/>{errors.buyer?.address && (@@ -162,7 +174,10 @@ export const BuyerInformation = memo(function BuyerInformation({type="text"id="buyerVatNoLabel"placeholder="Enter Tax number label"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.buyer?.vatNoLabelText),+ )}/>)}/>@@ -189,7 +204,10 @@ export const BuyerInformation = memo(function BuyerInformation({id="buyerVatNo"type="text"placeholder="Enter Tax number value"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.buyer?.vatNo),+ )}/>)}/>@@ -238,7 +256,12 @@ export const BuyerInformation = memo(function BuyerInformation({name="buyer.email"control={control}render={({ field }) => (- <Input {...field} id="buyerEmail" type="email" />+ <Input+ {...field}+ id="buyerEmail"+ type="email"+ className={inputErrorClassName(!!errors.buyer?.email)}+ />)}/>{errors.buyer?.email && (@@ -284,7 +307,12 @@ export const BuyerInformation = memo(function BuyerInformation({name="buyer.notes"control={control}render={({ field }) => (- <Textarea {...field} id="buyerNotes" rows={3} />+ <Textarea+ {...field}+ id="buyerNotes"+ rows={3}+ className={inputErrorClassName(!!errors.buyer?.notes)}+ />)}/>{errors.buyer?.notes && (diff --git a/src/app/(app)/components/invoice-form/sections/general-information.tsx b/src/app/(app)/components/invoice-form/sections/general-information.tsxindex 1735d02..a72c047 100644--- a/src/app/(app)/components/invoice-form/sections/general-information.tsx+++ b/src/app/(app)/components/invoice-form/sections/general-information.tsx@@ -1,8 +1,13 @@import {AlertIcon,ErrorMessage,+ inputErrorClassName,} from "@/app/(app)/components/invoice-form/common";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import {+ isFirstDayOfMonth,+ isServicePeriodStartInCurrentMonth,+} from "@/app/(app)/utils/format-service-period";import {DEFAULT_DATE_FORMAT,type InvoiceData,@@ -23,8 +28,9 @@ import { SelectNative } from "@/components/ui/select-native";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { CustomTooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";import dayjs from "dayjs";-import { AlertTriangle, RefreshCw, Upload, X } from "lucide-react";+import { AlertTriangle, InfoIcon, RefreshCw, Upload, X } from "lucide-react";import { memo, useCallback, useRef } from "react";import {type Control,@@ -64,7 +70,18 @@ export const GeneralInformation = memo(function GeneralInformation({name: "invoiceNumberObject.value",});+ const servicePeriodLabelText = useWatch({+ control,+ name: "servicePeriodLabelText",+ });++ const dateOfServiceLabelText = useWatch({+ control,+ name: "dateOfServiceLabelText",+ });+const dateOfService = useWatch({ control, name: "dateOfService" });+ const dateOfServiceStart = useWatch({ control, name: "dateOfServiceStart" });const language = useWatch({ control, name: "language" });const template = useWatch({ control, name: "template" });const logo = useWatch({ control, name: "logo" });@@ -73,14 +90,26 @@ export const GeneralInformation = memo(function GeneralInformation({const t = INVOICE_PDF_TRANSLATIONS[language];const defaultInvoiceNumber = `${t.invoiceNumber}:`;+ const defaultServicePeriodLabel = t.servicePeriod;+ const defaultDateOfServiceLabel = t.dateOfService;++ const isDefaultServicePeriodLabel =+ servicePeriodLabelText === defaultServicePeriodLabel;++ const isDefaultDateOfServiceLabel =+ dateOfServiceLabelText === defaultDateOfServiceLabel;const isDateOfIssueNotToday = !dayjs(dateOfIssue).isSame(dayjs(), "day");- const isDateOfServiceEqualsEndOfCurrentMonth = dayjs(dateOfService).isSame(+ const isDateOfServiceEndOfMonth = dayjs(dateOfService).isSame(dayjs().endOf("month"),"day",);+ const isServicePeriodStartOutsideCurrentMonth =+ !!dateOfServiceStart &&+ !isServicePeriodStartInCurrentMonth(dateOfServiceStart);+const isDefaultInvoiceNumberLabel =invoiceNumberLabel === defaultInvoiceNumber;@@ -151,8 +180,15 @@ export const GeneralInformation = memo(function GeneralInformation({!paymentDue ||!dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"), "day");- const canShowOutOfDateDatesHelper =- !isDateOfServiceEqualsEndOfCurrentMonth ||+ /**+ * Whether to show Stale Dates Banner.+ * Banner appears when any invoice date/number is out of sync with current month.+ * Triggers: service end not end of current month, service start not in current month,+ * invoice number not for current month, issue date not today, payment due not 14 days after issue.+ */+ const canShowStaleDatesBanner =+ !isDateOfServiceEndOfMonth ||+ isServicePeriodStartOutsideCurrentMonth ||!isInvoiceNumberInCurrentMonth ||isDateOfIssueNotToday ||isPaymentDueNotMatchingIssueDate;@@ -172,7 +208,7 @@ export const GeneralInformation = memo(function GeneralInformation({<SelectNative{...field}id={`template`}- className="block"+ className={cn("block", inputErrorClassName(!!errors.template))}onChange={(e) => {field.onChange(e);@@ -186,6 +222,9 @@ export const GeneralInformation = memo(function GeneralInformation({// Set unit field to be HIDDEN by default for Stripe template (matches stripe template behaviour)setValue("items.0.unitFieldIsVisible", false);++ // Set service period field to be VISIBLE for Stripe template (for backwards compatibility)+ setValue("servicePeriodFieldIsVisible", true);} else {// DEFAULT TEMPLATE@@ -235,7 +274,7 @@ export const GeneralInformation = memo(function GeneralInformation({<SelectNative{...field}id={`language`}- className="block"+ className={cn("block", inputErrorClassName(!!errors.language))}onChange={(e) => {field.onChange(e);@@ -274,6 +313,15 @@ export const GeneralInformation = memo(function GeneralInformation({// This ensures the tax column header in the invoice items table// displays the correct translation for the selected languagesetValue("taxLabelText", newTranslation);++ setValue(+ "servicePeriodLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].servicePeriod,+ );+ setValue(+ "dateOfServiceLabelText",+ INVOICE_PDF_TRANSLATIONS[newLanguage].dateOfService,+ );}}>{SUPPORTED_LANGUAGES.map((lang) => {@@ -314,6 +362,7 @@ export const GeneralInformation = memo(function GeneralInformation({id={`currency`}value={field.value}onChange={field.onChange}+ hasError={!!errors.currency}/>)}/>@@ -335,7 +384,11 @@ export const GeneralInformation = memo(function GeneralInformation({name="dateFormat"control={control}render={({ field }) => (- <SelectNative {...field} id={`dateFormat`} className="block">+ <SelectNative+ {...field}+ id={`dateFormat`}+ className={cn("block", inputErrorClassName(!!errors.dateFormat))}+ >{SUPPORTED_DATE_FORMATS.map((format) => {const preview = dayjs().locale(language).format(format);const isDefault = format === DEFAULT_DATE_FORMAT;@@ -376,7 +429,10 @@ export const GeneralInformation = memo(function GeneralInformation({type="text"id="invoiceNumberLabel"placeholder="Enter invoice number label"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.invoiceNumberObject?.label),+ )}/>)}/>@@ -414,7 +470,10 @@ export const GeneralInformation = memo(function GeneralInformation({type="text"id="invoiceNumberValue"placeholder="Enter invoice number value"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.invoiceNumberObject?.value),+ )}/>)}/>@@ -450,7 +509,7 @@ export const GeneralInformation = memo(function GeneralInformation({{...field}type="date"id={`dateOfIssue`}- className=""+ className={inputErrorClassName(!!errors.dateOfIssue)}onChange={(e) => {field.onChange(e);@@ -476,41 +535,279 @@ export const GeneralInformation = memo(function GeneralInformation({<AlertIcon />Date of issue is not today</span>+ <ButtonHelper+ onClick={() => {+ const today = dayjs().format("YYYY-MM-DD");++ setValue("dateOfIssue", today);+ setValue(+ "paymentDue",+ dayjs(today).add(14, "days").format("YYYY-MM-DD"),+ );+ }}+ >+ <span className="text-pretty">+ Set date of issue to today (+ {dayjs().format(selectedDateFormat)})+ </span>+ </ButtonHelper></InputHelperMessage>) : null}</div>- {/* Date of Service */}- <div>- <Label htmlFor={`dateOfService`} className="mb-1">- Date of Service- </Label>- <Controller- name="dateOfService"- control={control}- render={({ field }) => (- <Input {...field} type="date" id={`dateOfService`} className="" />- )}- />- {errors.dateOfService && (- <ErrorMessage>{errors.dateOfService.message}</ErrorMessage>- )}+ <fieldset className="rounded-md border p-4">+ <legend className="px-1 text-lg font-semibold text-gray-900">+ Service period+ </legend>- {!isDateOfServiceEqualsEndOfCurrentMonth && !errors.dateOfService ? (- <InputHelperMessage>- <span className="flex items-center text-amber-800">- <AlertIcon />- Date of service is not the last day of the current month- </span>- </InputHelperMessage>+ {/** Service period PDF visibility toggle */}+ <div className="mb-5 flex flex-col items-start gap-2 sm:justify-end sm:gap-4">+ <div className="inline-flex items-center gap-2">+ <Controller+ name="servicePeriodFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id="servicePeriodFieldIsVisible"+ data-testid="servicePeriodFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ aria-label='Show the "Service period" (Service period start and end) field in the PDF'+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="servicePeriodFieldIsVisible">+ Show "Service period" in PDF+ </Label>+ }+ content='Show the "Service period" (Service period start and end) field in the PDF'+ />+ </div>+ </div>++ {/** Service period start and end inputs */}+ <div className="space-y-4">+ <div>+ <Label htmlFor="dateOfServiceStart" className="mb-1">+ Service period start+ </Label>+ <Controller+ name="dateOfServiceStart"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ type="date"+ id="dateOfServiceStart"+ className={inputErrorClassName(!!errors.dateOfServiceStart)}+ onChange={(e) => {+ field.onChange(e);++ const newServicePeriodStartDate = e.target.value;++ // auto-show "Service period" in PDF when start date is not first day of its month+ if (+ newServicePeriodStartDate &&+ !isFirstDayOfMonth(newServicePeriodStartDate)+ ) {+ setValue("servicePeriodFieldIsVisible", true);+ }+ }}+ />+ )}+ />+ {errors.dateOfServiceStart ? (+ <ErrorMessage>{errors.dateOfServiceStart.message}</ErrorMessage>+ ) : null}++ {isServicePeriodStartOutsideCurrentMonth &&+ !errors.dateOfServiceStart ? (+ <InputHelperMessage>+ <span className="flex items-center text-amber-800">+ <AlertIcon />+ Service period start is not in the current month+ </span>+ </InputHelperMessage>+ ) : null}+ </div>++ <div>+ <div className="mb-1 flex items-center">+ <Label htmlFor="dateOfService">Service period end</Label>+ <CustomTooltip+ content='Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"'+ side="top"+ popoverOnMobile+ trigger={+ <button+ type="button"+ className="ml-1 inline-flex cursor-pointer items-center align-middle"+ aria-label='Shown on PDF as part of "Service period" and as "Date of sales/of executing the service"'+ >+ <InfoIcon+ className="size-3"+ aria-hidden+ data-testid="service-period-end-info-icon"+ />+ </button>+ }+ />+ </div>++ <Controller+ name="dateOfService"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ type="date"+ id="dateOfService"+ className={inputErrorClassName(!!errors.dateOfService)}+ />+ )}+ />+ {errors.dateOfService ? (+ <ErrorMessage>{errors.dateOfService.message}</ErrorMessage>+ ) : null}++ {!isDateOfServiceEndOfMonth && !errors.dateOfService ? (+ <InputHelperMessage>+ <span className="flex items-center text-amber-800">+ <AlertIcon />+ Service period end is not the last day of the current month+ </span>+ </InputHelperMessage>+ ) : null}+ </div>+ </div>++ {/** Service period PDF label customization - default template only */}+ {template === "default" ? (+ <div className="mt-5 space-y-5">+ <div>+ <Label htmlFor="servicePeriodLabelText">+ Service period PDF label+ </Label>+ <Controller+ name="servicePeriodLabelText"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id="servicePeriodLabelText"+ rows={2}+ placeholder="Enter service period PDF label"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.servicePeriodLabelText),+ )}+ />+ )}+ />+ {errors.servicePeriodLabelText ? (+ <ErrorMessage>+ {errors.servicePeriodLabelText.message}+ </ErrorMessage>+ ) : null}+ {!isDefaultServicePeriodLabel ? (+ <InputHelperMessage>+ <ButtonHelper+ onClick={() => {+ setValue(+ "servicePeriodLabelText",+ defaultServicePeriodLabel,+ );+ }}+ >+ Switch to default label ("{defaultServicePeriodLabel}+ ")+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>++ <div>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor="dateOfServiceLabelText">+ Date of sales PDF label+ </Label>+ <div className="inline-flex items-center gap-2">+ <Controller+ name="dateOfServiceFieldIsVisible"+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id="dateOfServiceFieldIsVisible"+ data-testid="dateOfServiceFieldIsVisible"+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ aria-label='Show the "Date of sales/of executing the service" field in the PDF'+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor="dateOfServiceFieldIsVisible">+ Show in PDF+ </Label>+ }+ content='Show the "Date of sales/of executing the service" field in the PDF'+ />+ </div>+ </div>+ <Controller+ name="dateOfServiceLabelText"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id="dateOfServiceLabelText"+ rows={2}+ placeholder="Enter date of sales (Service period end) PDF label"+ className={cn(+ "block w-full",+ inputErrorClassName(!!errors.dateOfServiceLabelText),+ )}+ />+ )}+ />+ {errors.dateOfServiceLabelText ? (+ <ErrorMessage>+ {errors.dateOfServiceLabelText.message}+ </ErrorMessage>+ ) : null}+ {!isDefaultDateOfServiceLabel ? (+ <InputHelperMessage>+ <ButtonHelper+ onClick={() => {+ setValue(+ "dateOfServiceLabelText",+ defaultDateOfServiceLabel,+ );+ }}+ >+ Switch to default label ("{defaultDateOfServiceLabel}+ ")+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>+ </div>) : null}- </div>+ </fieldset>{/* Out of Date Dates Helper */}- {canShowOutOfDateDatesHelper ? (- <OutOfDateDatesHelper+ {canShowStaleDatesBanner ? (+ <StaleDatesBannerdateOfIssue={dateOfIssue}dateOfService={dateOfService}+ dateOfServiceStart={dateOfServiceStart ?? ""}invoiceNumberValue={invoiceNumberValue ?? ""}paymentDue={paymentDue ?? ""}selectedDateFormat={selectedDateFormat ?? DEFAULT_DATE_FORMAT}@@ -561,7 +858,7 @@ export const GeneralInformation = memo(function GeneralInformation({{...field}id={`invoiceType`}rows={2}- className=""+ className={inputErrorClassName(!!errors.invoiceType)}placeholder="Enter header notes"/>)}@@ -580,7 +877,6 @@ export const GeneralInformation = memo(function GeneralInformation({<div className="space-y-2">{/* Logo preview */}<div className="relative inline-block">- {/* eslint-disable-next-line @next/next/no-img-element */}<imgsrc={logo}alt="Company logo preview"@@ -646,7 +942,10 @@ export const GeneralInformation = memo(function GeneralInformation({{...field}id={`stripePayOnlineUrl`}type="url"- className="mt-1"+ className={cn(+ "mt-1",+ inputErrorClassName(!!errors.stripePayOnlineUrl),+ )}/>)}/>@@ -668,6 +967,7 @@ export const GeneralInformation = memo(function GeneralInformation({interface OutOfDateDatesHelperProps {dateOfIssue: string;dateOfService: string;+ dateOfServiceStart: string;invoiceNumberValue: string;paymentDue: string;selectedDateFormat: string;@@ -676,15 +976,16 @@ interface OutOfDateDatesHelperProps {}/**- * Displays a helper component that detects and allows updating stale invoice dates.+ * Displays a helper (banner) component that detects and allows updating stale invoice dates.*- * This component checks if the invoice dates (date of issue, date of service, payment due)- * and invoice number are outdated compared to the current date. If any are stale, it displays- * a table showing the old vs new values and provides a button to update all dates at once.+ * This component checks if the invoice dates (date of issue, service period start/end,+ * payment due) and invoice number are outdated compared to the current date. If any are stale,+ * it displays a banner with a table showing the old vs new values and provides a button to update all dates at once.*/-function OutOfDateDatesHelper({+function StaleDatesBanner({dateOfIssue,dateOfService,+ dateOfServiceStart,invoiceNumberValue,paymentDue,selectedDateFormat,@@ -699,6 +1000,9 @@ function OutOfDateDatesHelper({dayjs().endOf("month"),"day",);+ const isDateOfServiceStartStale =+ !!dateOfServiceStart &&+ !isServicePeriodStartInCurrentMonth(dateOfServiceStart);const extractedMonthYear = /(\d{2}-\d{4})/.exec(invoiceNumberValue)?.[1];const isInvoiceNumberStale = extractedMonthYear !== CURRENT_MONTH_AND_YEAR;@@ -717,12 +1021,19 @@ function OutOfDateDatesHelper({.locale("en").endOf("month").format(selectedDateFormat);+ const targetStartOfMonth = dayjs()+ .locale("en")+ .startOf("month")+ .format(selectedDateFormat);const targetPaymentDue = dayjs().locale("en").add(14, "days").format(selectedDateFormat);+const targetInvoiceNumber = `1/${CURRENT_MONTH_AND_YEAR}`;+ const fallbackValue = "(not set)";+/*** Array of items to check for staleness.* Each item is either false (not stale) or an object containing:@@ -742,25 +1053,33 @@ function OutOfDateDatesHelper({)[] = [isDateOfIssueStale && {label: "Date of issue",- oldValue: formatDate(dateOfIssue),+ oldValue: dateOfIssue ? formatDate(dateOfIssue) : fallbackValue,newValue: targetToday,hint: "today",},isDateOfServiceStale && {- label: "Date of service",- oldValue: formatDate(dateOfService),+ label: "Service period end",+ oldValue: dateOfService ? formatDate(dateOfService) : fallbackValue,newValue: targetEndOfMonth,hint: "end of current month",},+ isDateOfServiceStartStale && {+ label: "Service period start",+ oldValue: dateOfServiceStart+ ? formatDate(dateOfServiceStart)+ : fallbackValue,+ newValue: targetStartOfMonth,+ hint: "start of current month",+ },isInvoiceNumberStale && {label: "Invoice number",- oldValue: invoiceNumberValue || "—",+ oldValue: invoiceNumberValue ? invoiceNumberValue : fallbackValue,newValue: targetInvoiceNumber,hint: "current month",},isPaymentDueStale && {label: "Payment due",- oldValue: paymentDue ? formatDate(paymentDue) : "—",+ oldValue: paymentDue ? formatDate(paymentDue) : fallbackValue,newValue: targetPaymentDue,hint: "date of issue + 14 days",},@@ -834,10 +1153,14 @@ function OutOfDateDatesHelper({onClick={() => {const today = dayjs().format("YYYY-MM-DD");+ const firstDayOfCurrentMonth = dayjs()+ .startOf("month")+ .format("YYYY-MM-DD");const lastDayOfCurrentMonth = dayjs().endOf("month").format("YYYY-MM-DD");+ setValue("dateOfServiceStart", firstDayOfCurrentMonth);setValue("dateOfService", lastDayOfCurrentMonth);setValue("dateOfIssue", today);setValue("invoiceNumberObject.value", targetInvoiceNumber);diff --git a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(app)/components/invoice-form/sections/invoice-items.tsxindex 8dd4d10..2ba3ead 100644--- a/src/app/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(app)/components/invoice-form/sections/invoice-items.tsx@@ -1,8 +1,10 @@+import { inputErrorClassName } from "@/app/(app)/components/invoice-form/common";import {type InvoiceData,type SupportedCurrencies,type SupportedLanguages,} from "@/app/schema";+import { cn } from "@/lib/utils";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { memo, useState } from "react";@@ -148,7 +150,9 @@ export const InvoiceItems = memo(function InvoiceItems({{...field}rows={4}id={`itemName${index}`}- className=""+ className={inputErrorClassName(+ !!errors.items?.[index]?.name,+ )}/>)}/>@@ -208,7 +212,9 @@ export const InvoiceItems = memo(function InvoiceItems({<Input{...field}id={`itemTypeOfGTU${index}`}- className=""+ className={inputErrorClassName(+ !!errors.items?.[index]?.typeOfGTU,+ )}type="text"/>)}@@ -277,7 +283,9 @@ export const InvoiceItems = memo(function InvoiceItems({type="number"step="0.01"min="0"- className=""+ className={inputErrorClassName(+ !!errors.items?.[index]?.amount,+ )}/>{!errors.items?.[index]?.amount && (<InputHelperMessage>@@ -336,7 +344,14 @@ export const InvoiceItems = memo(function InvoiceItems({name={`items.${index}.unit`}control={control}render={({ field }) => (- <Input {...field} id={`itemUnit${index}`} type="text" />+ <Input+ {...field}+ id={`itemUnit${index}`}+ type="text"+ className={inputErrorClassName(+ !!errors.items?.[index]?.unit,+ )}+ />)}/>{errors.items?.[index]?.unit && (@@ -415,7 +430,12 @@ export const InvoiceItems = memo(function InvoiceItems({type="number"step="0.01"min="0"- className="w-full"+ className={cn(+ "w-full",+ inputErrorClassName(+ !!errors.items?.[index]?.netPrice,+ ),+ )}dataTestId={`itemNetPrice${index}`}/>{!errors.items?.[index]?.netPrice && (@@ -483,7 +503,10 @@ export const InvoiceItems = memo(function InvoiceItems({type="text"id="taxLabelText"placeholder="Enter tax label (e.g., VAT, Tax, GST, Sales Tax)"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.taxLabelText),+ )}/>)}/>@@ -514,7 +537,9 @@ export const InvoiceItems = memo(function InvoiceItems({{...field}id={`itemVat${index}`}type="text"- className=""+ className={inputErrorClassName(+ !!errors.items?.[index]?.vat,+ )}/>)}/>@@ -583,6 +608,9 @@ export const InvoiceItems = memo(function InvoiceItems({minimumFractionDigits: 2,maximumFractionDigits: 2,})}+ className={inputErrorClassName(+ !!errors.items?.[index]?.netAmount,+ )}dataTestId={`itemNetAmount${index}`}/>);@@ -652,6 +680,9 @@ export const InvoiceItems = memo(function InvoiceItems({minimumFractionDigits: 2,maximumFractionDigits: 2,})}+ className={inputErrorClassName(+ !!errors.items?.[index]?.vatAmount,+ )}data-testid="vat-amount"/>);@@ -722,6 +753,9 @@ export const InvoiceItems = memo(function InvoiceItems({minimumFractionDigits: 2,maximumFractionDigits: 2,})}+ className={inputErrorClassName(+ !!errors.items?.[index]?.preTaxAmount,+ )}/>);}}diff --git a/src/app/(app)/components/invoice-form/sections/seller-information.tsx b/src/app/(app)/components/invoice-form/sections/seller-information.tsxindex 1b6f630..9428f93 100644--- a/src/app/(app)/components/invoice-form/sections/seller-information.tsx+++ b/src/app/(app)/components/invoice-form/sections/seller-information.tsx@@ -1,4 +1,6 @@+import { inputErrorClassName } from "@/app/(app)/components/invoice-form/common";import { SellerManagement } from "@/app/(app)/components/invoice-form/sections/components/seller/seller-management";+import { cn } from "@/lib/utils";import { type InvoiceData, type SellerData } from "@/app/schema";import { AccordionContent } from "@/components/ui/accordion";import { Input } from "@/components/ui/input";@@ -90,7 +92,12 @@ export const SellerInformation = memo(function SellerInformation({name="seller.name"control={control}render={({ field }) => (- <Textarea {...field} id="sellerName" rows={3} />+ <Textarea+ {...field}+ id="sellerName"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.name)}+ />)}/>{errors.seller?.name && (@@ -106,7 +113,12 @@ export const SellerInformation = memo(function SellerInformation({name="seller.address"control={control}render={({ field }) => (- <Textarea {...field} id="sellerAddress" rows={3} />+ <Textarea+ {...field}+ id="sellerAddress"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.address)}+ />)}/>{errors.seller?.address && (@@ -164,7 +176,10 @@ export const SellerInformation = memo(function SellerInformation({type="text"id="sellerVatNoLabel"placeholder="Enter Tax number label"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.seller?.vatNoLabelText),+ )}/>)}/>@@ -191,7 +206,10 @@ export const SellerInformation = memo(function SellerInformation({id="sellerVatNo"type="text"placeholder="Enter Tax number value"- className="mt-1 block w-full"+ className={cn(+ "mt-1 block w-full",+ inputErrorClassName(!!errors.seller?.vatNo),+ )}/>)}/>@@ -242,7 +260,12 @@ export const SellerInformation = memo(function SellerInformation({name="seller.email"control={control}render={({ field }) => (- <Input {...field} id="sellerEmail" type="email" />+ <Input+ {...field}+ id="sellerEmail"+ type="email"+ className={inputErrorClassName(!!errors.seller?.email)}+ />)}/>{errors.seller?.email && (@@ -289,7 +312,14 @@ export const SellerInformation = memo(function SellerInformation({name="seller.accountNumber"control={control}render={({ field }) => (- <Textarea {...field} id="sellerAccountNumber" rows={3} />+ <Textarea+ {...field}+ id="sellerAccountNumber"+ rows={3}+ className={inputErrorClassName(+ !!errors.seller?.accountNumber,+ )}+ />)}/>{errors.seller?.accountNumber && (@@ -337,7 +367,12 @@ export const SellerInformation = memo(function SellerInformation({name="seller.swiftBic"control={control}render={({ field }) => (- <Textarea {...field} id="sellerSwiftBic" rows={3} />+ <Textarea+ {...field}+ id="sellerSwiftBic"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.swiftBic)}+ />)}/>{errors.seller?.swiftBic && (@@ -384,7 +419,12 @@ export const SellerInformation = memo(function SellerInformation({name="seller.notes"control={control}render={({ field }) => (- <Textarea {...field} id="sellerNotes" rows={3} />+ <Textarea+ {...field}+ id="sellerNotes"+ rows={3}+ className={inputErrorClassName(!!errors.seller?.notes)}+ />)}/>{errors.seller?.notes && (diff --git a/src/app/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-header.tsx b/src/app/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-header.tsxindex ac72b86..da5b4d4 100644--- a/src/app/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-header.tsx+++ b/src/app/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-header.tsx@@ -3,28 +3,78 @@ import { type InvoiceData } from "@/app/schema";import dayjs from "dayjs";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import {+ formatDateOfServiceEnd,+ formatServicePeriodRange,+} from "@/app/(app)/utils/format-service-period";import type { PDF_DEFAULT_TEMPLATE_STYLES } from ".";-/**- * Invoice number, date of issue and date of service fields on top of the invoice- */-export function InvoiceHeader({+function HeaderDates({invoiceData,styles,}: {invoiceData: InvoiceData;styles: typeof PDF_DEFAULT_TEMPLATE_STYLES;}) {- const language = invoiceData.language;- const t = INVOICE_PDF_TRANSLATIONS[language];+ const t = INVOICE_PDF_TRANSLATIONS[invoiceData.language];const dateOfIssue = dayjs(invoiceData.dateOfIssue).format(invoiceData.dateFormat,);- const dateOfService = dayjs(invoiceData.dateOfService).format(- invoiceData.dateFormat,+ const dateOfServiceEnd = formatDateOfServiceEnd(invoiceData);+ const servicePeriodRange = formatServicePeriodRange(invoiceData);++ const showServicePeriod = invoiceData?.servicePeriodFieldIsVisible;++ const showDateOfService = invoiceData?.dateOfServiceFieldIsVisible;++ const servicePeriodLabel =+ invoiceData.servicePeriodLabelText ?? t.servicePeriod;+ const dateOfServiceLabel =+ invoiceData.dateOfServiceLabelText ?? t.dateOfService;++ return (+ <View+ style={{+ display: "flex",+ flexDirection: "column",+ alignItems: "flex-end",+ }}+ >+ <Text style={styles.fontSize7}>+ {t.dateOfIssue}:{" "}+ <Text style={[styles.fontBold, styles.fontSize8]}>{dateOfIssue}</Text>+ </Text>+ {showServicePeriod ? (+ <Text style={styles.fontSize7}>+ {servicePeriodLabel}:{" "}+ <Text style={[styles.fontBold, styles.fontSize8]}>+ {servicePeriodRange}+ </Text>+ </Text>+ ) : null}+ {showDateOfService ? (+ <Text style={styles.fontSize7}>+ {dateOfServiceLabel}:{" "}+ <Text style={[styles.fontBold, styles.fontSize8]}>+ {dateOfServiceEnd}+ </Text>+ </Text>+ ) : null}+ </View>);+}+/**+ * Invoice number, date of issue and date of service fields on top of the invoice+ */+export function InvoiceHeader({+ invoiceData,+ styles,+}: {+ invoiceData: InvoiceData;+ styles: typeof PDF_DEFAULT_TEMPLATE_STYLES;+}) {const invoiceNumberLabel = invoiceData?.invoiceNumberObject?.label;const invoiceNumberValue = invoiceData?.invoiceNumberObject?.value;@@ -57,26 +107,7 @@ export function InvoiceHeader({}}/></View>- <View- style={{- display: "flex",- flexDirection: "column",- alignItems: "flex-end",- }}- >- <Text style={styles.fontSize7}>- {t.dateOfIssue}:{" "}- <Text style={[styles.fontBold, styles.fontSize8]}>- {dateOfIssue}- </Text>- </Text>- <Text style={styles.fontSize7}>- {t.dateOfService}:{" "}- <Text style={[styles.fontBold, styles.fontSize8]}>- {dateOfService}- </Text>- </Text>- </View>+ <HeaderDates invoiceData={invoiceData} styles={styles} /></View>) : null}@@ -101,26 +132,7 @@ export function InvoiceHeader({) : null}</View>{!hasLogo ? (- <View- style={{- display: "flex",- flexDirection: "column",- alignItems: "flex-end",- }}- >- <Text style={styles.fontSize7}>- {t.dateOfIssue}:{" "}- <Text style={[styles.fontBold, styles.fontSize8]}>- {dateOfIssue}- </Text>- </Text>- <Text style={styles.fontSize7}>- {t.dateOfService}:{" "}- <Text style={[styles.fontBold, styles.fontSize8]}>- {dateOfService}- </Text>- </Text>- </View>+ <HeaderDates invoiceData={invoiceData} styles={styles} />) : null}</View></View>diff --git a/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx b/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsxindex 6891141..dd96293 100644--- a/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx+++ b/src/app/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx@@ -1,4 +1,5 @@import { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";+import { formatServicePeriodRange } from "@/app/(app)/utils/format-service-period";import { formatCurrency } from "@/app/(app)/utils/format-currency";import type { InvoiceData } from "@/app/schema";import { Text, View } from "@react-pdf/renderer/lib/react-pdf.browser";@@ -32,13 +33,7 @@ export function StripeItemsTable({dayjs.locale(language);// Calculate service period (example: Jan 01 2025 - Jan 31 2025)- const servicePeriodStart = dayjs(invoiceData.dateOfService)- .startOf("month")- .format(invoiceData.dateFormat);-- const servicePeriodEnd = dayjs(invoiceData.dateOfService).format(- invoiceData.dateFormat,- );+ const servicePeriod = formatServicePeriodRange(invoiceData);const unitFieldIsVisible = invoiceData.items[0].unitFieldIsVisible;const vatAmountFieldIsVisible = invoiceData.items[0].vatFieldIsVisible;@@ -109,10 +104,11 @@ export function StripeItemsTable({><View style={styles.colDescription}><Text style={[styles.fontSize10]}>{item.name}</Text>- {/* Add service period if available */}- <Text style={[styles.fontSize9, styles.mt4]}>- {servicePeriodStart} – {servicePeriodEnd}- </Text>+ {invoiceData.servicePeriodFieldIsVisible ? (+ <Text style={[styles.fontSize9, styles.mt4]}>+ {servicePeriod}+ </Text>+ ) : null}</View><View style={styles.colQty}><Text style={[styles.fontSize11, styles.textDark]}>diff --git a/src/app/(app)/pdf-i18n-translations/pdf-translations.ts b/src/app/(app)/pdf-i18n-translations/pdf-translations.tsindex 5677642..4718231 100644--- a/src/app/(app)/pdf-i18n-translations/pdf-translations.ts+++ b/src/app/(app)/pdf-i18n-translations/pdf-translations.ts@@ -172,6 +172,7 @@ export const translationSchema = zinvoiceNumber: z.string(),dateOfIssue: z.string(),dateOfService: z.string(),+ servicePeriod: z.string(),invoiceType: z.string(),seller: sellerTranslationSchema,buyer: buyerTranslationSchema,@@ -215,6 +216,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Invoice No. of",dateOfIssue: "Date of issue",dateOfService: "Date of sales/of executing the service",+ servicePeriod: "Service period",invoiceType: "Invoice Type",seller: {name: "Seller",@@ -337,6 +339,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Faktura nr",dateOfIssue: "Data wystawienia",dateOfService: "Data sprzedaży / wykonania usługi",+ servicePeriod: "Okres realizacji",invoiceType: "Typ faktury",seller: {name: "Sprzedawca",@@ -424,6 +427,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Rechnungsnummer",dateOfIssue: "Ausstellungsdatum",dateOfService: "Verkaufsdatum/Leistungsdatum",+ servicePeriod: "Leistungszeitraum",invoiceType: "Rechnungstyp",seller: {name: "Verkäufer",@@ -511,6 +515,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Factura N°",dateOfIssue: "Fecha de emisión",dateOfService: "Fecha de venta/prestación del servicio",+ servicePeriod: "Periodo de servicio",invoiceType: "Tipo de factura",seller: {name: "Vendedor",@@ -598,6 +603,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Fatura N°",dateOfIssue: "Data de emissão",dateOfService: "Data de venda/prestação do serviço",+ servicePeriod: "Período de serviço",invoiceType: "Tipo de fatura",seller: {name: "Vendedor",@@ -685,6 +691,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Инвойс №",dateOfIssue: "Дата выставления",dateOfService: "Дата продажи/оказания услуги",+ servicePeriod: "Период оказания услуг",invoiceType: "Тип счёта",seller: {name: "Продавец",@@ -772,6 +779,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Рахунок-фактура №",dateOfIssue: "Дата виставлення",dateOfService: "Дата продажу/надання послуги",+ servicePeriod: "Період надання послуги",invoiceType: "Тип рахунку",seller: {name: "Продавець",@@ -859,6 +867,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Facture N°",dateOfIssue: "Date d'émission",dateOfService: "Date de vente/prestation de service",+ servicePeriod: "Période de service",invoiceType: "Type de facture",seller: {name: "Vendeur",@@ -946,6 +955,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Fattura N°",dateOfIssue: "Data di emissione",dateOfService: "Data di vendita/prestazione del servizio",+ servicePeriod: "Periodo di servizio",invoiceType: "Tipo di fattura",seller: {name: "Venditore",@@ -1033,6 +1043,7 @@ export const INVOICE_PDF_TRANSLATIONS = {invoiceNumber: "Factuurnummer",dateOfIssue: "Uitgiftedatum",dateOfService: "Datum van verkoop/dienstverlening",+ servicePeriod: "Dienstverleningperiode",invoiceType: "Factuurtype",seller: {name: "Verkoper",diff --git a/src/app/(app)/utils/__tests__/format-service-period.test.ts b/src/app/(app)/utils/__tests__/format-service-period.test.tsnew file mode 100644index 0000000..a18cc0d--- /dev/null+++ b/src/app/(app)/utils/__tests__/format-service-period.test.ts@@ -0,0 +1,100 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ formatDateOfServiceEnd,+ formatServicePeriodRange,+ getServicePeriod,+ isFirstDayOfMonth,+ isServicePeriodStartInCurrentMonth,+} from "@/app/(app)/utils/format-service-period";+import type { InvoiceData } from "@/app/schema";++const baseInvoiceData = {+ dateFormat: "YYYY-MM-DD",+} as Pick<InvoiceData, "dateFormat">;++describe("format-service-period", () => {+ describe("getServicePeriod", () => {+ it("should derive start from end month when start is missing", () => {+ const { start, end } = getServicePeriod({+ dateOfService: "2025-06-20",+ });++ expect(start.format("YYYY-MM-DD")).toBe("2025-06-01");+ expect(end.format("YYYY-MM-DD")).toBe("2025-06-20");+ });++ it("should use explicit start when provided", () => {+ const { start, end } = getServicePeriod({+ dateOfServiceStart: "2025-06-14",+ dateOfService: "2025-06-20",+ });++ expect(start.format("YYYY-MM-DD")).toBe("2025-06-14");+ expect(end.format("YYYY-MM-DD")).toBe("2025-06-20");+ });+ });++ describe("formatDateOfServiceEnd", () => {+ it("should always return the formatted end date", () => {+ const result = formatDateOfServiceEnd({+ ...baseInvoiceData,+ dateOfServiceStart: "2025-06-14",+ dateOfService: "2025-06-20",+ } as InvoiceData);++ expect(result).toBe("2025-06-20");+ });+ });++ describe("isFirstDayOfMonth", () => {+ it("should return true for the first day of any month", () => {+ expect(isFirstDayOfMonth("2026-05-01")).toBe(true);+ expect(isFirstDayOfMonth("2025-12-01")).toBe(true);+ });++ it("should return false for non-first days regardless of current month", () => {+ expect(isFirstDayOfMonth("2026-05-11")).toBe(false);+ expect(isFirstDayOfMonth("2025-06-14")).toBe(false);+ });+ });++ describe("isServicePeriodStartInCurrentMonth", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2025-06-15T12:00:00Z"));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("should return true when start is the first day of the current month", () => {+ expect(isServicePeriodStartInCurrentMonth("2025-06-01")).toBe(true);+ });++ it("should return true when start is mid-month in the current month", () => {+ expect(isServicePeriodStartInCurrentMonth("2025-06-14")).toBe(true);+ });++ it("should return false when start is in a different month of the same year", () => {+ expect(isServicePeriodStartInCurrentMonth("2025-05-01")).toBe(false);+ });++ it("should return false when start is in the same month of a different year", () => {+ expect(isServicePeriodStartInCurrentMonth("2024-06-01")).toBe(false);+ });+ });++ describe("formatServicePeriodRange", () => {+ it("should always show start and end separated by an en dash", () => {+ const result = formatServicePeriodRange({+ ...baseInvoiceData,+ dateOfServiceStart: "2025-06-14",+ dateOfService: "2025-06-20",+ } as InvoiceData);++ expect(result).toBe("2025-06-14 – 2025-06-20");+ });+ });+});diff --git a/src/app/(app)/utils/format-service-period.ts b/src/app/(app)/utils/format-service-period.tsnew file mode 100644index 0000000..f552250--- /dev/null+++ b/src/app/(app)/utils/format-service-period.ts@@ -0,0 +1,71 @@+import type { InvoiceData } from "@/app/schema";+import dayjs from "dayjs";++interface ServicePeriod {+ start: dayjs.Dayjs;+ end: dayjs.Dayjs;+}++/**+ * Get service period (start and end Dayjs objects) from invoice data.+ * If dateOfServiceStart is missing, start set to first day of end's month.+ * @param invoiceData - Contains dateOfService and optional dateOfServiceStart.+ * @returns ServicePeriod with Dayjs start and end.+ */+export function getServicePeriod(invoiceData: {+ dateOfService: string;+ dateOfServiceStart?: string;+}): ServicePeriod {+ const end = dayjs(invoiceData.dateOfService);+ const start = dayjs(+ invoiceData.dateOfServiceStart ?? end.startOf("month").format("YYYY-MM-DD"),+ );++ return { start, end };+}++/**+ * Format service period end date using invoice's date format.+ * @param invoiceData - Invoice containing dateFormat and dateOfService.+ * @returns Formatted end date string.+ */+export function formatDateOfServiceEnd(invoiceData: InvoiceData): string {+ const { end } = getServicePeriod(invoiceData);++ return end.format(invoiceData.dateFormat);+}++/**+ * Check if given date is the first day of its own month.+ * @param date - ISO date string.+ * @returns True if date is the first day of its month.+ */+export function isFirstDayOfMonth(date: string): boolean {+ const parsed = dayjs(date);++ return parsed.isSame(parsed.startOf("month"), "day");+}++/**+ * Check if given dateOfServiceStart is in the current calendar month.+ * @param dateOfServiceStart - ISO date string.+ * @returns True if date is in the current month and year.+ */+export function isServicePeriodStartInCurrentMonth(+ dateOfServiceStart: string,+): boolean {+ return dayjs(dateOfServiceStart).isSame(dayjs(), "month");+}++/**+ * Format start and end of service period as range using invoice's date format.+ * @param invoiceData - Invoice containing dateFormat and service period dates.+ * @returns Range string: 'start – end', formatted.+ */+export function formatServicePeriodRange(+ invoiceData: InvoiceData,+): `${string} – ${string}` {+ const { start, end } = getServicePeriod(invoiceData);++ return `${start.format(invoiceData.dateFormat)} – ${end.format(invoiceData.dateFormat)}`;+}diff --git a/src/app/api/generate-invoice/render-pdf-on-server.tsx b/src/app/api/generate-invoice/render-pdf-on-server.tsxindex 2970ffb..3301e59 100644--- a/src/app/api/generate-invoice/render-pdf-on-server.tsx+++ b/src/app/api/generate-invoice/render-pdf-on-server.tsx@@ -3,6 +3,7 @@ import { InvoiceBody } from "@/app/(app)/components/invoice-templates/invoice-pdimport { INVOICE_PDF_TRANSLATIONS } from "@/app/(app)/pdf-i18n-translations/pdf-translations";import {INVOICE_DEFAULT_NUMBER_VALUE,+ FIRST_DAY_OF_MONTH,LAST_DAY_OF_MONTH,PAYMENT_DUE,TODAY,@@ -85,7 +86,12 @@ export const ENGLISH_INVOICE_REAL_DATA = {},dateOfIssue: TODAY,+ dateOfServiceStart: FIRST_DAY_OF_MONTH,dateOfService: LAST_DAY_OF_MONTH,+ servicePeriodFieldIsVisible: false,+ dateOfServiceFieldIsVisible: true,+ servicePeriodLabelText: "Service period",+ dateOfServiceLabelText: "Date of sales/of executing the service",paymentDue: PAYMENT_DUE,invoiceType: "Reverse Charge",diff --git a/src/app/api/generate-invoice/route.tsx b/src/app/api/generate-invoice/route.tsxindex d916b1d..07f8e85 100644--- a/src/app/api/generate-invoice/route.tsx+++ b/src/app/api/generate-invoice/route.tsx@@ -75,6 +75,25 @@ export async function GET(req: NextRequest) {const shouldSaveToGoogleDrive =req.nextUrl.searchParams.get("saveToGoogleDrive") !== "false";+ const testModeWarnings: string[] = [];++ if (!shouldSendEmail) {+ testModeWarnings.push("👉 Email sending *disabled* (`sendEmail=false`)");+ }++ if (!shouldSaveToGoogleDrive) {+ testModeWarnings.push(+ "👉 Google Drive upload *disabled* (`saveToGoogleDrive=false`)",+ );+ }++ const testModeWarningBlock =+ testModeWarnings.length > 0+ ? `\n\n⚠️⚠️⚠️ *Test mode warning:* ⚠️⚠️⚠️\n\n${testModeWarnings+ .map((w) => `- ${w}`)+ .join("\n")}\n\n------------------------------------\n`+ : "";+const GENERATED_ENGLISH_INVOICE_PDF_DOCUMENT = renderToBuffer(<InvoicePdfTemplateToRenderOnBackendinvoiceData={ENGLISH_INVOICE_REAL_DATA}@@ -240,7 +259,7 @@ export async function GET(req: NextRequest) {// Send notifications in parallelconst notifications: Promise<unknown>[] = [sendTelegramMessage({- message: `📝 *Invoices for ${monthAndYear}*+ message: `${testModeWarningBlock}📝 *Invoices for ${monthAndYear}*Invoice No. of: *${invoiceNumberValue}*Date: *${dayjs().format("MMMM D, YYYY")}*diff --git a/src/app/constants/index.ts b/src/app/constants/index.tsindex 505210a..03d8963 100644--- a/src/app/constants/index.ts+++ b/src/app/constants/index.ts@@ -11,6 +11,7 @@ import { INVOICE_PDF_TRANSLATIONS } from "../(app)/pdf-i18n-translations/pdf-traimport dayjs from "dayjs";export const TODAY = dayjs().format("YYYY-MM-DD");+export const FIRST_DAY_OF_MONTH = dayjs().startOf("month").format("YYYY-MM-DD");export const LAST_DAY_OF_MONTH = dayjs().endOf("month").format("YYYY-MM-DD");export const PAYMENT_DUE = dayjs(TODAY).add(14, "days").format("YYYY-MM-DD");const INVOICE_CURRENT_MONTH_AND_YEAR = dayjs().format("MM-YYYY");@@ -88,7 +89,12 @@ export const INITIAL_INVOICE_DATA = {},dateOfIssue: TODAY,+ dateOfServiceStart: FIRST_DAY_OF_MONTH,dateOfService: LAST_DAY_OF_MONTH,+ servicePeriodFieldIsVisible: false,+ dateOfServiceFieldIsVisible: true,+ servicePeriodLabelText: INVOICE_PDF_TRANSLATIONS[EN].servicePeriod,+ dateOfServiceLabelText: INVOICE_PDF_TRANSLATIONS[EN].dateOfService,dateFormat: DEFAULT_DATE_FORMAT,invoiceType: "",diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex 8c90aca..2caa97b 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -747,11 +747,11 @@ export const invoiceItemSchema = z.object({message: "Amount is required",}).transform(Number)- .refine((val) => val > 0, {- message: "Amount must be positive",+ .refine((val) => val >= 0, {+ message: "Amount must be >= 0",})- .refine((val) => val <= 9_999_999_999.99, {- message: "Amount must not exceed 9 999 999 999.99",+ .refine((val) => val <= 999_999.99, {+ message: "Amount must not exceed 999 999.99",}),amountFieldIsVisible: z.boolean().default(true),@@ -767,8 +767,8 @@ export const invoiceItemSchema = z.object({.refine((val) => val >= 0, {message: "Net price must be >= 0",})- .refine((val) => val <= 100_000_000_000, {- message: "Net price must not exceed 100 billion",+ .refine((val) => val <= 1_000_000_000, {+ message: "Net price must not exceed 1 billion",}),netPriceFieldIsVisible: z.boolean().default(true),@@ -957,11 +957,11 @@ export const buyerSchema = z.object({export type BuyerData = z.infer<typeof buyerSchema>;/**- * Invoice schema+ * Invoice object schema (without cross-field transforms)*- * This schema is used to validate the invoice data+ * Exported for tests that need access to `.shape` (e.g. URL compression key map).*/-export const invoiceSchema = z.object({+export const invoiceObjectSchema = z.object({language: z.enum(SUPPORTED_LANGUAGES).default("en"),dateFormat: z.enum(SUPPORTED_DATE_FORMATS).default("YYYY-MM-DD"),currency: z.enum(SUPPORTED_CURRENCIES).default("EUR"),@@ -1043,6 +1043,18 @@ export const invoiceSchema = z.object({}).describe("Invoice date of issue. Default is today's date"),+ dateOfServiceStart: z+ .string()+ .trim()+ .optional()+ .describe(+ "Service period start date. Defaults to the first day of the month containing dateOfService",+ ),++ /**+ * Date of service end. (date of sales/of executing the service)+ * Name retained as "dateOfService" in schema for backwards compatibility.+ */dateOfService: z.string().trim()@@ -1056,6 +1068,41 @@ export const invoiceSchema = z.object({.describe("Invoice date of service. Default is the last day of the current month",),+ /**+ * Show/hide the "Date of sales/of executing the service" field in the PDF+ */+ dateOfServiceFieldIsVisible: z.boolean().default(true),++ /**+ * Show/hide the "Service period" (service period start and end date) field in the PDF+ */+ servicePeriodFieldIsVisible: z.boolean().default(false),++ /**+ * Customizable "Service period" label shown in the PDF header+ */+ servicePeriodLabelText: z+ .string()+ .min(1, "Service period label is required")+ .max(250, "Service period label must not exceed 250 characters")+ .trim()+ .default("Service period")+ .describe(+ "Customizable service period label. Defaults to the translated 'Service period' text for the selected language.",+ ),++ /**+ * Customizable "Date of sales/of executing the service" label shown in the PDF header+ */+ dateOfServiceLabelText: z+ .string()+ .min(1, "Date of sales label is required")+ .max(250, "Date of sales label must not exceed 250 characters")+ .trim()+ .default("Date of sales/of executing the service")+ .describe(+ "Customizable date of sales label. Defaults to the translated text for the selected language.",+ ),/*** Renamed from "Invoice Type" to "Header Notes" on UI to better reflect its purpose@@ -1175,6 +1222,30 @@ export const invoiceSchema = z.object({personAuthorizedToIssueFieldIsVisible: z.boolean().default(true),});+/**+ * Invoice schema+ *+ * This schema is used to validate the invoice data+ */+export const invoiceSchema = invoiceObjectSchema+ .transform((data) => ({+ ...data,+ dateOfServiceStart:+ data.dateOfServiceStart?.trim() ||+ dayjs(data.dateOfService).startOf("month").format("YYYY-MM-DD"),+ }))+ .superRefine((data, ctx) => {+ if (+ dayjs(data.dateOfServiceStart).isAfter(dayjs(data.dateOfService), "day")+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Service period start must be on or before the end date",+ path: ["dateOfServiceStart"],+ });+ }+ });+export type InvoiceData = z.infer<typeof invoiceSchema>;export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";diff --git a/src/components/currency-combobox.tsx b/src/components/currency-combobox.tsxindex 528dd1f..3a188d9 100644--- a/src/components/currency-combobox.tsx+++ b/src/components/currency-combobox.tsx@@ -35,10 +35,12 @@ export function CurrencyCombobox({id = "",value,onChange,+ hasError = false,}: {id: string;value: string;onChange: (value: string) => void;+ hasError?: boolean;}) {const [open, setOpen] = useState(false);@@ -113,7 +115,10 @@ export function CurrencyCombobox({variant="outline"role="combobox"aria-expanded={open}- className="w-full !scale-100 justify-between rounded-md border border-gray-300 bg-white pl-3 pr-2 text-sm font-normal text-slate-950 shadow-sm shadow-black/5 !outline-none transition-all hover:bg-slate-100/80 focus-visible:!border-2 focus-visible:!border-indigo-600 focus-visible:!ring-2 focus-visible:!ring-indigo-200 focus-visible:!ring-opacity-50 focus-visible:!ring-offset-1"+ className={cn(+ "w-full !scale-100 justify-between rounded-md border border-gray-300 bg-white pl-3 pr-2 text-sm font-normal text-slate-950 shadow-sm shadow-black/5 !outline-none transition-all hover:bg-slate-100/80 focus-visible:!border-2 focus-visible:!border-indigo-600 focus-visible:!ring-2 focus-visible:!ring-indigo-200 focus-visible:!ring-opacity-50 focus-visible:!ring-offset-1",+ hasError && "border-red-500",+ )}>{value ? (<span className="flex min-w-0 items-center gap-2">diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsxindex 443e2d9..0ac49ab 100644--- a/src/components/ui/tooltip.tsx+++ b/src/components/ui/tooltip.tsx@@ -3,6 +3,12 @@import * as TooltipPrimitive from "@radix-ui/react-tooltip";import * as React from "react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { useIsDesktop } from "@/hooks/use-media-query";import { cn } from "@/lib/utils";const TooltipProvider = React.memo(TooltipPrimitive.Provider);@@ -51,8 +57,11 @@ interface CustomTooltipProps {align?: "start" | "center" | "end";delayDuration?: number;showArrow?: boolean;+ popoverOnMobile?: boolean;}+const contentClassName = "max-w-[280px] px-2 py-1 text-xs";+const CustomTooltip = React.memo(({trigger,@@ -62,11 +71,32 @@ const CustomTooltip = React.memo(align = "center",delayDuration = 300,showArrow = false,+ popoverOnMobile = false,}: CustomTooltipProps) => {+ const isDesktop = useIsDesktop();+ const usePopover = popoverOnMobile && !isDesktop;+// Memoize both trigger and contentconst memoizedTrigger = React.useMemo(() => trigger, [trigger]);const memoizedContent = React.useMemo(() => content, [content]);+ if (usePopover) {+ return (+ <Popover>+ <PopoverTrigger asChild>{memoizedTrigger}</PopoverTrigger>+ {memoizedContent ? (+ <PopoverContent+ side={side}+ align={align}+ className={cn(contentClassName, className)}+ >+ {memoizedContent}+ </PopoverContent>+ ) : null}+ </Popover>+ );+ }+return (<Tooltip delayDuration={delayDuration}><TooltipTrigger asChild>{memoizedTrigger}</TooltipTrigger>@@ -74,7 +104,7 @@ const CustomTooltip = React.memo(<TooltipContentside={side}align={align}- className={cn("px-2 py-1 text-xs", className)}+ className={cn(contentClassName, className)}showArrow={showArrow}>{memoizedContent}diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex ee02b7c..6f70ffd 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -1,11 +1,25 @@import { Ratelimit } from "@upstash/ratelimit";import { redis } from "./redis";-// Create limiters with different configurations-export const ipLimiter = new Ratelimit({- redis,- // 5 requests per hour- limiter: Ratelimit.slidingWindow(5, "1 h"),- analytics: true,- prefix: "ratelimit:ip",-});+/**+ * IP-based rate limiter for /api/generate-invoice.+ *+ * - In development mode, disables rate limiting (always returns success).+ * - In production, limits to 10 requests per IP per hour (sliding window).+ *+ * Usage:+ * const result = await ipLimiter.limit(ip)+ * if (!result.success) { ... }+ */+export const ipLimiter =+ process.env.NODE_ENV === "development"+ ? {+ // in development mode, we don't want to rate limit+ limit: async () => ({ success: true }),+ }+ : new Ratelimit({+ redis,+ limiter: Ratelimit.slidingWindow(10, "1 h"),+ analytics: true,+ prefix: "ratelimit:ip",+ });diff --git a/src/utils/__tests__/data.ts b/src/utils/__tests__/data.tsindex 9782e68..6f6c491 100644--- a/src/utils/__tests__/data.ts+++ b/src/utils/__tests__/data.ts@@ -69,7 +69,12 @@ export const MOCK_INVOICE_DATA = {value: "INV-2024-001",},dateOfIssue: "2024-01-15",+ dateOfServiceStart: "2024-01-01",dateOfService: "2024-01-31",+ servicePeriodFieldIsVisible: false,+ dateOfServiceFieldIsVisible: true,+ servicePeriodLabelText: "Service period",+ dateOfServiceLabelText: "Date of sales/of executing the service",invoiceType: "Standard Invoice",invoiceTypeFieldIsVisible: true,seller: MOCK_SELLER_DATA,diff --git a/src/utils/__tests__/url-compression.test.ts b/src/utils/__tests__/url-compression.test.tsindex 9c5f55e..38967ea 100644--- a/src/utils/__tests__/url-compression.test.ts+++ b/src/utils/__tests__/url-compression.test.ts@@ -9,7 +9,7 @@ import {type InvoiceItemData,type SellerData,type BuyerData,- invoiceSchema,+ invoiceObjectSchema,sellerSchema,buyerSchema,invoiceItemSchema,@@ -28,7 +28,10 @@ describe("URL Compression Utilities", () => {expect(result).toHaveProperty("d", "default"); // templateexpect(result).toHaveProperty("e", MOCK_INVOICE_DATA.logo); // logoexpect(result).toHaveProperty("g", "2024-01-15"); // dateOfIssue+ expect(result).toHaveProperty("9", "2024-01-01"); // dateOfServiceStartexpect(result).toHaveProperty("h", "2024-01-31"); // dateOfService+ expect(result).toHaveProperty("!", false); // servicePeriodFieldIsVisible+ expect(result).toHaveProperty("@", true); // dateOfServiceFieldIsVisibleexpect(result).toHaveProperty("i", "Standard Invoice"); // invoiceTypeexpect(result).toHaveProperty("j", true); // invoiceTypeFieldIsVisibleexpect(result).toHaveProperty("n", 247.23); // total@@ -204,7 +207,10 @@ describe("URL Compression Utilities", () => {expect(result).toHaveProperty("template", "default");expect(result).toHaveProperty("logo", MOCK_INVOICE_DATA.logo);expect(result).toHaveProperty("dateOfIssue", "2024-01-15");+ expect(result).toHaveProperty("dateOfServiceStart", "2024-01-01");expect(result).toHaveProperty("dateOfService", "2024-01-31");+ expect(result).toHaveProperty("servicePeriodFieldIsVisible", false);+ expect(result).toHaveProperty("dateOfServiceFieldIsVisible", true);expect(result).toHaveProperty("invoiceType", "Standard Invoice");expect(result).toHaveProperty("invoiceTypeFieldIsVisible", true);expect(result).toHaveProperty("total", 247.23);@@ -528,8 +534,8 @@ describe("URL Compression Utilities", () => {// We'll do this by creating a comprehensive mock object and checking each key exists in INVOICE_KEY_COMPRESSION_MAPconst invoiceRootKeys = Object.keys(- invoiceSchema.shape,- ) as (keyof typeof invoiceSchema.shape)[];+ invoiceObjectSchema.shape,+ ) as (keyof typeof invoiceObjectSchema.shape)[];const sellerKeys = Object.keys(sellerSchema.shape,diff --git a/src/utils/url-compression.ts b/src/utils/url-compression.tsindex d5ee23c..ee8714c 100644--- a/src/utils/url-compression.ts+++ b/src/utils/url-compression.ts@@ -48,6 +48,11 @@ export const INVOICE_KEY_COMPRESSION_MAP = {invoiceNumberObject: "f",dateOfIssue: "g",dateOfService: "h",+ dateOfServiceStart: "9",+ servicePeriodFieldIsVisible: "!",+ dateOfServiceFieldIsVisible: "@",+ servicePeriodLabelText: "#",+ dateOfServiceLabelText: "$",invoiceType: "i",invoiceTypeFieldIsVisible: "j",seller: "k",