github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/client/src/form.ts (about)

     1  // Content managed by Project Forge, see [projectforge.md] for details.
     2  import {els} from "./dom";
     3  
     4  const selected = "--selected";
     5  
     6  export function setSiblingToNull(el: HTMLElement) {
     7    const i = el.parentElement?.parentElement?.querySelector("input");
     8    if (!i) {
     9      throw new Error("no associated input found");
    10    }
    11    i.value = "∅";
    12  }
    13  
    14  export function initForm(frm: HTMLFormElement) {
    15    frm.onreset = () => initForm(frm);
    16    const editorCache: { [key: string]: string; } = {};
    17    const selectedCache: { [key: string]: HTMLInputElement; } = {};
    18    for (const el of frm.elements) {
    19      const input = el as HTMLInputElement;
    20      if (input.name.length > 0) {
    21        if (input.name.endsWith(selected)) {
    22          selectedCache[input.name] = input;
    23        } else {
    24          if (input.type !== "radio" || input.checked) {
    25            editorCache[input.name] = input.value;
    26          }
    27          const evt = () => {
    28            const cv = selectedCache[input.name + selected];
    29            if (cv) {
    30              cv.checked = editorCache[input.name] !== input.value;
    31            }
    32          };
    33          input.onchange = evt;
    34          input.onkeyup = evt;
    35        }
    36      }
    37    }
    38  }
    39  
    40  export function formInit(): [(el: HTMLElement) => void, (frm: HTMLFormElement) => void] {
    41    for (const n of els<HTMLFormElement>("form.editor")) {
    42      initForm(n);
    43    }
    44    return [setSiblingToNull, initForm];
    45  }