Skip to content
Open
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
18 changes: 15 additions & 3 deletions packages/svelte/src/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,24 @@ 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(href) === '/' ? 'page' : null}>home</a>
* <a href="/about" aria-current={$state.eager(href) === '/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.
*
* Example:
* ```ts
* ```svelte
* <script>
* let items = $state.raw([0]);
*
Expand All @@ -109,7 +121,7 @@ declare namespace $state {
* };
* </script>
*
* <button on:click={addItem}>
* <button onclick={addItem}>
* {items.join(', ')}
* </button>
* ```
Expand All @@ -124,7 +136,7 @@ declare namespace $state {
* To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`:
*
* Example:
* ```ts
* ```svelte
* <script>
* let counter = $state({ count: 0 });
*
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/dom/blocks/boundary.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { queue_micro_task } from '../task.js';
import * as e from '../../errors.js';
import * as w from '../../warnings.js';
import { DEV } from 'esm-env';
import { Batch, current_batch, effect_pending_updates } from '../../reactivity/batch.js';
import { Batch, effect_pending_updates } from '../../reactivity/batch.js';
import { internal_set, source } from '../../reactivity/sources.js';
import { tag } from '../../dev/tracing.js';
import { createSubscriber } from '../../../../reactivity/create-subscriber.js';
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
47 changes: 45 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,48 @@ export function schedule_effect(signal) {
queued_root_effects.push(effect);
}

/** @type {Source<number>} */
let version;

let eager_flushing = false;

function eager_flush() {
try {
flushSync(() => {
update(version);
});
} finally {
eager_flushing = false;
}
}

/**
* @template T
* @param {() => T} fn
* @returns {T}
*/
export function eager(fn) {
const previous_batch_values = batch_values;

try {
get((version ??= source(0)));

inspect_effect(() => {
fn();

if (!eager_flushing) {
eager_flushing = true;
queue_micro_task(eager_flush);
}
});

batch_values = null;
return fn();
} finally {
batch_values = previous_batch_values;
}
}

/**
* Forcibly remove all current batches, to prevent cross-talk between tests
*/
Expand Down
8 changes: 4 additions & 4 deletions packages/svelte/src/internal/client/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,20 +653,20 @@ export function get(signal) {
if (is_derived) {
derived = /** @type {Derived} */ (signal);

var value = derived.v;
var derived_value = derived.v;

// if the derived is dirty and has reactions, or depends on the values that just changed, re-execute
// (a derived can be maybe_dirty due to the effect destroy removing its last reaction)
if (
((derived.f & CLEAN) === 0 && derived.reactions !== null) ||
depends_on_old_values(derived)
) {
value = execute_derived(derived);
derived_value = execute_derived(derived);
}

old_values.set(derived, value);
old_values.set(derived, derived_value);

return value;
return derived_value;
}
} else if (is_derived) {
derived = /** @type {Derived} */ (signal);
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,42 @@
import { tick } from 'svelte';
import { test } from '../../test';

export default test({
mode: ['client'],

compileOptions: {
dev: true
},

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>
18 changes: 15 additions & 3 deletions packages/svelte/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3193,12 +3193,24 @@ 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(href) === '/' ? 'page' : null}>home</a>
* <a href="/about" aria-current={$state.eager(href) === '/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.
*
* Example:
* ```ts
* ```svelte
* <script>
* let items = $state.raw([0]);
*
Expand All @@ -3207,7 +3219,7 @@ declare namespace $state {
* };
* </script>
*
* <button on:click={addItem}>
* <button onclick={addItem}>
* {items.join(', ')}
* </button>
* ```
Expand All @@ -3222,7 +3234,7 @@ declare namespace $state {
* To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`:
*
* Example:
* ```ts
* ```svelte
* <script>
* let counter = $state({ count: 0 });
*
Expand Down
Loading