concinnity-cook 0.19.0

Authored world model, validation, and the asset cook pipeline that bakes a Concinnity world into a blob
Documentation
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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
use super::emit::{CHOICE_BOX_RADIUS, DIALOG_BOX_RADIUS};
use super::helpers::{slug, wrap_text};
use super::*;

const CROSSROADS: &str = r#"---
title: The Crossroads
characters:
  ayame: { name: "Ayame", color: [1.0, 0.85, 0.8] }
  keeper: Innkeeper
---

# inn

You wake at a roadside inn. A note rests on the pillow.

**keeper:** Slept well? Someone left that for you.

# The Crossroads

The signpost points two ways.

- [Into the wood](#wood)
- [Toward the shore](#the-crossroads)

# wood

**ayame:** You came. I wasn't sure you would.

[The morning comes.](#ending)

# ending

You walk together toward the morning.
"#;

// Fixed portrait-shaped dimensions so emission tests need no image files.
fn stub_dims(_path: &str) -> Result<(u32, u32), String> {
    Ok((456, 700))
}

fn find<'a>(entries: &'a [serde_json::Value], name: &str) -> &'a serde_json::Value {
    entries
        .iter()
        .find(|e| asset_name(e) == name)
        .unwrap_or_else(|| panic!("missing entry '{}'", name))
}

fn action(entry: &serde_json::Value) -> &str {
    entry["args"]["action"].as_str().unwrap_or("")
}

#[test]
fn passes_through_without_imports() {
    let mut assets = vec![serde_json::json!({"name":"x","type":"Logger","args":{}})];
    expand_stories(&mut assets).unwrap();
    assert_eq!(assets.len(), 1);
    assert_eq!(assets[0]["type"], "Logger");
}

#[test]
fn missing_source_is_an_error() {
    let mut assets = vec![serde_json::json!({
        "name": "story", "type": "StoryImport", "args": {}
    })];
    let err = expand_stories(&mut assets).unwrap_err();
    assert!(err.contains("missing `source`"));
}

// An import with no args at all is the same missing-source failure.
#[test]
fn an_import_without_args_is_a_missing_source() {
    let mut assets = vec![serde_json::json!({"name":"story","type":"StoryImport"})];
    let err = expand_stories(&mut assets).unwrap_err();
    assert_eq!(err, "StoryImport 'story': missing `source`");
}

#[test]
fn unreadable_source_file_is_an_error() {
    let mut assets = vec![serde_json::json!({
        "name": "story", "type": "StoryImport",
        "args": {"source": "/no/such/story.md"}
    })];
    let err = expand_stories(&mut assets).unwrap_err();
    assert!(err.contains("cannot read"), "{err}");
    assert!(err.contains("/no/such/story.md"), "{err}");
}

#[test]
fn parse_failure_is_wrapped_with_import_context() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad.md");
    // Frontmatter with no `title` fails story parsing.
    std::fs::write(&path, "---\ncharacters:\n---\n\n# a\n\nhi\n").unwrap();
    let mut assets = vec![serde_json::json!({
        "name": "story", "type": "StoryImport",
        "args": {"source": path.to_str().unwrap()}
    })];
    let err = expand_stories(&mut assets).unwrap_err();
    assert!(err.contains("StoryImport 'story'"), "{err}");
    assert!(err.contains("title"), "{err}");
}

#[test]
fn parses_frontmatter_nodes_and_flow() {
    let story = parse_story(CROSSROADS).unwrap();
    assert_eq!(story.title, "The Crossroads");
    assert_eq!(story.characters["ayame"].name, "Ayame");
    assert_eq!(story.characters["ayame"].color, [1.0, 0.85, 0.8]);
    assert_eq!(story.characters["keeper"].name, "Innkeeper");
    assert_eq!(story.characters["keeper"].color, [1.0, 1.0, 1.0]);

    let slugs: Vec<&str> = story.nodes.iter().map(|n| n.slug.as_str()).collect();
    assert_eq!(slugs, ["inn", "the-crossroads", "wood", "ending"]);

    let inn = &story.nodes[0];
    assert_eq!(inn.pages.len(), 2);
    assert_eq!(inn.pages[1].speaker.as_deref(), Some("keeper"));

    let crossroads = &story.nodes[1];
    assert_eq!(crossroads.choices.len(), 2);
    assert_eq!(crossroads.choices[0].target, "wood");
    assert_eq!(crossroads.choices[1].target, "the-crossroads");

    let wood = &story.nodes[2];
    assert_eq!(wood.pages[1].jump.as_deref(), Some("ending"));
    assert_eq!(wood.pages[1].text, "The morning comes.");
}

