-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpopup.js
More file actions
379 lines (342 loc) · 12.4 KB
/
Copy pathpopup.js
File metadata and controls
379 lines (342 loc) · 12.4 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
/**
* Popup Logic
* Handles manual sync buttons, status display, and conflict resolution.
*/
import { initI18n, applyI18n, getMessage } from './lib/i18n.js';
import { clearElement } from './lib/dom-utils.js';
import { formatSyncProgress, runSyncPortAction } from './lib/sync-progress.js';
import { initTheme } from './lib/theme.js';
import { initUiDensity } from './lib/ui-density.js';
import { mountWhatsNewIfPending } from './lib/whats-new-ui.js';
import { buildCommitUrl } from './lib/git-provider.js';
// DOM elements
const notConfiguredEl = document.getElementById('not-configured');
const configuredEl = document.getElementById('configured');
const statusArea = document.getElementById('status-area');
const profileSelect = document.getElementById('profile-select');
const statusMessage = document.getElementById('status-message');
const lastDataChangeEl = document.getElementById('last-data-change');
const lastCommitWrap = document.getElementById('last-commit-wrap');
const mirrorStatusEl = document.getElementById('mirror-status');
const conflictBox = document.getElementById('conflict-box');
const autoSyncDot = document.getElementById('auto-sync-dot');
const autoSyncText = document.getElementById('auto-sync-text');
const syncBtn = document.getElementById('sync-btn');
const syncSpinner = document.getElementById('sync-spinner');
const syncText = document.getElementById('sync-text');
const pushBtn = document.getElementById('push-btn');
const pullBtn = document.getElementById('pull-btn');
const forcePushBtn = document.getElementById('force-push-btn');
const forcePullBtn = document.getElementById('force-pull-btn');
const openSettingsBtn = document.getElementById('open-settings-btn');
const settingsLink = document.getElementById('settings-link');
const nextSyncCountdownEl = document.getElementById('next-sync-countdown');
const ALARM_NAME = 'bookmarkSyncPull';
let countdownInterval = null;
let isSyncing = false;
// Demo mode: show configured UI for screenshots without real storage (?demo=1)
const isDemoMode = () =>
typeof location !== 'undefined' &&
new URLSearchParams(location.search || '').get('demo') === '1';
// Initialize on load
document.addEventListener('DOMContentLoaded', async () => {
await initTheme();
await initUiDensity();
await initI18n();
applyI18n();
if (isDemoMode()) {
showDemoUI();
return;
}
await loadStatus();
await mountWhatsNewIfPending(document.body, {
getMessage,
manifestVersion: chrome.runtime.getManifest().version,
});
});
async function loadStatus() {
try {
const status = await chrome.runtime.sendMessage({ action: 'getStatus' });
updateUI(status);
} catch (err) {
console.error('Could not load status:', err);
showNotConfigured();
}
}
function updateUI(status) {
if (!status || !status.configured) {
showNotConfigured();
return;
}
notConfiguredEl.style.display = 'none';
configuredEl.style.display = 'block';
// Profile selector (only when 2+ profiles)
const profiles = status.profiles || [];
const activeProfileId = status.activeProfileId;
if (profiles.length >= 2) {
clearElement(profileSelect);
for (const p of profiles) {
const opt = document.createElement('option');
opt.value = p.id;
opt.textContent = p.name || p.id;
if (p.id === activeProfileId) opt.selected = true;
profileSelect.appendChild(opt);
}
profileSelect.style.display = '';
} else {
profileSelect.style.display = 'none';
clearElement(profileSelect);
}
// Status message
if (status.hasConflict) {
setStatus('⚠️', getMessage('popup_conflictDetected'), 'status-warning');
conflictBox.style.display = 'block';
} else if (status.lastError) {
setStatus('❌', status.lastError, 'status-error');
conflictBox.style.display = 'none';
} else if (status.lastSyncTime) {
setStatus('✅', getMessage('popup_synced'), 'status-ok');
conflictBox.style.display = 'none';
} else {
setStatus('📋', getMessage('popup_notSyncedYet'), 'status-ok');
conflictBox.style.display = 'none';
}
// Last data change (timestamp)
const dataChangeTime = status.lastSyncWithChangesTime || status.lastSyncTime;
if (dataChangeTime) {
lastDataChangeEl.textContent = getMessage('popup_lastDataChange', [formatRelativeTime(new Date(dataChangeTime))]);
lastDataChangeEl.style.display = '';
} else {
lastDataChangeEl.style.display = 'none';
}
// Last commit (hash as link)
if (status.lastCommitSha && status.repoOwner && status.repoName) {
const shortSha = status.lastCommitSha.substring(0, 7);
const url = buildCommitUrl({
provider: status.gitProvider || 'github',
serverUrl: status.serverUrl || '',
owner: status.repoOwner,
repo: status.repoName,
commitSha: status.lastCommitSha,
});
clearElement(lastCommitWrap);
lastCommitWrap.appendChild(document.createTextNode(getMessage('popup_lastCommit') + ' '));
const a = document.createElement('a');
a.href = url;
a.target = '_blank';
a.rel = 'noopener';
a.className = 'commit-link';
a.textContent = shortSha;
lastCommitWrap.appendChild(a);
lastCommitWrap.style.display = '';
} else {
clearElement(lastCommitWrap);
lastCommitWrap.style.display = 'none';
}
if (mirrorStatusEl) {
if (status.mirrorSummary) {
let text = getMessage('popup_mirrorStatus', [status.mirrorSummary]);
const failed = (status.mirrorStatuses || []).filter((m) => !m.paused && m.lastError);
if (failed.length) {
text += ` — ${failed.map((m) => m.lastError).join('; ')}`;
}
mirrorStatusEl.textContent = text;
mirrorStatusEl.style.display = '';
} else {
mirrorStatusEl.style.display = 'none';
}
}
// Auto-sync status
if (status.autoSync) {
autoSyncDot.className = 'dot dot-active';
autoSyncText.textContent = getMessage('popup_autoSyncActive');
startCountdown();
} else {
autoSyncDot.className = 'dot dot-inactive';
autoSyncText.textContent = getMessage('popup_autoSyncDisabled');
autoSyncText.style.display = '';
stopCountdown();
nextSyncCountdownEl.style.display = 'none';
}
}
function formatCountdown(ms) {
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
async function updateCountdown() {
const alarm = await chrome.alarms.get(ALARM_NAME);
if (!alarm || !alarm.scheduledTime) {
nextSyncCountdownEl.style.display = 'none';
autoSyncText.style.display = '';
return;
}
const remaining = alarm.scheduledTime - Date.now();
if (remaining <= 0) {
nextSyncCountdownEl.textContent = getMessage('popup_nextSyncIn', [formatCountdown(0)]);
} else {
nextSyncCountdownEl.textContent = getMessage('popup_nextSyncIn', [formatCountdown(remaining)]);
}
nextSyncCountdownEl.style.display = '';
autoSyncText.style.display = 'none';
}
function startCountdown() {
stopCountdown();
updateCountdown();
countdownInterval = setInterval(updateCountdown, 1000);
}
function stopCountdownUi() {
nextSyncCountdownEl.style.display = 'none';
autoSyncText.style.display = '';
}
function stopCountdown() {
if (countdownInterval) {
clearInterval(countdownInterval);
countdownInterval = null;
}
stopCountdownUi();
}
function showNotConfigured() {
notConfiguredEl.style.display = 'block';
configuredEl.style.display = 'none';
}
function showDemoUI() {
notConfiguredEl.style.display = 'none';
configuredEl.style.display = 'block';
profileSelect.style.display = 'none';
setStatus('✅', getMessage('popup_synced'), 'status-ok');
conflictBox.style.display = 'none';
lastDataChangeEl.textContent = getMessage('popup_lastDataChange', [
getMessage('popup_minAgo', [5]),
]);
lastDataChangeEl.style.display = '';
clearElement(lastCommitWrap);
lastCommitWrap.appendChild(document.createTextNode(getMessage('popup_lastCommit') + ' '));
const a = document.createElement('a');
a.href = 'https://github.com/example/repo/commit/abc1234';
a.target = '_blank';
a.rel = 'noopener';
a.className = 'commit-link';
a.textContent = 'abc1234';
lastCommitWrap.appendChild(a);
lastCommitWrap.style.display = '';
autoSyncDot.className = 'dot dot-active';
autoSyncText.textContent = getMessage('popup_autoSyncActive');
nextSyncCountdownEl.style.display = 'none';
}
function setStatus(_icon, message, boxClass) {
statusMessage.textContent = message;
statusArea.className = 'status-area' + (boxClass === 'status-error' ? ' status-error' : '');
}
function formatRelativeTime(date) {
const now = new Date();
const diffMs = now - date;
const diffMin = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMin / 60);
if (diffMin < 1) return getMessage('popup_justNow');
if (diffMin < 60) return getMessage('popup_minAgo', [diffMin]);
if (diffHours < 24) return getMessage('popup_hoursAgo', [diffHours]);
return date.toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
// ---- Button handlers ----
function setLoading(loading, progressText = null) {
isSyncing = loading;
syncBtn.disabled = loading;
pushBtn.disabled = loading;
pullBtn.disabled = loading;
forcePushBtn.disabled = loading;
forcePullBtn.disabled = loading;
profileSelect.disabled = loading;
syncSpinner.style.display = loading ? 'inline-block' : 'none';
const label = progressText || (loading ? getMessage('popup_syncing') : getMessage('popup_syncNow'));
syncText.textContent = loading ? label : getMessage('popup_syncNow');
if (loading) {
statusMessage.textContent = label;
statusArea.classList.add('status-loading');
} else {
statusArea.classList.remove('status-loading');
}
}
function updateSyncProgress(payload) {
if (!isSyncing) return;
const text = formatSyncProgress(payload);
syncText.textContent = text;
statusMessage.textContent = text;
}
const SYNC_PORT_ACTIONS = new Set(['sync', 'push', 'pull', 'bootstrapFirstSync']);
async function handleAction(action) {
if (isSyncing) return;
setLoading(true);
try {
const result = SYNC_PORT_ACTIONS.has(action)
? await runSyncPortAction(action, {}, updateSyncProgress)
: await chrome.runtime.sendMessage({ action });
if (result.success) {
await loadStatus();
setStatus('✅', result.message, 'status-ok');
conflictBox.style.display = 'none';
} else {
if (result.conflict) {
setStatus('⚠️', result.message, 'status-warning');
conflictBox.style.display = 'block';
} else {
setStatus('❌', result.message, 'status-error');
}
}
} catch (err) {
setStatus('❌', getMessage('popup_error', [err.message]), 'status-error');
} finally {
setLoading(false);
}
}
syncBtn.addEventListener('click', () => handleAction('sync'));
pushBtn.addEventListener('click', () => handleAction('push'));
pullBtn.addEventListener('click', () => handleAction('pull'));
// Profile switch
profileSelect.addEventListener('change', async (e) => {
const targetId = e.target.value;
const status = await chrome.runtime.sendMessage({ action: 'getStatus' }).catch(() => null);
const activeId = status?.activeProfileId;
if (!activeId || targetId === activeId) return;
if (isSyncing) {
profileSelect.value = activeId;
return;
}
setLoading(true);
syncText.textContent = getMessage('popup_profileSwitching');
try {
const result = await chrome.runtime.sendMessage({ action: 'switchProfile', targetId });
if (result?.success) {
await loadStatus();
setStatus('✅', result.message, 'status-ok');
conflictBox.style.display = 'none';
} else {
setStatus('❌', result?.message || getMessage('popup_error', ['Switch failed']), 'status-error');
profileSelect.value = activeId;
}
} catch (err) {
setStatus('❌', getMessage('popup_error', [err.message]), 'status-error');
profileSelect.value = activeId;
} finally {
setLoading(false);
}
});
forcePushBtn.addEventListener('click', () => handleAction('push'));
forcePullBtn.addEventListener('click', () => handleAction('pull'));
// Settings links (close popup after opening options)
openSettingsBtn.addEventListener('click', () => {
chrome.runtime.openOptionsPage();
window.close();
});
settingsLink.addEventListener('click', (e) => {
e.preventDefault();
chrome.runtime.openOptionsPage();
window.close();
});