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

index.js « emoji « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1fa81a000a535e109fed19b825f9a1b740811608 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import Vue from 'vue';
import { escape, minBy } from 'lodash';
import emojiRegexFactory from 'emoji-regex';
import emojiAliases from 'emojis/aliases.json';
import createApolloClient from '~/lib/graphql';
import { setAttributes } from '~/lib/utils/dom_utils';
import { getEmojiScoreWithIntent } from '~/emoji/utils';
import AccessorUtilities from '../lib/utils/accessor';
import axios from '../lib/utils/axios_utils';
import customEmojiQuery from './queries/custom_emoji.query.graphql';
import { CACHE_KEY, CACHE_VERSION_KEY, CATEGORY_ICON_MAP, FREQUENTLY_USED_KEY } from './constants';

let emojiMap = null;
let validEmojiNames = null;

export const state = Vue.observable({
  loading: true,
});

export const FALLBACK_EMOJI_KEY = 'grey_question';

// Keep the version in sync with `lib/gitlab/emoji.rb`
export const EMOJI_VERSION = '2';

const isLocalStorageAvailable = AccessorUtilities.canUseLocalStorage();

async function loadEmoji() {
  if (
    isLocalStorageAvailable &&
    window.localStorage.getItem(CACHE_VERSION_KEY) === EMOJI_VERSION &&
    window.localStorage.getItem(CACHE_KEY)
  ) {
    const emojis = JSON.parse(window.localStorage.getItem(CACHE_KEY));
    // Workaround because the pride flag is broken in EMOJI_VERSION = '1'
    if (emojis.gay_pride_flag) {
      emojis.gay_pride_flag.e = '🏳️‍🌈';
    }
    return emojis;
  }

  // We load the JSON file direct from the server
  // because it can't be loaded from a CDN due to
  // cross domain problems with JSON
  const { data } = await axios.get(
    `${gon.relative_url_root || ''}/-/emojis/${EMOJI_VERSION}/emojis.json`,
  );
  window.localStorage.setItem(CACHE_VERSION_KEY, EMOJI_VERSION);
  window.localStorage.setItem(CACHE_KEY, JSON.stringify(data));
  return data;
}

async function loadEmojiWithNames() {
  const emojiRegex = emojiRegexFactory();

  return Object.entries(await loadEmoji()).reduce((acc, [key, value]) => {
    // Filter out entries which aren't emojis
    if (value.e.match(emojiRegex)?.[0] === value.e) {
      acc[key] = { ...value, name: key };
    }
    return acc;
  }, {});
}

export async function loadCustomEmojiWithNames() {
  if (document.body?.dataset?.groupFullPath && window.gon?.features?.customEmoji) {
    const client = createApolloClient();
    const { data } = await client.query({
      query: customEmojiQuery,
      variables: {
        groupPath: document.body.dataset.groupFullPath,
      },
    });

    return data?.group?.customEmoji?.nodes?.reduce((acc, e) => {
      // Map the custom emoji into the format of the normal emojis
      acc[e.name] = {
        c: 'custom',
        d: e.name,
        e: undefined,
        name: e.name,
        src: e.url,
        u: 'custom',
      };

      return acc;
    }, {});
  }

  return {};
}

async function prepareEmojiMap() {
  return Promise.all([loadEmojiWithNames(), loadCustomEmojiWithNames()]).then((values) => {
    emojiMap = {
      ...values[0],
      ...values[1],
    };
    validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
    state.loading = false;
  });
}

export function initEmojiMap() {
  initEmojiMap.promise = initEmojiMap.promise || prepareEmojiMap();
  return initEmojiMap.promise;
}

export function normalizeEmojiName(name) {
  return Object.prototype.hasOwnProperty.call(emojiAliases, name) ? emojiAliases[name] : name;
}

export function getValidEmojiNames() {
  return validEmojiNames;
}

export function isEmojiNameValid(name) {
  if (!emojiMap) {
    // eslint-disable-next-line @gitlab/require-i18n-strings
    throw new Error('The emoji map is uninitialized or initialization has not completed');
  }

  return name in emojiMap || name in emojiAliases;
}

export function getAllEmoji() {
  return emojiMap;
}

export function findCustomEmoji(name) {
  return emojiMap[name];
}

function getAliasesMatchingQuery(query) {
  return Object.keys(emojiAliases)
    .filter((alias) => alias.includes(query))
    .reduce((map, alias) => {
      const emojiName = emojiAliases[alias];
      const score = alias.indexOf(query);

      const prev = map.get(emojiName);
      // overwrite if we beat the previous score or we're more alphabetical
      const shouldSet =
        !prev ||
        prev.score > score ||
        (prev.score === score && prev.alias.localeCompare(alias) > 0);

      if (shouldSet) {
        map.set(emojiName, { score, alias });
      }

      return map;
    }, new Map());
}

