-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathpopup.js
359 lines (331 loc) · 14 KB
/
popup.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
document.addEventListener('DOMContentLoaded', () => {
const ipElement = document.getElementById('ip')
const tokenElement = document.getElementById('token')
const showTipElement = document.getElementById('showTip')
const searchDocElement = document.getElementById('searchDoc')
const parentDocElement = document.getElementById('parentDoc')
const tagsElement = document.getElementById('tags')
const assetsElement = document.getElementById('assets')
const expElement = document.getElementById('exp')
const expGroupElement = document.getElementById('expGroup')
const expSpanElement = document.getElementById('expSpan')
const expBoldElement = document.getElementById('expBold')
const expItalicElement = document.getElementById('expItalic')
const languageElement = document.getElementById('language')
ipElement.addEventListener('change', () => {
let ip = ipElement.value;
// 去掉结尾的斜杆 https://github.com/siyuan-note/siyuan/issues/11478
for (let i = ip.length - 1; i >= 0; i--) {
if ('/' === ip[i]) {
ip = ip.substring(0, i)
} else {
break
}
}
ipElement.value = ip
chrome.storage.sync.set({
ip: ipElement.value,
})
})
tokenElement.addEventListener('change', () => {
chrome.storage.sync.set({
token: tokenElement.value,
})
updateSearch()
})
showTipElement.addEventListener('change', () => {
chrome.storage.sync.set({
showTip: showTipElement.checked,
})
})
searchDocElement.addEventListener('change', () => {
chrome.storage.sync.set({
searchKey: searchDocElement.value,
})
updateSearch()
})
parentDocElement.addEventListener('change', () => {
const selectElement = document.getElementById('parentDoc');
const selectedOption = selectElement.options[selectElement.selectedIndex];
const notebook = selectedOption.getAttribute('data-notebook');
const parentDoc = selectedOption.getAttribute('data-parent');
chrome.storage.sync.set({
notebook: notebook,
parentDoc: parentDoc,
parentHPath: selectedOption.innerText,
})
})
tagsElement.addEventListener('change', () => {
tagsElement.value = tagsElement.value.replace(/#/g, '')
chrome.storage.sync.set({
tags: tagsElement.value,
})
})
assetsElement.addEventListener('change', () => {
chrome.storage.sync.set({
assets: assetsElement.checked,
})
})
expSpanElement.addEventListener('change', () => {
chrome.storage.sync.set({
expSpan: expSpanElement.checked,
})
})
expBoldElement.addEventListener('change', () => {
chrome.storage.sync.set({
expBold: expBoldElement.checked,
})
})
expItalicElement.addEventListener('change', () => {
chrome.storage.sync.set({
expItalic: expItalicElement.checked,
})
})
expElement.addEventListener('change', function () {
if (expElement.checked) {
expGroupElement.style.display = 'block';
} else {
expGroupElement.style.display = 'none';
}
});
languageElement.addEventListener('change', () => {
const langCode = languageElement.value;
console.log("langCode="+langCode);
siyuanLoadLanguageFile(langCode, (data) => {
siyuanTranslateDOM(data);
});
chrome.storage.sync.set({
langCode: langCode,
})
})
const eyeElement = document.querySelector('.b3-icon')
eyeElement.addEventListener('click', () => {
if (tokenElement.getAttribute("type") === "password") {
tokenElement.setAttribute("type", "text")
eyeElement.innerHTML = '<path d="M21.418 17.655l-1.6-1.6q0.945-2.582-0.982-4.291t-4.182-0.873l-1.6-1.6q0.618-0.4 1.382-0.582t1.564-0.182q2.582 0 4.382 1.8t1.8 4.382q0 0.8-0.2 1.582t-0.564 1.364zM26.109 22.346l-1.455-1.455q1.782-1.309 3.109-2.927t1.945-3.255q-1.818-4.036-5.455-6.382t-7.891-2.345q-1.527 0-3.127 0.291t-2.509 0.691l-1.673-1.709q1.273-0.582 3.255-1.018t3.873-0.436q5.2 0 9.509 2.964t6.309 7.945q-0.945 2.327-2.436 4.255t-3.455 3.382zM28.218 30.564l-6.109-6q-1.273 0.509-2.873 0.782t-3.236 0.273q-5.309 0-9.636-2.964t-6.364-7.945q0.727-1.891 2.018-3.691t3.145-3.436l-4.582-4.582 1.527-1.564 27.527 27.527zM6.655 9.109q-1.345 0.982-2.6 2.582t-1.8 3.018q1.855 4.036 5.582 6.382t8.455 2.345q1.2 0 2.364-0.145t1.745-0.436l-2.327-2.327q-0.4 0.182-0.982 0.273t-1.091 0.091q-2.545 0-4.364-1.782t-1.818-4.4q0-0.545 0.091-1.091t0.273-0.982z"></path>'
} else {
tokenElement.setAttribute("type", "password")
eyeElement.innerHTML = '<path d="M16 22.182q2.582 0 4.382-1.8t1.8-4.382-1.8-4.382-4.382-1.8-4.382 1.8-1.8 4.382 1.8 4.382 4.382 1.8zM16 20.073q-1.709 0-2.891-1.182t-1.182-2.891 1.182-2.891 2.891-1.182 2.891 1.182 1.182 2.891-1.182 2.891-2.891 1.182zM16 26.909q-5.309 0-9.6-3.018t-6.4-7.891q2.109-4.873 6.4-7.891t9.6-3.018 9.6 3.018 6.4 7.891q-2.109 4.873-6.4 7.891t-9.6 3.018zM16 24.727q4.4 0 8.091-2.382t5.618-6.345q-1.927-3.964-5.618-6.345t-8.091-2.382-8.091 2.382-5.655 6.345q1.964 3.964 5.655 6.345t8.091 2.382z"></path>'
}
})
const sendElement = document.getElementById('send')
sendElement.addEventListener('click', () => {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
chrome.scripting.executeScript({
target: {tabId: tabs[0].id},
func: siyuanGetReadability,
args: [tabs[0].id],
}, function () {
window.close();
})
});
})
chrome.storage.sync.get({
langCode: siyuanGetDefaultLangCode(),
ip: 'http://127.0.0.1:6806',
showTip: true,
token: '',
searchKey: '',
notebook: '',
parentDoc: '',
parentHPath: '',
tags: '',
assets: true,
expSpan: true,
expBold: false,
expItalic: false,
}, async function (items) {
siyuanLoadLanguageFile(items.langCode, (data) => {
siyuanTranslateDOM(data); // 在这里使用加载的数据
languageElement.value = items.langCode;
});
ipElement.value = items.ip || 'http://127.0.0.1:6806'
tokenElement.value = items.token || ''
showTipElement.checked = items.showTip
searchDocElement.value = items.searchKey || ''
parentDocElement.setAttribute("data-notebook", items.notebook)
parentDocElement.setAttribute("data-parent", items.parentDoc)
parentDocElement.setAttribute("data-parenthpath", items.parentHPath)
tagsElement.value = items.tags || ''
assetsElement.checked = items.assets
expSpanElement.checked = items.expSpan
expBoldElement.checked = items.expBold
expItalicElement.checked = items.expItalic
updateSearch()
})
})
const updateSearch = () => {
const ipElement = document.getElementById('ip')
const tokenElement = document.getElementById('token')
const searchDocElement = document.getElementById('searchDoc')
const parentDocElement = document.getElementById('parentDoc')
fetch(ipElement.value + '/api/filetree/searchDocs', {
method: 'POST',
redirect: "manual",
headers: {
'Authorization': 'Token ' + tokenElement.value,
},
body: JSON.stringify({
"k": searchDocElement.value,
"flashcard": false
})
}).then((response) => {
if (response.status !== 200) {
document.getElementById('log').innerHTML = "Authentication failed"
} else {
document.getElementById('log').innerHTML = ""
}
return response.json()
}).then((response) => {
if (0 !== response.code) {
document.getElementById('log').innerHTML = "Search docs failed"
return
}
let optionsHTML = ''
response.data.forEach(doc => {
const parentDoc = doc.path.substring(doc.path.toString().lastIndexOf('/') + 1).replace(".sy", '')
let selected = ""
if (parentDocElement.dataset.notebook === doc.box && parentDocElement.dataset.parent === parentDoc &&
parentDocElement.dataset.parenthpath === doc.hPath) {
selected = "selected";
}
optionsHTML += `<option ${selected} data-notebook="${doc.box}" data-parent="${parentDoc}">${escapeHtml(doc.hPath)}</option>`
})
parentDocElement.innerHTML = optionsHTML
if (parentDocElement.selectedOptions && parentDocElement.selectedOptions.length > 0) {
let selected = parentDocElement.querySelector('option[selected]')
if (!selected) {
selected = parentDocElement.selectedOptions[0]
chrome.storage.sync.set({
notebook: selected.getAttribute("data-notebook"),
parentDoc: selected.getAttribute("data-parent"),
parentHPath: selected.innerText,
})
}
} else {
chrome.storage.sync.set({
notebook: '',
parentDoc: '',
parentHPath: ''
})
}
})
}
const escapeHtml = (unsafe) => {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const siyuanGetReadability = async (tabId) => {
try {
siyuanShowTipByKey("tip_clipping", 60 * 1000)
} catch (e) {
alert(chrome.i18n.getMessage("tip_first_time"));
window.location.reload();
return;
}
try {
// 浏览器剪藏扩展剪藏某些网页代码块丢失注释 https://github.com/siyuan-note/siyuan/issues/5676
document.querySelectorAll(".hljs-comment").forEach(item => {
item.classList.remove("hljs-comment")
item.classList.add("hljs-cmt")
})
// 重构并合并Readability前处理 https://github.com/siyuan-note/siyuan/issues/13306
const clonedDoc = await siyuanGetCloneNode(document);
const article = new Readability(clonedDoc, {
keepClasses: true,
charThreshold: 16,
debug: true
}).parse()
const tempElement = document.createElement('div')
tempElement.innerHTML = article.content
// console.log(article)
siyuanSendUpload(tempElement, tabId, undefined, "article", article, window.location.href)
siyuanClearTip()
} catch (e) {
console.error(e)
siyuanShowTip(e.message, 7 * 1000)
}
}
// Add i18n support https://github.com/siyuan-note/siyuan/issues/13559
let siyuanLangData = null;
let siyuanLangCode = null;
function siyuanGetDefaultLangCode() {
const langCode = navigator.language || navigator.userLanguage || chrome.runtime.getManifest().default_locale;
const normalizedLangCode = langCode.replace('-', '_');
return normalizedLangCode;
}
// 合并当前语言和英语(en)翻译的函数
async function siyuanMergeTranslations(translations, langCode) {
// 默认语言是英语(en)
const defaultLangCode = 'en';
// 加载英语(en)翻译文件
let defaultTranslations = {};
// 如果当前语言不是英语,则加载英语翻译文件
if (langCode !== defaultLangCode) {
const extensionId = chrome.runtime.id;
const enTranslationFile = `chrome-extension://${extensionId}/_locales/en/messages.json`;
try {
// 异步加载英语翻译文件
const response = await fetch(enTranslationFile);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const enData = await response.json(); // 解析JSON
defaultTranslations = enData; // 保存英语翻译数据
} catch (err) {
console.error("Failed to load English translation:", err);
}
}
// 合并当前语言翻译和英语翻译,缺失的字段使用英语翻译
const merged = { ...defaultTranslations, ...translations };
return merged;
}
async function siyuanLoadLanguageFile(langCode, callback) {
// 检查是否已经加载过数据
if (siyuanLangData && siyuanLangCode === langCode) {
// 如果已经加载,直接调用回调并传递数据
callback(siyuanLangData);
return;
}
// 先加载当前语言的翻译文件
try {
const extensionId = chrome.runtime.id;
const translationFile = `chrome-extension://${extensionId}/_locales/${langCode}/messages.json`;
const response = await fetch(translationFile);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json(); // 解析JSON
// 加载成功,检查并补充缺失的翻译
// 先把加载的翻译数据保存在全局变量中
const mergedData = await siyuanMergeTranslations(data, langCode); // 等待合并翻译
siyuanLangData = mergedData;
siyuanLangCode = langCode;
// 调用回调并传递数据
callback(mergedData);
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
}
function siyuanTranslateDOM(translations) {
const elements = document.querySelectorAll('[data-i18n]');
elements.forEach(element => {
const key = element.getAttribute('data-i18n');
const translation = translations[key].message;
if (translation) {
if (element.placeholder !== undefined) {
// 翻译 placeholder 属性
element.placeholder = translation;
} else {
// 翻译 textContent
element.textContent = translation;
}
} else {
console.warn(`siyuanTranslateDOM Missing translation for key: ${key}`);
}
});
}