#[test]
fn emits_the_compiled_graph_and_stage() {
    let story = parse_story(CROSSROADS).unwrap();
    let entries = emit_story("story", &story, true, 30.0, &stub_dims).unwrap();

    // The title screen is initial and starts the story system.
    let title = find(&entries, "story_title");
    assert_eq!(title["args"]["initial"], true);
    assert_eq!(
        action(find(&entries, "story_title_start_btn")),
        "story:start"
    );

    // The compiled graph takes the import's own name. Speakers resolve
    // to display name + color, jump and choice targets to node indices,
    // and the reveal speed rides along.
    let graph = &find(&entries, "story")["args"];
    assert_eq!(graph["title"], "The Crossroads");
    assert_eq!(graph["text_speed"], 30.0);
    let nodes = graph["nodes"].as_array().unwrap();
    assert_eq!(nodes.len(), 4);
    let plate = &nodes[0]["pages"][1]["speaker"];
    assert_eq!(plate["name"], "Innkeeper");
    assert_eq!(nodes[1]["choices"][0]["label"], "Into the wood");
    assert_eq!(nodes[1]["choices"][0]["target"], 2);
    assert_eq!(nodes[1]["choices"][1]["target"], 1);
    assert_eq!(nodes[2]["pages"][1]["text"], "The morning comes.");
    assert_eq!(nodes[2]["pages"][1]["jump"], 3);

    // One stage screen carries the whole story: backdrop, portrait slots,
    // dialog furniture, the advance region, and one button per option of
    // the widest choice menu (disabled until the story reaches one).
    assert_eq!(find(&entries, "story_stage")["args"]["initial"], false);
    assert_eq!(find(&entries, "story_stage_bg")["args"]["fit"], "cover");
    assert_eq!(
        find(&entries, "story_stage_center")["args"]["visible"],
        false
    );
    assert_eq!(
        action(find(&entries, "story_stage_advance")),
        "story:advance"
    );
    // Space and Enter both advance the dialogue.
    assert_eq!(find(&entries, "story_advance_key")["args"]["key"], "Space");
    assert_eq!(
        find(&entries, "story_advance_key")["args"]["action"],
        "story:advance"
    );
    assert_eq!(
        find(&entries, "story_advance_key_enter")["args"]["key"],
        "Enter"
    );
    assert_eq!(
        find(&entries, "story_advance_key_enter")["args"]["action"],
        "story:advance"
    );
    let opt0 = find(&entries, "story_stage_opt0_btn");
    assert_eq!(action(opt0), "story:choose:0");
    assert_eq!(
        find(&entries, "story_stage_opt0_lbl")["args"]["visible"],
        false
    );

    // The scaffold block names the generated stage assets; the build
    // resolves these to ids so the compiled blob never needs the names.
    let scaffold = &graph["scaffold"];
    assert_eq!(scaffold["screen"], "story_stage");
    assert_eq!(scaffold["ending"], "story_ending");
    assert_eq!(scaffold["text_label"], "story_stage_text");
    assert_eq!(scaffold["option_boxes"][0], "story_stage_opt0_box");
    assert_eq!(scaffold["options"][0], "story_stage_opt0_lbl");
    assert_eq!(scaffold["options"].as_array().unwrap().len(), 2);

    // Each option slot gets its own rounded box behind the label, and the
    // dialog box sits nearly flush with the canvas bottom with the name
    // plate inside its bounds.
    let opt0_box = find(&entries, "story_stage_opt0_box");
    assert_eq!(opt0_box["args"]["corner_radius"], CHOICE_BOX_RADIUS);
    assert_eq!(opt0_box["args"]["tint"][3], 0.0);
    let dialog = &find(&entries, "story_stage_box")["args"];
    assert_eq!(dialog["corner_radius"], DIALOG_BOX_RADIUS);
    let box_bottom = dialog["y"].as_f64().unwrap() + dialog["height"].as_f64().unwrap();
    assert!((700.0..=720.0).contains(&box_bottom));
    let name = &find(&entries, "story_stage_name")["args"];
    assert!(name["y"].as_f64().unwrap() > dialog["y"].as_f64().unwrap());
    let text = &find(&entries, "story_stage_text")["args"];
    assert!(text["y"].as_f64().unwrap() > name["y"].as_f64().unwrap());
    assert!(!entries.iter().any(|e| asset_name(e).contains("_panel")));

    // Quick row, advance marker, overlay furniture, and slot rows all
    // exist and start hidden; the title screen offers Load.
    assert_eq!(
        action(find(&entries, "story_stage_qauto_btn")),
        "story:auto"
    );
    assert_eq!(action(find(&entries, "story_stage_qlog_btn")), "story:log");
    assert_eq!(
        action(find(&entries, "story_stage_qskip_btn")),
        "story:skip"
    );
    assert_eq!(
        action(find(&entries, "story_stage_qsave_btn")),
        "story:save"
    );
    assert_eq!(find(&entries, "story_stage_marker")["args"]["tint"][3], 0.0);
    assert_eq!(find(&entries, "story_stage_dim")["args"]["tint"][3], 0.0);
    assert_eq!(find(&entries, "story_stage_history")["args"]["content"], "");
    assert_eq!(
        action(find(&entries, "story_stage_slot2_btn")),
        "story:slot:2"
    );
    assert_eq!(
        find(&entries, "story_stage_slot0_box")["args"]["tint"][3],
        0.0
    );
    assert_eq!(action(find(&entries, "story_title_load_btn")), "story:load");
    // Five slot rows are emitted (the story scrolls this window over more
    // logical slots); each row's action carries its row index.
    assert_eq!(scaffold["slot_labels"].as_array().unwrap().len(), 5);
    assert_eq!(
        action(find(&entries, "story_stage_slot4_btn")),
        "story:slot:4"
    );
    assert_eq!(scaffold["advance_marker"], "story_stage_marker");
    assert_eq!(scaffold["title"], "story_title");
    assert!(
        entries
            .iter()
            .any(|e| asset_name(e) == "story_stage_opt1_btn")
    );
    assert!(
        !entries
            .iter()
            .any(|e| asset_name(e) == "story_stage_opt2_btn")
    );

    // No per-page screens or audio cues remain.
    assert!(!entries.iter().any(|e| asset_name(e).contains("_n_")));
    assert!(!entries.iter().any(|e| type_norm(e) == "audiocue"));

    // The ending returns to the title screen.
    assert_eq!(
        action(find(&entries, "story_ending_back_btn")),
        "screen:show:story_title"
    );
}

#[test]
fn no_title_screen_makes_the_stage_initial() {
    let story = parse_story(CROSSROADS).unwrap();
    let entries = emit_story("story", &story, false, 45.0, &stub_dims).unwrap();
    assert!(!entries.iter().any(|e| asset_name(e) == "story_title"));
    assert_eq!(find(&entries, "story_stage")["args"]["initial"], true);
    let back = find(&entries, "story_ending_back_btn");
    assert_eq!(action(back), "story:start");
    assert_eq!(
        find(&entries, "story_ending_back_lbl")["args"]["content"],
        "Restart"
    );
}

