// Disabled controls stay in the accessibility tree while work is in progress.
// Restore the initiating control only when the user has not moved elsewhere.
export function lockForm(form) {
  const document = form.ownerDocument;
  const target = document.activeElement;
  const restore = form.contains(target);
  const controls = [...form.querySelectorAll('input, select, textarea, button')]
    .map((control) => ({ control, disabled: control.disabled }));
  let moved = false;
  const onFocus = (event) => {
    if (event.target !== target && event.target !== document.body && event.target !== document.documentElement) moved = true;
  };
  document.addEventListener('focusin', onFocus, true);
  form.setAttribute('aria-busy', 'true');
  for (const { control } of controls) control.disabled = true;
  return () => {
    for (const { control, disabled } of controls) control.disabled = disabled;
    form.removeAttribute('aria-busy');
    document.removeEventListener('focusin', onFocus, true);
    const active = document.activeElement;
    if (restore && !moved && target.isConnected && document.hasFocus()
      && (active === document.body || active === document.documentElement || active === target)) {
      target.focus({ preventScroll: true });
    }
  };
}