Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/content/meta/CheckboxRoot.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@
'type': 'string',
'required': false
},
{
'name': 'parent',
'description': '<p>Whether the checkbox controls a group of child checkboxes.</p>\n',
'type': 'boolean',
'required': false
},
{
'name': 'required',
'description': '<p>When <code>true</code>, indicates that the user must set the value before the owning form can be submitted.</p>\n',
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/Checkbox/Checkbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,13 @@ describe('given CheckboxGroup', () => {
describe('when clicking the checkbox', async () => {
let wrapper: VueWrapper<InstanceType<typeof CheckboxGroup>>
let checkboxes: DOMWrapper<HTMLButtonElement>[]
let parentCheckbox: DOMWrapper<HTMLButtonElement>

beforeEach(async () => {
wrapper = mount(CheckboxGroup)
checkboxes = wrapper.findAll('button')
checkboxes[0].trigger('click')
parentCheckbox = wrapper.find('#parent')
})

it('should render a visible indicator', async () => {
Expand Down Expand Up @@ -124,6 +126,26 @@ describe('given CheckboxGroup', () => {
expect(checkboxes[2].attributes('data-state')).toBe('unchecked')
})
})

describe('when clicking parent checkbox', async () => {
it('should has indeterminate state', async () => {
expect(parentCheckbox.attributes('data-state')).toBe('indeterminate')
})

it('should toggle all checkbox', async () => {
// toggle on
await parentCheckbox.trigger('click')
expect(checkboxes[0].attributes('data-state')).toBe('checked')
expect(checkboxes[1].attributes('data-state')).toBe('checked')
expect(checkboxes[2].attributes('data-state')).toBe('checked')

// toggle off
await parentCheckbox.trigger('click')
expect(checkboxes[0].attributes('data-state')).toBe('unchecked')
expect(checkboxes[1].attributes('data-state')).toBe('unchecked')
expect(checkboxes[2].attributes('data-state')).toBe('unchecked')
})
})
})
})

Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/Checkbox/CheckboxGroupRoot.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Ref } from 'vue'
import type { RovingFocusGroupProps } from '@/RovingFocus'
import type { AcceptableValue, FormFieldProps } from '@/shared/types'
import { useVModel } from '@vueuse/core'
import { computed, toRefs } from 'vue'
import { computed, ref, toRefs } from 'vue'
import { Primitive, usePrimitiveElement } from '@/Primitive'
import { createContext, useDirection, useFormControl } from '@/shared'

