-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
447 lines (405 loc) · 15.5 KB
/
Copy pathpopup.js
File metadata and controls
447 lines (405 loc) · 15.5 KB
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
const elements = {
contextLabel: document.querySelector("#context-label"),
statusBadge: document.querySelector("#status-badge"),
notice: document.querySelector("#notice"),
loadingView: document.querySelector("#loading-view"),
setupView: document.querySelector("#setup-view"),
controlView: document.querySelector("#control-view"),
errorView: document.querySelector("#error-view"),
errorMessage: document.querySelector("#error-message"),
retryButton: document.querySelector("#retry-button"),
nativeSummary: document.querySelector("#native-summary"),
nativeTabs: document.querySelector("#native-tabs"),
manualSummary: document.querySelector("#manual-summary"),
targetTab: document.querySelector("#target-tab"),
connectButton: document.querySelector("#connect-button"),
sourceButtons: [...document.querySelectorAll("[data-source-option]")],
activeTabs: document.querySelector("#active-tabs"),
enabledToggle: document.querySelector("#enabled-toggle"),
toggleDescription: document.querySelector("#toggle-description"),
modeButtons: [...document.querySelectorAll("[data-mode]")],
anchorPanel: document.querySelector("#anchor-panel"),
anchorInstructions: document.querySelector("#anchor-instructions"),
addAnchor: document.querySelector("#add-anchor"),
calibrationActions: document.querySelector("#calibration-actions"),
cancelCalibration: document.querySelector("#cancel-calibration"),
finishCalibration: document.querySelector("#finish-calibration"),
anchorEmpty: document.querySelector("#anchor-empty"),
anchorList: document.querySelector("#anchor-list"),
clearAnchors: document.querySelector("#clear-anchors"),
disconnectButton: document.querySelector("#disconnect-button"),
};
let popupState = null;
let busy = false;
let setupSource = null;
elements.retryButton.addEventListener("click", loadState);
elements.connectButton.addEventListener("click", connectTabs);
elements.enabledToggle.addEventListener("change", toggleEnabled);
elements.disconnectButton.addEventListener("click", disconnectPair);
elements.addAnchor.addEventListener("click", addAnchor);
elements.cancelCalibration.addEventListener("click", cancelCalibration);
elements.finishCalibration.addEventListener("click", finishCalibration);
elements.clearAnchors.addEventListener("click", clearAnchors);
elements.sourceButtons.forEach((button) => {
button.addEventListener("click", () => changeSetupSource(button.dataset.sourceOption));
button.addEventListener("keydown", handleSourceKeydown);
});
elements.modeButtons.forEach((button, index) => {
button.addEventListener("click", () => changeMode(button.dataset.mode));
button.addEventListener("keydown", (event) => handleModeKeydown(event, index));
});
loadState();
async function loadState() {
setView("loading");
hideNotice();
try {
const response = await send({ type: "GET_POPUP_STATE" });
popupState = response;
render();
} catch (error) {
showFatal(error.message);
}
}
function render() {
if (popupState.pair) {
renderControls(popupState.pair);
} else {
renderSetup();
}
}
function renderSetup() {
setView("setup");
elements.statusBadge.textContent = "未连接";
elements.statusBadge.dataset.state = "paused";
const nativeTabs = popupState.nativeTabs || [];
const hasNativePair = nativeTabs.length === 2;
if (!setupSource || (setupSource === "native" && !hasNativePair)) {
setupSource = hasNativePair ? "native" : "manual";
}
elements.contextLabel.textContent = hasNativePair
? "拆分视图或跨 Tab 联动"
: "可连接任意 Chrome 标签页";
for (const button of elements.sourceButtons) {
const source = button.dataset.sourceOption;
const selected = source === setupSource;
button.disabled = source === "native" && !hasNativePair;
button.setAttribute("aria-checked", String(selected));
button.tabIndex = selected ? 0 : -1;
}
const candidates = popupState.allTabs.filter(
(tab) => tab.id !== popupState.activeTabId && tab.supported,
);
const previousTarget = elements.targetTab.value;
renderTabOptions(candidates);
if (candidates.some((tab) => String(tab.id) === previousTarget)) {
elements.targetTab.value = previousTarget;
}
const useNative = setupSource === "native";
elements.nativeSummary.hidden = !useNative;
elements.manualSummary.hidden = useNative;
elements.connectButton.dataset.source = setupSource;
if (useNative) {
renderTabs(elements.nativeTabs, nativeTabs);
elements.connectButton.disabled = false;
elements.connectButton.textContent = "连接这两个视图";
} else {
elements.connectButton.disabled = candidates.length === 0;
elements.connectButton.textContent = candidates.length ? "连接两个标签页" : "没有可连接的网页";
}
}
function renderTabOptions(candidates) {
elements.targetTab.replaceChildren();
const groups = new Map();
let otherWindowNumber = 0;
for (const tab of candidates) {
if (!groups.has(tab.windowId)) {
const group = document.createElement("optgroup");
group.label = tab.windowId === popupState.activeWindowId
? "当前窗口"
: `其他窗口 ${otherWindowNumber += 1}`;
groups.set(tab.windowId, group);
elements.targetTab.append(group);
}
const option = document.createElement("option");
option.value = String(tab.id);
option.textContent = `${tab.title} (${tab.domain || "网页"})`;
groups.get(tab.windowId).append(option);
}
}
function changeSetupSource(source) {
if (busy || !["native", "manual"].includes(source)) {
return;
}
if (source === "native" && (popupState.nativeTabs || []).length !== 2) {
return;
}
setupSource = source;
hideNotice();
renderSetup();
}
function handleSourceKeydown(event) {
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
return;
}
event.preventDefault();
const enabledButtons = elements.sourceButtons.filter((button) => !button.disabled);
const currentIndex = enabledButtons.indexOf(event.currentTarget);
const direction = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : -1;
const nextButton = enabledButtons[(currentIndex + direction + enabledButtons.length) % enabledButtons.length];
nextButton.focus();
changeSetupSource(nextButton.dataset.sourceOption);
}
function renderControls(pair) {
setView("control");
elements.contextLabel.textContent = "两个页面已建立联动";
elements.statusBadge.textContent = pair.calibrating ? "校准中" : pair.enabled ? "联动中" : "已暂停";
elements.statusBadge.dataset.state = pair.calibrating ? "calibrating" : pair.enabled ? "active" : "paused";
elements.enabledToggle.checked = pair.enabled;
elements.enabledToggle.disabled = Boolean(pair.calibrating);
elements.toggleDescription.textContent = pair.calibrating
? "联动已暂停,左右页面现在可以独立滚动。"
: pair.enabled
? "滚动任意一侧,另一侧会跟随。"
: "保持连接,但暂时不传递滚动。";
renderTabs(elements.activeTabs, pair.tabs);
for (const button of elements.modeButtons) {
const selected = button.dataset.mode === pair.mode;
button.setAttribute("aria-checked", String(selected));
button.tabIndex = selected ? 0 : -1;
button.disabled = Boolean(pair.calibrating && !selected);
}
const anchorsVisible = pair.mode === "anchors";
elements.anchorPanel.hidden = !anchorsVisible;
if (anchorsVisible) {
renderAnchors(pair.anchors || [], Boolean(pair.calibrating));
}
}
function renderTabs(container, tabs) {
container.replaceChildren();
tabs.slice(0, 2).forEach((tab, index) => {
const item = document.createElement("div");
item.className = "tab-item";
const key = document.createElement("span");
key.className = "tab-key";
key.textContent = index === 0 ? "A" : "B";
const copy = document.createElement("div");
copy.className = "tab-copy";
const title = document.createElement("div");
title.className = "tab-title";
title.textContent = tab.title;
title.title = tab.title;
const domain = document.createElement("div");
domain.className = "tab-domain";
const windowLabel = tab.windowId === popupState.activeWindowId ? "当前窗口" : "其他窗口";
domain.textContent = `${tab.domain || "普通网页"},${windowLabel}`;
copy.append(title, domain);
item.append(key, copy);
container.append(item);
});
}
function renderAnchors(anchors, calibrating) {
elements.anchorList.replaceChildren();
elements.anchorEmpty.hidden = anchors.length > 0;
elements.clearAnchors.hidden = anchors.length === 0;
elements.anchorInstructions.textContent = calibrating
? "联动保持暂停。请记录正文对应位置,完成校准后才恢复联动。"
: "关联点精确对齐标记位置;到达顶部或底部时,两侧自动贴边。";
elements.addAnchor.textContent = calibrating ? "记录位置" : "添加关联点";
elements.calibrationActions.hidden = !calibrating;
elements.finishCalibration.disabled = anchors.length === 0;
anchors.forEach((anchor, index) => {
const item = document.createElement("li");
item.className = "anchor-item";
const label = document.createElement("span");
label.textContent = `关联 ${index + 1}: A ${formatPercent(anchor.a)} 对应 B ${formatPercent(anchor.b)}`;
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.textContent = "删除";
removeButton.setAttribute("aria-label", `删除关联 ${index + 1}`);
removeButton.addEventListener("click", () => removeAnchor(anchor.id));
item.append(label, removeButton);
elements.anchorList.append(item);
});
}
async function connectTabs() {
if (busy) {
return;
}
const tabIds = elements.connectButton.dataset.source === "native"
? popupState.nativeTabs.map((tab) => tab.id)
: [popupState.activeTabId, Number(elements.targetTab.value)];
await runBusy(elements.connectButton, "正在连接", async () => {
const response = await send({ type: "START_PAIR", tabIds, mode: "ratio" });
popupState.pair = response.pair;
renderControls(response.pair);
showNotice("连接成功。现在滚动任意一侧即可测试。", "success");
});
}
async function toggleEnabled() {
const desired = elements.enabledToggle.checked;
try {
const response = await send({
type: "SET_ENABLED",
pairId: popupState.pair.id,
enabled: desired,
});
popupState.pair = response.pair;
renderControls(response.pair);
} catch (error) {
elements.enabledToggle.checked = !desired;
showNotice(error.message, "error");
}
}
async function changeMode(mode) {
if (busy || popupState.pair.calibrating || mode === popupState.pair.mode) {
return;
}
await runBusy(null, "", async () => {
const response = await send({
type: mode === "anchors" ? "BEGIN_ANCHOR_CALIBRATION" : "SET_MODE",
pairId: popupState.pair.id,
mode,
});
popupState.pair = response.pair;
renderControls(response.pair);
if (mode === "anchors") {
showNotice("联动已暂停。请分别调整两页,再记录对应位置。", "success");
} else {
hideNotice();
}
});
}
function handleModeKeydown(event, index) {
if (popupState.pair.calibrating || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
return;
}
event.preventDefault();
const direction = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : -1;
const nextIndex = (index + direction + elements.modeButtons.length) % elements.modeButtons.length;
const nextButton = elements.modeButtons[nextIndex];
nextButton.focus();
changeMode(nextButton.dataset.mode);
}
async function addAnchor() {
const calibrating = Boolean(popupState.pair.calibrating);
await runBusy(elements.addAnchor, calibrating ? "正在记录" : "正在暂停", async () => {
const response = await send({
type: calibrating ? "ADD_ANCHOR" : "BEGIN_ANCHOR_CALIBRATION",
pairId: popupState.pair.id,
});
popupState.pair = response.pair;
renderControls(response.pair);
if (calibrating) {
showNotice(`已记录第 ${response.pair.anchors.length} 组位置。可继续记录,或完成校准。`, "success");
} else {
showNotice("联动已暂停。请分别调整两页,再记录对应位置。", "success");
}
});
}
async function finishCalibration() {
await runBusy(elements.finishCalibration, "正在完成", async () => {
const response = await send({
type: "FINISH_ANCHOR_CALIBRATION",
pairId: popupState.pair.id,
});
popupState.pair = response.pair;
renderControls(response.pair);
showNotice(
response.pair.enabled ? "校准已完成,关联点联动已开启。" : "校准已完成,联动保持暂停。",
"success",
);
});
}
async function cancelCalibration() {
await runBusy(elements.cancelCalibration, "正在取消", async () => {
const response = await send({
type: "CANCEL_ANCHOR_CALIBRATION",
pairId: popupState.pair.id,
});
popupState.pair = response.pair;
renderControls(response.pair);
showNotice(
response.pair.enabled ? "已取消校准,本次记录已撤销。" : "已取消校准,本次记录已撤销,联动保持暂停。",
"success",
);
});
}
async function removeAnchor(anchorId) {
await runBusy(null, "", async () => {
const response = await send({ type: "REMOVE_ANCHOR", pairId: popupState.pair.id, anchorId });
popupState.pair = response.pair;
renderControls(response.pair);
});
}
async function clearAnchors() {
await runBusy(elements.clearAnchors, "正在清除", async () => {
const response = await send({ type: "CLEAR_ANCHORS", pairId: popupState.pair.id });
popupState.pair = response.pair;
renderControls(response.pair);
showNotice("关联点已清除。联动保持暂停,请重新记录对应位置。", "success");
});
}
async function disconnectPair() {
await runBusy(elements.disconnectButton, "正在断开", async () => {
await send({ type: "STOP_PAIR", pairId: popupState.pair.id });
await loadState();
});
}
async function runBusy(button, label, operation) {
if (busy) {
return;
}
busy = true;
const original = button?.textContent;
if (button) {
button.disabled = true;
button.textContent = label;
}
try {
hideNotice();
await operation();
} catch (error) {
showNotice(error.message, "error");
} finally {
busy = false;
if (button) {
button.disabled = false;
if (button.textContent === label) {
button.textContent = original;
}
}
}
}
async function send(message) {
const response = await chrome.runtime.sendMessage(message);
if (!response?.ok) {
throw new Error(response?.error || "操作失败。请重试。");
}
return response;
}
function setView(name) {
elements.loadingView.hidden = name !== "loading";
elements.setupView.hidden = name !== "setup";
elements.controlView.hidden = name !== "control";
elements.errorView.hidden = name !== "error";
}
function showNotice(message, kind) {
elements.notice.hidden = false;
elements.notice.dataset.kind = kind;
elements.notice.textContent = message;
}
function hideNotice() {
elements.notice.hidden = true;
elements.notice.textContent = "";
delete elements.notice.dataset.kind;
}
function showFatal(message) {
setView("error");
elements.statusBadge.textContent = "不可用";
elements.statusBadge.dataset.state = "paused";
elements.contextLabel.textContent = "需要普通网页";
elements.errorMessage.textContent = message;
}
function formatPercent(value) {
return `${Math.round(value * 100)}%`;
}