-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable-markdown.user.js
More file actions
238 lines (203 loc) · 7.6 KB
/
table-markdown.user.js
File metadata and controls
238 lines (203 loc) · 7.6 KB
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
// ==UserScript==
// @name Table to Markdown Copier
// @name:vi Chép bảng HTML qua dạng markdown
// @namespace https://github.com/hotmit/table-markdown-userscript
// @version 1.0.1
// @description Convert html table to markdown format
// @description:vi Chuyển bảng html (table) qua dạng markdown.
// @author Du Dang
// @include http://*/*
// @include https://*/*
// @grant none
// @require https://code.jquery.com/jquery-3.1.1.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.16/clipboard.min.js
// @license MIT
// ==/UserScript==
(function($) {
'use strict';
// max cell with in chars count
var MAX_COL_SIZE = 80;
var Str = {};
$(function(){
var lastThreeKeys = [], combinationLength = 3;
// region [ Display Control ]
/**
* Insert the "MD" button to all the last cell in the header of
* all the tables in the current page.
* @private
*/
function displayTableControl(){
$('table').each(function(i, e){
var id = 'btn-copy-md-' + i, $tb = $(e),
$btnMd = $('<button type="button" class="convert-to-markdown btn btn-primary" />'),
$lastCell = $tb.find('tr:first').find('td:last, th:last').first();
$btnMd.css({
height: '20px',
width: '30px',
'background-color': '#81358c',
color: '#fff',
padding: '0'
}).text('MD').attr('id', id);
// copy markdown content to the clipboard
new Clipboard('#' + id, {
text: function() {
return convertTableToMd($btnMd);
}
});
$lastCell.append($btnMd);
});
//$('.convert-to-markdown').click(convertTableToMd);
}
// endregion
// region [ Code ]
/**
* Extract the data from the table. Return array of row of data along with
* the maximum length for each column.
*
* @param $table
* @returns {{maxLengths: Array, tableData: Array}}
* @private
*/
function getData($table){
var maxLengths = [], tableData = [];
function setMax(index, length){
// create new column if does not exist
while(index >= maxLengths.length){
maxLengths.push(0);
}
maxLengths[index] = Math.max(maxLengths[index], length);
}
$table.find('tr').each(function(trIndex, tr){
var $tr = $(tr), row = [], offset = 0;
$tr.find('td, th').each(function(i, td){
var $td = $(td), text = getText($td, trIndex), tl = text.length,
index = i + offset, colspan = $td.attr('colspan');
setMax(index, tl);
row.push(text);
if (colspan && $.isNumeric(colspan) && Number(colspan) > 1){
colspan = Number(colspan);
offset += colspan - 1;
for (var k=0; k<colspan; k++){
row.push('');
}
}
});
tableData.push(row);
});
return {
maxLengths: maxLengths,
tableData: tableData
};
}
/**
* Convert the data from getData to actual markdown content.
*
* @param $btn - The "MD" button housed inside the table.
* @returns {string} - The markdown table content
* @private
*/
function convertTableToMd($btn){
var md = '', $table = $btn.parents('table').first(), data = getData($table), i, k,
maxLengths = data.maxLengths;
for (i=0; i<data.tableData.length; i++){
var row = data.tableData[i], rowMd = '| ', sepMd = '| ';
for(k=0; k<row.length; k++){
var rowWidth = Math.min(maxLengths[k], MAX_COL_SIZE),
text = Str.padRight(row[k], ' ', rowWidth);
rowMd += text + ' | ';
// add header separator
if (i === 0){
sepMd += Str.repeat(' ', rowWidth) + ' | ';
}
}
if (rowMd.length > 2){
md += Str.trim(rowMd) + "\n";
if (sepMd.length > 2){
md += Str.trim(sepMd).replace(/ /g, '-') + "\n";
}
}
}
md += getReferenceLink($table);
// copied indicator
$btn.css('background-color', '#6AB714');
setTimeout(function(){
$btn.css('background-color', '#81358c');
}, 3000);
return md;
}
/**
* Generate markdown link to the table for future reference.
*
* @param $table
* @returns {*}
*/
function getReferenceLink($table) {
var refLink, $anchor, refId = $table.attr('id'), href = location.href;
if(!refId) {
$anchor = $table.parents('[id]').first();
if ($anchor.length){
refId = $anchor.attr('id');
}
}
if (refId) {
if (href.indexOf('#') != -1) {
refLink = href.replace(/#.+/, '#' + refId);
}
else {
refLink = href + '#' + refId;
}
}
// if no id link, then just use the main link as reference
refLink = refLink || href;
return '[Table Source](' + refLink + ')';
}
/**
* Clean up the text for the cell content. Like remove new line so it doesn't break the table.
*
* @param $td
* @param trIndex
* @returns {string|*}
*/
function getText($td, trIndex) {
var text = $td.text();
if (trIndex === 0){
// remove the MD link from the text
text = text.replace(/MD$/, '');
}
text = text.replace("\n", '');
text = text.replace(/\s/g, ' ');
return Str.trim(text);
}
// endregion
// region [ Capture shortcut keys ]
// Activate Markdown Converter Interface
// => Shift, Shift, T (3 key strokes as a sequence, NOT press all together)
$(document).on('keydown', function(e) {
lastThreeKeys.push(e.which);
lastThreeKeys = lastThreeKeys.slice(-combinationLength);
if (lastThreeKeys.toString() == '16,16,84') {
displayTableControl();
e.preventDefault();
return false;
}
});
// endregion
// uncomment for dev
// displayTableControl();
}); //end jqReady
// region [ Str Lib ]
Str.trim = function (s) {
return s.replace(/^\s+/, '').replace(/\s+$/, '');
};
Str.padRight = function(s, padStr, totalLength){
return s.length >= totalLength ? s : s + Str.repeat(padStr, (totalLength-s.length)/padStr.length);
};
Str.repeat = function(s, count) {
var newS = "", i;
for (i=0; i<count; i++) {
newS += s;
}
return newS;
};
// endregion
})(jQuery.noConflict(true));