summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/behaviors/gl_emoji.js
blob: 8156e491a4245b38556f7cb8b8e325f8205653b8 (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
import installCustomElements from 'document-register-element';
import { emojiImageTag, emojiFallbackImageSrc } from '../emoji';
import isEmojiUnicodeSupported from '../emoji/support';

installCustomElements(window);

export default function installGlEmojiElement() {
  const GlEmojiElementProto = Object.create(HTMLElement.prototype);
  GlEmojiElementProto.createdCallback = function createdCallback() {
    const emojiUnicode = this.textContent.trim();
    const {
      name,
      unicodeVersion,
      fallbackSrc,
      fallbackSpriteClass,
    } = this.dataset;

    const isEmojiUnicode = this.childNodes && Array.prototype.every.call(
      this.childNodes,
      childNode => childNode.nodeType === 3,
    );
    const hasImageFallback = fallbackSrc && fallbackSrc.length > 0;
    const hasCssSpriteFalback = fallbackSpriteClass && fallbackSpriteClass.length > 0;

    if (
      emojiUnicode &&
      isEmojiUnicode &&
      !isEmojiUnicodeSupported(emojiUnicode, unicodeVersion)
    ) {
      // CSS sprite fallback takes precedence over image fallback
      if (hasCssSpriteFalback) {
        // IE 11 doesn't like adding multiple at once :(
        this.classList.add('emoji-icon');
        this.classList.add(fallbackSpriteClass);
      } else if (hasImageFallback) {
        this.innerHTML = emojiImageTag(name, fallbackSrc);
      } else {
        const src = emojiFallbackImageSrc(name);
        this.innerHTML = emojiImageTag(name, src);
      }
    }
  };

  document.registerElement('gl-emoji', {
    prototype: GlEmojiElementProto,
  });
}