// The dialog furniture is bottom-anchored, its labels centered/aligned,
// and the title menu buttons follow their labels so the story can lay the
// menu out at runtime.
#[test]
fn dialog_is_bottom_anchored_and_title_buttons_follow() {
    let story = parse_story(CROSSROADS).unwrap();
    let entries = emit_story("story", &story, true, 30.0, &stub_dims).unwrap();

    // The box, its text, its marker, and the quick row all hug the bottom.
    assert_eq!(find(&entries, "story_stage_box")["args"]["fit"], "bottom");
    assert_eq!(find(&entries, "story_stage_text")["args"]["fit"], "bottom");
    assert_eq!(
        find(&entries, "story_stage_marker")["args"]["fit"],
        "bottom"
    );
    assert_eq!(
        find(&entries, "story_stage_qauto_btn")["args"]["fit"],
        "bottom"
    );

    // The heading and menu buttons center on their anchor with real
    // metrics; each title button's region follows its label.
    assert_eq!(
        find(&entries, "story_title_heading")["args"]["align"],
        "center"
    );
    let start = find(&entries, "story_title_start_btn");
    assert_eq!(start["args"]["follow_label"], true);
    assert_eq!(start["args"]["label"], "story_title_start_lbl");
    assert_eq!(
        find(&entries, "story_title_start_lbl")["args"]["align"],
        "center"
    );
    let scaffold = &find(&entries, "story")["args"]["scaffold"];
    assert_eq!(scaffold["start_label"], "story_title_start_lbl");
    assert_eq!(scaffold["quit_label"], "story_title_quit_lbl");

    // The title carries a Settings button (opening the settings screen through
    // the story) and its label is registered in the scaffold for the runtime
    // title-menu layout.
    let settings = find(&entries, "story_title_settings_btn");
    assert_eq!(settings["args"]["action"], "story:settings");
    assert_eq!(settings["args"]["label"], "story_title_settings_lbl");
    assert_eq!(scaffold["settings_label"], "story_title_settings_lbl");
}

// A `background` frontmatter draws the title menu over a full-bleed image
// (a cover-fit textured sprite + one Texture entry).
#[test]
fn menu_background_becomes_a_cover_sprite() {
    let src = CROSSROADS.replace(
        "title: The Crossroads\n",
        "title: The Crossroads\nbackground: assets/menu.png\n",
    );
    let story = parse_story(&src).unwrap();
    assert_eq!(story.background.as_deref(), Some("assets/menu.png"));
    let entries = emit_story("story", &story, true, 30.0, &stub_dims).unwrap();
    let bg = &find(&entries, "story_title_bg")["args"];
    assert_eq!(bg["fit"], "cover");
    // The backdrop image is dimmed (tint < 1) so the light title/menu text
    // stays readable over a bright photo.
    let tint = bg["tint"].as_array().unwrap();
    assert!(
        tint[0].as_f64().unwrap() < 1.0,
        "backdrop should be dimmed, got {tint:?}"
    );
    let texture = bg["texture"].as_str().unwrap();
    let tex = find(&entries, texture);
    assert_eq!(type_norm(tex), "texture");
    assert_eq!(tex["args"]["source"], "assets/menu.png");
}

#[test]
fn expands_from_file_and_replaces_the_import() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("story.md");
    std::fs::write(&path, CROSSROADS).unwrap();
    let mut assets = vec![serde_json::json!({
        "name": "story", "type": "StoryImport",
        "args": {"source": path.to_str().unwrap()}
    })];
    expand_stories(&mut assets).unwrap();
    assert!(!assets.iter().any(|v| type_norm(v) == "storyimport"));
    assert!(assets.iter().any(|v| type_norm(v) == "screen"));
    assert!(assets.iter().any(|v| type_norm(v) == "hitregion"));
    assert!(assets.iter().any(|v| type_norm(v) == "font"));
}

#[test]
fn generated_name_collision_is_an_error() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("story.md");
    std::fs::write(&path, CROSSROADS).unwrap();
    let mut assets = vec![
        serde_json::json!({
            "name": "story", "type": "StoryImport",
            "args": {"source": path.to_str().unwrap()}
        }),
        serde_json::json!({"name":"story_title","type":"Screen","args":{}}),
    ];
    let err = expand_stories(&mut assets).unwrap_err();
    assert!(err.contains("collides"));
}

const SCORED: &str = r#"---
title: T
---

# inn

[music](assets/theme.ogg)

First page.

Second page.

[sound](assets/door.wav)

The door creaks.

# crossroads

[music](assets/tense.ogg)

