Repository navigation
Expand file tree
/
Copy pathoptions.js
More file actions
1909 lines (1700 loc) · 65.2 KB
/
Copy pathoptions.js
File metadata and controls
1909 lines (1700 loc) · 65.2 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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const MAX_BACKUPS = 20;
const manualSync = globalThis.TechWordManualSync;
if (!manualSync) {
throw new Error("TechWordLearn manual sync module failed to load");
}
const CLOUD_SYNC_STATUS_LABELS = {
idle: "未启动",
syncing: "同步中",
ok: "已同步",
error: "同步失败",
disabled: "未启用",
};
let baseVocab = {};
let customVocab = {};
let wordCounts = {};
let weeklyWordCounts = {};
let deletedSet = new Set();
let masteredSet = new Set();
let backups = [];
let rows = [];
let currentFilter = "";
let currentSourceFilter = "all";
let editingWord = null;
let selectedWord = null;
let drawerMode = "detail";
let activeView = "main";
let selectedVersionId = null;
let currentVersionId = null;
let currentVersionMode = "live";
let pageViewMode = "live";
let isReadOnlyView = false;
let cloudSyncEnabled = false;
let cloudSyncEndpoint = "";
let cloudSyncToken = "";
let cloudSyncDeviceId = "";
let cloudSyncStatus = "idle";
let cloudSyncLastSyncedAt = "";
let cloudSyncLastError = "";
let cloudSyncLastReason = "";
let cloudSyncLastAttemptAt = "";
let manualSyncContext = null;
let manualSyncBusy = false;
const statusEl = document.getElementById("status");
const summaryEl = document.getElementById("summary");
const weeklySummaryEl = document.getElementById("weekly-summary");
const versionSummaryEl = document.getElementById("version-summary");
const activeVersionDisplayEl = document.getElementById("active-version-display");
const vocabSectionTitleEl = document.getElementById("vocab-section-title");
const cloudSyncSummaryEl = document.getElementById("cloud-sync-summary");
const manualSyncSummaryEl = document.getElementById("manual-sync-summary");
const searchInput = document.getElementById("search-input");
const tbody = document.getElementById("vocab-tbody");
const weeklyTopListEl = document.getElementById("weekly-top-list");
const versionListEl = document.getElementById("version-list");
const versionPreviewTitleEl = document.getElementById("version-preview-title");
const versionPreviewListEl = document.getElementById("version-preview-list");
const setCurrentVersionBtn = document.getElementById("set-current-version-btn");
const viewLiveBtn = document.getElementById("view-live-btn");
const editorTitleEl = document.getElementById("editor-title");
const editForm = document.getElementById("edit-form");
const wordInput = document.getElementById("word-input");
const defInput = document.getElementById("def-input");
const saveBtn = document.getElementById("save-btn");
const resetFormBtn = document.getElementById("reset-form-btn");
const cloudSyncEnabledInput = document.getElementById("cloud-sync-enabled");
const cloudSyncEndpointInput = document.getElementById("cloud-sync-endpoint");
const cloudSyncTokenInput = document.getElementById("cloud-sync-token");
const saveCloudSyncBtn = document.getElementById("save-cloud-sync-btn");
const syncCloudNowBtn = document.getElementById("sync-cloud-now-btn");
const checkManualSyncBtn = document.getElementById("check-manual-sync-btn");
const uploadManualSyncBtn = document.getElementById("upload-manual-sync-btn");
const downloadManualSyncBtn = document.getElementById("download-manual-sync-btn");
const mainViewEl = document.getElementById("main-view");
const statsViewEl = document.getElementById("stats-view");
const syncViewEl = document.getElementById("sync-view");
const versionsViewEl = document.getElementById("versions-view");
const topbarActionsEl = document.getElementById("topbar-actions");
const moreMenuBtn = document.getElementById("more-menu-btn");
const maintenanceMenuEl = document.getElementById("maintenance-menu");
const cloudSettingsToggleBtn = document.getElementById("cloud-settings-toggle-btn");
const cloudSettingsPanelEl = document.getElementById("cloud-settings-panel");
const filterButtons = {
all: document.getElementById("filter-all-btn"),
custom: document.getElementById("filter-custom-btn"),
base: document.getElementById("filter-base-btn"),
hidden: document.getElementById("filter-hidden-btn"),
};
const drawerLayerEl = document.getElementById("drawer-layer");
const drawerTitleEl = document.getElementById("drawer-title");
const wordDetailViewEl = document.getElementById("word-detail-view");
const wordEditViewEl = document.getElementById("word-edit-view");
const detailDefinitionEl = document.getElementById("detail-definition");
const detailSourceEl = document.getElementById("detail-source");
const detailCountEl = document.getElementById("detail-count");
const editDetailBtn = document.getElementById("edit-detail-btn");
const restoreBaselineBtn = document.getElementById("restore-baseline-btn");
const unhideWordBtn = document.getElementById("unhide-word-btn");
const hideWordBtn = document.getElementById("hide-word-btn");
const deleteWordBtn = document.getElementById("delete-word-btn");
function normalizeWord(raw) {
const m = String(raw || "").match(/[A-Za-z][A-Za-z'-]*/);
return m ? m[0].toLowerCase() : null;
}
function sanitizeCloudEndpoint(raw) {
const text = String(raw || "").trim();
if (!text) return "";
try {
const url = new URL(text);
if (url.protocol !== "https:" && url.protocol !== "http:") return "";
url.hash = "";
return url.toString();
} catch (_) {
return "";
}
}
function sanitizeCloudToken(raw) {
return typeof raw === "string" ? raw.trim() : "";
}
function sanitizeWordMap(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const out = {};
for (const [k, v] of Object.entries(raw)) {
if (typeof k !== "string") continue;
if (typeof v !== "string") continue;
const key = normalizeWord(k);
const value = v.trim();
if (!key || value === "") continue;
out[key] = value;
}
return out;
}
function sanitizeWordList(raw) {
if (!Array.isArray(raw)) return [];
const next = [];
const seen = new Set();
for (const item of raw) {
const key = normalizeWord(item);
if (!key || seen.has(key)) continue;
seen.add(key);
next.push(key);
}
return next;
}
function sanitizeWordCountMap(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const out = {};
for (const [k, v] of Object.entries(raw)) {
const key = normalizeWord(k);
if (!key || key !== k) continue;
if (typeof v !== "number" || !Number.isFinite(v) || v < 0) continue;
out[key] = Math.floor(v);
}
return out;
}
function extractWordCounts(items) {
const out = {};
if (!items || typeof items !== "object") return out;
for (const [key, value] of Object.entries(items)) {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) continue;
const normalized = normalizeWord(key);
if (!normalized || normalized !== key) continue;
out[key] = Math.floor(value);
}
return out;
}
function sanitizeWeeklyWordCounts(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const out = {};
for (const [weekKey, value] of Object.entries(raw)) {
if (!/^\d{4}-W\d{2}$/.test(weekKey)) continue;
out[weekKey] = sanitizeWordCountMap(value);
}
return out;
}
function getCurrentWeekKey() {
const now = new Date();
const d = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
const dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
const weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, "0")}`;
}
function currentWeekCountMap() {
const weekKey = getCurrentWeekKey();
return sanitizeWordCountMap(weeklyWordCounts[weekKey]);
}
function makeId() {
return `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
function setStatus(text, isError = false) {
statusEl.hidden = false;
statusEl.textContent = text;
statusEl.style.color = isError ? "#b91c1c" : "#475569";
statusEl.style.background = isError ? "#fee2e2" : "#edf2f7";
}
function formatTime(iso) {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "Unknown";
return d.toLocaleString();
}
function shortText(text, maxLen) {
const s = String(text || "");
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
}
function cloudSyncReadyFromInputs() {
return cloudSyncEnabledInput.checked && Boolean(sanitizeCloudEndpoint(cloudSyncEndpointInput.value));
}
function updateCloudSyncActionState() {
syncCloudNowBtn.disabled = !cloudSyncReadyFromInputs();
}
function renderCloudSyncPanel() {
cloudSyncEnabledInput.checked = cloudSyncEnabled;
cloudSyncEndpointInput.value = cloudSyncEndpoint;
cloudSyncTokenInput.value = cloudSyncToken;
updateCloudSyncActionState();
const statusLabel = CLOUD_SYNC_STATUS_LABELS[cloudSyncStatus] || CLOUD_SYNC_STATUS_LABELS.idle;
const endpointHost = sanitizeCloudEndpoint(cloudSyncEndpoint)
? new URL(sanitizeCloudEndpoint(cloudSyncEndpoint)).host
: "未配置端点";
if (!cloudSyncEnabled) {
cloudSyncSummaryEl.textContent = "当前关闭。多台设备使用相同的服务器设置后即可共享词库。";
cloudSettingsToggleBtn.textContent = cloudSettingsPanelEl.hidden
? cloudSyncEndpoint
? "查看设置"
: "设置"
: "收起设置";
return;
}
const parts = [`状态: ${statusLabel}`, `端点: ${endpointHost}`];
if (cloudSyncLastSyncedAt) {
parts.push(`最近成功: ${formatTime(cloudSyncLastSyncedAt)}`);
} else if (cloudSyncLastAttemptAt) {
parts.push(`最近尝试: ${formatTime(cloudSyncLastAttemptAt)}`);
}
if (cloudSyncLastReason) {
parts.push(`触发: ${cloudSyncLastReason}`);
}
if (cloudSyncLastError) {
parts.push(`错误: ${cloudSyncLastError}`);
}
if (cloudSyncDeviceId) {
parts.push(`设备ID: ${cloudSyncDeviceId.slice(0, 8)}`);
}
cloudSyncSummaryEl.textContent = parts.join(" | ");
cloudSettingsToggleBtn.textContent = cloudSettingsPanelEl.hidden ? "查看设置" : "收起设置";
}
function showView(viewName) {
activeView = ["stats", "sync", "versions"].includes(viewName) ? viewName : "main";
mainViewEl.hidden = activeView !== "main";
statsViewEl.hidden = activeView !== "stats";
syncViewEl.hidden = activeView !== "sync";
versionsViewEl.hidden = activeView !== "versions";
summaryEl.hidden = activeView !== "main";
topbarActionsEl.hidden = activeView !== "main";
maintenanceMenuEl.hidden = true;
moreMenuBtn.setAttribute("aria-expanded", "false");
closeDrawer();
if (activeView === "main" && pageViewMode === "version") {
pageViewMode = "live";
renderAll();
}
if (typeof window.scrollTo === "function") {
window.scrollTo(0, 0);
}
}
function toggleMaintenanceMenu() {
const opening = maintenanceMenuEl.hidden;
maintenanceMenuEl.hidden = !opening;
moreMenuBtn.setAttribute("aria-expanded", opening ? "true" : "false");
}
function toggleCloudSettings() {
const opening = cloudSettingsPanelEl.hidden;
cloudSettingsPanelEl.hidden = !opening;
cloudSettingsToggleBtn.setAttribute("aria-expanded", opening ? "true" : "false");
cloudSettingsToggleBtn.textContent = opening ? "收起设置" : cloudSyncEndpoint || cloudSyncEnabled ? "查看设置" : "设置";
}
function setSourceFilter(filterName) {
currentSourceFilter = Object.prototype.hasOwnProperty.call(filterButtons, filterName) ? filterName : "all";
renderTable();
}
function storageGet(areaName, keys) {
return new Promise((resolve, reject) => {
const area = chrome.storage && chrome.storage[areaName];
if (!area || typeof area.get !== "function") {
reject(new Error(`storage_${areaName}_unavailable`));
return;
}
area.get(keys, (items) => {
const lastErr = chrome.runtime.lastError;
if (lastErr) {
reject(new Error(lastErr.message));
return;
}
resolve(items || {});
});
});
}
function storageSet(areaName, payload) {
return new Promise((resolve, reject) => {
const area = chrome.storage && chrome.storage[areaName];
if (!area || typeof area.set !== "function") {
reject(new Error(`storage_${areaName}_unavailable`));
return;
}
area.set(payload, () => {
const lastErr = chrome.runtime.lastError;
if (lastErr) {
reject(new Error(lastErr.message));
return;
}
resolve();
});
});
}
function storageRemove(areaName, keys) {
return new Promise((resolve, reject) => {
if (!Array.isArray(keys) || keys.length === 0) {
resolve();
return;
}
const area = chrome.storage && chrome.storage[areaName];
if (!area || typeof area.remove !== "function") {
reject(new Error(`storage_${areaName}_unavailable`));
return;
}
area.remove(keys, () => {
const lastErr = chrome.runtime.lastError;
if (lastErr) {
reject(new Error(lastErr.message));
return;
}
resolve();
});
});
}
function storageBytesInUse(areaName) {
return new Promise((resolve, reject) => {
const area = chrome.storage && chrome.storage[areaName];
if (!area || typeof area.getBytesInUse !== "function") {
resolve(0);
return;
}
area.getBytesInUse(null, (bytes) => {
const lastErr = chrome.runtime.lastError;
if (lastErr) {
reject(new Error(lastErr.message));
return;
}
resolve(Number(bytes) || 0);
});
});
}
function makeManualDeviceId() {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") {
return globalThis.crypto.randomUUID();
}
return `twl_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
async function ensureManualDeviceId(existingId) {
const current = typeof existingId === "string" ? existingId.trim() : "";
if (current) return current;
const deviceId = makeManualDeviceId();
await storageSet("local", { [manualSync.LOCAL_DEVICE_ID_KEY]: deviceId });
return deviceId;
}
async function inspectManualSync() {
const localKeys = [
"custom_vocab",
"deleted_vocab",
"mastered_list",
"vocab_backups",
manualSync.LOCAL_BASE_REVISION_KEY,
manualSync.LOCAL_BASE_FINGERPRINT_KEY,
manualSync.LOCAL_DEVICE_ID_KEY,
manualSync.LOCAL_LAST_SYNCED_AT_KEY,
];
const [localItems, remoteItems] = await Promise.all([
storageGet("local", localKeys),
storageGet("sync", null),
]);
const localState = manualSync.normalizeState(localItems);
const [localFingerprint, remote] = await Promise.all([
manualSync.stateFingerprint(localState),
manualSync.decodeSnapshot(remoteItems),
]);
let baseFingerprint =
typeof localItems[manualSync.LOCAL_BASE_FINGERPRINT_KEY] === "string"
? localItems[manualSync.LOCAL_BASE_FINGERPRINT_KEY]
: "";
if (
remote &&
remote.transportFingerprint &&
baseFingerprint === remote.transportFingerprint
) {
baseFingerprint = remote.fingerprint;
} else if (baseFingerprint) {
const localSchemaTwoFingerprint = await manualSync.stateFingerprintForSchema(localState, 2);
if (baseFingerprint === localSchemaTwoFingerprint) {
baseFingerprint = await manualSync.stateFingerprint({
...localState,
mastered_list: [],
});
}
}
const rawBaseRevision = Number(localItems[manualSync.LOCAL_BASE_REVISION_KEY]);
const baseRevision = Number.isSafeInteger(rawBaseRevision) && rawBaseRevision >= 0 ? rawBaseRevision : 0;
return {
localItems,
remoteItems,
localState,
localFingerprint,
remote,
baseFingerprint,
baseRevision,
status: manualSync.classifyState(localFingerprint, remote, baseFingerprint),
};
}
function setManualSyncBusy(busy) {
manualSyncBusy = Boolean(busy);
checkManualSyncBtn.disabled = manualSyncBusy;
uploadManualSyncBtn.disabled = manualSyncBusy;
downloadManualSyncBtn.disabled = manualSyncBusy;
}
function hideManualSyncActions() {
uploadManualSyncBtn.hidden = true;
downloadManualSyncBtn.hidden = true;
}
function manualSyncCounts(state) {
const normalized = manualSync.normalizeState(state);
return `${Object.keys(normalized.custom_vocab).length} 个自己添加或修改,${normalized.deleted_vocab.length} 个已隐藏,${normalized.mastered_list.length} 个已掌握`;
}
function remoteNeedsSnapshotMigration(remote) {
if (!remote) return false;
if (remote.kind === "legacy") return true;
return remote.kind === "snapshot" && remote.schemaVersion < manualSync.SCHEMA_VERSION;
}
function renderManualSyncContext(context) {
manualSyncContext = context;
hideManualSyncActions();
uploadManualSyncBtn.textContent = "使用本机词库上传";
downloadManualSyncBtn.textContent = "使用其他设备词库下载";
const localLabel = `本机:${manualSyncCounts(context.localState)}`;
const remoteLabel = context.remote
? `共享:${manualSyncCounts(context.remote.state)},版本 ${context.remote.revision}`
: "共享:尚无快照";
if (context.status === "in_sync") {
if (remoteNeedsSnapshotMigration(context.remote)) {
manualSyncSummaryEl.textContent = `${localLabel};${remoteLabel}。内容一致,但共享区仍是旧格式,可点击迁移。`;
uploadManualSyncBtn.textContent = "迁移为安全分块快照";
uploadManualSyncBtn.hidden = false;
return;
}
manualSyncSummaryEl.textContent = `${localLabel};${remoteLabel}。两边内容一致。`;
return;
}
if (context.status === "remote_missing") {
manualSyncSummaryEl.textContent = `${localLabel};${remoteLabel}。可手动创建第一份共享快照。`;
uploadManualSyncBtn.textContent = "创建共享快照";
uploadManualSyncBtn.hidden = false;
return;
}
if (context.status === "local_ahead") {
manualSyncSummaryEl.textContent = `${localLabel};${remoteLabel}。仅本机有新变化,可手动上传。`;
uploadManualSyncBtn.textContent = "上传本机变更";
uploadManualSyncBtn.hidden = false;
return;
}
if (context.status === "remote_ahead") {
manualSyncSummaryEl.textContent = `${localLabel};${remoteLabel}。仅共享快照有新变化,可手动下载。`;
downloadManualSyncBtn.textContent = "下载共享变更";
downloadManualSyncBtn.hidden = false;
return;
}
manualSyncSummaryEl.textContent =
`${localLabel};${remoteLabel}。两边都可能有变化,不会自动合并;请选择要保留的一边。`;
uploadManualSyncBtn.textContent = "用本机覆盖共享";
downloadManualSyncBtn.textContent = "用共享覆盖本机";
uploadManualSyncBtn.hidden = false;
downloadManualSyncBtn.hidden = false;
}
function manualSyncErrorMessage(err) {
const code = err && err.message ? err.message : String(err);
const messages = {
snapshot_exceeds_safe_sync_capacity: "词库快照超过 Chrome Sync 的安全容量,请先导出备份并精简词库",
snapshot_item_exceeds_sync_quota: "词库分块仍超过 Chrome Sync 单项配额",
sync_snapshot_hash_mismatch: "共享快照哈希不一致,已拒绝读取",
sync_chunk_missing: "共享快照缺少分块,已拒绝读取",
sync_snapshot_invalid_json: "共享快照格式无效,已拒绝读取",
sync_snapshot_not_canonical: "共享快照格式异常,已拒绝读取",
unsupported_sync_schema: "共享快照版本暂不受支持",
sync_changed_during_upload: "上传期间共享快照被另一台设备修改,请重新检查",
sync_quota_would_be_exceeded: "写入会超过 Chrome Sync 总容量,未执行上传",
};
return messages[code] || code;
}
async function checkManualSyncStatus() {
if (manualSyncBusy) return;
setManualSyncBusy(true);
hideManualSyncActions();
manualSyncSummaryEl.textContent = "正在读取并校验共享快照...";
try {
const context = await inspectManualSync();
if (
context.status === "in_sync" &&
context.remote &&
context.remote.kind === "snapshot" &&
context.baseFingerprint !== context.remote.fingerprint
) {
const deviceId = await ensureManualDeviceId(
context.localItems[manualSync.LOCAL_DEVICE_ID_KEY]
);
await storageSet("local", {
[manualSync.LOCAL_BASE_REVISION_KEY]: context.remote.revision,
[manualSync.LOCAL_BASE_FINGERPRINT_KEY]: context.remote.fingerprint,
[manualSync.LOCAL_DEVICE_ID_KEY]: deviceId,
[manualSync.LOCAL_LAST_SYNCED_AT_KEY]: new Date().toISOString(),
});
context.baseRevision = context.remote.revision;
context.baseFingerprint = context.remote.fingerprint;
}
renderManualSyncContext(context);
setStatus("手动同步状态检查完成");
} catch (err) {
manualSyncContext = null;
manualSyncSummaryEl.textContent = `检查失败:${manualSyncErrorMessage(err)}`;
setStatus(`手动同步检查失败: ${manualSyncErrorMessage(err)}`, true);
} finally {
setManualSyncBusy(false);
}
}
function uploadAllowed(context) {
if (!context) return false;
if (context.status === "in_sync") return remoteNeedsSnapshotMigration(context.remote);
return ["remote_missing", "local_ahead", "conflict", "conflict_unlinked"].includes(context.status);
}
async function uploadManualSnapshot() {
if (manualSyncBusy) return;
setManualSyncBusy(true);
try {
const context = await inspectManualSync();
renderManualSyncContext(context);
if (!uploadAllowed(context)) {
setStatus("同步状态已变化,请按当前提示选择操作", true);
return;
}
const warning = context.remote
? `将以本机词库(${manualSyncCounts(context.localState)})覆盖共享快照。继续?`
: `将以本机词库(${manualSyncCounts(context.localState)})创建共享快照。继续?`;
if (!window.confirm(warning)) return;
const deviceId = await ensureManualDeviceId(
context.localItems[manualSync.LOCAL_DEVICE_ID_KEY]
);
const nextRevision = Math.max(context.baseRevision, context.remote ? context.remote.revision : 0) + 1;
const snapshot = await manualSync.buildSnapshot(context.localState, {
revision: nextRevision,
deviceId,
});
const currentBytes = await storageBytesInUse("sync");
const projectedBytes = currentBytes + manualSync.itemsStorageBytes(snapshot.chunkItems);
const syncQuota = Number(chrome.storage.sync.QUOTA_BYTES) || 102400;
if (projectedBytes > Math.floor(syncQuota * 0.96)) {
throw new Error("sync_quota_would_be_exceeded");
}
await storageSet("sync", snapshot.chunkItems);
await storageSet("sync", { [manualSync.META_KEY]: snapshot.meta });
const verifyItems = await storageGet("sync", null);
const verified = await manualSync.decodeSnapshot(verifyItems);
if (
!verified ||
verified.kind !== "snapshot" ||
verified.generation !== snapshot.generation ||
verified.fingerprint !== snapshot.fingerprint
) {
throw new Error("sync_changed_during_upload");
}
const staleKeys = manualSync.staleManagedKeys(verifyItems, snapshot.generation);
let cleanupWarning = "";
try {
await storageRemove("sync", staleKeys);
} catch (err) {
cleanupWarning = `;旧分块清理失败:${manualSyncErrorMessage(err)}`;
}
const syncedAt = new Date().toISOString();
await storageSet("local", {
[manualSync.LOCAL_BASE_REVISION_KEY]: snapshot.meta.revision,
[manualSync.LOCAL_BASE_FINGERPRINT_KEY]: snapshot.fingerprint,
[manualSync.LOCAL_DEVICE_ID_KEY]: deviceId,
[manualSync.LOCAL_LAST_SYNCED_AT_KEY]: syncedAt,
});
const updated = await inspectManualSync();
renderManualSyncContext(updated);
setStatus(`手动上传完成,版本 ${snapshot.meta.revision}${cleanupWarning}`, Boolean(cleanupWarning));
} catch (err) {
setStatus(`手动上传失败: ${manualSyncErrorMessage(err)}`, true);
manualSyncSummaryEl.textContent = `上传失败:${manualSyncErrorMessage(err)}`;
} finally {
setManualSyncBusy(false);
}
}
async function downloadManualSnapshot() {
if (manualSyncBusy) return;
setManualSyncBusy(true);
try {
const context = await inspectManualSync();
renderManualSyncContext(context);
if (!context.remote || context.status === "in_sync") {
setStatus("共享词库没有需要下载的变化", true);
return;
}
if (
!window.confirm(
`将使用共享词库(${manualSyncCounts(context.remote.state)})覆盖本机;当前本机词库会先保存为可恢复版本。继续?`
)
) {
return;
}
const deviceId = await ensureManualDeviceId(
context.localItems[manualSync.LOCAL_DEVICE_ID_KEY]
);
const downloadedAt = new Date().toISOString();
const beforeDownload = {
id: makeId(),
at: downloadedAt,
label: `before_manual_sync_download:r${context.remote.revision}`,
custom_vocab: context.localState.custom_vocab,
deleted_vocab: context.localState.deleted_vocab,
mastered_list: context.localState.mastered_list,
};
const storedBackups = Array.isArray(context.localItems.vocab_backups)
? context.localItems.vocab_backups
: backups;
const nextBackups = [beforeDownload, ...storedBackups].slice(0, MAX_BACKUPS);
await storageSet("local", {
custom_vocab: context.remote.state.custom_vocab,
deleted_vocab: context.remote.state.deleted_vocab,
mastered_list: context.remote.state.mastered_list,
vocab_backups: nextBackups,
current_vocab_version_id: null,
current_vocab_mode: "live",
vocab_sync_updated_at: context.remote.updatedAt || downloadedAt,
[manualSync.LOCAL_BASE_REVISION_KEY]: context.remote.revision,
[manualSync.LOCAL_BASE_FINGERPRINT_KEY]: context.remote.fingerprint,
[manualSync.LOCAL_DEVICE_ID_KEY]: deviceId,
[manualSync.LOCAL_LAST_SYNCED_AT_KEY]: downloadedAt,
});
customVocab = context.remote.state.custom_vocab;
deletedSet = new Set(context.remote.state.deleted_vocab);
masteredSet = new Set(context.remote.state.mastered_list);
backups = nextBackups;
currentVersionId = null;
currentVersionMode = "live";
pageViewMode = "live";
renderAll();
const updated = await inspectManualSync();
renderManualSyncContext(updated);
setStatus(`手动下载完成,共享版本 ${context.remote.revision}`);
} catch (err) {
setStatus(`手动下载失败: ${manualSyncErrorMessage(err)}`, true);
manualSyncSummaryEl.textContent = `下载失败:${manualSyncErrorMessage(err)}`;
} finally {
setManualSyncBusy(false);
}
}
function buildEffectiveVocab(custom, deletedWordSet) {
const merged = { ...baseVocab, ...custom };
deletedWordSet.forEach((word) => {
delete merged[word];
});
return merged;
}
function currentEffectiveVocab() {
return buildEffectiveVocab(customVocab, deletedSet);
}
function rankRowsForVocab(vocabMap, limit, preferWeekly) {
const weekMap = currentWeekCountMap();
const items = Object.entries(vocabMap).map(([word, definition]) => ({
word,
definition,
weekCount: weekMap[word] || 0,
totalCount: wordCounts[word] || 0,
}));
const byWeekly = items
.filter((it) => it.weekCount > 0)
.sort((a, b) => b.weekCount - a.weekCount || b.totalCount - a.totalCount || a.word.localeCompare(b.word));
if (preferWeekly && byWeekly.length > 0) {
return byWeekly.slice(0, limit);
}
const byTotal = items
.filter((it) => it.totalCount > 0)
.sort((a, b) => b.totalCount - a.totalCount || a.word.localeCompare(b.word));
if (byTotal.length > 0) {
return byTotal.slice(0, limit);
}
return items.sort((a, b) => a.word.localeCompare(b.word)).slice(0, limit);
}
function mergeRows(viewCustom, viewDeleted) {
const customMap = viewCustom || customVocab;
const deletedWordSet = viewDeleted || deletedSet;
const merged = {};
for (const [word, def] of Object.entries(baseVocab)) {
if (deletedWordSet.has(word)) continue;
merged[word] = {
word,
definition: def,
count: wordCounts[word] || 0,
hasBase: true,
hasCustom: false,
};
}
for (const [word, def] of Object.entries(customMap)) {
if (deletedWordSet.has(word)) continue;
const hasBase = Object.prototype.hasOwnProperty.call(baseVocab, word);
merged[word] = {
word,
definition: def,
count: wordCounts[word] || 0,
hasBase,
hasCustom: true,
};
}
rows = Object.values(merged).sort((a, b) => b.count - a.count || a.word.localeCompare(b.word));
}
function hiddenRowsForState(viewCustom, viewDeleted) {
const customMap = viewCustom || customVocab;
const deletedWordSet = viewDeleted || deletedSet;
return Array.from(deletedWordSet)
.map((word) => {
const hasBase = Object.prototype.hasOwnProperty.call(baseVocab, word);
const hasCustom = Object.prototype.hasOwnProperty.call(customMap, word);
return {
word,
definition: hasCustom ? customMap[word] : baseVocab[word] || "",
count: wordCounts[word] || 0,
hasBase,
hasCustom,
hidden: true,
};
})
.sort((a, b) => b.count - a.count || a.word.localeCompare(b.word));
}
function rowMatchesFilter(row) {
if (!currentFilter) return true;
return row.word.includes(currentFilter) || row.definition.toLowerCase().includes(currentFilter);
}
function rowsForCurrentSourceFilter() {
if (currentSourceFilter === "hidden") {
return hiddenRowsForState(customVocab, deletedSet);
}
if (currentSourceFilter === "custom") {
return rows.filter((row) => row.hasCustom);
}
if (currentSourceFilter === "base") {
return rows.filter((row) => row.hasBase && !row.hasCustom);
}
return rows;
}
function renderFilterState() {
for (const [filterName, button] of Object.entries(filterButtons)) {
const active = filterName === currentSourceFilter;
button.className = `filter-tab${active ? " active" : ""}`;
button.setAttribute("aria-pressed", active ? "true" : "false");
}
const titles = {
all: "我的词库",
custom: "你添加或修改过的词",
base: "默认词",
hidden: "已隐藏的词",
};
vocabSectionTitleEl.textContent = titles[currentSourceFilter] || titles.all;
}
function renderTable() {
tbody.innerHTML = "";
renderFilterState();
const filtered = rowsForCurrentSourceFilter().filter(rowMatchesFilter);
if (filtered.length === 0) {
const empty = document.createElement("p");
empty.className = "empty";
empty.textContent = currentSourceFilter === "hidden" ? "没有已隐藏的词" : "没有匹配的单词";
tbody.appendChild(empty);
return;
}
const makeItem = (row) => {
const item = document.createElement("button");
item.type = "button";
item.className = "vocab-item-row";
item.setAttribute("role", "listitem");
item.setAttribute(
"aria-label",
`${row.word},点读 ${row.count || 0} 次${row.hidden ? ",已隐藏" : ""}`
);
item.addEventListener("click", () => openWordDetail(row.word));
const word = document.createElement("span");
word.className = "row-word";
word.textContent = row.word;
const count = document.createElement("span");
count.className = "row-count";
count.textContent = String(row.count || 0);
const chevron = document.createElement("span");
chevron.className = "row-chevron";
chevron.setAttribute("aria-hidden", "true");
chevron.textContent = "›";
item.appendChild(word);
item.appendChild(count);
item.appendChild(chevron);
return item;
};
for (let index = 0; index < filtered.length; index += 2) {
const pair = document.createElement("div");
pair.className = "vocab-pair-row";
pair.appendChild(makeItem(filtered[index]));
if (filtered[index + 1]) pair.appendChild(makeItem(filtered[index + 1]));
tbody.appendChild(pair);
}
}
function renderWeeklyTop(viewVocabMap) {
const vocab = viewVocabMap || currentEffectiveVocab();
weeklyTopListEl.innerHTML = "";
const topRows = rankRowsForVocab(vocab, 10, true);
const weekKey = getCurrentWeekKey();
const weeklyMap = currentWeekCountMap();
const weekWords = Object.keys(weeklyMap).length;
if (topRows.length === 0) {
weeklySummaryEl.textContent = `周次 ${weekKey} | 暂无记录`;
const empty = document.createElement("p");
empty.className = "empty";
empty.textContent = "本周还没有点击记录。";
weeklyTopListEl.appendChild(empty);
return;
}
weeklySummaryEl.textContent = `周次 ${weekKey} | 本周已记录 ${weekWords} 个词`;
topRows.forEach((row, idx) => {
const line = document.createElement("div");
line.className = "weekly-row";
const rank = document.createElement("span");
rank.className = "rank";
rank.textContent = `#${idx + 1}`;
const word = document.createElement("span");
word.className = "word";
word.textContent = `${row.word} · ${shortText(row.definition, 28)}`;
const count = document.createElement("span");
count.className = "count";
count.textContent = row.weekCount > 0 ? `${row.weekCount}次` : `${row.totalCount}次(总)`;
line.appendChild(rank);
line.appendChild(word);
line.appendChild(count);
weeklyTopListEl.appendChild(line);
});
}
function latestThreeVersions() {
const latest = backups.slice(0, 3);
if (currentVersionMode !== "version" || !currentVersionId) return latest;
if (latest.some((item) => item.id === currentVersionId)) return latest;
const currentSnapshot = backups.find((item) => item.id === currentVersionId);
if (!currentSnapshot) return latest;
if (latest.length < 3) {
return [...latest, currentSnapshot];
}
return [latest[0], latest[1], currentSnapshot];
}
function snapshotToVocab(snapshot) {
const custom = sanitizeWordMap(snapshot && snapshot.custom_vocab);
const deleted = new Set(sanitizeWordList(snapshot && snapshot.deleted_vocab));
return buildEffectiveVocab(custom, deleted);
}
function snapshotDisplayText(snapshot) {
if (!snapshot) return "Unknown";
return `${formatTime(snapshot.at)} · ${snapshot.label || "manual"}`;
}
function getCurrentViewSnapshot() {
if (pageViewMode !== "version" || !selectedVersionId) return null;
return backups.find((item) => item.id === selectedVersionId) || null;
}
function getDisplayedVocabState() {
const snapshot = getCurrentViewSnapshot();
if (!snapshot) {
return {
mode: "live",
snapshot: null,
custom: sanitizeWordMap(customVocab),
deleted: new Set(sanitizeWordList(Array.from(deletedSet))),
effective: currentEffectiveVocab(),
};
}
const custom = sanitizeWordMap(snapshot.custom_vocab);
const deleted = new Set(sanitizeWordList(snapshot.deleted_vocab));
return {
mode: "version",
snapshot,
custom,
deleted,
effective: buildEffectiveVocab(custom, deleted),
};
}
function renderViewContext(viewState) {
if (viewState.mode === "version" && viewState.snapshot) {
vocabSectionTitleEl.textContent = `词库预览:${snapshotDisplayText(viewState.snapshot)}`;