Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shy-boats-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: add `$state.eager(value)` rune
15 changes: 15 additions & 0 deletions documentation/docs/02-runes/02-$state.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,21 @@ To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snaps

This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`.

## `$state.eager`

When state changes, it may not be reflected in the UI immediately if it is used by an `await` expression, because [updates are synchronized](await-expressions#Synchronized-updates).

In some cases, you may want to update the UI as soon as the state changes. For example, you might want to update a navigation bar when the user clicks on a link, so that they get visual feedback while waiting for the new page to load. To do this, use `$state.eager(value)`:

```svelte
<nav>
<a href="/" aria-current={$state.eager(pathname) === '/' ? 'page' : null}>home</a>
<a href="/about" aria-current={$state.eager(pathname) === '/about' ? 'page' : null}>about</a>
</nav>
```

Use this feature sparingly, and only to provide feedback in response to user action — in general, allowing Svelte to coordinate updates will provide a better user experience.

## Passing state into functions

JavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words:
Expand Down
12 changes: 12 additions & 0 deletions packages/svelte/src/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,18 @@ declare namespace $state {
: never
: never;

/**
* Returns the latest `value`, even if the rest of the UI is suspending
* while async work (such as data loading) completes.
*
* ```svelte
* <nav>
* <a href="/" aria-current={$state.eager(pathname) === '/' ? 'page' : null}>home</a>
* <a href="/about" aria-current={$state.eager(pathname) === '/about' ? 'page' : null}>about</a>
* </nav>
* ```
*/
export function eager<T>(value: T): T;
/**
* Declares state that is _not_ made deeply reactive — instead of mutating it,
* you must reassign it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,13 @@ export function CallExpression(node, context) {
break;
}

case '$state.eager':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}

break;

case '$state.snapshot':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ export function CallExpression(node, context) {
return b.call('$.derived', rune === '$derived' ? b.thunk(fn) : fn);
}

case '$state.eager':
return b.call(
'$.eager',
b.thunk(/** @type {Expression} */ (context.visit(node.arguments[0])))
);

case '$state.snapshot':
return b.call(
'$.snapshot',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export function CallExpression(node, context) {
return b.call('$.derived', rune === '$derived' ? b.thunk(fn) : fn);
}

if (rune === '$state.eager') {
return node.arguments[0];
}

if (rune === '$state.snapshot') {
return b.call(
'$.snapshot',
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte/src/internal/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export {
save,
track_reactivity_loss
} from './reactivity/async.js';
export { flushSync as flush } from './reactivity/batch.js';
export { eager, flushSync as flush } from './reactivity/batch.js';
export {
async_derived,
user_derived as derived,
Expand Down
64 changes: 62 additions & 2 deletions packages/svelte/src/internal/client/reactivity/batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { async_mode_flag } from '../../flags/index.js';
import { deferred, define_property } from '../../shared/utils.js';
import {
active_effect,
get,
is_dirty,
is_updating_effect,
set_is_updating_effect,
Expand All @@ -27,8 +28,8 @@ import * as e from '../errors.js';
import { flush_tasks, queue_micro_task } from '../dom/task.js';
import { DEV } from 'esm-env';
import { invoke_error_boundary } from '../error-handling.js';
import { old_values } from './sources.js';
import { unlink_effect } from './effects.js';
import { old_values, source, update } from './sources.js';
import { inspect_effect, unlink_effect } from './effects.js';

/** @type {Set<Batch>} */
const batches = new Set();
Expand Down Expand Up @@ -702,6 +703,65 @@ export function schedule_effect(signal) {
queued_root_effects.push(effect);
}

/** @type {Source<number>[]} */
let eager_versions = [];

function eager_flush() {
try {
flushSync(() => {
for (const version of eager_versions) {
update(version);
}
});
} finally {
eager_versions = [];
}
}

/**
* Implementation of `$state.eager(fn())`
* @template T
* @param {() => T} fn
* @returns {T}
*/
export function eager(fn) {
var version = source(0);
var initial = true;
var value = /** @type {T} */ (undefined);

get(version);

inspect_effect(() => {
if (initial) {
// the first time this runs, we create an inspect effect
// that will run eagerly whenever the expression changes
var previous_batch_values = batch_values;

try {
batch_values = null;
value = fn();
} finally {
batch_values = previous_batch_values;
}

return;
}

// the second time this effect runs, it's to schedule a
// `version` update. since this will recreate the effect,
// we don't need to evaluate the expression here
if (eager_versions.length === 0) {
queue_micro_task(eager_flush);
}

eager_versions.push(version);
});

initial = false;

return value;
}

/**
* Forcibly remove all current batches, to prevent cross-talk between tests
*/
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ const STATE_CREATION_RUNES = /** @type {const} */ ([

const RUNES = /** @type {const} */ ([
...STATE_CREATION_RUNES,
'$state.eager',
'$state.snapshot',
'$props',
'$props.id',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { tick } from 'svelte';
import { test } from '../../test';

export default test({
async test({ assert, target }) {
const [count, shift] = target.querySelectorAll('button');

shift.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>0</button><button>shift</button><p>0</p>`);

count.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>1</button><button>shift</button><p>0</p>`);

count.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>2</button><button>shift</button><p>0</p>`);

count.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>3</button><button>shift</button><p>0</p>`);

shift.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>3</button><button>shift</button><p>1</p>`);

shift.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>3</button><button>shift</button><p>2</p>`);

shift.click();
await tick();
assert.htmlEqual(target.innerHTML, `<button>3</button><button>shift</button><p>3</p>`);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<script>
let count = $state(0);

let resolvers = [];

function push(value) {
const { promise, resolve } = Promise.withResolvers();
resolvers.push(() => resolve(value));
return promise;
}
</script>

<button onclick={() => count += 1}>{$state.eager(count)}</button>
<button onclick={() => resolvers.shift()?.()}>shift</button>

<svelte:boundary>
<p>{await push(count)}</p>

{#snippet pending()}{/snippet}
</svelte:boundary>
12 changes: 12 additions & 0 deletions packages/svelte/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3193,6 +3193,18 @@ declare namespace $state {
: never
: never;

/**
* Returns the latest `value`, even if the rest of the UI is suspending
* while async work (such as data loading) completes.
*
* ```svelte
* <nav>
* <a href="/" aria-current={$state.eager(pathname) === '/' ? 'page' : null}>home</a>
* <a href="/about" aria-current={$state.eager(pathname) === '/about' ? 'page' : null}>about</a>
* </nav>
* ```
*/
export function eager<T>(value: T): T;
/**
* Declares state that is _not_ made deeply reactive — instead of mutating it,
* you must reassign it.
Expand Down
Loading