Skip to main content

Part 3 / Animations / The animate directive

In the previous chapter, we used deferred transitions to create the illusion of motion as elements move from one todo list to the other.

To complete the illusion, we also need to apply motion to the elements that aren't transitioning. For this, we use the animate directive.

First, import the flip function — flip stands for 'First, Last, Invert, Play' — from svelte/animate into TodoList.svelte:

TodoList.svelte
<script>
	import { flip } from 'svelte/animate';
	import { send, receive } from './transition.js';

	export let store;
	export let filter;
</script>

Then add it to the <label> elements:

TodoList.svelte
<label
	in:receive={{ key: todo.id }}
	out:send={{ key: todo.id }}
	animate:flip
>

The movement is a little slow in this case, so we can add a duration parameter:

TodoList.svelte
<label
	in:receive={{ key: todo.id }}
	out:send={{ key: todo.id }}
	animate:flip={{ duration: 200 }}
>

duration can also be a d => milliseconds function, where d is the number of pixels the element has to travel

Note that all the transitions and animations are being applied with CSS, rather than JavaScript, meaning they won't block (or be blocked by) the main thread.

Next: Actions

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
67
68
<script>
	import { createTodoStore } from './todos.js';
	import TodoList from './TodoList.svelte';
 
	const todos = createTodoStore([
		{ 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' }
	]);
</script>
 
<div class="board">
	<input
		placeholder="what needs to be done?"
		on:keydown={(e) => {
			if (e.key === 'Enter') {
				todos.add(e.currentTarget.value);
				e.currentTarget.value = '';
			}
		}}
	/>
 
	<div class="todo">
		<h2>todo</h2>
		<TodoList store={todos} filter={(t) => !t.done} />
	</div>
 
	<div class="done">
		<h2>done</h2>
		<TodoList store={todos} filter={(t) => t.done} />
	</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;
	}
 
	.todo {
		--label: #222;
		--filter: drop-shadow(2px 3px 6px rgba(0,0,0,0.1));
	}
 
	.done {
		--label: #999;
		--filter: none;
	}
</style>
 
initialising