summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/copy_as_gfm.js.es6
blob: 0059dc3f60f59e7b2612865f78d7ac982cbeedf0 (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
306
307
308
309
310
311
312
313
314
/* eslint-disable class-methods-use-this */
/*jshint esversion: 6 */

/*= require lib/utils/common_utils */


(() => {
  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: {
      'input[type=checkbox].task-list-item-checkbox'(el, text) {
        return `[${el.checked ? 'x' : ' '}]`;
      }
    },
    ReferenceFilter: {
      '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: {
      'ul.section-nav'(el, text) {
        return '[[_TOC_]]';
      },
    },
    EmojiFilter: {
      'img.emoji'(el, text) {
        return el.getAttribute('alt');
      },
    },
    ImageLinkFilter: {
      'a.no-attachment-icon'(el, text) {
        return text;
      },
    },
    VideoLinkFilter: {
      '.video-container'(el, text) {
        let videoEl = el.querySelector('video');
        if (!videoEl) return false;

        return CopyAsGFM.nodeToGFM(videoEl);
      },
      'video'(el, text) {
        return `![${el.dataset.title}](${el.getAttribute('src')})`;
      },
    },
    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 + '`$';
      },
      'span.katex-display span.katex-mathml'(el, text) {
        let mathAnnotation = el.querySelector('annotation[encoding="application/x-tex"]');
        if (!mathAnnotation) return false;

        return '```math\n' + CopyAsGFM.nodeToGFM(mathAnnotation)  + '\n```';
      },
      'span.katex-mathml'(el, text) {
        let mathAnnotation = el.querySelector('annotation[encoding="application/x-tex"]');
        if (!mathAnnotation) return false;

        return '$`' + CopyAsGFM.nodeToGFM(mathAnnotation) + '`$';
      },
      'span.katex-html'(el, text) {
        // 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();
      }
    },
    SyntaxHighlightFilter: {
      'pre.code.highlight'(el, text) {
        let lang = el.getAttribute('lang');
        if (lang === 'plaintext') {
          lang = '';
        }
        return '```' + lang + '\n' + text.trim() + '\n```';
      },
      'pre > code'(el, text) {
         // Don't wrap code blocks in ``
        return text;
      },
    },
    MarkdownFilter: {
      'code'(el, text) {
        let backtickCount = 1;
        let backtickMatch = text.match(/`+/);
        if (backtickMatch) {
          backtickCount = backtickMatch[0].length + 1;
        }

        let backticks = new Array(backtickCount + 1).join('`');
        let spaceOrNoSpace = backtickCount > 1 ? ' ' : '';

        return backticks + spaceOrNoSpace + text + spaceOrNoSpace + backticks;
      },
      'blockquote'(el, text) {
        return text.trim().split('\n').map((s) => `> ${s}`.trim()).join('\n');
      },
      'img'(el, text) {
        return `![${el.getAttribute('alt')}](${el.getAttribute('src')})`;
      },
      '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) {
        let lines = text.trim().split('\n');
        let firstLine = '- ' + lines.shift();
        // Add two spaces to the front of subsequent list items lines, or leave the line entirely blank.
        let nextLines = lines.map(function(s) {
          if (s.trim().length === 0) {
            return '';
          } else {
            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}`;
      },
      'hr'(el, text) {
        return '-----';
      },
      'table'(el, text) {
        let theadText = CopyAsGFM.nodeToGFM(el.querySelector('thead'));
        let tbodyText = CopyAsGFM.nodeToGFM(el.querySelector('tbody'));

        return theadText + tbodyText;
      },
      'thead'(el, text) {
        let cells = _.map(el.querySelectorAll('th'), function(cell) {
          let chars = CopyAsGFM.nodeToGFM(cell).trim().length;

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

          chars = Math.max(chars, 0);

          let middle = new Array(chars + 1).join('-');

          return before + middle + after;
        });

        return text + `| ${cells.join(' | ')} |`;
      },
      'tr'(el, text) {
        let cells = _.map(el.querySelectorAll('td, th'), function(cell) {
          return CopyAsGFM.nodeToGFM(cell).trim();
        });
        return `| ${cells.join(' | ')} |`;
      },
    }
  };

  class CopyAsGFM {
    constructor() {
      $(document).on('copy', '.md, .wiki', this.handleCopy.bind(this));
      $(document).on('paste', '.js-gfm-input', this.handlePaste.bind(this));
    }

    handleCopy(e) {
      let clipboardData = e.originalEvent.clipboardData;
      if (!clipboardData) return;

      let documentFragment = window.gl.utils.getSelectedFragment();
      if (!documentFragment) return;

      e.preventDefault();
      clipboardData.setData('text/plain', documentFragment.textContent);

      let gfm = CopyAsGFM.nodeToGFM(documentFragment);
      clipboardData.setData('text/x-gfm', gfm);
    }

    handlePaste(e) {
      let clipboardData = e.originalEvent.clipboardData;
      if (!clipboardData) return;

      let gfm = clipboardData.getData('text/x-gfm');
      if (!gfm) return;

      e.preventDefault();

      window.gl.utils.insertText(e.target, gfm);
    }

    static nodeToGFM(node) {
      if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent;
      }

      let text = this.innerGFM(node);

      if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
        return text;
      }

      for (let filter in gfmRules) {
        let rules = gfmRules[filter];

        for (let selector in rules) {
          let func = rules[selector];

          if (!window.gl.utils.nodeMatchesSelector(node, selector)) continue;

          let result = func(node, text);
          if (result === false) continue;

          return result;
        }
      }

      return text;
    }

    static innerGFM(parentNode) {
      let nodes = parentNode.childNodes;

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

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

        let text = this.nodeToGFM(node);

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

      return clonedParentNode.innerText || clonedParentNode.textContent;
    }
  }

  window.gl = window.gl || {};
  window.gl.CopyAsGFM = CopyAsGFM;

  new CopyAsGFM();
})();