-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1224 lines (1061 loc) · 37.5 KB
/
Copy pathscript.js
File metadata and controls
1224 lines (1061 loc) · 37.5 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
/**
* Datenpunk — multilingual content (i18n)
* ========================================
*
* All user-visible copy lives in content/de.json and content/en.json.
* HTML only marks *where* strings go (data attributes); it should not
* contain wording you care about in production (except technical markup).
*
* Default language: German ("de"). The visitor’s choice is stored in
* localStorage (STORAGE_KEY) so it survives reloads and works on every
* HTML page in this site.
*
* Language switch UI: set ENABLE_LANG_SWITCH below to true to show the
* DE | EN control again. When false, the site always loads German ("de");
* localStorage is not read until the switch is re-enabled.
*
* Local preview: fetch() usually fails on file:// URLs. Run a static
* server from this folder (e.g. python -m http.server) so JSON loads.
*
* ---------------------------------------------------------------------------
* How to add a new translation key later
* ---------------------------------------------------------------------------
*
* 1. Pick a stable dot path, e.g. "aboutPage.newSection.body".
*
* 2. Add that path with the SAME shape to BOTH de.json and en.json.
* Values must be strings (or numbers) at the leaf — not objects.
*
* 3. In HTML, put the key on the element:
* <p data-i18n="aboutPage.newSection.body"></p>
* When the locale loads or the user switches language, the script
* replaces the element’s textContent with the string from JSON.
*
* 4. For translated HTML *attributes* (aria-label, title, alt, …):
* <nav
* data-i18n-attr="nav.ariaMain"
* data-i18n-attr-name="aria-label"
* aria-label="">
* </nav>
* The attribute named in data-i18n-attr-name receives the value at
* data-i18n-attr in the JSON.
*
* 5. For the browser tab title on one page, set on the <html> element:
* <html data-i18n-document-title="meta.documentTitle.about" …>
* Then add meta.documentTitle.about (or your chosen key) in both
* JSON files. If the key is missing, meta.siteTitle is used instead.
*
* 6. For project cards on the home / projects pages, edit the "projects"
* array in JSON. Each item may include: id, href, title, teaser, cta,
* optional github (URL), and optional thumb + thumbAlt (thumbnail image
* URL and short alt text for the home / projects list).
* The script builds the card DOM from those fields (no extra keys in
* HTML for card body copy).
*
* 7. After adding keys, reload with DE and EN both selected once to
* confirm both files parse and every key resolves.
*
* Missing keys: if a path is absent or not a string/number, the UI
* shows [your.path] so missing translations are obvious while editing.
*/
(function () {
"use strict";
var STORAGE_KEY = "datenpunk-lang";
var LANGS = ["de", "en"];
/** Set to true to show DE | EN and honour localStorage again. */
var ENABLE_LANG_SWITCH = false;
var cache = {};
var progressBarEl = null;
var revealObserver = null;
function parsePathTokens(pathStr) {
if (!pathStr) return [];
// Tokens: "foo", "bar", 0, "baz" from "foo.bar[0].baz"
var tokens = [];
var i = 0;
while (i < pathStr.length) {
var ch = pathStr[i];
if (ch === ".") {
i++;
continue;
}
if (ch === "[") {
var end = pathStr.indexOf("]", i + 1);
if (end === -1) break;
var inner = pathStr.slice(i + 1, end);
var idx = parseInt(inner, 10);
if (!isNaN(idx)) tokens.push(idx);
i = end + 1;
continue;
}
var j = i;
while (j < pathStr.length && pathStr[j] !== "." && pathStr[j] !== "[") j++;
tokens.push(pathStr.slice(i, j));
i = j;
}
return tokens;
}
function getByPath(obj, path) {
if (!obj || !path) return undefined;
var tokens = parsePathTokens(String(path));
var cur = obj;
for (var t = 0; t < tokens.length; t++) {
if (cur == null || typeof cur !== "object") return undefined;
cur = cur[tokens[t]];
}
return cur;
}
function missingText(path) {
return "[" + path + "]";
}
/** True if the JSON value can be shown as text in the DOM. */
function isRenderableValue(val) {
return typeof val === "string" || typeof val === "number";
}
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
/**
* Minimal inline formatting for copy strings.
* - Supports **bold** and *italic* / _italic_.
* - Escapes everything else (no raw HTML).
*/
function formatCopyInline(val) {
var raw = String(val);
var hasLink = /\[[^\]]+\]\([^)]+\)/.test(raw);
var hasBold = raw.indexOf("**") !== -1;
var hasAsteriskItalic = raw.indexOf("*") !== -1;
var hasUnderscoreItalic = raw.indexOf("_") !== -1;
if (!hasLink && !hasBold && !hasAsteriskItalic && !hasUnderscoreItalic) {
return { isHtml: false, text: raw };
}
var safe = escapeHtml(raw);
var html = safe.replace(
/\[([^\]]+)\]\(([^)]+)\)/g,
function (_m, label, url) {
var href = String(url).trim();
if (!/^https?:\/\//i.test(href)) return _m;
return (
'<a href="' +
escapeHtml(href) +
'" target="_blank" rel="noopener noreferrer">' +
label +
"</a>"
);
}
);
html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
// Avoid matching **bold** as *italic*.
html = html.replace(/(^|[^*])\*(?!\s)([^*]+?)(?!\s)\*(?!\*)/g, "$1<em>$2</em>");
html = html.replace(/(^|[^_])_(?!\s)([^_]+?)(?!\s)_/g, "$1<em>$2</em>");
return { isHtml: true, html: html };
}
function getStoredLang() {
try {
var stored = localStorage.getItem(STORAGE_KEY);
if (stored && LANGS.indexOf(stored) !== -1) return stored;
} catch (e) {
/* localStorage unavailable (private mode, policy, etc.) */
}
return "de";
}
function setStoredLang(lang) {
try {
localStorage.setItem(STORAGE_KEY, lang);
} catch (e) {
/* ignore */
}
}
function loadLocale(lang, callback) {
if (cache[lang]) {
callback(null, cache[lang]);
return;
}
function setByPath(root, pathStr, value) {
if (!root || !pathStr) return;
var tokens = parsePathTokens(String(pathStr));
var cur = root;
for (var t = 0; t < tokens.length; t++) {
var key = tokens[t];
var isLast = t === tokens.length - 1;
var nextKey = tokens[t + 1];
var nextIsIndex = typeof nextKey === "number";
if (isLast) {
cur[key] = value;
return;
}
if (cur[key] == null) {
cur[key] = nextIsIndex ? [] : {};
}
cur = cur[key];
}
}
function parseCopyMarkdown(text) {
// Format produced by scripts/export-i18n-to-md.mjs:
// ## `path.to.key`
// <value lines> OR ```text ... ```
var out = {};
var lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
var curKey = null;
var curValLines = [];
var inFence = false;
var started = false;
function flush() {
if (!curKey) return;
var raw = curValLines.join("\n");
var val = raw.trimEnd();
setByPath(out, curKey, val);
}
for (var li = 0; li < lines.length; li++) {
var line = lines[li];
var m = line.match(/^##\s+`(.+)`\s*$/);
if (!inFence && m) {
started = true;
flush();
curKey = m[1];
curValLines = [];
continue;
}
if (!started) continue;
if (line.trim() === "```text") {
inFence = true;
continue;
}
if (line.trim() === "```" && inFence) {
inFence = false;
continue;
}
// Collect value lines (including blank lines inside fences)
curValLines.push(line);
}
flush();
return out;
}
function loadFromMarkdown() {
var mdUrl = "content/copy." + lang + ".md";
return fetch(mdUrl, { cache: "no-store" }).then(function (res) {
if (!res.ok) throw new Error("Failed to load " + mdUrl);
return res.text();
});
}
loadFromMarkdown()
.then(function (md) {
var data = parseCopyMarkdown(md);
cache[lang] = data;
callback(null, data);
})
.catch(function (errMd) {
console.error(errMd);
callback(errMd, null);
});
}
/**
* Sets document.title from <html data-i18n-document-title="path.to.key">.
* Falls back to meta.siteTitle so the tab is never empty when JSON loads.
*/
function applyDocumentTitle(bundle) {
var key = document.documentElement.getAttribute("data-i18n-document-title");
var fallback = getByPath(bundle, "meta.siteTitle");
if (!key) {
if (isRenderableValue(fallback)) document.title = String(fallback);
return;
}
var val = getByPath(bundle, key);
if (isRenderableValue(val)) {
document.title = String(val);
} else if (isRenderableValue(fallback)) {
document.title = String(fallback);
} else {
document.title = missingText(key);
}
}
function applyHtmlLang(bundle) {
var lang = getByPath(bundle, "meta.htmlLang");
if (isRenderableValue(lang)) {
document.documentElement.lang = String(lang);
}
}
function applyDataI18nNodes(bundle) {
document.querySelectorAll("[data-i18n]").forEach(function (el) {
var key = el.getAttribute("data-i18n");
var val = getByPath(bundle, key);
if (isRenderableValue(val)) {
var rendered = formatCopyInline(val);
if (rendered.isHtml) el.innerHTML = rendered.html;
else el.textContent = rendered.text;
} else {
el.textContent = missingText(key);
}
});
}
function applyDataI18nAttrs(bundle) {
document.querySelectorAll("[data-i18n-attr]").forEach(function (el) {
function applyOne(keyAttr, nameAttr, defaultName) {
var key = el.getAttribute(keyAttr);
if (!key) return;
var attrName = el.getAttribute(nameAttr) || defaultName;
var val = getByPath(bundle, key);
if (isRenderableValue(val)) {
el.setAttribute(attrName, String(val));
} else {
el.setAttribute(attrName, missingText(key));
}
}
applyOne("data-i18n-attr", "data-i18n-attr-name", "aria-label");
applyOne("data-i18n-attr-2", "data-i18n-attr-name-2", "title");
});
}
function accentHeroTitleDot() {
var el = document.getElementById("hero-title");
if (!el) return;
// i18n fills textContent; turn trailing "." into a stylable span.
var raw = String(el.textContent || "");
if (!raw || raw.length < 2) return;
if (raw[raw.length - 1] !== ".") return;
var base = raw.slice(0, -1);
el.textContent = "";
var textNode = document.createTextNode(base);
var dot = document.createElement("span");
dot.className = "dp-dot";
dot.textContent = ".";
el.appendChild(textNode);
el.appendChild(dot);
}
/**
* Kolumnen page: render one article at a time (default index 0).
* Optional ?art=1 for older pieces; only that article is shown.
*/
function applyKolumnenArticle(bundle) {
var root = document.querySelector("[data-kolumnen-page]");
if (!root) return;
var params = new URLSearchParams(window.location.search);
var index = 0;
if (params.has("art")) {
var parsed = parseInt(params.get("art"), 10);
if (!isNaN(parsed) && parsed >= 0) index = parsed;
}
var titleEl = root.querySelector("[data-kolumnen-title]");
var deckEl = root.querySelector("[data-kolumnen-deck]");
var bodyEl = root.querySelector("[data-kolumnen-body]");
var tagsEl = root.querySelector("[data-kolumnen-tags]");
if (!titleEl || !deckEl || !bodyEl) return;
var base = "kolumnen.articles[" + index + "]";
var titleVal = getByPath(bundle, base + ".title");
var deckVal = getByPath(bundle, base + ".deck");
var tagVal = getByPath(bundle, base + ".tag");
titleEl.textContent = isRenderableValue(titleVal)
? String(titleVal)
: missingText(base + ".title");
deckEl.textContent = isRenderableValue(deckVal)
? String(deckVal)
: missingText(base + ".deck");
if (tagsEl) {
tagsEl.innerHTML = "";
if (isRenderableValue(tagVal)) {
var tagLi = document.createElement("li");
tagLi.className = "teaser__tag";
tagLi.textContent = String(tagVal);
tagsEl.appendChild(tagLi);
}
}
bodyEl.innerHTML = "";
var pi = 0;
while (true) {
var pKey = base + ".paragraphs[" + pi + "]";
var pVal = getByPath(bundle, pKey);
if (!isRenderableValue(pVal)) break;
var p = document.createElement("p");
p.className = "reveal";
var rendered = formatCopyInline(pVal);
if (rendered.isHtml) p.innerHTML = rendered.html;
else p.textContent = rendered.text;
bodyEl.appendChild(p);
pi++;
}
if (pi === 0) {
var empty = document.createElement("p");
empty.className = "reveal";
empty.textContent = missingText(base + ".paragraphs[0]");
bodyEl.appendChild(empty);
}
if (isRenderableValue(titleVal)) {
var siteTitle = getByPath(bundle, "meta.siteTitle");
var suffix = isRenderableValue(siteTitle) ? String(siteTitle) : "Datenpunk";
document.title = String(titleVal) + " — " + suffix;
}
}
function applyObfuscatedEmailLinks() {
document.querySelectorAll("[data-email-link]").forEach(function (a) {
var parent = a.parentElement || document;
var userEl = parent.querySelector("[data-email-user]");
var domainEl = parent.querySelector("[data-email-domain]");
var user = userEl ? String(userEl.textContent || "").trim() : "";
var domain = domainEl ? String(domainEl.textContent || "").trim() : "";
if (!user || !domain) return;
a.setAttribute("href", "mailto:" + user + "@" + domain);
});
}
function updateLangButtons(lang) {
document.querySelectorAll("[data-set-lang]").forEach(function (btn) {
var code = btn.getAttribute("data-set-lang");
btn.setAttribute("aria-pressed", code === lang ? "true" : "false");
});
}
/**
* Renders project rows into [data-project-list] from bundle.projects.
* Markup follows a magazine “teaser” pattern (headline + dek + read line),
* not product cards — styling is entirely in style.css (.teaser*).
*/
function appendProjectGithubLink(target, proj, bundle, opts) {
var options = opts || {};
var raw = proj.github;
var hasRaw = isRenderableValue(raw) && String(raw).trim() !== "";
if (!hasRaw && !options.always) return;
var label = getByPath(bundle, "common.projectGithubCta");
var text = isRenderableValue(label) ? String(label) : "GitHub";
var el;
if (hasRaw) {
el = document.createElement("a");
el.href = String(raw).trim();
el.setAttribute("rel", "noopener noreferrer");
el.setAttribute("target", "_blank");
} else {
// Placeholder to keep card heights aligned when some projects lack GitHub.
el = document.createElement("span");
el.setAttribute("aria-hidden", "true");
}
el.className = options.className || "teaser__github";
el.textContent = text;
if (!hasRaw) el.classList.add("teaser__github--placeholder");
target.appendChild(el);
}
function normalizeTag(tag) {
if (!isRenderableValue(tag)) return "";
return String(tag).trim();
}
function normalizeTagKey(tag) {
// Must be safe for space-separated storage in data-tags.
// e.g. "In Vorbereitung" -> "in-vorbereitung", "Data Viz" -> "data-viz"
return normalizeTag(tag)
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^a-z0-9\u00C0-\u017F-]+/g, "")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
}
function renderProjectCards(bundle) {
var containers = document.querySelectorAll("[data-project-list]");
if (!containers.length) return;
var projects = getByPath(bundle, "projects");
if (!Array.isArray(projects)) return;
containers.forEach(function (container) {
var max = container.getAttribute("data-project-limit");
var list = max ? projects.slice(0, parseInt(max, 10)) : projects.slice();
var layout = container.getAttribute("data-project-layout") || "";
container.innerHTML = "";
list.forEach(function (proj, index) {
var hasLink = proj.href && String(proj.href).trim() !== "";
var href = hasLink ? String(proj.href).trim() : "";
var isExternalLink = /^https?:\/\//i.test(href);
var thumbSrc = proj.thumb;
var hasThumb =
isRenderableValue(thumbSrc) && String(thumbSrc).trim() !== "";
var effectiveThumbSrc =
hasThumb || layout !== "featured"
? thumbSrc
: "assets/images/meerkats.jpg";
var effectiveHasThumb =
isRenderableValue(effectiveThumbSrc) &&
String(effectiveThumbSrc).trim() !== "";
var tagsRaw = Array.isArray(proj.tags) ? proj.tags : [];
var tags = tagsRaw
.map(normalizeTag)
.filter(function (t) {
return t !== "";
});
tags.sort(function (a, b) {
return String(a).localeCompare(String(b), undefined, {
sensitivity: "base",
});
});
var tagKeys = tags.map(normalizeTagKey);
var article = document.createElement("article");
article.className =
"teaser reveal" + (hasLink ? " teaser--linked" : " teaser--static");
if (effectiveHasThumb) article.classList.add("teaser--has-thumb");
if (layout === "featured") article.classList.add("teaser--featured");
if (tagKeys.length) article.setAttribute("data-tags", tagKeys.join(" "));
var titleText = isRenderableValue(proj.title)
? String(proj.title)
: missingText("projects[" + index + "].title");
var deckText = isRenderableValue(proj.teaser)
? String(proj.teaser)
: missingText("projects[" + index + "].teaser");
var readText = isRenderableValue(proj.cta)
? String(proj.cta)
: missingText("projects[" + index + "].cta");
function appendTags(target) {
if (!tags.length) return;
var wrap = document.createElement("ul");
wrap.className = "teaser__tags";
tags.forEach(function (t) {
var li = document.createElement("li");
li.className = "teaser__tag";
li.textContent = t;
wrap.appendChild(li);
});
target.appendChild(wrap);
}
function appendTeaserTextNodes(target) {
var h3 = document.createElement("h3");
h3.className = "teaser__hed";
h3.textContent = titleText;
target.appendChild(h3);
var deck = document.createElement("p");
deck.className = "teaser__deck";
deck.textContent = deckText;
target.appendChild(deck);
appendTags(target);
// Featured cards use a cleaner editorial block: no "read" line.
if (layout !== "featured") {
var read = document.createElement("span");
read.className = "teaser__read";
read.textContent = readText;
target.appendChild(read);
}
}
function appendTeaserBodyNodes(target) {
var deck = document.createElement("p");
deck.className = "teaser__deck";
deck.textContent = deckText;
target.appendChild(deck);
appendTags(target);
}
function makeTitleHed() {
var h3 = document.createElement("h3");
h3.className = "teaser__hed";
h3.textContent = titleText;
return h3;
}
function makeMediaWithTitle() {
var media = document.createElement("div");
media.className = "teaser__media";
media.appendChild(makeThumbImg());
media.appendChild(makeTitleHed());
return media;
}
function makeThumbImg() {
var img = document.createElement("img");
img.className = "teaser__thumb";
img.src = String(effectiveThumbSrc).trim();
img.setAttribute("loading", "lazy");
img.setAttribute("decoding", "async");
if (proj && proj.thumbRaw === true) img.classList.add("thumb--raw");
var altVal = proj.thumbAlt;
img.alt = isRenderableValue(altVal) ? String(altVal) : "";
return img;
}
if (hasLink) {
var link = document.createElement("a");
link.className = "teaser__link";
link.setAttribute("href", href);
if (isExternalLink) {
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
}
if (effectiveHasThumb) {
if (layout === "featured") {
link.appendChild(makeMediaWithTitle());
var bodyF = document.createElement("div");
bodyF.className = "teaser__body";
appendTeaserBodyNodes(bodyF);
link.appendChild(bodyF);
} else {
link.appendChild(makeThumbImg());
var body = document.createElement("div");
body.className = "teaser__body";
appendTeaserTextNodes(body);
link.appendChild(body);
}
} else {
appendTeaserTextNodes(link);
}
article.appendChild(link);
} else if (effectiveHasThumb) {
var row = document.createElement("div");
row.className = "teaser__row";
if (layout === "featured") row.appendChild(makeMediaWithTitle());
else row.appendChild(makeThumbImg());
var bodyS = document.createElement("div");
bodyS.className = "teaser__body";
if (layout === "featured") appendTeaserBodyNodes(bodyS);
else appendTeaserTextNodes(bodyS);
row.appendChild(bodyS);
article.appendChild(row);
} else {
appendTeaserTextNodes(article);
}
var hideGithub = container.hasAttribute("data-project-hide-github");
if (layout !== "featured" && !hideGithub) {
appendProjectGithubLink(article, proj, bundle);
}
container.appendChild(article);
});
});
}
function initProjectTagFilters(bundle) {
var filterRoot = document.querySelector("[data-project-tag-filter]");
if (!filterRoot) return;
var controls = filterRoot.querySelector(".tag-filter__controls");
if (!controls) return;
var listContainer = document.querySelector("[data-project-list]");
if (!listContainer) return;
var emptyEl = document.querySelector("[data-project-empty]");
var projects = getByPath(bundle, "projects");
if (!Array.isArray(projects)) return;
var tagMap = {};
projects.forEach(function (p) {
var tags = Array.isArray(p.tags) ? p.tags : [];
tags
.map(normalizeTag)
.filter(function (t) {
return t !== "";
})
.forEach(function (t) {
var key = normalizeTagKey(t);
if (!key) return;
if (!tagMap[key]) tagMap[key] = t;
});
});
var keys = Object.keys(tagMap).sort(function (a, b) {
return String(tagMap[a]).localeCompare(String(tagMap[b]), undefined, {
sensitivity: "base",
});
});
controls.innerHTML = "";
var allLabel = getByPath(bundle, "projectsPage.filterAll");
var allText = isRenderableValue(allLabel) ? String(allLabel) : "All";
var selected = {};
function getSelectedKeys() {
return Object.keys(selected).filter(function (k) {
return selected[k];
});
}
function setButtonState(btn, on) {
btn.setAttribute("aria-pressed", on ? "true" : "false");
}
function applyFilter() {
var selectedKeys = getSelectedKeys();
var cards = listContainer.querySelectorAll("article.teaser");
var shown = 0;
cards.forEach(function (card) {
var tagAttr = card.getAttribute("data-tags") || "";
var tags = tagAttr ? tagAttr.split(/\s+/).filter(Boolean) : [];
var match =
selectedKeys.length === 0 ||
selectedKeys.some(function (k) {
return tags.indexOf(k) !== -1;
});
card.hidden = !match;
if (match) shown++;
});
if (emptyEl) emptyEl.hidden = shown !== 0;
}
var allBtn = document.createElement("button");
allBtn.type = "button";
allBtn.className = "tag-filter__btn tag-filter__btn--all";
allBtn.textContent = allText;
setButtonState(allBtn, true);
allBtn.addEventListener("click", function () {
selected = {};
Array.prototype.slice.call(controls.querySelectorAll("[data-tag-key]")).forEach(function (b) {
setButtonState(b, false);
});
setButtonState(allBtn, true);
applyFilter();
});
controls.appendChild(allBtn);
keys.forEach(function (key) {
var btn = document.createElement("button");
btn.type = "button";
btn.className = "tag-filter__btn";
btn.textContent = tagMap[key];
btn.setAttribute("data-tag-key", key);
setButtonState(btn, false);
btn.addEventListener("click", function () {
var next = !selected[key];
selected[key] = next;
setButtonState(btn, next);
var any = getSelectedKeys().length > 0;
setButtonState(allBtn, !any);
applyFilter();
});
controls.appendChild(btn);
});
applyFilter();
}
function initFeaturedCarousel() {
var container = document.querySelector("[data-featured-carousel]");
if (!container) return;
var articles = Array.prototype.slice.call(container.querySelectorAll(":scope > article"));
if (!articles.length) return;
var dotsRoot = document.querySelector("[data-featured-dots]");
if (!dotsRoot) return;
function cardStepPx() {
if (!articles.length) return 0;
var a0 = articles[0];
var a1 = articles[1];
if (!a0) return 0;
if (!a1) return a0.getBoundingClientRect().width;
return Math.max(0, a1.offsetLeft - a0.offsetLeft);
}
function cardsPerView() {
// Keep in sync with the CSS breakpoint for the 2-up carousel.
// style2.css: @media (min-width: 1200px) { grid-auto-columns: .../2 }
var mq = window.matchMedia && window.matchMedia("(min-width: 1200px)");
return mq && mq.matches ? 2 : 1;
}
function gapPx() {
try {
var g = window.getComputedStyle(container).columnGap || "0px";
var n = parseFloat(g);
return Number.isFinite(n) ? n : 0;
} catch (e) {
return 0;
}
}
function applyCarouselSizing() {
var per = cardsPerView();
container.setAttribute("data-featured-per", String(per));
var w = container.clientWidth || 0;
if (!w) return;
var gap = gapPx();
var cardW = per >= 2 ? Math.max(1, (w - gap) / 2) : w;
// Force stable geometry so the first card can't collapse to 0 width.
container.style.gridAutoColumns = cardW.toFixed(2) + "px";
articles.forEach(function (a) {
a.style.minWidth = cardW.toFixed(2) + "px";
});
}
function viewCount() {
// Views:
// - mobile (1-up): [1], [2], [3], [4] => N
// - desktop (2-up):
// - 3 cards: [1+2], [2+3] => 2 views
// - 4 cards: [1+2], [3+4] => 2 views
var per = cardsPerView();
if (per <= 1) return Math.max(1, articles.length);
if (articles.length <= 2) return 1;
if (articles.length === 3) return 2;
// For 4 cards (the home limit), show 1+2 then 3+4.
return Math.ceil(articles.length / 2);
}
function startIndexForView(viewIdx) {
var per = cardsPerView();
if (per <= 1) return viewIdx;
// 2-up special case for 3 cards: second view starts at card 2 (index 1).
if (articles.length === 3) return viewIdx === 0 ? 0 : 1;
// Default for 2-up: non-overlapping pages of 2.
return viewIdx * 2;
}
function scrollLeftForView(idx) {
// View index maps to the left-most card index.
var max = viewCount() - 1;
var safe = Math.max(0, Math.min(max, idx));
var startIdx = startIndexForView(safe);
var a = articles[startIdx];
var left = a ? a.offsetLeft : 0;
var end = Math.max(0, container.scrollWidth - container.clientWidth);
return Math.max(0, Math.min(end, left));
}
function rebuildDots() {
var pages = viewCount();
dotsRoot.innerHTML = "";
container.setAttribute("data-featured-pages", String(pages));
// Hide dots when there's only one page.
if (pages <= 1) {
dotsRoot.hidden = true;
container.removeAttribute("data-featured-ready");
return;
}
dotsRoot.hidden = false;
container.setAttribute("data-featured-ready", "true");
for (var i = 0; i < pages; i++) {
var btn = document.createElement("button");
btn.type = "button";
btn.className = "featured-dot";
btn.setAttribute("data-featured-dot", String(i));
btn.setAttribute("aria-label", "Scroll to view " + (i + 1) + " of " + pages);
btn.setAttribute("aria-current", i === 0 ? "true" : "false");
dotsRoot.appendChild(btn);
}
}
function dots() {
return Array.prototype.slice.call(dotsRoot.querySelectorAll("[data-featured-dot]"));
}
function setActive(idx) {
dots().forEach(function (d, i) {
d.setAttribute("aria-current", i === idx ? "true" : "false");
});
}
function scrollLeftForEnd() {
return scrollLeftForView(viewCount() - 1);
}
// (Re)build dots now that we know how many pages exist.
rebuildDots();
if (container.getAttribute("data-featured-bound") !== "true") {
dotsRoot.addEventListener("click", function (ev) {
var target = ev.target;
if (!target || !target.getAttribute) return;
var raw = target.getAttribute("data-featured-dot");
if (raw == null) return;
var idx = parseInt(raw, 10);
if (isNaN(idx)) return;
var left = scrollLeftForView(idx);
container.scrollTo({ left: left, behavior: "smooth" });
});
var ticking = false;
function onScroll() {
if (ticking) return;
ticking = true;
window.requestAnimationFrame(function () {
ticking = false;
// Pick the nearest view to the current scroll position.
var maxIdx = viewCount() - 1;
if (maxIdx <= 0) {
setActive(0);
return;
}
var pos = container.scrollLeft;
var bestIdx = 0;
var bestDist = Infinity;
for (var i = 0; i <= maxIdx; i++) {
var left = scrollLeftForView(i);
var d = Math.abs(left - pos);
if (d < bestDist) {
bestDist = d;
bestIdx = i;
}
}
setActive(bestIdx);
});
}
container.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", function () {
applyCarouselSizing();
rebuildDots();
onScroll();
}, { passive: true });
container.setAttribute("data-featured-bound", "true");
}
// Initial state
setActive(0);
// Ensure the carousel starts at the first card after layout (avoid stale
// scroll restoration / snap landing on later cards after CSS changes).
window.requestAnimationFrame(function () {
applyCarouselSizing();
try {
container.scrollTo({ left: 0, behavior: "auto" });
} catch (e) {
container.scrollLeft = 0;
}
});
}
function initEuropeMap() {
var maps = document.querySelectorAll("[data-europe-map]");
if (!maps.length) return;