# Role
You are a Svelte Expert who builds production-grade components leveraging Svelte's reactive compiler, stores, and built-in animation system.
# Task
Create a complete Svelte component with TypeScript, reactive stores, proper bindings, transitions, and optimized performance following Svelte best practices.
# Instructions
**Component Specifications:**
**Component Details:**
- Component name: [COMPONENT_NAME]
- Purpose: [DESCRIPTION]
- Parent component context: [CONTEXT]
- User interactions: [INTERACTIONS]
**Props and Data:**
```typescript
[DESCRIBE_EXPECTED_PROPS]
Examples:
- Data objects
- Callback functions
- Configuration
- Slot content
```
**Reactivity Requirements:**
- Reactive computations needed: [DESCRIPTION]
- Store subscriptions: [WRITABLE_READABLE_DERIVED]
- Two-way bindings: [INPUTS_FORMS_OTHER]
- Lifecycle hooks needed: [ONMOUNT_ONDESTROY_OTHER]
**Visual and Animation:**
- Transitions needed: [FADE_SLIDE_FLY_CUSTOM]
- Animations: [IN_OUT_BOTH]
- Conditional rendering: [IF_EACH_AWAIT]
- Styling approach: [SCOPED_CSS_GLOBAL_TAILWIND]
**TypeScript Integration:**
- Prop types: [INTERFACES_NEEDED]
- Store types: [TYPE_DEFINITIONS]
- Event types: [CUSTOM_EVENTS]
**State Management:**
- Local component state: [DESCRIPTION]
- Shared stores: [WHICH_STORES]
- Context API usage: [YES_NO_DETAILS]
**Existing Codebase:**
```typescript
[PASTE_RELEVANT_CODE]
Include:
- Store definitions
- Type definitions
- Related components
- Styling conventions
```
Based on this information:
1. **Component Structure:**
```svelte
<script lang="ts">
// Imports
import { writable, derived, readable } from 'svelte/store';
import { onMount, onDestroy } from 'svelte';
import { fade, slide, fly } from 'svelte/transition';
// TypeScript interfaces
interface [COMPONENT_NAME]Props {
// Prop definitions
}
// Props with defaults
export let prop1: type = defaultValue;
export let prop2: type;
// Local state (reactive)
let localState = initialValue;
// Reactive declarations
$: computedValue = expression;
$: {
// Reactive block for side effects
}
// Store subscriptions
import { globalStore } from './stores';
$: storeValue = $globalStore;
// Functions
function handleEvent() {
// Event handler
}
// Lifecycle
onMount(() => {
// Initialization
return () => {
// Cleanup
};
});
</script>
<!-- Template -->
<div class="component-wrapper">
{#if condition}
<!-- Conditional content -->
{:else if otherCondition}
<!-- Alternative -->
{:else}
<!-- Fallback -->
{/if}
{#each items as item (item.id)}
<!-- List items with key -->
{/each}
{#await promise}
<!-- Loading -->
{:then value}
<!-- Success -->
{:catch error}
<!-- Error -->
{/await}
</div>
<style>
/* Scoped styles */
.component-wrapper {
/* Styles */
}
</style>
```
2. **TypeScript Type Definitions:**
```typescript
// Props interface
export interface [COMPONENT_NAME]Props {
prop1: string;
prop2?: number;
onEvent?: (data: EventData) => void;
}
// Internal types
interface LocalState {
// State shape
}
// Event types
interface CustomEventDetail {
// Event payload
}
```
3. **Reactive Declarations:**
**Simple Reactivity:**
```typescript
$: doubled = count * 2;
$: greeting = `Hello, ${name}!`;
```
**Reactive Blocks:**
```typescript
$: {
console.log(`Count changed to ${count}`);
// Side effects when dependencies change
}
```
**Reactive Statements:**
```typescript
$: if (count > 10) {
alert('Count is high!');
}
```
4. **Store Integration:**
**Writable Store:**
```typescript
import { writable } from 'svelte/store';
export const count = writable(0);
// In component
$: currentCount = $count;
function increment() {
count.update((n) => n + 1);
}
```
**Derived Store:**
```typescript
import { derived } from 'svelte/store';
export const doubled = derived(count, ($count) => $count * 2);
```
**Custom Store:**
```typescript
function createCustomStore() {
const { subscribe, set, update } = writable(initialValue);
return {
subscribe,
customMethod: () => update(n => /* logic */),
reset: () => set(initialValue)
};
}
```
5. **Bindings and Two-Way Data Flow:**
**Input Bindings:**
```svelte
<input bind:value={text} />
<input type="checkbox" bind:checked={isChecked} />
<select bind:value={selected}>
<option value="a">A</option>
</select>
```
**Component Bindings:**
```svelte
<ChildComponent bind:value={parentValue} />
```
**Element Bindings:**
```svelte
<div bind:clientWidth={width} bind:clientHeight={height}>
```
6. **Transitions and Animations:**
**Built-in Transitions:**
```svelte
{#if visible}
<div transition:fade={{ duration: 300 }}>Fading content</div>
{/if}
{#if show}
<div in:fly={{ y: 200, duration: 500 }} out:fade>Flying in, fading out</div>
{/if}
```
**Custom Transitions:**
```typescript
function customTransition(node, params) {
return {
duration: params.duration,
css: (t) => `
opacity: ${t};
transform: scale(${t});
`
};
}
```
**Animate Directive:**
```svelte
{#each items as item (item.id)}
<div animate:flip={{ duration: 300 }}>
{item.name}
</div>
{/each}
```
7. **Event Handling:**
**Standard Events:**
```svelte
<button on:click={handleClick}>Click</button>
<input on:input={handleInput} />
```
**Event Modifiers:**
```svelte
<button on:click|preventDefault|stopPropagation={handle}>
```
**Custom Events:**
```typescript
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher<{
customEvent: CustomEventDetail;
}>();
function triggerEvent() {
dispatch('customEvent', { data: value });
}
```
8. **Slots and Composition:**
**Default Slot:**
```svelte
<div class="wrapper">
<slot>Fallback content</slot>
</div>
```
**Named Slots:**
```svelte
<slot name="header" />
<slot />
<!-- default -->
<slot name="footer" />
```
**Slot Props:**
```svelte
<slot item={currentItem} index={i} />
<!-- Usage -->
<Component let:item let:index>
{item.name} at {index}
</Component>
```
9. **Context API:**
**Setting Context:**
```typescript
import { setContext } from 'svelte';
setContext('key', {
value: data,
method: () => {}
});
```
**Getting Context:**
```typescript
import { getContext } from 'svelte';
const context = getContext<ContextType>('key');
```
10. **Lifecycle and Cleanup:**
```typescript
import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte';
onMount(() => {
// Runs after component first renders
const interval = setInterval(() => {}, 1000);
return () => {
// Cleanup function
clearInterval(interval);
};
});
onDestroy(() => {
// Cleanup when component is destroyed
});
beforeUpdate(() => {
// Before DOM updates
});
afterUpdate(() => {
// After DOM updates
});
```
11. **Actions (Custom Directives):**
```typescript
function customAction(node: HTMLElement, parameters: any) {
// Setup
return {
update(newParameters) {
// Called when parameters change
},
destroy() {
// Cleanup
}
};
}
// Usage
<div use:customAction={params} />
```
12. **Styling Approaches:**
**Scoped CSS:**
```svelte
<style>
.component {
/* Automatically scoped */
}
:global(.global-class) {
/* Global styles */
}
</style>
```
**Dynamic Styles:**
```svelte
<div style="color: {textColor}; font-size: {size}px">
```
**Class Directives:**
```svelte
<div class:active={isActive} class:disabled={!enabled}>
```
13. **Performance Optimizations:**
**Keyed Each Blocks:**
```svelte
{#each items as item (item.id)}
<!-- Properly keyed for efficient updates -->
{/each}
```
**Lazy Loading:**
```svelte
{#await import('./HeavyComponent.svelte')}
Loading...
{:then module}
<svelte:component this={module.default} />
{/await}
```
14. **Complete Example Component:**
Provide full working component with:
- All TypeScript types
- Reactive declarations
- Store integrations
- Event handlers
- Transitions
- Proper accessibility
- Inline comments
15. **Usage Examples:**
```svelte
<!-- Basic usage -->
<[COMPONENT_NAME]
prop1="value"
prop2={123}
on:customEvent={handleEvent}
/>
<!-- With slots -->
<[COMPONENT_NAME]>
<div slot="header">Header</div>
Default content
</[COMPONENT_NAME]>
<!-- With bindings -->
<[COMPONENT_NAME] bind:value={boundValue} />
```
Provide the complete Svelte component code following all best practices, with TypeScript types, reactive declarations, proper store usage, and transitions. Include comments explaining Svelte-specific patterns and optimizations.