Skip to main content

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(() => {
	if (div) {
		const scrollableDistance = div.scrollHeight - div.offsetHeight;
		autoscroll = div.scrollTop > scrollableDistance - 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.

Next: tick

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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<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 = [];
 
	async function handleKeydown(event) {
		if (event.key === 'Enter' && event.target.value) {
			const comment = {
				author: 'user',
				text: event.target.value
			};
 
			const reply = {
				author: 'eliza',
				text: eliza.transform(comment.text)
			};
 
			event.target.value = '';
			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="container">
	<div class="phone">
		<div class="chat" bind:this={div}>
			<header>
				<h1>Eliza</h1>
 
				<article class="eliza">
					<span>{eliza.getInitial()}</span>
				</article>
			</header>
 
			{#each comments as comment}
				<article class={comment.author}>
					<span>{comment.text}</span>
				</article>
			{/each}
		</div>
 
		<input on:keydown={handleKeydown} />
	</div>
</div>
 
<style>
	.container {
		display: grid;
		place-items: center;
		height: 100%;
	}
 
	.phone {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}
 
	header {
		display: flex;
		flex-direction: column;
		height: 100%;
		padding: 4em 0 0 0;
		box-sizing: border-box;
	}
 
	h1 {
		flex: 1;
		font-size: 1.4em;
		text-align: center;
	}
 
	.chat {
		height: 0;
		flex: 1 1 auto;
		padding: 0 1em;
		overflow-y: auto;
		scroll-behavior: smooth;
	}
 
	article {
		margin: 0 0 0.5em 0;
	}
 
	.user {
		text-align: right;
	}
 
	span {
		padding: 0.5em 1em;
		display: inline-block;
	}
 
	.eliza span {
		background-color: var(--bg-1);
		border-radius: 1em 1em 1em 0;
		color: var(--fg-1);
	}
 
	.user span {
		background-color: #0074d9;
		color: white;
		border-radius: 1em 1em 0 1em;
		word-break: break-all;
	}
 
	input {
		margin: 0.5em 1em 1em 1em;
	}
 
	@media (min-width: 400px) {
		.phone {
			background: var(--bg-2);
			position: relative;
			font-size: min(2.5vh, 1rem);
			width: auto;
			height: 36em;
			aspect-ratio: 9 / 16;
			border: 0.2em solid #222;
			border-radius: 1em;
			box-sizing: border-box;
			filter: drop-shadow(1px 1px 0px #222) drop-shadow(2px 2px 0px #222) drop-shadow(3px 3px 0px #222)
		}
 
		.phone::after {
			position: absolute;
			content: '';
			background: #222;
			width: 60%;
			height: 1em;
			left: 20%;
			top: 0;
			border-radius: 0 0 0.5em 0.5em
		}
	}
 
	@media (prefers-reduced-motion) {
		.chat {
			scroll-behavior: auto;
		}
	}
</style>
 
initialising