add checkbox component
This commit is contained in:
91
src/lib/Checkbox.svelte
Normal file
91
src/lib/Checkbox.svelte
Normal file
@@ -0,0 +1,91 @@
|
||||
<script lang="ts" module>
|
||||
export type CheckboxState = 'indeterminate' | boolean;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import { validate } from '@svelte-toolkit/validate';
|
||||
|
||||
interface Props {
|
||||
name?: string;
|
||||
required?: boolean;
|
||||
value?: CheckboxState;
|
||||
color?: 'default' | 'contrast';
|
||||
children?: Snippet;
|
||||
onchange: (value: CheckboxState) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
name,
|
||||
required = false,
|
||||
value = $bindable(false),
|
||||
color = 'contrast',
|
||||
children,
|
||||
onchange
|
||||
}: Props = $props();
|
||||
|
||||
let id = $derived.by(() => {
|
||||
return `checkbox-${name || Math.random().toString(36).substring(2, 15)}`;
|
||||
});
|
||||
|
||||
let valid = $state(true);
|
||||
</script>
|
||||
|
||||
<div class="flex items-center">
|
||||
<input
|
||||
type="hidden"
|
||||
{name}
|
||||
value={value.toString()}
|
||||
use:validate={{
|
||||
valfunc: () => {
|
||||
if (required && value !== true) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}}
|
||||
onvalidate={(e) => {
|
||||
valid = e.detail.valid;
|
||||
}}
|
||||
/>
|
||||
|
||||
<button
|
||||
{id}
|
||||
class={[
|
||||
'text-text flex size-7 appearance-none items-center',
|
||||
'justify-center rounded-lg shadow transition-all hover:opacity-75',
|
||||
color === 'default' && 'bg-white',
|
||||
color === 'contrast' && 'border-text/40 border bg-white',
|
||||
!valid && 'border-accent-400 border'
|
||||
]}
|
||||
onclick={() => {
|
||||
if (value === false || value === 'indeterminate') {
|
||||
value = true;
|
||||
} else {
|
||||
value = false;
|
||||
}
|
||||
onchange(value);
|
||||
}}
|
||||
>
|
||||
{#if value === 'indeterminate'}
|
||||
<span class="material-symbols-outlined">remove</span>
|
||||
{:else if value === true}
|
||||
<span class="material-symbols-outlined">check</span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
{#if children}
|
||||
<label
|
||||
class={[
|
||||
'text-text pl-4 font-medium transition-colors select-none',
|
||||
!valid && 'text-accent-400'
|
||||
]}
|
||||
for={id}
|
||||
>
|
||||
{@render children()}
|
||||
{#if required}
|
||||
<span class="text-accent-400">*</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/if}
|
||||
</div>
|
||||
Reference in New Issue
Block a user