summaryrefslogtreecommitdiff
path: root/spec/javascripts/dirty_submit/helper.js
blob: b51783cb9159d5804287c8de86b67630ef2f780b (plain)
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
import DirtySubmitForm from '~/dirty_submit/dirty_submit_form';
import setTimeoutPromiseHelper from '../helpers/set_timeout_promise_helper';

function isCheckableType(type) {
  return /^(radio|checkbox)$/.test(type);
}

export function setInputValue(element, value) {
  const { type } = element;
  let eventType;

  if (isCheckableType(type)) {
    element.checked = !element.checked;
    eventType = 'change';
  } else {
    element.value = value;
    eventType = 'input';
  }

  element.dispatchEvent(
    new Event(eventType, {
      bubbles: true,
    }),
  );

  return setTimeoutPromiseHelper(DirtySubmitForm.THROTTLE_DURATION);
}

export function getInputValue(input) {
  return isCheckableType(input.type) ? input.checked : input.value;
}

export function createForm(type = 'text') {
  const form = document.createElement('form');
  form.innerHTML = `
    <input type="${type}" name="${type}" class="js-input"/>
    <button type="submit" class="js-dirty-submit"></button>
  `;

  const input = form.querySelector('.js-input');
  const submit = form.querySelector('.js-dirty-submit');

  return {
    form,
    input,
    submit,
  };
}