# CheckBox Component

A versatile checkbox component that supports various states including indeterminate, with comprehensive event handling and accessibility features. Perfect for single selections, toggle options, and form controls.

## Features

- **Multiple States**: Checked, unchecked, and indeterminate states
- **Event Handling**: Click, change, focus, and blur event support
- **Accessibility**: Proper ARIA attributes and keyboard navigation
- **Auto Focus**: Optional automatic focus capability
- **Custom Styling**: Flexible styling and compact mode
- **Read-only & Disabled**: Support for non-interactive states
- **Programmatic Control**: Focus management and value control

## Basic Usage

```svelte
<script>
import CheckBox from '@ticatec/uniface-element/CheckBox';

let isChecked = false;

const handleChange = (value) => {
  console.log('Checkbox changed:', value);
  isChecked = value;
};
</script>

<CheckBox 
  label="Accept terms and conditions"
  bind:value={isChecked}
  onchange={handleChange}
/>
```

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `label` | `string \| null` | `null` | Text label displayed next to checkbox |
| `readonly` | `boolean` | `false` | Whether the checkbox is read-only |
| `disabled` | `boolean` | `false` | Whether the checkbox is disabled |
| `value` | `boolean` | `false` | Checked state of the checkbox |
| `indeterminate` | `boolean` | `false` | Indeterminate state (partial selection) |
| `style` | `string` | `''` | Custom CSS styles |
| `compact` | `boolean` | `false` | Compact display mode |
| `onclick` | `((event: MouseEvent) => void) \| null` | `null` | Click event handler |
| `onchange` | `OnChangeHandler<boolean>` | - | Value change event handler |
| `onfocus` | `((event: FocusEvent) => void) \| null` | `null` | Focus event handler |
| `onblur` | `((event: FocusEvent) => void) \| null` | `null` | Blur event handler |
| `autoFocus` | `boolean` | `false` | Whether to auto-focus on mount |

## Methods

| Method | Description |
|--------|-------------|
| `setFocus()` | Programmatically focus the checkbox |

## Basic Examples

### Simple Checkbox

```svelte
<script>
let agreed = false;
</script>

<CheckBox 
  label="I agree to the terms"
  bind:value={agreed}
/>

<p>Status: {agreed ? 'Agreed' : 'Not agreed'}</p>
```

### With Change Handler

```svelte
<script>
let notifications = true;

const handleNotificationChange = (value) => {
  console.log('Notifications:', value ? 'enabled' : 'disabled');
  notifications = value;
};
</script>

<CheckBox 
  label="Enable notifications"
  value={notifications}
  onChange={handleNotificationChange}
/>
```

### Indeterminate State

```svelte
<script>
let parentChecked = false;
let childItems = [
  { id: 1, name: 'Item 1', checked: true },
  { id: 2, name: 'Item 2', checked: false },
  { id: 3, name: 'Item 3', checked: true }
];

$: {
  const checkedCount = childItems.filter(item => item.checked).length;
  parentChecked = checkedCount === childItems.length;
  parentIndeterminate = checkedCount > 0 && checkedCount < childItems.length;
}

const handleParentChange = (value) => {
  childItems = childItems.map(item => ({ ...item, checked: value }));
};

const handleChildChange = (id) => (value) => {
  childItems = childItems.map(item => 
    item.id === id ? { ...item, checked: value } : item
  );
};
</script>

<CheckBox 
  label="Select All"
  value={parentChecked}
  indeterminate={parentIndeterminate}
  onChange={handleParentChange}
/>

{#each childItems as item}
  <div style="margin-left: 20px;">
    <CheckBox 
      label={item.name}
      value={item.checked}
      onChange={handleChildChange(item.id)}
    />
  </div>
{/each}
```

## Event Handling

