Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1494 lines (1417 loc) · 73.8 KB
/
Copy pathscript.js
File metadata and controls
1494 lines (1417 loc) · 73.8 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
/* ══ DEFAULT CATEGORIES — 3-level: category → subcategory → type ══ */
const DEFAULT_CATS=[
{id:'NOUN',label:'Noun',subs:[
{id:'NOUN-ANIM',label:'Animate',types:[]},
{id:'NOUN-INANIM',label:'Inanimate',types:[
{id:'NOUN-INANIM-OBJ',label:'Object'},
{id:'NOUN-INANIM-EVT',label:'Event'}
]}
]},
{id:'ADJ',label:'Adjective',subs:[
{id:'ADJ-INT',label:'Intersective',types:[
{id:'ADJ-INT-SHAPE',label:'Shape'},
{id:'ADJ-INT-COLOR',label:'Color'},
{id:'ADJ-INT-MAT',label:'Material'}
]},
{id:'ADJ-NINT',label:'Non-intersective',types:[
{id:'ADJ-NINT-SIZE',label:'Size'},
{id:'ADJ-NINT-AGE',label:'Age'},
{id:'ADJ-NINT-QUAL',label:'Qualifier'}
]}
]},
{id:'ART',label:'Article',subs:[
{id:'ART-DEF',label:'Definite',types:[]},
{id:'ART-INDEF',label:'Indefinite',types:[]}
]},
{id:'POSS',label:'Possessive',subs:[
{id:'POSS-GEN',label:'Genitive',types:[]},
{id:'POSS-PP-GEN',label:'PP-Genitive',types:[]}
]},
{id:'NUM',label:'Numeral',subs:[
{id:'NUM-ORD',label:'Ordinal',types:[]},
{id:'NUM-CARD',label:'Cardinal',types:[]}
]},
{id:'DEM',label:'Demonstrative',subs:[
{id:'DEM-PROX',label:'Proximal',types:[]},
{id:'DEM-DIST',label:'Distal',types:[]}
]},
{id:'QUANT',label:'Quantifier',subs:[
{id:'QUANT-EXIST',label:'Existential',types:[]},
{id:'QUANT-UNIV',label:'Universal',types:[]}
]},
{id:'RC',label:'Relative Clause',subs:[
{id:'RC-REST',label:'Restrictive',types:[]},
{id:'RC-NREST',label:'Non-restrictive',types:[]}
]},
{id:'PP',label:'Prepositional Phrase',subs:[]}
];
/* ══ STATE ══ */
let categories=JSON.parse(JSON.stringify(DEFAULT_CATS));
let tokens=[],selectedIdx=new Set(),currentAnnotations=[],currentGlosses={},currentPhraseTranslation='';
let savedAnnotations=[];
let fileRows=[],fileHeaders=[],activeRowIdx=-1;
let colMap={data:-1,lang:-1,code:-1,context:-1,source:-1};
let session={language:'',code:''};
let phraseCounter=0;
let lexicon={},lexCounter=0;
let pendingAutoTag=null;
let referenceDataset=null;
let referenceTagSuggestions={};
const AVAILABLE_REFERENCE_DATASETS=[
{id:'english-reference',label:'English reference tags',language:'English',file:'Sample/pretrained/english_reference.csv'},
{id:'turkish-reference',label:'Turkish reference tags',language:'Turkish',file:'Sample/pretrained/turkish_reference.csv'},
{id:'spanish-reference',label:'Spanish reference tags',language:'Spanish',file:'Sample/pretrained/spanish_reference.csv'},
{id:'catalan-reference',label:'Catalan reference tags',language:'Catalan',file:'Sample/pretrained/catalan_reference.csv'}
];
/* tagSuggestions: map of joined-token-string -> tagId, built from savedAnnotations and reference datasets */
let tagSuggestions={};
let rawContext=''; // stores the original context text, never overwritten by NP edits
/* ══════════════════════════════════════
AUTO-SAVE (localStorage, no external API)
══════════════════════════════════════ */
const LS_KEY='np_annotator_v1';
const ROWS_SIDEBAR_KEY='np_annotator_rows_collapsed';
function buildSessionSnapshot(){
const persistedTagSuggestions={};
savedAnnotations.forEach(s=>{
s.annotations.forEach(a=>{
const key=a.tokens.toLowerCase();
if(!persistedTagSuggestions[key]) persistedTagSuggestions[key]=[];
if(!persistedTagSuggestions[key].includes(a.tag)) persistedTagSuggestions[key].push(a.tag);
});
});
const snap={
version:1,
ts: Date.now(),
session: JSON.parse(JSON.stringify(session||{})),
fileHeaders: JSON.parse(JSON.stringify(fileHeaders||[])),
fileRows: JSON.parse(JSON.stringify(fileRows||[])),
colMap: JSON.parse(JSON.stringify(colMap||{data:-1,lang:-1,code:-1,context:-1,source:-1})),
categories: JSON.parse(JSON.stringify(categories||DEFAULT_CATS)),
phraseCounter,
lexicon: Object.values(lexicon||{}).map(e=>({
...e,
senses:(e.senses||[]).map(s=>({...s,phraseIds:(s.phraseIds||[]).slice()}))
})),
lexCounter,
savedAnnotations: JSON.parse(JSON.stringify(savedAnnotations||[])),
tagSuggestions: JSON.parse(JSON.stringify(persistedTagSuggestions||{})),
currentDraft:{
tokens: JSON.parse(JSON.stringify(tokens||[])),
selectedIdx: [...(selectedIdx||[])],
currentAnnotations: JSON.parse(JSON.stringify(currentAnnotations||[])),
currentGlosses: JSON.parse(JSON.stringify(currentGlosses||{})),
currentPhraseTranslation: currentPhraseTranslation||'',
activeRowIdx,
rawContext: rawContext||'',
pendingAutoTag: pendingAutoTag ? {indices:[...(pendingAutoTag.indices||[])], tagId:pendingAutoTag.tagId} : null,
activeGlossToken: activeGlossToken ?? null
}
};
return snap;
}
function restoreSessionSnapshot(snap){
const data=snap&&typeof snap==='object'?snap:{};
if(!data||(!data.fileRows&&!(data.savedAnnotations||[]).length&&!Object.keys(data.lexicon||{}).length&&!data.session)){
throw new Error('This file does not contain a valid annotation session.');
}
session = JSON.parse(JSON.stringify(data.session||{language:'',code:''}));
fileHeaders = Array.isArray(data.fileHeaders)?data.fileHeaders.slice():[];
fileRows = Array.isArray(data.fileRows)?data.fileRows.map(r=>Array.isArray(r)?r.slice():[r]):[];
colMap = Object.assign({data:-1,lang:-1,code:-1,context:-1,source:-1}, data.colMap||{});
categories = data.categories ? JSON.parse(JSON.stringify(data.categories)) : JSON.parse(JSON.stringify(DEFAULT_CATS));
phraseCounter = Number(data.phraseCounter)||0;
lexCounter = Number(data.lexCounter)||0;
savedAnnotations = Array.isArray(data.savedAnnotations)?JSON.parse(JSON.stringify(data.savedAnnotations)):[];
tagSuggestions = data.tagSuggestions ? JSON.parse(JSON.stringify(data.tagSuggestions)) : {};
lexicon={};
(Array.isArray(data.lexicon)?data.lexicon:[]).forEach(e=>{
if(e.lexId&&e.wordForm){
const k=bk(e.wordForm,e.language||'');
lexicon[k]={...e,senses:(e.senses||[]).map(s=>({...s,phraseIds:s.phraseIds||[]}))};
}
});
const draft=data.currentDraft||{};
tokens = Array.isArray(draft.tokens)?JSON.parse(JSON.stringify(draft.tokens)) : [];
selectedIdx = new Set(Array.isArray(draft.selectedIdx)?draft.selectedIdx:[]);
currentAnnotations = Array.isArray(draft.currentAnnotations)?JSON.parse(JSON.stringify(draft.currentAnnotations)):[];
currentGlosses = draft.currentGlosses ? JSON.parse(JSON.stringify(draft.currentGlosses)) : {};
currentPhraseTranslation = draft.currentPhraseTranslation||'';
activeRowIdx = Number.isInteger(draft.activeRowIdx)?draft.activeRowIdx:-1;
rawContext = draft.rawContext||'';
pendingAutoTag = draft.pendingAutoTag ? {indices:[...(draft.pendingAutoTag.indices||[])], tagId:draft.pendingAutoTag.tagId} : null;
activeGlossToken = draft.activeGlossToken ?? null;
rebuildTagSuggestions();
return {session,fileHeaders,fileRows,colMap,categories,phraseCounter,lexicon,lexCounter,savedAnnotations,tagSuggestions};
}
function autoSave(){
if(!fileRows.length) return; // nothing to save before a session is open
try{
const snap=buildSessionSnapshot();
localStorage.setItem(LS_KEY, JSON.stringify(snap));
updateAutoSaveBar();
}catch(e){
// localStorage can throw if storage quota exceeded
console.warn('Auto-save failed:', e.message);
}
}
function updateAutoSaveBar(){
const bar=document.getElementById('autosave-bar');
if(!bar) return;
bar.style.display='flex';
const dot=document.getElementById('as-dot');
dot.classList.add('saving');
setTimeout(()=>dot.classList.remove('saving'),600);
const d=new Date();
document.getElementById('as-time').textContent=
'Last saved: '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit',second:'2-digit'});
document.getElementById('as-count').textContent=
savedAnnotations.length+' phrase'+(savedAnnotations.length!==1?'s':'')+' · '+
Object.keys(lexicon).length+' lexicon entries';
}
function checkStorageOnLoad(){
try{
const raw=localStorage.getItem(LS_KEY);
if(!raw) return;
const snap=JSON.parse(raw);
if(!snap||!snap.fileRows||!snap.fileRows.length) return;
// Show restore banner
const banner=document.getElementById('restore-banner');
if(banner){
const d=new Date(snap.ts);
banner.querySelector('strong').textContent=
'Saved session found — '+d.toLocaleDateString()+' '+
d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})+
' · '+( snap.savedAnnotations||[]).length+' phrases annotated';
banner.classList.add('visible');
}
}catch(e){ console.warn('Storage check failed:', e); }
}
function restoreFromStorage(){
// If we already have state in memory (called from goHome), just re-activate
if(fileRows.length>0 && session.language){
dismissRestoreBanner();
_activateSession();
document.getElementById('autosave-bar').style.display='flex';
updateAutoSaveBar();
return;
}
// Otherwise read from localStorage (page-load restore)
try{
const raw=localStorage.getItem(LS_KEY);
if(!raw) return;
const snap=JSON.parse(raw);
restoreSessionSnapshot(snap);
dismissRestoreBanner();
_activateSession();
document.getElementById('autosave-bar').style.display='flex';
updateAutoSaveBar();
}catch(e){
alert('Could not restore session: '+e.message);
}
}
function dismissRestoreBanner(){
const b=document.getElementById('restore-banner');
if(b) b.classList.remove('visible');
}
/* Shared boot logic used by both startSession and restoreFromStorage */
function _activateSession(){
document.getElementById('sh-lang').textContent = session.language;
document.getElementById('sh-code').textContent = session.code;
document.getElementById('sh-col').textContent =
(colMap.context>=0 && fileHeaders[colMap.context]) ? fileHeaders[colMap.context] : '—';
document.getElementById('session-strip').classList.add('visible');
document.getElementById('setup-screen').style.display='none';
['annotate','data','lexicon','categories'].forEach(id=>
document.getElementById('nav-'+id).disabled=false
);
renderRowList();
renderSaved();
renderLexicon();
renderCatManager();
if(tokens.length){
renderPhrase();
renderGlossPanel();
renderTagOrderStrip();
if(selectedIdx.size){renderTagPickerActive();} else {renderTagPickerIdle();}
} else {
renderPhrase();
renderGlossPanel();
renderTagOrderStrip();
renderTagPickerIdle();
}
switchTab('annotate');
}
function clearStorage(){
const count=(savedAnnotations||[]).length;
const msg=count>0
? `This will permanently delete all ${count} saved phrase${count!==1?'s':''} and the lexicon from this browser.\n\nPlease make sure you have exported your data first.\n\nContinue?`
: 'Clear saved data from browser storage and start fresh?';
if(!confirm(msg)) return;
try{ localStorage.removeItem(LS_KEY); }catch(e){}
location.reload();
}
/* ══ LEXICON (gloss-only, no wordClass) ══ */
function bk(w,l){return(l||'').toLowerCase()+'::'+w.toLowerCase();}
function getLexBase(w,l){
// Try exact language match first, then fall back to any entry for this word form
const exact=lexicon[bk(w,l)];
if(exact) return exact;
// Fallback: find any entry whose wordForm matches (case-insensitive)
const wLow=w.toLowerCase();
return Object.values(lexicon).find(e=>e.wordForm.toLowerCase()===wLow)||null;
}
function ensureLexBase(w,l){
const k=bk(w,l);
if(!lexicon[k]){lexCounter++;lexicon[k]={lexId:'LEX-'+String(lexCounter).padStart(4,'0'),wordForm:w,language:l||'',senses:[]};}
return lexicon[k];
}
function ensureSense(base,gloss,phraseId){
let s=base.senses.find(x=>x.phraseIds.includes(phraseId));
if(!s) s=base.senses.find(x=>x.gloss===gloss);
if(!s){const n=base.senses.length+1;s={senseId:base.lexId+'-S'+n,gloss:gloss||'',phraseIds:[]};base.senses.push(s);}
if(gloss!==undefined&&gloss!==null) s.gloss=String(gloss).trim();
if(phraseId&&!s.phraseIds.includes(phraseId))s.phraseIds.push(phraseId);
return s;
}
/* ══ TAG SUGGESTIONS (from Data section) ══ */
function buildReferenceTagSuggestionsFromRows(rows){
const suggestions={};
if(!Array.isArray(rows)||!rows.length) return suggestions;
const dataRows=rows.filter(r=>Array.isArray(r)&&r.some(c=>String(c).trim()));
if(!dataRows.length) return suggestions;
const header=dataRows[0].map(h=>String(h).trim().toLowerCase());
const phraseIdx=header.findIndex(h=>['phrase','np','data','token','tokens','form','word','text','surface'].includes(h));
const wordIdx=header.findIndex(h=>['word','token','form','surface'].includes(h));
const tagIdx=header.findIndex(h=>['tag','label','annotation','annotation_tag'].includes(h));
const catIdx=header.findIndex(h=>['category','cat'].includes(h));
const subIdx=header.findIndex(h=>['subcategory','subcat','sub_category'].includes(h));
const typeIdx=header.findIndex(h=>['type','kind'].includes(h));
dataRows.slice(1).forEach(row=>{
if(!Array.isArray(row)||!row.some(c=>String(c).trim())) return;
const phrase=String((phraseIdx>=0?row[phraseIdx]:wordIdx>=0?row[wordIdx]:row[0])||'').trim();
const tagValue=String((tagIdx>=0?row[tagIdx]:'')||'').trim();
const catValue=String((catIdx>=0?row[catIdx]:'')||'').trim();
const subValue=String((subIdx>=0?row[subIdx]:'')||'').trim();
const typeValue=String((typeIdx>=0?row[typeIdx]:'')||'').trim();
const entry={
tag: tagValue || [catValue, subValue, typeValue].filter(Boolean).join('-') || '',
category: catValue || '',
subcategory: subValue || '',
type: typeValue || ''
};
if(!phrase||!entry.tag) return;
const key=phrase.toLowerCase().replace(/\s+/g,' ').trim();
if(!suggestions[key]) suggestions[key]=[];
if(!suggestions[key].some(s=>s.tag===entry.tag && s.category===entry.category && s.subcategory===entry.subcategory && s.type===entry.type)) suggestions[key].push(entry);
});
return suggestions;
}
function rebuildTagSuggestions(){
tagSuggestions={};
const addSuggestions=(source)=>{
Object.entries(source||{}).forEach(([k,v])=>{
const values=Array.isArray(v)?v:[v];
if(!tagSuggestions[k]) tagSuggestions[k]=[];
values.forEach(entry=>{
const normalized=typeof entry==='string'?{tag:entry,category:'',subcategory:'',type:''}:entry;
if(!normalized||!normalized.tag) return;
const exists=tagSuggestions[k].some(s=>s.tag===normalized.tag && s.category===normalized.category && s.subcategory===normalized.subcategory && s.type===normalized.type);
if(!exists) tagSuggestions[k].push(normalized);
});
});
};
savedAnnotations.forEach(s=>{
s.annotations.forEach(a=>{
const key=a.tokens.toLowerCase();
addSuggestions({[key]:[{tag:a.tag,category:a.category||'',subcategory:a.subcategory||'',type:a.type||''}]});
});
});
addSuggestions(referenceTagSuggestions);
}
function populateReferenceDatasetSelect(){
const sel=document.getElementById('pretrainedDatasetSelect');
if(!sel) return;
sel.innerHTML='<option value="">— none —</option>';
AVAILABLE_REFERENCE_DATASETS.forEach(ds=>{
const opt=document.createElement('option');
opt.value=ds.id;
opt.textContent=`${ds.label} (${ds.language})`;
sel.appendChild(opt);
});
}
async function loadSelectedReferenceDataset(){
const sel=document.getElementById('pretrainedDatasetSelect');
const note=document.getElementById('reference-dataset-note');
if(!sel||!note) return;
const entry=AVAILABLE_REFERENCE_DATASETS.find(d=>d.id===sel.value);
if(!entry){
referenceDataset=null;
referenceTagSuggestions={};
rebuildTagSuggestions();
note.style.display='none';
return;
}
try{
const res=await fetch(entry.file,{cache:'no-store'});
if(!res.ok) throw new Error(`Could not load ${entry.file}`);
const text=await res.text();
const rows=parseCSV(text);
referenceDataset={...entry,rows};
referenceTagSuggestions=buildReferenceTagSuggestionsFromRows(rows);
rebuildTagSuggestions();
note.style.display='';
note.textContent=`✓ Loaded ${entry.label} as a read-only reference dataset for suggestions.`;
}catch(err){
referenceDataset=null;
referenceTagSuggestions={};
rebuildTagSuggestions();
note.style.display='';
note.textContent=`⚠ ${err.message}`;
}
}
function onReferenceDatasetChange(){
loadSelectedReferenceDataset();
}
function getTagSuggestionEntries(indices){
if(!indices||!indices.length)return[];
const words=indices.map(i=>tokens[i].word).join(' ').toLowerCase();
const values=tagSuggestions[words]||[];
return Array.isArray(values)?values.filter(Boolean).map(entry=>typeof entry==='string'?{tag:entry,category:'',subcategory:'',type:''}:entry):[];
}
function getTagSuggestion(indices){
return getTagSuggestionEntries(indices).map(e=>e.tag).filter(Boolean);
}
function getSuggestionCategoryId(entry){
if(!entry) return null;
const catLabel=String(entry.category||'').trim();
const direct=categories.find(c=>c.id===catLabel || c.label.toLowerCase()===catLabel.toLowerCase());
if(direct) return direct.id;
const tag=String(entry.tag||'').trim();
return tag.split('-')[0]||null;
}
function getSuggestionSubcategoryId(entry){
if(!entry) return null;
const catId=getSuggestionCategoryId(entry);
const subLabel=String(entry.subcategory||'').trim();
const cat=categories.find(c=>c.id===catId);
if(cat){
const direct=(cat.subs||[]).find(s=>s.id===subLabel || s.label.toLowerCase()===subLabel.toLowerCase());
if(direct) return direct.id;
}
const tag=String(entry.tag||'').trim();
const parts=tag.split('-');
return parts.slice(0,2).join('-')||null;
}
function getSuggestionTypeId(entry){
if(!entry) return null;
const catId=getSuggestionCategoryId(entry);
const subId=getSuggestionSubcategoryId(entry);
const sub=categories.find(c=>c.id===catId)?.subs?.find(s=>s.id===subId);
const typeLabel=String(entry.type||'').trim();
if(sub){
const direct=(sub.types||[]).find(t=>t.id===typeLabel || t.label.toLowerCase()===typeLabel.toLowerCase());
if(direct) return direct.id;
}
const tag=String(entry.tag||'').trim();
return tag||null;
}
/* ══ TAG HELPERS ══ */
function splitTag(id){
for(const c of categories){
if(id===c.id) return{category:c.label,subcategory:'',type:''};
for(const s of c.subs||[]){
if(id===s.id) return{category:c.label,subcategory:s.label,type:''};
for(const t of s.types||[])
if(id===t.id) return{category:c.label,subcategory:s.label,type:t.label};
}
}
const p=id.split('-');return{category:p[0],subcategory:p.slice(1,-1).join('-'),type:p[p.length-1]};
}
function tagLabel(id){
for(const c of categories){
if(id===c.id) return c.label;
for(const s of c.subs||[]){
if(id===s.id) return s.label;
for(const t of s.types||[]) if(id===t.id) return t.label;
}
}
return id;
}
/* ══ SETUP ══ */
function handleFile(e){
const f=e.target.files[0];if(!f)return;
const ext=f.name.split('.').pop().toLowerCase();
if(ext==='csv'){const r=new FileReader();r.onload=ev=>initFile(parseCSV(ev.target.result),f.name);r.readAsText(f,'UTF-8');}
else{const r=new FileReader();r.onload=ev=>{const wb=XLSX.read(ev.target.result,{type:'binary',codepage:65001});const raw=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]],{header:1,defval:''}).map(r=>r.map(c=>String(c==null?'':c)));initFile(raw,f.name);};r.readAsBinaryString(f);}
}
function parseCSV(text){
return text.replace(/\r\n/g,'\n').replace(/\r/g,'\n').split('\n').map(line=>{
const cells=[];let cur='';let q=false;
for(let i=0;i<line.length;i++){const ch=line[i];if(ch==='"'){if(q&&line[i+1]==='"'){cur+='"';i++;}else q=!q;}else if(ch===','&&!q){cells.push(cur);cur='';}else cur+=ch;}
cells.push(cur);return cells.map(c=>c.trim());
});
}
function initFile(raw,name){
raw=raw.filter(r=>r.some(c=>String(c).trim()));
if(!raw.length){alert('File appears empty.');return;}
// Detect if first row looks like headers (all non-numeric, no blank)
const firstRow=raw[0];
const looksLikeHeader=firstRow.every(c=>isNaN(Number(c))&&String(c).trim().length>0);
if(looksLikeHeader){
fileHeaders=firstRow.map((h,i)=>String(h).trim()||`Column ${i+1}`);
fileRows=raw.slice(1);
} else {
// No header row — generate column names, all rows are data
fileHeaders=firstRow.map((_,i)=>`Column ${i+1}`);
fileRows=raw;
}
document.getElementById('file-note').style.display='';
document.getElementById('file-note').textContent=`✓ "${name}" — ${fileRows.length} rows · ${fileHeaders.length} columns`;
// Show the header toggle so user can override detection
const toggle=document.getElementById('header-toggle-wrap');
if(toggle){
toggle.style.display='';
document.getElementById('has-header-cb').checked=looksLikeHeader;
document.getElementById('header-toggle-wrap').querySelector('span').textContent=
looksLikeHeader?'First row treated as header (auto-detected)':'First row treated as data (no headers detected)';
}
document.getElementById('sn-1').classList.add('done');
populateColSelects();renderColTable();unlockStep('sc-2');validateSetup();
}
function toggleHeaderRow(){
const cb=document.getElementById('has-header-cb');
const allRaw=[...(cb.checked?[fileHeaders,...fileRows]:[fileHeaders,...fileRows])];
// Re-read raw from last loaded file — reconstruct from current state
const raw=[fileHeaders,...fileRows];
if(cb.checked){
// treat first data row as header
fileHeaders=raw[0].map((h,i)=>String(h).trim()||`Column ${i+1}`);
fileRows=raw.slice(1);
} else {
fileHeaders=raw[0].map((_,i)=>`Column ${i+1}`);
fileRows=raw;
}
document.getElementById('has-header-cb').closest('span').nextElementSibling&&null;
document.getElementById('header-toggle-wrap').querySelector('span').textContent=
cb.checked?'First row treated as header':'First row treated as data';
document.getElementById('file-note').textContent=
document.getElementById('file-note').textContent.replace(/\d+ rows/,fileRows.length+' rows');
populateColSelects();renderColTable();validateSetup();
}
function importLexicon(e){
const f=e.target.files[0];if(!f)return;
const r=new FileReader();
r.onload=ev=>{try{const data=JSON.parse(ev.target.result);let count=0;const entries=Array.isArray(data)?data:Object.values(data);entries.forEach(entry=>{if(entry.lexId&&entry.wordForm){const k=bk(entry.wordForm,entry.language||'');lexicon[k]={...entry,senses:(entry.senses||[]).map(s=>({...s,phraseIds:s.phraseIds||[]}))};const n=parseInt((entry.lexId||'').replace('LEX-',''));if(!isNaN(n)&&n>lexCounter)lexCounter=n;count++;}});document.getElementById('lex-import-note').style.display='';document.getElementById('lex-import-note').textContent=`✓ ${count} entries imported`;}catch{alert('Invalid lexicon JSON.');}};
r.readAsText(f,'UTF-8');
}
function populateColSelects(){
['data','code','context'].forEach(role=>{
const sel=document.getElementById('sel-'+role);if(!sel)return;
sel.innerHTML='<option value="">— select —</option>';
fileHeaders.forEach((h,i)=>{const o=document.createElement('option');o.value=i;o.textContent=h;sel.appendChild(o);});
const g=autoGuess(role);if(g>=0)sel.value=g;
});syncColMap();
}
function autoGuess(r){
const p={
data:[/\bnp\b/i,/noun.?phrase/i,/phrase/i,/\bdata\b/i],
code:[/\bcode\b/i,/corpus/i,/dataset/i],
context:[/context/i,/sentence/i,/\bsent\b/i,/full/i,/example/i,/text/i]
};
for(const pat of(p[r]||[])){const i=fileHeaders.findIndex(h=>pat.test(h));if(i>=0)return i;}
return -1;
}
function syncColMap(){
const parse=id=>{const v=document.getElementById(id)?.value;return(v===''||v===null||v===undefined)?-1:parseInt(v);};
colMap.data = parse('sel-data');
colMap.code = parse('sel-code');
colMap.context= parse('sel-context');
colMap.source = -1;
colMap.lang = -1;
}
function onColMapChange(){syncColMap();renderColTable();if(colMap.context>=0){document.getElementById('sn-2').classList.add('done');}validateSetup();}
function renderColTable(){
const ro={};Object.entries(colMap).forEach(([r,i])=>{if(i>=0)ro[i]=r;});
const prev=fileRows.slice(0,5);let h='<table class="col-table"><thead><tr>';
fileHeaders.forEach((col,i)=>{const r=ro[i]||'';h+=`<th class="${r?'role-'+r:''}">${col}${r?` <span style="font-size:9px;opacity:.7">[${r}]</span>`:''}</th>`;});
h+='</tr></thead><tbody>';
prev.forEach(row=>{h+='<tr>';fileHeaders.forEach((_,i)=>{const r=ro[i]||'';h+=`<td class="${r?'role-'+r:''}">${row[i]||''}</td>`;});h+='</tr>';});
h+='</tbody></table>';
document.getElementById('col-table-wrap').innerHTML=h;
const clrs={data:'var(--accent)',code:'var(--amber)',context:'var(--purple)',source:'var(--teal)'};
document.getElementById('col-legend').innerHTML=Object.entries(colMap)
.filter(([r,i])=>i>=0&&r!=='lang')
.map(([r,i])=>`<div class="legend-item"><span class="badge-dot" style="background:${clrs[r]||'var(--ink-4)'};width:8px;height:8px;border-radius:50%;flex-shrink:0"></span><span style="color:${clrs[r]||'var(--ink-2)'};font-weight:600">${r}</span><span style="color:var(--ink-3)"> → ${fileHeaders[i]}</span></div>`).join('');
}
function unlockStep(id){document.getElementById(id).classList.remove('locked');}
function onLangChange(){const v=document.getElementById('langSelect').value;document.getElementById('langCustom').style.display=v==='__other__'?'':'none';validateSetup();}
function validateSetup(){
const hf=fileRows.length>0;
const hCtx=colMap.context>=0;
const hData=colMap.data>=0;
const hColCode=colMap.code>=0;
const lv=document.getElementById('langSelect').value,lc=document.getElementById('langCustom').value.trim();
const hl=(lv&&lv!=='__other__')||(lv==='__other__'&&lc.length>0);
const hSrc=(document.getElementById('sourceNameInput')?.value||'').trim().length>0;
const hDsCode=document.getElementById('codeInput').value.trim().length>0;
const ok=hf&&hCtx&&hData&&hColCode&&hl&&hSrc&&hDsCode;
document.getElementById('start-btn').disabled=!ok;
const m=[];
if(!hCtx) m.push('select context column');
if(!hData) m.push('select data column');
if(!hColCode)m.push('select data code column');
if(!hl) m.push('select language');
if(!hSrc) m.push('enter source name');
if(!hDsCode) m.push('enter dataset code');
document.getElementById('setup-msg').textContent=ok?'':'Still needed: '+m.join(' · ')+'.';
if(ok) document.getElementById('sn-2').classList.add('done');
}
async function startSession(){
const lv=document.getElementById('langSelect').value;
session.language=lv==='__other__'?document.getElementById('langCustom').value.trim():lv;
session.code=document.getElementById('codeInput').value.trim();
session.sourceName=document.getElementById('sourceNameInput').value.trim();
await loadSelectedReferenceDataset();
_activateSession();
autoSave();
}
function goHome(){
if(savedAnnotations.length>0){
if(!confirm('Go back to the main page? Your annotated data is auto-saved.'))return;
}
// Show setup screen
document.getElementById('setup-screen').style.display='';
document.getElementById('session-strip').classList.remove('visible');
['annotate','data','lexicon','categories'].forEach(id=>{
document.getElementById('nav-'+id).disabled=true;
const p=document.getElementById('tab-'+id);
p.style.display='none';p.classList.remove('active');
});
document.getElementById('nav-annotate').classList.add('active');
// Show the resume banner if we have saved work
if(savedAnnotations.length>0||Object.keys(lexicon).length>0){
const banner=document.getElementById('restore-banner');
if(banner){
const count=savedAnnotations.length;
banner.querySelector('strong').textContent=
'Session in progress — '+count+' phrase'+(count!==1?'s':'')+' annotated';
banner.classList.add('visible');
}
}
}
function resetSession(){
if(!confirm('Start a new session? Your current auto-saved data will remain in storage until you clear it.'))return;
location.reload();
}
/* ══ TABS ══ */
function switchTab(t){
['annotate','data','lexicon','categories'].forEach(id=>{
const p=document.getElementById('tab-'+id);const show=id===t;
p.style.display=show?'flex':'none';p.classList.toggle('active',show);
document.getElementById('nav-'+id).classList.toggle('active',show);
});
if(t==='data')renderSaved();if(t==='lexicon')renderLexicon();if(t==='categories')renderCatManager();
}
/* ══ ROW LIST ══ */
function gv(row,col,fb){if(col>=0&&row[col]!==undefined)return String(row[col]).trim();return fb;}
function renderRowList(){
document.getElementById('row-list').innerHTML=fileRows.map((row,i)=>{
const ctx=gv(row,colMap.context,'');const savedEntry=getSavedEntryForRow(i);
const np=savedEntry&&typeof savedEntry.phrase==='string'?savedEntry.phrase:gv(row,colMap.data,'');
const done=!!savedEntry;
const active=i===activeRowIdx;
return`<div class="row-item${done?' done':''}${active?' active':''}" onclick="selectRow(${i})" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();selectRow(${i})}" id="ri-${i}" role="option" tabindex="0" aria-selected="${active}"><span class="row-num">${i+1}</span><span class="row-copy"><span class="row-phrase">${np?escHtml(np):'<em>—</em>'}</span><span class="row-text">${ctx?escHtml(ctx):'No context'}</span></span>${done?'<span class="done-badge">done</span>':''}</div>`;
}).join('');updateProgress();updateRowNavigation();
}
function updateProgress(){
const total=fileRows.length,done=fileRows.filter((_,i)=>savedAnnotations.some(a=>a.rowIndex===i)).length;
const pct=total?Math.round(done/total*100):0;
document.getElementById('prog-fill').style.width=pct+'%';
document.getElementById('prog-label').textContent=`${done} / ${total} annotated (${pct}%)`;
document.getElementById('file-status').textContent=`${total} rows`;
}
function updateRowNavigation(){
const label=document.getElementById('active-row-label');
const prev=document.getElementById('prev-row-btn');
const next=document.getElementById('next-row-btn');
const hasActive=activeRowIdx>=0&&activeRowIdx<fileRows.length;
if(label)label.textContent=hasActive?`Row ${activeRowIdx+1} of ${fileRows.length}`:'No row selected';
if(prev)prev.disabled=!hasActive||activeRowIdx===0;
if(next)next.disabled=!fileRows.length||(hasActive&&activeRowIdx===fileRows.length-1);
}
function applyRowsSidebarState(collapsed){
const layout=document.getElementById('annotate-layout');
const card=document.querySelector('.rows-card');
const toggle=document.getElementById('rows-sidebar-toggle');
if(!layout||!card||!toggle)return;
layout.classList.toggle('rows-collapsed',collapsed);
card.classList.toggle('collapsed',collapsed);
toggle.textContent=collapsed?'☰':'‹';
toggle.setAttribute('aria-expanded',String(!collapsed));
toggle.setAttribute('aria-label',collapsed?'Expand row navigation':'Collapse row navigation');
toggle.title=collapsed?'Expand row navigation':'Collapse row navigation';
}
function toggleRowsSidebar(){
const layout=document.getElementById('annotate-layout');
if(!layout)return;
const collapsed=!layout.classList.contains('rows-collapsed');
applyRowsSidebarState(collapsed);
try{localStorage.setItem(ROWS_SIDEBAR_KEY,collapsed?'1':'0');}catch(e){}
}
function restoreRowsSidebarState(){
let collapsed=false;
try{collapsed=localStorage.getItem(ROWS_SIDEBAR_KEY)==='1';}catch(e){}
applyRowsSidebarState(collapsed);
}
function selectAdjacentRow(offset){
if(!fileRows.length)return;
const nextIndex=activeRowIdx<0?0:Math.max(0,Math.min(fileRows.length-1,activeRowIdx+offset));
selectRow(nextIndex);
}
function selectRow(i){
if(i<0||i>=fileRows.length)return;
activeRowIdx=i;document.querySelectorAll('.row-item').forEach((el,idx)=>el.classList.toggle('active',idx===i));
document.querySelectorAll('.row-item').forEach((el,idx)=>el.setAttribute('aria-selected',String(idx===i)));
const activeRow=document.getElementById('ri-'+i);
if(activeRow&&activeRow.scrollIntoView)activeRow.scrollIntoView({block:'nearest',inline:'nearest'});
updateRowNavigation();
const row=fileRows[i];
const ctx=gv(row,colMap.context,'');
const savedEntry=getSavedEntryForRow(i);
// A saved annotation is canonical. fileRows is also updated on save, while
// this fallback keeps older imported sessions (whose fileRows still contain
// the original CSV value) working correctly.
const np=savedEntry&&typeof savedEntry.phrase==='string'
? savedEntry.phrase
: gv(row,colMap.data,'');
loadPhrase(np,ctx,savedEntry);
}
/* ══ PHRASE ══ */
function rowLang(){return session.language||'';}
function highlightNP(ctx, np){
if(!np||!ctx) return escHtml(ctx);
// Strip trailing/leading punctuation from each NP token for a flexible match
const stripped=np.trim().replace(/[.,!?;:'"()\[\]{}«»]+$/,'').replace(/^[.,!?;:'"()\[\]{}«»]+/,'');
if(!stripped) return escHtml(ctx);
const escaped=stripped.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
// Case-insensitive, punctuation-tolerant: match the NP followed by optional punctuation
const re=new RegExp('('+escaped+'[.,!?;:\'")\\]]*)', 'gi');
if(!re.test(ctx)) return escHtml(ctx); // no match — return safely escaped plain text
return escHtml(ctx).replace(new RegExp('('+escaped.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'[.,!?;:\'"\\]\\)]*)', 'gi'),
'<mark style="background:var(--purple-light);color:var(--purple);border-radius:3px;padding:0 3px;font-weight:600">$1</mark>');
}
function escHtml(t){
return String(t).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function getSavedEntryForRow(rowIndex){
return savedAnnotations.find(s=>Number(s.rowIndex)===Number(rowIndex))||null;
}
function restoreDraftFromSavedEntry(savedEntry){
if(!savedEntry){
currentAnnotations=[];
currentPhraseTranslation='';
selectedIdx=new Set();
return;
}
currentPhraseTranslation = savedEntry.phraseTranslation || '';
(savedEntry.tokenRecords||[]).forEach(tr=>{
const tokenIndex = Number(tr.position)-1;
if(tokens[tokenIndex] && tr.gloss && String(tr.gloss).trim()) {
currentGlosses[tokens[tokenIndex].id] = String(tr.gloss).trim();
}
});
currentAnnotations = (savedEntry.annotations||[]).map((a,idx)=>{
const words = String(a.tokens||'').split(/\s+/).filter(Boolean);
const indices = [];
words.forEach(word=>{
const tokenIndex = tokens.findIndex((t,pos)=>!indices.includes(pos) && t.word===word);
if(tokenIndex>=0) indices.push(tokenIndex);
});
return {
indices,
words: a.tokens || '',
tag: a.tag || '',
category: a.category || '',
subcategory: a.subcategory || '',
type: a.type || '',
order: a.order || idx + 1
};
});
selectedIdx = new Set();
}
function autoResizeNPInput(el){
if(!el)return;
el.style.height='auto';
const nextHeight=Math.max(el.scrollHeight||48,48);
el.style.height=nextHeight+'px';
el.style.overflowY='hidden';
}
function loadPhrase(npText,ctx,savedEntry=null){
// Store raw context — never touch this again
rawContext=ctx||'';
const ctxBox=document.getElementById('context-box');
const ctxEl=document.getElementById('context-text');
if(rawContext){
ctxEl.innerHTML=highlightNP(rawContext,npText);
ctxBox.style.display='';
} else {
ctxBox.style.display='none';
}
// Set editable NP
document.getElementById('np-edit-area').style.display='';
const npInput=document.getElementById('np-edit-input');
npInput.value=npText;
autoResizeNPInput(npInput);
// Tokenise
tokeniseFromInput(npText);
restoreDraftFromSavedEntry(savedEntry);
renderPhrase();renderGlossPanel();renderTagOrderStrip();renderTagPickerIdle();updateStatusHint();
}
function reloadTokens(){
const val=document.getElementById('np-edit-input').value.trim();
// Re-highlight in context using stored raw text — NP edit never changes context
if(rawContext){
document.getElementById('context-text').innerHTML=highlightNP(rawContext,val);
}
tokeniseFromInput(val);
}
function tokeniseFromInput(text){
tokens=text.split(/\s+/).filter(Boolean).map((w,i)=>({id:i,word:w}));
selectedIdx=new Set();currentAnnotations=[];currentPhraseTranslation='';
pendingAutoTag=null;dismissBanner();hideValidation();
const lang=rowLang();
// Pre-fill glosses from lexicon
currentGlosses={};
tokens.forEach(t=>{const base=getLexBase(t.word,lang);if(base&&base.senses.length>0)currentGlosses[t.id]=base.senses[0].gloss;});
renderPhrase();renderGlossPanel();renderTagOrderStrip();renderTagPickerIdle();updateStatusHint();
}
function renderPhrase(){
const el=document.getElementById('phrase-stage');
if(!tokens.length){el.innerHTML='<span class="empty-stage">No tokens — edit and click Reload.</span>';return;}
const lang=rowLang();
el.innerHTML=tokens.map(t=>{
const anno=currentAnnotations.find(a=>a.indices.includes(t.id));
const sel=selectedIdx.has(t.id);
const base=getLexBase(t.word,lang);
const hasSense=base&&base.senses.length>0;
const cls='word-chip'+(sel?' selected':anno?' tagged':'')+(hasSense?' has-sense':'');
return`<div class="${cls}" onclick="toggleToken(${t.id})">
<div class="token">${t.word}</div>
${anno?`<div class="tag-lbl">${anno.tag}</div>`:''}
${base?`<div class="lex-code">${base.lexId}</div>`:''}
${anno?`<div class="ord-num">${anno.order}</div>`:''}
<div class="sense-dot"></div>
</div>`;
}).join('');
}
/* Grammatical gloss feature sets */
const DEFAULT_GRAM_GLOSSES=[
{group:'Number', items:['PL','SG']},
{group:'Gender', items:['FEM','MASC','NEUT']},
{group:'Person', items:['1SG','2SG','3SG','1PL','2PL','3PL']},
{group:'Case', items:['GEN','POSS','LOC','REL']}
];
const GRAM_GLOSS_STORAGE_KEY='np_annotator_gram_glosses_v1';
let customGramGlossGroups=loadCustomGramGlossGroups();
function loadCustomGramGlossGroups(){
try{
const raw=localStorage.getItem(GRAM_GLOSS_STORAGE_KEY);
if(!raw) return [{group:'Other', items:[]}];
const parsed=JSON.parse(raw);
if(Array.isArray(parsed)) return parsed.filter(g=>g&&g.group).length ? parsed.filter(g=>g&&g.group) : [{group:'Other', items:[]}];
}catch(e){
console.warn('Could not load custom gloss groups:', e);
}
return [{group:'Other', items:[]}];
}
function saveCustomGramGlossGroups(){
try{ localStorage.setItem(GRAM_GLOSS_STORAGE_KEY, JSON.stringify(customGramGlossGroups)); }catch(e){ console.warn('Could not save custom gloss groups:', e); }
}
function getGlossPaletteGroups(){
const groups=DEFAULT_GRAM_GLOSSES.map(g=>({group:g.group, items:[...(g.items||[])]}));
const other=customGramGlossGroups.find(g=>g.group==='Other');
if(other){
groups.push({group:'Other', items:[...(other.items||[])]});
} else {
groups.push({group:'Other', items:[]});
}
return groups;
}
function addCustomGramGlossItem(value){
const cleaned=String(value||'').trim().replace(/\s+/g,'');
if(!cleaned) return;
let other=customGramGlossGroups.find(g=>g.group==='Other');
if(!other){other={group:'Other', items:[]}; customGramGlossGroups.push(other);}
if(!other.items.some(item=>item.toLowerCase()===cleaned.toLowerCase())){
other.items.push(cleaned);
saveCustomGramGlossGroups();
}
renderGlossPanel();
}
function removeCustomGramGlossItem(value){
const cleaned=String(value||'').trim();
if(!cleaned) return;
const other=customGramGlossGroups.find(g=>g.group==='Other');
if(!other) return;
other.items=other.items.filter(item=>item!==cleaned);
saveCustomGramGlossGroups();
renderGlossPanel();
}
function addCustomGlossItemFromInput(){
const input=document.getElementById('custom-gram-item-input');
if(!input) return;
addCustomGramGlossItem(input.value);
input.value='';
}
function appendGramGloss(tid, gram){
const inp=document.getElementById('gi-'+tid);if(!inp)return;
const cur=inp.value.trim();
inp.value=cur?(cur+'.'+gram):gram;
currentGlosses[tid]=inp.value;
}
function renderGlossPanel(){
const panel=document.getElementById('gloss-panel');
if(!tokens.length){panel.innerHTML='<div style="color:var(--ink-4);font-size:13px;font-style:italic">Load a phrase to add glosses.</div>';return;}
const lang=rowLang();
// Build grammatical chip palette (shared, shown once above token rows)
const glossGroups=getGlossPaletteGroups();
let chipPalette=`<div class="gram-palette">`;
glossGroups.forEach(grp=>{
chipPalette+=`<div class="gram-group"><span class="gram-group-label">${escHtml(grp.group)}</span>`;
if(grp.group==='Other' && !grp.items.length){
chipPalette+=`<div style="font-size:11px;color:var(--ink-4);margin-top:4px">No custom glosses yet.</div>`;
} else {
grp.items.forEach(item=>{
const safeItem=String(item).replace(/'/g,"\\'");
chipPalette+=`<div style="display:flex;align-items:center;gap:4px">`;
chipPalette+=`<button class="gram-chip" onclick="appendGramGlossActive('${safeItem}')" title="Append .${escHtml(item)} to selected token gloss">${escHtml(item)}</button>`;
if(grp.group==='Other'){
chipPalette+=`<button class="icon-btn" onclick="removeCustomGramGlossItem('${safeItem}')" title="Remove custom gloss">×</button>`;
}
chipPalette+=`</div>`;
});
}
chipPalette+=`</div>`;
});
chipPalette+=`</div>`;
let html=`<div class="gloss-panel-label">Token glosses</div>
${chipPalette}
<div class="gram-hint">Click a chip to append to the focused gloss field, or type freely.</div>
<div style="display:flex;gap:6px;margin:8px 0 10px">
<input id="custom-gram-item-input" type="text" placeholder="Add custom gloss item (e.g. ACC)" style="flex:1;min-width:0">
<button class="btn btn-sm btn-ghost" onclick="addCustomGlossItemFromInput()">+ Add</button>
</div>
<div class="gloss-tokens">`;
tokens.forEach(t=>{
const val=(currentGlosses[t.id]||'').replace(/"/g,'"');
const base=getLexBase(t.word,lang);
const sc=base?base.senses.length:0;
const hint=sc>1?`${sc} senses`:sc===1?'from lexicon':'';
html+=`<div class="gloss-row-item">
<span class="gloss-word" title="${t.word}">${t.word}</span>
<input class="gloss-input" id="gi-${t.id}" type="text" value="${val}" placeholder="gloss…"
oninput="setGloss(${t.id},this.value)"
onfocus="activeGlossToken=${t.id}"
title="English or grammatical gloss for '${t.word}'">
<span class="gloss-suggest">${hint}</span>
</div>`;
});
html+=`</div><div class="phrase-trans-row">
<span class="phrase-trans-label">Translation</span>
<input class="phrase-trans-input" id="phrase-trans" type="text" placeholder="Type the translation…" value="${currentPhraseTranslation.replace(/"/g,'"')}">
</div>`;
panel.innerHTML=html;
}
let activeGlossToken=null; // tracks which gloss input is focused for chip clicks
function setGloss(tid,val){currentGlosses[tid]=val;}
function appendGramGlossActive(gram){
// Use the focused token; fall back to the last token if none focused
const tid = activeGlossToken!==null ? activeGlossToken
: (tokens.length ? tokens[tokens.length-1].id : null);
if(tid===null) return;
const inp=document.getElementById('gi-'+tid);
if(!inp) return;
const cur=inp.value.trim();
inp.value=cur ? cur+'.'+gram : gram;
currentGlosses[tid]=inp.value;
inp.focus();
}
function toggleToken(id){
selectedIdx.has(id)?selectedIdx.delete(id):selectedIdx.add(id);
renderPhrase();updateStatusHint();checkAutoTag();renderTagPickerActive();
}
function updateStatusHint(){/* status shown via tag picker */}
function clearSelection(){selectedIdx=new Set();renderPhrase();dismissBanner();renderTagPickerIdle();}
function clearAll(){selectedIdx=new Set();currentAnnotations=[];renderPhrase();renderTagOrderStrip();dismissBanner();hideValidation();renderTagPickerIdle();}
/* ══ TAG PICKER (three-step: category → subcategory → type) ══ */
let tagPickerCat=null;