All files / app/assets/javascripts/behaviors/markdown copy_as_gfm.js

57.29% Statements 55/96
50% Branches 19/38
60% Functions 12/20
63.21% Lines 55/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  2x 2x 2x   2x     2x     2x       2x 2x   2x 2x   2x 2x   2x 2x   2x 2x 2x   2x 2x   2x   2x   2x                   3x 3x   3x 3x 3x 3x   3x     3x 2x     1x 1x 1x   1x             3x               3x 3x   3x 1x     2x         14x 14x   5x     9x                                                                                                                         17x           17x 17x 17x 17x   17x                 1x           102x 102x       2x    
import $ from 'jquery';
import { sanitize } from '~/lib/dompurify';
import { getSelectedFragment, insertText } from '~/lib/utils/common_utils';
 
export class CopyAsGFM {
  constructor() {
    // iOS currently does not support clipboardData.setData(). This bug should
    // be fixed in iOS 12, but for now we'll disable this for all iOS browsers
    // ref: https://trac.webkit.org/changeset/222228/webkit
    const userAgent = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
    const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent);
    Iif (isIOS) return;
 
    $(document).on('copy', '.md', (e) => {
      CopyAsGFM.copyAsGFM(e, CopyAsGFM.transformGFMSelection);
    });
    $(document).on('copy', 'pre.code.highlight, table.code td.line_content', (e) => {
      CopyAsGFM.copyAsGFM(e, CopyAsGFM.transformCodeSelection);
    });
    $(document).on('paste', '.js-gfm-input', CopyAsGFM.pasteGFM);
  }
 
  static copyAsGFM(e, transformer) {
    const { clipboardData } = e.originalEvent;
    Iif (!clipboardData) return;
 
    const documentFragment = getSelectedFragment();
    Iif (!documentFragment) return;
 
    const el = transformer(documentFragment.cloneNode(true), e.currentTarget);
    Iif (!el) return;
 
    e.preventDefault();
    e.stopPropagation();
 
    const div = document.createElement('div');
    div.appendChild(el.cloneNode(true));
    const html = div.innerHTML;
 
    clipboardData.setData('text/plain', el.textContent);
    clipboardData.setData('text/html', html);
    // We are also setting this as fallback to transform the selection to gfm on paste
    clipboardData.setData('text/x-gfm-html', html);
 
    CopyAsGFM.nodeToGFM(el)
      .then((res) => {
        clipboardData.setData('text/x-gfm', res);
      })
      .catch(() => {
        // Not showing the error as Firefox might doesn't allow
        // it or other browsers who have a time limit on the execution
        // of the copy event
      });
  }
 
  static pasteGFM(e) {
    const { clipboardData } = e.originalEvent;
    Iif (!clipboardData) return;
 
    const text = clipboardData.getData('text/plain');
    const gfm = clipboardData.getData('text/x-gfm');
    const gfmHtml = clipboardData.getData('text/x-gfm-html');
    Iif (!gfm && !gfmHtml) return;
 
    e.preventDefault();
 
    // We have the original selection already converted to gfm
    if (gfm) {
      CopyAsGFM.insertPastedText(e.target, text, gfm);
    } else {
      // Due to the async copy call we are not able to produce gfm so we transform the cached HTML
      const div = document.createElement('div');
      div.innerHTML = sanitize(gfmHtml);
      CopyAsGFM.nodeToGFM(div)
        .then((transformedGfm) => {
          CopyAsGFM.insertPastedText(e.target, text, transformedGfm);
        })
        .catch(() => {});
    }
  }
 
  static insertPastedText(target, text, gfm) {
    insertText(target, (textBefore) => {
      // If the text before the cursor contains an odd number of backticks,
      // we are either inside an inline code span that starts with 1 backtick
      // or a code block that starts with 3 backticks.
      // This logic still holds when there are one or more _closed_ code spans
      // or blocks that will have 2 or 6 backticks.
      // This will break down when the actual code block contains an uneven
      // number of backticks, but this is a rare edge case.
      const backtickMatch = textBefore.match(/`/g);
      const insideCodeBlock = backtickMatch && backtickMatch.length % 2 === 1;
 
      if (insideCodeBlock) {
        return text;
      }
 
      return gfm;
    });
  }
 
  static transformGFMSelection(documentFragment) {
    const gfmElements = documentFragment.querySelectorAll('.md');
    switch (gfmElements.length) {
      case 0: {
        return documentFragment;
      }
      case 1: {
        return gfmElements[0];
      }
      default: {
        const allGfmElement = document.createElement('div');
 
        for (let i = 0; i < gfmElements.length; i += 1) {
          const gfmElement = gfmElements[i];
          allGfmElement.appendChild(gfmElement);
          allGfmElement.appendChild(document.createTextNode('\n\n'));
        }
 
        return allGfmElement;
      }
    }
  }
 
  static transformCodeSelection(documentFragment, target) {
    let lineSelector = '.line';
 
    if (target) {
      const lineClass = ['left-side', 'right-side'].filter((name) =>
        target.classList.contains(name),
      )[0];
      if (lineClass) {
        lineSelector = `.line_content.${lineClass} ${lineSelector}`;
      }
    }
 
    const lineElements = documentFragment.querySelectorAll(lineSelector);
 
    let codeElement;
    if (lineElements.length > 1) {
      codeElement = document.createElement('pre');
      codeElement.className = 'code highlight';
 
      const lang = lineElements[0].getAttribute('lang');
      if (lang) {
        codeElement.setAttribute('lang', lang);
      }
    } else {
      codeElement = document.createElement('code');
    }
 
    if (lineElements.length > 0) {
      for (let i = 0; i < lineElements.length; i += 1) {
        const lineElement = lineElements[i];
        const line = document.createElement('span');
        line.append(...lineElement.childNodes);
        codeElement.appendChild(line);
        codeElement.appendChild(document.createTextNode('\n'));
      }
    } else {
      codeElement.appendChild(documentFragment);
    }
 
    [...codeElement.querySelectorAll('.idiff')].forEach((el) => el.classList.remove('idiff'));
 
    return codeElement;
  }
 
  static nodeToGFM(node) {
    return Promise.all([
      import(/* webpackChunkName: 'gfm_copy_extra' */ '@tiptap/pm/model'),
      import(/* webpackChunkName: 'gfm_copy_extra' */ './schema'),
      import(/* webpackChunkName: 'gfm_copy_extra' */ './serializer'),
    ])
      .then(([prosemirrorModel, schema, markdownSerializer]) => {
        const { DOMParser } = prosemirrorModel;
        const wrapEl = document.createElement('div');
        wrapEl.appendChild(node.cloneNode(true));
        const doc = DOMParser.fromSchema(schema.default).parse(wrapEl);
 
        return markdownSerializer.default.serialize(
          { doc },
          { useCanonicalSrc: false, skipEmptyNodes: true },
        );
      })
      .catch(() => {});
  }
 
  static quoted(markdown) {
    return `> ${markdown.split('\n').join('\n> ')}`;
  }
}
 
// Export CopyAsGFM as a global for rspec to access
// see /spec/features/markdown/copy_as_gfm_spec.rb
Eif (process.env.NODE_ENV !== 'production') {
  window.CopyAsGFM = CopyAsGFM;
}
 
export default function initCopyAsGFM() {
  return new CopyAsGFM();
}