- [Left](#inn)
- [Right](#crossroads)
"#;

#[test]
fn media_directives_parse_and_propagate() {
    let story = parse_story(SCORED).unwrap();
    let inn = &story.nodes[0];
    // Music persists from its directive across the following pages.
    assert_eq!(inn.pages[0].music.as_deref(), Some("assets/theme.ogg"));
    assert_eq!(inn.pages[1].music.as_deref(), Some("assets/theme.ogg"));
    // The one-shot attaches only to the page directly after it.
    assert!(inn.pages[1].sounds.is_empty());
    assert_eq!(inn.pages[2].sounds, ["assets/door.wav"]);
    // A pages-free choice node still carries the current music.
    let crossroads = &story.nodes[1];
    assert!(crossroads.pages.is_empty());
    assert_eq!(crossroads.choice_music.as_deref(), Some("assets/tense.ogg"));
}

#[test]
fn media_directives_compile_to_deduped_clip_names() {
    let story = parse_story(SCORED).unwrap();
    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();

    // Three distinct audio files -> three AudioClip entries; the theme is
    // deduplicated to one clip despite two pages sharing its music.
    let clips: Vec<&serde_json::Value> = entries
        .iter()
        .filter(|e| type_norm(e) == "audioclip")
        .collect();
    assert_eq!(clips.len(), 3);
    assert_eq!(clips[0]["args"]["source"], "assets/theme.ogg");

    // Pages carry the deduplicated clip names in the compiled graph.
    let nodes = &find(&entries, "s")["args"]["nodes"];
    assert_eq!(nodes[0]["pages"][0]["music"], clips[0]["name"]);
    assert_eq!(nodes[0]["pages"][1]["music"], clips[0]["name"]);

    // The one-shot lands on its page only.
    assert_eq!(nodes[0]["pages"][2]["sounds"][0], clips[1]["name"]);
    assert_eq!(nodes[0]["pages"][1]["sounds"].as_array().unwrap().len(), 0);

    // The choice menu carries the tense track.
    assert_eq!(nodes[1]["choice_music"], clips[2]["name"]);
}

#[test]
fn bg_directive_parses_propagates_and_emits_textured_backdrops() {
    let src = "---\ntitle: T\n---\n\n# inn\n\n![bg](assets/inn.png)\n\nFirst.\n\nSecond.\n\n# out\n\n![bg](assets/street.png)\n\n- [Stay](#inn)\n";
    let story = parse_story(src).unwrap();
    // The backdrop persists across the pages after its directive.
    assert_eq!(
        story.nodes[0].pages[0].stage.bg.as_deref(),
        Some("assets/inn.png")
    );
    assert_eq!(
        story.nodes[0].pages[1].stage.bg.as_deref(),
        Some("assets/inn.png")
    );
    // A pages-free choice node carries the current backdrop.
    assert_eq!(
        story.nodes[1].choice_stage.bg.as_deref(),
        Some("assets/street.png")
    );

    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();
    // Two distinct images -> two Texture entries.
    let textures: Vec<&serde_json::Value> = entries
        .iter()
        .filter(|e| type_norm(e) == "texture")
        .collect();
    assert_eq!(textures.len(), 2);
    assert_eq!(textures[0]["args"]["source"], "assets/inn.png");

    // Both pages of the node share the deduplicated texture in the
    // compiled graph; a full-canvas rectangle places the backdrop.
    let nodes = &find(&entries, "s")["args"]["nodes"];
    let bg = &nodes[0]["pages"][0]["stage"]["bg"];
    assert_eq!(bg["texture"], textures[0]["name"]);
    assert_eq!(bg["width"], 1280.0);
    assert_eq!(
        nodes[0]["pages"][1]["stage"]["bg"]["texture"],
        textures[0]["name"]
    );
    assert_eq!(
        nodes[1]["choice_stage"]["bg"]["texture"],
        textures[1]["name"]
    );

    // The title screen keeps its flat fill (no texture key at all).
    assert!(
        find(&entries, "s_title_bg")["args"]
            .get("texture")
            .is_none()
    );
}

#[test]
fn stacked_directives_in_one_paragraph_all_apply() {
    // Adjacent directive lines form one Markdown paragraph; all apply.
    let src = "---\ntitle: T\n---\n\n# a\n\n![bg](x.png)\n[music](m.ogg)\n[sound](s.wav)\n\nhi\n";
    let story = parse_story(src).unwrap();
    let page = &story.nodes[0].pages[0];
    assert_eq!(page.stage.bg.as_deref(), Some("x.png"));
    assert_eq!(page.music.as_deref(), Some("m.ogg"));
    assert_eq!(page.sounds, ["s.wav"]);
}

#[test]
fn jump_link_mixed_with_directives_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![bg](x.png)\n[go](#a)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("cannot share"), "{err}");
}

#[test]
fn portraits_persist_and_bg_change_clears_them() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![bg](room.png)\n![left](ana.png)\n\nOne.\n\n![right](ben.png)\n![center](cho.png)\n\nTwo.\n\n![bg](street.png)\n\nThree.\n";
    let story = parse_story(src).unwrap();
    let pages = &story.nodes[0].pages;
    // Page one: left portrait only.
    assert_eq!(pages[0].stage.left.as_deref(), Some("ana.png"));
    assert_eq!(pages[0].stage.center, None);
    assert_eq!(pages[0].stage.right, None);
    // Page two: the right and center portraits join; the left persists.
    assert_eq!(pages[1].stage.left.as_deref(), Some("ana.png"));
    assert_eq!(pages[1].stage.center.as_deref(), Some("cho.png"));
    assert_eq!(pages[1].stage.right.as_deref(), Some("ben.png"));
    // Page three: the scene change cleared every portrait.
    assert_eq!(pages[2].stage.bg.as_deref(), Some("street.png"));
    assert_eq!(pages[2].stage.left, None);
    assert_eq!(pages[2].stage.center, None);
    assert_eq!(pages[2].stage.right, None);
}

#[test]
fn portraits_compile_at_native_size_and_bottom_anchor() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![left](ana.png)\n\nhi\n";
    let story = parse_story(src).unwrap();
    // stub_dims reports 456x700: placed at native pixel size against the
    // 720 canvas, bottom-anchored; the cover-fit stage sprites put the
    // canvas bottom at the window bottom.
    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();
    let p = &find(&entries, "s")["args"]["nodes"][0]["pages"][0]["stage"]["left"];
    assert_eq!(p["width"], 456.0);
    assert_eq!(p["height"], 700.0);
    assert_eq!(p["y"], 20.0);
    let x = p["x"].as_f64().unwrap() as f32;
    assert!((x - (320.0 - 456.0 / 2.0)).abs() < 1e-3);
    // The portrait image becomes a Texture entry like a backdrop.
    assert_eq!(p["texture"], find(&entries, "s_img0")["name"]);
}

#[test]
fn oversized_portrait_scales_down_to_the_canvas_height() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![center](big.png)\n\nhi\n";
    let story = parse_story(src).unwrap();
    let dims = |_: &str| Ok((900u32, 1440u32));
    let entries = emit_story("s", &story, true, 45.0, &dims).unwrap();
    let p = &find(&entries, "s")["args"]["nodes"][0]["pages"][0]["stage"]["center"];
    // Taller than the canvas: clamped to 720 with the width following.
    assert_eq!(p["height"], 720.0);
    assert_eq!(p["width"], 450.0);
    assert_eq!(p["y"], 0.0);
    // Centered on the canvas.
    let x = p["x"].as_f64().unwrap() as f32;
    assert!((x - (640.0 - 450.0 / 2.0)).abs() < 1e-3);
}

#[test]
fn unknown_image_role_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![portrait](x.png)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("'portrait'"), "{err}");
    assert!(err.contains("![left]"), "{err}");
}

#[test]
fn non_image_bg_target_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![bg](x.gif)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("png/jpg/jpeg"), "{err}");
}

#[test]
fn image_mixed_with_text_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\nlook: ![bg](x.png)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("stand alone"), "{err}");
}

#[test]
fn trailing_bg_directive_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\nhi\n\n![bg](x.png)\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("needs a following"), "{err}");
}

#[test]
fn trailing_media_directive_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\nhi\n\n[sound](x.wav)\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("needs a following"), "{err}");
}

