summaryrefslogtreecommitdiffstats
path: root/src/scripts/common.js
blob: bd516c8b16ef0684558b25a1c956af48ea949260 (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
'use strict';

// ----------------- Pattern Check ------------------

function checkPattern(pattern, type) {
  
  const pat = pattern.value;

  if (!pat) {
    pattern.classList.add('invalid');
    pattern.focus();
    showResult(chrome.i18n.getMessage('errorEmpty'), true);
    return;
  }  

  const patternTypeSet = {
    '1': 'wildcard',
    '2': 'regex'
  }

  let regex;

  switch (patternTypeSet[type.value]) {

    // RegEx
    case 'regex':
      try { regex = new RegExp(pat); }
      catch (e) {
        pattern.classList.add('invalid');
        showResult(e.message, true);
        return false;
      }
      break;

    // wildcard
    default:
      if (pat.includes('/')) {
        pattern.classList.add('invalid');
        showResult(chrome.i18n.getMessage('errorSlash'), true);
        return false;
      }

      try { regex = new RegExp(Utils.wildcardToRegExp(pat)); }
      catch (e) {
        pattern.classList.add('invalid');
        showResult(e.message, true);
        return false;
      }
  }  
  
  // --- pattern is valid
  return regex;
}




function showResult(text, fail) {

  fail && result.classList.add('alert');
  result.textContent = text;
  result.classList.remove('hide');
}