```svelte
<script>
let value = false;
let focusCount = 0;
let clickCount = 0;

const handleChange = (newValue) => {
  console.log('Value changed to:', newValue);
  value = newValue;
};

const handleClick = (event) => {
  clickCount++;
  console.log('Checkbox clicked', clickCount, 'times');
};

const handleFocus = (event) => {
  focusCount++;
  console.log('Checkbox focused');
};

const handleBlur = (event) => {
  console.log('Checkbox blurred');
};
</script>

<CheckBox 
  label="Interactive checkbox"
  {value}
  onchange={handleChange}
  onclick={handleClick}
  onfocus={handleFocus}
  onblur={handleBlur}
/>

<div>
  <p>Current value: {value}</p>
  <p>Focus count: {focusCount}</p>
  <p>Click count: {clickCount}</p>
</div>
```

## States and Modes

### Disabled State

```svelte
<CheckBox 
  label="Disabled unchecked"
  value={false}
  disabled={true}
/>

<CheckBox 
  label="Disabled checked"
  value={true}
  disabled={true}
/>
```

### Read-only State

```svelte
<CheckBox 
  label="Read-only unchecked"
  value={false}
  readonly={true}
/>

<CheckBox 
  label="Read-only checked"
  value={true}
  readonly={true}
/>
```

### Compact Mode

```svelte
<div style="display: flex; gap: 16px; align-items: center;">
  <CheckBox label="Normal" value={true} />
  <CheckBox label="Compact" value={true} compact={true} />
</div>
```

### Auto Focus

```svelte
<CheckBox 
  label="Auto-focused checkbox"
  autoFocus={true}
/>
```

## Advanced Examples

### Form Integration

```svelte
<script>
let formData = {
  newsletter: false,
  terms: false,
  privacy: false
};

$: canSubmit = formData.terms && formData.privacy;

const handleSubmit = () => {
  if (canSubmit) {
    console.log('Form submitted:', formData);
  }
};

const updateField = (field) => (value) => {
  formData = { ...formData, [field]: value };
};
</script>

<form on:submit|preventDefault={handleSubmit}>
  <div class="form-section">
    <CheckBox 
      label="Subscribe to newsletter (optional)"
      value={formData.newsletter}
      onChange={updateField('newsletter')}
    />
  </div>
  
  <div class="form-section">
    <CheckBox 
      label="I accept the terms of service *"
      value={formData.terms}
      onChange={updateField('terms')}
    />
  </div>
  
  <div class="form-section">
    <CheckBox 
      label="I accept the privacy policy *"
      value={formData.privacy}
      onChange={updateField('privacy')}
    />
  </div>
  
  <button type="submit" disabled={!canSubmit}>
    Submit
  </button>
</form>

<style>
  .form-section {
    margin: 16px 0;
  }
</style>
```

### Settings Panel

```svelte
<script>
let settings = {
  darkMode: false,
  notifications: true,
  autoSave: true,
  soundEffects: false
};

const updateSetting = (key) => (value) => {
  settings = { ...settings, [key]: value };
  localStorage.setItem('app-settings', JSON.stringify(settings));
};

// Load settings on mount
import { onMount } from 'svelte';

onMount(() => {
  const saved = localStorage.getItem('app-settings');
  if (saved) {
    settings = { ...settings, ...JSON.parse(saved) };
  }
});
</script>

<div class="settings-panel">
  <h3>Application Settings</h3>
  
  <div class="setting-group">
    <h4>Appearance</h4>
    <CheckBox 
      label="Dark mode"
      value={settings.darkMode}
      onChange={updateSetting('darkMode')}
    />
  </div>
  
  <div class="setting-group">
    <h4>Notifications</h4>
    <CheckBox 
      label="Enable notifications"
      value={settings.notifications}
      onChange={updateSetting('notifications')}
    />
  </div>
  
  <div class="setting-group">
    <h4>Editor</h4>
    <CheckBox 
      label="Auto-save documents"
      value={settings.autoSave}
      onChange={updateSetting('autoSave')}
    />
  </div>
  
  <div class="setting-group">
    <h4>Audio</h4>
    <CheckBox 
      label="Sound effects"
      value={settings.soundEffects}
      onChange={updateSetting('soundEffects')}
    />
  </div>
</div>

<style>
  .settings-panel {
    max-width: 400px;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 8px;
  }
  
  .setting-group {
    margin: 20px 0;
  }
  
  .setting-group h4 {
    margin: 0 0 12px 0;
    color: #666;
    font-size: 14px;
    text-transform: uppercase;
  }
</style>
```

