forked from siyuan-note/siyuan-chrome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
205 lines (185 loc) · 6.44 KB
/
content.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
document.addEventListener('DOMContentLoaded', function () {
chrome.runtime.onMessage.addListener(
async (request, sender, sendResponse) => {
if ('tip' === request.func && request.tip) {
siyuanShowTip(request.msg)
return
}
if ('copy2Clipboard' === request.func) {
copyToClipboard(request.data)
return
}
if ('copy' !== request.func) {
return
}
siyuanShowTip('Clipping, please wait a moment...')
const selection = window.getSelection()
if (selection && 0 < selection.rangeCount) {
const range = selection.getRangeAt(0)
const tempElement = document.createElement('div')
tempElement.appendChild(range.cloneContents())
siyuanSendUpload(tempElement, request.tabId, request.srcUrl, "part")
}
})
const copyToClipboard = (textToCopy) => {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(textToCopy)
}
let textArea = document.createElement('textarea')
textArea.value = textToCopy
textArea.style.position = 'fixed'
textArea.style.left = '-999999px'
textArea.style.top = '-999999px'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
return new Promise((res, rej) => {
document.execCommand('copy') ? res() : rej()
textArea.remove()
})
}
})
const siyuanShowTip = (msg, timeout) => {
let messageElement = document.getElementById('siyuanmessage')
if (!messageElement) {
document.body.insertAdjacentHTML('afterend', `<div style=" position:fixed;top: 0;z-index: 999999999;transform: translate3d(0, -100px, 0);opacity: 0;transition: opacity 0.15s cubic-bezier(0, 0, 0.2, 1) 0ms, transform 0.15s cubic-bezier(0, 0, 0.2, 1) 0ms;width: 100%;align-items: center;justify-content: center;height: 0;display: flex;" id="siyuanmessage">
<div style="line-height: 20px;border-radius: 4px;padding: 8px 16px;color: #fff;font-size: inherit;background-color: #4285f4;box-sizing: border-box;box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2), 0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12);transition: transform 0.15s cubic-bezier(0, 0, 0.2, 1) 0ms;transform: scale(0.8);top: 16px;position: absolute;word-break: break-word;max-width: 80vw;"></div></div>`)
messageElement = document.getElementById('siyuanmessage')
}
messageElement.style.transform = 'translate3d(0, 0, 0)'
messageElement.style.opacity = '1'
messageElement.firstElementChild.innerHTML = msg
if (!timeout) {
timeout = 3000
}
setTimeout(() => {
siyuanClearTip()
}, timeout)
}
const siyuanClearTip = () => {
let messageElement = document.getElementById('siyuanmessage')
if (!messageElement) {
return
}
messageElement.style.transform = 'translate3d(0, -100px, 0)'
messageElement.style.opacity = '0'
}
const siyuanConvertBlobToBase64 = (blob) => new Promise((resolve, reject) => {
const reader = new FileReader
reader.onerror = reject
reader.onload = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
const siyuanSendUpload = async (tempElement, tabId, srcUrl, type, article, href) => {
let srcList = []
if (srcUrl) {
srcList.push(srcUrl)
}
const images = tempElement.querySelectorAll('img')
images.forEach(item => {
let src = item.getAttribute('src')
if (!src) {
return
}
// 处理使用 data-original 属性的情况 https://github.com/siyuan-note/siyuan/issues/11826
let dataOriginal = item.getAttribute('data-original')
if (dataOriginal) {
if (!src || !src.endsWith('.gif')) {
src = dataOriginal
}
}
if ('https:' === window.location.protocol && src.startsWith('http:')) {
src = src.replace('http:', 'https:')
item.setAttribute('src', src)
}
srcList.push(src)
})
const files = {}
srcList = [...new Set(srcList)]
let fetchFileErr = false;
for (let i = 0; i < srcList.length; i++) {
let src = srcList[i]
const msgSrc = src.length > 64 ? src.substring(0, 64) + '...' : src
siyuanShowTip('Clipping images [' + msgSrc + '], please wait a moment...')
let response;
try {
// Wikipedia 使用图片原图 https://github.com/siyuan-note/siyuan/issues/11640
if (-1 !== src.indexOf('wikipedia/commons/thumb/')) {
let idx = src.lastIndexOf('.')
let ext = src.substring(idx)
if (0 < src.indexOf('.svg.png')) {
ext = '.svg'
}
idx = src.indexOf(ext + '/')
if (0 < idx) {
src = src.substring(0, idx + ext.length)
src = src.replace('/commons/thumb/', '/commons/')
}
}
response = await fetch(src)
} catch (e) {
console.warn("fetch [" + src + "] failed", e)
fetchFileErr = true;
continue
}
const image = await response.blob()
files[escape(src)] = {
type: image.type,
data: await siyuanConvertBlobToBase64(image),
}
}
chrome.storage.sync.get({
ip: 'http://127.0.0.1:6806',
showTip: true,
token: '',
notebook: '',
}, function (items) {
if (!items.token) {
siyuanShowTip('Please config API token before clipping content 剪藏前请先配置 API token')
return
}
let title = article && article.title ? article.title : "";
let siteName = article && article.siteName ? article.siteName : "";
let excerpt = article && article.excerpt ? article.excerpt : "";
const msgJSON = {
fetchFileErr,
files: files,
dom: tempElement.innerHTML,
api: items.ip,
token: items.token,
notebook: items.notebook,
tip: items.showTip,
title: title,
siteName: siteName,
excerpt: excerpt,
href,
type,
tabId,
};
const jsonStr = JSON.stringify(msgJSON);
const jsonBlob = new Blob([jsonStr], {type: "application/json"});
const dataURL = URL.createObjectURL(jsonBlob);
chrome.runtime.sendMessage({func: 'upload-copy', dataURL: dataURL})
})
}
let toggle = false;
let scrollTimer;
const scrollTo1 = (callback) => {
const onScroll = function () {
// console.log(window.innerHeight, window.scrollY)
if (0 >= window.scrollY || window.innerHeight / 2 > window.scrollY) {
window.removeEventListener('scroll', onScroll)
callback()
}
}
window.addEventListener('scroll', onScroll)
onScroll()
toggle = !toggle;
if (toggle) {
scrollTimer = setInterval(function () {
window.scrollBy(0, -window.innerHeight);
}, 666);
} else {
clearInterval(scrollTimer);
}
}