Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
3472 lines (3190 loc) · 198 KB
/
Copy pathindex.html
File metadata and controls
3472 lines (3190 loc) · 198 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OVOS Localize — Help translate OpenVoiceOS skills</title>
<meta name="description" content="Translate OpenVoiceOS voice-assistant skills into your language. A GitHub-native, human-first localization platform with source-code context for accurate translations.">
<link rel="canonical" href="https://openvoiceos.github.io/ovos-localize/">
<meta name="theme-color" content="#0a0a0a">
<!-- Open Graph / social unfurl (crawlers do not run the hash router, so the
landing page carries the shared card) -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="OVOS Localize">
<meta property="og:title" content="OVOS Localize — Help translate OpenVoiceOS skills">
<meta property="og:description" content="A GitHub-native, human-first platform for translating OpenVoiceOS voice-assistant skills into your language.">
<meta property="og:url" content="https://openvoiceos.github.io/ovos-localize/">
<meta property="og:image" content="https://openvoiceos.github.io/ovos-localize/logo.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="OVOS Localize — Help translate OpenVoiceOS skills">
<meta name="twitter:description" content="A GitHub-native, human-first platform for translating OpenVoiceOS voice-assistant skills into your language.">
<meta name="twitter:image" content="https://openvoiceos.github.io/ovos-localize/logo.png">
<link rel="icon" type="image/png" href="logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
ovos: { bg: '#0a0a0a', card: '#171717', accent: '#ef4444', text: '#e5e5e5', muted: '#737373', input: '#262626', hover: '#1f1f1f' }
}
}
}
}
</script>
<style>
body { background: #0a0a0a; color: #e5e5e5; font-family: 'Inter', system-ui, -apple-system, sans-serif; }
a { color: #ef4444; }
a:hover { text-decoration: underline; }
code, .mono { font-family: ui-monospace, 'Cascadia Code', 'Fira Code', monospace; }
.slot { color: #fbbf24; font-weight: 600; font-family: ui-monospace, monospace; }
.badge { display: inline-flex; align-items: center; padding: 0.125rem 0.5rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; }
.badge-green { background: #166534; color: #86efac; }
.badge-amber { background: #713f12; color: #fde047; }
.badge-red { background: #7f1d1d; color: #fca5a5; }
.badge-blue { background: #450a0a; color: #fca5a5; }
.badge-gray { background: #262626; color: #a3a3a3; }
textarea { tab-size: 4; }
textarea:focus { outline: 2px solid #ef4444; outline-offset: -1px; }
/* Visible focus for keyboard users across interactive elements */
a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, [tabindex]:focus-visible {
outline: 2px solid #ef4444; outline-offset: 2px;
}
#app:focus { outline: 2px solid #4f9cf9; outline-offset: 4px; }
/* Skip link: visually hidden until focused */
.skip-link {
position: absolute; left: 0.5rem; top: -3rem; z-index: 60;
background: #ef4444; color: #fff; padding: 0.5rem 1rem; border-radius: 0.5rem;
transition: top 0.15s ease;
}
.skip-link:focus { top: 0.5rem; }
.toast {
position: fixed; bottom: 1.5rem; right: 1.5rem; z-index: 50;
padding: 0.75rem 1.25rem; border-radius: 0.5rem; font-size: 0.875rem;
animation: slideUp 0.25s ease-out; box-shadow: 0 4px 24px rgba(0,0,0,0.3);
}
@keyframes slideUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; } }
.spinner { display: inline-block; width: 1rem; height: 1rem; border: 2px solid #525252;
border-top-color: #ef4444; border-radius: 50%; animation: spin 0.6s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 40; display: flex; align-items: center; justify-content: center; }
.modal { background: #171717; border: 1px solid #262626; border-radius: 0.75rem; padding: 1.5rem; max-width: 32rem; width: 90%; box-shadow: 0 8px 32px rgba(0,0,0,0.6); }
/* Tooltip */
[data-tip] { position: relative; cursor: help; }
[data-tip]:hover::after {
content: attr(data-tip); position: absolute; bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%);
background: #0a0a0a; border: 1px solid #262626; color: #e5e5e5; padding: 0.375rem 0.625rem;
border-radius: 0.375rem; font-size: 0.75rem; white-space: nowrap; z-index: 30; max-width: 20rem;
white-space: normal; text-align: center; pointer-events: none;
}
/* Info callout */
.callout { background: #171717; border-left: 3px solid #ef4444; padding: 0.75rem 1rem; border-radius: 0 0.375rem 0.375rem 0; }
.callout-warn { border-left-color: #f59e0b; }
/* Progress bar */
.progress-bar { height: 0.375rem; border-radius: 9999px; background: #334155; overflow: hidden; }
.progress-fill { height: 100%; border-radius: 9999px; transition: width 0.3s; }
/* Hover cards */
.skill-card { transition: transform 0.15s, box-shadow 0.15s; }
.skill-card:hover { transform: translateY(-1px); box-shadow: 0 4px 16px rgba(0,0,0,0.2); }
/* Search */
.search-box { background: #171717; border: 1px solid #262626; border-radius: 0.5rem; }
.search-box:focus-within { border-color: #ef4444; }
/* README content styling */
.readme-content { color: #e5e5e5; line-height: 1.6; }
.readme-content h1, .readme-content h2, .readme-content h3 { font-weight: bold; margin: 1em 0 0.5em; border-bottom: 1px solid #262626; padding-bottom: 0.3em; }
.readme-content h1 { font-size: 1.5em; }
.readme-content h2 { font-size: 1.25em; }
.readme-content h3 { font-size: 1.1em; border: none; }
.readme-content p { margin: 0.5em 0; }
.readme-content ul, .readme-content ol { margin: 0.5em 0; padding-left: 1.5em; }
.readme-content li { margin: 0.25em 0; }
.readme-content code { background: #262626; padding: 0.15em 0.4em; border-radius: 0.25em; font-size: 0.9em; }
.readme-content pre { background: #171717; padding: 0.75em; border-radius: 0.5em; overflow-x: auto; margin: 0.5em 0; }
.readme-content pre code { background: none; padding: 0; }
.readme-content a { color: #ef4444; }
.readme-content img { max-width: 100%; border-radius: 0.5em; }
.readme-content table { border-collapse: collapse; width: 100%; margin: 0.5em 0; }
.readme-content th, .readme-content td { border: 1px solid #262626; padding: 0.4em 0.6em; text-align: left; }
.readme-content th { background: #171717; }
.readme-content blockquote { border-left: 3px solid #ef4444; padding-left: 1em; color: #a3a3a3; margin: 0.5em 0; }
</style>
</head>
<body class="min-h-screen">
<!-- The router owns location.hash, so the link must not navigate: following
it would route to an unknown view and discard whatever is on screen. -->
<a href="#app" class="skip-link" onclick="event.preventDefault(); document.getElementById('app').focus()">Skip to main content</a>
<!-- ===== HEADER ===== -->
<header class="border-b border-ovos-card px-6 py-3 flex items-center gap-4 sticky top-0 bg-ovos-bg z-20">
<a href="#/" class="flex items-center gap-2 hover:no-underline">
<img src="logo.png" alt="OVOS" width="32" height="32" class="rounded">
<span class="text-lg font-bold text-ovos-accent">OVOS Localize</span>
</a>
<nav aria-label="Primary" class="hidden sm:flex gap-4 ml-4 text-sm">
<a href="#/" class="text-ovos-muted hover:text-ovos-text">Dashboard</a>
<a href="#/stats" class="text-ovos-muted hover:text-ovos-text">Stats</a>
<a href="#/entities" class="text-ovos-muted hover:text-ovos-text">Entities</a>
<a href="#/open-data" class="text-ovos-muted hover:text-ovos-text">Open Data</a>
<a href="#/how-it-works" class="text-ovos-muted hover:text-ovos-text">How it works</a>
<a href="#/issues" class="text-ovos-muted hover:text-ovos-text">Issues</a>
<a href="#/submit-skill" class="text-ovos-muted hover:text-ovos-text">Submit Skill</a>
</nav>
<div class="ml-auto flex items-center gap-2">
<button onclick="showOnboarding()" id="profile-btn" class="text-sm px-3 py-1.5 rounded-lg border border-ovos-card hover:bg-ovos-hover flex items-center gap-2" title="Your languages">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
Set languages
</button>
</div>
</header>
<main id="app" tabindex="-1" class="mx-auto px-4 sm:px-6 py-6"></main>
<footer class="border-t border-ovos-card mt-12 py-6 px-6 text-center text-xs text-ovos-muted">
<p>Developed by <a href="https://tigregotico.pt" target="_blank" class="font-medium">TigreGoticoLda</a> with <span class="text-red-500">♥</span> for the <a href="https://openvoiceos.org" target="_blank" class="font-medium">OpenVoiceOS</a> community</p>
<p class="mt-1">Made with the help of AI.</p>
<div class="mt-2 flex items-center justify-center gap-4">
<a href="https://github.com/OpenVoiceOS/ovos-localize" target="_blank">GitHub</a>
<a href="#/how-it-works">How it works</a>
<a href="#/stats">Stats</a>
<a href="#/entities">Entities</a>
<a href="https://matrix.to/#/#OpenVoiceOS:matrix.org" target="_blank">Matrix Chat</a>
</div>
<p class="mt-4">
<a href="https://nlnet.nl/project/OpenVoiceOS" target="_blank">
<img src="ngi.png" alt="NGI0 Commons Fund" width="517" height="91" class="mx-auto" style="max-width:220px;width:100%;height:auto">
</a>
</p>
<p class="mt-2">Funded by the <a href="https://nlnet.nl/project/OpenVoiceOS" target="_blank">NGI0 Commons Fund</a> /
<a href="https://nlnet.nl" target="_blank">NLnet</a> under grant agreement No
<a href="https://cordis.europa.eu/project/id/101135429" target="_blank">101135429</a>, through the European
Commission's <a href="https://ngi.eu" target="_blank">Next Generation Internet</a> programme.</p>
</footer>
<div id="toast-container" role="status" aria-live="polite" aria-atomic="true"></div>
<div id="modal-container"></div>
<script>
// =========================================================================
// SUBMISSION (via GitHub Issues — zero auth required)
// =========================================================================
const LOCALIZE_REPO = 'OpenVoiceOS/ovos-localize';
// Per-route document title (tab UX + crawlers that execute JS).
const ROUTE_TITLES = {
'#/': 'OVOS Localize — Help translate OpenVoiceOS skills',
'': 'OVOS Localize — Help translate OpenVoiceOS skills',
'#/dashboard': 'Dashboard — OVOS Localize',
'#/stats': 'Translation Stats — OVOS Localize',
'#/entities': 'Entities — OVOS Localize',
'#/open-data': 'Open Data — OVOS Localize',
'#/how-it-works': 'How it works — OVOS Localize',
'#/issues': 'Issues — OVOS Localize',
'#/submit-skill': 'Submit a Skill — OVOS Localize',
};
function setRouteTitle(hash) {
if (ROUTE_TITLES[hash]) { document.title = ROUTE_TITLES[hash]; return; }
const m = hash.match(/^#\/skill\/([^/]+)/);
document.title = m ? `Translate ${decodeURIComponent(m[1])} — OVOS Localize`
: 'OVOS Localize';
}
// Human-first languages — the editor's per-string auto-translate
// suggestion is intentionally hidden. These languages have little to no
// machine-translation signal, so a suggestion would be unreliable and
// risks anchoring the translator to a bad first draft instead of
// translating directly from the English source.
const HUMAN_FIRST_LANGS = new Set(['kab']); // Kabyle — issue #208
// Match the primary subtag: the same language reaches us as 'kab' from one
// repo and 'kab-DZ' from another, depending on how each locale directory
// was named.
const isHumanFirst = (lang) => HUMAN_FIRST_LANGS.has(String(lang || '').split('-')[0].toLowerCase());
// Right-to-left languages, keyed on the BCP-47 primary subtag.
// MUST stay in sync with _RTL_LANGS in ovos_localize/lang_utils.py.
const RTL_LANGS = new Set(['ar', 'arc', 'ckb', 'dv', 'fa', 'he', 'ps', 'sd', 'ug', 'ur', 'yi']);
function isRtlLang(lang) {
if (!lang) return false;
return RTL_LANGS.has(lang.toLowerCase().split('-')[0]);
}
/**
* Submit a translation by opening a pre-filled GitHub Issue.
* A GitHub Action picks it up, creates a PR, and closes the issue.
* The user only needs to be logged into GitHub — zero tokens required.
*/
function submitTranslation(org, repo, filePath, newContent, lang, fileKey, branch) {
const b64Content = btoa(unescape(encodeURIComponent(newContent)));
const title = encodeURIComponent(`[translate] ${lang}: ${org}/${repo} — ${fileKey}`);
const body = encodeURIComponent(
`> Submitted via [OVOS Localize](https://openvoiceos.github.io/ovos-localize/). ` +
`A bot will create a PR automatically.\n\n` +
`<!-- TRANSLATION_META\n` +
`org: ${org}\n` +
`repo: ${repo}\n` +
`file_path: ${filePath}\n` +
`lang: ${lang}\n` +
`file_key: ${fileKey}\n` +
`branch: ${branch}\n` +
`-->\n\n` +
`<content>\n${b64Content}\n</content>`
);
window.open(`https://github.com/${LOCALIZE_REPO}/issues/new?title=${title}&labels=translation&body=${body}`, '_blank');
toast('GitHub issue page opened — click "Submit new issue" to complete.', 'green', 6000);
}
function closeModal() { document.getElementById('modal-container').innerHTML = ''; }
async function showReadme(repoFullName) {
const el = document.getElementById('modal-container');
el.innerHTML = `
<div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
<div class="modal" style="max-width:48rem;max-height:85vh;display:flex;flex-direction:column">
<div class="flex items-center justify-between mb-3 flex-shrink-0">
<h3 class="text-lg font-bold">README — ${escapeHtml(repoFullName)}</h3>
<button onclick="closeModal()" class="text-ovos-muted hover:text-ovos-text px-2">×</button>
</div>
<div class="flex-1 overflow-auto text-sm text-ovos-muted flex items-center justify-center">
<span class="spinner"></span> Loading...
</div>
</div>
</div>`;
try {
const r = await fetch('https://api.github.com/repos/' + repoFullName + '/readme', {
headers: { 'Accept': 'application/vnd.github.html+json' },
signal: AbortSignal.timeout(15000),
});
if (!r.ok) throw new Error(r.status === 404 ? 'No README found' : 'GitHub API ' + r.status);
const html = await r.text();
const content = el.querySelector('.overflow-auto');
content.className = 'flex-1 overflow-auto text-sm readme-content p-1';
content.innerHTML = html;
} catch (e) {
const content = el.querySelector('.overflow-auto');
content.innerHTML = '<p class="text-red-400">Failed to load README: ' + escapeHtml(e.message) + '</p><p class="mt-2"><a href="https://github.com/' + repoFullName + '#readme" target="_blank">View on GitHub</a></p>';
}
}
// =========================================================================
// USER PROFILE (localStorage — languages)
// =========================================================================
function getProfile() {
const p = localStorage.getItem('ovos_profile');
return p ? JSON.parse(p) : null;
}
function saveProfile(profile) {
localStorage.setItem('ovos_profile', JSON.stringify(profile));
updateProfileUI();
}
function getUserLangs() {
const p = getProfile();
return p?.languages || ['en-US'];
}
function hasCompletedOnboarding() { return true; }
function updateProfileUI() {
const btn = document.getElementById('profile-btn');
if (!btn) return;
const p = getProfile();
if (p) {
const langCount = p.languages.length;
btn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>${langCount} lang${langCount !== 1 ? 's' : ''}`;
btn.title = `Your languages: ${p.languages.join(', ')}`;
} else {
btn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>Set languages`;
}
}
async function showOnboarding() {
let langMeta = {};
try {
const coverage = await fetchJSON('data/coverage.json');
langMeta = coverage.lang_meta || {};
} catch {}
const allLangs = Object.keys(langMeta).sort((a, b) => {
const na = langMeta[a]?.native || a;
const nb = langMeta[b]?.native || b;
return na.localeCompare(nb);
});
const existing = getProfile();
const selectedSet = new Set(existing?.languages || []);
document.getElementById('modal-container').innerHTML = `
<div class="modal-backdrop">
<div class="modal" style="max-width:36rem">
<div class="text-center mb-4">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="1.5" class="mx-auto mb-3"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
<h2 class="text-xl font-bold">${existing ? 'Update your languages' : 'Welcome to OVOS Localize!'}</h2>
<p class="text-sm text-ovos-muted mt-1">${existing ? 'Change which languages you see.' : 'What languages do you speak? We will only show skills that need help in your languages.'}</p>
</div>
<div class="mb-3">
<div class="search-box flex items-center px-3 py-2 gap-2 mb-3">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#737373" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
<input id="lang-search" type="text" placeholder="Search languages..." class="bg-transparent text-sm text-ovos-text w-full outline-none placeholder-ovos-muted" oninput="filterOnboardingLangs()">
</div>
<div id="lang-grid" class="grid grid-cols-2 gap-1.5 max-h-64 overflow-auto pr-1">
${allLangs.map(code => {
const m = langMeta[code] || {};
const checked = selectedSet.has(code) ? 'checked' : '';
return `<label class="lang-option flex items-center gap-2 p-2 rounded-lg hover:bg-ovos-hover cursor-pointer text-sm" data-code="${code}" data-search="${(m.native||'').toLowerCase()} ${(m.display||'').toLowerCase()} ${code.toLowerCase()}">
<input type="checkbox" value="${code}" class="lang-cb accent-red-500 w-4 h-4" ${checked} onchange="updateOnboardingCount()">
<div>
<div class="font-medium">${escapeHtml(m.native || code)}</div>
<div class="text-xs text-ovos-muted">${escapeHtml(m.display || code)}</div>
</div>
</label>`;
}).join('')}
</div>
<div class="mt-2 text-xs text-ovos-muted"><span id="onboarding-count">${selectedSet.size}</span> language${selectedSet.size !== 1 ? 's' : ''} selected</div>
</div>
<div class="flex items-center justify-between">
<button onclick="closeModal();showRequestLangModal()" class="text-xs text-ovos-muted hover:text-ovos-text">Can't find your language? Request it</button>
<div class="flex gap-2">
${existing ? '<button onclick="closeModal()" class="px-4 py-2 text-sm rounded-lg border border-ovos-card hover:bg-ovos-hover">Cancel</button>' : ''}
<button onclick="saveOnboarding()" id="save-onboarding-btn" class="px-4 py-2 text-sm rounded-lg bg-ovos-accent text-ovos-bg font-bold hover:opacity-80 disabled:opacity-40" ${selectedSet.size === 0 && !existing ? 'disabled' : ''}>
${existing ? 'Save' : 'Get started'}
</button>
</div>
</div>
</div>
</div>`;
}
function filterOnboardingLangs() {
const q = (document.getElementById('lang-search')?.value || '').toLowerCase();
document.querySelectorAll('.lang-option').forEach(el => {
el.style.display = el.dataset.search.includes(q) ? '' : 'none';
});
}
function updateOnboardingCount() {
const count = document.querySelectorAll('.lang-cb:checked').length;
const el = document.getElementById('onboarding-count');
if (el) el.textContent = count;
const btn = document.getElementById('save-onboarding-btn');
if (btn) btn.disabled = count === 0;
}
function saveOnboarding() {
const selected = Array.from(document.querySelectorAll('.lang-cb:checked')).map(cb => cb.value);
if (selected.length === 0) { toast('Select at least one language', 'amber'); return; }
const isFirst = !hasCompletedOnboarding();
saveProfile({ languages: selected, createdAt: new Date().toISOString() });
closeModal();
toast(`Showing ${selected.length} language${selected.length > 1 ? 's' : ''}`, 'green');
if (isFirst) {
location.hash = '#/dashboard';
} else {
route();
}
}
function showRequestLangModal() {
document.getElementById('modal-container').innerHTML = `
<div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
<div class="modal" style="max-width:28rem">
<div class="text-center mb-4">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="1.5" class="mx-auto mb-3"><circle cx="12" cy="12" r="10"/><path d="M8 12h8"/><path d="M12 8v8"/></svg>
<h3 class="text-lg font-bold">Request a new language</h3>
<p class="text-sm text-ovos-muted mt-1">If your language isn't listed, we can add it!</p>
</div>
<div class="space-y-3 mb-4">
<div>
<label class="text-xs font-bold text-ovos-muted">Language name</label>
<input id="req-lang-name" type="text" placeholder="e.g. Hindi, Swahili, Korean..."
class="mt-1 w-full bg-ovos-input text-ovos-text px-3 py-2 rounded-lg border border-ovos-card text-sm">
</div>
<div>
<label class="text-xs font-bold text-ovos-muted">Language code <span class="font-normal text-ovos-muted">(BCP-47, e.g. hi-IN)</span></label>
<input id="req-lang-code" type="text" placeholder="e.g. hi-IN"
class="mt-1 w-full bg-ovos-input text-ovos-text px-3 py-2 rounded-lg border border-ovos-card text-sm mono">
</div>
</div>
<button onclick="submitLangRequest()" class="w-full px-4 py-2.5 text-sm rounded-lg bg-ovos-accent text-white font-bold hover:opacity-80 mb-3">
Open request on GitHub
</button>
<div class="mt-3 text-center">
<button onclick="closeModal()" class="text-sm text-ovos-muted hover:text-ovos-text">Cancel</button>
</div>
</div>
</div>`;
setTimeout(() => document.getElementById('req-lang-name')?.focus(), 100);
}
function submitLangRequest() {
const name = document.getElementById('req-lang-name')?.value.trim();
const code = document.getElementById('req-lang-code')?.value.trim();
if (!name) { toast('Enter a language name', 'amber'); return; }
if (!code) { toast('Enter a BCP-47 language code (e.g. hi-IN)', 'amber'); return; }
if (!/^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,})*$/.test(code)) {
toast('Invalid language code format. Use BCP-47, e.g. hi-IN', 'amber'); return;
}
const title = encodeURIComponent('Add language: ' + name + ' (' + code + ')');
const enc = s => encodeURIComponent(s);
const NL = '%0A';
const body = [
enc('<!-- NEW_LANGUAGE_META'),
enc('name: ' + name),
enc('code: ' + code),
enc('-->'),
'',
enc('I am requesting the **' + name + '** (`' + code + '`) language to be added to OVOS Localize so I can start contributing translations.'),
].join(NL);
window.open('https://github.com/OpenVoiceOS/ovos-localize/issues/new?title=' + title + '&body=' + body + '&labels=new-language', '_blank');
closeModal();
}
// =========================================================================
// UI HELPERS
// =========================================================================
function toast(msg, color = 'blue', duration = 3000) {
const colors = { green: 'bg-green-800 text-green-200', red: 'bg-red-800 text-red-200', blue: 'bg-neutral-800 text-neutral-200', amber: 'bg-amber-800 text-amber-200' };
const id = 't' + Date.now();
document.getElementById('toast-container').innerHTML = `<div id="${id}" class="toast ${colors[color]||colors.blue}">${escapeHtml(msg)}</div>`;
if (duration > 0) setTimeout(() => document.getElementById(id)?.remove(), duration);
}
function showProgress(msg) {
document.getElementById('toast-container').innerHTML = `<div class="toast bg-neutral-800 text-neutral-200 flex items-center gap-2"><span class="spinner"></span>${escapeHtml(msg)}</div>`;
}
function hideProgress() { document.getElementById('toast-container').innerHTML = ''; }
const cache = {};
async function fetchJSON(url) {
if (cache[url]) return cache[url];
const r = await fetch(url);
if (!r.ok) throw new Error(`Failed to fetch ${url}: ${r.status}`);
const d = await r.json();
cache[url] = d;
return d;
}
/** The locale-path rules, written by scripts/gen_locale_rules.py. */
async function fetchLocaleRules() {
try {
return await fetchJSON('data/locale_rules.json');
} catch {
// A table that did not load is not a table saying "no such tag".
// It returns null so the page can say which of the two happened;
// either way it places no file.
return null;
}
}
async function fetchSkill(skillId) {
const skill = await fetchJSON(`data/skills/${skillId}.json`);
if (skill.chunks && skill.chunks.length > 0) {
for (const chunk of skill.chunks) {
const chunkData = await fetchJSON(`data/skills/${chunk}`);
if (chunkData.files) {
Object.assign(skill.files, chunkData.files);
}
}
}
return skill;
}
// =========================================================================
// OVOS TRANSLATION API (auto-translate via community servers)
// =========================================================================
const TRANSLATE_SERVERS = [
{ name: "NLLB - Smart'Gic", url: "https://translator.smartgic.io/nllb" },
{ name: "NLLB - Ziggyai", url: "https://ovosnllb.ziggyai.online" },
{ name: "NLLB - TigreGotico", url: "https://nllb.tigregotico.pt" },
{ name: "Google Translate - TigreGotico", url: "https://google-translate.tigregotico.pt" },
];
function getTranslateServer() {
return localStorage.getItem('ovos_tx_server') || TRANSLATE_SERVERS[0].url;
}
function setTranslateServer(url) {
localStorage.setItem('ovos_tx_server', url);
}
/** Check server status via GET /status */
async function checkTxServerStatus(serverUrl) {
try {
const r = await fetch(`${serverUrl}/status`, { signal: AbortSignal.timeout(8000) });
if (!r.ok) return { ok: false, error: `HTTP ${r.status}` };
const data = await r.json();
return {
ok: true,
plugin: data.translation_plugin || data.plugin_type || 'unknown',
langs: data.langs || data.languages || [],
};
} catch (e) {
return { ok: false, error: e.name === 'AbortError' ? 'Timeout (8s)' : (e.message || 'Connection failed') };
}
}
/** Update the status dot in the action bar */
async function updateTxStatusDot() {
const dot = document.getElementById('tx-server-status');
if (!dot) return;
dot.className = 'w-2 h-2 rounded-full bg-yellow-500 flex-shrink-0 animate-pulse';
const status = await checkTxServerStatus(getTranslateServer());
dot.className = `w-2 h-2 rounded-full ${status.ok ? 'bg-green-500' : 'bg-red-500'} flex-shrink-0`;
dot.title = status.ok ? `Online — ${status.plugin} (${status.langs.length} languages)` : `Offline — ${status.error}`;
}
function showTxServerModal() {
const current = getTranslateServer();
const isCustom = !TRANSLATE_SERVERS.some(s => s.url === current);
document.getElementById('modal-container').innerHTML = `
<div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
<div class="modal" style="max-width:32rem">
<h3 class="text-lg font-bold mb-1">Translation server</h3>
<p class="text-sm text-ovos-muted mb-4">Choose a community server or enter your own <a href="https://github.com/OpenVoiceOS/ovos-localize-server" target="_blank">ovos-localize-server</a> URL.</p>
<div class="space-y-2 mb-4" id="tx-server-list">
${TRANSLATE_SERVERS.map(s => `
<label class="flex items-center gap-3 p-3 rounded-lg hover:bg-ovos-hover cursor-pointer ${s.url === current ? 'bg-ovos-hover ring-1 ring-ovos-accent' : 'bg-ovos-bg'}">
<input type="radio" name="tx-server" value="${s.url}" ${s.url === current ? 'checked' : ''} class="accent-red-500" onchange="txServerSelected(this.value)">
<div class="flex-1 min-w-0">
<div class="text-sm font-medium">${escapeHtml(s.name)}</div>
<div class="text-xs text-ovos-muted mono truncate">${escapeHtml(s.url)}</div>
</div>
<span class="tx-status-dot w-2.5 h-2.5 rounded-full bg-gray-500 flex-shrink-0" data-url="${s.url}"></span>
</label>
`).join('')}
<!-- Custom URL option -->
<label class="flex items-center gap-3 p-3 rounded-lg hover:bg-ovos-hover cursor-pointer ${isCustom ? 'bg-ovos-hover ring-1 ring-ovos-accent' : 'bg-ovos-bg'}">
<input type="radio" name="tx-server" value="__custom__" ${isCustom ? 'checked' : ''} class="accent-red-500" onchange="document.getElementById('custom-tx-url').focus()">
<div class="flex-1">
<div class="text-sm font-medium">Custom server</div>
<input id="custom-tx-url" type="url" placeholder="https://my-server.example.com"
value="${isCustom ? escapeHtml(current) : ''}"
class="mt-1 w-full bg-ovos-input text-ovos-text px-2 py-1.5 rounded border border-ovos-card text-xs mono"
onfocus="document.querySelector('input[value=__custom__]').checked=true"
oninput="txServerSelected(this.value)">
</div>
<span class="tx-status-dot w-2.5 h-2.5 rounded-full bg-gray-500 flex-shrink-0" data-url="__custom__"></span>
</label>
</div>
<div id="tx-status-detail" class="text-xs text-ovos-muted mb-4"></div>
<div class="flex gap-2 justify-between">
<button onclick="checkAllTxServers()" class="px-3 py-1.5 text-sm rounded-lg border border-ovos-card hover:bg-ovos-hover">Check all servers</button>
<button onclick="saveTxServer()" class="px-4 py-1.5 text-sm rounded-lg bg-ovos-accent text-white font-bold hover:opacity-80">Save</button>
</div>
</div>
</div>`;
// Auto-check the selected server
const selectedUrl = isCustom ? current : current;
checkSingleTxServer(selectedUrl);
}
function txServerSelected(url) {
if (url && url !== '__custom__') {
checkSingleTxServer(url);
}
}
async function checkSingleTxServer(url) {
const detail = document.getElementById('tx-status-detail');
const dot = document.querySelector(`.tx-status-dot[data-url="${url}"]`)
|| document.querySelector('.tx-status-dot[data-url="__custom__"]');
if (dot) dot.className = 'tx-status-dot w-2.5 h-2.5 rounded-full bg-yellow-500 flex-shrink-0 animate-pulse';
if (detail) detail.innerHTML = '<span class="spinner"></span> Checking...';
const status = await checkTxServerStatus(url);
if (dot) dot.className = `tx-status-dot w-2.5 h-2.5 rounded-full ${status.ok ? 'bg-green-500' : 'bg-red-500'} flex-shrink-0`;
if (detail) {
if (status.ok) {
detail.innerHTML = `<span class="text-green-400">Online</span> — plugin: <strong>${escapeHtml(status.plugin)}</strong>, ${status.langs.length} languages supported`;
} else {
detail.innerHTML = `<span class="text-red-400">Offline</span> — ${escapeHtml(status.error)}. The server may be down or blocking cross-origin requests (CORS).`;
}
}
}
async function checkAllTxServers() {
const dots = document.querySelectorAll('.tx-status-dot');
dots.forEach(d => d.className = 'tx-status-dot w-2.5 h-2.5 rounded-full bg-yellow-500 flex-shrink-0 animate-pulse');
for (const s of TRANSLATE_SERVERS) {
const dot = document.querySelector(`.tx-status-dot[data-url="${s.url}"]`);
const status = await checkTxServerStatus(s.url);
if (dot) dot.className = `tx-status-dot w-2.5 h-2.5 rounded-full ${status.ok ? 'bg-green-500' : 'bg-red-500'} flex-shrink-0`;
if (dot) dot.title = status.ok ? `${status.plugin} — ${status.langs.length} langs` : status.error;
}
// Check custom if entered
const customInput = document.getElementById('custom-tx-url');
if (customInput?.value.trim()) {
const dot = document.querySelector('.tx-status-dot[data-url="__custom__"]');
const status = await checkTxServerStatus(customInput.value.trim());
if (dot) dot.className = `tx-status-dot w-2.5 h-2.5 rounded-full ${status.ok ? 'bg-green-500' : 'bg-red-500'} flex-shrink-0`;
}
}
function saveTxServer() {
const selected = document.querySelector('input[name="tx-server"]:checked')?.value;
if (!selected) return;
let url;
if (selected === '__custom__') {
url = document.getElementById('custom-tx-url')?.value.trim();
if (!url) { toast('Enter a server URL', 'amber'); return; }
// Strip trailing slash
url = url.replace(/\/+$/, '');
} else {
url = selected;
}
setTranslateServer(url);
// Update the label in the action bar
const label = document.getElementById('tx-server-label');
if (label) {
const preset = TRANSLATE_SERVERS.find(s => s.url === url);
label.textContent = preset ? preset.name : 'Custom';
}
closeModal();
toast('Translation server saved', 'green');
updateTxStatusDot();
}
/** Strip region from BCP-47 for the translate API (e.g. pt-BR → pt, en-US → en) */
function langToShort(code) {
return code.split('-')[0].toLowerCase();
}
/**
* Translate a single string via OVOS translate server.
* GET /translate/{src}/{tgt}/{text}
*/
async function ovsTranslate(text, srcLang, tgtLang, serverUrl) {
const src = langToShort(srcLang);
const tgt = langToShort(tgtLang);
const url = `${serverUrl}/translate/${src}/${tgt}/${encodeURIComponent(text)}`;
const r = await fetch(url, { signal: AbortSignal.timeout(20000) });
if (!r.ok) throw new Error(`Translation server returned ${r.status}`);
const data = await r.json().catch(() => r.text());
return typeof data === 'string' ? data : (data.translation || data.translated || String(data));
}
/**
* Auto-translate all lines from source to target language.
* Translates line-by-line to preserve structure.
*/
async function autoTranslateLines(lines, tgtLang, serverUrl, onProgress, srcLang = 'en-US') {
const results = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (!line || line.startsWith('#')) {
results.push(line);
continue;
}
// Preserve {slots} — replace with placeholders before translating
const slots = [];
const cleaned = line.replace(/\{(\w+)\}/g, (match) => {
slots.push(match);
return `__SLOT${slots.length - 1}__`;
});
// Preserve (a|b) alternatives — translate each option separately
const altGroups = [];
const withoutAlts = cleaned.replace(/\(([^)]+)\)/g, (match, group) => {
altGroups.push(group);
return `__ALT${altGroups.length - 1}__`;
});
let translated;
try {
translated = await ovsTranslate(withoutAlts, srcLang, tgtLang, serverUrl);
} catch {
translated = withoutAlts; // Keep original on failure
}
// Restore alternatives (translate each option)
for (let j = 0; j < altGroups.length; j++) {
const options = altGroups[j].split('|');
const translatedOpts = [];
for (const opt of options) {
if (!opt.trim()) { translatedOpts.push(''); continue; }
try {
translatedOpts.push(await ovsTranslate(opt.trim(), srcLang, tgtLang, serverUrl));
} catch {
translatedOpts.push(opt);
}
}
translated = translated.replace(`__ALT${j}__`, `(${translatedOpts.join('|')})`);
}
// Restore slots
for (let j = 0; j < slots.length; j++) {
translated = translated.replace(`__SLOT${j}__`, slots[j]);
}
results.push(translated);
if (onProgress) onProgress(i + 1, lines.length);
}
return results;
}
function coverageBadge(pct) {
if (pct == null) return '<span class="badge badge-gray">missing</span>';
const cls = pct >= 80 ? 'badge-green' : pct >= 50 ? 'badge-amber' : 'badge-red';
return `<span class="badge ${cls}">${pct.toFixed(0)}%</span>`;
}
// <bdi> isolates the (Latin) slot name so it doesn't scramble the
// surrounding text's bidirectional ordering in RTL languages.
function highlightSlots(text) { return text.replace(/\{(\w+)\}/g, '<bdi class="slot">{$1}</bdi>'); }
function highlightCodeStrings(code) {
// Highlight string literals (single and double quoted)
return code
.replace(/((?:"|")[^"]*(?:"|"))/g, '<span style="color:#a5d6ff">$1</span>')
.replace(/('[^']*')/g, '<span style="color:#a5d6ff">$1</span>')
.replace(/('(?:[^'\\]|\\.)*')/g, '<span style="color:#a5d6ff">$1</span>')
.replace(/(self\.(speak_dialog|get_response|ask_yesno))/g, '<span style="color:#fbbf24;font-weight:600">$1</span>')
.replace(/(@intent_handler)/g, '<span style="color:#c084fc;font-weight:600">$1</span>')
.replace(/(def\s+\w+)/g, '<span style="color:#7dd3fc">$1</span>');
}
function escapeHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
function filePathFromEditUrl(u) { const m = u.match(/\/edit\/[^/]+\/(.+)$/); return m ? m[1] : ''; }
/**
* Place a resource file for a target language, from the path of the
* reference file the translator reads.
*
* The rule is not written here. ovos_localize/locale_rules.py builds it
* and scripts/gen_locale_rules.py writes the answer to
* data/locale_rules.json, which this reads, because the submission
* guard runs that same Python. Two implementations of one rule drift:
* this page once upper-cased every subtag after the first, which is
* right for a region and wrong for a script (zh-Hant) or a variant
* (ca-ES-valencia), and the guard then refused the path the page had
* composed.
*
* A rules entry carries the canonical spelling of the tag, its primary
* subtag, whether it may be written into a region-less directory, and
* the tags it would collide with there.
*
* @param {string} refPath Path of the reference file.
* @param {string} targetLang Language tag being translated into.
* @param {string} [fileKey] Resource name, when the reference is another file.
* @param {object} [rules] The table from data/locale_rules.json.
* @returns {{path: string, reason: string, collidesWith: string[]}}
* The target path, or an empty path and the reason it is refused:
* no-locale-root, unknown-tag or region-collision.
*/
function localePathForLangDetailed(refPath, targetLang, fileKey, rules) {
const noRoot = { path: '', reason: 'no-locale-root', collidesWith: [] };
const table = (rules || {}).tags;
// No table is not the same answer as "this tag is not in the table".
// Reporting a fetch failure as unknown-tag tells the translator their
// language is unsupported when the platform simply did not load.
if (!table || !Object.keys(table).length) {
return { path: '', reason: 'table-not-loaded', collidesWith: [] };
}
if (!refPath || !targetLang) return noRoot;
const parts = String(refPath).split('/');
// The innermost locale root, matching locale_root_index in
// ovos_localize/locale_rules.py. A tree nests the two roots
// (ocp/res/locale/en-us/Music.voc), and taking the first would read
// 'locale' as the language.
const isRoot = (seg) => seg === 'locale' || seg === 'res';
let idx = -1;
for (let i = parts.length - 1; i >= 0; i--) {
if (isRoot(parts[i]) && parts.length >= i + 3 && parts[i + 1] && !isRoot(parts[i + 1])) {
idx = i;
break;
}
}
if (idx === -1) return noRoot;
const rule = table[String(targetLang).trim().toLowerCase()];
if (!rule) return { path: '', reason: 'unknown-tag', collidesWith: [] };
const refSeg = parts[idx + 1];
let seg;
if (refSeg.includes('-')) {
seg = rule.canonical;
} else {
if (!rule.bare_ok) {
return { path: '', reason: 'region-collision', collidesWith: rule.rivals || [] };
}
seg = rule.primary;
}
if (refSeg === refSeg.toLowerCase()) seg = seg.toLowerCase();
const path = fileKey
? parts.slice(0, idx + 1).concat([seg, fileKey]).join('/')
: parts.slice(0, idx + 1).concat([seg], parts.slice(idx + 2)).join('/');
return { path, reason: 'ok', collidesWith: rule.rivals || [] };
}
/**
* What to tell the translator when no file can be placed.
*
* Each reason is a different thing to do next, so each says something
* different. A table that did not load is a platform fault and must
* never read as "your language is not supported".
*
* @param {string} reason One of the reasons localePathForLangDetailed returns.
* @param {string} lang The target language tag.
* @param {string[]} collidesWith The tags that would share the file.
* @returns {string} A sentence for the disabled Submit button.
*/
function pathRefusalMessage(reason, lang, collidesWith) {
const tags = (collidesWith || []).join(', ');
if (reason === 'region-collision') {
return `This repository writes ${String(lang).split('-')[0]} without a region, so `
+ `${lang} and ${tags} would share one file. Use "GitHub" to add a ${lang} directory.`;
}
if (reason === 'unknown-tag') {
return `${lang} is not a language this platform writes yet. `
+ 'Open a "Request a language" issue first.';
}
if (reason === 'table-not-loaded') {
return 'The language table did not load, so this page cannot tell where the file goes. '
+ 'Reload the page; if it keeps happening, this is a fault on our side.';
}
return 'This repository has no locale tree that the page can place a new file in — '
+ 'use "GitHub" to add the file';
}
/** The path alone. '' when the file cannot be placed. */
function localePathForLang(refPath, targetLang, fileKey, rules) {
return localePathForLangDetailed(refPath, targetLang, fileKey, rules).path;
}
function progressBar(pct, size = 'sm') {
const h = size === 'sm' ? 'h-1.5' : 'h-2.5';
const color = pct >= 80 ? '#22c55e' : pct >= 50 ? '#f59e0b' : '#ef4444';
return `<div class="progress-bar ${h}"><div class="progress-fill" style="width:${pct}%;background:${color}"></div></div>`;
}
// =========================================================================
// TEMPLATE EXPANSION — port of ovos_utils.bracket_expansion.expand_template
// =========================================================================
function expandTemplate(template) {
// [optional] → (optional|)
let t = template.replace(/\[([^\[\]]+)\]/g, '($1|)');
function expandAlternatives(text) {
const parts = [];
const segments = text.split(/(\([^()]+\))/);
for (const seg of segments) {
if (seg.startsWith('(') && seg.endsWith(')')) {
parts.push(seg.slice(1, -1).split('|'));
} else {
parts.push([seg]);
}
}
// Cartesian product
return cartesian(parts).map(combo => combo.join('').replace(/\s+/g, ' ').trim());
}
function cartesian(arrays) {
return arrays.reduce((acc, arr) => {
const result = [];
for (const a of acc) for (const b of arr) result.push([...a, b]);
return result;
}, [['']]); // Start with array containing empty string, not empty array
}
// Iteratively expand until stable
let result = new Set([t]);
for (let i = 0; i < 10; i++) { // safety limit
const expanded = new Set();
for (const text of result) {
for (const e of expandAlternatives(text)) expanded.add(e);
}
if (expanded.size === result.size && [...expanded].every(x => result.has(x))) break;
result = expanded;
}
return [...result].filter(s => s.trim()).sort();
}
/** Expand all lines and return total count + sample */
function expandAllLines(text, maxPerLine = 50, maxTotal = 200) {
const lines = text.split('\n').filter(l => l.trim() && !l.trim().startsWith('#'));
let total = 0;
const samples = [];
for (const line of lines) {
const expanded = expandTemplate(line);
total += expanded.length;
// Keep some samples
for (const e of expanded.slice(0, maxPerLine)) {
if (samples.length < maxTotal) samples.push(e);
}
}
return { total, samples, lineCount: lines.length };
}
// =========================================================================
// JSON SYNTAX HIGHLIGHTING
// =========================================================================
function highlightJson(jsonStr) {
return jsonStr
.replace(/("(?:[^"\\]|\\.)*")\s*:/g, '<span style="color:#fca5a5">$1</span>:') // keys in red
.replace(/:\s*("(?:[^"\\]|\\.)*")/g, ': <span style="color:#86efac">$1</span>') // string values in green
.replace(/:\s*(true|false|null)/g, ': <span style="color:#fde047">$1</span>') // booleans in yellow
.replace(/:\s*(\d+(?:\.\d+)?)/g, ': <span style="color:#93c5fd">$1</span>'); // numbers in blue
}
// file type explanations for translators
const FILE_TYPE_HELP = {
intent: 'Training phrases for the voice assistant to recognize what the user wants. Add many natural variations.',
voc: 'Short keywords the voice assistant listens for. Keep them to 1-3 words.',
dialog: 'What the voice assistant says back to the user. Write naturally — these are spoken aloud.',
entity: 'Example values for a category (e.g. colors, cities). List real examples.',
rx: 'Regex patterns to extract information from speech. Keep named groups unchanged.',
value: 'Mapping of display names to system values. Only translate the left side.',
'skill.json': 'Skill metadata (name, description). Translate user-facing text.',
settingsmeta: 'Settings UI labels. Translate user-facing labels and descriptions.',
};
// =========================================================================
// ROUTER
// =========================================================================
async function route() {
const hash = location.hash || '#/';
setRouteTitle(hash);
const app = document.getElementById('app');
app.innerHTML = '<div class="flex items-center gap-2 py-12 justify-center text-ovos-muted"><span class="spinner"></span> Loading...</div>';
// Show onboarding on first visit — only for pages that need a user profile
// Informational pages (stats, entities, open-data) are accessible without a profile
const publicPages = ['#/', '', '#/how-it-works', '#/stats', '#/entities', '#/open-data', '#/issues', '#/submit-skill'];
// Skill editor pages with an explicit lang in the URL are accessible without a profile
// (the lang is encoded in the route, so no profile is needed to determine what to show)
const isSkillEditorWithLang = /^#\/skill\/[^/]+\/[^/]+\/.+/.test(hash);
if (!hasCompletedOnboarding() && !publicPages.includes(hash) && !isSkillEditorWithLang) {
await renderLanding(app);
return;
}
try {
if (hash === '#/' || hash === '') await renderLanding(app);
else if (hash === '#/how-it-works') renderHowItWorks(app);
else if (hash === '#/stats') await renderStats(app);
else if (hash === '#/entities') await renderEntities(app);
else if (hash === '#/open-data') await renderOpenData(app);
else if (hash === '#/issues') await renderIssues(app);
else if (hash === '#/submit-skill') await renderSubmitSkill(app);
else if (hash === '#/dashboard') await renderDashboard(app);
else if (hash.match(/^#\/skill\/([^/]+)\/([^/]+)\/(.+)$/)) {
// Editor: #/skill/{id}/{file}/{lang}
const [, id, file, lang] = hash.match(/^#\/skill\/([^/]+)\/([^/]+)\/(.+)$/);
await renderEditor(app, id, decodeURIComponent(file), decodeURIComponent(lang));
} else if (hash.match(/^#\/skill\/([^/]+)\/(.+)$/)) {
// Skill detail for a specific language: #/skill/{id}/{lang}
const [, id, lang] = hash.match(/^#\/skill\/([^/]+)\/(.+)$/);
await renderSkillDetail(app, id, decodeURIComponent(lang));
} else if (hash.match(/^#\/skill\/([^/]+)$/)) {
// Skill detail without language — redirect to first user lang
const id = RegExp.$1;
const uLangs = getUserLangs();
const defaultLang = uLangs.length > 0 ? uLangs[0] : 'de-DE';
location.hash = `#/skill/${id}/${defaultLang}`;
return;
} else app.innerHTML = '<p>Page not found. <a href="#/">Go home</a></p>';
} catch(e) {
app.innerHTML = `<div class="py-12 text-center"><p class="text-red-400 text-lg mb-2">Something went wrong</p><p class="text-ovos-muted text-sm mb-4">${escapeHtml(e.message)}</p><a href="#/" class="text-sm">Go home</a></div>`;
}
// Move focus to the freshly-rendered view so screen-reader users are
// told the page changed (SPA route changes are otherwise silent). Skip
// the very first load so we don't yank focus off the top of the page.
if (!isInitialRoute) {
const heading = app.querySelector('h1, h2');
const target = heading || app;
if (target === heading) heading.tabIndex = -1; // make the heading programmatically focusable