-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsewing_tools_launcher.html
More file actions
688 lines (591 loc) · 24.1 KB
/
sewing_tools_launcher.html
File metadata and controls
688 lines (591 loc) · 24.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sewing Tools</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #333;
}
.container {
background: white;
border-radius: 16px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
padding: 48px 40px;
max-width: 450px;
width: 90%;
text-align: center;
}
h1 {
font-size: 28px;
margin-bottom: 8px;
color: #222;
}
.subtitle {
color: #999;
font-size: 14px;
margin-bottom: 24px;
}
.message {
font-size: 16px;
color: #555;
line-height: 1.6;
margin: 20px 0;
}
.status {
font-size: 13px;
color: #999;
margin: 12px 0;
height: 20px;
}
.spinner {
display: inline-block;
width: 18px;
height: 18px;
border: 3px solid #f0f0f0;
border-top-color: #667eea;
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-right: 8px;
vertical-align: middle;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Update Notification */
.notification {
position: fixed;
top: 24px;
right: 24px;
background: white;
padding: 20px 24px;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
z-index: 1000;
max-width: 320px;
animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.notification-title {
font-weight: 600;
margin-bottom: 12px;
color: #222;
font-size: 14px;
}
.notification-text {
font-size: 13px;
color: #666;
margin-bottom: 12px;
line-height: 1.5;
}
.notification-buttons {
display: flex;
gap: 8px;
}
button {
padding: 8px 16px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
transition: all 0.2s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-1px);
}
.btn-secondary {
background: #f0f0f0;
color: #333;
}
.btn-secondary:hover {
background: #e0e0e0;
}
.error {
color: #d32f2f;
background: #ffebee;
padding: 12px 16px;
border-radius: 8px;
margin: 12px 0;
font-size: 13px;
}
.version-info {
font-size: 12px;
color: #bbb;
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #eee;
}
@media (max-width: 480px) {
.container {
padding: 32px 24px;
}
.notification {
top: 12px;
right: 12px;
left: 12px;
max-width: none;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Sewing Tools</h1>
<div class="message" id="message">Initializing...</div>
<div class="status" id="status"></div>
<div id="errorContainer"></div>
<div class="version-info">
<span id="versionText">v0.0.0</span>
</div>
</div>
<script>
// ============================================================================
// CONFIGURATION
// ============================================================================
const CONFIG = {
GITHUB_USER: 'mbarneche',
GITHUB_REPO: 'sewing_tools',
APP_ROOT_PATH: 'app/',
MANIFEST_PATH: 'app/manifest.json',
UPDATE_CHECK_INTERVAL: 7 * 24 * 60 * 60 * 1000, // 7 days in milliseconds
JSZIP_CDN: ''
};
const DB_NAME = 'SewingToolsDB';
const DB_VERSION = 1;
const STORE_NAME = 'files';
const META_KEY = '__metadata__';
let db;
// ============================================================================
// IndexedDB OPERATIONS
// ============================================================================
async function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve();
};
request.onupgradeneeded = (event) => {
const database = event.target.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME);
}
};
});
}
async function storeFile(path, content) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(content, path);
request.onerror = () => reject(request.error);
request.onsuccess = resolve;
});
}
async function getFile(path) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(path);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function deleteFile(path) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(path);
request.onerror = () => reject(request.error);
request.onsuccess = resolve;
});
}
async function getAllKeys() {
return new Promise((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.getAllKeys();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function getMetadata() {
return getFile(META_KEY);
}
async function storeMetadata(data) {
return storeFile(META_KEY, data);
}
// ============================================================================
// GITHUB API OPERATIONS
// ============================================================================
async function getLatestRelease() {
const url = `https://api.github.com/repos/${CONFIG.GITHUB_USER}/${CONFIG.GITHUB_REPO}/releases/latest`;
const response = await fetch(url, {
headers: { 'Accept': 'application/vnd.github+json' }
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`GitHub API error (${response.status}): ${detail}`);
}
return response.json();
}
async function downloadFile(url) {
const response = await fetch(url);
if (!response.ok) {
const detail = await response.text();
throw new Error(`Download failed (${response.status}): ${detail}`);
}
return response.arrayBuffer();
}
async function downloadJson(url) {
const response = await fetch(url, {
headers: { 'Accept': 'application/json' }
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`Download failed (${response.status}): ${detail}`);
}
return response.json();
}
function getManifestUrl(release) {
const tag = release.tag_name;
const path = (CONFIG.MANIFEST_PATH || '').replace(/^\/+/, '');
if (tag && path) {
return `https://raw.githubusercontent.com/${CONFIG.GITHUB_USER}/${CONFIG.GITHUB_REPO}/${tag}/${path}`;
}
throw new Error('Manifest path is missing. Set CONFIG.MANIFEST_PATH.');
}
function getRawFileUrl(release, filePath) {
const tag = release.tag_name;
const appRoot = String(CONFIG.APP_ROOT_PATH || '').replace(/^\/+/, '');
const path = String(filePath || '').replace(/^\/+/, '');
if (!tag || !path) {
throw new Error('Manifest contains an invalid file path.');
}
return `https://raw.githubusercontent.com/${CONFIG.GITHUB_USER}/${CONFIG.GITHUB_REPO}/${tag}/${appRoot}${path}`;
}
async function downloadAndStoreManifestFiles(release) {
updateStatus('Downloading manifest...');
const manifestUrl = getManifestUrl(release);
const manifest = await downloadJson(manifestUrl);
const files = Array.isArray(manifest.files) ? manifest.files : [];
if (files.length === 0) {
throw new Error('Manifest has no files. Check app/manifest.json.');
}
let fileCount = 0;
for (const filePath of files) {
const fileUrl = getRawFileUrl(release, filePath);
const content = await downloadFile(fileUrl);
await storeFile(filePath, content);
fileCount++;
if (fileCount % 10 === 0) {
updateStatus(`Downloading files... (${fileCount}/${files.length})`);
}
}
const metadata = {
version: release.tag_name,
downloadedAt: new Date().toISOString(),
lastUpdateCheck: new Date().getTime(),
files
};
await storeMetadata(metadata);
return fileCount;
}
// ============================================================================
// UI UPDATES
// ============================================================================
function updateMessage(msg) {
const element = document.getElementById('message');
if (element) element.textContent = msg;
}
function updateStatus(msg) {
const element = document.getElementById('status');
if (element) {
if (msg) {
element.innerHTML = `<span class="spinner"></span>${msg}`;
} else {
element.textContent = '';
}
}
}
function setVersion(version) {
const element = document.getElementById('versionText');
if (element) element.textContent = `v${version.replace(/^v/, '')}`;
}
function showError(message) {
const container = document.getElementById('errorContainer');
if (container) {
container.innerHTML = `<div class="error">${message}</div>`;
}
}
function clearError() {
const container = document.getElementById('errorContainer');
if (container) container.innerHTML = '';
}
// ============================================================================
// NOTIFICATIONS
// ============================================================================
function showNotification(title, message, onConfirm, onCancel) {
const notification = document.createElement('div');
notification.className = 'notification';
const confirmBtn = document.createElement('button');
confirmBtn.className = 'btn-primary';
confirmBtn.textContent = 'Yes';
confirmBtn.onclick = () => {
notification.remove();
onConfirm();
};
const cancelBtn = document.createElement('button');
cancelBtn.className = 'btn-secondary';
cancelBtn.textContent = 'Not Now';
cancelBtn.onclick = () => {
notification.remove();
onCancel && onCancel();
};
notification.innerHTML = `
<div class="notification-title">${title}</div>
<div class="notification-text">${message}</div>
<div class="notification-buttons"></div>
`;
notification.querySelector('.notification-buttons').appendChild(confirmBtn);
notification.querySelector('.notification-buttons').appendChild(cancelBtn);
document.body.appendChild(notification);
// Auto-dismiss after 30 seconds if not interacted
setTimeout(() => {
if (notification.parentElement) {
notification.remove();
onCancel && onCancel();
}
}, 30000);
}
// ============================================================================
// UPDATE CHECKING
// ============================================================================
async function checkForUpdates() {
try {
const metadata = await getMetadata();
if (!metadata) return; // First run, nothing to update
updateStatus('Checking for updates...');
const release = await getLatestRelease();
const currentVersion = metadata.version;
const newVersion = release.tag_name;
// Update last check time
metadata.lastUpdateCheck = new Date().getTime();
await storeMetadata(metadata);
if (currentVersion !== newVersion) {
clearError();
showNotification(
`📦 Update available: ${newVersion}`,
`Your current version: ${currentVersion}<br>Download and install the new version?`,
async () => await downloadUpdate(release),
() => updateStatus('')
);
} else {
updateStatus('Already up to date');
setTimeout(() => updateStatus(''), 2500);
}
} catch (error) {
console.error('Update check failed:', error);
updateStatus('');
showError('⚠️ Could not check for updates (offline?)');
setTimeout(clearError, 5000);
}
}
async function downloadUpdate(release) {
try {
updateStatus('Downloading update...');
updateStatus('Installing update...');
// Clear old files
const oldKeys = await getAllKeys();
for (const key of oldKeys) {
if (key !== META_KEY) {
await deleteFile(key);
}
}
// Download and store new files
await downloadAndStoreManifestFiles(release);
showNotification(
'✅ Update installed',
'Reloading app...',
() => location.reload(),
() => location.reload()
);
} catch (error) {
console.error('Update download failed:', error);
updateStatus('');
showError(`❌ Update failed: ${error.message}`);
showNotification(
'⚠️ Update failed',
'Continue with current version?',
() => openApp(),
() => openApp()
);
}
}
// ============================================================================
// OPENING THE APP
// ============================================================================
async function openApp() {
try {
updateStatus('Opening app...');
// Register service worker to serve files from IndexedDB
// Service Workers only work with http/https, not file://
const isFileProtocol = window.location.protocol === 'file:';
if ('serviceWorker' in navigator && !isFileProtocol) {
await registerServiceWorker();
}
// Redirect to app page
setTimeout(() => {
// For file:// protocol, use relative path; for http(s), use absolute path
const appPath = isFileProtocol ? './app/index.html' : '/app/';
window.location.href = appPath;
}, 500);
} catch (error) {
console.error('Failed to open app:', error);
showError('Error loading app. Please refresh the page.');
}
}
// ============================================================================
// SERVICE WORKER
// ============================================================================
async function registerServiceWorker() {
// Only register service worker if not using file:// protocol
protocol = window.location.protocol;
isFileProtocol = protocol === 'file:' || protocol === 'filesystem:' || protocol === 'content:';
if (isFileProtocol) {
console.warn(`Service Worker not available with ${protocol}// protocol. Files will be served directly.`);
return;
}
try {
const swCode = `
const DB_NAME = '${DB_NAME}';
const STORE_NAME = '${STORE_NAME}';
async function getFromDB(path) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME);
request.onsuccess = () => {
const db = request.result;
const transaction = db.transaction([STORE_NAME], 'readonly');
const store = transaction.objectStore(STORE_NAME);
const req = store.get(path);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
};
request.onerror = () => reject(request.error);
});
}
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (url.pathname === '/' || url.pathname === '/app/') {
event.respondWith(getFromDB('index.html').then(blob => {
return new Response(blob, {
headers: { 'Content-Type': 'text/html' }
});
}));
} else {
const filePath = url.pathname.replace(/^\\/app\\//, '');
event.respondWith(
getFromDB(filePath).then(blob => {
if (!blob) {
return fetch(event.request);
}
const contentType = filePath.endsWith('.js') ? 'application/javascript' :
filePath.endsWith('.css') ? 'text/css' :
filePath.endsWith('.json') ? 'application/json' :
'text/plain';
return new Response(blob, {
headers: { 'Content-Type': contentType }
});
}).catch(() => fetch(event.request))
);
}
});
`;
const swBlob = new Blob([swCode], { type: 'application/javascript' });
const swUrl = URL.createObjectURL(swBlob);
await navigator.serviceWorker.register(swUrl, { scope: '/app/' });
} catch (error) {
console.warn('Service Worker registration failed:', error);
}
}
// ============================================================================
// INITIALIZATION
// ============================================================================
async function init() {
try {
await initDB();
const metadata = await getMetadata();
if (!metadata) {
// ===== FIRST RUN =====
updateMessage('Downloading Sewing Tools (first time)...');
updateStatus('Requires internet connection');
const release = await getLatestRelease();
updateStatus('Downloading files...');
await downloadAndStoreManifestFiles(release);
setVersion(release.tag_name);
updateMessage('Ready!');
updateStatus('');
setTimeout(() => openApp(), 1000);
} else {
// ===== RETURNING USER =====
setVersion(metadata.version);
updateMessage('Welcome back!');
updateStatus('');
// Check if we should prompt for updates
const timeSinceCheck = new Date().getTime() - metadata.lastUpdateCheck;
if (timeSinceCheck > CONFIG.UPDATE_CHECK_INTERVAL) {
// Prompt for update check
setTimeout(() => {
showNotification(
'🔄 Check for updates?',
'It means connecting to the internet briefly to see if there\'s a newer version.',
checkForUpdates,
() => openApp()
);
}, 600);
} else {
// No update check needed yet - just open the app silently
setTimeout(() => openApp(), 800);
}
}
} catch (error) {
console.error('Initialization error:', error);
updateMessage('Error');
showError(error.message);
}
}
// Start initialization
init();
</script>
</body>
</html>