fix: keep bound inputs in sync in runes mode (#13328)

* fix: keep bound inputs in sync in runes mode

* small tweak, add more detailed explanatory comment

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/13335/head
Dominic Gannaway 1 day ago committed by GitHub
parent 00cc3640b1
commit db6545d173
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: keep bound inputs in sync in runes mode

@ -5,6 +5,7 @@ import * as e from '../../../errors.js';
import { get_proxied_value, is } from '../../../proxy.js';
import { queue_micro_task } from '../../task.js';
import { hydrating } from '../../hydration.js';
import { is_runes } from '../../../runtime.js';
/**
* @param {HTMLInputElement} input
@ -13,13 +14,24 @@ import { hydrating } from '../../hydration.js';
* @returns {void}
*/
export function bind_value(input, get, set = get) {
var runes = is_runes();
listen_to_event_and_reset_event(input, 'input', () => {
if (DEV && input.type === 'checkbox') {
// TODO should this happen in prod too?
e.bind_invalid_checkbox_value();
}
set(is_numberlike_input(input) ? to_number(input.value) : input.value);
/** @type {unknown} */
var value = is_numberlike_input(input) ? to_number(input.value) : input.value;
set(value);
// In runes mode, respect any validation in accessors (doesn't apply in legacy mode,
// because we use mutable state which ensures the render effect always runs)
if (runes && value !== (value = get())) {
// @ts-expect-error the value is coerced on assignment
input.value = value ?? '';
}
});
render_effect(() => {

@ -0,0 +1,27 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `<input type="number"><div>0</div>`,
mode: ['client', 'hydrate'],
async test({ assert, target }) {
const [input1] = target.querySelectorAll('input');
assert.equal(input1.value, '0');
input1.value = '1';
input1.dispatchEvent(new window.InputEvent('input'));
flushSync();
assert.equal(input1.value, '1');
assert.htmlEqual(target.innerHTML, `<input type="number"><div>1</div>`);
input1.value = '101';
input1.dispatchEvent(new window.InputEvent('input'));
flushSync();
assert.equal(input1.value, '100');
assert.htmlEqual(target.innerHTML, `<input type="number"><div>100</div>`);
}
});

@ -0,0 +1,11 @@
<script>
let v = $state(0)
let count = {
get v() { return v },
set v(x) { {
v = Math.min(100, +x)
}},
};
</script>
<input bind:value={count.v} type="number">
<div>{count.v}</div>
Loading…
Cancel
Save