def util.query(q)
  js(q) return document.querySelector(q) end then return the result
end

def util.queryAll(q)
  js(q) return document.querySelectorAll(q) end then return the result
end

def form.getRelatedContentFor(input)
  set s to "label[for=" + input's id + "]"
  call util.query(s) then set label to the result
  if label is null then
    return null
  otherwise
    set s to "[aria-labelledby=" + label's id + "]"
    call util.query(s) then return the result
  end
end

def form.getRadiosInGroup(radio)
  set s to "input[name=" + radio's name + "]"
  call util.queryAll(s) then return the result
end

behavior TouchableField
  on change or keydown
    send touched to the closest <form/>
  end
end

behavior PropagateRequiredRadioContent
  init
    if I am in <:required:checked/>
      call form.getRelatedContentFor(me) then set related to the result
      add @required='' to <[data-require="conditionally"/> in related
    end
  end

  on change or blur
    call form.getRadiosInGroup(me) then set radios to the result
    for radio in radios
      call form.getRelatedContentFor(radio) then set related to the result
      if related does not exist
        continue
      otherwise if radio is in <:required:checked/>
        add @required='' to <[data-require="conditionally"]/> in related
      otherwise
        remove @required='' from <[data-require="conditionally"]/> in related
      end
    end
  end
end

behavior CaptureFocusFromRelatedContent(radio)
  on focus set { checked: true } on radio
end

behavior DisableSubmission
  init
    if I match .submission-is-disabled
      add @disabled='true' to <button[type="submit"]/> in me
    end
  end

  on change or blur
    if I match .submission-is-disabled
      add @disabled='true' to <button[type="submit"]/> in me
    otherwise
      remove @disabled='true' from <button[type="submit"]/> in me
    end
  end
end
