This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for System Design on BFE.dev
20. Implement nested checkboxes

To implement nested checkboxes with the above functionalities, we can follow these steps:

  1. Structure the HTML elements for the checkboxes. Each parent checkbox should have a unique ID, and each child checkbox should have a data attribute that indicates its parent checkbox.
  2. Use JavaScript to add event listeners to the parent and child checkboxes.
  3. When a parent checkbox is clicked, iterate over all its child checkboxes and set their checked property to match the parent checkbox.
  4. When a child checkbox is clicked, check its parent checkbox to see the state of all its siblings. If they are all checked, set the parent checkbox to checked. If some are checked and some are unchecked, set the parent checkbox to indeterminate. If none are checked, set the parent checkbox to unchecked.

Here's an example implementation in JavaScript:

<ul>
  <li>
    <label>
      <input type="checkbox" id="parent1"> Parent 1
    </label>
    <ul>
      <li>
        <label>
          <input type="checkbox" data-parent="parent1"> Child 1
        </label>
      </li>
      <li>
        <label>
          <input type="checkbox" data-parent="parent1"> Child 2
        </label>
      </li>
    </ul>
  </li>
  <li>
    <label>
      <input type="checkbox" id="parent2"> Parent 2
    </label>
    <ul>
      <li>
        <label>
          <input type="checkbox" data-parent="parent2"> Child 3
        </label>
      </li>
      <li>
        <label>
          <input type="checkbox" data-parent="parent2"> Child 4
        </label>
      </li>
    </ul>
  </li>
</ul>
const parents = document.querySelectorAll('input[type="checkbox"]');
const children = document.querySelectorAll('input[data-parent]');

parents.forEach(parent => {
  parent.addEventListener('click', () => {
    children.forEach(child => {
      if (child.getAttribute('data-parent') === parent.getAttribute('id')) {
        child.checked = parent.checked;
      }
    });
  });
});

children.forEach(child => {
  child.addEventListener('click', () => {
    const parent = document.getElementById(child.getAttribute('data-parent'));
    const siblings = document.querySelectorAll(`[data-parent="${parent.getAttribute('id')}"]`);
    const allChecked = [...siblings].every(sibling => sibling.checked);
    const someChecked = [...siblings].some(sibling => sibling.checked);
    
    if (allChecked) {
      parent.checked = true;
      parent.indeterminate = false;
    } else if (someChecked) {
      parent.checked = false;
      parent.indeterminate = true;
    } else {
      parent.checked = false;
      parent.indeterminate = false;
    }
  });
});