Expand All @@ -25,6 +25,7 @@ export type CheckboxGroupRootEmits<T = AcceptableValue> = {

interface CheckboxGroupRootContext {
modelValue: Ref<AcceptableValue[]>
childValues: Ref<AcceptableValue[]>
rovingFocus: Ref<boolean>
disabled: Ref<boolean>
}
Expand Down Expand Up @@ -53,12 +54,15 @@ const modelValue = useVModel(props, 'modelValue', emits, {
passive: (props.modelValue === undefined) as false,
}) as Ref<T[]>

const childValues = ref<T[]>([])

const rovingFocusProps = computed(() => {
return rovingFocus.value ? { loop: props.loop, dir: dir.value, orientation: props.orientation } : {}
})

provideCheckboxGroupRootContext({
modelValue,
childValues,
rovingFocus,
disabled,
})
Expand Down
43 changes: 36 additions & 7 deletions packages/core/src/Checkbox/CheckboxRoot.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface CheckboxRootProps extends PrimitiveProps, FormFieldProps {
modelValue?: boolean | 'indeterminate' | null
/** When `true`, prevents the user from interacting with the checkbox */
disabled?: boolean
/** Whether the checkbox controls a group of child checkboxes. */
parent?: boolean
/**
* The value given as data when submitted with a `name`.
* @defaultValue "on"
Expand Down Expand Up @@ -43,7 +45,7 @@ import { computed } from 'vue'
import { Primitive } from '@/Primitive'
import { RovingFocusItem } from '@/RovingFocus'
import { VisuallyHiddenInput } from '@/VisuallyHidden'
import { getState, isIndeterminate } from './utils'
import { getParentState, getState, isIndeterminate } from './utils'

defineOptions({
inheritAttrs: false,
Expand Down Expand Up @@ -78,7 +80,10 @@ const disabled = computed(() => checkboxGroupContext?.disabled.value || props.di

const checkboxState = computed<CheckedState>(() => {
if (!isNullish(checkboxGroupContext?.modelValue.value)) {
return isValueEqualOrExist(checkboxGroupContext.modelValue.value, props.value)
if (!props.parent) {
return isValueEqualOrExist(checkboxGroupContext.modelValue.value, props.value)
}
return getParentState(checkboxGroupContext.childValues.value, checkboxGroupContext.modelValue.value)
}
else {
return modelValue.value === 'indeterminate' ? 'indeterminate' : modelValue.value
Expand All @@ -87,13 +92,30 @@ const checkboxState = computed<CheckedState>(() => {

function handleClick() {
if (!isNullish(checkboxGroupContext?.modelValue.value)) {
const modelValueArray = [...(checkboxGroupContext.modelValue.value || [])]
if (isValueEqualOrExist(modelValueArray, props.value)) {
const index = modelValueArray.findIndex(i => isEqual(i, props.value))
modelValueArray.splice(index, 1)
let modelValueArray = [...(checkboxGroupContext.modelValue.value || [])]

if (props.parent) {
if (checkboxState.value === true) {
modelValueArray = modelValueArray.filter((value) => {
return !checkboxGroupContext.childValues.value.includes(value)
})
}
else {
checkboxGroupContext.childValues.value.forEach((value) => {
if (!modelValueArray.includes(value)) {
modelValueArray.push(value)
}
})
}
}
else {
modelValueArray.push(props.value)
if (isValueEqualOrExist(modelValueArray, props.value)) {
const index = modelValueArray.findIndex(i => isEqual(i, props.value))
modelValueArray.splice(index, 1)
}
else {
modelValueArray.push(props.value)
}
}
checkboxGroupContext.modelValue.value = modelValueArray
}
Expand All @@ -107,6 +129,13 @@ const ariaLabel = computed(() => props.id && currentElement.value
? (document.querySelector(`[for="${props.id}"]`) as HTMLLabelElement)?.innerText
: undefined)

// Track child value on checkboxGroupContext
if (checkboxGroupContext && !props.parent) {
if (!isValueEqualOrExist(checkboxGroupContext.childValues.value, props.value)) {
checkboxGroupContext.childValues.value = [...checkboxGroupContext.childValues.value, props.value]
}
}

provideCheckboxRootContext({
disabled,
state: checkboxState,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/Checkbox/story/CheckboxGroup.story.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const checkboxes = ref([items[1]])
</CheckboxRoot>
<label
:for="item.name"
class="select-none text-white"
class="select-none"
>
{{ item.name }}
</label>
Expand Down
147 changes: 147 additions & 0 deletions packages/core/src/Checkbox/story/CheckboxGroupNested.story.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { ref } from 'vue'
import { CheckboxGroupRoot, CheckboxIndicator, CheckboxRoot } from '..'

const fruits = ['Apple', 'Banana', 'Orange']
const vegetables = ['Tomato', 'Carrot', 'Onion']
const selected = ref(['Banana'])
</script>

<template>
<Story
title="Checkbox/Nested Group"
:layout="{ type: 'single', iframe: false }"
>
<Variant title="default">
<h1 class="font-medium mb-6">
What's your favorite food?
</h1>
<CheckboxGroupRoot
v-model="selected"
name="test"
class="flex flex-col gap-2.5"
>
<div class="flex flex-row gap-4 items-center [&>.checkbox]:hover:bg-neutral-100">
<CheckboxRoot
id="fruits"
class="shadow-blackA7 hover:bg-violet3 flex h-[25px] w-[25px] appearance-none items-center justify-center rounded-[4px] bg-white shadow-[0_2px_10px] outline-none focus-within:shadow-[0_0_0_2px_black]"
parent
>
<template #default="{ state }">
<CheckboxIndicator
class="bg-white h-full w-full rounded flex items-center justify-center"
>
<Icon
v-if="state === 'indeterminate'"
icon="radix-icons:divider-horizontal"
class="h-4 w-4 text-black"
/>
<Icon
v-else-if="state"
icon="radix-icons:check"
class="h-4 w-4 text-black"
/>
</CheckboxIndicator>
</template>
</CheckboxRoot>
<label
for="fruits"
class="select-none"
>
All fruits
</label>
</div>
<div
v-for="name in fruits"
:key="name"
class="flex flex-row gap-4 items-center [&>.checkbox]:hover:bg-neutral-100"
>
<CheckboxRoot
:id="name"
:value="name"
class="shadow-blackA7 hover:bg-violet3 flex h-[25px] w-[25px] appearance-none items-center justify-center rounded-[4px] bg-white shadow-[0_2px_10px] outline-none focus-within:shadow-[0_0_0_2px_black]"
>
<CheckboxIndicator
class="bg-white h-full w-full rounded flex items-center justify-center"
>
<Icon
icon="radix-icons:check"
class="h-4 w-4 text-black"
/>
</CheckboxIndicator>
</CheckboxRoot>
<label
:for="name"
class="select-none"
>
{{ name }}
</label>
</div>
</CheckboxGroupRoot>

<CheckboxGroupRoot
v-model="selected"
name="test"
class="flex flex-col gap-2.5 pt-8"
>
<div class="flex flex-row gap-4 items-center [&>.checkbox]:hover:bg-neutral-100">
<CheckboxRoot
id="fruits"
class="shadow-blackA7 hover:bg-violet3 flex h-[25px] w-[25px] appearance-none items-center justify-center rounded-[4px] bg-white shadow-[0_2px_10px] outline-none focus-within:shadow-[0_0_0_2px_black]"
parent
>
<template #default="{ state }">
<CheckboxIndicator
class="bg-white h-full w-full rounded flex items-center justify-center"
>
<Icon
v-if="state === 'indeterminate'"
icon="radix-icons:divider-horizontal"
class="h-4 w-4 text-black"
/>
<Icon
v-else-if="state"
icon="radix-icons:check"
class="h-4 w-4 text-black"
/>
</CheckboxIndicator>
</template>
</CheckboxRoot>
<label
for="vegetables"
class="select-none"
>
All vegetables
</label>
</div>
<div
v-for="name in vegetables"
:key="name"
class="flex flex-row gap-4 items-center [&>.checkbox]:hover:bg-neutral-100"
>
<CheckboxRoot
:id="name"
:value="name"
class="shadow-blackA7 hover:bg-violet3 flex h-[25px] w-[25px] appearance-none items-center justify-center rounded-[4px] bg-white shadow-[0_2px_10px] outline-none focus-within:shadow-[0_0_0_2px_black]"
>
<CheckboxIndicator
class="bg-white h-full w-full rounded flex items-center justify-center"
>
<Icon
icon="radix-icons:check"
class="h-4 w-4 text-black"
/>
</CheckboxIndicator>
</CheckboxRoot>
<label
:for="name"
class="select-none"
>
{{ name }}
</label>
</div>
</CheckboxGroupRoot>
</Variant>
</Story>
</template>
23 changes: 23 additions & 0 deletions packages/core/src/Checkbox/story/_CheckboxGroup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,28 @@ const items = [{ name: 'jack' }, { name: 'john' }, { name: 'mike' }]
{{ item.name }}
</label>
</div>
<CheckboxRoot
id="parent"
aria-label="parent"
parent
>
<template #default="{ state }">
<CheckboxIndicator
data-testid="test-indicator"
class="bg-white h-full w-full rounded flex items-center justify-center"
>
<Icon
v-if="state === 'indeterminate'"
icon="radix-icons:divider-horizontal"
class="h-4 w-4 text-black"
/>
<Icon
v-else-if="state"
icon="radix-icons:check"
class="h-4 w-4 text-black"
/>
</CheckboxIndicator>
</template>
</CheckboxRoot>
</CheckboxGroupRoot>
</template>
22 changes: 22 additions & 0 deletions packages/core/src/Checkbox/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,25 @@ export function isIndeterminate(checked?: CheckedState): checked is 'indetermina
export function getState(checked: CheckedState) {
return isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked'
}

export function getParentState<T>(childValues: T[], selectedValues: T[]): boolean | 'indeterminate' {
const selectedSet = new Set(selectedValues)

let hasSome = false
let hasAll = true

for (const value of childValues) {
if (selectedSet.has(value)) {
hasSome = true
}
else {
hasAll = false
}
}

if (hasAll)
return true
if (hasSome)
return 'indeterminate'
return false
}