-
Notifications
You must be signed in to change notification settings - Fork 111
/
script.js
82 lines (72 loc) · 2.32 KB
/
script.js
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
var editor = document.getElementById("editor")
function columnWidth(rows, columnIndex) {
return Math.max.apply(null, rows.map(function(row) {
return ('' + row[columnIndex]).length
}))
}
function looksLikeTable(data) {
return true
}
editor.addEventListener("paste", function(event) {
var clipboard = event.clipboardData
var data = clipboard.getData('text/plain').trim()
if(looksLikeTable(data)) {
event.preventDefault()
}else{
return
}
var rows = data.split((/[\u0085\u2028\u2029]|\r\n?/g)).map(function(row) {
row = row.replace('\n', ' ')
return row.split("\t")
})
var colAlignments = []
var columnWidths = rows[0].map(function(column, columnIndex) {
var alignment = "l"
var re = /^(\^[lcr])/i
var m = column.match(re)
if (m) {
var align = m[1][1].toLowerCase()
if (align === "c") {
alignment = "c"
} else if (align === "r") {
alignment = "r"
}
}
colAlignments.push(alignment)
column = column.replace(re, "")
rows[0][columnIndex] = column
return columnWidth(rows, columnIndex)
})
var markdownRows = rows.map(function(row, rowIndex) {
// | Name | Title | Email Address |
// |--------------|-------|----------------|
// | Jane Atler | CEO | [email protected] |
// | John Doherty | CTO | [email protected] |
// | Sally Smith | CFO | [email protected] |
return "| " + row.map(function(column, index) {
return column + Array(columnWidths[index] - column.length + 1).join(" ")
}).join(" | ") + " |"
row.map
})
markdownRows.splice(1, 0, "|" + columnWidths.map(function(width, index) {
var prefix = ""
var postfix = ""
var adjust = 0
var alignment = colAlignments[index]
if (alignment === "r") {
postfix = ":"
adjust = 1
} else if (alignment == "c") {
prefix = ":"
postfix = ":"
adjust = 2
}
return prefix + Array(columnWidths[index] + 3 - adjust).join("-") + postfix
}).join("|") + "|")
// https://www.w3.org/TR/clipboard-apis/#the-paste-action
// When pasting, the drag data store mode flag is read-only, hence calling
// setData() from a paste event handler will not modify the data that is
// inserted, and not modify the data on the clipboard.
event.target.value = markdownRows.join("\n")
return false
})