#[test]
fn bad_audio_label_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n[loop](x.ogg)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("`music`"), "{err}");
    assert!(err.contains("loop"), "{err}");
}

#[test]
fn non_audio_link_target_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n[music](x.txt)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("neither"), "{err}");
}

#[test]
fn choice_to_audio_file_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n- [music](x.ogg)\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("must link to a `#heading`"), "{err}");
}

#[test]
fn block_style_characters_parse() {
    let src = "---\ntitle: T\ncharacters:\n  ayame:\n    name: Ayame\n    color: [1.0, 0.85, 0.8]\n  keeper: Innkeeper\n---\n\n# a\n\n**ayame:** hi\n\n**keeper:** bye\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.characters["ayame"].name, "Ayame");
    assert_eq!(story.characters["ayame"].color, [1.0, 0.85, 0.8]);
    assert_eq!(story.characters["keeper"].name, "Innkeeper");
    assert_eq!(story.characters["keeper"].color, [1.0, 1.0, 1.0]);
}

#[test]
fn unquoted_flow_map_name_parses() {
    let src = "---\ntitle: T\ncharacters:\n  a: { name: Ayame Doe, color: [1, 1, 1] }\n---\n\n# n\n\n**a:** hi\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.characters["a"].name, "Ayame Doe");
}

#[test]
fn block_character_missing_name_is_an_error() {
    let src = "---\ntitle: T\ncharacters:\n  ayame:\n    color: [1, 1, 1]\n---\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("missing `name`"), "{err}");
    assert!(err.contains("ayame"), "{err}");
}

#[test]
fn block_character_unknown_key_is_an_error() {
    let src =
        "---\ntitle: T\ncharacters:\n  ayame:\n    name: Ayame\n    voice: low\n---\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("unknown character key 'voice'"), "{err}");
}

#[test]
fn fields_under_a_plain_character_are_an_error() {
    // `keeper: Innkeeper` is complete; a deeper line under it has no open
    // block to attach to.
    let src =
        "---\ntitle: T\ncharacters:\n  keeper: Innkeeper\n    color: [1, 1, 1]\n---\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("need an `id:` line"), "{err}");
}

#[test]
fn dangling_link_target_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n[go](#nowhere)\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("#nowhere"), "{err}");
}

#[test]
fn undeclared_speaker_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n**ghost:** boo\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("ghost"), "{err}");
    assert!(err.contains("line 7"), "{err}");
}

#[test]
fn duplicate_heading_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\nhi\n\n# a\n\nbye\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("duplicate"), "{err}");
}

#[test]
fn missing_title_is_an_error() {
    let src = "---\ncharacters:\n---\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("title"), "{err}");
}

#[test]
fn content_before_first_heading_is_an_error() {
    let src = "---\ntitle: T\n---\n\nno node yet\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("before the first"), "{err}");
}

#[test]
fn empty_node_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n# b\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("empty"), "{err}");
}

#[test]
fn unsupported_constructs_are_errors() {
    let base = "---\ntitle: T\n---\n\n# a\n\n";
    for (body, needle) in [
        ("```\ncode\n```\n", "script blocks use"),
        ("```rust\nlet x = 1;\n```\n", "script blocks use"),
        ("> quoted\n", "block quotes"),
        ("## sub\n", "headings"),
        ("*soft*\n", "emphasis"),
        ("1. [go](#a)\n", "bullet list"),
        ("see `code`\n", "inline code"),
    ] {
        let err = parse_story(&format!("{base}{body}")).unwrap_err();
        assert!(err.contains(needle), "{body:?} -> {err}");
    }
}

#[test]
fn mixed_link_and_text_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\ngo [here](#a) now\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("stand alone"), "{err}");
}

#[test]
fn content_after_choices_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n- [go](#a)\n\nafterthought\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("last content"), "{err}");
}

#[test]
fn script_blocks_parse_ops_gates_and_choice_conditions() {
    let src = "---\ntitle: T\n---\n\n# a\n\n```story\nset asked\nclear shy\nif asked -> #b\nif not shy -> #b\n```\n\nOne.\n\n- [Go](#b \"if asked\")\n- [Stay](#a \"if not shy\")\n- [Leave](#b)\n\n# b\n\nDone.\n";
    let story = parse_story(src).unwrap();
    let page = &story.nodes[0].pages[0];
    // Ops and gates attach to the page after the block, in order. Flag
    // syntax compiles to the numeric model: set = 1, clear = 0, a bare
    // test = "not zero", a `not` test = "zero".
    assert_eq!(page.ops.len(), 2);
    assert_eq!(page.ops[0].name, "asked");
    assert_eq!((page.ops[0].value, page.ops[0].add), (1, false));
    assert_eq!((page.ops[1].value, page.ops[1].add), (0, false));
    assert_eq!(page.gates.len(), 2);
    assert_eq!(page.gates[0].target, "b");
    assert_eq!(
        (page.gates[0].condition.op, page.gates[0].condition.value),
        ("ne", 0)
    );
    assert_eq!(
        (page.gates[1].condition.op, page.gates[1].condition.value),
        ("eq", 0)
    );
    // Link titles gate their choices; an untitled choice is unconditional.
    let choices = &story.nodes[0].choices;
    let c = choices[0].condition.as_ref().unwrap();
    assert_eq!(c.name, "asked");
    assert_eq!((c.op, c.value), ("ne", 0));
    assert_eq!(choices[1].condition.as_ref().unwrap().op, "eq");
    assert!(choices[2].condition.is_none());
}

#[test]
fn script_numeric_ops_and_comparisons_parse() {
    let src = "---\ntitle: T\n---\n\n# a\n\n```story\nset gold = 5\nadd gold -2\nif gold >= 3 -> #b\nif gold == 0 -> #b\nif gold != 1 -> #b\nif gold < 2 -> #b\nif gold <= 2 -> #b\nif gold > 2 -> #b\n```\n\nOne.\n\n- [Buy](#b \"if gold >= 3\")\n- [Beg](#b)\n\n# b\n\nDone.\n";
    let story = parse_story(src).unwrap();
    let page = &story.nodes[0].pages[0];
    assert_eq!(
        (
            page.ops[0].name.as_str(),
            page.ops[0].value,
            page.ops[0].add
        ),
        ("gold", 5, false)
    );
    assert_eq!((page.ops[1].value, page.ops[1].add), (-2, true));
    let ops: Vec<&str> = page.gates.iter().map(|g| g.condition.op).collect();
    assert_eq!(ops, vec!["ge", "eq", "ne", "lt", "le", "gt"]);
    assert_eq!(page.gates[0].condition.value, 3);
    let c = story.nodes[0].choices[0].condition.as_ref().unwrap();
    assert_eq!((c.name.as_str(), c.op, c.value), ("gold", "ge", 3));
}

