copy_as_gfm.js 14.3 KB
Newer Older
Douwe Maan's avatar
Douwe Maan committed
1
/* eslint-disable class-methods-use-this, object-shorthand, no-unused-vars, no-use-before-define, no-new, max-len, no-restricted-syntax, guard-for-in, no-continue */
2

3
import _ from 'underscore';
4 5
import { insertText, getSelectedFragment, nodeMatchesSelector } from '../lib/utils/common_utils';
import { placeholderImage } from '../lazy_loader';
Douwe Maan's avatar
Douwe Maan committed
6

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
const gfmRules = {
  // The filters referenced in lib/banzai/pipeline/gfm_pipeline.rb convert
  // GitLab Flavored Markdown (GFM) to HTML.
  // These handlers consequently convert that same HTML to GFM to be copied to the clipboard.
  // Every filter in lib/banzai/pipeline/gfm_pipeline.rb that generates HTML
  // from GFM should have a handler here, in reverse order.
  // The GFM-to-HTML-to-GFM cycle is tested in spec/features/copy_as_gfm_spec.rb.
  InlineDiffFilter: {
    'span.idiff.addition'(el, text) {
      return `{+${text}+}`;
    },
    'span.idiff.deletion'(el, text) {
      return `{-${text}-}`;
    },
  },
  TaskListFilter: {
23
    'input[type=checkbox].task-list-item-checkbox'(el) {
24 25 26 27
      return `[${el.checked ? 'x' : ' '}]`;
    },
  },
  ReferenceFilter: {
28
    '.tooltip'(el) {
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
      return '';
    },
    'a.gfm:not([data-link=true])'(el, text) {
      return el.dataset.original || text;
    },
  },
  AutolinkFilter: {
    'a'(el, text) {
      // Fallback on the regular MarkdownFilter's `a` handler.
      if (text !== el.getAttribute('href')) return false;

      return text;
    },
  },
  TableOfContentsFilter: {
44
    'ul.section-nav'(el) {
45 46 47 48
      return '[[_TOC_]]';
    },
  },
  EmojiFilter: {
49
    'img.emoji'(el) {
50 51
      return el.getAttribute('alt');
    },
52
    'gl-emoji'(el) {
53 54 55 56 57 58 59 60
      return `:${el.getAttribute('data-name')}:`;
    },
  },
  ImageLinkFilter: {
    'a.no-attachment-icon'(el, text) {
      return text;
    },
  },
61 62 63 64 65
  ImageLazyLoadFilter: {
    'img'(el, text) {
      return `![${el.getAttribute('alt')}](${el.getAttribute('src')})`;
    },
  },
66
  VideoLinkFilter: {
67
    '.video-container'(el) {
68 69 70 71 72
      const videoEl = el.querySelector('video');
      if (!videoEl) return false;

      return CopyAsGFM.nodeToGFM(videoEl);
    },
73
    'video'(el) {
74 75 76
      return `![${el.dataset.title}](${el.getAttribute('src')})`;
    },
  },
Douwe Maan's avatar
Douwe Maan committed
77 78 79 80 81 82 83 84 85 86 87 88
  MermaidFilter: {
    'svg.mermaid'(el, text) {
      const sourceEl = el.querySelector('text.source');
      if (!sourceEl) return false;

      return `\`\`\`mermaid\n${CopyAsGFM.nodeToGFM(sourceEl)}\n\`\`\``;
    },
    'svg.mermaid style, svg.mermaid g'(el, text) {
      // We don't want to include the content of these elements in the copied text.
      return '';
    },
  },
89 90 91 92 93 94 95
  MathFilter: {
    'pre.code.math[data-math-style=display]'(el, text) {
      return `\`\`\`math\n${text.trim()}\n\`\`\``;
    },
    'code.code.math[data-math-style=inline]'(el, text) {
      return `$\`${text}\`$`;
    },
96
    'span.katex-display span.katex-mathml'(el) {
97 98 99 100 101
      const mathAnnotation = el.querySelector('annotation[encoding="application/x-tex"]');
      if (!mathAnnotation) return false;

      return `\`\`\`math\n${CopyAsGFM.nodeToGFM(mathAnnotation)}\n\`\`\``;
    },
102
    'span.katex-mathml'(el) {
103 104 105 106 107
      const mathAnnotation = el.querySelector('annotation[encoding="application/x-tex"]');
      if (!mathAnnotation) return false;

      return `$\`${CopyAsGFM.nodeToGFM(mathAnnotation)}\`$`;
    },
108
    'span.katex-html'(el) {
109 110 111 112 113 114 115 116
      // We don't want to include the content of this element in the copied text.
      return '';
    },
    'annotation[encoding="application/x-tex"]'(el, text) {
      return text.trim();
    },
  },
  SanitizationFilter: {
117
    'a[name]:not([href]):empty'(el) {
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
      return el.outerHTML;
    },
    'dl'(el, text) {
      let lines = text.trim().split('\n');
      // Add two spaces to the front of subsequent list items lines,
      // or leave the line entirely blank.
      lines = lines.map((l) => {
        const line = l.trim();
        if (line.length === 0) return '';

        return `  ${line}`;
      });

      return `<dl>\n${lines.join('\n')}\n</dl>`;
    },
    'sub, dt, dd, kbd, q, samp, var, ruby, rt, rp, abbr, summary, details'(el, text) {
      const tag = el.nodeName.toLowerCase();
      return `<${tag}>${text}</${tag}>`;
    },
  },
  SyntaxHighlightFilter: {
    'pre.code.highlight'(el, t) {
140
      const text = t.trimRight();
141 142

      let lang = el.getAttribute('lang');
143
      if (!lang || lang === 'plaintext') {
144 145 146 147 148 149
        lang = '';
      }

      // Prefixes lines with 4 spaces if the code contains triple backticks
      if (lang === '' && text.match(/^```/gm)) {
        return text.split('\n').map((l) => {
Douwe Maan's avatar
Douwe Maan committed
150 151
          const line = l.trim();
          if (line.length === 0) return '';
152

153 154 155
          return `    ${line}`;
        }).join('\n');
      }
156

157 158 159 160 161 162 163 164
      return `\`\`\`${lang}\n${text}\n\`\`\``;
    },
    'pre > code'(el, text) {
       // Don't wrap code blocks in ``
      return text;
    },
  },
  MarkdownFilter: {
165
    'br'(el) {
166 167
      // Two spaces at the end of a line are turned into a BR
      return '  ';
168
    },
169 170 171 172 173 174
    'code'(el, text) {
      let backtickCount = 1;
      const backtickMatch = text.match(/`+/);
      if (backtickMatch) {
        backtickCount = backtickMatch[0].length + 1;
      }
Douwe Maan's avatar
Douwe Maan committed
175

176 177
      const backticks = Array(backtickCount + 1).join('`');
      const spaceOrNoSpace = backtickCount > 1 ? ' ' : '';
178

179
      return backticks + spaceOrNoSpace + text.trim() + spaceOrNoSpace + backticks;
180 181 182 183
    },
    'blockquote'(el, text) {
      return text.trim().split('\n').map(s => `> ${s}`.trim()).join('\n');
    },
184
    'img'(el) {
185 186 187
      const imageSrc = el.src;
      const imageUrl = imageSrc && imageSrc !== placeholderImage ? imageSrc : (el.dataset.src || '');
      return `![${el.getAttribute('alt')}](${imageUrl})`;
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
    },
    'a.anchor'(el, text) {
      // Don't render a Markdown link for the anchor link inside a heading
      return text;
    },
    'a'(el, text) {
      return `[${text}](${el.getAttribute('href')})`;
    },
    'li'(el, text) {
      const lines = text.trim().split('\n');
      const firstLine = `- ${lines.shift()}`;
      // Add four spaces to the front of subsequent list items lines,
      // or leave the line entirely blank.
      const nextLines = lines.map((s) => {
        if (s.trim().length === 0) return '';

        return `    ${s}`;
      });

      return `${firstLine}\n${nextLines.join('\n')}`;
    },
    'ul'(el, text) {
      return text;
    },
    'ol'(el, text) {
      // LIs get a `- ` prefix by default, which we replace by `1. ` for ordered lists.
      return text.replace(/^- /mg, '1. ');
    },
    'h1'(el, text) {
      return `# ${text.trim()}`;
    },
    'h2'(el, text) {
      return `## ${text.trim()}`;
    },
    'h3'(el, text) {
      return `### ${text.trim()}`;
    },
    'h4'(el, text) {
      return `#### ${text.trim()}`;
    },
    'h5'(el, text) {
      return `##### ${text.trim()}`;
    },
    'h6'(el, text) {
      return `###### ${text.trim()}`;
    },
    'strong'(el, text) {
      return `**${text}**`;
    },
    'em'(el, text) {
      return `_${text}_`;
    },
    'del'(el, text) {
      return `~~${text}~~`;
    },
    'sup'(el, text) {
      return `^${text}`;
    },
246
    'hr'(el) {
247 248
      return '-----';
    },
249
    'table'(el) {
250 251 252
      const theadEl = el.querySelector('thead');
      const tbodyEl = el.querySelector('tbody');
      if (!theadEl || !tbodyEl) return false;
253

254 255
      const theadText = CopyAsGFM.nodeToGFM(theadEl);
      const tbodyText = CopyAsGFM.nodeToGFM(tbodyEl);
256

257
      return [theadText, tbodyText].join('\n');
258 259 260
    },
    'thead'(el, text) {
      const cells = _.map(el.querySelectorAll('th'), (cell) => {
261
        let chars = CopyAsGFM.nodeToGFM(cell).length + 2;
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

        let before = '';
        let after = '';
        switch (cell.style.textAlign) {
          case 'center':
            before = ':';
            after = ':';
            chars -= 2;
            break;
          case 'right':
            after = ':';
            chars -= 1;
            break;
          default:
            break;
277 278
        }

279
        chars = Math.max(chars, 3);
280

281
        const middle = Array(chars + 1).join('-');
282

283 284
        return before + middle + after;
      });
285

286 287 288
      const separatorRow = `|${cells.join('|')}|`;

      return [text, separatorRow].join('\n');
289
    },
290 291 292 293 294
    'tr'(el) {
      const cellEls = el.querySelectorAll('td, th');
      if (cellEls.length === 0) return false;

      const cells = _.map(cellEls, cell => CopyAsGFM.nodeToGFM(cell));
295 296 297 298
      return `| ${cells.join(' | ')} |`;
    },
  },
};
299

300
export class CopyAsGFM {
301
  constructor() {
302 303 304 305 306 307 308
    // 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);
    if (isIOS) return;

Douwe Maan's avatar
Douwe Maan committed
309 310 311
    $(document).on('copy', '.md, .wiki', (e) => { CopyAsGFM.copyAsGFM(e, CopyAsGFM.transformGFMSelection); });
    $(document).on('copy', 'pre.code.highlight, .diff-content .line_content', (e) => { CopyAsGFM.copyAsGFM(e, CopyAsGFM.transformCodeSelection); });
    $(document).on('paste', '.js-gfm-input', CopyAsGFM.pasteGFM);
312
  }
Douwe Maan's avatar
Douwe Maan committed
313

Douwe Maan's avatar
Douwe Maan committed
314
  static copyAsGFM(e, transformer) {
315 316
    const clipboardData = e.originalEvent.clipboardData;
    if (!clipboardData) return;
317

318
    const documentFragment = getSelectedFragment();
319
    if (!documentFragment) return;
320

321
    const el = transformer(documentFragment.cloneNode(true), e.currentTarget);
322
    if (!el) return;
323

324
    e.preventDefault();
325
    e.stopPropagation();
326

327
    clipboardData.setData('text/plain', el.textContent);
Douwe Maan's avatar
Douwe Maan committed
328
    clipboardData.setData('text/x-gfm', this.nodeToGFM(el));
329
  }
330

Douwe Maan's avatar
Douwe Maan committed
331
  static pasteGFM(e) {
332 333
    const clipboardData = e.originalEvent.clipboardData;
    if (!clipboardData) return;
334

335
    const text = clipboardData.getData('text/plain');
336 337
    const gfm = clipboardData.getData('text/x-gfm');
    if (!gfm) return;
338

339
    e.preventDefault();
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    window.gl.utils.insertText(e.target, (textBefore, textAfter) => {
      // 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;
    });
358
  }
359

360
  static transformGFMSelection(documentFragment) {
361 362
    const gfmElements = documentFragment.querySelectorAll('.md, .wiki');
    switch (gfmElements.length) {
363 364 365 366
      case 0: {
        return documentFragment;
      }
      case 1: {
367
        return gfmElements[0];
368 369
      }
      default: {
370
        const allGfmElement = document.createElement('div');
371

372 373 374 375
        for (let i = 0; i < gfmElements.length; i += 1) {
          const gfmElement = gfmElements[i];
          allGfmElement.appendChild(gfmElement);
          allGfmElement.appendChild(document.createTextNode('\n\n'));
376
        }
377

378
        return allGfmElement;
379 380
      }
    }
381 382
  }

383 384
  static transformCodeSelection(documentFragment, target) {
    let lineSelector = '.line';
385

386 387 388 389 390 391 392 393 394 395 396 397 398
    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';
399

400
      const lang = lineElements[0].getAttribute('lang');
401
      if (lang) {
402
        codeElement.setAttribute('lang', lang);
403 404
      }
    } else {
405
      codeElement = document.createElement('code');
406 407
    }

408 409 410 411 412
    if (lineElements.length > 0) {
      for (let i = 0; i < lineElements.length; i += 1) {
        const lineElement = lineElements[i];
        codeElement.appendChild(lineElement);
        codeElement.appendChild(document.createTextNode('\n'));
413 414
      }
    } else {
415
      codeElement.appendChild(documentFragment);
416 417
    }

418
    return codeElement;
419 420
  }

421
  static nodeToGFM(node, respectWhitespaceParam = false) {
422 423 424 425
    if (node.nodeType === Node.COMMENT_NODE) {
      return '';
    }

426 427 428
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent;
    }
429

Douwe Maan's avatar
Douwe Maan committed
430
    const respectWhitespace = respectWhitespaceParam || (node.nodeName === 'PRE' || node.nodeName === 'CODE');
431 432

    const text = this.innerGFM(node, respectWhitespace);
433

434
    if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
435 436 437
      return text;
    }

438 439
    for (const filter in gfmRules) {
      const rules = gfmRules[filter];
440

441 442
      for (const selector in rules) {
        const func = rules[selector];
443

444
        if (!nodeMatchesSelector(node, selector)) continue;
445

446 447 448 449 450 451 452 453 454 455 456
        let result;
        if (func.length === 2) {
          // if `func` takes 2 arguments, it depends on text.
          // if there is no text, we don't need to generate GFM for this node.
          if (text.length === 0) continue;

          result = func(node, text);
        } else {
          result = func(node);
        }

457
        if (result === false) continue;
Douwe Maan's avatar
Douwe Maan committed
458

459
        return result;
460
      }
461 462 463 464
    }

    return text;
  }
465

466
  static innerGFM(parentNode, respectWhitespace = false) {
467 468 469 470 471 472 473 474 475
    const nodes = parentNode.childNodes;

    const clonedParentNode = parentNode.cloneNode(true);
    const clonedNodes = Array.prototype.slice.call(clonedParentNode.childNodes, 0);

    for (let i = 0; i < nodes.length; i += 1) {
      const node = nodes[i];
      const clonedNode = clonedNodes[i];

476
      const text = this.nodeToGFM(node, respectWhitespace);
477 478 479

      // `clonedNode.replaceWith(text)` is not yet widely supported
      clonedNode.parentNode.replaceChild(document.createTextNode(text), clonedNode);
480
    }
481

482 483 484 485 486 487 488
    let nodeText = clonedParentNode.innerText || clonedParentNode.textContent;

    if (!respectWhitespace) {
      nodeText = nodeText.trim();
    }

    return nodeText;
489
  }
490
}
491

492 493 494 495 496
// Export CopyAsGFM as a global for rspec to access
// see /spec/features/copy_as_gfm_spec.rb
if (process.env.NODE_ENV !== 'production') {
  window.CopyAsGFM = CopyAsGFM;
}
497

498 499 500
export default function initCopyAsGFM() {
  return new CopyAsGFM();
}