### Todo List with Select All

```svelte
<script>
let todos = [
  { id: 1, text: 'Buy groceries', completed: false },
  { id: 2, text: 'Walk the dog', completed: true },
  { id: 3, text: 'Read a book', completed: false },
  { id: 4, text: 'Call mom', completed: true }
];

$: completedCount = todos.filter(todo => todo.completed).length;
$: allCompleted = completedCount === todos.length;
$: someCompleted = completedCount > 0 && completedCount < todos.length;

const toggleAll = (value) => {
  todos = todos.map(todo => ({ ...todo, completed: value }));
};

const toggleTodo = (id) => (completed) => {
  todos = todos.map(todo => 
    todo.id === id ? { ...todo, completed } : todo
  );
};
</script>

<div class="todo-list">
  <h3>Todo List</h3>
  
  <CheckBox 
    label={`Select All (${completedCount}/${todos.length})`}
    value={allCompleted}
    indeterminate={someCompleted}
    onChange={toggleAll}
    style="border-bottom: 1px solid #ddd; padding-bottom: 12px; margin-bottom: 12px;"
  />
  
  {#each todos as todo}
    <div class="todo-item" class:completed={todo.completed}>
      <CheckBox 
        label={todo.text}
        value={todo.completed}
        onChange={toggleTodo(todo.id)}
      />
    </div>
  {/each}
  
  <div class="todo-summary">
    {completedCount} of {todos.length} completed
  </div>
</div>

<style>
  .todo-list {
    max-width: 400px;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 16px;
  }
  
  .todo-item {
    margin: 8px 0;
    transition: opacity 0.2s;
  }
  
  .todo-item.completed {
    opacity: 0.6;
  }
  
  .todo-summary {
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #ddd;
    font-size: 14px;
    color: #666;
    text-align: center;
  }
</style>
```

## Programmatic Control

```svelte
<script>
let checkbox;
let value = false;

const focusCheckbox = () => {
  checkbox?.setFocus();
};

const toggleValue = () => {
  value = !value;
};
</script>

<div class="controls">
  <button on:click={focusCheckbox}>Focus Checkbox</button>
  <button on:click={toggleValue}>Toggle Value</button>
</div>

<CheckBox 
  bind:this={checkbox}
  label="Programmatically controlled"
  {value}
  onChange={(v) => value = v}
/>

<style>
  .controls {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
  }
</style>
```

## Custom Styling

```svelte
<CheckBox 
  label="Custom styled checkbox"
  value={true}
  style="
    padding: 12px;
    background: #f0f8ff;
    border: 2px solid #007acc;
    border-radius: 8px;
    font-weight: 500;
  "
/>
```

## Accessibility

The CheckBox component includes:

- Proper semantic `input[type="checkbox"]` element
- Associated label for screen readers
- Keyboard navigation support (Tab, Space)
- Focus and blur event handling
- Disabled state management
- ARIA attributes for indeterminate state

### Best Practices

```svelte
<!-- Good: Clear, descriptive labels -->
<CheckBox label="Enable two-factor authentication" />

<!-- Good: Group related checkboxes -->
<fieldset>
  <legend>Notification Preferences</legend>
  <CheckBox label="Email notifications" />
  <CheckBox label="SMS notifications" />
  <CheckBox label="Push notifications" />
</fieldset>

<!-- Good: Indicate required fields -->
<CheckBox label="I agree to the terms of service *" />
```

## Browser Support

Works in all modern browsers that support:
- ES6+ JavaScript
- Modern DOM APIs
- CSS custom properties
- HTML5 form elements

## Performance Considerations

- Efficient event handling with proper cleanup
- Minimal re-renders with reactive updates
- Lightweight DOM structure
- Optimized focus management