Created
May 31, 2022 12:19
-
-
Save julianrubisch/e5a35b2983b0a8c08e052c055ecc4c9f to your computer and use it in GitHub Desktop.
This file contains 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
import { Controller } from '@hotwired/stimulus' | |
export default class extends Controller { | |
connect () { | |
this.element.addEventListener('change', this.handleChange.bind(this)) | |
} | |
handleChange (event) { | |
this.traverseDown(event.target, event.target.checked) | |
} | |
traverseDown (element, checked) { | |
let rootElement | |
// if a <summary> is closer than a <details>, we're in a category summary and need to toggle all children | |
if (element.closest('details').contains(element.closest('summary'))) { | |
rootElement = element.closest('details') | |
} | |
if (rootElement) { | |
for (const checkbox of rootElement.querySelectorAll( | |
':scope > :not(summary) input[type=checkbox]' | |
)) { | |
checkbox.checked = checked | |
checkbox.indeterminate = falsest | |
} | |
} | |
// else we're in a leaf | |
this.traverseUp(element) | |
} | |
traverseUp (element) { | |
const closestDetails = element.closest('details') | |
const childCheckboxes = [ | |
...closestDetails.querySelectorAll( | |
':scope > :not(summary) input[type=checkbox]' | |
) | |
] | |
const rootCheckbox = closestDetails.querySelector( | |
':scope > summary input[type=checkbox]' | |
) | |
if (childCheckboxes.every(element => element.checked)) { | |
rootCheckbox.checked = true | |
rootCheckbox.indeterminate = false | |
} else if (childCheckboxes.every(element => !element.checked)) { | |
rootCheckbox.checked = false | |
rootCheckbox.indeterminate = false | |
} else { | |
rootCheckbox.checked = false | |
rootCheckbox.indeterminate = true | |
} | |
const rootDetails = | |
element.tagName === 'DETAILS' | |
? element.parentElement.closest('details') | |
: element.closest('details') | |
if (rootDetails && rootDetails != element) this.traverseUp(rootDetails) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment