Tweened is svelte tools to help you build slick user interfaces that use animation to communicate changes. Below is example of progress bar, tweened is used to make transition smoother. easing is even make it more smoother.
<script> import {tweened} from 'svelte/motion'; import {cubicOut} from 'svelte/easing'; const progress = tweened(0, { duration: 400, easing: cubicOut }); </script> <style> progress { display: block; width: 100%; } </style> <progress value={$progress}></progress> <button on:click="{() => progress.set(0)}"> 0% </button> <button on:click="{() => progress.set(0.25)}"> 25% </button> <button on:click="{() => progress.set(0.5)}"> 50% </button> <button on:click="{() => progress.set(0.75)}"> 75% </button> <button on:click="{() => progress.set(1)}"> 100% </button>
The full set of options available to tweened:
delay — milliseconds before the tween starts
duration — either the duration of the tween in milliseconds, or a (from, to) => milisecons function allowing you to (e.g.) specify longer tweens for larger changes in value
easing — a p => t function
interpolate — a custom (from, to) => t => value function for interpolating between arbitrary values. By default, Svelte will interpolate between numbers, dates, and identically-shaped arrays and objects (as long as they only contain numbers and dates or other valid arrays and objects). If you want to interpolate (for example) colour strings or transformation matrices, supply a custom interpolator
You can also pass these options to progress.set and progress.update as a second argument, in which case they will override the defaults. The set and update methods both return a promise that resolves when the tween completes.
Spring
The spring function is an alternative to tweened that often works better for values that are frequently changing. In this example we have two stores — one representing the circle's coordinates, and one representing its size. Both springs have default stiffness and damping values, which control the spring's, well... springiness. We can specify our own initial values:
<script> import { spring } from 'svelte/motion'; let coords = spring({ x: 50, y: 50 }, { stiffness: 0.1, damping: 0.25 }) let size = spring(10); </script> <style> svg { width: 100%; height: 100%; margin: -8px; } circle { fill: #ff3e00 } </style> <div style="position: absolute; right: 1em;"> <label> <h3>stiffness ({coords.stiffness})</h3> <input bind:value={coords.stiffness} type="range" min="0" max="1" step="0.01"> </label> <label> <h3>damping ({coords.damping})</h3> <input bind:value={coords.damping} type="range" min="0" max="1" step="0.01"> </label> </div> <svg on:mousemove="{e => coords.set({ x: e.clientX, y: e.clientY })}" on:mousedown="{() => size.set(30)}" on:mouseup="{() => size.set(10)}" > <circle cx={$coords.x} cy={$coords.y} r={$size}/> </svg>
Waggle your mouse around, and try dragging the sliders to get a feel for how they affect the spring's behaviour. Notice that you can adjust the values while the spring is still in motion.
Indonesia
Tweened
tweened adalah alat yang disediakan svelte untuk membantu kita membuat user interface yang enak digunakan, yang menggunakan animasi untuk menampilkan suatu perubahan. Dibawah ini adalah contoh program untuk membuat progress bar, tweened digunakan untuk membuat transisi lebih mulus. easing membuatnya makin mulus lagi.
duration — antara durasi tween dalam milisekon, atau sebuah fungsi (from, to) => milisecons yang memungkinkan kita untuk (misalnya) mengatur tween yang lebih lama untuk perubahan yang lebih besar
easing — sebuah fungsi p => t
interpolate — sebuah fungsi custom (from, to) => t => value untuk melakukan interpolasi antara nilai arbitari. Secara default, svelte akan melakukaninterpolasi antara angka, tanggal, dan array yang bentuknya identik, dan object (selama hanya mengandung angka dan tanggal atau array yang valid dan object). Jika kita ingin melakukan interpolasi (sebagai contoh) sekumpulan warna atau matriks transformasi, sediakan interpolator custom
Kita juga bisa pass option ini ke progress.set dan progress.update sebagai argumen kedua, sehingga akan melakukan override untuk nilai default nya. Method set dan update keduanya akan me return promise yang akan resolve ketika tween selesai.
Spring
Fungsi spring adalah alternatif dari tweened yang biasanya akan bekerja lebih baik untuk nilai2 yang sering berubah. Pada contoh berikut kita akan memiliki dua store — satu menandakan koordinat lingkaran, dan satunya menyimpan ukuran lingkaran. spring mempunyai nilai default stiffness dan damping, yang akan mengontrol ke spring an nya.. Kita juga bisa memberikan nilai sendiri:
<script> import { spring } from 'svelte/motion'; let coords = spring({ x: 50, y: 50 }, { stiffness: 0.1, damping: 0.25 }) let size = spring(10); </script> <style> svg { width: 100%; height: 100%; margin: -8px; } circle { fill: #ff3e00 } </style> <div style="position: absolute; right: 1em;"> <label> <h3>stiffness ({coords.stiffness})</h3> <input bind:value={coords.stiffness} type="range" min="0" max="1" step="0.01"> </label> <label> <h3>damping ({coords.damping})</h3> <input bind:value={coords.damping} type="range" min="0" max="1" step="0.01"> </label> </div> <svg on:mousemove="{e => coords.set({ x: e.clientX, y: e.clientY })}" on:mousedown="{() => size.set(30)}" on:mouseup="{() => size.set(10)}" > <circle cx={$coords.x} cy={$coords.y} r={$size}/> </svg> Goyang-goyangkan mouse, dan cobalah menggeser slider untuk memahami bagaimana mereka mempengaruhi kelakuan spring. Perhatikan bahwa kita juga bisa mengubah efeknya ketika spring masih sedang bergerak.
Not all application state belongs inside your application's component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.
Writable Stores
In Svelte, we do this with stores. A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes. Below is an example where, count is a store, and we're setting count_value in the count.subscribe callback.
let count_value; const unsubscribe = count.subscribe(value => { count_value = value; });
This is the definition of count. It's a writable store, which means it has set and update methods in addition to subscribe. import { writable } from 'svelte/store'; export const count = writable(0);
count can be updated or set like this:
function increment() { count.update(n => n + 1); } function reset() { count.set(0); }
The app in the previous example works, but there's a subtle bug — the unsubscribe function never gets called. If the component was instantiated and destroyed many times, this would result in a memory leak.
One way to fix it would be to use the onDestroy lifecycle hook:
<script> import { onDestroy } from 'svelte'; import { count } from './stores.js'; import Incrementer from './Incrementer.svelte'; import Decrementer from './Decrementer.svelte'; import Resetter from './Resetter.svelte'; let count_value; const unsubscribe = count.subscribe(value => { count_value = value; }); onDestroy(unsubscribe); </script> <h1>The count is {count_value}</h1>
It starts to get a bit boilerplatey though, especially if your component subscribes to multiple stores. Instead, Svelte has a trick up its sleeve — with autosubscribe means you can reference a store value by prefixing the store name with $ (you don't need to manually do onDestroy too, it's automatic):
<script> import { count } from './stores.js'; import Incrementer from './Incrementer.svelte'; import Decrementer from './Decrementer.svelte'; import Resetter from './Resetter.svelte'; </script> <h1>The count is {$count}</h1>
You can see the difference in first and second example, much simpler by using $. Auto-subscription only works with store variables that are declared (or imported) at the top-level scope of a component.
You're not limited to using $count inside the markup, either — you can use it anywhere in the <script> as well, such as in event handlers or reactive declarations.
Any name beginning with $ is assumed to refer to a store value. It's effectively a reserved character — Svelte will prevent you from declaring your own variables with a $ prefix.
Readable Stores
Not all stores should be writable by whoever has a reference to them. For example, you might have a store representing the mouse position or the user's geolocation, and it doesn't make sense to be able to set those values from 'outside'. For those cases, we have readable stores.
Create a stores.js file. The first argument to readable is an initial value, which can be null or undefined if you don't have one yet. The second argument is a start function that takes a set callback and returns a stop function. The start function is called when the store gets its first subscriber; stop is called when the last subscriber unsubscribes.
// this is stores.js import { readable } from 'svelte/store'; export const time = readable(new Date(), function start(set) { // called at subscribe const interval = setInterval(() => { set(new Date()); }, 1000); return function stop() { // called when unsubscribe clearInterval(interval); }; });
Then we can use time in App.svelte: <script> import { time } from './stores.js'; const formatter = new Intl.DateTimeFormat('en', { hour12: true, hour: 'numeric', minute: '2-digit', second: '2-digit' }); </script> <h1>The time is {formatter.format($time)}</h1>
Derived Stores
You can create a store whose value is based on the value of one or more other stores with derived. Building on our previous example, we can create a store that derives the time the page has been open:
It's possible to derive a store from multiple inputs, and to explicitly set a value instead of returning it (which is useful for deriving values asynchronously). Consult the API reference for more information. Full example can be seen here.
Custom Stores
As long as an object correctly implements the subscribe method, it's a store. Beyond that, anything goes. It's very easy, therefore, to create custom stores with domain-specific logic.
For example, the count store from our earlier example could include increment, decrement and reset methods and avoid exposing set and update:
function createCount() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; }
And here is how we're gonna use it in main app:
<script> import { count } from './stores.js'; </script> <h1>The count is {$count}</h1> <button on:click={count.increment}>+</button> <button on:click={count.decrement}>-</button> <button on:click={count.reset}>reset</button>
Stores Binding
If a store is writable — i.e. it has a set method — you can bind to its value, just as you can bind to local component state. In this example we have a writable store name and a derived store greeting.
Changing the input value will now update name and all its dependents. We can also assign directly to store values inside a component. Add a <button> element:
The $name+='!' assignment is equivalent to name.set($name+'!').
Indonesia
Stores
Tidak semua nilai dalam aplikasi berada di dalam hirarki komponen. Kadang, kita akan mempunyai suatu nilai yang perlu diakses oleh beberapa komponen yang tidak berhubungan, atau bisa juga oleh modul JavaScript biasa.
Writable Stores
Di svelte, kita bisa menggunakan store untuk keperluan ini. Store adalah suatu object dengan method subscribe yang memungkinkan bagian yang membutuhkan untuk mendapat notifikasi saat nilai dari store itu berubah. Di bawah ini adalah contoh store, count dan kita akan mengatur nilai dari count_value pada callback count.subscribe.
let count_value; const unsubscribe = count.subscribe(value => { count_value = value; });
Di bawah ini adalah definisi dari count. Yang merupakan writable store, berarti count memiliki method set dan update selain subscribe. import { writable } from 'svelte/store'; export const count = writable(0);
ini contoh cara update atau setcount:
function increment() { count.update(n => n + 1); } function reset() { count.set(0); }
Aplikasi di contoh sebelumnya akan berjalan, tapi ada sedikit kekurangan — fungsi unsubscribe tidak pernah dijalankan. Jika komponen itu akan di instantiate dan di destroy berulang kali, akan ada memori yang bocor.
Salah satu cara untuk memperbaikinya adalah dengan menggunakan pancingan lifecycle onDestroy :
<script> import { onDestroy } from 'svelte'; import { count } from './stores.js'; import Incrementer from './Incrementer.svelte'; import Decrementer from './Decrementer.svelte'; import Resetter from './Resetter.svelte'; let count_value; const unsubscribe = count.subscribe(value => { count_value = value; }); onDestroy(unsubscribe); </script> <h1>The count is {count_value}</h1>
Tapi programnya mulai terlihat sedikit ribet, terutama jika komponen itu melakukan subscribe ke banyak store. Maka, svelte sudah menyediakan satu kemudahan — dengan autosubscribe, yang berarti kita bisa langsung melakukan referensi ke suatu store dengan memberikan awalan nama store dengan $ (maka kita tidak perlu lagi melakukan unsubscribe di onDestroy):
<script> import { count } from './stores.js'; import Incrementer from './Incrementer.svelte'; import Decrementer from './Decrementer.svelte'; import Resetter from './Resetter.svelte'; </script> <h1>The count is {$count}</h1> Kita bisa liat perbedaan dari contoh pertama dan kedua, akan jauh lebih mudah dengan menggunakan $. Auto subscription hanya bekerja dengan variabel store yang dideklarasikan (atau di import) pada bagian atas dari scope suatu komponen.
Kita juga tidak terbatas untuk menggunakan $count hanya di dalam markup, kita bisa gunakan di dalam <script> juga, seperti di event handle atau deklarasi reactive.
Semua nama yang berawalan dengan $ akan dianggap mengacu pada nilai store. Maka karakter ini adalah karakter reserved — Svelte akan mencegah kita deklarasi variabel dengan awalan $.
Readable Stores
Tidak semua store perlu bisa writable. Sebagai contoh , kita bisa mempunyai store yang menyimpan posisi mouse, atau geolokasi, maka akan tidak masuk akal jika nilai store itu mau dirubah-rubah. Untuk kasus seperti itu ada readable store, store yang hanya readonly.
Pertama buat file stores.js . Argumen pertama untuk readable adalah inisialisasi awal, bisa berisi null atau undefined jika memang belum ada. Argumen kedua adalah fungsi start yang akan menerima callback set dan me return fungsi stop. Fungsi start akan dijalankan ketika store mendapat subsriber pertamanya, dan stop akan dijalankan saat subscriber terakhir unsubscribe.
// this is stores.js import { readable } from 'svelte/store'; export const time = readable(new Date(), function start(set) { // called at subscribe const interval = setInterval(() => { set(new Date()); }, 1000); return function stop() { // called when unsubscribe clearInterval(interval); }; });
Sesudah itu kita bisa menggunakan komponen time di dalam App.svelte: <script> import { time } from './stores.js'; const formatter = new Intl.DateTimeFormat('en', { hour12: true, hour: 'numeric', minute: '2-digit', second: '2-digit' }); </script> <h1>The time is {formatter.format($time)}</h1>
Derived Stores
Kita bisa membuat store yang nilainya berdasarkan dari nilai satu atau lebih store dengan derived. Melanjutkan dari contoh sebelumnya, kita bisa membuat store yang akan menghitung waktu berapa lama halaman aplikasi sudah dijalankan:
Kita bisa men derive store dari berbagai input, dan secara eksplisit memberikan nilai daripada me return nya (biasanya digunakan untuk derive sesuatu secara asinkron). Cek API reference untuk informasi lebih lanjut. Contoh lengkap bisa dilihat di sini.
Custom Stores
Selama suatu object menjalankan method subscribe dengan benar, maka dia adalah store. Maka dari itu kita bisa dengan mudah membuat store custom dengan logika yang spesifik untuk domain tertentu.
Sebagai contoh store count dari contoh sebelumnya bisa menambakan method increment, decrement dan reset sehingga tidak perlu mengekspos set dan update pada saat penggunaan komponen:
function createCount() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; } Kemudian bisa digunakan di aplikasi utama seperti ini:
<script> import { count } from './stores.js'; </script> <h1>The count is {$count}</h1> <button on:click={count.increment}>+</button> <button on:click={count.decrement}>-</button> <button on:click={count.reset}>reset</button>
Stores Binding
Jika suatu store writable — mempunyai method set — kita bisa melakukan bind pada nilainya, seperti kita bisa melakukan bind pada state komponen lokal. Pada contoh berikut kita memiliki store writable name dan derived store greeting.
Maka mengubah nilai input sekarang akan meng update name dan semua dependensinya. Kita juga bisa melakukan assign nilai secara langsung pada store di dalam komponen. Tambahkan elemen <button> :
Every component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.
onMount
The one you'll use most frequently is onMount, which runs after the component is first rendered to the DOM. We briefly encountered it when we needed to interact with a <canvas> element after it had been rendered. We'll add an onMount handler that loads some data over the network:
<script> import { onMount } from 'svelte'; let photos = []; onMount(async () => { const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`); photos = await res.json(); }); </script>
It's recommended to put the fetch in onMount rather than at the top level of the <script> because of server-side rendering (SSR). With the exception of onDestroy, lifecycle functions don't run during SSR, which means we can avoid fetching data that should be loaded lazily once the component has been mounted in the DOM.
Lifecycle functions must be called while the component is initialising so that the callback is bound to the component instance — not (say) in a setTimeout.
If the onMount callback returns a function, that function will be called when the component is destroyed.
onDestroy
To run code when your component is destroyed, use onDestroy. For example, we can add a setInterval function when our component initialises, and clean it up when it's no longer relevant. Doing so prevents memory leaks. <script> import { onDestroy } from 'svelte'; let seconds = 0; const interval = setInterval(() => seconds += 1, 1000); onDestroy(() => clearInterval(interval)); </script>
While it's important to call lifecycle functions during the component's initialisation, it doesn't matter where you call them from. So if we wanted, we could abstract the interval logic into a helper function in util.js...
<script> import { onInterval } from './utils.js'; let seconds = 0; onInterval(() => seconds += 1, 1000); </script>
beforeUpdate and afterUpdate
The beforeUpdate function schedules work to happen immediately before the DOM has been 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. let div; let autoscroll; 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. See working example here.
Tick
The tick function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
When you invalidate component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
You can see that behaviour in this example. Select a range of text and hit the tab key. Because the <textarea> value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end. We can fix this by importing tick... ...and running it immediately before we set this.selectionStart and .selectionEnd at the end of handleKeydown:
<script> import { tick } from 'svelte'; let text = `Select some text and hit the tab key to toggle uppercase`; async function handleKeydown(event) { if (event.which !== 9) return; event.preventDefault(); const { selectionStart, selectionEnd, value } = this; const selection = value.slice(selectionStart, selectionEnd); const replacement = /[a-z]/.test(selection) ? selection.toUpperCase() : selection.toLowerCase(); text = ( value.slice( 0, selectionStart) + replacement + value.slice(selectionEnd)); await tick(); // update textarea value first // then put selection in place this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; } </script> <style>textarea { width: 100%;height: 200px; } </style> <textarea value={text} on:keydown={handleKeydown}></textarea>
Indonesia
Lifecycle
Setiap komponen mempunyai lifecycle yang dimulai ketika komponen itu dicreate, dan berakhir ketika komponen didestroy. Ada beberapa fungsi yang berguna untuk memungkinkan kita menjalankan program pada saat tertentu selama lifecycle.
onMount
onMount adalah fungsi yang paling sering digunakan, fungsi ini akan berjalan saat komponen pertama kali dirender ke dalam DOM. Kita sempat menggunakan onMount saat melakukan interaksi dengan elemen <canvas> sesudah dirender. Kita akan menambahkan handler onMount yang akan melakukan loading data melalui jaringan:
<script> import { onMount } from 'svelte'; let photos = []; onMount(async () => { const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`); photos = await res.json(); }); </script>
Alangkah baiknya jika kita meletakkan fetch di onMount dan bukan di baris atas <script> hal ini dikarenakan proses server-side rendering (SSR). Dengan perkecualian untuk onDestroy, fungsi lifecycle tidak berjalan saat SSR, maka kita bisa menghindari fetch data yang bisa diload belakangan kita komponen sudah termount pada DOM.
Fungsi lifecycle harus dipanggil saat komponen dalam proses pembentukan jadi callback nya akan terikat pada komponen itu — jangan (misalnya) dalam setTimeout.
Jika callback onMount mereturn suatu fungsi, fungsi tersebut akan dipanggil saat komponen di destroy.
onDestroy
Untuk menjalankan program saat komponen di destroy, gunakan onDestroy. Sebagai contoh, kita bisa menambakan fungsi setInterval ketika komponen dibentuk, dan membersihkan ketika interval sudah tidak lagi dibutuhkan. Hal ini untuk mencegah kehabisan memori. <script> import { onDestroy } from 'svelte'; let seconds = 0; const interval = setInterval(() => seconds += 1, 1000); onDestroy(() => clearInterval(interval)); </script>
Meskipun penting untuk memanggil fungsi lifecycle selama masa pembentukan komponen. Tapi tidak masalah kita memanggil dari mana. Jadi jika kita mau, kita bisa melakukan proses logika interval dalam fungsi helper di dalam util.js...
<script> import { onInterval } from './utils.js'; let seconds = 0; onInterval(() => seconds += 1, 1000); </script>
beforeUpdate and afterUpdate
Fungsi beforeUpdate menjadwalkan kerja program untuk terjadi segera sebelum DOM nya ter update. afterUpdate adalah kebalikannya, digunakan untuk menjalankan program, setelah DOM sudah tersinkronisasi dengan data dalam program. Bersama-sama, kedua fungsi ini berguna untuk melakukan hal-hal yang susah dilakukan dalam cara yang murni berhubungan dengan state, seperti mengupdate posisi scroll suatu elemen. let div; let autoscroll; beforeUpdate(() => { autoscroll = div && (div.offsetHeight + div.scrollTop) > (div.scrollHeight - 20); }); afterUpdate(() => { if (autoscroll) div.scrollTo(0, div.scrollHeight); });
Jangan lupa bahwa beforeUpdate akan dijalankan duluan sebelum komponen sudah ter mount, jadi kita harus melakukan pengecekan keberadaan div, sebelum mengecek properti nya. Contoh aplikasi yang sudah berjalan bisa dilihat di sini.
Tick
Fungsi tick tidak seperti fungsi lifecycle yang lainnya, dalam hal fungsi ini bisa dipanggil kapan saja, bukan hanya saat komponen pertama terbentuk. Fungsi ini akan mereturn promise yang akan cair saat semua perubahan state yang masih pending sudah diterapkan pada DOM (atau segera, jika tidak ada perubahan state yang pending).
Ketika terjadi invalidasi state komponen, perubahan DOM tidak dilakukan langsung. Melainkan menunggu beberapa perubahan kecil lain untuk melihat apabila ada beberapa perubahan yang bisa dilakukan bersamaan, termasuk perubahan di komponen lain. Hal ini dimaksudkan untuk menghindari pekerjaan tambahan dan juga membantui browser untuk bekerja lebih efektif.
Kita bisa melihat kelakukan itu di contoh ini. Pilih sekumpulan teks dan pencet tombol tab. Karena nilai <textarea> berubah, pilihan teks akan hilang dan kursor akan lompat ke bagian akhir, sangat mengganggu.. Kita bisa memperbaiki ini dengan menggunakan tick... dan langsung menjalankan secara langsung sebelum kita mengatur this.selectionStart dan this.selectionEnd di bagian akhir handleKeydown:
<script> import { tick } from 'svelte'; let text = `Select some text and hit the tab key to toggle uppercase`; async function handleKeydown(event) { if (event.which !== 9) return; event.preventDefault(); const { selectionStart, selectionEnd, value } = this; const selection = value.slice(selectionStart, selectionEnd); const replacement = /[a-z]/.test(selection) ? selection.toUpperCase() : selection.toLowerCase(); text = ( value.slice( 0, selectionStart) + replacement + value.slice(selectionEnd)); await tick(); // tick akan update textarea dulu // baru selection akan diset ulang this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; } </script> <style>textarea { width: 100%;height: 200px; } </style> <textarea value={text} on:keydown={handleKeydown}></textarea>