<script>
import { animateView, spring } from "motion"
import { flushSync } from "svelte"
let isOn = $state(false)
let handle
function toggle() {
animateView(
() => {
isOn = !isOn
// Apply the state change to the DOM before the browser takes
// the new snapshot.
flushSync()
},
{ type: spring, bounce: 0.3, visualDuration: 0.3 }
).add(handle)
}
</script>
<button
class="toggle-container"
class:on={isOn}
aria-pressed={isOn}
aria-label="Toggle"
onclick={toggle}
>
<div class="toggle-handle" bind:this={handle}></div>
</button>
<style>
.toggle-container {
width: 100px;
height: 50px;
background-color: var(--hue-3-transparent);
border-radius: 50px;
cursor: pointer;
display: flex;
padding: 10px;
border: none;
justify-content: flex-start;
box-sizing: content-box;
}
.toggle-container.on {
justify-content: flex-end;
}
.toggle-handle {
width: 50px;
height: 50px;
background-color: var(--hue-3);
border-radius: 50%;
}
</style>