#[test]
fn script_numeric_errors_are_strict() {
    let bad_amount = "---\ntitle: T\n---\n\n# a\n\n```story\nadd gold two\n```\n\nhi\n";
    assert!(parse_story(bad_amount).unwrap_err().contains("integer"));
    let missing_amount = "---\ntitle: T\n---\n\n# a\n\n```story\nadd gold\n```\n\nhi\n";
    assert!(parse_story(missing_amount).unwrap_err().contains("amount"));
    let bad_value = "---\ntitle: T\n---\n\n# a\n\n```story\nset gold = lots\n```\n\nhi\n";
    assert!(parse_story(bad_value).unwrap_err().contains("integer"));
    let bad_cmp = "---\ntitle: T\n---\n\n# a\n\n```story\nif gold >= many -> #a\n```\n\nhi\n";
    assert!(parse_story(bad_cmp).unwrap_err().contains("integer"));
}

#[test]
fn script_before_choices_attaches_to_the_menu() {
    let src = "---\ntitle: T\n---\n\n# a\n\nHi.\n\n```story\nset ready\nif done -> #b\n```\n\n- [Go](#b)\n\n# b\n\nDone.\n";
    let story = parse_story(src).unwrap();
    let node = &story.nodes[0];
    assert!(node.pages[0].ops.is_empty());
    assert_eq!(node.choice_ops.len(), 1);
    assert_eq!(node.choice_ops[0].name, "ready");
    assert_eq!(node.choice_gates.len(), 1);
    assert_eq!(node.choice_gates[0].target, "b");
}

#[test]
fn script_errors_are_strict() {
    // A malformed line, a bad flag name, a dangling gate target, a
    // trailing block with nothing to attach to, and a titled
    // non-choice link are all build errors.
    let bad_line = "---\ntitle: T\n---\n\n# a\n\n```story\nraise x\n```\n\nhi\n";
    assert!(parse_story(bad_line).unwrap_err().contains("is not `set"));
    let bad_flag = "---\ntitle: T\n---\n\n# a\n\n```story\nset Bad Flag\n```\n\nhi\n";
    assert!(
        parse_story(bad_flag)
            .unwrap_err()
            .contains("not a variable name")
    );
    let dangling = "---\ntitle: T\n---\n\n# a\n\n```story\nif x -> #nowhere\n```\n\nhi\n";
    assert!(
        parse_story(dangling)
            .unwrap_err()
            .contains("matches no heading")
    );
    let trailing = "---\ntitle: T\n---\n\n# a\n\nhi\n\n```story\nset x\n```\n";
    assert!(
        parse_story(trailing)
            .unwrap_err()
            .contains("needs a following")
    );
    let titled_jump = "---\ntitle: T\n---\n\n# a\n\n[Go](#a \"if x\")\n\nhi\n";
    assert!(
        parse_story(titled_jump)
            .unwrap_err()
            .contains("only supported on choices")
    );
}

#[test]
fn script_state_compiles_into_the_graph() {
    let src = "---\ntitle: T\n---\n\n# a\n\n```story\nset asked\nif asked -> #b\n```\n\nOne.\n\n- [Go](#b \"if asked\")\n\n# b\n\nDone.\n";
    let story = parse_story(src).unwrap();
    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();
    let nodes = &find(&entries, "s")["args"]["nodes"];
    let page = &nodes[0]["pages"][0];
    assert_eq!(page["ops"][0]["name"], "asked");
    assert_eq!(page["ops"][0]["value"], 1);
    assert_eq!(page["ops"][0]["add"], false);
    // Gate targets compile to node indices like every other jump.
    assert_eq!(page["gates"][0]["target"], 1);
    assert_eq!(page["gates"][0]["op"], "ne");
    assert_eq!(page["gates"][0]["value"], 0);
    assert_eq!(nodes[0]["choices"][0]["condition"]["name"], "asked");
    assert_eq!(nodes[0]["choices"][0]["condition"]["op"], "ne");
}

#[test]
fn heading_names_cannot_collide_with_generated_screens() {
    // Node names no longer mint screens (the whole story plays inside one
    // stage screen), so headings named after the scaffolding are fine.
    let src = "---\ntitle: T\n---\n\n# title\n\nhi\n\n# stage\n\nbye\n\n# ending\n\nfin\n";
    let story = parse_story(src).unwrap();
    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();
    let nodes = &find(&entries, "s")["args"]["nodes"];
    assert_eq!(nodes.as_array().unwrap().len(), 3);
    // Exactly the three scaffolding screens exist.
    let screens: Vec<String> = entries
        .iter()
        .filter(|e| type_norm(e) == "screen")
        .map(asset_name)
        .collect();
    assert_eq!(screens, ["s_title", "s_stage", "s_ending"]);
}

// The editor's authoring front end validates source without expanding it, so
// it must accept and reject exactly what the expansion does.
#[test]
fn validate_story_source_accepts_and_rejects_like_the_expansion() {
    assert_eq!(validate_story_source(CROSSROADS), Ok(()));
    let err = validate_story_source("---\ntitle: T\n---\n\n# a\n\n> quoted\n").unwrap_err();
    assert!(err.contains("block quotes"), "{err}");
}

// The expansion replaces the import in place and leaves everything else in the
// world alone.
#[test]
fn other_assets_survive_a_story_expansion() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("s.md");
    std::fs::write(&path, "---\ntitle: T\n---\n\n# a\n\nhi\n").unwrap();
    let mut assets = vec![
        serde_json::json!({"name":"win","type":"Window","args":{}}),
        serde_json::json!({
            "name": "tale", "type": "StoryImport",
            "args": {"source": path.to_str().unwrap()}
        }),
    ];
    expand_stories(&mut assets).unwrap();
    assert_eq!(assets[0]["name"], "win");
    assert!(!assets.iter().any(|v| type_norm(v) == "storyimport"));
    assert!(assets.iter().any(|v| asset_name(v) == "tale"));
}

