-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable2json.js
232 lines (212 loc) · 6.69 KB
/
table2json.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
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
let domain = {}
let id = 1
document.documentElement.classList.add('table2json')
chrome.storage.sync.get([location.host], function(result) {
domain = result[location.host]
observeDOMChange()
})
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
domain = request
clearInsert()
sendResponse('success')
})
function clearInsert() {
Array.from(document.querySelectorAll('table-target')).forEach(node => {
const insertNode = node.querySelector('.export-button-wrap')
insertNode.remove()
})
}
function observeDOMChange() {
const observer = new MutationObserver(function(mutationList, observer) {
const tableElList = Array.from(document.querySelectorAll(domain.selector)).filter(node => !node.classList.contains('table-target'))
if (tableElList.length) {
tableElList.forEach(node => {
if (!node.classList.contains('table-target')) {
node.classList.add('table-target')
insertRowSelection(node)
node.parentElement.insertBefore(tableToolBar(node), node)
}
})
}
})
observer.observe(document.body, {
subtree: true, childList: true
})
}
function tableToolBar(tableEl) {
const toolBar = document.createElement('div')
toolBar.className = 'export-button-wrap'
toolBar.append(exportButton('转Object', export2obj, tableEl))
toolBar.append(exportButton('转Array', export2arr, tableEl))
toolBar.append(tableID(tableEl))
return toolBar
}
function insertRowSelection(tableEl) {
const colgroup = tableEl.querySelector('colgroup')
const col = document.createElement('col')
col.setAttribute('width', '30')
colgroup.prepend(col)
const thead = tableEl.querySelector('thead')
const tr = thead.querySelector('tr')
tr.prepend(createCheckbox('th', tableEl))
watchTableChange(tableEl)
}
function tbodyRowSelection(tableEl, observer) {
observer.disconnect()
const tbody = tableEl.querySelector('tbody')
const trList = tbody.querySelectorAll('tr')
trList.forEach(item => {
if (!item.getAttribute('inserted-checkbox')) {
item.setAttribute('inserted-checkbox', true)
item.prepend(createCheckbox('td'))
}
})
observer.observe(tableEl, {
childList: true,
subtree: true
})
}
function watchTableChange(tableEl) {
const observer = new MutationObserver((mutationList, observer) => {
tbodyRowSelection(tableEl, observer)
})
tbodyRowSelection(tableEl, observer)
}
function createCheckbox(tag, tableEl) {
const td = document.createElement(tag)
const input = document.createElement('input')
input.setAttribute('type', 'checkbox')
if (tableEl) {
const tbody = tableEl.querySelector('tbody')
input.addEventListener('change', (e) => {
const checkList = tbody.querySelectorAll('input[type=checkbox]')
checkList.forEach(check => check.checked = e.target.checked)
})
}
td.appendChild(input)
return td
}
function tableID(tableEl) {
const tableId = calcId()
tableEl.setAttribute('id', tableId)
const button = document.createElement('button')
button.classList.add('export-button')
button.innerHTML = '复制: ' + tableId
button.onclick = function () {
copy2clipboard(tableId)
}
return button
}
function calcId() {
const sort = 'NO' + id.toString().padStart(2, '0')
id++
if (id > 100) {
id = 1
}
return sort
}
function exportButton(name, fn, scope) {
const button = document.createElement('button')
button.classList.add('export-button')
button.innerText = name
button.onclick = function () {
fn(scope)
}
return button
}
function formatTr(trEl) {
return Array.prototype.slice.call(trEl.children).reduce((pre, th) => {
pre.push(th.innerText)
return pre
}, [])
}
function formatThead(tableEl) {
const thead = tableEl.querySelector('thead')
const tr = thead.querySelector('tr')
const propList = formatTr(tr)
const propIndex = propList.findIndex(prop => prop === domain.prop)
const labelIndex = propList.findIndex(prop => prop === domain.label)
return {
labelIndex,
propIndex
}
}
function formatBody(tableEl) {
const rowList = []
const tbody = tableEl.querySelector('tbody')
const checkboxList = tbody.querySelectorAll('input[type=checkbox]')
checkboxList.forEach(item => {
if (item.checked) {
rowList.push(formatTr(item.parentElement.parentElement))
}
})
return rowList
}
function export2obj(tableEl) {
const { labelIndex, propIndex } = formatThead(tableEl)
if (propIndex === -1) {
setTimeout(showNotification('error'), 2000)
return
}
const rowList = formatBody(tableEl)
const rowStrList = rowList.map(row => {
return row[labelIndex] ? ` ${row[propIndex]}: '', // ${row[labelIndex]}` : ` ${row[propIndex]}: '',`
})
rowStrList.unshift('{')
rowStrList.push('}')
const content = rowStrList.join('\n')
copy2clipboard(content)
}
function export2arr(tableEl) {
const { labelIndex, propIndex } = formatThead(tableEl)
if (propIndex === -1) {
setTimeout(showNotification('error'), 2000)
return
}
const rowList = formatBody(tableEl)
const columns = rowList.map(row => {
return {
label: row[labelIndex],
prop: row[propIndex]
}
})
const content = JSON.stringify(columns, null, 2)
copy2clipboard(content)
}
function copy2clipboard(content) {
console.log(content)
if (navigator.clipboard) {
navigator.clipboard.writeText(content)
.then(() => {
setTimeout(showNotification('success'), 2000)
})
.catch(err => {
// This can happen if the user denies clipboard permissions:
// 如果用户没有授权,则抛出异常
console.error('无法复制此文本:', err);
});
}
}
function showNotification(type) {
const typeMap = {
success: {
label: '成功',
value: '已复制到剪切板'
},
error: {
label: '错误',
value: `未找到 "${domain.prop}" 对应的列`
}
}
const wrapper = document.createElement('div')
wrapper.className = 'notification-wrapper'
const typeObj = typeMap[type]
wrapper.innerHTML = `
<div class="notification-title is-${type}">${typeObj.label}</div>
<div class="notification-content">${typeObj.value}</div>
`
document.body.append(wrapper)
return function() {
wrapper.remove()
}
}