Repository navigation
Expand file tree
/
Copy pathpublications.html
More file actions
1486 lines (1382 loc) · 60.9 KB
/
Copy pathpublications.html
File metadata and controls
1486 lines (1382 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Publications – Cyril Pernet</title>
<style>
/* ── Base ─────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; }
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
font-size: 1rem;
line-height: 1.65;
color: #222;
background: #fff;
}
a { color: #2b6cb0; }
h1 { margin: 0 0 0.25rem; font-size: 1.9rem; letter-spacing: -0.03em; }
/* ── Layout ───────────────────────────────────────────── */
.container { max-width: 1100px; margin: 0 auto; padding: 0 1.5rem; }
header.page-header {
border-bottom: 1px solid #e8e8e8;
padding: 1.5rem 0 1rem;
margin-bottom: 1.5rem;
}
header.page-header p { color: #555; margin: 0.25rem 0 0; font-size: 0.92rem; }
/* ── Search / controls bar ────────────────────────────── */
.controls {
display: flex;
flex-wrap: wrap;
gap: 0.6rem 1rem;
align-items: center;
margin-bottom: 1.25rem;
}
.controls label { font-size: 0.85rem; color: #555; }
.controls input[type="text"] {
padding: 0.35rem 0.65rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 0.9rem;
min-width: 180px;
}
.controls select {
padding: 0.35rem 0.55rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 0.9rem;
background: #fff;
}
.btn {
padding: 0.38rem 0.9rem;
border: none;
border-radius: 4px;
font-size: 0.88rem;
cursor: pointer;
transition: background 0.15s;
}
.btn-primary { background: #2b6cb0; color: #fff; }
.btn-primary:hover { background: #2558a3; }
.btn-secondary { background: #e2e8f0; color: #2d3748; }
.btn-secondary:hover { background: #cbd5e0; }
.btn-danger { background: #fc8181; color: #fff; font-size: 0.8rem; padding: 0.2rem 0.55rem; }
.btn-danger:hover { background: #f56565; }
.btn-edit { background: #f6e05e; color: #2d3748; font-size: 0.8rem; padding: 0.2rem 0.55rem; }
.btn-edit:hover { background: #ecc94b; }
/* ── Status / loader ──────────────────────────────────── */
#status {
font-size: 0.9rem; color: #555; margin-bottom: 0.75rem;
min-height: 1.4rem;
}
.spinner {
display: inline-block; width: 14px; height: 14px;
border: 2px solid #ccc; border-top-color: #2b6cb0;
border-radius: 50%; animation: spin 0.7s linear infinite;
vertical-align: middle; margin-right: 6px;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ── Stats strip ──────────────────────────────────────── */
#stats-bar {
display: flex; flex-wrap: wrap; gap: 1rem;
margin-bottom: 1rem; font-size: 0.88rem; color: #4a5568;
}
#stats-bar span strong { color: #1a202c; }
/* ── Filter chips ─────────────────────────────────────── */
.filter-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-bottom: 1rem; }
.chip {
padding: 0.2rem 0.65rem; border-radius: 99px; font-size: 0.8rem;
cursor: pointer; border: 1px solid #ccc; background: #f7fafc; color: #2d3748;
transition: background 0.12s, border-color 0.12s;
}
.chip.active { background: #2b6cb0; color: #fff; border-color: #2b6cb0; }
.chip:hover:not(.active) { background: #ebf4ff; border-color: #90cdf4; }
/* ── Table ────────────────────────────────────────────── */
.table-wrap { overflow-x: auto; }
table {
width: 100%;
border-collapse: collapse;
font-size: 0.88rem;
}
thead th {
background: #f7fafc;
border-bottom: 2px solid #e2e8f0;
padding: 0.55rem 0.65rem;
text-align: left;
font-weight: 600;
white-space: nowrap;
cursor: pointer;
user-select: none;
}
thead th:hover { background: #ebf4ff; }
thead th .sort-icon { font-size: 0.7rem; margin-left: 3px; opacity: 0.5; }
thead th.sorted .sort-icon { opacity: 1; color: #2b6cb0; }
tbody tr { border-bottom: 1px solid #edf2f7; }
tbody tr:hover { background: #f7fafc; }
tbody td { padding: 0.5rem 0.65rem; vertical-align: top; }
.td-num { width: 2.5rem; text-align: center; color: #718096; }
.td-topic { width: 7rem; }
.td-year { width: 3.5rem; text-align: center; }
.td-title { min-width: 220px; }
.td-journal { min-width: 120px; color: #4a5568; }
.td-authors { min-width: 150px; }
.td-actions { width: 6rem; white-space: nowrap; }
.topic-badge {
display: inline-block; padding: 0.1rem 0.5rem; border-radius: 99px;
font-size: 0.75rem; font-weight: 600; text-transform: uppercase;
letter-spacing: 0.04em;
cursor: pointer;
}
.topic-badge:hover { opacity: 0.78; }
/* inline topic picker shown when badge is clicked */
.topic-picker {
font-size: 0.82rem; border: 1px solid #90cdf4; border-radius: 4px;
padding: 0.15rem 0.3rem; background: #fff; cursor: pointer;
outline: none;
}
.topic-method { background: #7fc97f; color: #1a4731; }
.topic-stats { background: #beaed4; color: #44337a; }
.topic-data { background: #fdc086; color: #7b341e; }
.topic-clinical { background: #ffff99; color: #744210; }
.topic-cog-neuro { background: #386cb0; color: #fff; }
.topic-book { background: #f0027f; color: #fff; }
.topic-other { background: #bf5b17; color: #fff; }
/* ── Export dropdown ─────────────────────────────────── */
.export-wrap { position: relative; align-self: flex-end; }
.export-menu {
display: none; position: absolute; top: calc(100% + 4px); left: 0;
background: #fff; border: 1px solid #e2e8f0; border-radius: 6px;
box-shadow: 0 8px 24px rgba(0,0,0,0.12); z-index: 50;
min-width: 170px; overflow: hidden;
}
.export-menu.open { display: block; }
.export-menu button {
display: block; width: 100%; text-align: left;
padding: 0.5rem 1rem; border: none; background: none;
font-size: 0.88rem; cursor: pointer; color: #2d3748;
}
.export-menu button:hover { background: #ebf4ff; }
.export-menu hr { margin: 0.25rem 0; border: none; border-top: 1px solid #e2e8f0; }
/* ── Print / PDF styles ──────────────────────────────── */
@media print {
.controls, .filter-chips, #status, #stats-bar,
.td-actions, header.page-header p, footer { display: none !important; }
body { font-size: 10pt; color: #000; }
h1 { font-size: 16pt; margin-bottom: 0.5rem; }
table { font-size: 9pt; border-collapse: collapse; width: 100%; }
thead th { background: #f0f0f0 !important; border-bottom: 1.5pt solid #000; }
tbody tr { border-bottom: 0.5pt solid #ccc; }
tbody td { padding: 3pt 5pt; }
.topic-badge { border: 0.5pt solid #888; background: none !important;
color: #000 !important; padding: 0 3pt; }
a { color: #000; text-decoration: none; }
}
/* ── Add / edit modal ─────────────────────────────────── */
.modal-overlay {
display: none; position: fixed; inset: 0;
background: rgba(0,0,0,0.45); z-index: 100;
align-items: center; justify-content: center;
}
.modal-overlay.open { display: flex; }
.modal {
background: #fff; border-radius: 8px; padding: 1.5rem;
width: min(95vw, 580px); max-height: 90vh; overflow-y: auto;
box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}
.modal h2 { margin: 0 0 1rem; font-size: 1.15rem; }
.form-grid {
display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem 1rem;
}
.form-grid .full { grid-column: 1 / -1; }
.form-group { display: flex; flex-direction: column; gap: 0.25rem; }
.form-group label { font-size: 0.82rem; font-weight: 600; color: #4a5568; }
.form-group input, .form-group select, .form-group textarea {
padding: 0.38rem 0.6rem; border: 1px solid #cbd5e0;
border-radius: 4px; font-size: 0.9rem; font-family: inherit;
}
.form-group textarea { resize: vertical; min-height: 60px; }
.modal-actions { display: flex; gap: 0.5rem; justify-content: flex-end; margin-top: 1rem; }
/* ── Footer ───────────────────────────────────────────── */
footer {
margin-top: 3rem; padding: 1rem 0;
border-top: 1px solid #e8e8e8;
font-size: 0.82rem; color: #718096; text-align: center;
}
</style>
</head>
<body>
<div class="container">
<header class="page-header">
<h1>Publications</h1>
<p>
Load your saved list, then fetch updates from <strong>PubMed</strong> and <strong>Semantic Scholar</strong>.
You can filter, sort, and manually add, edit, or remove entries.
After editing, <strong>Export → JSON</strong> and place <code>publications.json</code> next to this page — it will be loaded automatically on the next visit.
</p>
</header>
<!-- ── Author search ──────────────────────────────────── -->
<div class="controls">
<div>
<label for="author-input">Author name</label><br>
<input type="text" id="author-input" value="Cyril Pernet" placeholder="First Last" />
</div>
<button class="btn btn-primary" id="fetch-btn" style="align-self:flex-end">Fetch publications</button>
<button class="btn btn-secondary" id="add-btn" style="align-self:flex-end">+ Add manually</button>
<div class="export-wrap">
<button class="btn btn-secondary" id="export-toggle" style="align-self:flex-end">⬇ Export ▾</button>
<div class="export-menu" id="export-menu">
<button data-fmt="apa">APA (.txt)</button>
<button data-fmt="bibtex">BibTeX (.bib)</button>
<button data-fmt="ris">RIS (.ris)</button>
<hr>
<button data-fmt="csv">CSV (.csv)</button>
<button data-fmt="json">JSON (.json)</button>
<hr>
<button data-fmt="pdf">Print / Save as PDF</button>
</div>
</div>
<button class="btn btn-secondary" id="import-btn" style="align-self:flex-end">⬆ Import JSON</button>
<input type="file" id="import-file" accept=".json" style="display:none" />
</div>
<!-- ── Sort controls ──────────────────────────────────── -->
<div class="controls">
<label>Sort by:</label>
<select id="sort-col">
<option value="year">Year</option>
<option value="topic">Topic</option>
<option value="firstAuthor">First author</option>
<option value="lastAuthor">Last author</option>
<option value="title">Title</option>
</select>
<select id="sort-dir">
<option value="desc">Descending</option>
<option value="asc">Ascending</option>
</select>
<button class="btn btn-secondary" id="sort-btn">Apply sort</button>
</div>
<!-- ── Topic filter chips ─────────────────────────────── -->
<div class="filter-chips" id="topic-chips">
<span class="chip active" data-topic="all">All</span>
<!-- chips are populated dynamically from TOPICS config -->
</div>
<!-- ── Status line ────────────────────────────────────── -->
<div id="status"></div>
<!-- ── Stats ──────────────────────────────────────────── -->
<div id="stats-bar"></div>
<!-- ── Table ──────────────────────────────────────────── -->
<div class="table-wrap">
<table id="pub-table">
<thead>
<tr>
<th class="td-num" data-col="num" title="Click to sort">#<span class="sort-icon">↕</span></th>
<th class="td-topic" data-col="topic" title="Click to sort">Topic<span class="sort-icon">↕</span></th>
<th class="td-authors" data-col="firstAuthor" title="Click to sort">Authors<span class="sort-icon">↕</span></th>
<th class="td-year" data-col="year" title="Click to sort">Year<span class="sort-icon">↕</span></th>
<th class="td-title" data-col="title" title="Click to sort">Title<span class="sort-icon">↕</span></th>
<th class="td-journal" data-col="journal" title="Click to sort">Journal<span class="sort-icon">↕</span></th>
<th class="td-actions">Actions</th>
</tr>
</thead>
<tbody id="pub-tbody"></tbody>
</table>
</div>
</div><!-- /container -->
<!-- ── Add / Edit modal ───────────────────────────────── -->
<div class="modal-overlay" id="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="modal-title">
<div class="modal">
<h2 id="modal-title">Add publication</h2>
<div class="form-grid">
<div class="form-group full">
<label for="m-title">Title *</label>
<textarea id="m-title" rows="2"></textarea>
</div>
<div class="form-group full">
<label for="m-authors">Authors (comma-separated, Last FM format)</label>
<input type="text" id="m-authors" placeholder="Pernet C, Smith A, …" />
</div>
<div class="form-group">
<label for="m-year">Year *</label>
<input type="text" id="m-year" placeholder="2024" />
</div>
<div class="form-group">
<label for="m-journal">Journal</label>
<input type="text" id="m-journal" />
</div>
<div class="form-group">
<label for="m-volume">Volume</label>
<input type="text" id="m-volume" placeholder="12" />
</div>
<div class="form-group">
<label for="m-issue">Issue</label>
<input type="text" id="m-issue" placeholder="3" />
</div>
<div class="form-group">
<label for="m-pages">Pages</label>
<input type="text" id="m-pages" placeholder="45-67" />
</div>
<div class="form-group">
<label for="m-topic">Topic *</label>
<select id="m-topic"><!-- populated from TOPICS --></select>
</div>
<div class="form-group">
<label for="m-doi">DOI / URL</label>
<input type="text" id="m-doi" placeholder="10.xxxx/…" />
</div>
<div class="form-group">
<label for="m-pmid">PubMed ID</label>
<input type="text" id="m-pmid" />
</div>
<div class="form-group">
<label for="m-source">Source</label>
<input type="text" id="m-source" value="manual" />
</div>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" id="modal-cancel">Cancel</button>
<button class="btn btn-primary" id="modal-save">Save</button>
</div>
</div>
</div>
<div class="modal-overlay" id="review-overlay" role="dialog" aria-modal="true" aria-labelledby="review-title">
<div class="modal" style="width:min(95vw,900px)">
<h2 id="review-title">Review fetched changes</h2>
<p id="review-summary"></p>
<p>New publications and empty-field additions are selected by default. Conflicting values stay unchanged unless selected. Topics and manual records are preserved.</p>
<div id="review-items"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="review-cancel">Discard fetched changes</button>
<button class="btn btn-primary" id="review-apply">Apply selected changes</button>
</div>
</div>
</div>
<footer>
<div class="container">
Publications fetched live from PubMed E-utilities & Semantic Scholar APIs.
Last fetch: <span id="last-fetch">—</span>
</div>
</footer>
<script>
/* ════════════════════════════════════════════════════════════════
██ USER-EDITABLE CONFIGURATION — safe to change these values ██
════════════════════════════════════════════════════════════════
TOPICS
──────
Each entry: { id, label, keywords }
• id : used internally and as a CSS class suffix (no spaces).
• label : displayed in the UI.
• keywords: array of lowercase strings used to auto-classify a
publication by matching against its title/journal.
Add / remove words freely.
The FIRST topic whose keywords match wins; "other"
is the fallback.
Order matters — put the most specific topics first.
AUTHOR_VARIANTS
───────────────
All name forms PubMed might return for the target author.
Used to detect 1st-author and last-author status.
PUBMED_RETMAX
─────────────
Maximum number of PubMed records to fetch (hard cap: 9999).
*/
const CONFIG = {
TOPICS: [
{
id: "method",
label: "Method",
keywords: [
"artifact", "preprocessing", "pipeline", "toolbox", "standards",
"software", "algorithm", "open source", "reliability", "bids"
]
},
{
id: "stats",
label: "Stats",
keywords: [
"statistic", "statistical", "glm", "effect size",
"false discovery", "correction", "power", "cluster",
"robust", "univariate", "multivariate"
]
},
{
id: "data",
label: "Data",
keywords: [
"dataset", "data", "database", "repository", "open data"
]
},
{
id: "clinical",
label: "Clinical",
keywords: [
"patient", "disorder", "disease", "clinical", "schizophrenia",
"depression", "bipolar", "epilepsy", "autism", "adhd",
"stroke", "dementia", "alzheimer", "therapy", "treatment",
"diagnosis"
]
},
{
id: "cog-neuro",
label: "Cog Neuro",
keywords: [
"cognitive", "perception", "attention", "memory", "language",
"face", "emotion", "decision", "learning", "working memory",
"executive", "motor", "sensory", "cortex", "brain", "neural",
"neuroscience", "connectivity"
]
},
{
id: "book",
label: "Book",
keywords: [
"book", "chapter", "editor", "publisher"
]
}
/* ── ADD MORE TOPICS HERE following the same structure ── */
],
AUTHOR_VARIANTS: [
"Pernet C",
"Pernet CR",
"Pernet Cyril"
],
PUBMED_RETMAX: 500
}; /* ── END OF USER-EDITABLE CONFIG ── */
/* ════════════════════════════════════════════════════════════════
Application code — edit with care
════════════════════════════════════════════════════════════════ */
// ── State ──────────────────────────────────────────────────────
let publications = []; // master array
let filtered = []; // currently visible (after topic filter)
let sortState = { col: "year", dir: "desc" };
let activeFilter = "all";
let editingId = null; // null = new entry, string = existing id
let tombstones = new Set(); // normalised titles the user deleted
let cachedAuthor = ""; // author name currently in cache
let pendingReview = null;
let fetching = false;
let initializing = true;
// ── localStorage helpers ─────────────────────────────────────────
function storageKey(name) {
return "pubs_v1_" + name.toLowerCase().replace(/\s+/g, "_");
}
function tombstoneKey(name) {
return "pubs_tombs_v1_" + name.toLowerCase().replace(/\s+/g, "_");
}
function normTitle(t) {
return String(t).toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 60);
}
/** Persist current list + tombstones to localStorage for `name`. */
function saveToCache(name) {
if (!name) return;
try {
localStorage.setItem(storageKey(name), JSON.stringify(publications));
localStorage.setItem(tombstoneKey(name), JSON.stringify([...tombstones]));
localStorage.setItem(storageKey(name) + "_fetchdate",
document.getElementById("last-fetch").textContent);
} catch(e) { /* storage full – silently skip */ }
}
/** Load list + tombstones from localStorage for `name`. Returns true if found. */
function loadFromCache(name) {
if (!name) return false;
try {
const raw = localStorage.getItem(storageKey(name));
if (!raw) return false;
const tombs = localStorage.getItem(tombstoneKey(name));
const fd = localStorage.getItem(storageKey(name) + "_fetchdate");
return applyImportedData({ author: name, publications: JSON.parse(raw),
tombstones: tombs ? JSON.parse(tombs) : [], lastFetch: fd || '—' });
} catch(e) { return false; }
}
/**
* Commit all mutations: save to cache then re-render.
* Call this instead of bare applyFilterAndRender() after any change.
*/
function commitAndRender() {
saveToCache(cachedAuthor || document.getElementById("author-input").value.trim());
applyFilterAndRender();
}
// ── Helpers ────────────────────────────────────────────────────
function uid() {
return Math.random().toString(36).slice(2) + Date.now().toString(36);
}
function setStatus(html) {
document.getElementById("status").innerHTML = html;
}
function classifyTopic(title = "", journal = "") {
const haystack = (title + " " + journal).toLowerCase();
for (const t of CONFIG.TOPICS) {
if (t.keywords.some(kw => haystack.includes(kw))) return t.id;
}
return "other";
}
function parseAuthors(authorStr = "") {
// handles "A B, C D" or array of objects from APIs
if (Array.isArray(authorStr)) {
return authorStr.map(a => a.name || a.authname || "").filter(Boolean);
}
return authorStr.split(/[;,]/).map(s => s.trim()).filter(Boolean);
}
function isTargetAuthor(name) {
const n = name.toLowerCase().replace(/\s+/g, " ");
return CONFIG.AUTHOR_VARIANTS.some(v => {
const vl = v.toLowerCase().replace(/\s+/g, " ");
return n === vl || n.startsWith(vl.split(" ")[0]) && n.includes(vl.split(" ")[1] || "");
});
}
function computeAuthorFlags(authors) {
const isFirst = authors.length > 0 && isTargetAuthor(authors[0]);
const isLast = authors.length > 0 && isTargetAuthor(authors[authors.length - 1]);
return { isFirst, isLast };
}
function topicBadge(pubId, topicId) {
const topic = CONFIG.TOPICS.find(t => t.id === topicId);
const label = topic ? topic.label : "Other";
const cls = topic ? `topic-${topicId}` : "topic-other";
// title attribute hints the user they can click to change topic
return `<span class="topic-badge ${cls}" data-pubid="${pubId}" title="Click to change topic">${label}</span>`;
}
function formatAuthors(authors) {
if (!authors || authors.length === 0) return "—";
if (authors.length <= 4) return authors.join(", ");
return authors.slice(0, 3).join(", ") + " … " + authors[authors.length - 1];
}
// ── Build topic chips ──────────────────────────────────────────
function buildChips() {
const container = document.getElementById("topic-chips");
container.innerHTML = `<span class="chip active" data-topic="all">All</span>`;
for (const t of CONFIG.TOPICS) {
const chip = document.createElement("span");
chip.className = "chip";
chip.dataset.topic = t.id;
chip.textContent = t.label;
container.appendChild(chip);
}
// "Other" chip
const other = document.createElement("span");
other.className = "chip";
other.dataset.topic = "other";
other.textContent = "Other";
container.appendChild(other);
container.addEventListener("click", e => {
if (!e.target.classList.contains("chip")) return;
container.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
e.target.classList.add("active");
activeFilter = e.target.dataset.topic;
applyFilterAndRender();
});
}
// ── Populate modal topic select ────────────────────────────────
function buildTopicSelect() {
const sel = document.getElementById("m-topic");
sel.innerHTML = "";
for (const t of CONFIG.TOPICS) {
const opt = document.createElement("option");
opt.value = t.id;
opt.textContent = t.label;
sel.appendChild(opt);
}
const other = document.createElement("option");
other.value = "other";
other.textContent = "Other";
sel.appendChild(other);
}
// ── Stats bar ──────────────────────────────────────────────────
function updateStats() {
const bar = document.getElementById("stats-bar");
const total = publications.length;
const first = publications.filter(p => p.isFirst).length;
const last = publications.filter(p => p.isLast).length;
const topicCounts = {};
for (const p of publications) {
topicCounts[p.topic] = (topicCounts[p.topic] || 0) + 1;
}
let html = `<span>Total: <strong>${total}</strong></span>
<span>1st author: <strong>${first}</strong></span>
<span>Last author: <strong>${last}</strong></span>`;
for (const t of CONFIG.TOPICS) {
if (topicCounts[t.id]) {
html += `<span>${t.label}: <strong>${topicCounts[t.id]}</strong></span>`;
}
}
bar.innerHTML = html;
}
// ── Render table ───────────────────────────────────────────────
function applyFilterAndRender() {
filtered = activeFilter === "all"
? [...publications]
: publications.filter(p => p.topic === activeFilter);
// apply sort
const col = sortState.col;
const dir = sortState.dir === "asc" ? 1 : -1;
filtered.sort((a, b) => {
let va = a[col] || "", vb = b[col] || "";
if (col === "year") { va = parseInt(va) || 0; vb = parseInt(vb) || 0; }
else { va = String(va).toLowerCase(); vb = String(vb).toLowerCase(); }
return va < vb ? -dir : va > vb ? dir : 0;
});
renderTable();
updateStats();
updateSortHeaders();
}
function renderTable() {
const tbody = document.getElementById("pub-tbody");
if (filtered.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;padding:2rem;color:#718096">No publications to display.</td></tr>`;
return;
}
tbody.innerHTML = filtered.map((p, i) => {
const firstFlag = p.isFirst ? ' title="First author"' : "";
const lastFlag = p.isLast ? ' title="Last author"' : "";
const authorsHtml = (() => {
if (!p.authors || p.authors.length === 0) return "—";
let parts;
if (p.authors.length <= 4) {
parts = p.authors.map((a, idx) => {
const isF = idx === 0 && p.isFirst;
const isL = idx === p.authors.length - 1 && p.isLast;
const style = (isF || isL) ? " style=\"font-weight:600\"" : "";
return `<span${style}>${a}</span>`;
});
return parts.join(", ");
} else {
const first3 = p.authors.slice(0, 3).map((a, idx) => {
const isF = idx === 0 && p.isFirst;
const style = isF ? " style=\"font-weight:600\"" : "";
return `<span${style}>${a}</span>`;
}).join(", ");
const lastA = p.authors[p.authors.length - 1];
const isL = p.isLast;
const lastStyle = isL ? " style=\"font-weight:600\"" : "";
return first3 + ` … <span${lastStyle}>${lastA}</span>`;
}
})();
const titleHtml = p.doi
? `<a href="${p.doi.startsWith("http") ? p.doi : "https://doi.org/" + p.doi}" target="_blank" rel="noopener">${escHtml(p.title)}</a>`
: escHtml(p.title);
return `<tr data-id="${p.id}">
<td class="td-num">${i + 1}</td>
<td class="td-topic">${topicBadge(p.id, p.topic)}</td>
<td class="td-authors">${authorsHtml}</td>
<td class="td-year">${p.year || "—"}</td>
<td class="td-title">${titleHtml}</td>
<td class="td-journal">${formatJournal(p)}</td>
<td class="td-actions">
<button class="btn btn-edit" onclick="openEdit('${p.id}')" title="Edit">✏</button>
<button class="btn btn-danger" onclick="removeEntry('${p.id}')" title="Remove">✕</button>
</td>
</tr>`;
}).join("");
}
// ── Inline topic picker ───────────────────────────────────────
// Clicking a topic badge replaces it with a <select>; choosing a
// value saves immediately and re-renders just that badge.
document.getElementById("pub-tbody").addEventListener("click", e => {
const badge = e.target.closest(".topic-badge");
if (!badge) return;
const pubId = badge.dataset.pubid;
if (!pubId) return;
// Build inline select
const sel = document.createElement("select");
sel.className = "topic-picker";
for (const t of CONFIG.TOPICS) {
const opt = document.createElement("option");
opt.value = t.id;
opt.textContent = t.label;
sel.appendChild(opt);
}
const other = document.createElement("option");
other.value = "other"; other.textContent = "Other";
sel.appendChild(other);
const pub = publications.find(p => p.id === pubId);
if (pub) sel.value = pub.topic;
// Replace badge with select
badge.replaceWith(sel);
sel.focus();
function commit() {
const newTopic = sel.value;
if (pub) pub.topic = newTopic;
// Re-render only this cell to avoid full table repaint
const newBadge = document.createElement("span");
newBadge.outerHTML; // placeholder
const td = sel.parentElement;
if (td) td.innerHTML = topicBadge(pubId, newTopic);
// persist the topic change without a full re-render
saveToCache(cachedAuthor || document.getElementById("author-input").value.trim());
updateStats();
}
sel.addEventListener("change", commit);
sel.addEventListener("blur", commit);
sel.addEventListener("keydown", e => {
if (e.key === "Escape") {
// restore original badge without saving
const td = sel.parentElement;
if (td && pub) td.innerHTML = topicBadge(pubId, pub.topic);
}
});
});
function formatJournal(p) {
let s = escHtml(p.journal || "");
if (p.volume) {
s += ", <em>" + escHtml(p.volume) + "</em>";
if (p.issue) s += "(" + escHtml(p.issue) + ")";
}
if (p.pages) s += ":" + escHtml(p.pages);
return s || "—";
}
function escHtml(str) {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
// ── Sort header highlighting ───────────────────────────────────
function updateSortHeaders() {
document.querySelectorAll("thead th[data-col]").forEach(th => {
const col = th.dataset.col;
th.classList.toggle("sorted", col === sortState.col);
const icon = th.querySelector(".sort-icon");
if (icon) {
icon.textContent = col === sortState.col
? (sortState.dir === "asc" ? "↑" : "↓")
: "↕";
}
});
}
// click-to-sort on headers
document.querySelectorAll("thead th[data-col]").forEach(th => {
th.addEventListener("click", () => {
const col = th.dataset.col;
if (col === "num") return;
if (sortState.col === col) {
sortState.dir = sortState.dir === "asc" ? "desc" : "asc";
} else {
sortState.col = col;
sortState.dir = "asc";
}
applyFilterAndRender();
});
});
// sort dropdown
document.getElementById("sort-btn").addEventListener("click", () => {
sortState.col = document.getElementById("sort-col").value;
sortState.dir = document.getElementById("sort-dir").value;
applyFilterAndRender();
});
// ── Remove / Edit ──────────────────────────────────────────────
function removeEntry(id) {
if (!confirm("Remove this publication?\n\nThis entry will not come back on re-fetch.")) return;
const pub = publications.find(p => p.id === id);
if (pub) {
tombstones.add(normTitle(pub.title));
if (pub.doi) tombstones.add("doi:" + normDoi(pub.doi));
if (pub.pmid) tombstones.add("pmid:" + String(pub.pmid).trim());
} // remember so re-fetch skips it
publications = publications.filter(p => p.id !== id);
commitAndRender();
}
function openEdit(id) {
const p = publications.find(x => x.id === id);
if (!p) return;
editingId = id;
document.getElementById("modal-title").textContent = "Edit publication";
document.getElementById("m-title").value = p.title || "";
document.getElementById("m-authors").value = (p.authors || []).join(", ");
document.getElementById("m-year").value = p.year || "";
document.getElementById("m-journal").value = p.journal || "";
document.getElementById("m-volume").value = p.volume || "";
document.getElementById("m-issue").value = p.issue || "";
document.getElementById("m-pages").value = p.pages || "";
document.getElementById("m-topic").value = p.topic || "other";
document.getElementById("m-doi").value = p.doi || "";
document.getElementById("m-pmid").value = p.pmid || "";
document.getElementById("m-source").value = p.source || "manual";
openModal();
}
// ── Modal ──────────────────────────────────────────────────────
function openModal() {
document.getElementById("modal-overlay").classList.add("open");
}
function closeModal() {
document.getElementById("modal-overlay").classList.remove("open");
editingId = null;
}
document.getElementById("add-btn").addEventListener("click", () => {
editingId = null;
document.getElementById("modal-title").textContent = "Add publication";
["m-title","m-authors","m-year","m-journal","m-volume","m-issue","m-pages","m-doi","m-pmid"].forEach(id =>
document.getElementById(id).value = "");
document.getElementById("m-topic").value = CONFIG.TOPICS[0]?.id || "other";
document.getElementById("m-source").value = "manual";
openModal();
});
document.getElementById("modal-cancel").addEventListener("click", closeModal);
document.getElementById("modal-overlay").addEventListener("click", e => {
if (e.target === e.currentTarget) closeModal();
});
document.getElementById("modal-save").addEventListener("click", () => {
const title = document.getElementById("m-title").value.trim();
if (!title) { alert("Title is required."); return; }
const authors = parseAuthors(document.getElementById("m-authors").value);
const { isFirst, isLast } = computeAuthorFlags(authors);
const entry = {
id: editingId || uid(),
title,
authors,
firstAuthor: authors[0] || "",
lastAuthor: authors[authors.length - 1] || "",
year: document.getElementById("m-year").value.trim(),
journal: document.getElementById("m-journal").value.trim(),
volume: document.getElementById("m-volume").value.trim(),
issue: document.getElementById("m-issue").value.trim(),
pages: document.getElementById("m-pages").value.trim(),
topic: document.getElementById("m-topic").value,
doi: document.getElementById("m-doi").value.trim(),
pmid: document.getElementById("m-pmid").value.trim(),
source: document.getElementById("m-source").value.trim(),
isFirst, isLast
};
if (editingId) {
const idx = publications.findIndex(p => p.id === editingId);
if (idx !== -1) publications[idx] = entry;
} else {
publications.push(entry);
}
closeModal();
commitAndRender();
});
// ── Export / Import ────────────────────────────────────────────
// APA
function formatAPA(p) {
const authors = (p.authors || []).join(", ");
const year = p.year ? `(${p.year})` : "(n.d.)";
const doi = p.doi
? "https://doi.org/" + p.doi.replace(/^https?:\/\/doi\.org\//, "")
: "";
let journalRef = p.journal || "";
if (p.volume) { journalRef += ", " + p.volume; if (p.issue) journalRef += "(" + p.issue + ")"; }
if (p.pages) journalRef += ", " + p.pages;
return [authors, year, (p.title || "Untitled") + ".", journalRef, doi]
.filter(Boolean).join(" ");
}
// BibTeX
function formatBibTeX(p, idx) {
const key = (p.authors?.[0] || "Unknown").replace(/\s+/g, "") + (p.year || "0000") + idx;
const author = (p.authors || []).join(" and ");
const doiLine = p.doi ? `\n doi = {${p.doi}},` : "";
const volumeLine = p.volume ? `\n volume = {${p.volume}},` : "";
const numberLine = p.issue ? `\n number = {${p.issue}},` : "";
const pagesLine = p.pages ? `\n pages = {${p.pages}},` : "";
return `@article{${key},\n author = {${author}},\n title = {${p.title || ""}},\n journal = {${p.journal || ""}},\n year = {${p.year || ""}},${volumeLine}${numberLine}${pagesLine}${doiLine}\n}`;
}
// RIS
function formatRIS(p) {
const lines = ["TY - JOUR"];
(p.authors || []).forEach(a => lines.push(`AU - ${a}`));
if (p.year) lines.push(`PY - ${p.year}`);
if (p.title) lines.push(`TI - ${p.title}`);
if (p.journal) lines.push(`JO - ${p.journal}`);
if (p.volume) lines.push(`VL - ${p.volume}`);
if (p.issue) lines.push(`IS - ${p.issue}`);
if (p.pages) lines.push(`SP - ${p.pages}`);
if (p.doi) lines.push(`DO - ${p.doi}`);
if (p.pmid) lines.push(`AN - ${p.pmid}`);
lines.push("ER - ");
return lines.join("\n");
}
// Download helper
function triggerDownload(content, filename, mime) {
const blob = new Blob([content], { type: mime });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
}
// Export menu toggle
const exportToggle = document.getElementById("export-toggle");
const exportMenu = document.getElementById("export-menu");
exportToggle.addEventListener("click", e => {
e.stopPropagation();
exportMenu.classList.toggle("open");
});
document.addEventListener("click", () => exportMenu.classList.remove("open"));
exportMenu.addEventListener("click", e => {
const btn = e.target.closest("button[data-fmt]");
if (!btn) return;
exportMenu.classList.remove("open");
const fmt = btn.dataset.fmt;
// export what is currently visible (filtered), fall back to all
const list = filtered.length ? filtered : publications;
if (fmt === "json") {
// Always export the full dataset (all publications) + tombstones so the
// file can serve as a complete restore point when placed next to the page.
triggerDownload(JSON.stringify(buildExportObject(), null, 2), "publications.json", "application/json");
} else if (fmt === "apa") {
const text = list.map((p, i) => `${i + 1}. ${formatAPA(p)}`).join("\n\n");
triggerDownload(text, "publications_apa.txt", "text/plain");