Part 1 / Lifecycle / beforeUpdate and afterUpdate
The beforeUpdate
function schedules work to happen immediately before the DOM is updated. afterUpdate
is its counterpart, used for running code once the DOM is in sync with your data.
Together, they're useful for doing things imperatively that are difficult to achieve in a purely state-driven way, like updating the scroll position of an element.
This Eliza chatbot is annoying to use, because you have to keep scrolling the chat window. Let's fix that.
App.svelte
let div;
let autoscroll = false;
beforeUpdate(() => {
autoscroll = div && div.offsetHeight + div.scrollTop > div.scrollHeight - 20;
});
afterUpdate(() => {
if (autoscroll) {
div.scrollTo(0, div.scrollHeight);
}
});
Note that beforeUpdate
will first run before the component has mounted, so we need to check for the existence of div
before reading its properties.
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<script>
import Eliza from 'elizabot';
import {
beforeUpdate,
afterUpdate
} from 'svelte';
let div;
beforeUpdate(() => {
// determine whether we should auto-scroll
// once the DOM is updated...
});
afterUpdate(() => {
// ...the DOM is now in sync with the data
});
const eliza = new Eliza();
const pause = (ms) => new Promise((fulfil) => setTimeout(fulfil, ms));
const typing = { author: 'eliza', text: '...' };
let comments = [
{ author: 'eliza', text: eliza.getInitial() }
];
async function handleKeydown(event) {
if (event.key === 'Enter' && event.target.value) {
event.target.value = '';
const comment = {
author: 'user',
text: event.target.value
};
const reply = {
author: 'eliza',
text: eliza.transform(comment.text)
};
comments = [...comments, comment];
await pause(200 * (1 + Math.random()));
comments = [...comments, typing];
await pause(500 * (1 + Math.random()));
comments = [...comments, reply].filter(comment => comment !== typing);
}
}
</script>
<div class="chat">
<h1>Eliza</h1>
<div class="scrollable" bind:this={div}>
{#each comments as comment}
<article class={comment.author}>
<span>{comment.text}</span>
</article>
{/each}
</div>
<input on:keydown={handleKeydown} />
</div>
<style>
.chat {
display: flex;
flex-direction: column;
height: 100%;
max-width: 320px;
}
.scrollable {
flex: 1 1 auto;
border-top: 1px solid #eee;
margin: 0 0 0.5em 0;
overflow-y: auto;
}
article {
margin: 0.5em 0;
}
.user {
text-align: right;
}
span {
padding: 0.5em 1em;
display: inline-block;
}
.eliza span {
background-color: #eee;
border-radius: 1em 1em 1em 0;
color: black;
}
.user span {
background-color: #0074d9;
color: white;
border-radius: 1em 1em 0 1em;
word-break: break-all;
}
</style>
initialising