Svelteのトランジションエンジンの特に強力な機能は、トランジションを遅延させることができる点です。これにより、複数の要素間でトランジションを調整できます。
タスクリストのペアを考えてみましょう。ここでは、タスクの切り替えによって、タスクが反対側のリストに送られます。現実世界では、オブジェクトはそうした動作はしません。別の場所に消えて現れる代わりに、一連の中間位置を通って移動します。モーションを使用することで、アプリで何が起こっているかをユーザーが理解するのに役立ちます。
この効果は、`transition.js`にあるように`crossfade`関数を使用して実現できます。この関数は、`send`と`receive`という2つのトランジションを作成します。要素が「送信」されると、対応する「受信」要素を探し、要素を対応する要素の位置に変換してフェードアウトするトランジションを生成します。「受信」された要素の場合は、逆の処理が行われます。対応する要素がない場合、`fallback`トランジションが使用されます。
`TodoList.svelte`を開きます。最初に、`transition.js`から`send`と`receive`トランジションをインポートします。
TodoList
<script>
import { send, receive } from './transition.js';
let { todos, remove } = $props();
</script>
次に、要素と要素を一致させるキーとして`todo.id`プロパティを使用して、`<li>`要素にそれらを追加します。
TodoList
<li
class:done={todo.done}
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
>
これで、アイテムを切り替えると、スムーズに新しい場所に移動します。トランジションしていないアイテムは依然としてぎこちなく飛び回っています。これは次の演習で修正できます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<script>
import TodoList from './TodoList.svelte';
const todos = $state([
{ done: false, description: 'write some docs' },
{ done: false, description: 'start writing blog post' },
{ done: true, description: 'buy some milk' },
{ done: false, description: 'mow the lawn' },
{ done: false, description: 'feed the turtle' },
{ done: false, description: 'fix some bugs' }
]);
function remove(todo) {
const index = todos.indexOf(todo);
todos.splice(index, 1);
}
</script>
<div class="board">
<input
placeholder="what needs to be done?"
onkeydown={(e) => {
if (e.key !== 'Enter') return;
todos.push({
done: false,
description: e.currentTarget.value
});
e.currentTarget.value = '';
}}
/>
<div class="todo">
<h2>todo</h2>
<TodoList todos={todos.filter((t) => !t.done)} {remove} />
</div>
<div class="done">
<h2>done</h2>
<TodoList todos={todos.filter((t) => t.done)} {remove} />
</div>
</div>
<style>
.board {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 1em;
max-width: 36em;
margin: 0 auto;
}
.board > input {
font-size: 1.4em;
grid-column: 1/3;
padding: 0.5em;
margin: 0 0 1rem 0;
}
h2 {
font-size: 2em;
font-weight: 200;
}
</style>