// The import's args reach the emitted graph: the title screen can be dropped
// and the reveal speed set per import.
#[test]
fn import_args_reach_the_compiled_graph() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("s.md");
    std::fs::write(&path, "---\ntitle: T\n---\n\n# a\n\nhi\n").unwrap();
    let mut assets = vec![serde_json::json!({
        "name": "tale", "type": "StoryImport",
        "args": {"source": path.to_str().unwrap(), "title_screen": false, "text_speed": 12.0}
    })];
    expand_stories(&mut assets).unwrap();
    assert_eq!(find(&assets, "tale")["args"]["text_speed"], 12.0);
    assert!(!assets.iter().any(|v| asset_name(v) == "tale_title"));
    // With no title screen the stage shows at launch instead.
    assert_eq!(find(&assets, "tale_stage")["args"]["initial"], true);
}

// An emission failure (here an unreadable portrait) is reported against the
// import and its source file, not as a bare probe error.
#[test]
fn an_emission_failure_is_wrapped_with_import_context() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("s.md");
    std::fs::write(
        &path,
        "---\ntitle: T\n---\n\n# a\n\n![left](/no/such/portrait.png)\n\nhi\n",
    )
    .unwrap();
    let mut assets = vec![serde_json::json!({
        "name": "tale", "type": "StoryImport",
        "args": {"source": path.to_str().unwrap()}
    })];
    let err = expand_stories(&mut assets).unwrap_err();
    assert!(err.contains("StoryImport 'tale'"), "{err}");
    assert!(err.contains("portrait.png"), "{err}");
}

// A loose bullet list wraps each choice in its own paragraph; the choices must
// parse the same as a tight list.
#[test]
fn a_loose_choice_list_parses_like_a_tight_one() {
    let src = "---\ntitle: T\n---\n\n# a\n\nHi.\n\n- [Go](#b)\n\n- [Stay](#a)\n\n# b\n\nDone.\n";
    let story = parse_story(src).unwrap();
    let choices = &story.nodes[0].choices;
    assert_eq!(choices.len(), 2);
    assert_eq!(choices[0].target, "b");
    assert_eq!(choices[1].target, "a");
}

// A second bullet list would be content after the choices, which the runtime
// has nowhere to show, whether prose separates the two lists or not.
#[test]
fn a_second_choice_list_in_one_node_is_an_error() {
    for src in [
        "---\ntitle: T\n---\n\n# a\n\n- [Go](#a)\n\ntext\n\n- [Stay](#a)\n",
        "---\ntitle: T\n---\n\n# a\n\n- [Go](#a)\n\n* [Stay](#a)\n",
    ] {
        let err = parse_story(src).unwrap_err();
        assert!(err.contains("last content"), "{src:?} -> {err}");
    }
}

// The space between two links is not prose: a choice item is still rejected
// for holding two links rather than for holding text.
#[test]
fn the_space_between_two_choice_links_is_not_text() {
    let src = "---\ntitle: T\n---\n\n# a\n\n- [Go](#a) [Stay](#a)\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("exactly one link"), "{err}");
}

// Two directives on one line are separated by a space, which must not count as
// the prose that would make the paragraph a mixed one.
#[test]
fn two_directives_on_one_line_still_stand_alone() {
    let src = "---\ntitle: T\n---\n\n# a\n\n[music](m.ogg) [sound](s.wav)\n\nhi\n";
    let story = parse_story(src).unwrap();
    let page = &story.nodes[0].pages[0];
    assert_eq!(page.music.as_deref(), Some("m.ogg"));
    assert_eq!(page.sounds, ["s.wav"]);
    assert_eq!(page.text, "hi");
}

// The final node is closed at end of file, so an empty one there is caught
// like an empty node anywhere else.
#[test]
fn an_empty_last_node_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\nhi\n\n# b\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("node 'b' is empty"), "{err}");
}

#[test]
fn a_link_inside_image_alt_text_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![bg [x](#a)](room.png)\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("image alt text"), "{err}");
}

#[test]
fn bold_outside_a_paragraph_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n- **loud**\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("speaker attribution"), "{err}");
}

// A choice item is exactly one link: a wrapped second line makes it prose.
#[test]
fn a_multi_line_choice_item_is_an_error() {
    for body in ["- [Go](#a)\n  and then\n", "- [Go](#a)  \n  and then\n"] {
        let src = format!("---\ntitle: T\n---\n\n# a\n\n{body}");
        let err = parse_story(&src).unwrap_err();
        assert!(err.contains("exactly one link"), "{body:?} -> {err}");
    }
}

#[test]
fn a_script_fence_before_the_first_heading_is_an_error() {
    let src = "---\ntitle: T\n---\n\n```story\nset x\n```\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("before the first"), "{err}");
}

#[test]
fn a_script_fence_after_choices_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n- [Go](#a)\n\n```story\nset x\n```\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("last content"), "{err}");
}

// Blank lines inside a script fence are layout, not statements.
#[test]
fn blank_lines_in_a_script_fence_are_ignored() {
    let src = "---\ntitle: T\n---\n\n# a\n\n```story\n\nset x\n\n```\n\nhi\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.nodes[0].pages[0].ops.len(), 1);
    assert_eq!(story.nodes[0].pages[0].ops[0].name, "x");
}

// A speaker attribution with nothing after it has no line to reveal.
#[test]
fn a_speaker_with_no_text_is_an_error() {
    let src = "---\ntitle: T\ncharacters:\n  k: Keeper\n---\n\n# a\n\n**k:**\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("empty paragraph"), "{err}");
}

// Frontmatter alone is not a story: there is nothing to play.
#[test]
fn a_story_with_no_nodes_is_an_error() {
    let err = parse_story("---\ntitle: T\n---\n").unwrap_err();
    assert!(err.contains("no nodes"), "{err}");
}

