|
| 1 | +--- |
| 2 | +description: 'Svelte 5 and SvelteKit development standards and best practices for component-based user interfaces and full-stack applications' |
| 3 | +applyTo: '**/*.svelte, **/*.ts, **/*.js, **/*.css, **/*.scss, **/*.json' |
| 4 | +--- |
| 5 | + |
| 6 | +(original https://github.com/github/awesome-copilot/blob/main/instructions/svelte.instructions.md) |
| 7 | + |
| 8 | +# Svelte 5 and SvelteKit Development Instructions |
| 9 | + |
| 10 | +Instructions for building high-quality Svelte 5 and SvelteKit applications with modern runes-based reactivity, TypeScript, and performance optimization. |
| 11 | + |
| 12 | +## MoonLight-Specific Constraints |
| 13 | + |
| 14 | +> **Important:** MoonLight periodically merges upstream [ESP32-sveltekit](https://github.com/theelims/ESP32-sveltekit) changes. Upstream files use Svelte stores (not runes) and must **not** be reformatted or modernised to avoid merge conflicts. |
| 15 | +> |
| 16 | +> Apply these guidelines **only** to MoonLight-specific files: |
| 17 | +> - `interface/src/routes/moonbase/` |
| 18 | +> - `interface/src/lib/components/moonbase/` |
| 19 | +> - `interface/src/lib/stores/moonbase_utilities.ts` |
| 20 | +> - `interface/src/lib/types/moonbase_models.ts` |
| 21 | +> |
| 22 | +> Do **not** migrate upstream files to runes, reformat them, or change their store patterns. |
| 23 | +
|
| 24 | +## Project Context |
| 25 | +- Svelte 5.x with runes system ($state, $derived, $effect, $props, $bindable) — moonbase-specific files only |
| 26 | +- SvelteKit for full-stack applications with file-based routing |
| 27 | +- TypeScript for type safety and better developer experience |
| 28 | +- Component-scoped styling with CSS custom properties |
| 29 | +- Progressive enhancement and performance-first approach |
| 30 | +- Modern build tooling (Vite) with optimizations |
| 31 | + |
| 32 | +## Core Concepts |
| 33 | + |
| 34 | +### Architecture |
| 35 | +- Use Svelte 5 runes system for all reactivity instead of legacy stores |
| 36 | +- Organize components by feature or domain for scalability |
| 37 | +- Separate presentation components from logic-heavy components |
| 38 | +- Extract reusable logic into composable functions |
| 39 | +- Implement proper component composition with slots and snippets |
| 40 | +- Use SvelteKit's file-based routing with proper load functions |
| 41 | + |
| 42 | +### Component Design |
| 43 | +- Follow single responsibility principle for components |
| 44 | +- Use `<script lang="ts">` with runes syntax as default |
| 45 | +- Keep components small and focused on one concern |
| 46 | +- Implement proper prop validation with TypeScript annotations |
| 47 | +- Use `{#snippet}` blocks for reusable template logic within components |
| 48 | +- Use slots for component composition and content projection |
| 49 | +- Pass `children` snippet for flexible parent-child composition |
| 50 | +- Design components to be testable and reusable |
| 51 | + |
| 52 | +## Reactivity and State |
| 53 | + |
| 54 | +### Svelte 5 Runes System |
| 55 | +- Use `$state()` for reactive local state management |
| 56 | +- Implement `$derived()` for computed values and expensive calculations |
| 57 | +- Use `$derived.by()` for complex computations beyond simple expressions |
| 58 | +- Use `$effect()` sparingly - prefer `$derived` or function bindings for state sync |
| 59 | +- Implement `$effect.pre()` for running code before DOM updates |
| 60 | +- Use `untrack()` to prevent infinite loops when reading/writing same state in effects |
| 61 | +- Define component props with `$props()` and destructuring with TypeScript annotations |
| 62 | +- Use `$bindable()` for two-way data binding between components |
| 63 | +- Migrate from legacy stores to runes for better performance |
| 64 | +- Override derived values directly for optimistic UI patterns (Svelte 5.25+) |
| 65 | + |
| 66 | +### State Management |
| 67 | +- Use `$state()` for local component state |
| 68 | +- Implement type-safe context with `createContext()` helper over raw `setContext`/`getContext` |
| 69 | +- Use context API for sharing reactive state down component trees |
| 70 | +- Avoid global `$state` modules for SSR - use context to prevent cross-request data leaks |
| 71 | +- Use SvelteKit stores for global application state when needed |
| 72 | +- Keep state normalized for complex data structures |
| 73 | +- Prefer `$derived()` over `$effect()` for computed values |
| 74 | +- Implement proper state persistence for client-side data |
| 75 | + |
| 76 | +### Effect Best Practices |
| 77 | +- **Avoid** using `$effect()` to synchronize state - use `$derived()` instead |
| 78 | +- **Do** use `$effect()` for side effects: analytics, logging, DOM manipulation |
| 79 | +- **Do** return cleanup functions from effects for proper teardown |
| 80 | +- Use `$effect.pre()` when code must run before DOM updates (e.g., scroll position) |
| 81 | +- Use `$effect.root()` for manually controlled effects outside component lifecycle |
| 82 | +- Use `untrack()` to read state without creating dependencies in effects |
| 83 | +- Remember: async code in effects doesn't track dependencies after `await` |
| 84 | + |
| 85 | +## SvelteKit Patterns |
| 86 | + |
| 87 | +### Routing and Layouts |
| 88 | +- Use `+page.svelte` for page components with proper SEO |
| 89 | +- Implement `+layout.svelte` for shared layouts and navigation |
| 90 | +- Handle routing with SvelteKit's file-based system |
| 91 | + |
| 92 | +### Data Loading and Mutations |
| 93 | +- Use `+page.server.ts` for server-side data loading and API calls |
| 94 | +- Implement form actions in `+page.server.ts` for data mutations |
| 95 | +- Use `+server.ts` for API endpoints and server-side logic |
| 96 | +- Use SvelteKit's load functions for server-side and universal data fetching |
| 97 | +- Implement proper loading, error, and success states |
| 98 | +- Handle streaming data with promises in server load functions |
| 99 | +- Use `invalidate()` and `invalidateAll()` for cache management |
| 100 | +- Implement optimistic updates for better user experience |
| 101 | +- Handle offline scenarios and network errors gracefully |
| 102 | + |
| 103 | +### Forms and Validation |
| 104 | +- Use SvelteKit's form actions for server-side form handling |
| 105 | +- Implement progressive enhancement with `use:enhance` |
| 106 | +- Use `bind:value` for controlled form inputs |
| 107 | +- Validate data both client-side and server-side |
| 108 | +- Handle file uploads and complex form scenarios |
| 109 | +- Implement proper accessibility with labels and ARIA attributes |
| 110 | + |
| 111 | +## UI and Styling |
| 112 | + |
| 113 | +### Styling |
| 114 | +- Use component-scoped styles with `<style>` blocks |
| 115 | +- Implement CSS custom properties for theming and design systems |
| 116 | +- Use `class:` directive for conditional styling |
| 117 | +- Follow BEM or utility-first CSS conventions |
| 118 | +- Implement responsive design with mobile-first approach |
| 119 | +- Use `:global()` sparingly for truly global styles |
| 120 | + |
| 121 | +### Transitions and Animations |
| 122 | +- Use `transition:` directive for enter/exit animations (fade, slide, scale, fly) |
| 123 | +- Use `in:` and `out:` for separate enter/exit transitions |
| 124 | +- Implement `animate:` directive with `flip` for smooth list reordering |
| 125 | +- Create custom transitions for branded motion design |
| 126 | +- Use `|local` modifier to trigger transitions only on direct changes |
| 127 | +- Combine transitions with keyed `{#each}` blocks for list animations |
| 128 | + |
| 129 | +## TypeScript and Tooling |
| 130 | + |
| 131 | +### TypeScript Integration |
| 132 | +- Enable strict mode in `tsconfig.json` for maximum type safety |
| 133 | +- Annotate props with TypeScript: `let { name }: { name: string } = $props()` |
| 134 | +- Type event handlers, refs, and SvelteKit's generated types |
| 135 | +- Use generic types for reusable components |
| 136 | +- Leverage `$types.ts` files generated by SvelteKit |
| 137 | +- Implement proper type checking with `svelte-check` |
| 138 | +- Use type inference where possible to reduce boilerplate |
| 139 | + |
| 140 | +### Development Tools |
| 141 | +- Use ESLint with eslint-plugin-svelte and Prettier for code consistency |
| 142 | +- Use Svelte DevTools for debugging and performance analysis |
| 143 | +- Keep dependencies up to date and audit for security vulnerabilities |
| 144 | +- Document complex components and logic with JSDoc |
| 145 | +- Follow Svelte's naming conventions (PascalCase for components, camelCase for functions) |
| 146 | + |
| 147 | +## Production Readiness |
| 148 | + |
| 149 | +### Performance Optimization |
| 150 | +- Use keyed `{#each}` blocks for efficient list rendering |
| 151 | +- Implement lazy loading with dynamic imports and `<svelte:component>` |
| 152 | +- Use `$derived()` for expensive computations to avoid unnecessary recalculations |
| 153 | +- Use `$derived.by()` for complex derived values that require multiple statements |
| 154 | +- Avoid `$effect()` for derived state - it's less efficient than `$derived()` |
| 155 | +- Leverage SvelteKit's automatic code splitting and preloading |
| 156 | +- Optimize bundle size with tree shaking and proper imports |
| 157 | +- Profile with Svelte DevTools to identify performance bottlenecks |
| 158 | +- Use `$effect.tracking()` in abstractions to conditionally create reactive listeners |
| 159 | + |
| 160 | +### Error Handling |
| 161 | +- Implement `+error.svelte` pages for route-level error boundaries |
| 162 | +- Use try/catch blocks in load functions and form actions |
| 163 | +- Provide meaningful error messages and fallback UI |
| 164 | +- Log errors appropriately for debugging and monitoring |
| 165 | +- Handle validation errors in forms with proper user feedback |
| 166 | +- Use SvelteKit's `error()` and `redirect()` helpers for proper responses |
| 167 | +- Track pending promises with `$effect.pending()` for loading states |
| 168 | + |
| 169 | +### Testing |
| 170 | +- Write unit tests for components using Vitest and Testing Library |
| 171 | +- Test component behavior, not implementation details |
| 172 | +- Use Playwright for end-to-end testing of user workflows |
| 173 | +- Mock SvelteKit's load functions and stores appropriately |
| 174 | +- Test form actions and API endpoints thoroughly |
| 175 | +- Implement accessibility testing with axe-core |
| 176 | + |
| 177 | +### Security |
| 178 | +- Sanitize user inputs to prevent XSS attacks |
| 179 | +- Use `@html` directive carefully and validate HTML content |
| 180 | +- Implement proper CSRF protection with SvelteKit |
| 181 | +- Validate and sanitize data in load functions and form actions |
| 182 | +- Use HTTPS for all external API calls and production deployments |
| 183 | +- Store sensitive data securely with proper session management |
| 184 | + |
| 185 | +### Accessibility |
| 186 | +- Use semantic HTML elements and proper heading hierarchy |
| 187 | +- Implement keyboard navigation for all interactive elements |
| 188 | +- Provide proper ARIA labels and descriptions |
| 189 | +- Ensure color contrast meets WCAG guidelines |
| 190 | +- Test with screen readers and accessibility tools |
| 191 | +- Implement focus management for dynamic content |
| 192 | + |
| 193 | +### Deployment |
| 194 | +- Use environment variables for configuration across different deployment stages |
| 195 | +- Implement proper SEO with SvelteKit's meta tags and structured data |
| 196 | +- Deploy with appropriate SvelteKit adapter based on hosting platform |
| 197 | + |
| 198 | +## Implementation Process |
| 199 | +1. Initialize SvelteKit project with TypeScript and desired adapters |
| 200 | +2. Set up project structure with proper folder organization |
| 201 | +3. Define TypeScript interfaces and component props |
| 202 | +4. Implement core components with Svelte 5 runes |
| 203 | +5. Add routing, layouts, and navigation with SvelteKit |
| 204 | +6. Implement data loading and form handling |
| 205 | +7. Add styling system with custom properties and responsive design |
| 206 | +8. Implement error handling and loading states |
| 207 | +9. Add comprehensive testing coverage |
| 208 | +10. Optimize performance and bundle size |
| 209 | +11. Ensure accessibility compliance |
| 210 | +12. Deploy with appropriate SvelteKit adapter |
| 211 | + |
| 212 | +## Common Patterns |
| 213 | +- Renderless components with slots for flexible UI composition |
| 214 | +- Custom actions (`use:` directives) for cross-cutting concerns and DOM manipulation |
| 215 | +- `{#snippet}` blocks for reusable template logic within components |
| 216 | +- Type-safe context with `createContext()` for component tree state sharing |
| 217 | +- Progressive enhancement for forms and interactive features with `use:enhance` |
| 218 | +- Server-side rendering with client-side hydration for optimal performance |
| 219 | +- Function bindings (`bind:value={() => value, setValue}`) for two-way binding |
| 220 | +- Avoid `$effect()` for state synchronization - use `$derived()` or callbacks instead |
0 commit comments