Welcome to mirror list, hosted at ThFree Co, Russian Federation.

utils.js « extensions « components « vue_merge_request_widget « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 83f5c1490e265b88b95ecf11822302c69336265b (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
78
const TEXT_STYLES = {
  success: {
    start: '%{success_start}',
    end: '%{success_end}',
  },
  danger: {
    start: '%{danger_start}',
    end: '%{danger_end}',
  },
  critical: {
    start: '%{critical_start}',
    end: '%{critical_end}',
  },
  same: {
    start: '%{same_start}',
    end: '%{same_end}',
  },
  strong: {
    start: '%{strong_start}',
    end: '%{strong_end}',
  },
  small: {
    start: '%{small_start}',
    end: '%{small_end}',
  },
};

const getStartTag = (tag) => TEXT_STYLES[tag].start;
const textStyleTags = {
  [getStartTag('success')]: '<span class="gl-font-weight-bold gl-text-green-500">',
  [getStartTag('danger')]: '<span class="gl-font-weight-bold gl-text-red-500">',
  [getStartTag('critical')]: '<span class="gl-font-weight-bold gl-text-red-800">',
  [getStartTag('same')]: '<span class="gl-font-weight-bold gl-text-gray-700">',
  [getStartTag('strong')]: '<span class="gl-font-weight-bold">',
  [getStartTag('small')]: '<span class="gl-font-sm gl-text-gray-700">',
};

const escapeText = (text) =>
  document.createElement('div').appendChild(document.createTextNode(text)).parentNode.innerHTML;

const createText = (text) => {
  return text
    .replace(
      new RegExp(
        `(${Object.values(TEXT_STYLES)
          .reduce((acc, i) => [...acc, ...Object.values(i)], [])
          .join('|')})`,
        'gi',
      ),
      (replace) => {
        const replacement = textStyleTags[replace];

        // If the replacement tag ends with a `_end` then we can just return `</span>`
        // unless we have a replacement, for cases were we want to change the HTML tag
        if (!replacement && replace.endsWith('_end}')) {
          return '</span>';
        }

        return replacement;
      },
    )
    .replace(/%{([a-z]|_)+}/g, ''); // Filter out any tags we don't know about
};

export const generateText = (text) => {
  if (typeof text === 'string') {
    return createText(escapeText(text));
  }
  if (typeof text === 'object' && typeof text.text === 'string' && typeof text.href === 'string') {
    return createText(
      `${
        text.prependText ? `${escapeText(text.prependText)} ` : ''
      }<a class="gl-text-decoration-underline" href="${text.href}">${escapeText(text.text)}</a>`,
    );
  }

  return null;
};