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
- Revolutionary JavaScript framework and compiler that builds web applications without runtime overhead by compiling components at build time.
- Author
- tessl
- Last updated
core-runtime.md docs/
1# Core Runtime23Component lifecycle hooks, event dispatching, and context management for building interactive Svelte components.45## Capabilities67### Component Lifecycle89Manage component mounting, updating, and destruction with lifecycle hooks.1011```javascript { .api }12/**13* Schedules a callback to run as soon as the component has been mounted to the DOM.14* If a function is returned synchronously, it will be called when the component is unmounted.15* @param fn - Function to run on mount, optionally returning cleanup function16*/17function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;1819/**20* Schedules a callback to run immediately before the component is unmounted.21* @param fn - Function to run on destroy22*/23function onDestroy(fn: () => any): void;2425/**26* Schedules a callback to run immediately before the component is updated after any state change.27* @param fn - Function to run before update28*/29function beforeUpdate(fn: () => any): void;3031/**32* Schedules a callback to run immediately after the component has been updated.33* @param fn - Function to run after update34*/35function afterUpdate(fn: () => any): void;36```3738**Usage Examples:**3940```javascript41import { onMount, onDestroy, beforeUpdate, afterUpdate } from "svelte";4243// Component mounting44onMount(async () => {45const response = await fetch('/api/data');46const data = await response.json();4748// Return cleanup function49return () => {50console.log('Component is being destroyed');51};52});5354// Component destruction55onDestroy(() => {56// Cleanup subscriptions, timers, etc.57clearInterval(intervalId);58});5960// Before/after updates61let element;6263beforeUpdate(() => {64console.log('About to update, current height:', element?.offsetHeight);65});6667afterUpdate(() => {68console.log('Updated, new height:', element?.offsetHeight);69});70```7172### Event System7374Create and dispatch custom events for component communication.7576```javascript { .api }77/**78* Creates an event dispatcher for component events79* @returns EventDispatcher function for dispatching typed events80*/81function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;8283interface EventDispatcher<EventMap extends Record<string, any>> {84<Type extends keyof EventMap>(85...args: null extends EventMap[Type]86? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]87: undefined extends EventMap[Type]88? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]89: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]90): boolean;91}9293interface DispatchOptions {94cancelable?: boolean;95}96```9798**Usage Examples:**99100```javascript101import { createEventDispatcher } from "svelte";102103// Typed event dispatcher104const dispatch = createEventDispatcher<{105close: never;106submit: { name: string; email: string };107change: string;108}>();109110// Dispatching events111function handleClose() {112dispatch('close'); // No detail parameter113}114115function handleSubmit() {116dispatch('submit', {117name: 'John',118email: 'john@example.com'119});120}121122function handleChange(newValue) {123dispatch('change', newValue, { cancelable: true });124}125```126127### Context Management128129Share data between components without prop drilling using context.130131```javascript { .api }132/**133* Associates a context object with the current component for access by children134* @param key - Context identifier135* @param context - Value to store in context136* @returns The context value137*/138function setContext<T>(key: any, context: T): T;139140/**141* Retrieves context that belongs to the closest parent component with the specified key142* @param key - Context identifier143* @returns The context value144*/145function getContext<T>(key: any): T;146147/**148* Retrieves the whole context map from the closest parent component149* @returns Map of all context values150*/151function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;152153/**154* Checks whether a given key has been set in the context of a parent component155* @param key - Context identifier to check156* @returns True if context exists157*/158function hasContext(key: any): boolean;159```160161**Usage Examples:**162163```javascript164import { setContext, getContext, hasContext } from "svelte";165166// Parent component - setting context167const themeKey = Symbol('theme');168169setContext(themeKey, {170primaryColor: '#007acc',171backgroundColor: '#ffffff'172});173174// Child component - consuming context175const theme = getContext(themeKey);176177// Conditional context usage178if (hasContext(themeKey)) {179const theme = getContext(themeKey);180console.log('Theme available:', theme);181}182183// Getting all contexts184const allContexts = getAllContexts();185console.log('Available contexts:', allContexts);186```187188### Reactivity Control189190Control when Svelte updates the DOM and flushes pending changes.191192```javascript { .api }193/**194* Returns a promise that resolves once pending state changes have been applied195* @returns Promise that resolves after DOM updates196*/197function tick(): Promise<void>;198```199200**Usage Examples:**201202```javascript203import { tick } from "svelte";204205let items = [];206let container;207208async function addItem() {209items = [...items, { id: Date.now(), text: 'New item' }];210211// Wait for DOM to update212await tick();213214// Now we can access the updated DOM215const newElement = container.lastElementChild;216newElement.scrollIntoView();217}218219// Useful for animations or DOM measurements after state changes220async function animateHeight() {221const startHeight = element.offsetHeight;222223showContent = true;224await tick(); // Wait for content to render225226const endHeight = element.offsetHeight;227// Now animate from startHeight to endHeight228}229```230231## Base Component Class232233```javascript { .api }234/**235* Base class for Svelte components with TypeScript support236*/237class SvelteComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> {238constructor(options: ComponentConstructorOptions<Props>);239240/** Destroy the component and cleanup resources */241$destroy(): void;242243/** Listen to component events */244$on<K extends Extract<keyof Events, string>>(245type: K,246callback: ((e: Events[K]) => void) | null | undefined247): () => void;248249/** Update component props */250$set(props: Partial<Props>): void;251}252253interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>> {254/** Target DOM element to mount the component */255target: Element | Document | ShadowRoot;256/** Element to insert the component before */257anchor?: Element;258/** Initial props for the component */259props?: Props;260/** Context map for the component */261context?: Map<any, any>;262/** Whether to hydrate existing DOM */263hydrate?: boolean;264/** Whether to play intro transitions */265intro?: boolean;266}267```