|
| 1 | +<!-- |
| 2 | + (c) 2023-2025, Center for Computational Thinking and Design at Aarhus University and contributors |
| 3 | + |
| 4 | + SPDX-License-Identifier: MIT |
| 5 | + --> |
| 6 | + |
| 7 | +<script lang="ts"> |
| 8 | + import { createEventDispatcher } from 'svelte'; |
| 9 | + export let checked: boolean = false; |
| 10 | + export let disabled: boolean = false; |
| 11 | + export let label: string = ''; |
| 12 | + export let size: 'sm' | 'md' | 'lg' = 'md'; |
| 13 | + const dispatch = createEventDispatcher(); |
| 14 | +
|
| 15 | + function toggle() { |
| 16 | + if (disabled) return; |
| 17 | + checked = !checked; |
| 18 | + dispatch('change', { checked }); |
| 19 | + } |
| 20 | +
|
| 21 | + // Size classes |
| 22 | + const sizeMap = { |
| 23 | + sm: { btn: 'w-8 h-5', knob: 'w-4 h-4', translate: '0.9rem' }, |
| 24 | + md: { btn: 'w-12 h-7', knob: 'w-6 h-6', translate: '1.25rem' }, |
| 25 | + lg: { btn: 'w-16 h-9', knob: 'w-8 h-8', translate: '1.75rem' }, |
| 26 | + }; |
| 27 | + $: btnSize = sizeMap[size]?.btn || sizeMap.md.btn; |
| 28 | + $: knobSize = sizeMap[size]?.knob || sizeMap.md.knob; |
| 29 | + $: knobTranslate = sizeMap[size]?.translate || sizeMap.md.translate; |
| 30 | +</script> |
| 31 | + |
| 32 | +<div class="flex items-center space-x-3 select-none"> |
| 33 | + {#if label} |
| 34 | + <label class="text-base cursor-pointer" on:click={toggle}>{label}</label> |
| 35 | + {/if} |
| 36 | + <button |
| 37 | + type="button" |
| 38 | + class="relative focus:outline-none transition-colors duration-200 rounded-full border-2 border-gray-300 bg-gray-200 flex items-center {btnSize} {disabled |
| 39 | + ? 'opacity-50 cursor-not-allowed' |
| 40 | + : 'cursor-pointer'}" |
| 41 | + aria-checked={checked} |
| 42 | + on:click|stopPropagation |
| 43 | + aria-label={label} |
| 44 | + {disabled} |
| 45 | + on:click={toggle} |
| 46 | + role="switch" |
| 47 | + tabindex="0"> |
| 48 | + <span |
| 49 | + class="absolute left-0 top-0 w-full h-full rounded-full transition-colors duration-200" |
| 50 | + class:bg-primary={checked && !disabled} |
| 51 | + class:bg-gray-200={!checked || disabled} |
| 52 | + class:border-primary={checked && !disabled} |
| 53 | + class:border-gray-300={!checked || disabled}></span> |
| 54 | + <span |
| 55 | + class="inline-block bg-white rounded-full shadow transform transition-transform duration-200 z-10 border border-gray-300 {knobSize}" |
| 56 | + style="transform: translateX({checked ? knobTranslate : '0rem'});"></span> |
| 57 | + </button> |
| 58 | +</div> |
0 commit comments