Skip to content

Commit e1e372b

Browse files
committed
merge main
2 parents 25e03b3 + 99ca7a4 commit e1e372b

File tree

9 files changed

+138
-121
lines changed

9 files changed

+138
-121
lines changed

documentation/docs/02-runes/04-$effect.md

Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -280,62 +280,34 @@ You might be tempted to do something convoluted with effects to link one value t
280280
</label>
281281
```
282282

283-
Instead, use callbacks where possible ([demo](/playground/untitled#H4sIAAAAAAAACo1SMW6EMBD8imWluFMSIEUaDiKlvy5lSOHjlhOSMRZeTiDkv8deMEEJRcqdmZ1ZjzzxqpZgePo5cRw18JQA_sSVaPz0rnVk7iDRYxdhYA8vW4Wg0NnwzJRdrfGtUAVKQIYtCsly9pIkp4AZ7cQOezAoEA7JcWUkVBuCdol0dNWrEutWsV5fHfnhPQ5wZJMnCwyejxCh6G6A0V3IHk4zu_jOxzzPBxBld83PTr7xXrb3rUNw8PbiYJ3FP22oTIoLSComq5XuXTeu8LzgnVA3KDgj13wiQ8taRaJ82rzXskYM-URRlsXktejjgNLoo9e4fyf70_8EnwncySX1GuunX6kGRwnzR_BgaPNaGy3FmLJKwrCUeBM6ZUn0Cs2mOlp3vwthQJ5i14P9st9vZqQlsQIAAA==)):
283+
Instead, use `oninput` callbacks or — better still — [function bindings](bind#Function-bindings) where possible ([demo](/playground/untitled#H4sIAAAAAAAAE51SsW6DMBT8FcvqABINdOhCIFKXTt06lg4GHpElYyz8iECIf69tcIIipo6-u3f3fPZMJWuBpvRzkBXyTpKSy5rLq6YRbbgATdOfmeKkrMgCBt9GPpQ66RsItFjJNBzhVScRJBobmumq5wovhSxQABLskAmSk7ckOXtMKyM22ItGhhAk4Z0R0OwIN-tIQzd-90HVhvy2HsGNiQFCMltBgd7XoecV2xzXNV7XaEcth7ZfRv7kujnsTX2Qd7USb5rFjwZkJlgJwpWRcakG04cpOS9oz-QVCuoeInXW-RyEJL-sG0b7Wy6kZWM-u7CFxM5tdrIl9qg72vB74H-y7T2iXROHyVb0CLanp1yNk4D1A1jQ91hzrQSbUtIIGLcir0ylJDm9Q7urz42bX4UwIk2xH2D5Xf4A7SeMcMQCAAA=)):
284284

285285
```svelte
286286
<script>
287287
let total = 100;
288288
let spent = $state(0);
289289
let left = $state(total);
290290
291-
function updateSpent(e) {
292-
spent = +e.target.value;
291+
function updateSpent(value) {
292+
spent = value;
293293
left = total - spent;
294294
}
295295
296-
function updateLeft(e) {
297-
left = +e.target.value;
296+
function updateLeft(value) {
297+
left = value;
298298
spent = total - left;
299299
}
300300
</script>
301301
302302
<label>
303-
<input type="range" value={spent} oninput={updateSpent} max={total} />
303+
<input type="range" bind:value={() => spent, updateSpent} max={total} />
304304
{spent}/{total} spent
305305
</label>
306306
307307
<label>
308-
<input type="range" value={left} oninput={updateLeft} max={total} />
308+
<input type="range" bind:value={() => left, updateLeft} max={total} />
309309
{left}/{total} left
310310
</label>
311311
```
312312

313-
If you need to use bindings, for whatever reason (for example when you want some kind of "writable `$derived`"), consider using getters and setters to synchronise state ([demo](/playground/untitled#H4sIAAAAAAAACpWRwW6DMBBEf8WyekikFOihFwcq9TvqHkyyQUjGsfCCQMj_XnvBNKpy6Qn2DTOD1wu_tRocF18Lx9kCFwT4iRvVxenT2syNoDGyWjl4xi93g2AwxPDSXfrW4oc0EjUgwzsqzSr2VhTnxJwNHwf24lAhHIpjVDZNwy1KS5wlNoGMSg9wOCYksQccerMlv65p51X0p_Xpdt_4YEy9yTkmV3z4MJT579-bUqsaNB2kbI0dwlnCgirJe2UakJzVrbkKaqkWivasU1O1ULxnOVk3JU-Uxti0p_-vKO4no_enbQ_yXhnZn0aHs4b1jiJMK7q2zmo1C3bTMG3LaZQVrMjeoSPgaUtkDxePMCEX2Ie6b_8D4WyJJEwCAAA=)):
314-
315-
```svelte
316-
<script>
317-
let total = 100;
318-
let spent = $state(0);
319-
320-
let left = {
321-
get value() {
322-
return total - spent;
323-
},
324-
set value(v) {
325-
spent = total - v;
326-
}
327-
};
328-
</script>
329-
330-
<label>
331-
<input type="range" bind:value={spent} max={total} />
332-
{spent}/{total} spent
333-
</label>
334-
335-
<label>
336-
<input type="range" bind:value={left.value} max={total} />
337-
{left.value}/{total} left
338-
</label>
339-
```
340-
341313
If you absolutely have to update `$state` within an effect and run into an infinite loop because you read and write to the same `$state`, use [untrack](svelte#untrack).

documentation/docs/06-runtime/02-context.md

Lines changed: 86 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -2,129 +2,137 @@
22
title: Context
33
---
44

5-
<!-- - get/set/hasContext
6-
- how to use, best practises (like encapsulating them) -->
5+
Context allows components to access values owned by parent components without passing them down as props (potentially through many layers of intermediate components, known as 'prop-drilling'). The parent component sets context with `setContext(key, value)`...
76

8-
Most state is component-level state that lives as long as its component lives. There's also section-wide or app-wide state however, which also needs to be handled somehow.
9-
10-
The easiest way to do that is to create global state and just import that.
7+
```svelte
8+
<!--- file: Parent.svelte --->
9+
<script>
10+
import { setContext } from 'svelte';
1111
12-
```ts
13-
/// file: state.svelte.js
14-
export const myGlobalState = $state({
15-
user: {
16-
/* ... */
17-
}
18-
/* ... */
19-
});
12+
setContext('my-context', 'hello from Parent.svelte');
13+
</script>
2014
```
2115

16+
...and the child retrieves it with `getContext`:
17+
2218
```svelte
23-
<!--- file: App.svelte --->
19+
<!--- file: Child.svelte --->
2420
<script>
25-
import { myGlobalState } from './state.svelte.js';
26-
// ...
21+
import { getContext } from 'svelte';
22+
23+
const message = getContext('my-context');
2724
</script>
25+
26+
<h1>{message}, inside Child.svelte</h1>
2827
```
2928

30-
This has a few drawbacks though:
29+
This is particularly useful when `Parent.svelte` is not directly aware of `Child.svelte`, but instead renders it as part of a `children` [snippet](snippet) ([demo](/playground/untitled#H4sIAAAAAAAAE42Q3W6DMAyFX8WyJgESK-oto6hTX2D3YxcM3IIUQpR40yqUd58CrCXsp7tL7HNsf2dAWXaEKR56yfTBGOOxFWQwfR6Qz8q1XAHjL-GjUhvzToJd7bU09FO9ctMkG0wxM5VuFeeFLLjtVK8ZnkpNkuGo-w6CTTJ9Z3PwsBAemlbUF934W8iy5DpaZtOUcU02-ZLcaS51jHEkTFm_kY1_wfOO8QnXrb8hBzDEc6pgZ4gFoyz4KgiD7nxfTe8ghqAhIfrJ46cTzVZBbkPlODVJsLCDO6V7ZcJoncyw1yRr0hd1GNn_ZbEM3I9i1bmVxOlWElUvDUNHxpQngt3C4CXzjS1rtvkw22wMrTRtTbC8Lkuabe7jvthPPe3DofYCAAA=)):
30+
31+
```svelte
32+
<Parent>
33+
<Child />
34+
</Parent>
35+
```
3136

32-
- it only safely works when your global state is only used client-side - for example, when you're building a single page application that does not render any of your components on the server. If your state ends up being managed and updated on the server, it could end up being shared between sessions and/or users, causing bugs
33-
- it may give the false impression that certain state is global when in reality it should only used in a certain part of your app
37+
The key (`'my-context'`, in the example above) and the context itself can be any JavaScript value.
3438

35-
To solve these drawbacks, Svelte provides a few `context` primitives which alleviate these problems.
39+
In addition to [`setContext`](svelte#setContext) and [`getContext`](svelte#getContext), Svelte exposes [`hasContext`](svelte#hasContext) and [`getAllContexts`](svelte#getAllContexts) functions.
3640

37-
## Setting and getting context
41+
## Using context with state
3842

39-
To associate an arbitrary object with the current component, use `setContext`.
43+
You can store reactive state in context ([demo](/playground/untitled#H4sIAAAAAAAAE41R0W6DMAz8FSuaBNUQdK8MkKZ-wh7HHihzu6hgosRMm1D-fUpSVNq12x4iEvvOx_kmQU2PIhfP3DCCJGgHYvxkkYid7NCI_GUS_KUcxhVEMjOelErNB3bsatvG4LW6n0ZsRC4K02qpuKqpZtmrQTNMYJA3QRAs7PTQQxS40eMCt3mX3duxnWb-lS5h7nTI0A4jMWoo4c44P_Hku-zrOazdy64chWo-ScfRkRgl8wgHKrLTH1OxHZkHgoHaTraHcopXUFYzPPVfuC_hwQaD1GrskdiNCdQwJljJqlvXfyqVsA5CGg0uRUQifHw56xFtciO75QrP07vo_JXf_tf8yK2ezDKY_ZWt_1y2qqYzv7bI1IW1V_sN19m-07wCAAA=))...
4044

4145
```svelte
4246
<script>
4347
import { setContext } from 'svelte';
48+
import Child from './Child.svelte';
4449
45-
setContext('key', value);
50+
let counter = $state({
51+
count: 0
52+
});
53+
54+
setContext('counter', counter);
4655
</script>
56+
57+
<button onclick={() => counter.count += 1}>
58+
increment
59+
</button>
60+
61+
<Child />
62+
<Child />
63+
<Child />
4764
```
4865

49-
The context is then available to children of the component (including slotted content) with `getContext`.
66+
...though note that if you _reassign_ `counter` instead of updating it, you will 'break the link' — in other words instead of this...
5067

5168
```svelte
52-
<script>
53-
import { getContext } from 'svelte';
54-
55-
const value = getContext('key');
56-
</script>
69+
<button onclick={() => counter = { count: 0 }}>
70+
reset
71+
</button>
5772
```
5873

59-
`setContext` and `getContext` solve the above problems:
74+
...you must do this:
6075

61-
- the state is not global, it's scoped to the component. That way it's safe to render your components on the server and not leak state
62-
- it's clear that the state is not global but rather scoped to a specific component tree and therefore can't be used in other parts of your app
76+
```svelte
77+
<button onclick={() => +++counter.count = 0+++}>
78+
reset
79+
</button>
80+
```
6381

64-
> [!NOTE] `setContext`/`getContext` must be called during component initialisation.
82+
Svelte will warn you if you get it wrong.
6583

66-
Context is not inherently reactive. If you need reactive values in context then you can pass a `$state` object into context, whose properties _will_ be reactive.
84+
## Type-safe context
6785

68-
```svelte
69-
<!--- file: Parent.svelte --->
70-
<script>
71-
import { setContext } from 'svelte';
86+
A useful pattern is to wrap the calls to `setContext` and `getContext` inside helper functions that let you preserve type safety:
7287

73-
let value = $state({ count: 0 });
74-
setContext('counter', value);
75-
</script>
88+
```js
89+
/// file: context.js
90+
// @filename: ambient.d.ts
91+
interface User {}
7692

77-
<button onclick={() => value.count++}>increment</button>
78-
```
93+
// @filename: index.js
94+
// ---cut---
95+
import { getContext, setContext } from 'svelte';
7996

80-
```svelte
81-
<!--- file: Child.svelte --->
82-
<script>
83-
import { getContext } from 'svelte';
97+
let key = {};
8498

85-
const value = getContext('counter');
86-
</script>
99+
/** @param {User} user */
100+
export function setUserContext(user) {
101+
setContext(key, user);
102+
}
87103

88-
<p>Count is {value.count}</p>
104+
export function getUserContext() {
105+
return /** @type {User} */ (getContext(key));
106+
}
89107
```
90108

91-
To check whether a given `key` has been set in the context of a parent component, use `hasContext`.
109+
## Replacing global state
92110

93-
```svelte
94-
<script>
95-
import { hasContext } from 'svelte';
111+
When you have state shared by many different components, you might be tempted to put it in its own module and just import it wherever it's needed:
96112

97-
if (hasContext('key')) {
98-
// do something
113+
```js
114+
/// file: state.svelte.js
115+
export const myGlobalState = $state({
116+
user: {
117+
// ...
99118
}
100-
</script>
119+
// ...
120+
});
101121
```
102122

103-
You can also retrieve the whole context map that belongs to the closest parent component using `getAllContexts`. This is useful, for example, if you programmatically create a component and want to pass the existing context to it.
123+
In many cases this is perfectly fine, but there is a risk: if you mutate the state during server-side rendering (which is discouraged, but entirely possible!)...
104124

105125
```svelte
126+
<!--- file: App.svelte ---->
106127
<script>
107-
import { getAllContexts } from 'svelte';
128+
import { myGlobalState } from 'svelte';
108129
109-
const contexts = getAllContexts();
130+
let { data } = $props();
131+
132+
if (data.user) {
133+
myGlobalState.user = data.user;
134+
}
110135
</script>
111136
```
112137

113-
## Encapsulating context interactions
114-
115-
The above methods are very unopinionated about how to use them. When your app grows in scale, it's worthwhile to encapsulate setting and getting the context into functions and properly type them.
116-
117-
```ts
118-
// @errors: 2304
119-
import { getContext, setContext } from 'svelte';
120-
121-
let userKey = Symbol('user');
122-
123-
export function setUserContext(user: User) {
124-
setContext(userKey, user);
125-
}
126-
127-
export function getUserContext(): User {
128-
return getContext(userKey) as User;
129-
}
130-
```
138+
...then the data may be accessible by the _next_ user. Context solves this problem because it is not shared between requests.

packages/svelte/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# svelte
22

3+
## 5.23.2
4+
5+
### Patch Changes
6+
7+
- fix: don't hoist listeners that access non hoistable snippets ([#15534](https://github.com/sveltejs/svelte/pull/15534))
8+
39
## 5.23.1
410

511
### Patch Changes

packages/svelte/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "svelte",
33
"description": "Cybernetically enhanced web apps",
44
"license": "MIT",
5-
"version": "5.23.1",
5+
"version": "5.23.2",
66
"type": "module",
77
"types": "./types/index.d.ts",
88
"engines": {

packages/svelte/src/compiler/phases/2-analyze/visitors/Attribute.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,15 @@ function get_delegated_event(event_name, handler, context) {
183183
const binding = scope.get(reference);
184184
const local_binding = context.state.scope.get(reference);
185185

186+
// if the function access a snippet that can't be hoisted we bail out
187+
if (
188+
local_binding !== null &&
189+
local_binding.initial?.type === 'SnippetBlock' &&
190+
!local_binding.initial.metadata.can_hoist
191+
) {
192+
return unhoisted;
193+
}
194+
186195
// If we are referencing a binding that is shadowed in another scope then bail out.
187196
if (local_binding !== null && binding !== null && local_binding.node !== binding.node) {
188197
return unhoisted;

packages/svelte/src/internal/client/proxy.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,13 @@ function clone_options(options) {
4949
* @returns {T}
5050
*/
5151
export function proxy(value, _options, parent = null, prev) {
52-
let options = clone_options(_options);
53-
/** @type {Error | null} */
54-
var stack = null;
55-
if (DEV && tracing_mode_flag) {
56-
stack = get_stack('CreatedAt');
57-
}
5852
// if non-proxyable, or is already a proxy, return `value`
5953
if (typeof value !== 'object' || value === null) {
6054
return value;
6155
}
6256

57+
var options = clone_options(_options);
58+
6359
if (STATE_SYMBOL in value) {
6460
// @ts-ignore
6561
value[PROXY_ONCHANGE_SYMBOL](options?.onchange);
@@ -88,6 +84,8 @@ export function proxy(value, _options, parent = null, prev) {
8884
var is_proxied_array = is_array(value);
8985
var version = source(0);
9086

87+
var stack = DEV && tracing_mode_flag ? get_stack('CreatedAt') : null;
88+
9189
if (is_proxied_array) {
9290
// We need to create the length source eagerly to ensure that
9391
// mutations to the array are properly synced with our proxy

packages/svelte/src/version.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@
44
* The current version, as set in package.json.
55
* @type {string}
66
*/
7-
export const VERSION = '5.23.1';
7+
export const VERSION = '5.23.2';
88
export const PUBLIC_VERSION = '5';
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { flushSync } from 'svelte';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
async test({ assert, target, errors }) {
6+
const button = target.querySelector('button');
7+
flushSync(() => {
8+
button?.click();
9+
});
10+
assert.deepEqual(errors, []);
11+
}
12+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<script>
2+
const log = () => {
3+
console.log(snip);
4+
}
5+
let x = $state(0);
6+
</script>
7+
8+
<button onclick={log}></button>
9+
10+
{#snippet snip()}
11+
snippet {x}
12+
{/snippet}

0 commit comments

Comments
 (0)