Skip to content

Commit c8865bb

Browse files
fix: make Tween with duration 0 set current to target immediately (#14937)
* fix: Make Tween duration 0 set current to target immediately * Run prettier on test file * tweak --------- Co-authored-by: Rich Harris <[email protected]>
1 parent a1f371e commit c8865bb

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

.changeset/cold-cups-act.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: Make Tween duration 0 set current to target immediately

packages/svelte/src/motion/tweened.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,20 +230,25 @@ export class Tween {
230230
set(value, options) {
231231
set(this.#target, value);
232232

233-
let previous_task = this.#task;
234-
235-
let started = false;
236233
let {
237234
delay = 0,
238235
duration = 400,
239236
easing = linear,
240237
interpolate = get_interpolator
241238
} = { ...this.#defaults, ...options };
242239

240+
if (duration === 0) {
241+
this.#task?.abort();
242+
set(this.#current, value);
243+
return Promise.resolve();
244+
}
245+
243246
const start = raf.now() + delay;
244247

245248
/** @type {(t: number) => T} */
246249
let fn;
250+
let started = false;
251+
let previous_task = this.#task;
247252

248253
this.#task = loop((now) => {
249254
if (now < start) {

packages/svelte/tests/motion/test.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import '../helpers.js'; // for the matchMedia polyfill
33
import { describe, it, assert } from 'vitest';
44
import { get } from 'svelte/store';
5-
import { spring, tweened } from 'svelte/motion';
5+
import { spring, tweened, Tween } from 'svelte/motion';
66

77
describe('motion', () => {
88
describe('spring', () => {
@@ -39,4 +39,20 @@ describe('motion', () => {
3939
assert.equal(get(size), 20);
4040
});
4141
});
42+
43+
describe('Tween', () => {
44+
it('sets immediately when duration is 0', () => {
45+
const size = new Tween(0);
46+
47+
size.set(100, { duration: 0 });
48+
assert.equal(size.current, 100);
49+
});
50+
});
51+
52+
it('updates correctly when initialized with a `null`-ish value', () => {
53+
const size = new Tween(undefined as unknown as number, { duration: 0 });
54+
55+
size.set(10);
56+
assert.equal(size.current, 10);
57+
});
4258
});

0 commit comments

Comments
 (0)