-
-
Notifications
You must be signed in to change notification settings - Fork 180
/
tabs.preview.ts
545 lines (456 loc) · 15 KB
/
tabs.preview.ts
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import { ADDON_HOST, NOID } from 'src/defaults'
import { InstanceType } from 'src/types'
import { Sidebar } from './sidebar'
import { Tabs } from './tabs.fg'
import { Styles } from './styles'
import { Windows } from './windows'
import { Settings } from './settings'
import * as Logs from './logs'
import * as IPC from './ipc'
import { Menu } from './menu'
import { Mouse } from './mouse'
import { Selection } from './selection'
import { TabPreviewInitData } from 'src/injections/tab-preview'
export const enum Status {
Closing = -1,
Closed = 0,
Opening = 1,
Open = 2,
}
export const enum Mode {
Nope = 0,
Inline = 1,
Window = 2,
InPage = 3,
}
export const state = {
status: Status.Closed,
mode: Mode.Nope,
modeFallback: false,
popupWinId: NOID,
targetTabId: NOID,
mouseEnterTimeout: undefined as number | undefined,
mouseLeaveTimeout: undefined as number | undefined,
}
const approxFFToolbarsHeight = 70
const approxPopupHeaderHeight = 40
const inlinePreviewConf = {
format: 'jpeg' as const,
quality: 90,
scale: window.devicePixelRatio / 2,
}
let currentWinWidth = 0
let currentWinHeight = 0
let currentWinY = 0
let currentWinX = 0
let currentWinOffsetY = 0
let currentWinOffsetX = 0
let deadOnArrival = false
let listening = false
let tooltipUpdTimeout: number | undefined = undefined
function dbgStr() {
let m = state.mode === Mode.Nope ? 'Nope' : 'Inline'
if (state.mode === Mode.Window) m = 'Window'
else if (state.mode === Mode.InPage) m = 'InPage'
let s = state.status === Status.Closed ? 'Closed' : 'Closing'
if (state.status === Status.Open) s = 'Open'
else if (state.status === Status.Opening) s = 'Opening'
return `mode: ${m}, status: ${s}`
}
export function setTargetTab(tabId: ID, y: number) {
clearTimeout(state.mouseEnterTimeout)
if (Settings.state.previewTabsFollowMouse) {
clearTimeout(state.mouseLeaveTimeout)
}
state.targetTabId = tabId
// Start timeout to...
if (!Menu.isOpen && !Mouse.multiSelectionMode && !Selection.selected.length) {
// Update default tooltip
clearTimeout(tooltipUpdTimeout)
tooltipUpdTimeout = setTimeout(() => {
const tab = Tabs.byId[tabId]
if (tab) {
const isClosed = state.status === Status.Closed
if (
(Settings.state.previewTabsMode === 'p' && state.mode === Mode.Nope) ||
(state.mode === Mode.InPage && isClosed && (tab.discarded || tab.active)) ||
(state.mode === Mode.Window && isClosed && (tab.discarded || tab.active)) ||
(state.mode === Mode.Inline && tab.discarded)
) {
tab.reactive.tooltip = Tabs.getTooltip(tab)
} else {
tab.reactive.tooltip = ''
}
}
}, 64)
// Show preview in inline mode
if (state.mode === Mode.Inline) {
state.mouseEnterTimeout = setTimeout(() => {
state.mouseEnterTimeout = undefined
showPreviewInline(state.targetTabId)
}, Settings.state.previewTabsDelay)
return
}
// Update popup
if (Settings.state.previewTabsFollowMouse && state.status === Status.Open) {
state.mouseEnterTimeout = setTimeout(() => {
state.mouseEnterTimeout = undefined
updatePreviewPopup(state.targetTabId)
}, 128)
return
}
// Show preview popup
if (state.status === Status.Closed) {
state.mouseEnterTimeout = setTimeout(() => {
state.mouseEnterTimeout = undefined
showPreview(state.targetTabId, y)
}, Settings.state.previewTabsDelay)
return
}
}
}
export function resetTargetTab(tabId: ID) {
clearTimeout(state.mouseEnterTimeout)
clearTimeout(state.mouseLeaveTimeout)
if (tabId === undefined || tabId === state.targetTabId) {
state.targetTabId = NOID
}
state.mouseEnterTimeout = undefined
if (state.mode !== Mode.Inline) {
state.mouseLeaveTimeout = setTimeout(() => {
closePreviewPopup()
}, 36)
}
}
async function injectTabPreview(tabId: ID, y?: number) {
const activeTab = Tabs.byId[Tabs.activeId]
if (!activeTab) return
const initData = getTabPreviewInitData(tabId, y)
const initDataJson = JSON.stringify(initData)
const injectingData = browser.tabs
.executeScript(activeTab.id, {
code: `window.sideberyInitData=${initDataJson};window.onSideberyInitDataReady?.();true;`,
runAt: 'document_start',
allFrames: false,
matchAboutBlank: true,
})
.catch(() => {
// Cannot inject init data
})
const injectingScript = browser.tabs
.executeScript(activeTab.id, {
file: '../injections/tab-preview.js',
runAt: 'document_start',
allFrames: false,
matchAboutBlank: true,
})
.catch(() => {
// Cannot exec script
})
const [result, _] = await Promise.all([injectingData, injectingScript])
return result
}
function getTabPreviewInitData(tabId: ID, y?: number): TabPreviewInitData {
const tab = Tabs.byId[tabId]
return {
bg: Styles.parsedTheme?.vars.frame_bg,
fg: Styles.parsedTheme?.vars.frame_fg,
hbg: Styles.parsedTheme?.vars.toolbar_bg,
hfg: Styles.parsedTheme?.vars.toolbar_fg,
tabId: tabId,
winId: Windows.id,
title: tab?.title ?? '---',
url: tab?.url ?? '---',
y: y ?? 0,
dpr: window.devicePixelRatio,
popupWidth: Settings.state.previewTabsPopupWidth,
offsetY: Settings.state.previewTabsInPageOffsetY,
offsetX: Settings.state.previewTabsInPageOffsetX,
atTheLeft: Settings.state.previewTabsSide === 'right',
rCrop: Settings.state.previewTabsCropRight,
}
}
async function showPreview(tabId: ID, y?: number) {
const tab = Tabs.byId[tabId]
if (!tab || tab.invisible || tab.discarded || tab.active) return
// Inline
if (state.mode === Mode.Inline) {
return showPreviewInline(tabId)
}
// In page popup
else if (state.mode === Mode.InPage) {
state.status = Status.Opening
const result = await injectTabPreview(tabId, y)
if (result?.[0]) {
state.status = Status.Open
if (deadOnArrival || tab.invisible) {
deadOnArrival = false
closePreviewPopup()
}
return
}
state.status = Status.Closed
state.modeFallback = true
if (Settings.state.previewTabsPageModeFallback === 'n') {
state.mode = Mode.Nope
// Set default tooltip
tab.reactive.tooltip = Tabs.getTooltip(tab)
return
}
if (Settings.state.previewTabsPageModeFallback === 'i') {
state.mode = Mode.Inline
return showPreviewInline(tabId)
}
if (Windows.focused && Settings.state.previewTabsPageModeFallback === 'w') {
state.mode = Mode.Window
return showPreveiwPopupWindow(tabId, y)
}
}
// Popup window
else if (Windows.focused && state.mode === Mode.Window) {
return showPreveiwPopupWindow(tabId, y)
}
}
export function closePreview() {
clearTimeout(state.mouseEnterTimeout)
clearTimeout(state.mouseLeaveTimeout)
if (state.mode === Mode.Inline) return closePreviewInline()
else if (state.mode === Mode.InPage || state.mode === Mode.Window) return closePreviewPopup()
}
export function resetMode() {
if (state.status !== Status.Closed) closePreview()
if (Settings.state.previewTabsMode === 'i') state.mode = Mode.Inline
else if (Settings.state.previewTabsMode === 'p') state.mode = Mode.InPage
else state.mode = Mode.Window
state.modeFallback = false
}
export async function showPreveiwPopupWindow(tabId: ID, y?: number) {
const tab = Tabs.byId[tabId]
if (!tab || tab.invisible || tab.discarded) return
state.status = Status.Opening
const currentWindow = await browser.windows.getCurrent({ populate: false })
currentWinWidth = currentWindow.width ?? 0
currentWinHeight = currentWindow.height ?? 0
currentWinY = currentWindow.top ?? 0
currentWinX = currentWindow.left ?? 0
if (currentWinWidth === 0 || currentWinHeight === 0) {
state.status = Status.Closed
return
}
if (!listening) setupPopupDisconnectionListener()
currentWinOffsetY = 0
currentWinOffsetX = 0
const previewWidth = Settings.state.previewTabsPopupWidth
const previewData: Record<string, string> = {
bg: Styles.parsedTheme?.vars.frame_bg ?? '',
fg: Styles.parsedTheme?.vars.frame_fg ?? '',
hbg: Styles.parsedTheme?.vars.toolbar_bg ?? '',
hfg: Styles.parsedTheme?.vars.toolbar_fg ?? '',
tabId: tab.id.toString(),
winId: Windows.id.toString(),
title: tab.title,
url: tab.url,
}
const pageWidth = currentWinWidth - Sidebar.width
// Calc preview height
let previewHeight = Math.round((currentWinHeight / pageWidth) * previewWidth)
if (previewHeight > previewWidth) previewHeight = previewWidth
// Calc preview scale
const w = pageWidth / previewWidth
const h = currentWinHeight / previewHeight
let scale = (window.devicePixelRatio / Math.min(w, h)) * 1.5
if (scale > window.devicePixelRatio) scale = window.devicePixelRatio
// Append height of header to previewHeight
previewHeight += approxPopupHeaderHeight
previewData.scale = String(scale)
if (tab.discarded) previewData.off = 'y'
const params = new URLSearchParams(previewData).toString()
const top = (currentWinY ?? 0) + (y ?? 0) + Settings.state.previewTabsWinOffsetY
const left = getPopupX()
const previewWindow = await browser.windows.create({
allowScriptsToClose: true,
focused: true,
top,
left,
width: previewWidth,
height: previewHeight,
incognito: false,
state: 'normal',
type: 'popup',
url: `/popup.tab-preview/tab-preview.html?${params}`,
// For userChrome modificatoins with `#main-window[titlepreface='Tab Preview']`
titlePreface: 'Tab Preview',
})
if (previewWindow.id === undefined) {
state.status = Status.Closed
return
}
state.popupWinId = previewWindow.id
state.status = Status.Open
if (deadOnArrival || tab.invisible) {
deadOnArrival = false
closePreviewPopup()
return
}
let updPosition = false
let updSize = false
// Get differences between defined and actual size
const dw = (previewWindow.width ?? previewWidth) - previewWidth
const dh = (previewWindow.height ?? previewHeight) - previewHeight
if (dw !== 0 || dh !== 0) updSize = true
// Get differences between defined and actual position
const dt = (previewWindow.top ?? top) - top
const dl = (previewWindow.left ?? left) - left
// Preserve discrepancy if small
if (Math.abs(dt) < 30 && Math.abs(dl) < 5) {
currentWinOffsetY = dt
currentWinOffsetX = dl
}
// or try to update preview position
else {
updPosition = true
}
if (updSize) {
await browser.windows.update(previewWindow.id, {
width: previewWidth,
height: previewHeight,
})
}
if (updPosition) {
await browser.windows.update(previewWindow.id, {
top,
left,
})
}
}
export function setPreviewPopupPosition(y: number) {
if (state.popupWinId !== NOID) {
browser.windows.update(state.popupWinId, {
top: currentWinY + y + Settings.state.previewTabsWinOffsetY + currentWinOffsetY,
left: getPopupX(),
})
} else if (IPC.state.previewConnection) {
IPC.sendToPreview('setY', y)
}
}
export function updatePreviewPopup(tabId: ID) {
if (state.status !== Status.Open) return
const tab = Tabs.byId[tabId]
if (!tab) return
if (IPC.state.previewConnection) {
IPC.sendToPreview('updatePreview', tabId, tab.title, tab.url, !!tab.discarded)
} else {
closePreviewPopup()
}
}
export async function closePreviewPopup() {
if (state.status === Status.Opening) {
deadOnArrival = true
return
}
if (state.status === Status.Open) {
state.status = Status.Closing
if (state.popupWinId !== NOID) await browser.windows.remove(state.popupWinId)
else if (Settings.state.previewTabsMode === 'p' && IPC.state.previewConnection) {
IPC.sendToPreview('close')
}
state.popupWinId = NOID
state.status = Status.Closed
}
}
function getPopupX() {
if (Settings.state.previewTabsSide === 'right') {
return currentWinX + Sidebar.width + Settings.state.previewTabsWinOffsetX + currentWinOffsetX
} else {
return (
currentWinX +
currentWinWidth -
Sidebar.width -
Settings.state.previewTabsPopupWidth -
Settings.state.previewTabsWinOffsetX +
currentWinOffsetX
)
}
}
export function setupPopupDisconnectionListener() {
const checkPart = ADDON_HOST.slice(50, 52) + '/p'
IPC.onDisconnected(InstanceType.preview, async () => {
if (!Settings.state.previewTabs) return
const recentlyClosedItems = await browser.sessions.getRecentlyClosed({ maxResults: 3 })
for (const rc of recentlyClosedItems) {
if (!rc.window?.sessionId) continue
if (rc.window.tabs?.length === 1) {
const url = rc.window.tabs[0].url
if (url.startsWith(checkPart, 50)) browser.sessions.forgetClosedWindow(rc.window.sessionId)
}
}
})
listening = true
}
let inlinePreviewTabId = NOID
export async function showPreviewInline(tabId: ID) {
if (inlinePreviewTabId === tabId) return
const tab = Tabs.byId[tabId]
if (!tab || tab.discarded) return
state.status = Status.Opening
const currentWindow = await browser.windows.getCurrent({ populate: false })
const pageWidth = (currentWindow.width ?? 0) - Sidebar.width
const pageHeight = (currentWindow.height ?? 0) - approxFFToolbarsHeight
if (pageWidth <= 0) return
// Calc preview scale
const w = pageWidth / Sidebar.width
inlinePreviewConf.scale = (window.devicePixelRatio / w) * 1.5
if (inlinePreviewConf.scale > window.devicePixelRatio) {
inlinePreviewConf.scale = window.devicePixelRatio
}
const preview = await browser.tabs.captureTab(tabId, inlinePreviewConf).catch(() => '')
const prevTabId = inlinePreviewTabId
inlinePreviewTabId = tabId
state.status = Status.Open
if (deadOnArrival) {
deadOnArrival = false
closePreviewInline()
return
}
let previewHeight = Settings.state.previewTabsInlineHeight
if (Settings.state.previewTabsInlineHeight === 0) {
previewHeight = Math.round((pageHeight / pageWidth) * Sidebar.width)
if (previewHeight > Sidebar.width) previewHeight = Sidebar.width
}
document.body.style.setProperty('--tabs-inline-preview-height', `${previewHeight}px`)
const prevTab = Tabs.byId[prevTabId]
if (prevTab) prevTab.reactive.preview = false
if (tab.pinned) {
if (prevTab && !prevTab.pinned) {
Tabs.reactive.inlinePreviewTabId = NOID
}
Tabs.reactive.inlinePreviewPinnedImg = `url("${preview}")`
} else {
if (prevTab && prevTab.pinned) Tabs.reactive.inlinePreviewPinnedImg = ''
tab.previewImg = `url("${preview}")`
tab.reactive.preview = true
Tabs.reactive.inlinePreviewTabId = tabId
}
}
export function closePreviewInline() {
if (state.status === Status.Opening) {
deadOnArrival = true
return
}
const tab = Tabs.byId[inlinePreviewTabId]
if (!tab) {
Tabs.reactive.inlinePreviewPinnedImg = ''
Tabs.reactive.inlinePreviewTabId = NOID
inlinePreviewTabId = NOID
state.status = Status.Closed
return
}
if (tab.pinned) {
Tabs.reactive.inlinePreviewPinnedImg = ''
} else {
Tabs.reactive.inlinePreviewTabId = NOID
tab.reactive.preview = false
}
inlinePreviewTabId = NOID
state.status = Status.Closed
}