Spec Registry
Help your agents use open-source better. Learn more.
Find usage specs for your project’s dependencies
- Author
- tessl
- Last updated
- Spec files
npm-svelte
Describes: npm/svelte
- Description
- A cybernetically enhanced web application framework that compiles to highly optimized JavaScript with reactive state management and component-based architecture.
- Author
- tessl
- Last updated
context.md docs/
1# Context Management23Svelte's context API provides a way to share data between parent and child components without explicitly passing props through every level of the component tree. Context is ideal for themes, user authentication, and other cross-cutting concerns.45## Capabilities67### setContext89Associates an arbitrary context object with the current component and the specified key. Must be called during component initialization.1011```typescript { .api }12/**13* Associates an arbitrary context object with the current component and the specified key14* @param key - Context key (can be any value, often string or Symbol)15* @param context - Context value to store16* @returns The context value17*/18function setContext<T>(key: any, context: T): T;19```2021**Usage Examples:**2223```typescript24import { setContext } from "svelte";2526// Parent component27const THEME_KEY = "theme";2829const theme = {30colors: {31primary: "#ff3e00",32secondary: "#40b3ff"33},34fonts: {35body: "Arial, sans-serif",36heading: "Georgia, serif"37}38};3940// Set context for children41setContext(THEME_KEY, theme);4243// Using Symbol keys for uniqueness44const API_KEY = Symbol("api");45setContext(API_KEY, {46baseUrl: "https://api.example.com",47headers: { "Authorization": `Bearer ${token}` }48});4950// Reactive context (context value itself can be reactive)51let user = $state({ name: "Alice", role: "admin" });52setContext("user", user);53```5455### getContext5657Retrieves the context associated with the specified key from the nearest parent component.5859```typescript { .api }60/**61* Retrieves the context associated with the specified key62* @param key - Context key to look up63* @returns Context value or undefined if not found64*/65function getContext<T>(key: any): T;66```6768**Usage Examples:**6970```typescript71import { getContext } from "svelte";7273// Child component74const THEME_KEY = "theme";7576// Get theme from parent context77const theme = getContext(THEME_KEY);7879if (theme) {80console.log("Primary color:", theme.colors.primary);81}8283// Type-safe context access with TypeScript84interface ThemeContext {85colors: { primary: string; secondary: string };86fonts: { body: string; heading: string };87}8889const theme: ThemeContext = getContext(THEME_KEY);9091// Using Symbol keys92const API_KEY = Symbol("api");93const api = getContext(API_KEY);9495// Fallback for missing context96const settings = getContext("settings") || { defaultSetting: true };9798// Context in reactive expressions99let theme = getContext("theme");100let primaryColor = $derived(theme?.colors?.primary || "#000");101```102103### hasContext104105Checks whether a given key has been set in the context of a parent component.106107```typescript { .api }108/**109* Checks whether a given key has been set in the context of a parent component110* @param key - Context key to check111* @returns true if context exists, false otherwise112*/113function hasContext(key: any): boolean;114```115116**Usage Examples:**117118```typescript119import { hasContext, getContext } from "svelte";120121// Check if context exists before using122if (hasContext("theme")) {123const theme = getContext("theme");124// Safe to use theme125} else {126// Handle missing theme context127console.warn("No theme context provided");128}129130// Conditional feature activation131const hasAnalytics = hasContext("analytics");132if (hasAnalytics) {133const analytics = getContext("analytics");134analytics.track("page_view");135}136137// Optional context consumption138function useOptionalContext(key, fallback) {139return hasContext(key) ? getContext(key) : fallback;140}141142const userPrefs = useOptionalContext("preferences", { lang: "en" });143```144145### getAllContexts146147Returns a Map of all contexts from the current component. Useful for debugging or context forwarding.148149```typescript { .api }150/**151* Returns a Map of all context entries from the current component152* @returns Map containing all context key-value pairs153*/154function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;155```156157**Usage Examples:**158159```typescript160import { getAllContexts, setContext } from "svelte";161162// Debug utility to log all available contexts163function debugContexts() {164const contexts = getAllContexts();165console.log("Available contexts:", contexts);166167for (const [key, value] of contexts) {168console.log(`Context ${key}:`, value);169}170}171172// Context forwarding component173function forwardAllContexts(targetComponent) {174const contexts = getAllContexts();175176// Forward all contexts to child component177for (const [key, value] of contexts) {178setContext(key, value);179}180}181182// Context merging utility183function mergeContexts(additionalContexts) {184const existingContexts = getAllContexts();185186return new Map([187...existingContexts,188...Object.entries(additionalContexts)189]);190}191```192193## Usage Patterns194195### Theme Provider Pattern196197```typescript198// ThemeProvider.svelte199import { setContext } from "svelte";200201let { theme, children } = $props();202203setContext("theme", theme);204205// Template: {@render children()}206207// Child component208import { getContext } from "svelte";209210const theme = getContext("theme");211const primaryColor = theme.colors.primary;212```213214### Store Provider Pattern215216```typescript217// StoreProvider.svelte218import { setContext } from "svelte";219import { writable } from "svelte/store";220221// Create stores222const userStore = writable(null);223const cartStore = writable([]);224225// Provide stores via context226setContext("stores", {227user: userStore,228cart: cartStore229});230231// Child component232import { getContext } from "svelte";233234const stores = getContext("stores");235const user = stores.user;236const cart = stores.cart;237238// Use with auto-subscription239// let currentUser = $user;240// let cartItems = $cart;241```242243### API Client Pattern244245```typescript246// APIProvider.svelte247import { setContext } from "svelte";248249class APIClient {250constructor(baseUrl, token) {251this.baseUrl = baseUrl;252this.token = token;253}254255async fetch(endpoint, options = {}) {256return fetch(`${this.baseUrl}${endpoint}`, {257...options,258headers: {259"Authorization": `Bearer ${this.token}`,260...options.headers261}262});263}264}265266const apiClient = new APIClient("https://api.example.com", token);267setContext("api", apiClient);268269// Child component270import { getContext } from "svelte";271272const api = getContext("api");273274async function loadData() {275const response = await api.fetch("/data");276return response.json();277}278```279280## Types281282```typescript { .api }283// Context key can be any type284type ContextKey = any;285286// Context value can be any type287type ContextValue = any;288289// Map type for getAllContexts290type ContextMap = Map<ContextKey, ContextValue>;291```292293## Best Practices2942951. **Use descriptive keys**: Use strings or Symbols for context keys to avoid collisions2962. **Set context early**: Call `setContext` during component initialization, not in effects2973. **Provide fallbacks**: Check for context existence with `hasContext` or provide defaults2984. **Keep context focused**: Don't put everything in context - use it for cross-cutting concerns2995. **Document context contracts**: Clearly document what context keys your components expect3006. **Use TypeScript**: Type your context objects for better developer experience3017. **Consider Symbol keys**: Use Symbol keys for private contexts to prevent accidental access