All files / publisher submitEnabler.ts

100% Statements 29/29
91.66% Branches 11/12
100% Functions 5/5
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62            7x 1x     6x 2x     4x   4x 1x     3x 6x     3x   3x   3x 3x     3x 6x 6x 6x       3x 3x 3x   3x 3x     3x 3x 6x 4x 4x   2x 2x              
import shallowDiff from "../libs/shallowDiff";
 
function submitEnabler(
  formSelector: string | undefined,
  buttonSelectors: any[] | undefined,
) {
  if (!formSelector) {
    throw new TypeError("`formSelector` argument is required");
  }
 
  if (!buttonSelectors || buttonSelectors.length === 0) {
    throw new TypeError("At least one `buttonSelectors` must be defined");
  }
 
  const formEl = document.querySelector(formSelector) as HTMLFormElement;
 
  if (!formEl) {
    throw new Error(`${formSelector} is not a valid element`);
  }
 
  const buttonEls = buttonSelectors.map((selector) =>
    document.querySelector(selector),
  );
 
  const initialState = new FormData(formEl);
 
  const initialStateJson: { [key: string]: any } = {};
 
  for (const [key, value] of initialState.entries()) {
    initialStateJson[key] = value;
  }
 
  buttonEls.forEach((button) => {
    Eif (button) {
      button.setAttribute("disabled", "disabled");
      button.classList.add("is-disabled");
    }
  });
 
  formEl.addEventListener("change", () => {
    const newState = new FormData(formEl);
    const newStateJson: { [key: string]: any } = {};
 
    for (const [key, value] of newState.entries()) {
      newStateJson[key] = value;
    }
 
    const diff = shallowDiff(initialStateJson, newStateJson);
    buttonEls.forEach((button) => {
      if (diff) {
        button.removeAttribute("disabled");
        button.classList.remove("is-disabled");
      } else {
        button.setAttribute("disabled", "disabled");
        button.classList.add("is-disabled");
      }
    });
  });
}
 
export { submitEnabler as default };