Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

npm-svelte

Describes: npmnpm/svelte

Description
Revolutionary JavaScript framework and compiler that builds web applications without runtime overhead by compiling components at build time.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-svelte@4.2.0

core-runtime.md docs/

1
# Core Runtime
2
3
Component lifecycle hooks, event dispatching, and context management for building interactive Svelte components.
4
5
## Capabilities
6
7
### Component Lifecycle
8
9
Manage component mounting, updating, and destruction with lifecycle hooks.
10
11
```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 function
16
*/
17
function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;
18
19
/**
20
* Schedules a callback to run immediately before the component is unmounted.
21
* @param fn - Function to run on destroy
22
*/
23
function onDestroy(fn: () => any): void;
24
25
/**
26
* Schedules a callback to run immediately before the component is updated after any state change.
27
* @param fn - Function to run before update
28
*/
29
function beforeUpdate(fn: () => any): void;
30
31
/**
32
* Schedules a callback to run immediately after the component has been updated.
33
* @param fn - Function to run after update
34
*/
35
function afterUpdate(fn: () => any): void;
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
import { onMount, onDestroy, beforeUpdate, afterUpdate } from "svelte";
42
43
// Component mounting
44
onMount(async () => {
45
const response = await fetch('/api/data');
46
const data = await response.json();
47
48
// Return cleanup function
49
return () => {
50
console.log('Component is being destroyed');
51
};
52
});
53
54
// Component destruction
55
onDestroy(() => {
56
// Cleanup subscriptions, timers, etc.
57
clearInterval(intervalId);
58
});
59
60
// Before/after updates
61
let element;
62
63
beforeUpdate(() => {
64
console.log('About to update, current height:', element?.offsetHeight);
65
});
66
67
afterUpdate(() => {
68
console.log('Updated, new height:', element?.offsetHeight);
69
});
70
```
71
72
### Event System
73
74
Create and dispatch custom events for component communication.
75
76
```javascript { .api }
77
/**
78
* Creates an event dispatcher for component events
79
* @returns EventDispatcher function for dispatching typed events
80
*/
81
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;
82
83
interface 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
}
92
93
interface DispatchOptions {
94
cancelable?: boolean;
95
}
96
```
97
98
**Usage Examples:**
99
100
```javascript
101
import { createEventDispatcher } from "svelte";
102
103
// Typed event dispatcher
104
const dispatch = createEventDispatcher<{
105
close: never;
106
submit: { name: string; email: string };
107
change: string;
108
}>();
109
110
// Dispatching events
111
function handleClose() {
112
dispatch('close'); // No detail parameter
113
}
114
115
function handleSubmit() {
116
dispatch('submit', {
117
name: 'John',
118
email: 'john@example.com'
119
});
120
}
121
122
function handleChange(newValue) {
123
dispatch('change', newValue, { cancelable: true });
124
}
125
```
126
127
### Context Management
128
129
Share data between components without prop drilling using context.
130
131
```javascript { .api }
132
/**
133
* Associates a context object with the current component for access by children
134
* @param key - Context identifier
135
* @param context - Value to store in context
136
* @returns The context value
137
*/
138
function setContext<T>(key: any, context: T): T;
139
140
/**
141
* Retrieves context that belongs to the closest parent component with the specified key
142
* @param key - Context identifier
143
* @returns The context value
144
*/
145
function getContext<T>(key: any): T;
146
147
/**
148
* Retrieves the whole context map from the closest parent component
149
* @returns Map of all context values
150
*/
151
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
152
153
/**
154
* Checks whether a given key has been set in the context of a parent component
155
* @param key - Context identifier to check
156
* @returns True if context exists
157
*/
158
function hasContext(key: any): boolean;
159
```
160
161
**Usage Examples:**
162
163
```javascript
164
import { setContext, getContext, hasContext } from "svelte";
165
166
// Parent component - setting context
167
const themeKey = Symbol('theme');
168
169
setContext(themeKey, {
170
primaryColor: '#007acc',
171
backgroundColor: '#ffffff'
172
});
173
174
// Child component - consuming context
175
const theme = getContext(themeKey);
176
177
// Conditional context usage
178
if (hasContext(themeKey)) {
179
const theme = getContext(themeKey);
180
console.log('Theme available:', theme);
181
}
182
183
// Getting all contexts
184
const allContexts = getAllContexts();
185
console.log('Available contexts:', allContexts);
186
```
187
188
### Reactivity Control
189
190
Control when Svelte updates the DOM and flushes pending changes.
191
192
```javascript { .api }
193
/**
194
* Returns a promise that resolves once pending state changes have been applied
195
* @returns Promise that resolves after DOM updates
196
*/
197
function tick(): Promise<void>;
198
```
199
200
**Usage Examples:**
201
202
```javascript
203
import { tick } from "svelte";
204
205
let items = [];
206
let container;
207
208
async function addItem() {
209
items = [...items, { id: Date.now(), text: 'New item' }];
210
211
// Wait for DOM to update
212
await tick();
213
214
// Now we can access the updated DOM
215
const newElement = container.lastElementChild;
216
newElement.scrollIntoView();
217
}
218
219
// Useful for animations or DOM measurements after state changes
220
async function animateHeight() {
221
const startHeight = element.offsetHeight;
222
223
showContent = true;
224
await tick(); // Wait for content to render
225
226
const endHeight = element.offsetHeight;
227
// Now animate from startHeight to endHeight
228
}
229
```
230
231
## Base Component Class
232
233
```javascript { .api }
234
/**
235
* Base class for Svelte components with TypeScript support
236
*/
237
class SvelteComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> {
238
constructor(options: ComponentConstructorOptions<Props>);
239
240
/** Destroy the component and cleanup resources */
241
$destroy(): void;
242
243
/** Listen to component events */
244
$on<K extends Extract<keyof Events, string>>(
245
type: K,
246
callback: ((e: Events[K]) => void) | null | undefined
247
): () => void;
248
249
/** Update component props */
250
$set(props: Partial<Props>): void;
251
}
252
253
interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>> {
254
/** Target DOM element to mount the component */
255
target: Element | Document | ShadowRoot;
256
/** Element to insert the component before */
257
anchor?: Element;
258
/** Initial props for the component */
259
props?: Props;
260
/** Context map for the component */
261
context?: Map<any, any>;
262
/** Whether to hydrate existing DOM */
263
hydrate?: boolean;
264
/** Whether to play intro transitions */
265
intro?: boolean;
266
}
267
```