summaryrefslogtreecommitdiffstats
path: root/src/scripts/pattern-tester.js
blob: 83e0a2662e6e58c158795311e23492873931a135 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';

// ----------------- Internationalization ------------------
document.querySelectorAll('[data-i18n]').forEach(node => {
  let [text, attr] = node.dataset.i18n.split('|');
  text = chrome.i18n.getMessage(text);
  attr ? node[attr] = text : node.appendChild(document.createTextNode(text));
});
// ----------------- /Internationalization -----------------

// --- global
const url = document.querySelector('#url');
const pattern = document.querySelector('#pattern');
const type = document.querySelector('#type');
const protocols = document.querySelector('#protocols');
const result = document.querySelector('#result');


document.querySelector('button[data-i18n="test"]').addEventListener('click', testPattern);


// ----- check for Edit
const pat = localStorage.getItem('pattern');
if (pat) {

  pattern.value = pat;
  type.value = localStorage.getItem('type');
  protocols.value = localStorage.getItem('protocols');

  localStorage.removeItem('pattern');
  localStorage.removeItem('type');
  localStorage.removeItem('protocols');
}


function testPattern() {

  // --- reset
  url.classList.remove('invalid');
  pattern.classList.remove('invalid');
  result.classList.add('hide');
  result.classList.remove('alert');

  // --- trim text values
  [url, pattern].forEach(item => item.value = item.value.trim());
  
  // --- URL check
  let parsedURL;
  try { parsedURL = new URL(url.value); }
  catch (e) {
    url.classList.add('invalid');
    showResult(e.message, true);
    return;
  }

  // --- protocol check
  const protocolSet = {                                     // converting to meaningful terms
    '1': ['http:', 'https:'],
    '2': ['http:'],
    '4': ['https:']
  };

  if (!protocolSet[protocols.value].includes(parsedURL.protocol)) {
    showResult(chrome.i18n.getMessage('errorProtocol'), true);
    return;
  }


  // --- pattern check  
  const regex = checkPattern(pattern, type);
  if (!regex) { return; }
  
  // --- pattern on URL check (pattern is valid)
  regex.test(parsedURL.host) ? showResult(chrome.i18n.getMessage('patternMatch')) : 
                                showResult(chrome.i18n.getMessage('patternNotMatch'), true);

}