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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
|
// Package integrationtests runs end-to-end tests of the snonux generator pipeline.
// Each test creates temporary input/output directories, places fixture files, runs
// the full processor+generator pipeline, and asserts the expected outputs.
package integrationtests
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"image"
"image/color"
"image/color/palette"
"image/gif"
"image/jpeg"
"image/png"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"codeberg.org/snonux/snonux/internal/config"
"codeberg.org/snonux/snonux/internal/generator"
"codeberg.org/snonux/snonux/internal/processor"
"codeberg.org/snonux/snonux/internal/version"
)
var ctx = context.Background() //nolint:gochecknoglobals // test-only top-level helper used by every test in the file
// runPipeline executes both pipeline stages and returns the config used.
func runPipeline(t *testing.T, inputDir, outputDir string) *config.Config {
t.Helper()
cfg := &config.Config{
InputDir: inputDir,
OutputDir: outputDir,
BaseURL: "https://snonux.foo",
Theme: "neon",
}
_, err := processor.Run(ctx, cfg)
if err != nil {
t.Fatalf("processor.Run: %v", err)
}
if err := generator.Run(ctx, cfg); err != nil {
t.Fatalf("generator.Run: %v", err)
}
return cfg
}
// makeDirs creates temporary input and output directories for a test.
func makeDirs(t *testing.T) (inputDir, outputDir string) {
t.Helper()
base := t.TempDir()
inputDir = filepath.Join(base, "inbox")
outputDir = filepath.Join(base, "outdir")
if err := os.MkdirAll(inputDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(outputDir, 0o755); err != nil {
t.Fatal(err)
}
return inputDir, outputDir
}
// readFile is a helper that reads a file and fails the test on error.
func readFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(data)
}
// assertContains fails the test if content does not contain substr.
func assertContains(t *testing.T, content, substr, label string) {
t.Helper()
if !strings.Contains(content, substr) {
t.Errorf("%s: expected to contain %q\ngot:\n%s", label, substr, content[:min(len(content), 500)])
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// TestTxtInput verifies plain text files are converted to posts.
func TestTxtInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
if err := os.WriteFile(filepath.Join(inputDir, "hello.txt"), []byte("Hello, Nexus!"), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
// Source file should have been removed after processing.
if _, err := os.Stat(filepath.Join(inputDir, "hello.txt")); !os.IsNotExist(err) {
t.Error("source file should have been deleted from input dir")
}
// A post directory should exist under outdir/posts/.
entries, err := os.ReadDir(filepath.Join(outputDir, "posts"))
if err != nil {
t.Fatalf("read posts dir: %v", err)
}
if len(entries) != 1 {
t.Fatalf("expected 1 post dir, got %d", len(entries))
}
// index.html must contain the post text.
index := readFile(t, filepath.Join(outputDir, "index.html"))
assertContains(t, index, "Hello, Nexus!", "index.html")
// splash WebGL canvas is part of the per-theme splash markup baked in.
assertContains(t, index, "splash-gl-canvas", "index.html splash WebGL canvas")
assertContains(t, index, `href="atom.xml"`, "index.html atom feed link")
// shared bundles must also be written.
if _, err := os.Stat(filepath.Join(outputDir, "shared.css")); err != nil {
t.Fatalf("shared.css missing: %v", err)
}
if _, err := os.Stat(filepath.Join(outputDir, "shared.js")); err != nil {
t.Fatalf("shared.js missing: %v", err)
}
}
// TestMarkdownInput verifies Markdown files are converted to HTML.
func TestMarkdownInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
md := "# Hello Nexus\n\nThis is **bold** text."
if err := os.WriteFile(filepath.Join(inputDir, "post.md"), []byte(md), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
index := readFile(t, filepath.Join(outputDir, "index.html"))
assertContains(t, index, "<strong>bold</strong>", "index.html markdown bold")
assertContains(t, index, "<h1>", "index.html markdown h1")
}
// assertStandaloneImagePost checks index.html and posts/<id>/image.jpg after a lone image input.
func assertStandaloneImagePost(t *testing.T, outputDir string) {
t.Helper()
index := readFile(t, filepath.Join(outputDir, "index.html"))
assertContains(t, index, `<img`, "index.html image tag")
assertContains(t, index, `image.jpg`, "index.html image filename")
postDirs, err := os.ReadDir(filepath.Join(outputDir, "posts"))
if err != nil {
t.Fatalf("read posts dir: %v", err)
}
if len(postDirs) != 1 {
t.Fatalf("expected 1 post, got %d", len(postDirs))
}
imgPath := filepath.Join(outputDir, "posts", postDirs[0].Name(), "image.jpg")
if _, err := os.Stat(imgPath); err != nil {
t.Errorf("expected image.jpg in post dir: %v", err)
}
}
// TestPNGInput verifies .png files are converted to JPEG posts and embedded in pages.
func TestPNGInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
writeSamplePNG(t, filepath.Join(inputDir, "photo.png"))
runPipeline(t, inputDir, outputDir)
assertStandaloneImagePost(t, outputDir)
}
// TestJPGInput verifies .jpg files are processed the same way as PNG.
func TestJPGInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
writeSampleJPEG(t, filepath.Join(inputDir, "photo.jpg"))
runPipeline(t, inputDir, outputDir)
assertStandaloneImagePost(t, outputDir)
}
// TestJPEGInput verifies the .jpeg extension is accepted.
func TestJPEGInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
writeSampleJPEG(t, filepath.Join(inputDir, "snapshot.jpeg"))
runPipeline(t, inputDir, outputDir)
assertStandaloneImagePost(t, outputDir)
}
// TestGIFInput verifies .gif files are decoded (first frame) and output as JPEG.
func TestGIFInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
writeSampleGIF(t, filepath.Join(inputDir, "anim.gif"))
runPipeline(t, inputDir, outputDir)
assertStandaloneImagePost(t, outputDir)
}
// TestAudioInput verifies .mp3 files are copied and an audio element is generated.
func TestAudioInput(t *testing.T) {
inputDir, outputDir := makeDirs(t)
// Write a minimal non-empty file as a stand-in for MP3 content.
if err := os.WriteFile(filepath.Join(inputDir, "track.mp3"), []byte("ID3fake"), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
index := readFile(t, filepath.Join(outputDir, "index.html"))
assertContains(t, index, `<audio`, "index.html audio tag")
assertContains(t, index, `track.mp3`, "index.html audio filename")
}
// TestMarkdownWithImage verifies that a Markdown post referencing a local image
// copies the image into the post dir and updates the src path.
func TestMarkdownWithImage(t *testing.T) {
inputDir, outputDir := makeDirs(t)
md := "Look at this:\n\n\n"
if err := os.WriteFile(filepath.Join(inputDir, "post.md"), []byte(md), 0o644); err != nil {
t.Fatal(err)
}
writeSamplePNG(t, filepath.Join(inputDir, "photo.png"))
runPipeline(t, inputDir, outputDir)
postDirs, _ := os.ReadDir(filepath.Join(outputDir, "posts"))
if len(postDirs) != 1 {
t.Fatalf("expected 1 post, got %d", len(postDirs))
}
// The referenced image should be copied into the post dir.
imgPath := filepath.Join(outputDir, "posts", postDirs[0].Name(), "photo.png")
if _, err := os.Stat(imgPath); err != nil {
t.Errorf("expected photo.png in post dir: %v", err)
}
}
// TestPagination verifies that 45 posts are split across two pages (42 + 3).
func TestPagination(t *testing.T) {
inputDir, outputDir := makeDirs(t)
for i := 0; i < 45; i++ {
name := fmt.Sprintf("post%02d.txt", i)
content := fmt.Sprintf("Post number %d", i)
if err := os.WriteFile(filepath.Join(inputDir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
runPipeline(t, inputDir, outputDir)
// index.html should exist and contain 42 posts.
index := readFile(t, filepath.Join(outputDir, "index.html"))
if count := strings.Count(index, `class="post"`); count != 42 {
t.Errorf("index.html: expected 42 posts, got %d", count)
}
// page2.html should exist and contain 3 posts.
page2 := readFile(t, filepath.Join(outputDir, "page2.html"))
if count := strings.Count(page2, `class="post"`); count != 3 {
t.Errorf("page2.html: expected 3 posts, got %d", count)
}
}
// TestPaginationNavLinks verifies prev/next navigation links are positioned correctly.
func TestPaginationNavLinks(t *testing.T) {
inputDir, outputDir := makeDirs(t)
for i := 0; i < 45; i++ {
if err := os.WriteFile(filepath.Join(inputDir, fmt.Sprintf("p%02d.txt", i)), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
}
runPipeline(t, inputDir, outputDir)
index := readFile(t, filepath.Join(outputDir, "index.html"))
// index.html (page 1) has no prev, should have next link (page2.html).
assertContains(t, index, "page2.html", "index.html next link")
if strings.Contains(index, "NEWER TRANSMISSIONS") {
t.Error("index.html should not have a prev-page link")
}
page2 := readFile(t, filepath.Join(outputDir, "page2.html"))
// page2.html should have a prev link to index with splash=0 (keyboard nav has no reliable Referer).
assertContains(t, page2, `href="index.html?splash=0"`, "page2.html prev href skips splash")
assertContains(t, page2, "NEWER TRANSMISSIONS", "page2.html prev link")
if strings.Contains(page2, "OLDER TRANSMISSIONS") {
t.Error("page2.html should not have a next-page link")
}
}
// TestAtomFeed verifies that atom.xml is well-formed and contains ≤42 entries.
func TestAtomFeed(t *testing.T) {
inputDir, outputDir := makeDirs(t)
for i := 0; i < 5; i++ {
if err := os.WriteFile(filepath.Join(inputDir, fmt.Sprintf("p%d.txt", i)), []byte("feed post"), 0o644); err != nil {
t.Fatal(err)
}
}
runPipeline(t, inputDir, outputDir)
atomPath := filepath.Join(outputDir, "atom.xml")
data, err := os.ReadFile(atomPath)
if err != nil {
t.Fatalf("read atom.xml: %v", err)
}
// Validate well-formed XML.
var feed struct {
XMLName xml.Name `xml:"feed"`
Entries []struct {
Title string `xml:"title"`
} `xml:"entry"`
}
if err := xml.Unmarshal(data, &feed); err != nil {
t.Fatalf("atom.xml not valid XML: %v", err)
}
if len(feed.Entries) != 5 {
t.Errorf("expected 5 entries in atom.xml, got %d", len(feed.Entries))
}
}
// TestInputCleanup verifies all source files are removed from the input dir.
func TestInputCleanup(t *testing.T) {
inputDir, outputDir := makeDirs(t)
for _, name := range []string{"a.txt", "b.txt", "c.txt"} {
if err := os.WriteFile(filepath.Join(inputDir, name), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
}
runPipeline(t, inputDir, outputDir)
entries, _ := os.ReadDir(inputDir)
if len(entries) != 0 {
t.Errorf("input dir should be empty after processing, got %d files", len(entries))
}
}
// TestKeyboardNavJS verifies that the generated HTML includes navigation attributes
// and that the shared JS binds the correct hotkeys.
func TestKeyboardNavJS(t *testing.T) {
inputDir, outputDir := makeDirs(t)
if err := os.WriteFile(filepath.Join(inputDir, "nav.txt"), []byte("nav test"), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
index := readFile(t, filepath.Join(outputDir, "index.html"))
assertContains(t, index, `data-index="0"`, "index.html data-index attribute")
// Shared CSS and JS now live as separate files referenced from the shell.
sharedCSS := readFile(t, filepath.Join(outputDir, "shared.css"))
assertContains(t, sharedCSS, `.post-active`, "shared.css .post-active rule")
sharedJS := readFile(t, filepath.Join(outputDir, "shared.js"))
assertContains(t, sharedJS, `playNavSound`, "shared.js playNavSound function")
// Final shortcut mapping: p = ambient playback start/pause, f = flash.
assertContains(t, sharedJS, "case 'p':", "shared.js p key handler")
assertContains(t, sharedJS, "toggleAmbientMode();", "shared.js p toggles ambient")
assertContains(t, sharedJS, "case 'f':", "shared.js f key handler")
assertContains(t, sharedJS, "triggerFlashEffect();", "shared.js f triggers flash")
// Nav hints and splash hints should display the updated keys.
assertContains(t, index, "<kbd>p</kbd><span class=\"sno-btn-text\">music</span>", "index.html nav hint p=ambient")
assertContains(t, index, "<kbd>f</kbd><span class=\"sno-btn-text\">flash</span>", "index.html nav hint f=flash")
}
// TestSplashMusicChoiceMarkup verifies (task js0) that the generated shared.js
// injects an explicit "with music" / "without music" choice into the splash
// overlay, and that shared.css styles it. The buttons are added at runtime
// (identically for every theme) rather than baked into each theme's
// splash_inner_html, so this asserts on the generated JS/CSS rather than on
// index.html markup.
func TestSplashMusicChoiceMarkup(t *testing.T) {
inputDir, outputDir := makeDirs(t)
if err := os.WriteFile(filepath.Join(inputDir, "splash-music.txt"), []byte("splash music choice test"), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
sharedJS := readFile(t, filepath.Join(outputDir, "shared.js"))
assertContains(t, sharedJS, "function snonuxRenderSplashMusicChoice()", "shared.js defines the splash music choice injector")
assertContains(t, sharedJS, "splash-music-choice", "shared.js references the splash-music-choice container class")
assertContains(t, sharedJS, `data-sno-music="on"`, "shared.js with-music button markup")
assertContains(t, sharedJS, `data-sno-music="off"`, "shared.js without-music button markup")
assertContains(t, sharedJS, "snonuxAmbientSavePreference(withMusic)", "shared.js saves the chosen preference")
// Re-injected after both places that replace #splash-overlay's innerHTML
// wholesale (theme switch at runtime, and theme-meta application on load
// when a visitor's saved theme differs from the page's baked-in default),
// otherwise those choice buttons would silently disappear again. Assert
// the exact count (not just presence) so a regression that drops one of
// the two call sites doesn't hide behind the other still matching.
reinjectLine := "if (typeof snonuxRenderSplashMusicChoice === 'function') snonuxRenderSplashMusicChoice();"
if got := strings.Count(sharedJS, reinjectLine); got != 2 {
t.Errorf("shared.js re-injects splash music choice at %d call sites; want 2 (snonuxSwitchTheme + snonuxApplyThemeMeta)", got)
}
sharedCSS := readFile(t, filepath.Join(outputDir, "shared.css"))
assertContains(t, sharedCSS, ".splash-music-choice", "shared.css styles the splash music choice container")
assertContains(t, sharedCSS, ".splash-music-btn", "shared.css styles the splash music choice buttons")
}
// TestSplashMusicChoiceBrowser drives a real headless browser to verify (task
// js0) that clicking the splash's "without music" button dismisses the splash,
// persists the decline, and actually leaves the ambient engine stopped; that
// "with music" persists acceptance and actually starts the ambient engine;
// and that the choice buttons survive (and keep working after) something
// wiping #splash-overlay's innerHTML wholesale — the exact hazard
// snonuxSwitchTheme() and snonuxApplyThemeMeta() pose, since both replace it
// on the fly when a visitor's saved theme differs from the page default.
func TestSplashMusicChoiceBrowser(t *testing.T) {
chromium, ok := findChromium()
if !ok {
t.Skip("Chromium executable not found; skipping browser splash-music-choice test")
}
inputDir, outputDir := makeDirs(t)
if err := os.WriteFile(filepath.Join(inputDir, "splash-music-browser.txt"), []byte("splash music choice browser test"), 0o644); err != nil {
t.Fatal(err)
}
runPipeline(t, inputDir, outputDir)
writeSplashMusicChoiceBrowserHarness(t, outputDir)
testHTML := filepath.Join(outputDir, "splash-music-choice-test.html")
pageURL := url.URL{Scheme: "file", Path: testHTML}
out, err := exec.Command(
chromium,
"--headless",
"--disable-gpu",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-background-networking",
"--allow-file-access-from-files",
"--window-size=900,700",
"--virtual-time-budget=4000",
"--dump-dom",
pageURL.String(),
).CombinedOutput()
if err != nil {
t.Fatalf("run headless Chromium: %v\n%s", err, string(out))
}
dom := string(out)
if !strings.Contains(dom, `data-splash-music-test="pass"`) {
t.Fatalf("splash music choice behavior failed; DOM dump tail:\n%s", dom[max(0, len(dom)-3000):])
}
}
// writeSplashMusicChoiceBrowserHarness clones index.html (stripping CDN
// assets unreachable from a file:// context, same as the scroll-selection
// harness) and appends a script that exercises both splash music choice
// buttons in sequence, recording pass/fail on document.body.
func writeSplashMusicChoiceBrowserHarness(t *testing.T, outputDir string) {
t.Helper()
indexPath := filepath.Join(outputDir, "index.html")
html := readFile(t, indexPath)
html = strings.ReplaceAll(html, `<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>`, "")
html = strings.ReplaceAll(html, `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">`, "")
html = strings.Replace(html,
`<script src="shared.js" defer></script>`,
`<script src="shared.js" defer></script>`+"\n"+
` <script src="splash-music-choice-test.js" defer></script>`,
1,
)
if err := os.WriteFile(filepath.Join(outputDir, "splash-music-choice-test.html"), []byte(html), 0o644); err != nil {
t.Fatalf("write splash-music-choice-test.html: %v", err)
}
harness := `
(function () {
function finish(status, detail) {
document.body.setAttribute('data-splash-music-test', status);
var pre = document.createElement('pre');
pre.id = 'splash-music-test-result';
pre.textContent = detail;
document.body.appendChild(pre);
}
function ambientPref() {
try { return localStorage.getItem('snonuxAmbientEnabled'); } catch (_) { return null; }
}
function ambientPlaying() {
return !!(window.snonuxAmbientIsPlaying && window.snonuxAmbientIsPlaying());
}
function findButtons(overlay) {
return {
on: overlay.querySelector('.splash-music-btn[data-sno-music="on"]'),
off: overlay.querySelector('.splash-music-btn[data-sno-music="off"]')
};
}
function run() {
var overlay = document.getElementById('splash-overlay');
var btns = overlay && findButtons(overlay);
if (!overlay || !btns.on || !btns.off) {
finish('fail', 'missing splash overlay or music-choice buttons');
return;
}
// Negative path: decline music. Should dismiss the splash, persist
// '0', and actually leave the ambient engine stopped (not just the
// localStorage side effect).
try { localStorage.removeItem('snonuxAmbientEnabled'); } catch (_) {}
btns.off.click();
var declinedDismissed = overlay.classList.contains('splash--dismissed');
var declinedPref = ambientPref();
var declinedPlaying = ambientPlaying();
// Re-open the splash (buttons must still be attached and working)
// so the positive path starts from a clean slate.
if (window._snonuxShowSplash) window._snonuxShowSplash();
var reopened = !overlay.classList.contains('splash--dismissed');
// Positive path: accept music. Should dismiss the splash, persist
// '1', and actually start the ambient engine.
btns.on.click();
var acceptedDismissed = overlay.classList.contains('splash--dismissed');
var acceptedPref = ambientPref();
var acceptedPlaying = ambientPlaying();
// Simulate the hazard the re-injection fix guards against:
// snonuxSwitchTheme()/snonuxApplyThemeMeta() replace #splash-overlay's
// entire innerHTML with a fresh theme's markup on the fly, which wipes
// out anything appended to it — including these choice buttons. Drop
// just the choice element (same end state as that wholesale replace)
// and confirm the exported re-injector rebuilds a single, live copy.
var inner = overlay.querySelector('.splash-inner');
var choiceBeforeWipe = inner && inner.querySelector('.splash-music-choice');
if (choiceBeforeWipe) choiceBeforeWipe.remove();
var wiped = !overlay.querySelector('.splash-music-choice');
if (window.snonuxRenderSplashMusicChoice) window.snonuxRenderSplashMusicChoice();
var rebuilt = overlay.querySelectorAll('.splash-music-choice').length === 1;
// The rebuilt buttons must be freshly wired, not stale references —
// re-fetch them and exercise the decline path once more.
try { localStorage.removeItem('snonuxAmbientEnabled'); } catch (_) {}
if (window._snonuxShowSplash) window._snonuxShowSplash();
var rebuiltBtns = findButtons(overlay);
var rebuiltBtnsFound = !!(rebuiltBtns.on && rebuiltBtns.off);
if (rebuiltBtnsFound) rebuiltBtns.off.click();
var rebuiltDismissed = overlay.classList.contains('splash--dismissed');
var rebuiltPref = ambientPref();
// The prior scenario left the engine playing (acceptedPlaying), so this
// decline must flip it back off too — not just the localStorage side effect.
var rebuiltPlaying = ambientPlaying();
// Regression check for the keyboard-focus fix: the document-level
// splash keydown handler used to unconditionally preventDefault()
// and dismiss on Enter/Space whenever the splash was open, which
// swallows the native "activate the focused button" default action
// a keyboard-only visitor relies on to actually press one of these
// buttons. A trusted, browser-synthesized key press can't be faked
// from page script, but we can verify the property our fix controls
// directly: with a music button focused, our handler must leave the
// event un-prevented and must not itself dismiss the splash, so the
// browser is free to run its native button-activation default action.
if (window._snonuxShowSplash) window._snonuxShowSplash();
rebuiltBtns.off.focus();
var focusedButtonIsActive = document.activeElement === rebuiltBtns.off;
var enterEvent = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true });
rebuiltBtns.off.dispatchEvent(enterEvent);
var keydownPreventedByUs = enterEvent.defaultPrevented;
var dismissedByGenericKeydown = overlay.classList.contains('splash--dismissed');
var detail = 'declinedDismissed=' + declinedDismissed + ' declinedPref=' + declinedPref +
' declinedPlaying=' + declinedPlaying +
' reopened=' + reopened +
' acceptedDismissed=' + acceptedDismissed + ' acceptedPref=' + acceptedPref +
' acceptedPlaying=' + acceptedPlaying +
' wiped=' + wiped + ' rebuilt=' + rebuilt +
' rebuiltBtnsFound=' + rebuiltBtnsFound +
' rebuiltDismissed=' + rebuiltDismissed + ' rebuiltPref=' + rebuiltPref +
' rebuiltPlaying=' + rebuiltPlaying +
' focusedButtonIsActive=' + focusedButtonIsActive +
' keydownPreventedByUs=' + keydownPreventedByUs +
' dismissedByGenericKeydown=' + dismissedByGenericKeydown;
var pass = declinedDismissed && declinedPref === '0' && !declinedPlaying &&
reopened &&
acceptedDismissed && acceptedPref === '1' && acceptedPlaying &&
wiped && rebuilt &&
rebuiltBtnsFound && rebuiltDismissed && rebuiltPref === '0' && !rebuiltPlaying &&
focusedButtonIsActive && !keydownPreventedByUs && !dismissedByGenericKeydown;
finish(pass ? 'pass' : 'fail', detail);
}
if (document.readyState === 'complete') run();
else window.addEventListener('load', run);
})();
`
if err := os.WriteFile(filepath.Join(outputDir, "splash-music-choice-test.js"), []byte(harness), 0o644); err != nil {
t.Fatalf("write splash-music-choice-test.js: %v", err)
}
}
// TestScrollDrivenPostSelection verifies the generated page behavior in a real
// browser: scrolling the post container moves .post-active to the article
// nearest the container center.
func TestScrollDrivenPostSelection(t *testing.T) {
chromium, ok := findChromium()
if !ok {
t.Skip("Chromium executable not found; skipping browser scroll-selection test")
}
inputDir, outputDir := makeDirs(t)
for i := 0; i < 24; i++ {
name := fmt.Sprintf("scroll-post-%02d.txt", i)
content := fmt.Sprintf("Scroll selection fixture post %02d\n\n%s", i, strings.Repeat("body line\n", 6))
if err := os.WriteFile(filepath.Join(inputDir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
runPipeline(t, inputDir, outputDir)
writeScrollSelectionBrowserHarness(t, outputDir)
testHTML := filepath.Join(outputDir, "scroll-selection-test.html")
pageURL := url.URL{Scheme: "file", Path: testHTML}
out, err := exec.Command(
chromium,
"--headless",
"--disable-gpu",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-background-networking",
"--allow-file-access-from-files",
"--window-size=900,700",
"--virtual-time-budget=4000",
"--dump-dom",
pageURL.String(),
).CombinedOutput()
if err != nil {
t.Fatalf("run headless Chromium: %v\n%s", err, string(out))
}
dom := string(out)
if !strings.Contains(dom, `data-scroll-selection-test="pass"`) {
t.Fatalf("scroll-driven post selection failed; result=%q DOM dump tail:\n%s",
scrollSelectionBrowserResult(dom), dom[max(0, len(dom)-3000):])
}
}
func findChromium() (string, bool) {
for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"} {
path, err := exec.LookPath(name)
if err == nil {
return path, true
}
}
return "", false
}
func writeScrollSelectionBrowserHarness(t *testing.T, outputDir string) {
t.Helper()
indexPath := filepath.Join(outputDir, "index.html")
html := readFile(t, indexPath)
html = strings.ReplaceAll(html, `<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>`, "")
html = strings.ReplaceAll(html, `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|