-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
event.js
269 lines (229 loc) · 7.92 KB
/
event.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
const shortcuts = {
'[': () => window.history.back(),
']': () => window.history.forward(),
'-': () => zoomOut(),
'=': () => zoomIn(),
'+': () => zoomIn(),
0: () => setZoom('100%'),
r: () => window.location.reload(),
ArrowUp: () => scrollTo(0, 0),
ArrowDown: () => scrollTo(0, document.body.scrollHeight),
};
function setZoom(zoom) {
const html = document.getElementsByTagName('html')[0];
html.style.zoom = zoom;
window.localStorage.setItem('htmlZoom', zoom);
}
function zoomCommon(zoomChange) {
const currentZoom = window.localStorage.getItem('htmlZoom') || '100%';
setZoom(zoomChange(currentZoom));
}
function zoomIn() {
zoomCommon(currentZoom => `${Math.min(parseInt(currentZoom) + 10, 200)}%`);
}
function zoomOut() {
zoomCommon(currentZoom => `${Math.max(parseInt(currentZoom) - 10, 30)}%`);
}
function handleShortcut(event) {
if (shortcuts[event.key]) {
event.preventDefault();
shortcuts[event.key]();
}
}
// Judgment of file download.
function isDownloadLink(url) {
// prettier-ignore
const fileExtensions = [
'3gp', '7z', 'ai', 'apk', 'avi', 'bmp', 'csv', 'dmg', 'doc', 'docx',
'fla', 'flv', 'gif', 'gz', 'gzip', 'ico', 'iso', 'indd', 'jar', 'jpeg',
'jpg', 'm3u8', 'mov', 'mp3', 'mp4', 'mpa', 'mpg', 'mpeg', 'msi', 'odt',
'ogg', 'ogv', 'pdf', 'png', 'ppt', 'pptx', 'psd', 'rar', 'raw',
'svg', 'swf', 'tar', 'tif', 'tiff', 'ts', 'txt', 'wav', 'webm', 'webp',
'wma', 'wmv', 'xls', 'xlsx', 'xml', 'zip', 'json', 'yaml', '7zip', 'mkv',
];
const downloadLinkPattern = new RegExp(`\\.(${fileExtensions.join('|')})$`, 'i');
return downloadLinkPattern.test(url);
}
document.addEventListener('DOMContentLoaded', () => {
const tauri = window.__TAURI__;
const appWindow = tauri.window.getCurrentWindow();
const invoke = tauri.core.invoke;
if (!document.getElementById('pake-top-dom')) {
const topDom = document.createElement('div');
topDom.id = 'pake-top-dom';
document.body.appendChild(topDom);
}
const domEl = document.getElementById('pake-top-dom');
domEl.addEventListener('touchstart', () => {
appWindow.startDragging();
});
domEl.addEventListener('mousedown', e => {
e.preventDefault();
if (e.buttons === 1 && e.detail !== 2) {
appWindow.startDragging();
}
});
domEl.addEventListener('dblclick', () => {
appWindow.isFullscreen().then(fullscreen => {
appWindow.setFullscreen(!fullscreen);
});
});
if (window['pakeConfig']?.disabled_web_shortcuts !== true) {
document.addEventListener('keyup', event => {
if (/windows|linux/i.test(navigator.userAgent) && event.ctrlKey) {
handleShortcut(event);
}
if (/macintosh|mac os x/i.test(navigator.userAgent) && event.metaKey) {
handleShortcut(event);
}
});
}
// Collect blob urls to blob by overriding window.URL.createObjectURL
function collectUrlToBlobs() {
const backupCreateObjectURL = window.URL.createObjectURL;
window.blobToUrlCaches = new Map();
window.URL.createObjectURL = blob => {
const url = backupCreateObjectURL.call(window.URL, blob);
window.blobToUrlCaches.set(url, blob);
return url;
};
}
function convertBlobUrlToBinary(blobUrl) {
return new Promise(resolve => {
const blob = window.blobToUrlCaches.get(blobUrl);
const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = () => {
resolve(Array.from(new Uint8Array(reader.result)));
};
});
}
function downloadFromDataUri(dataURI, filename) {
const byteString = atob(dataURI.split(',')[1]);
// write the bytes of the string to an ArrayBuffer
const bufferArray = new ArrayBuffer(byteString.length);
// create a view into the buffer
const binary = new Uint8Array(bufferArray);
// set the bytes of the buffer to the correct values
for (let i = 0; i < byteString.length; i++) {
binary[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a binary, and you're done
invoke('download_file_by_binary', {
params: {
filename,
binary: Array.from(binary),
},
});
}
function downloadFromBlobUrl(blobUrl, filename) {
convertBlobUrlToBinary(blobUrl).then(binary => {
invoke('download_file_by_binary', {
params: {
filename,
binary,
},
});
});
}
// detect blob download by createElement("a")
function detectDownloadByCreateAnchor() {
const createEle = document.createElement;
document.createElement = el => {
if (el !== 'a') return createEle.call(document, el);
const anchorEle = createEle.call(document, el);
// use addEventListener to avoid overriding the original click event.
anchorEle.addEventListener(
'click',
e => {
const url = anchorEle.href;
const filename = anchorEle.download || getFilenameFromUrl(url);
if (window.blobToUrlCaches.has(url)) {
downloadFromBlobUrl(url, filename);
// case: download from dataURL -> convert dataURL ->
} else if (url.startsWith('data:')) {
downloadFromDataUri(url, filename);
}
},
true,
);
return anchorEle;
};
}
// process special download protocol['data:','blob:']
const isSpecialDownload = url => ['blob', 'data'].some(protocol => url.startsWith(protocol));
const isDownloadRequired = (url, anchorElement, e) => anchorElement.download || e.metaKey || e.ctrlKey || isDownloadLink(url);
const handleExternalLink = url => {
invoke('plugin:shell|open', {
path: url,
});
};
const detectAnchorElementClick = e => {
const anchorElement = e.target.closest('a');
if (anchorElement && anchorElement.href) {
const target = anchorElement.target;
const hrefUrl = new URL(anchorElement.href);
const absoluteUrl = hrefUrl.href;
let filename = anchorElement.download || getFilenameFromUrl(absoluteUrl);
// Handling external link redirection, _blank will automatically open.
if (target === '_blank') {
e.preventDefault();
return;
}
if (target === '_new') {
e.preventDefault();
handleExternalLink(absoluteUrl);
return;
}
// Process download links for Rust to handle.
if (isDownloadRequired(absoluteUrl, anchorElement, e) && !isSpecialDownload(absoluteUrl)) {
e.preventDefault();
invoke('download_file', { params: { url: absoluteUrl, filename } });
}
}
};
// Prevent some special websites from executing in advance, before the click event is triggered.
document.addEventListener('click', detectAnchorElementClick, true);
collectUrlToBlobs();
detectDownloadByCreateAnchor();
// Rewrite the window.open function.
const originalWindowOpen = window.open;
window.open = function (url, name, specs) {
// Apple login and google login
if (name === 'AppleAuthentication') {
//do nothing
} else if (specs && (specs.includes('height=') || specs.includes('width='))) {
location.href = url;
} else {
const baseUrl = window.location.origin + window.location.pathname;
const hrefUrl = new URL(url, baseUrl);
handleExternalLink(hrefUrl.href);
}
// Call the original window.open function to maintain its normal functionality.
return originalWindowOpen.call(window, url, name, specs);
};
// Set the default zoom, There are problems with Loop without using try-catch.
try {
setDefaultZoom();
} catch (e) {
console.log(e);
}
// Fix Chinese input method "Enter" on Safari
document.addEventListener(
'keydown',
e => {
if (e.keyCode === 229) e.stopPropagation();
},
true,
);
});
function setDefaultZoom() {
const htmlZoom = window.localStorage.getItem('htmlZoom');
if (htmlZoom) {
setZoom(htmlZoom);
}
}
function getFilenameFromUrl(url) {
const urlPath = new URL(url).pathname;
return urlPath.substring(urlPath.lastIndexOf('/') + 1);
}