-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
2545 lines (2274 loc) · 124 KB
/
Copy patheditor.js
File metadata and controls
2545 lines (2274 loc) · 124 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
const SB = 'https://tfqnzszyjsdgdeksizel.supabase.co/rest/v1';
const KEY = window.__SUPABASE_KEY__;
const H = { 'apikey': KEY, 'Authorization': `Bearer ${KEY}`,
'Content-Type': 'application/json', 'Prefer': 'return=representation' };
function downloadSelf() {
const html = document.documentElement.outerHTML;
const blob = new Blob([html], { type: 'text/html' });
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
}
// ── API ───────────────────────────────────────────────────────────────────────
async function get(path, signal) {
const r = await fetch(SB + path, { headers: H, signal });
if (!r.ok) throw new Error(`GET ${path} → ${r.status}`);
return r.json();
}
async function post(table, data) {
const r = await fetch(`${SB}/${table}`, { method: 'POST', headers: H, body: JSON.stringify(data) });
if (!r.ok) throw new Error(`POST ${table} → ${r.status}: ${await r.text()}`);
const j = await r.json(); return Array.isArray(j) ? j[0] : j;
}
async function patch(table, filter, data) {
const r = await fetch(`${SB}/${table}?${filter}`, { method: 'PATCH', headers: H, body: JSON.stringify(data) });
if (!r.ok) throw new Error(`PATCH ${table} → ${r.status}: ${await r.text()}`);
return r.status;
}
async function del(table, filter) {
const r = await fetch(`${SB}/${table}?${filter}`, { method: 'DELETE', headers: H });
if (!r.ok) throw new Error(`DELETE ${table} → ${r.status}: ${await r.text()}`);
return r.status;
}
// Escapes a value for safe interpolation into innerHTML template strings. Database text
// (titles, names, notes, source/publisher names, error messages) is never trusted verbatim —
// without this, a title or note containing "<" or "&" could break rendering or inject markup.
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, ch => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
})[ch]);
}
// Escapes a value for safe interpolation into a single-quoted JS string literal that itself
// sits inside a double-quoted inline onclick="..." HTML attribute (a nested context that plain
// escapeHtml doesn't fully cover, since the browser HTML-decodes the attribute before running it
// as JS — an apostrophe surviving that decode would still break out of the JS string).
function escapeJsAttr(value) {
return String(value ?? '')
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/"/g, '"')
.replace(/</g, '<').replace(/>/g, '>');
}
// ── Tabs ──────────────────────────────────────────────────────────────────────
let bioLoaded = false;
let arbeidslisteLoaded = false;
let sisteLoaded = false;
function switchTab(name) {
if (name === 'biolinks' && !bioLoaded) loadBioPersons();
if (name === 'arbeidsliste' && !arbeidslisteLoaded) loadArbeidsliste();
if (name === 'siste' && !sisteLoaded) loadSiste();
document.querySelectorAll('.tab').forEach(t => {
t.classList.toggle('active', t.getAttribute('onclick') === `switchTab('${name}')`);
});
document.querySelectorAll('.tab-content').forEach(el => {
el.classList.toggle('active', el.id === `tab-${name}`);
});
}
// ── Person lookup factory ─────────────────────────────────────────────────────
async function openComposerScores(personId, name) {
const cc = await get(`/composition_person?person_id=eq.${personId}&select=composition_id&limit=100`);
const ids = cc.map(r => r.composition_id).join(',');
const comps = ids ? (await get(`/composition?composition_id=in.(${ids})&select=composition_id,title,year_composed,public_domain,musescore_link`)).sort((a,b) => (a.title||'').localeCompare(b.title||'')) : [];
const modal = document.createElement('div');
modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;display:flex;align-items:center;justify-content:center';
const box = document.createElement('div');
box.style.cssText = 'background:white;border-radius:8px;padding:1.5rem;max-width:600px;width:90%;max-height:80vh;overflow-y:auto';
box.innerHTML = `<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem">
<h3 style="margin:0;font-size:1rem">${escapeHtml(name)} — ${comps.length} komposisjoner</h3>
<button type="button" onclick="this.closest('.modal-overlay').remove()" style="background:none;border:none;font-size:1.2rem;cursor:pointer">✕</button>
</div>
<table style="width:100%;border-collapse:collapse;font-size:0.85rem">
<tr style="border-bottom:2px solid #eee"><th style="text-align:left;padding:0.3rem">Tittel</th><th>År</th><th>PD</th><th>MS</th></tr>
${comps.map(c => `<tr style="border-bottom:1px solid #f0f0f0">
<td style="padding:0.3rem">${escapeHtml(c.title)}</td>
<td style="text-align:center;color:#666">${escapeHtml(c.year_composed||'—')}</td>
<td style="text-align:center">${c.public_domain==='Yes'?'✓':''}</td>
<td style="text-align:center">${c.musescore_link?`<a href="${escapeHtml(c.musescore_link)}" target="_blank" rel="noopener noreferrer">🔗</a>`:''}</td>
</tr>`).join('')}
</table>`;
modal.className = 'modal-overlay';
modal.appendChild(box);
modal.onclick = e => { if(e.target===modal) modal.remove(); };
document.body.appendChild(modal);
}
function makeLookup(searchId, resultsId, tagsId, list, modalTarget) {
const inp = document.getElementById(searchId);
const res = document.getElementById(resultsId);
let t, controller;
inp.addEventListener('input', () => {
clearTimeout(t);
const q = inp.value.trim();
if (q.length < 2) { res.classList.remove('open'); return; }
t = setTimeout(async () => {
controller?.abort();
controller = new AbortController();
let rows;
try {
rows = await get(`/person?last_name=ilike.${encodeURIComponent(q)}*&select=person_id,first_name,last_name,nationality,born,died,pseudonym&limit=12&order=last_name`, controller.signal);
} catch (err) {
if (err.name === 'AbortError') return;
throw err;
}
res.innerHTML = '';
rows.forEach(p => {
const name = [p.first_name, p.last_name].filter(Boolean).join(' ');
const flag = p.nationality ? countryCodeToFlag(p.nationality) : '';
const years = p.born ? ` ${p.born}${p.died ? '–'+p.died : ''}` : '';
const d = document.createElement('div');
d.className = 'lookup-item';
d.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:0.5rem';
const left = document.createElement('span');
left.innerHTML = `${flag} ${escapeHtml(name)}<span style="color:var(--muted);font-size:0.8rem">${escapeHtml(years)}</span>`;
left.style.cursor = 'pointer';
left.onclick = () => { addTag(p.person_id, name, tagsId, list, '', p.pseudonym || ''); inp.value = ''; res.classList.remove('open'); };
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = '🎵';
btn.title = 'Se scores';
btn.style.cssText = 'background:none;border:1px solid var(--border);border-radius:4px;padding:0 0.4rem;cursor:pointer;font-size:0.85rem;flex-shrink:0';
btn.onclick = (e) => { e.stopPropagation(); openComposerScores(p.person_id, name); inp.value = ''; res.classList.remove('open'); };
d.appendChild(left);
d.appendChild(btn);
res.appendChild(d);
});
const add = document.createElement('div');
add.className = 'lookup-item add-new';
add.textContent = `+ Legg til "${q}" som ny person`;
add.onclick = () => { openPersonModal(q, tagsId, list); inp.value = ''; res.classList.remove('open'); };
res.appendChild(add);
res.classList.add('open');
}, 250);
});
document.addEventListener('click', e => {
if (!inp.contains(e.target) && !res.contains(e.target)) res.classList.remove('open');
});
}
function addTag(pid, name, tagsId, list, creditedAs, pseudonyms) {
if (list.find(x => x.person_id === pid)) return;
list.push({ person_id: pid, name, credited_as: creditedAs || '', pseudonyms: pseudonyms || '' });
renderTags(tagsId, list);
}
function renderTags(tagsId, list) {
const c = document.getElementById(tagsId);
c.innerHTML = '';
list.forEach((p, i) => {
const t = document.createElement('div');
t.className = 'tag';
t.style.cssText = 'display:inline-flex;align-items:center;gap:0.35rem;padding:0.25rem 0.5rem;flex-wrap:wrap';
const nameSpan = document.createElement('span');
nameSpan.textContent = p.name;
nameSpan.style.cursor = 'pointer';
nameSpan.title = 'Vis komposisjoner';
nameSpan.onclick = () => openComposerScores(p.person_id, p.name);
// Build pseudonym dropdown
const pseudoList = (p.pseudonyms || '').split(',').map(s => s.trim()).filter(Boolean);
let creditedEl;
if (pseudoList.length > 0) {
creditedEl = document.createElement('select');
creditedEl.title = 'Velg pseudonym brukt på dette noteeksemplaret';
creditedEl.style.cssText = 'font-size:0.78rem;padding:0.15rem 0.35rem;border:1px dashed var(--border);border-radius:3px;background:white;color:var(--ink);font-family:inherit;font-weight:400;max-width:150px';
const blank = document.createElement('option');
blank.value = '';
blank.textContent = 'Brukt pseudonym…';
creditedEl.appendChild(blank);
pseudoList.forEach(ps => {
const opt = document.createElement('option');
opt.value = ps;
opt.textContent = ps;
if (ps === p.credited_as) opt.selected = true;
creditedEl.appendChild(opt);
});
if (p.credited_as && !pseudoList.includes(p.credited_as)) {
// credited_as was saved but not in pseudonym list — show it anyway
const opt = document.createElement('option');
opt.value = p.credited_as;
opt.textContent = p.credited_as;
opt.selected = true;
creditedEl.appendChild(opt);
}
creditedEl.onchange = () => { list[i].credited_as = creditedEl.value; };
} else {
creditedEl = document.createElement('input');
creditedEl.type = 'text';
creditedEl.value = p.credited_as || '';
creditedEl.placeholder = 'Brukt pseudonym…';
creditedEl.title = 'Fyll inn hvis et pseudonym er brukt på dette noteeksemplaret';
creditedEl.style.cssText = 'width:130px;font-size:0.78rem;padding:0.15rem 0.35rem;border:1px dashed var(--border);border-radius:3px;background:white;color:var(--ink);font-family:inherit;font-weight:400';
creditedEl.oninput = () => { list[i].credited_as = creditedEl.value.trim(); };
}
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.textContent = '×';
delBtn.onclick = () => { list.splice(i,1); renderTags(tagsId, list); };
t.appendChild(nameSpan);
t.appendChild(creditedEl);
t.appendChild(delBtn);
c.appendChild(t);
});
}
// ── Credited-as field helper ──────────────────────────────────────────────────
// prefix = 'e' or 'n', idx = row index, pseudonyms = comma-separated string, current = saved value
function renderCreditedAsField(prefix, idx, pseudonyms, current) {
const wrap = document.getElementById(`${prefix}_ccredited_wrap_${idx}`);
if (!wrap) return;
wrap.innerHTML = '';
const list = prefix === 'e' ? eContributors : nContributors;
const c = list.find(x => x.idx === idx);
const pseudoList = (pseudonyms||'').split(',').map(s => s.trim()).filter(Boolean);
if (pseudoList.length > 0) {
const sel = document.createElement('select');
sel.style.cssText = 'width:100%;font-size:0.82rem;padding:0.3rem 0.5rem;border:1px dashed var(--border);border-radius:4px;background:white;font-family:inherit';
sel.title = 'Pseudonym brukt på dette eksemplaret';
const blank = document.createElement('option');
blank.value = '';
blank.textContent = '— Kreditert som (pseudonym) —';
sel.appendChild(blank);
pseudoList.forEach(ps => {
const opt = document.createElement('option');
opt.value = ps; opt.textContent = ps;
if (ps === current) opt.selected = true;
sel.appendChild(opt);
});
if (current && !pseudoList.includes(current)) {
const opt = document.createElement('option');
opt.value = current; opt.textContent = current; opt.selected = true;
sel.appendChild(opt);
}
sel.onchange = () => { if (c) c.credited_as = sel.value; };
wrap.appendChild(sel);
} else {
const inp = document.createElement('input');
inp.type = 'text';
inp.value = current || '';
inp.placeholder = 'Kreditert som (valgfritt)…';
inp.style.cssText = 'width:100%;font-size:0.82rem;padding:0.3rem 0.5rem;border:1px dashed var(--border);border-radius:4px;background:white;font-family:inherit';
inp.title = 'Fyll inn hvis personen er kreditert under et annet navn på dette eksemplaret';
inp.oninput = () => { if (c) c.credited_as = inp.value.trim(); };
wrap.appendChild(inp);
}
}
// ── "Translates" picker (for role = Translator) ──────────────────────────────
// Returns the other rows in this contributor list currently set to role = Lyricist
function getLyricistCandidates(prefix, contributors, excludeIdx) {
return contributors
.filter(c => c.idx !== excludeIdx && c.person_id)
.map(c => ({ ...c, _role: document.getElementById(`${prefix}_crole_${c.idx}`)?.value }))
.filter(c => c._role === 'Lyricist');
}
// Shows/hides and (re)populates the "oversetter teksten til…" dropdown for a row,
// based on its current role. Call again after adding/removing rows if a translator
// row was set up before its lyricist row existed, to refresh the candidate list.
function updateTranslatesField(prefix, idx) {
const contributors = prefix === 'e' ? eContributors : nContributors;
const c = contributors.find(x => x.idx === idx);
const roleSel = document.getElementById(`${prefix}_crole_${idx}`);
const wrap = document.getElementById(`${prefix}_ctranslates_wrap_${idx}`);
if (!roleSel || !wrap || !c) return;
if (roleSel.value !== 'Translator') {
wrap.style.display = 'none';
wrap.innerHTML = '';
c.translates_person_id = null;
return;
}
const candidates = getLyricistCandidates(prefix, contributors, idx);
wrap.innerHTML = '';
if (candidates.length === 1) {
// Only one lyricist on this composition — no ambiguity, so just use it.
c.translates_person_id = candidates[0].person_id;
const note = document.createElement('div');
note.style.cssText = 'font-size:0.82rem;color:var(--muted);padding:0.3rem 0';
note.textContent = `Oversetter teksten til ${candidates[0].name}`;
wrap.appendChild(note);
const refresh = document.createElement('span');
refresh.textContent = '↻ oppdater liste';
refresh.title = 'Oppdater listen over tekstforfattere';
refresh.style.cssText = 'display:inline-block;font-size:0.75rem;color:var(--muted);cursor:pointer;text-decoration:underline';
refresh.onclick = () => updateTranslatesField(prefix, idx);
wrap.appendChild(refresh);
wrap.style.display = 'block';
return;
}
const sel = document.createElement('select');
sel.style.cssText = 'width:100%;font-size:0.82rem;padding:0.3rem 0.5rem;border:1px dashed var(--border);border-radius:4px;background:white;font-family:inherit';
sel.title = 'Hvilken tekstforfatters tekst blir oversatt';
const blank = document.createElement('option');
blank.value = '';
blank.textContent = candidates.length ? '— oversetter teksten til —' : '— legg til tekstforfatteren først —';
sel.appendChild(blank);
candidates.forEach(cand => {
const opt = document.createElement('option');
opt.value = cand.person_id;
opt.textContent = cand.name || `#${cand.person_id}`;
if (c.translates_person_id === cand.person_id) opt.selected = true;
sel.appendChild(opt);
});
sel.onchange = () => { c.translates_person_id = parseInt(sel.value) || null; };
wrap.appendChild(sel);
// Small refresh link, in case the lyricist row was added/edited after this one
const refresh = document.createElement('span');
refresh.textContent = '↻ oppdater liste';
refresh.title = 'Oppdater listen over tekstforfattere';
refresh.style.cssText = 'display:inline-block;margin-top:0.2rem;font-size:0.75rem;color:var(--muted);cursor:pointer;text-decoration:underline';
refresh.onclick = () => updateTranslatesField(prefix, idx);
wrap.appendChild(refresh);
wrap.style.display = 'block';
}
function makePubLookup(searchId, resultsId, hiddenId, stateObj, key) {
const inp = document.getElementById(searchId);
const res = document.getElementById(resultsId);
let t, controller;
inp.addEventListener('input', () => {
clearTimeout(t);
stateObj[key] = null;
document.getElementById(hiddenId).value = '';
const q = inp.value.trim();
if (q.length < 2) { res.classList.remove('open'); return; }
t = setTimeout(async () => {
controller?.abort();
controller = new AbortController();
let rows;
try {
rows = await get(`/publisher?publisher_name=ilike.*${encodeURIComponent(q)}*&select=publisher_id,publisher_name&limit=10&order=publisher_name`, controller.signal);
} catch (err) {
if (err.name === 'AbortError') return;
throw err;
}
res.innerHTML = '';
rows.forEach(p => {
const d = document.createElement('div');
d.className = 'lookup-item';
d.textContent = p.publisher_name;
d.onclick = () => {
inp.value = p.publisher_name;
stateObj[key] = p.publisher_id;
document.getElementById(hiddenId).value = p.publisher_id;
res.classList.remove('open');
};
res.appendChild(d);
});
const add = document.createElement('div');
add.className = 'lookup-item add-new';
add.textContent = `+ Bruk "${q}" (legges til automatisk)`;
add.onclick = () => { inp.value = q; stateObj[key] = null; res.classList.remove('open'); };
res.appendChild(add);
res.classList.add('open');
}, 250);
});
document.addEventListener('click', e => {
if (!inp.contains(e.target) && !res.contains(e.target)) res.classList.remove('open');
});
}
// Shared publisher resolution used by both Ny innføring and Rediger: returns an existing
// publisher_id (case/whitespace-insensitive name match) or creates a new publisher row.
async function resolveOrCreatePublisher(name, existingId) {
if (existingId) return existingId;
const trimmed = (name || '').trim();
if (!trimmed) return null;
const existing = await get(`/publisher?publisher_name=ilike.${encodeURIComponent(trimmed)}&select=publisher_id`);
if (existing.length > 0) return existing[0].publisher_id;
const np = await post('publisher', { publisher_name: trimmed });
return np.publisher_id;
}
// ── Add person modal ──────────────────────────────────────────────────────────
let modalTarget = null;
function openPersonModal(prefill, tagsId, list) {
modalTarget = { tagsId, list };
['m_firstName','m_lastName','m_born','m_died','m_bioUrl','m_nationality'].forEach(id => document.getElementById(id).value = '');
document.getElementById('m_gender').value = '';
document.getElementById('m_bioUrlVerified').checked = false;
document.getElementById('m_bioLink').style.display = 'none';
const parts = prefill.trim().split(/\s+/);
if (parts.length >= 2) {
document.getElementById('m_firstName').value = parts.slice(0,-1).join(' ');
document.getElementById('m_lastName').value = parts[parts.length-1];
} else {
document.getElementById('m_lastName').value = prefill;
}
document.getElementById('addPersonModal').classList.add('open');
}
function closePersonModal() {
document.getElementById('addPersonModal').classList.remove('open');
modalTarget = null;
}
async function saveNewPerson() {
const last = document.getElementById('m_lastName').value.trim();
const first = document.getElementById('m_firstName').value.trim();
if (!last) { alert('Etternavn er påkrevd.'); return; }
// Duplicate check — query by last name, then look for name overlap
const existing = await get(`/person?last_name=ilike.${encodeURIComponent(last)}&select=person_id,first_name,last_name,born,died,pseudonym`);
const matches = existing.filter(p => personNameOverlap(first, last, p));
if (matches.length) {
const lines = matches.map(p => {
const fn = ((p.first_name || '') + ' ' + p.last_name).trim();
const yrs = p.born ? ` (${p.born}${p.died ? '–'+p.died : ''})` : '';
return `• ${fn}${yrs} [ID ${p.person_id}]`;
}).join('<br>');
// Show inline warning and block save unless checkbox ticked
let warn = document.getElementById('m_dupWarn');
if (!warn) {
warn = document.createElement('div');
warn.id = 'm_dupWarn';
warn.style.cssText = 'margin-top:0.75rem;background:#fff8e8;border:1px solid #e8c84a;border-radius:4px;padding:0.6rem 0.85rem;font-size:0.85rem;color:#5a4a00';
document.querySelector('#addPersonModal .modal-actions').before(warn);
}
warn.innerHTML = '<div style="font-weight:600;margin-bottom:0.35rem">⚠ Person med dette navnet finnes allerede:</div>'
+ '<div style="margin-bottom:0.5rem">' + lines + '</div>'
+ '<div style="display:flex;align-items:center;gap:0.5rem">'
+ '<input type="checkbox" id="m_notDuplicate" style="width:auto;margin:0;accent-color:var(--accent)">'
+ '<label for="m_notDuplicate" style="margin:0;text-transform:none;font-size:0.85rem;letter-spacing:0;font-weight:500;color:#5a4a00;cursor:pointer">Dette er ikke et duplikat — opprett likevel</label>'
+ '</div>';
warn.style.display = 'block';
if (!document.getElementById('m_notDuplicate')?.checked) return;
}
// Hide warning if shown from a previous attempt
const prevWarn = document.getElementById('m_dupWarn');
if (prevWarn) prevWarn.style.display = 'none';
const gender = document.getElementById('m_gender').value;
const nationality = document.getElementById('m_nationality').value.trim() || null;
const birth_country = document.getElementById('m_birth_country').value.trim() || null;
const birth_country_primary = document.getElementById('m_birth_country_primary').checked;
const data = {
first_name: first || null,
last_name: last,
born: parseInt(document.getElementById('m_born').value) || null,
died: parseInt(document.getElementById('m_died').value) || null,
nationality,
birth_country,
birth_country_primary,
gender: gender || null,
bio_url: document.getElementById('m_bioUrl').value.trim() || null,
bio_url_verified: document.getElementById('m_bioUrlVerified').checked || false,
};
try {
const p = await post('person', data);
const name = [data.first_name, data.last_name].filter(Boolean).join(' ');
if (modalTarget) addTag(p.person_id, name, modalTarget.tagsId, modalTarget.list);
closePersonModal();
} catch(e) { alert('Feil: ' + e.message); }
}
// Helper: returns true if two persons likely have overlapping names.
// Handles exact match, missing first name, and initial match (e.g. "R." vs "Rudolf").
function personNameOverlap(newFirst, newLast, existing) {
if (existing.last_name.toLowerCase() !== newLast.toLowerCase()) return false;
const ef = (existing.first_name || '').toLowerCase().trim();
const nf = newFirst.toLowerCase().trim();
if (!ef || !nf) return true; // one side has no first name
if (ef === nf) return true; // exact match
// Initial match: "r." matches "rudolf", or "rudolf" matches "r."
const efInit = ef.replace(/\.$/, '');
const nfInit = nf.replace(/\.$/, '');
if (efInit.length === 1 && nfInit.startsWith(efInit)) return true;
if (nfInit.length === 1 && efInit.startsWith(nfInit)) return true;
return false;
}
// ── Source cache ──────────────────────────────────────────────────────────────
// name -> id map for source lookup
const sourceMap = new Map();
async function loadSources() {
const rows = await get('/source?select=source_id,source_name&order=source_name');
const dl = document.getElementById('sourceList');
rows.forEach(r => { if (r.source_name) sourceMap.set(r.source_name.trim(), r.source_id); });
dl.innerHTML = [...sourceMap.keys()].sort().map(s => `<option value="${s}">`).join('');
}
function getSourceId(name) {
const match = findSourceMatch(name);
return match ? sourceMap.get(match) : null;
}
// Case/whitespace-insensitive lookup: returns the actual stored key if a case-insensitive
// match exists in sourceMap, or null if this source name is genuinely new.
function findSourceMatch(name) {
const trimmed = name.trim();
if (sourceMap.has(trimmed)) return trimmed;
const lower = trimmed.toLowerCase();
for (const key of sourceMap.keys()) {
if (key.toLowerCase() === lower) return key;
}
return null;
}
function validateSource(inputId) {
const val = document.getElementById(inputId).value.trim();
if (!val) return true; // empty is fine
if (sourceMap.has(val)) return true;
return confirm(`"${val}" er ikke en kjent kilde.\n\nKlikk OK for å lagre likevel, eller Avbryt for å velge en eksisterende kilde.`);
}
loadSources();
// ── NEW ENTRY ─────────────────────────────────────────────────────────────────
const nContributors = [];
const nPubState = {};
const nRowIdxRef = { value: 0 };
function nAddContributorRow(person, role, creditedAs, translatesPersonId) { addContributorRow('n', nContributors, nRowIdxRef, person, role, creditedAs||'', translatesPersonId); }
const ROLES = ['Composer','Lyricist','Arranger','Illustrator','Translator'];
const ROLE_NO = { Composer:'Komponist', Lyricist:'Tekstforfatter', Arranger:'Arrangør', Illustrator:'Illustratør', Translator:'Oversetter' };
// ── Shared contributor row factory ────────────────────────────────────────────
function addContributorRow(prefix, contributors, rowIdxRef, person, role, creditedAs, translatesPersonId) {
role = role || 'Composer';
const idx = rowIdxRef.value++;
const name = person ? [person.first_name||'', person.last_name||''].filter(Boolean).join(' ') : null;
const list = document.getElementById(`${prefix}_contributorList`);
const div = document.createElement('div');
div.id = `${prefix}_crow_${idx}`;
div.style.cssText = 'display:flex;align-items:flex-start;gap:0.5rem;margin-bottom:0.5rem;padding:0.5rem;background:var(--warm);border-radius:5px';
div.innerHTML = `
<div style="flex:1">
<select id="${prefix}_crole_${idx}" style="width:100%;margin-bottom:0.3rem;padding:0.3rem 0.5rem;border:1px solid var(--border);border-radius:4px;font-size:0.85rem;font-family:inherit">
${ROLES.map(r => `<option value="${r}"${r===role?' selected':''}>${ROLE_NO[r]}</option>`).join('')}
</select>
<div style="position:relative">
<input type="text" id="${prefix}_csearch_${idx}" placeholder="Søk etter person…" autocomplete="off"
style="width:100%;padding:0.4rem 0.6rem;border:1px solid var(--border);border-radius:4px;font-size:0.85rem">
<div id="${prefix}_cresults_${idx}" class="lookup-results"></div>
</div>
<div id="${prefix}_cselected_${idx}" style="font-size:0.82rem;color:var(--accent);margin-top:0.2rem;font-weight:500">${escapeHtml(name||'')}</div>
<div id="${prefix}_ccredited_wrap_${idx}" style="margin-top:0.3rem"></div>
<div id="${prefix}_ctranslates_wrap_${idx}" style="display:none;margin-top:0.3rem"></div>
</div>
<button type="button" id="${prefix}_cremove_${idx}" style="background:none;border:none;cursor:pointer;font-size:1.1rem;color:var(--muted);padding:0.2rem;line-height:1;margin-top:1.8rem">✕</button>`;
list.appendChild(div);
contributors.push({ idx, person_id: person?.person_id||null, name, credited_as: creditedAs||'', translates_person_id: translatesPersonId||null });
if (person) {
renderCreditedAsField(prefix, idx, person.pseudonym||'', creditedAs||'');
}
// Role select: show/hide the "translates" picker
document.getElementById(`${prefix}_crole_${idx}`).addEventListener('change', () => updateTranslatesField(prefix, idx));
updateTranslatesField(prefix, idx);
// Remove button
document.getElementById(`${prefix}_cremove_${idx}`).addEventListener('click', () => {
document.getElementById(`${prefix}_crow_${idx}`)?.remove();
const i = contributors.findIndex(c => c.idx === idx);
if (i !== -1) contributors.splice(i, 1);
});
// Search input
let searchTimer, searchController;
document.getElementById(`${prefix}_csearch_${idx}`).addEventListener('input', function() {
clearTimeout(searchTimer);
const val = this.value;
const res = document.getElementById(`${prefix}_cresults_${idx}`);
if (val.length < 2) { res.innerHTML = ''; res.style.display = 'none'; return; }
searchTimer = setTimeout(async () => {
searchController?.abort();
searchController = new AbortController();
let rows;
try {
rows = await get(`/person?last_name=ilike.${encodeURIComponent(val)}*&select=person_id,first_name,last_name,born,died&order=last_name.asc&limit=10`, searchController.signal);
} catch (err) {
if (err.name === 'AbortError') return;
throw err;
}
if (!rows.length) { res.innerHTML = ''; res.style.display = 'none'; return; }
res.style.display = 'block';
res.innerHTML = rows.map(p => {
const pname = [p.first_name,p.last_name].filter(Boolean).join(' ');
const dates = p.born||p.died ? ` (${[p.born,p.died].filter(Boolean).join('–')})` : '';
return `<div class="lookup-item" data-pid="${p.person_id}" data-name="${escapeHtml(pname)}"><span class="lookup-name">${escapeHtml(pname)}</span><span class="lookup-meta">${escapeHtml(dates)}</span></div>`;
}).join('');
// Wire result clicks
res.querySelectorAll('.lookup-item').forEach(item => {
item.addEventListener('click', async () => {
const personId = parseInt(item.dataset.pid);
const pname = item.dataset.name;
const c = contributors.find(x => x.idx === idx);
if (c) { c.person_id = personId; c.name = pname; c.credited_as = ''; }
document.getElementById(`${prefix}_csearch_${idx}`).value = '';
res.style.display = 'none';
document.getElementById(`${prefix}_cselected_${idx}`).textContent = pname;
try {
const pr = await get(`/person?person_id=eq.${personId}&select=pseudonym`);
renderCreditedAsField(prefix, idx, pr[0]?.pseudonym||'', '');
} catch(e) { renderCreditedAsField(prefix, idx, '', ''); }
});
});
}, 250);
});
}
// Add default composer row on load
nAddContributorRow(null, 'Composer');
makePubLookup('n_publisherSearch', 'n_publisherResults', 'n_publisherId', nPubState, 'id');
function showMsg(tabId, text, type) {
const el = document.getElementById(tabId);
el.textContent = text;
el.className = 'msg' + (type ? ' ' + type : '');
}
document.getElementById('newForm').addEventListener('submit', async e => {
e.preventDefault();
const msgEl = document.getElementById('newMsg');
const btn = document.getElementById('newSubmitBtn');
if (btn.disabled) return; // already mid-submit — ignore extra clicks entirely
btn.disabled = true; // disabled synchronously, before any await, so a rapid second click can't slip in
const resetBtn = () => { btn.disabled = false; btn.textContent = 'Lagre innføring'; };
try {
// Duplicate-title gate
const warnVisible = document.getElementById('n_duplicateWarn').style.display !== 'none';
if (warnVisible && !document.getElementById('n_notDuplicate').checked) {
showMsg('newMsg', '⚠ Mulige duplikater funnet — bekreft at dette ikke er et duplikat før du lagrer.', 'error');
msgEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
resetBtn();
return;
}
showMsg('newMsg', '', '');
// 1. Freeze every field value up front, before any async gaps or confirmations,
// so nothing can change out from under us while a warning is pending.
const data = {
title: document.getElementById('n_title').value.trim(),
year: document.getElementById('n_year').value.trim(),
cat: document.getElementById('n_category').value,
notes: document.getElementById('n_notes').value.trim(),
dedication: document.getElementById('n_dedication').value.trim(),
msLink: document.getElementById('n_msLink').value.trim(),
opus: document.getElementById('n_opus').value.trim(),
toInvestigate: document.getElementById('n_toInvestigate').checked,
underArbeid: document.getElementById('n_underArbeid').checked,
uploadedToday: document.getElementById('n_uploadedToday').checked,
plate: document.getElementById('n_plateNumber').value.trim(),
publisherName: document.getElementById('n_publisherSearch').value.trim(),
publisherId: nPubState.id,
yearPublished: document.getElementById('n_yearPublished').value.trim(),
pdfUrl: document.getElementById('n_pdfUrl').value.trim(),
mp3Url: document.getElementById('n_mp3Url').value.trim(),
source: document.getElementById('n_source').value.trim(),
hasFrontpage: document.getElementById('n_hasFrontpage').checked,
aiFrontpage: document.getElementById('n_aiFrontpage').checked,
contributors: nContributors.map(c => ({
...c,
role: document.getElementById(`n_crole_${c.idx}`)?.value || 'Composer',
})),
};
if (!data.title) { showMsg('newMsg', 'Feil: Tittel er påkrevd.', 'error'); msgEl.scrollIntoView({behavior:'smooth',block:'center'}); resetBtn(); return; }
if (!data.cat) { showMsg('newMsg', 'Feil: Kategori er påkrevd.', 'error'); msgEl.scrollIntoView({behavior:'smooth',block:'center'}); resetBtn(); return; }
// 2. Contributor completeness — a name typed but never selected from the list
// would otherwise be silently dropped.
for (const c of data.contributors) {
const searchVal = document.getElementById(`n_csearch_${c.idx}`)?.value.trim();
if (searchVal && !c.person_id) {
showMsg('newMsg', `Feil: En bidragsyterrad har et navn skrevet inn ("${searchVal}"), men ingen person er valgt fra listen. Velg en person fra søkeresultatene, eller tøm feltet.`, 'error');
msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
resetBtn();
return;
}
}
// 3. Source validation — decide now whether an unknown source will be created,
// rather than silently discarding it later.
let sourceIsNew = false;
if (data.source && !findSourceMatch(data.source)) {
const proceed = confirm(`"${data.source}" er ikke en kjent kilde.\n\nKlikk OK for å opprette den som en ny kilde og lagre, eller Avbryt for å velge en eksisterende kilde.`);
if (!proceed) { showMsg('newMsg', 'Lagring avbrutt — velg en eksisterende kilde eller bekreft oppretting av ny.', 'error'); resetBtn(); return; }
sourceIsNew = true;
}
// 4. Duplicate plate-number check — scoped to the same publisher, since different
// publishers can legitimately reuse the same plate number. Runs BEFORE any
// database write, so "Avbryt" truly means nothing was saved.
if (data.plate) {
// Read-only publisher resolution just for this check — does NOT create a new
// publisher row. If the publisher is new or unspecified, nothing existing could
// share both that publisher and this plate number, so the check is skipped.
let checkPubId = data.publisherId;
if (!checkPubId && data.publisherName) {
const pubLookup = await get(`/publisher?publisher_name=ilike.${encodeURIComponent(data.publisherName)}&select=publisher_id`);
checkPubId = pubLookup[0]?.publisher_id || null;
}
if (checkPubId) {
const dupScores = await get(`/score?plate_number=eq.${encodeURIComponent(data.plate)}&publisher_id=eq.${checkPubId}&select=score_id,composition_id,plate_number`);
if (dupScores.length) {
const dupIds = dupScores.map(s => s.composition_id).join(',');
const dupComps = await get(`/composition?composition_id=in.(${dupIds})&select=composition_id,title`);
const titleMap = Object.fromEntries(dupComps.map(c => [c.composition_id, c.title]));
const dupLines = dupScores.map(s => `• "${escapeHtml(titleMap[s.composition_id] || '?')}" (score_id=${s.score_id}, plate=${escapeHtml(s.plate_number)})`).join('<br>');
msgEl.innerHTML = `<div style="background:#fff8e8;border:1px solid #e8c84a;border-radius:4px;padding:0.6rem 0.85rem;font-size:0.85rem;color:#5a4a00">
<div style="font-weight:600;margin-bottom:0.35rem">⚠ Denne utgiveren har allerede et noteeksemplar med platenummer <em>${escapeHtml(data.plate)}</em> (ingenting er lagret ennå):</div>
<div style="margin-bottom:0.5rem">${dupLines}</div>
<div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-top:0.4rem">
<button id="scoreDupConfirm" class="btn" style="font-size:0.8rem;padding:0.25rem 0.6rem;background:#c8a000;color:#fff;border:none;border-radius:4px;cursor:pointer">Lagre likevel</button>
<button id="scoreDupCancel" class="btn btn-secondary" style="font-size:0.8rem;padding:0.25rem 0.6rem">Avbryt</button>
</div>
</div>`;
msgEl.className = 'msg';
msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Button stays disabled while this choice is pending, so a stray click elsewhere can't start a second save.
document.getElementById('scoreDupCancel').onclick = () => { msgEl.innerHTML = ''; resetBtn(); };
document.getElementById('scoreDupConfirm').onclick = () => { msgEl.innerHTML = ''; performNewEntrySave(data, sourceIsNew); };
return;
}
}
}
await performNewEntrySave(data, sourceIsNew);
} catch (err) {
console.error('Ny innføring — uventet feil før lagring:', err);
showMsg('newMsg', 'Uventet feil: ' + err.message, 'error');
msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
resetBtn();
}
});
// Performs the actual writes for a new entry, after every validation gate above
// has already passed. If the score insert fails partway through, the composition
// and its contributor rows are rolled back rather than left orphaned.
async function performNewEntrySave(data, sourceIsNew) {
const btn = document.getElementById('newSubmitBtn');
const msgEl = document.getElementById('newMsg');
btn.disabled = true; btn.innerHTML = '<span class="spinner"></span>Lagrer…';
let compId = null;
try {
// Publisher (create if new)
const pubId = await resolveOrCreatePublisher(data.publisherName, data.publisherId);
// Source (create if new & confirmed above) — source_id is manually assigned, not autoincrement
let sourceId = null;
if (data.source) {
sourceId = sourceIsNew ? await ensureSourceId(data.source) : getSourceId(data.source);
}
const pubDomain = data.cat === 'pd' ? 'Yes' : 'No';
const today = new Date().toISOString().slice(0,10);
const comp = await post('composition', {
title: data.title, public_domain: pubDomain, year_composed: data.year || null,
opus_number: data.opus || null, composition_notes: data.notes || null,
musescore_link: data.msLink || null, dedication: data.dedication || null,
to_investigate: data.toInvestigate || null, under_arbeid: data.underArbeid || null,
musescore_uploaded: data.uploadedToday ? today : null,
});
compId = comp.composition_id;
if (!compId) throw new Error('Feil ved lagring av komposisjon.');
for (const c of data.contributors) {
if (!c.person_id) continue;
await post('composition_person', { composition_id: compId, person_id: c.person_id, role: c.role, credited_as: c.credited_as || null, translates_person_id: c.role === 'Translator' ? (c.translates_person_id || null) : null });
}
await post('score', {
composition_id: compId, plate_number: data.plate || null, publisher_id: pubId || null,
year_published: data.yearPublished || null, pdf_url: data.pdfUrl || null, mp3_url: data.mp3Url || null,
source_id: sourceId || null, has_frontpage: data.hasFrontpage, ai_frontpage: data.aiFrontpage,
});
showMsg('newMsg', `✓ "${data.title}" er lagret (id=${compId})`, 'success');
msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
resetNewForm();
} catch(err) {
// Best-effort rollback so a failed score insert never leaves a half-saved entry behind.
let rolledBack = false;
if (compId) {
try {
await del('composition_person', `composition_id=eq.${compId}`);
await del('composition', `composition_id=eq.${compId}`);
rolledBack = true;
} catch (cleanupErr) {
console.error('Rollback failed:', cleanupErr);
}
}
showMsg('newMsg', `Feil: ${err.message}${rolledBack ? ' — hele innføringen ble rullet tilbake, ingenting ble lagret.' : (compId ? ' — ADVARSEL: opprydding feilet også, sjekk komposisjon id=' + compId + ' manuelt.' : '')}`, 'error');
msgEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
btn.disabled = false; btn.textContent = 'Lagre innføring';
}
// Returns the source_id for a name, creating a new source row (with the next
// manually-assigned id, since source_id is not autoincrement) if it doesn't exist yet.
async function ensureSourceId(name) {
const trimmed = name.trim();
if (!trimmed) return null;
const match = findSourceMatch(trimmed);
if (match) return sourceMap.get(match);
// source_id is manually assigned (not autoincrement), so two near-simultaneous creates
// could compute the same "next" id. Retry once against a fresh max if that happens.
// NOTE: the only real fix is making source_id an identity/sequence column in Postgres —
// this is a mitigation, not a guarantee, for the current schema.
for (let attempt = 0; attempt < 2; attempt++) {
const existing = await get(`/source?select=source_id&order=source_id.desc&limit=1`);
const nextId = (existing[0]?.source_id || 0) + 1;
try {
await post('source', { source_id: nextId, source_name: trimmed });
sourceMap.set(trimmed, nextId);
const dl = document.getElementById('sourceList');
if (dl) dl.innerHTML = [...sourceMap.keys()].sort().map(s => `<option value="${s}">`).join('');
return nextId;
} catch (err) {
const isConflict = /409|23505|duplicate/i.test(err.message);
if (isConflict && attempt === 0) continue; // someone else took nextId — retry once
throw err;
}
}
}
function resetNewForm() {
document.getElementById('newForm').reset();
document.getElementById('n_toInvestigate').checked = false;
document.getElementById('n_underArbeid').checked = false;
nPubState.id = null;
nContributors.length = 0;
nRowIdxRef.value = 0;
document.getElementById('n_contributorList').innerHTML = '';
nAddContributorRow(null, 'Composer');
const pubSearch = document.getElementById('n_publisherSearch');
if (pubSearch) pubSearch.value = '';
hideDuplicateWarn();
}
// ── Duplicate title check ─────────────────────────────────────────────────────
function hideDuplicateWarn() {
document.getElementById('n_duplicateWarn').style.display = 'none';
document.getElementById('n_duplicateList').innerHTML = '';
document.getElementById('n_notDuplicate').checked = false;
}
let dupCheckTimeout, dupCheckController;
document.getElementById('n_title').addEventListener('input', () => {
clearTimeout(dupCheckTimeout);
hideDuplicateWarn();
const q = document.getElementById('n_title').value.trim();
if (q.length < 2) return;
dupCheckTimeout = setTimeout(async () => {
dupCheckController?.abort();
dupCheckController = new AbortController();
let results;
try {
results = await get(`/composition?title=ilike.*${encodeURIComponent(q)}*&select=composition_id,title,year_composed,public_domain&limit=8&order=title`, dupCheckController.signal);
} catch (err) {
if (err.name === 'AbortError') return;
throw err;
}
if (!results.length) return;
const list = document.getElementById('n_duplicateList');
list.innerHTML = results.map(c => {
const year = c.year_composed ? ` (${escapeHtml(c.year_composed)})` : '';
const pd = c.public_domain === 'Yes' ? ' · PD' : '';
return `<div style="padding:0.2rem 0;border-bottom:1px solid #e8d88a;display:flex;align-items:center;justify-content:space-between;gap:0.75rem">
<span>${escapeHtml(c.title)}${year}${pd}</span>
<a href="#" onclick="event.preventDefault();switchTab('edit');loadEditForm(${c.composition_id})"
style="font-size:0.78rem;white-space:nowrap;color:var(--accent);text-decoration:underline">Åpne →</a>
</div>`;
}).join('');
document.getElementById('n_duplicateWarn').style.display = 'block';
}, 350);
});
// ── EDIT TAB ──────────────────────────────────────────────────────────────────
const eContributors = [];
const ePubState = {};
// ── e (Edit tab) ─────────────────────────────────────────────────────────────
const eRowIdxRef = { value: 0 };
function eAddContributorRow(person, role, creditedAs, translatesPersonId) { addContributorRow('e', eContributors, eRowIdxRef, person, role, creditedAs, translatesPersonId); }
makePubLookup('e_publisherSearch', 'e_publisherResults', 'e_publisherId', ePubState, 'id');
let editSearchTimeout;
function setSearchMode(mode) {
document.getElementById('editSearchMode').value = mode;
document.getElementById('editSearch').placeholder = mode === 'composer' ? 'Søk på komponist…' : 'Søk på tittel…';
document.getElementById('editSearch').value = '';
document.getElementById('editSearchResults').innerHTML = '';
document.getElementById('searchModeComposer').style.fontWeight = mode === 'composer' ? '700' : '';
document.getElementById('searchModeTitle').style.fontWeight = mode === 'title' ? '700' : '';
}
let editSearchToken = 0;
document.getElementById('editSearch').addEventListener('input', () => {
clearTimeout(editSearchTimeout);
const q = document.getElementById('editSearch').value.trim();
document.getElementById('editSearchResults').innerHTML = '';
editSearchToken++; // invalidate any in-flight search from a previous keystroke
if (q.length < 2) return;
const myToken = editSearchToken;
editSearchTimeout = setTimeout(() => searchCompositions(q, myToken), 300);
});
async function searchCompositions(q, myToken) {
const mode = document.getElementById('editSearchMode').value;
const container = document.getElementById('editSearchResults');
container.innerHTML = '<div style="color:var(--muted);font-size:.85rem;padding:.5rem 0">Søker…</div>';
let results = [];
if (mode === 'title') {
results = await get(`/composition?title=ilike.*${encodeURIComponent(q)}*&select=composition_id,title,year_composed,public_domain,approved,musescore_link,to_investigate,under_arbeid&limit=30&order=title`);
} else {
// Composer mode — find persons by last name, then their compositions
const persons = await get(`/person?last_name=ilike.${encodeURIComponent(q)}*&select=person_id,first_name,last_name&limit=10&order=last_name`);
for (const p of persons) {
const cc = await get(`/composition_person?person_id=eq.${p.person_id}&role=eq.Composer&select=composition_id`);
if (!cc.length) continue;
const ids = cc.map(r => r.composition_id).join(',');
const comps = await get(`/composition?composition_id=in.(${ids})&select=composition_id,title,year_composed,public_domain,approved,musescore_link,to_investigate,under_arbeid`);
comps.forEach(c => {
if (!results.find(r => r.composition_id === c.composition_id)) {
c._composer = [p.first_name, p.last_name].filter(Boolean).join(' ');
c._composer_id = p.person_id;
results.push(c);
}
});
}
results.sort((a,b) => a.title.localeCompare(b.title));
}
// A newer search has started since this one began — drop these stale results
if (myToken !== editSearchToken) return;
if (!results.length) {
container.innerHTML = '<div style="color:var(--muted);font-size:.85rem;padding:.5rem 0">Ingen treff.</div>';
return;
}
container.innerHTML = '';
results.slice(0, 30).forEach(c => {
const d = document.createElement('div');
d.className = 'result-row';
const approvedBadge = c.approved ? ' <span class="approved-badge">✓</span>' : '';
const investigateBadge = c.to_investigate ? ' <span style="font-size:0.75rem;background:#fff3cd;border:1px solid #f0c040;border-radius:2px;padding:0.1rem 0.4rem;color:#7a5c00;font-weight:500;vertical-align:middle">🔍 Undersøke</span>' : '';
const underArbeidBadge = c.under_arbeid ? ' <span style="font-size:0.75rem;background:#fff0d6;border:1px solid #e8a000;border-radius:2px;padding:0.1rem 0.4rem;color:#7a4500;font-weight:500;vertical-align:middle">⚙ Under arbeid</span>' : '';