forked from YUZU-Hub/appscreen
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlanguage-utils.js
More file actions
565 lines (483 loc) · 19.1 KB
/
Copy pathlanguage-utils.js
File metadata and controls
565 lines (483 loc) · 19.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
// Language utilities for localized screenshot management
// This file handles language detection, localized image management, and translation dialogs
// Current screenshot index for translations modal
let currentTranslationsIndex = null;
/**
* Extract the base filename without language suffix
* e.g., "screenshot_de.png" -> "screenshot", "image-fr.png" -> "image"
* @param {string} filename - The filename to parse
* @returns {string} - Base filename without language suffix and extension
*/
function getBaseFilename(filename) {
// Remove extension
const withoutExt = filename.replace(/\.[^.]+$/, '');
// All supported language codes from languageFlags
const supportedLangs = Object.keys(languageFlags);
// Sort by length (longest first) to match pt-br before pt
const sortedLangs = [...supportedLangs].sort((a, b) => b.length - a.length);
for (const lang of sortedLangs) {
// Match patterns like: _pt-br, -pt-br, _pt_br, -pt_br, _de, -de
const escapedLang = lang.replace('-', '[-_]?');
const pattern = new RegExp(`[_-]${escapedLang}(?:[_-][a-z]{2})?$`, 'i');
if (pattern.test(withoutExt)) {
return withoutExt.replace(pattern, '');
}
}
return withoutExt;
}
/**
* Find an existing screenshot with a matching base filename
* @param {string} filename - The filename to check
* @returns {number} - Index of matching screenshot, or -1 if not found
*/
function findScreenshotByBaseFilename(filename) {
const baseName = getBaseFilename(filename);
for (let i = 0; i < state.screenshots.length; i++) {
const screenshot = state.screenshots[i];
if (!screenshot.localizedImages) continue;
// Check each localized image's filename
for (const lang of Object.keys(screenshot.localizedImages)) {
const localizedName = screenshot.localizedImages[lang]?.name;
if (localizedName && getBaseFilename(localizedName) === baseName) {
return i;
}
}
}
return -1;
}
/**
* Detect language code from filename
* Supports patterns like: screenshot_de.png, screenshot-fr.png, screenshot_pt-br.png
* @param {string} filename - The filename to parse
* @returns {string} - Language code (e.g., 'de', 'fr', 'pt-br') or 'en' as fallback
*/
function detectLanguageFromFilename(filename) {
// All supported language codes from languageFlags (defined in app.js)
const supportedLangs = Object.keys(languageFlags);
// Normalize filename for matching
const lower = filename.toLowerCase();
// Check for longer codes first (pt-br, zh-tw, en-gb) to avoid false matches
const sortedLangs = [...supportedLangs].sort((a, b) => b.length - a.length);
for (const lang of sortedLangs) {
// Match patterns like: _pt-br., -pt-br., _pt_br., -pt_br.
// Also: _de., -de., _DE., -DE., _de-DE., etc.
const escapedLang = lang.replace('-', '[-_]?');
const pattern = new RegExp(`[_-]${escapedLang}(?:[_-][a-z]{2})?\\.`, 'i');
if (pattern.test(lower)) {
return lang;
}
}
return 'en'; // fallback to English
}
/**
* Get the appropriate image for a screenshot based on current language
* Falls back to first available language if current language has no image
* @param {Object} screenshot - The screenshot object
* @returns {Image|null} - The Image object to use for rendering
*/
function getScreenshotImage(screenshot) {
if (!screenshot) return null;
const lang = state.currentLanguage;
// Try current language first
if (screenshot.localizedImages?.[lang]?.image) {
return screenshot.localizedImages[lang].image;
}
// Fallback to first available language in project order
for (const l of state.projectLanguages) {
if (screenshot.localizedImages?.[l]?.image) {
return screenshot.localizedImages[l].image;
}
}
// Fallback to any available language
if (screenshot.localizedImages) {
for (const l of Object.keys(screenshot.localizedImages)) {
if (screenshot.localizedImages[l]?.image) {
return screenshot.localizedImages[l].image;
}
}
}
// Legacy fallback for old screenshot format
return screenshot.image || null;
}
/**
* Get list of languages that have images for a screenshot
* @param {Object} screenshot - The screenshot object
* @returns {string[]} - Array of language codes that have images
*/
function getAvailableLanguagesForScreenshot(screenshot) {
if (!screenshot?.localizedImages) return [];
return Object.keys(screenshot.localizedImages).filter(
lang => screenshot.localizedImages[lang]?.image
);
}
/**
* Check if a screenshot has images for all project languages
* @param {Object} screenshot - The screenshot object
* @returns {boolean} - True if all project languages have images
*/
function isScreenshotComplete(screenshot) {
if (!screenshot?.localizedImages) return false;
if (state.projectLanguages.length === 0) return true;
return state.projectLanguages.every(
lang => screenshot.localizedImages[lang]?.image
);
}
/**
* Migrate old screenshot format to new localized format
* Moves image to localizedImages.en (or detected language)
* @param {Object} screenshot - The screenshot object to migrate
* @param {string} detectedLang - Optional detected language from filename
*/
function migrateScreenshotToLocalized(screenshot, detectedLang = 'en') {
if (!screenshot) return;
// Already migrated
if (screenshot.localizedImages && Object.keys(screenshot.localizedImages).length > 0) {
return;
}
// Initialize localizedImages if needed
if (!screenshot.localizedImages) {
screenshot.localizedImages = {};
}
// Move legacy image to localized storage
if (screenshot.image) {
screenshot.localizedImages[detectedLang] = {
image: screenshot.image,
src: screenshot.image.src,
name: screenshot.name || 'screenshot.png'
};
}
}
/**
* Add a localized image to a screenshot
* @param {number} screenshotIndex - Index of the screenshot
* @param {string} lang - Language code
* @param {Image} image - The Image object
* @param {string} src - Data URL of the image
* @param {string} name - Filename
*/
function addLocalizedImage(screenshotIndex, lang, image, src, name) {
const screenshot = state.screenshots[screenshotIndex];
if (!screenshot) return;
if (!screenshot.localizedImages) {
screenshot.localizedImages = {};
}
screenshot.localizedImages[lang] = {
image: image,
src: src,
name: name
};
// Auto-add language to project if not already present
if (!state.projectLanguages.includes(lang)) {
addProjectLanguage(lang);
}
// Update displays
updateScreenshotList();
updateCanvas();
saveState();
}
/**
* Remove a localized image from a screenshot
* @param {number} screenshotIndex - Index of the screenshot
* @param {string} lang - Language code to remove
*/
function removeLocalizedImage(screenshotIndex, lang) {
const screenshot = state.screenshots[screenshotIndex];
if (!screenshot?.localizedImages?.[lang]) return;
delete screenshot.localizedImages[lang];
// Update displays
updateScreenshotList();
updateCanvas();
saveState();
// Refresh modal if open
if (currentTranslationsIndex === screenshotIndex) {
updateScreenshotTranslationsList();
}
}
// ==========================================
// Screenshot Translations Modal Functions
// ==========================================
/**
* Open the screenshot translations modal for a specific screenshot
* @param {number} index - Index of the screenshot to manage
*/
function openScreenshotTranslationsModal(index) {
currentTranslationsIndex = index;
const modal = document.getElementById('screenshot-translations-modal');
if (!modal) return;
modal.classList.add('visible');
updateScreenshotTranslationsList();
}
/**
* Close the screenshot translations modal
*/
function closeScreenshotTranslationsModal() {
currentTranslationsIndex = null;
const modal = document.getElementById('screenshot-translations-modal');
if (modal) {
modal.classList.remove('visible');
}
}
/**
* Update the list of languages in the translations modal
*/
function updateScreenshotTranslationsList() {
const container = document.getElementById('screenshot-translations-list');
if (!container || currentTranslationsIndex === null) return;
const screenshot = state.screenshots[currentTranslationsIndex];
if (!screenshot) return;
container.innerHTML = '';
state.projectLanguages.forEach(lang => {
const hasImage = screenshot.localizedImages?.[lang]?.image;
const flag = languageFlags[lang] || '🏳️';
const name = languageNames[lang] || lang.toUpperCase();
const item = document.createElement('div');
item.className = 'translation-item' + (hasImage ? ' has-image' : '');
if (hasImage) {
// Create thumbnail
const thumbCanvas = document.createElement('canvas');
thumbCanvas.width = 40;
thumbCanvas.height = 86;
const ctx = thumbCanvas.getContext('2d');
const img = screenshot.localizedImages[lang].image;
const scale = Math.min(40 / img.width, 86 / img.height);
const w = img.width * scale;
const h = img.height * scale;
ctx.drawImage(img, (40 - w) / 2, (86 - h) / 2, w, h);
item.innerHTML = `
<div class="translation-thumb">
<img src="${thumbCanvas.toDataURL()}" alt="${name}">
</div>
<div class="translation-info">
<span class="flag">${flag}</span>
<span class="name">${name}</span>
</div>
<button class="translation-remove" title="Remove ${name} screenshot">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>
</button>
`;
item.querySelector('.translation-remove').addEventListener('click', () => {
removeLocalizedImage(currentTranslationsIndex, lang);
});
} else {
item.innerHTML = `
<div class="translation-thumb empty">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
<circle cx="8.5" cy="8.5" r="1.5"/>
<path d="M21 15l-5-5L5 21"/>
</svg>
</div>
<div class="translation-info">
<span class="flag">${flag}</span>
<span class="name">${name}</span>
</div>
<button class="translation-upload" title="Upload ${name} screenshot">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
Upload
</button>
`;
item.querySelector('.translation-upload').addEventListener('click', () => {
uploadScreenshotForLanguage(lang);
});
}
container.appendChild(item);
});
}
/**
* Trigger file upload for a specific language
* @param {string} lang - Language code to upload for
*/
function uploadScreenshotForLanguage(lang) {
const input = document.getElementById('translation-file-input');
if (!input) return;
// Store the target language
input.dataset.targetLang = lang;
input.click();
}
/**
* Handle file selection for translation upload
* @param {Event} event - The change event from file input
*/
function handleTranslationFileSelect(event) {
const input = event.target;
const lang = input.dataset.targetLang;
const file = input.files?.[0];
if (!file || !lang || currentTranslationsIndex === null) {
input.value = '';
return;
}
if (!file.type.startsWith('image/')) {
input.value = '';
return;
}
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
addLocalizedImage(currentTranslationsIndex, lang, img, e.target.result, file.name);
updateScreenshotTranslationsList();
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
input.value = '';
}
// ==========================================
// Export Language Dialog Functions
// ==========================================
/**
* Show export language choice dialog
* @param {Function} callback - Function to call with choice ('current' or 'all')
*/
function showExportLanguageDialog(callback) {
const modal = document.getElementById('export-language-modal');
if (!modal) {
// Fallback if modal doesn't exist
callback('current');
return;
}
// Store callback for later
window._exportLanguageCallback = callback;
// Update current language display
const currentLangDisplay = document.getElementById('export-current-lang');
if (currentLangDisplay) {
const flag = languageFlags[state.currentLanguage] || '🏳️';
const name = languageNames[state.currentLanguage] || state.currentLanguage.toUpperCase();
currentLangDisplay.textContent = `${flag} ${name}`;
}
modal.classList.add('visible');
}
/**
* Close export language dialog and execute callback
* @param {string} choice - 'current' or 'all'
*/
function closeExportLanguageDialog(choice) {
const modal = document.getElementById('export-language-modal');
if (modal) {
modal.classList.remove('visible');
}
if (window._exportLanguageCallback && choice) {
window._exportLanguageCallback(choice);
window._exportLanguageCallback = null;
}
}
// ==========================================
// Duplicate Screenshot Dialog Functions
// ==========================================
// Queue for pending duplicate resolution
let duplicateQueue = [];
let currentDuplicateResolve = null;
/**
* Show duplicate screenshot dialog
* @param {Object} params - Parameters for the dialog
* @param {number} params.existingIndex - Index of existing screenshot
* @param {string} params.detectedLang - Detected language of new file
* @param {Image} params.newImage - New image object
* @param {string} params.newSrc - Data URL of new image
* @param {string} params.newName - Filename of new file
* @returns {Promise<string>} - User choice: 'replace', 'create', or 'ignore'
*/
function showDuplicateDialog(params) {
return new Promise((resolve) => {
currentDuplicateResolve = resolve;
const modal = document.getElementById('duplicate-screenshot-modal');
if (!modal) {
resolve('create'); // fallback
return;
}
const screenshot = state.screenshots[params.existingIndex];
const existingThumb = document.getElementById('duplicate-existing-thumb');
const newThumb = document.getElementById('duplicate-new-thumb');
const existingName = document.getElementById('duplicate-existing-name');
const newName = document.getElementById('duplicate-new-name');
const langNameEl = document.getElementById('duplicate-lang-name');
// Get existing thumbnail for the specific language being replaced
const existingLangImg = screenshot.localizedImages?.[params.detectedLang]?.image;
if (existingThumb) {
if (existingLangImg) {
existingThumb.innerHTML = `<img src="${existingLangImg.src}" alt="Existing">`;
} else {
// No existing image for this language - show empty placeholder
existingThumb.innerHTML = `
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="color: var(--text-secondary); opacity: 0.5;">
<rect x="3" y="3" width="18" height="18" rx="2"/>
<circle cx="8.5" cy="8.5" r="1.5"/>
<path d="M21 15l-5-5L5 21"/>
</svg>
`;
}
}
// Set new thumbnail
if (newThumb && params.newImage) {
newThumb.innerHTML = `<img src="${params.newSrc}" alt="New">`;
}
// Set filenames
if (existingName) {
const existingLangName = screenshot.localizedImages?.[params.detectedLang]?.name;
if (existingLangName) {
existingName.textContent = existingLangName;
} else {
// Show that no image exists for this language yet
const flag = languageFlags[params.detectedLang] || '🏳️';
existingName.textContent = `No ${flag} image`;
}
}
if (newName) {
newName.textContent = params.newName;
}
// Set language name in replace description
if (langNameEl) {
const flag = languageFlags[params.detectedLang] || '🏳️';
const name = languageNames[params.detectedLang] || params.detectedLang.toUpperCase();
langNameEl.textContent = `${flag} ${name}`;
}
// Store params for handlers
modal.dataset.existingIndex = params.existingIndex;
modal.dataset.detectedLang = params.detectedLang;
window._duplicateNewImage = params.newImage;
window._duplicateNewSrc = params.newSrc;
window._duplicateNewName = params.newName;
modal.classList.add('visible');
});
}
/**
* Close duplicate dialog with a choice
* @param {string} choice - 'replace', 'create', or 'ignore'
*/
function closeDuplicateDialog(choice) {
const modal = document.getElementById('duplicate-screenshot-modal');
if (modal) {
modal.classList.remove('visible');
}
if (currentDuplicateResolve) {
currentDuplicateResolve(choice);
currentDuplicateResolve = null;
}
// Clean up stored data
window._duplicateNewImage = null;
window._duplicateNewSrc = null;
window._duplicateNewName = null;
}
/**
* Initialize duplicate dialog event listeners
*/
function initDuplicateDialogListeners() {
const replaceBtn = document.getElementById('duplicate-replace');
const createBtn = document.getElementById('duplicate-create-new');
const ignoreBtn = document.getElementById('duplicate-ignore');
if (replaceBtn) {
replaceBtn.addEventListener('click', () => closeDuplicateDialog('replace'));
}
if (createBtn) {
createBtn.addEventListener('click', () => closeDuplicateDialog('create'));
}
if (ignoreBtn) {
ignoreBtn.addEventListener('click', () => closeDuplicateDialog('ignore'));
}
}