-
Notifications
You must be signed in to change notification settings - Fork 32
feat(GridForm, ConnectedForm): Add nested checkboxes #3168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 11 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
53167ab
wip
aresnik11 fff7888
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 cef1cbf
working
aresnik11 3a53551
update types
aresnik11 b1d05a8
add aria-checked
aresnik11 05c00fb
update stories
aresnik11 ec5e503
fix connectednestedcheckbox
aresnik11 9562d55
dont use children as prop name
aresnik11 6dbaf28
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 f8dbe30
add back in nested examples
aresnik11 309c8a3
fix errors
aresnik11 7d5ddfa
PR feedback
aresnik11 8f9a058
DRY up code
aresnik11 a34b0b5
first stab at tests
aresnik11 641aeb2
it works in gridform
aresnik11 86152dc
clean up logs and comments
aresnik11 5108c8c
fix defaultValue type issue
aresnik11 f67e05d
types refactor
aresnik11 fea9287
gridform default value
aresnik11 e2e3cc6
connectedform default value
aresnik11 8c65ca0
update connectedform
aresnik11 d6b147e
add passing tests
aresnik11 5694439
clean up tests
aresnik11 a562cc1
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 82d2598
PR feedback
aresnik11 6208a48
Merge branch 'ajr-nested-checkboxes' of github.com:Codecademy/gamut i…
aresnik11 9a809ff
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 b55a426
improvements
aresnik11 05f8fab
Merge branch 'ajr-nested-checkboxes' of github.com:Codecademy/gamut i…
aresnik11 18bc8fd
update gridform spacing
aresnik11 4a31dec
update spacing logic
aresnik11 90cb56a
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 00e475b
Merge branch 'main' into ajr-nested-checkboxes
aresnik11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
265 changes: 265 additions & 0 deletions
265
packages/gamut/src/ConnectedForm/ConnectedInputs/ConnectedNestedCheckboxes.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,265 @@ | ||
| import * as React from 'react'; | ||
| import { useCallback, useMemo } from 'react'; | ||
| import { Controller } from 'react-hook-form'; | ||
|
|
||
| import { Box, Checkbox, CheckboxLabelUnion } from '../..'; | ||
| import { useField } from '..'; | ||
| import { | ||
| ConnectedNestedCheckboxesProps, | ||
| MinimalCheckboxProps, | ||
| NestedConnectedCheckboxOption, | ||
| } from './types'; | ||
|
|
||
| type FlatCheckboxState = MinimalCheckboxProps & | ||
| CheckboxLabelUnion & { | ||
| level: number; | ||
| parentValue?: string; | ||
| options: string[]; | ||
| }; | ||
|
|
||
| export const ConnectedNestedCheckboxes: React.FC< | ||
| ConnectedNestedCheckboxesProps | ||
| > = ({ name, options, disabled, onUpdate, spacing }) => { | ||
| const { isDisabled, control, validation, isRequired } = useField({ | ||
| name, | ||
| disabled, | ||
| }); | ||
|
|
||
| // Flatten the nested structure for easier state management | ||
| const flattenOptions = useCallback( | ||
| ( | ||
| opts: NestedConnectedCheckboxOption[], | ||
| level = 0, | ||
| parentValue?: string | ||
| ) => { | ||
| const result: FlatCheckboxState[] = []; | ||
|
|
||
| opts.forEach((option) => { | ||
| // Ensure value is a string | ||
| const optionValue = String(option.value); | ||
| const options = option.options | ||
| ? option.options.map((child) => String(child.value)) | ||
| : []; | ||
|
|
||
| result.push({ | ||
| ...option, | ||
| spacing, | ||
| value: optionValue, | ||
| level, | ||
| parentValue, | ||
| options, | ||
| }); | ||
|
|
||
| if (option.options) { | ||
| result.push( | ||
| ...flattenOptions(option.options, level + 1, optionValue) | ||
| ); | ||
| } | ||
| }); | ||
|
|
||
| return result; | ||
| }, | ||
| [spacing] | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| const flatOptions = useMemo( | ||
| () => flattenOptions(options), | ||
| [options, flattenOptions] | ||
| ); | ||
|
|
||
| // Helper function to get all descendants of a given option | ||
| const getAllDescendants = useCallback( | ||
| (parentValue: string) => { | ||
| const descendants: string[] = []; | ||
|
|
||
| const collectDescendants = (currentParentValue: string) => { | ||
| flatOptions.forEach((option) => { | ||
| if (option.parentValue === currentParentValue) { | ||
| descendants.push(String(option.value)); | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // Recursively collect descendants of this option | ||
| collectDescendants(String(option.value)); | ||
| } | ||
| }); | ||
| }; | ||
|
|
||
| collectDescendants(parentValue); | ||
| return descendants; | ||
| }, | ||
| [flatOptions] | ||
| ); | ||
|
|
||
| // Calculate checkbox states based on selected values | ||
| const calculateStates = useCallback( | ||
| (selectedValues: string[]) => { | ||
| const states = new Map<string, FlatCheckboxState>(); | ||
|
|
||
| // Initialize all states | ||
| flatOptions.forEach((option) => { | ||
| states.set(String(option.value), { | ||
| ...option, | ||
| checked: selectedValues.includes(String(option.value)), | ||
| }); | ||
| }); | ||
|
|
||
| // Calculate parent states based on all descendants (infinite levels) | ||
| flatOptions.forEach((option) => { | ||
| if (option.options.length > 0) { | ||
| const allDescendants = getAllDescendants(String(option.value)); | ||
| const checkedDescendants = allDescendants.filter((descendantValue) => | ||
| selectedValues.includes(descendantValue) | ||
| ); | ||
|
|
||
| const state = states.get(String(option.value))!; | ||
| if (checkedDescendants.length === 0) { | ||
| state.checked = false; | ||
| state.indeterminate = false; | ||
| } else if (checkedDescendants.length === allDescendants.length) { | ||
| state.checked = true; | ||
| } else { | ||
| state.checked = false; | ||
| state.indeterminate = true; | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| return states; | ||
| }, | ||
| [flatOptions, getAllDescendants] | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| const handleCheckboxChange = useCallback( | ||
| ( | ||
| currentValue: string, | ||
| isChecked: boolean, | ||
| selectedValues: string[], | ||
| onChange: (values: string[]) => void | ||
| ) => { | ||
| const option = flatOptions.find((opt) => opt.value === currentValue); | ||
| if (!option) return; | ||
|
|
||
| let newSelectedValues = [...selectedValues]; | ||
|
|
||
| if (option.options.length > 0) { | ||
| // Parent checkbox - toggle all descendants (infinite levels) | ||
| const allDescendants = getAllDescendants(currentValue); | ||
|
|
||
| if (isChecked) { | ||
| // Add all descendants that aren't already selected | ||
| allDescendants.forEach((descendantValue) => { | ||
| if (!newSelectedValues.includes(descendantValue)) { | ||
| newSelectedValues.push(descendantValue); | ||
| } | ||
| }); | ||
| } else { | ||
| // Remove all descendants | ||
| newSelectedValues = newSelectedValues.filter( | ||
| (value) => !allDescendants.includes(value) | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Handle the current checkbox itself (for leaf nodes or when toggling individual items) | ||
| if (isChecked) { | ||
| if (!newSelectedValues.includes(currentValue)) { | ||
| newSelectedValues.push(currentValue); | ||
| } | ||
| } else { | ||
| newSelectedValues = newSelectedValues.filter( | ||
| (value) => value !== currentValue | ||
| ); | ||
| } | ||
|
|
||
| onChange(newSelectedValues); | ||
| onUpdate?.(newSelectedValues); | ||
| }, | ||
| [flatOptions, onUpdate, getAllDescendants] | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| const renderCheckbox = useCallback( | ||
| ( | ||
| option: FlatCheckboxState, | ||
| selectedValues: string[], | ||
| onChange: (values: string[]) => void, | ||
| onBlur: () => void, | ||
| ref: React.RefCallback<HTMLInputElement> | ||
| ) => { | ||
| const states = calculateStates(selectedValues); | ||
| const state = states.get(String(option.value))!; | ||
| const checkboxId = `${name}-${option.value}`; | ||
|
|
||
| let checkedProps = {}; | ||
| if (state.checked) { | ||
| checkedProps = { | ||
| checked: true, | ||
| 'aria-checked': true, | ||
| }; | ||
| } else if (state.indeterminate) { | ||
| checkedProps = { | ||
| indeterminate: true, | ||
| checked: false, | ||
| 'aria-checked': 'mixed', | ||
| }; | ||
| } else { | ||
| checkedProps = { | ||
| checked: false, | ||
| 'aria-checked': false, | ||
| }; | ||
| } | ||
|
|
||
| return ( | ||
| <Box | ||
| as="li" | ||
| key={String(option.value)} | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| listStyle="none" | ||
| ml={(option.level * 24) as any} | ||
| > | ||
| <Checkbox | ||
| aria-label={ | ||
| state['aria-label'] === undefined | ||
| ? typeof state.label === 'string' | ||
| ? state.label | ||
| : 'checkbox' | ||
| : state['aria-label'] | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| aria-required={isRequired} | ||
| disabled={isDisabled || state.disabled} | ||
| htmlFor={checkboxId} | ||
| id={checkboxId} | ||
| label={state.label} | ||
| multiline={state.multiline} | ||
| name={`${name}-${option.value}`} | ||
| spacing={state.spacing} | ||
| onBlur={onBlur} | ||
| onChange={(event) => { | ||
| handleCheckboxChange( | ||
| String(option.value), | ||
| event.target.checked, | ||
| selectedValues, | ||
| onChange | ||
| ); | ||
| }} | ||
| {...checkedProps} | ||
| {...ref} | ||
| /> | ||
| </Box> | ||
| ); | ||
| }, | ||
| [calculateStates, name, isRequired, isDisabled, handleCheckboxChange] | ||
| ); | ||
|
|
||
| return ( | ||
| <Controller | ||
| control={control} | ||
| defaultValue={[]} | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| name={name} | ||
| render={({ field: { value, onChange, onBlur, ref } }) => ( | ||
| <Box as="ul" m={0} p={0}> | ||
| {flatOptions.map((option) => | ||
| renderCheckbox(option, value || [], onChange, onBlur, ref) | ||
aresnik11 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| )} | ||
| </Box> | ||
| )} | ||
| rules={validation} | ||
| /> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.