function getUnicodeMatch(emoji, query) {
  if (emoji.e === query) {
    return { score: 0, field: 'e', fieldValue: emoji.name, emoji };
  }

  return null;
}

function getDescriptionMatch(emoji, query) {
  if (emoji.d.includes(query)) {
    return { score: emoji.d.indexOf(query), field: 'd', fieldValue: emoji.d, emoji };
  }

  return null;
}

function getAliasMatch(emoji, matchingAliases) {
  if (matchingAliases.has(emoji.name)) {
    const { score, alias } = matchingAliases.get(emoji.name);

    return { score, field: 'alias', fieldValue: alias, emoji };
  }

  return null;
}

function getNameMatch(emoji, query) {
  if (emoji.name.includes(query)) {
    return {
      score: emoji.name.indexOf(query),
      field: 'name',
      fieldValue: emoji.name,
      emoji,
    };
  }

  return null;
}

// Sort emoji by emoji score falling back to a string comparison
export function sortEmoji(a, b) {
  return a.score - b.score || a.fieldValue.localeCompare(b.fieldValue);
}

export function searchEmoji(query) {
  const lowercaseQuery = query ? `${query}`.toLowerCase() : '';

  const matchingAliases = getAliasesMatchingQuery(lowercaseQuery);

  return Object.values(emojiMap)
    .map((emoji) => {
      const matches = [
        getUnicodeMatch(emoji, query),
        getDescriptionMatch(emoji, lowercaseQuery),
        getAliasMatch(emoji, matchingAliases),
        getNameMatch(emoji, lowercaseQuery),
      ]
        .filter(Boolean)
        .map((x) => ({ ...x, score: getEmojiScoreWithIntent(x.emoji.name, x.score) }));

      return minBy(matches, (x) => x.score);
    })
    .filter(Boolean)
    .sort(sortEmoji);
}

export const CATEGORY_NAMES = Object.keys(CATEGORY_ICON_MAP);

let emojiCategoryMap;
export function getEmojiCategoryMap() {
  if (!emojiCategoryMap && emojiMap) {
    emojiCategoryMap = CATEGORY_NAMES.reduce((acc, category) => {
      if (category === FREQUENTLY_USED_KEY) {
        return acc;
      }
      return { ...acc, [category]: [] };
    }, {});
    Object.keys(emojiMap).forEach((name) => {
      const emoji = emojiMap[name];
      if (emojiCategoryMap[emoji.c]) {
        emojiCategoryMap[emoji.c].push(name);
      }
    });
  }
  return emojiCategoryMap;
}

/**
 * Retrieves an emoji by name
 *
 * @param {String} query The emoji name
 * @param {Boolean} fallback If true, a fallback emoji will be returned if the
 * named emoji does not exist.
 * @returns {Object} The matching emoji.
 */
export function getEmojiInfo(query, fallback = true) {
  if (!emojiMap) {
    // eslint-disable-next-line @gitlab/require-i18n-strings
    throw new Error('The emoji map is uninitialized or initialization has not completed');
  }

  const lowercaseQuery = query ? `${query}`.toLowerCase() : '';
  const name = normalizeEmojiName(lowercaseQuery);

  if (name in emojiMap) {
    return emojiMap[name];
  }

  return fallback ? emojiMap[FALLBACK_EMOJI_KEY] : null;
}

export function emojiFallbackImageSrc(inputName) {
  const { name, src } = getEmojiInfo(inputName);
  return (
    src ||
    `${gon.asset_host || ''}${gon.relative_url_root || ''}/-/emojis/${EMOJI_VERSION}/${name}.png`
  );
}

export function emojiImageTag(name, src) {
  const img = document.createElement('img');

  img.className = 'emoji';
  setAttributes(img, {
    title: `:${name}:`,
    alt: `:${name}:`,
    src,
    align: 'absmiddle',
  });

  return img;
}

export function glEmojiTag(inputName, options) {
  const opts = { sprite: false, ...options };
  const name = normalizeEmojiName(inputName);
  const fallbackSpriteClass = `emoji-${name}`;

  const fallbackSpriteAttribute = opts.sprite
    ? `data-fallback-sprite-class="${escape(fallbackSpriteClass)}" `
    : '';

  const fallbackUrl = opts.url;
  const fallbackSrcAttribute = fallbackUrl
    ? `data-fallback-src="${fallbackUrl}" data-unicode-version="custom"`
    : '';

  return `<gl-emoji ${fallbackSrcAttribute}${fallbackSpriteAttribute}data-name="${escape(
    name,
  )}"></gl-emoji>`;
}