|
14 | 14 |
|
15 | 15 | var diffJson = null; |
16 | 16 | var defaultTarget = "body"; |
| 17 | + var currentSelectionColumnId = -1; |
17 | 18 |
|
18 | 19 | function Diff2HtmlUI(config) { |
19 | 20 | var cfg = config || {}; |
|
23 | 24 | } else if (cfg.json) { |
24 | 25 | diffJson = cfg.json; |
25 | 26 | } |
| 27 | + |
| 28 | + this._initSelection(); |
26 | 29 | } |
27 | 30 |
|
28 | 31 | Diff2HtmlUI.prototype.draw = function(targetId, config) { |
|
130 | 133 | }); |
131 | 134 | }; |
132 | 135 |
|
| 136 | + Diff2HtmlUI.prototype._initSelection = function() { |
| 137 | + var body = $('body'); |
| 138 | + var that = this; |
| 139 | + |
| 140 | + body.on('mousedown', '.d2h-diff-table', function(event) { |
| 141 | + var target = $(event.target); |
| 142 | + var table = target.closest('.d2h-diff-table'); |
| 143 | + |
| 144 | + if (target.closest('.d2h-code-line,.d2h-code-side-line').length) { |
| 145 | + table.removeClass('selecting-left'); |
| 146 | + table.addClass('selecting-right'); |
| 147 | + currentSelectionColumnId = 1; |
| 148 | + } else if (target.closest('.d2h-code-linenumber,.d2h-code-side-linenumber').length) { |
| 149 | + table.removeClass('selecting-right'); |
| 150 | + table.addClass('selecting-left'); |
| 151 | + currentSelectionColumnId = 0; |
| 152 | + } |
| 153 | + }); |
| 154 | + |
| 155 | + body.on('copy', '.d2h-diff-table', function(event) { |
| 156 | + var clipboardData = event.originalEvent.clipboardData; |
| 157 | + var text = that._getSelectedText(); |
| 158 | + clipboardData.setData('text', text); |
| 159 | + event.preventDefault(); |
| 160 | + }); |
| 161 | + }; |
| 162 | + |
| 163 | + |
| 164 | + Diff2HtmlUI.prototype._getSelectedText = function() { |
| 165 | + var sel = window.getSelection(); |
| 166 | + var range = sel.getRangeAt(0); |
| 167 | + var doc = range.cloneContents(); |
| 168 | + var nodes = doc.querySelectorAll('tr'); |
| 169 | + var text = ''; |
| 170 | + var idx = currentSelectionColumnId; |
| 171 | + |
| 172 | + if (nodes.length === 0) { |
| 173 | + text = doc.textContent; |
| 174 | + } else { |
| 175 | + [].forEach.call(nodes, function(tr, i) { |
| 176 | + var td = tr.cells[tr.cells.length === 1 ? 0 : idx]; |
| 177 | + text += (i ? '\n' : '') + td.textContent.replace(/(?:\r\n|\r|\n)/g, ''); |
| 178 | + }); |
| 179 | + } |
| 180 | + |
| 181 | + return text; |
| 182 | + }; |
| 183 | + |
133 | 184 | module.exports.Diff2HtmlUI = Diff2HtmlUI; |
134 | 185 |
|
135 | 186 | // Expose diff2html in the browser |
|
0 commit comments