// A variable name is checked wherever it appears in a script line.
#[test]
fn a_bad_variable_name_is_rejected_in_every_script_form() {
    for line in [
        "set Bad Flag = 1",
        "clear Bad Flag",
        "add Bad Flag 1",
        "if Bad Flag >= 1 -> #a",
    ] {
        let src = format!("---\ntitle: T\n---\n\n# a\n\n```story\n{line}\n```\n\nhi\n");
        let err = parse_story(&src).unwrap_err();
        assert!(err.contains("not a variable name"), "{line:?} -> {err}");
    }
}

// Blank lines separate frontmatter blocks; they are not entries.
#[test]
fn blank_frontmatter_lines_are_skipped() {
    let src = "---\ntitle: T\n\ncharacters:\n\n  k: Keeper\n---\n\n# a\n\n**k:** hi\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.title, "T");
    assert_eq!(story.characters["k"].name, "Keeper");
}

// A malformed field of a block-form character is reported against the
// frontmatter line it sits on.
#[test]
fn a_bad_block_character_field_names_its_frontmatter_line() {
    let src =
        "---\ntitle: T\ncharacters:\n  k:\n    name: Keeper\n    color: red\n---\n\n# a\n\nhi\n";
    let err = parse_story(src).unwrap_err();
    assert!(err.contains("frontmatter line 5"), "{err}");
    assert!(err.contains("color"), "{err}");
}

// A block character is closed by the next id line and by the next top-level
// key alike, so a missing `name` is caught either way.
#[test]
fn a_block_character_missing_its_name_is_caught_at_every_close() {
    let next_id = "---\ntitle: T\ncharacters:\n  a:\n  b: Ben\n---\n\n# a\n\nhi\n";
    let err = parse_story(next_id).unwrap_err();
    assert!(err.contains("character 'a': missing `name`"), "{err}");

    let next_key = "---\ncharacters:\n  a:\ntitle: T\n---\n\n# a\n\nhi\n";
    let err = parse_story(next_key).unwrap_err();
    assert!(err.contains("character 'a': missing `name`"), "{err}");
}

// A quoted name that is not a JSON string is malformed, in a block character
// and in a flow map alike.
#[test]
fn a_malformed_character_name_or_color_is_an_error() {
    let block = "---\ntitle: T\ncharacters:\n  a:\n    name: \"unterminated\n---\n\n# a\n\nhi\n";
    assert!(!parse_story(block).unwrap_err().is_empty());

    let flow_name = "---\ntitle: T\ncharacters:\n  a: { name: \"oops }\n---\n\n# a\n\nhi\n";
    assert!(!parse_story(flow_name).unwrap_err().is_empty());

    let flow_color = "---\ntitle: T\ncharacters:\n  a: { name: A, color: red }\n---\n\n# a\n\nhi\n";
    let err = parse_story(flow_color).unwrap_err();
    assert!(err.contains("color"), "{err}");
}

// A trailing comma in a flow map leaves an empty field, which is layout.
#[test]
fn a_trailing_comma_in_a_flow_map_is_ignored() {
    let src = "---\ntitle: T\ncharacters:\n  k: { name: Keeper, }\n---\n\n# a\n\n**k:** hi\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.characters["k"].name, "Keeper");
    assert_eq!(story.characters["k"].color, [1.0, 1.0, 1.0]);
}

// A one-shot queued before a choice list plays with the menu, and its clip is
// emitted like a page's.
#[test]
fn a_sound_before_a_choice_list_rides_with_the_menu() {
    let src = "---\ntitle: T\n---\n\n# a\n\nHi.\n\n[sound](ding.wav)\n\n- [Go](#a)\n";
    let story = parse_story(src).unwrap();
    assert_eq!(story.nodes[0].choice_sounds, ["ding.wav"]);

    let entries = emit_story("s", &story, true, 45.0, &stub_dims).unwrap();
    let clip = find(&entries, "s_clip0");
    assert_eq!(clip["args"]["source"], "ding.wav");
    let nodes = &find(&entries, "s")["args"]["nodes"];
    assert_eq!(nodes[0]["choice_sounds"][0], "s_clip0");
}

// An unreadable portrait fails the build with the probe's own message, on a
// page stage and on a choice-menu stage alike.
#[test]
fn an_unreadable_portrait_fails_emission() {
    let fail = |_: &str| Err("cannot read 'ana.png'".to_string());
    let page_src = "---\ntitle: T\n---\n\n# a\n\n![left](ana.png)\n\nhi\n";
    let story = parse_story(page_src).unwrap();
    let err = emit_story("s", &story, true, 45.0, &fail).unwrap_err();
    assert!(err.contains("cannot read 'ana.png'"), "{err}");

    let choice_src = "---\ntitle: T\n---\n\n# a\n\n![left](ana.png)\n\n- [Go](#a)\n";
    let story = parse_story(choice_src).unwrap();
    let err = emit_story("s", &story, true, 45.0, &fail).unwrap_err();
    assert!(err.contains("cannot read 'ana.png'"), "{err}");
}

// A zero-sized portrait would divide by zero while fitting it to the canvas.
#[test]
fn a_zero_sized_portrait_is_an_error() {
    let src = "---\ntitle: T\n---\n\n# a\n\n![right](ana.png)\n\nhi\n";
    let story = parse_story(src).unwrap();
    let zero = |_: &str| Ok((0u32, 0u32));
    let err = emit_story("s", &story, true, 45.0, &zero).unwrap_err();
    assert!(err.contains("zero dimension"), "{err}");
    assert!(err.contains("ana.png"), "{err}");
}

#[test]
fn slug_matches_github_style_anchors() {
    assert_eq!(slug("The Crossroads"), "the-crossroads");
    assert_eq!(slug("  Inn's  Door  "), "inns-door");
    assert_eq!(slug("wood"), "wood");
}

#[test]
fn wrap_text_wraps_on_word_boundaries() {
    let wrapped = wrap_text("one two three four five", 9);
    assert_eq!(wrapped, "one two\nthree\nfour five");
    // Authored hard breaks survive.
    assert_eq!(wrap_text("a\nb", 80), "a\nb");
}