laterite-web 0.9.16

Laterite CMF public web layer: themes, static-site generation, page metadata, canonical URLs, and sitemaps
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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
//! The Themes screen: every theme, its config and its templates, edited from
//! the admin under the `web.manage_themes` permission.

use super::{archive, engine, store, EditTheme, Kind, Revision, Template, Theme, ThemeError};
use laterite_admin::axum::extract::{Form, Path, State};
use laterite_admin::axum::http::{header, StatusCode};
use laterite_admin::axum::response::{IntoResponse, Redirect, Response};
use laterite_admin::axum::routing::{get, post};
use laterite_admin::axum::{Extension, Router};
use laterite_admin::html::Markup;
use laterite_admin::routes::{RouteCtx, Screen, ScreenReg};
use laterite_admin::VerifiedUpload;
use laterite_admin::{FlashLevel, PageHead, Permission, SessionHandle, Shell, ROLE_ADMIN};
use laterite_auth::AuthenticatedUser;
use laterite_core::{t, Text};
use std::sync::Arc;

/// The permission the screen and every write under it require.
pub const PERMISSION: &str = "web.manage_themes";

/// The screen's permission, as the module registers it.
pub fn permission() -> Permission {
    Permission::new(PERMISSION, t!("Manage themes"), t!("Website")).roles([ROLE_ADMIN])
}

/// The screen, as the module registers it: the Themes tab.
pub fn screen() -> ScreenReg {
    ScreenReg::new("/themes", PERMISSION, Arc::new(ThemeScreen))
        .in_menu(t!("Themes"))
        .menu(laterite_admin::nav::Placement::new().icon("palette"))
}

/// The Themes screen.
pub struct ThemeScreen;

impl Screen for ThemeScreen {
    fn mount(&self, ctx: &RouteCtx) -> Router {
        let state = Arc::new(ctx.clone());
        Router::new()
            .route("/", get(index).post(create))
            .route("/import", post(import_new))
            .route("/{code}/export", get(export))
            .route("/{code}/import", post(import_into))
            .route("/{code}", get(show))
            .route("/{code}/config", post(update_config))
            .route("/{code}/properties", post(save_properties))
            .route("/{code}/settings", post(save_settings))
            .route("/{code}/activate", post(activate))
            .route("/{code}/edit", post(edit))
            .route("/{code}/duplicate", post(duplicate))
            .route("/{code}/child", post(child))
            .route("/{code}/lock", post(lock))
            .route("/{code}/delete", post(delete))
            .route("/{code}/templates", post(create_template))
            .route("/{code}/templates/{id}", get(template))
            .route("/{code}/templates/{id}/save", post(save_template))
            .route("/{code}/templates/{id}/delete", post(delete_template))
            .route("/{code}/templates/{id}/restore", post(restore))
            .with_state(state)
    }
}

type Ctx = State<Arc<RouteCtx>>;

fn back(ctx: &RouteCtx, rest: &str) -> Response {
    Redirect::to(&ctx.url(rest)).into_response()
}

fn flash_error(session: &SessionHandle, e: &ThemeError) {
    session.push_flash(FlashLevel::Error, Text::dynamic(e.to_string()));
}

fn page<T: askama::Template>(shell: &Shell, title: Text, template: &T) -> Response {
    page_with(shell, PageHead::new(title), template)
}

fn page_with<T: askama::Template>(shell: &Shell, head: PageHead, template: &T) -> Response {
    match Markup::from_template(template) {
        Ok(body) => shell.page_with(head, body),
        Err(e) => {
            tracing::error!(error = %e, "rendering a theme page failed");
            shell.page(&t!("Themes"), Markup::empty())
        }
    }
}

/// Which theme is active, and which one this operator previews.
async fn standing(ctx: &RouteCtx, user: &AuthenticatedUser) -> (Option<String>, Option<String>) {
    let active = super::active_theme(ctx.db())
        .await
        .ok()
        .flatten()
        .map(|t| t.code);
    // The operator's own choice alone: the active theme is what they edit
    // otherwise, and the Active badge already says so.
    let editing = laterite_admin::settings::load_for::<EditTheme>(ctx.db(), user.user.id)
        .await
        .ok()
        .and_then(|e| e.code);
    (active, editing)
}

/// Up to two initials of a name: the first letters of its first two words,
/// or the first letter alone.
fn initials(name: &str) -> String {
    let mut words = name.split_whitespace().filter_map(|w| w.chars().next());
    let mut out: String = words
        .by_ref()
        .take(2)
        .flat_map(|c| c.to_uppercase())
        .collect();
    if out.is_empty() {
        out.push('?');
    }
    out
}

/// A theme as the list shows it.
struct ThemeRow {
    code: String,
    name: String,
    /// The name's initials, for the thumbnail block when no preview is set.
    initials: String,
    preview: String,
    author: String,
    description: String,
    parent: String,
    active: bool,
    editing: bool,
    locked: bool,
    href: String,
}

#[derive(askama::Template)]
#[template(path = "themes.html")]
struct IndexTemplate {
    shell: Shell,
    base: String,
    themes: Vec<ThemeRow>,
}

async fn index(
    State(ctx): Ctx,
    Extension(shell): Extension<Shell>,
    Extension(user): Extension<AuthenticatedUser>,
) -> Response {
    let themes = store::list_themes(ctx.db()).await.unwrap_or_default();
    let (active, editing) = standing(&ctx, &user).await;
    let rows = themes
        .into_iter()
        .map(|t| ThemeRow {
            href: ctx.url(&t.code),
            active: active.as_deref() == Some(t.code.as_str()),
            editing: editing.as_deref() == Some(t.code.as_str()),
            parent: t.parent.clone().unwrap_or_default(),
            initials: initials(&t.config.name),
            preview: t.config.preview.clone().unwrap_or_default(),
            author: t.config.author.clone(),
            description: t.config.description.clone(),
            name: t.config.name.clone(),
            locked: t.locked,
            code: t.code,
        })
        .collect();
    page(
        &shell,
        t!("Themes"),
        &IndexTemplate {
            base: ctx.url(""),
            shell: shell.clone(),
            themes: rows,
        },
    )
}

#[derive(serde::Deserialize)]
struct NewTheme {
    code: String,
    name: String,
}

async fn create(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Form(form): Form<NewTheme>,
) -> Response {
    let config = super::ThemeConfig {
        name: form.name.trim().to_string(),
        ..Default::default()
    };
    let yaml = match config.to_yaml() {
        Ok(y) => y,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    match store::create_theme(ctx.db(), form.code.trim(), &yaml).await {
        Ok(theme) => {
            ctx.audit(
                &user,
                "web.theme.create",
                Some("theme"),
                Some(&theme.code),
                Some(&theme.config.name),
                None,
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Theme created."));
            back(&ctx, &theme.code)
        }
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, "")
        }
    }
}

/// The most an uploaded archive may weigh.
const UPLOAD_LIMIT: u64 = 32 * 1024 * 1024;

async fn export(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Path(code): Path<String>,
) -> Response {
    match archive::export(ctx.db(), &code).await {
        Ok(bytes) => (
            StatusCode::OK,
            [
                (header::CONTENT_TYPE, "application/zip".to_string()),
                (
                    header::CONTENT_DISPOSITION,
                    format!("attachment; filename=\"{code}.zip\""),
                ),
            ],
            bytes,
        )
            .into_response(),
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, &code)
        }
    }
}

/// The fields of an import form: the code (for a new theme), the file, and
/// whether to replace what exists.
struct ImportForm {
    code: String,
    replace: bool,
    file: Option<Vec<u8>>,
    too_large: bool,
}

async fn read_import(upload: &mut VerifiedUpload) -> ImportForm {
    let mut form = ImportForm {
        code: String::new(),
        replace: false,
        file: None,
        too_large: false,
    };
    while let Ok(Some(mut field)) = upload.next_field().await {
        match field.name().unwrap_or_default() {
            "code" => form.code = field.text().await.unwrap_or_default().trim().to_string(),
            "replace" => form.replace = field.text().await.unwrap_or_default() == "1",
            "file" => {
                let mut bytes = Vec::new();
                while let Ok(Some(chunk)) = field.chunk().await {
                    if bytes.len() as u64 + chunk.len() as u64 > UPLOAD_LIMIT {
                        form.too_large = true;
                        break;
                    }
                    bytes.extend_from_slice(&chunk);
                }
                form.file = Some(bytes);
            }
            _ => {}
        }
    }
    form
}

async fn run_import(
    ctx: &RouteCtx,
    session: &SessionHandle,
    user: &AuthenticatedUser,
    code: &str,
    form: ImportForm,
) -> Option<String> {
    if form.too_large {
        session.push_flash(FlashLevel::Error, t!("The archive is larger than 32 MB."));
        return None;
    }
    let Some(bytes) = form.file.filter(|b| !b.is_empty()) else {
        session.push_flash(FlashLevel::Error, t!("Choose a zip to import."));
        return None;
    };
    match archive::import(ctx.db(), code, &bytes, form.replace, Some(user.user.id)).await {
        Ok(report) => {
            ctx.audit(
                user,
                "web.theme.import",
                Some("theme"),
                Some(code),
                None,
                Some(&format!(
                    "{{\"created\":{},\"imported\":{},\"skipped\":{}}}",
                    report.created, report.imported, report.skipped
                )),
            )
            .await;
            session.push_flash(
                FlashLevel::Success,
                t!(
                    "Imported {imported} template(s), skipped {skipped}.",
                    imported = report.imported as i64,
                    skipped = report.skipped as i64
                ),
            );
            Some(code.to_string())
        }
        Err(e) => {
            flash_error(session, &e);
            None
        }
    }
}

async fn import_new(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    mut upload: VerifiedUpload,
) -> Response {
    let form = read_import(&mut upload).await;
    let code = form.code.clone();
    if code.is_empty() {
        session.push_flash(FlashLevel::Error, t!("Give the new theme a code."));
        return back(&ctx, "");
    }
    match run_import(&ctx, &session, &user, &code, form).await {
        Some(code) => back(&ctx, &code),
        None => back(&ctx, ""),
    }
}

async fn import_into(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    mut upload: VerifiedUpload,
) -> Response {
    let form = read_import(&mut upload).await;
    run_import(&ctx, &session, &user, &code, form).await;
    back(&ctx, &code)
}

/// The layouts a theme and its ancestors hold, by path.
async fn layouts_of(ctx: &RouteCtx, code: &str) -> Result<Vec<String>, ThemeError> {
    let mut layouts = Vec::new();
    for theme in store::chain(ctx.db(), code).await? {
        for t in store::list_templates(ctx.db(), theme.id, Some(Kind::Layout)).await? {
            if !layouts.contains(&t.path) {
                layouts.push(t.path);
            }
        }
    }
    layouts.sort();
    Ok(layouts)
}

/// The registered components, as the Components help lists them.
fn components_help(ctx: &RouteCtx) -> String {
    let regs = ctx.contributions::<super::component::ComponentReg>();
    if regs.is_empty() {
        return String::from("No component is registered.");
    }
    regs.iter()
        .map(|r| {
            let props: Vec<String> = r
                .component
                .properties()
                .iter()
                .map(|p| p.name.clone())
                .collect();
            if props.is_empty() {
                r.code.clone()
            } else {
                format!("{} ({})", r.code, props.join(", "))
            }
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// A page's settings as the editor shows them: typed fields over the bag.
fn page_fields(layouts: &[String], components_help: &str) -> Vec<laterite_admin::form::FormField> {
    use laterite_admin::form::FormField;
    let names: Vec<String> = layouts
        .iter()
        .map(|l| super::page::page_name(l).to_string())
        .collect();
    let mut choices: Vec<(&str, &str)> = vec![("", "")];
    choices.extend(names.iter().map(|n| (n.as_str(), n.as_str())));
    let components_help = Text::dynamic(format!(
        "A JSON object keyed by alias: {{\"posts\": {{\"component\": \"acme.posts\", \"limit\": 5}}}}. Registered: {components_help}"
    ));
    vec![
        FormField::text("url", t!("URL"))
            .required()
            .help(t!("A pattern: /blog/:slug, /docs/:path*, /page/:n?1")),
        FormField::select("layout", t!("Layout"), choices),
        FormField::text("title", t!("Title")),
        FormField::textarea("description", t!("Description")),
        FormField::text("meta_title", t!("Meta title")),
        FormField::textarea("meta_description", t!("Meta description")),
        FormField::text("meta_image", t!("Meta image")),
        FormField::text("meta_type", t!("Meta type")),
        FormField::text("meta_robots", t!("Meta robots")),
        FormField::switch("hidden", t!("Hidden: shown only while previewing")),
        FormField::textarea("components", t!("Components")).help(components_help),
    ]
}

/// The bag as the fields show it: `components` as pretty JSON text.
fn bag_for_fields(settings: &serde_json::Value) -> serde_json::Value {
    let mut bag = settings.clone();
    if let Some(obj) = bag.as_object_mut() {
        let text = match obj.get("components") {
            Some(serde_json::Value::Object(m)) if !m.is_empty() => {
                serde_json::to_string_pretty(m).unwrap_or_default()
            }
            _ => String::new(),
        };
        obj.insert("components".into(), serde_json::Value::String(text));
    }
    bag
}

/// A page's settings as a save checks them: the URL parses and the layout
/// is one the theme or an ancestor has.
async fn check_page(
    ctx: &RouteCtx,
    code: &str,
    settings: &serde_json::Value,
) -> Result<(), ThemeError> {
    let page = super::page::PageSettings::from_value(settings)?;
    page.check(&layouts_of(ctx, code).await?)?;
    let regs = ctx.contributions::<super::component::ComponentReg>();
    super::component::check(settings, &regs)
}

/// A template as the theme page lists it: the theme's own, or an ancestor's.
struct TemplateRow {
    path: String,
    from: String,
    href: String,
    /// A page's URL pattern; empty for every other kind.
    url: String,
    /// Whether this is the template open in the editor.
    active: bool,
}

struct KindGroup {
    kind: &'static str,
    label: String,
    rows: Vec<TemplateRow>,
}

/// The controls beside a theme's title.
#[derive(askama::Template)]
#[template(path = "theme_actions.html")]
struct ActionsTemplate {
    shell: Shell,
    theme_url: String,
    active: bool,
    editing: bool,
    locked: bool,
}

#[derive(askama::Template)]
#[template(path = "theme.html")]
struct ShowTemplate {
    shell: Shell,
    theme_url: String,
    code: String,
    name: String,
    parent: String,
    author: String,
    homepage: String,
    description: String,
    active: bool,
    editing: bool,
    locked: bool,
    preview: String,
    /// The settings fields over the theme's values, when its config (or an
    /// ancestor's) declares a form.
    settings: Option<String>,
    groups: Vec<KindGroup>,
    kinds: Vec<(&'static str, String)>,
}

fn kind_label(shell: &Shell, kind: Kind) -> String {
    match kind {
        Kind::Layout => shell.t("Layouts"),
        Kind::Page => shell.t("Pages"),
        Kind::Partial => shell.t("Partials"),
        Kind::Content => shell.t("Content"),
        Kind::Asset => shell.t("Assets"),
    }
}

/// Every template the theme renders with, by kind: its own rows and the
/// ancestors' it does not override, each linked to the editor of the theme
/// that holds it.
async fn groups(
    ctx: &RouteCtx,
    shell: &Shell,
    chain: &[Theme],
    current: Option<i64>,
) -> Result<Vec<KindGroup>, ThemeError> {
    let mut seen: std::collections::HashMap<(Kind, String), (String, i64, String)> =
        Default::default();
    for theme in chain {
        for t in store::list_templates(ctx.db(), theme.id, None).await? {
            let url = match t.kind {
                Kind::Page => t
                    .settings
                    .get("url")
                    .and_then(|u| u.as_str())
                    .unwrap_or_default()
                    .to_string(),
                _ => String::new(),
            };
            seen.entry((t.kind, t.path.clone()))
                .or_insert((theme.code.clone(), t.id, url));
        }
    }
    let own = &chain[0].code;
    Ok(Kind::ALL
        .into_iter()
        .map(|kind| {
            let mut rows: Vec<TemplateRow> = seen
                .iter()
                .filter(|((k, _), _)| *k == kind)
                .map(|((_, path), (from, id, url))| TemplateRow {
                    path: path.clone(),
                    from: if from == own {
                        String::new()
                    } else {
                        from.clone()
                    },
                    href: ctx.url(&format!("{from}/templates/{id}")),
                    url: url.clone(),
                    active: current == Some(*id),
                })
                .collect();
            rows.sort_by(|a, b| a.path.cmp(&b.path));
            KindGroup {
                kind: kind.as_str(),
                label: kind_label(shell, kind),
                rows,
            }
        })
        .collect())
}

async fn show(
    State(ctx): Ctx,
    Extension(shell): Extension<Shell>,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
) -> Response {
    let chain = match store::chain(ctx.db(), &code).await {
        Ok(chain) => chain,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    let groups = match groups(&ctx, &shell, &chain, None).await {
        Ok(g) => g,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    let theme = &chain[0];
    let kinds = Kind::ALL
        .into_iter()
        .map(|k| (k.as_str(), kind_label(&shell, k)))
        .collect();
    let fields = store::form_fields(&chain);
    let settings = if fields.is_empty() {
        None
    } else {
        match ctx.value_form(&fields, &theme.code) {
            Ok(form) => Some(form.render(&theme.settings, &shell).into_string()),
            Err(text) => {
                session.push_flash(FlashLevel::Error, text);
                None
            }
        }
    };
    let (active, editing) = standing(&ctx, &user).await;
    let active = active.as_deref() == Some(theme.code.as_str());
    let editing = editing.as_deref() == Some(theme.code.as_str());
    let actions = Markup::from_template(&ActionsTemplate {
        shell: shell.clone(),
        theme_url: ctx.url(&theme.code),
        active,
        editing,
        locked: theme.locked,
    })
    .unwrap_or_else(|_| Markup::empty());
    page_with(
        &shell,
        PageHead::new(Text::dynamic(theme.config.name.clone()))
            .back(t!("Themes"), ctx.url(""))
            .actions(actions),
        &ShowTemplate {
            theme_url: ctx.url(&theme.code),
            code: theme.code.clone(),
            name: theme.config.name.clone(),
            parent: theme.parent.clone().unwrap_or_default(),
            author: theme.config.author.clone(),
            homepage: theme.config.homepage.clone(),
            description: theme.config.description.clone(),
            active,
            editing,
            locked: theme.locked,
            preview: theme.config.preview.clone().unwrap_or_default(),
            settings,
            groups,
            kinds,
            shell: shell.clone(),
        },
    )
}

#[derive(serde::Deserialize)]
struct ConfigForm {
    config: String,
}

async fn update_config(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<ConfigForm>,
) -> Response {
    match store::update_theme_config(ctx.db(), &code, &form.config).await {
        Ok(theme) => {
            ctx.audit(
                &user,
                "web.theme.update",
                Some("theme"),
                Some(&theme.code),
                Some(&theme.config.name),
                None,
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Theme config saved."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, &code)
}

#[derive(serde::Deserialize)]
struct PropertiesForm {
    #[serde(default)]
    name: String,
    #[serde(default)]
    author: String,
    #[serde(default)]
    homepage: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    preview: String,
}

/// The properties dialog: the human fields of theme.yaml, rewritten into the
/// config with everything else (the form, the parent, the requirements) kept.
async fn save_properties(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<PropertiesForm>,
) -> Response {
    let name = form.name.trim();
    if name.is_empty() {
        session.push_flash(FlashLevel::Error, t!("A theme needs a name."));
        return back(&ctx, &code);
    }
    let theme = match store::find_theme(ctx.db(), &code).await {
        Ok(Some(theme)) => theme,
        Ok(None) => {
            flash_error(&session, &ThemeError::NotFound(code.clone()));
            return back(&ctx, "");
        }
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    let mut config = theme.config.clone();
    config.name = name.to_string();
    config.author = form.author.trim().to_string();
    config.homepage = form.homepage.trim().to_string();
    config.description = form.description.trim().to_string();
    config.preview = Some(form.preview.trim().to_string()).filter(|p| !p.is_empty());
    let yaml = match config.to_yaml() {
        Ok(yaml) => yaml,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, &code);
        }
    };
    match store::update_theme_config(ctx.db(), &code, &yaml).await {
        Ok(theme) => {
            ctx.audit(
                &user,
                "web.theme.update",
                Some("theme"),
                Some(&theme.code),
                Some(&theme.config.name),
                None,
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Theme properties saved."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, &code)
}

async fn save_settings(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(data): Form<std::collections::HashMap<String, String>>,
) -> Response {
    let chain = match store::chain(ctx.db(), &code).await {
        Ok(chain) => chain,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    let fields = store::form_fields(&chain);
    let collected = ctx
        .value_form(&fields, &code)
        .and_then(|form| form.collect(&data));
    match collected {
        Ok(values) => match store::save_settings(ctx.db(), &code, &values).await {
            Ok(()) => {
                ctx.audit(
                    &user,
                    "web.theme.settings",
                    Some("theme"),
                    Some(&code),
                    Some(&chain[0].config.name),
                    None,
                )
                .await;
                session.push_flash(FlashLevel::Success, t!("Theme settings saved."));
            }
            Err(e) => flash_error(&session, &e),
        },
        Err(text) => session.push_flash(FlashLevel::Error, text),
    }
    back(&ctx, &code)
}

async fn activate(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
) -> Response {
    match super::set_active_theme(ctx.db(), &code).await {
        Ok(()) => {
            ctx.audit(
                &user,
                "web.theme.activate",
                Some("theme"),
                Some(&code),
                None,
                None,
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("The site now uses this theme."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, "")
}

async fn edit(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
) -> Response {
    let current: Option<String> = super::edit_theme(ctx.db(), user.user.id)
        .await
        .ok()
        .flatten()
        .map(|t| t.code);
    let active = super::active_theme(ctx.db())
        .await
        .ok()
        .flatten()
        .map(|t| t.code);
    // Choosing the active theme clears the preference, so a later activation
    // follows the operator along.
    let choice =
        if current.as_deref() == Some(code.as_str()) || active.as_deref() == Some(code.as_str()) {
            None
        } else {
            Some(code.as_str())
        };
    let _ = EditTheme::default();
    match super::set_edit_theme(ctx.db(), user.user.id, choice).await {
        Ok(()) => session.push_flash(
            FlashLevel::Success,
            if choice.is_some() {
                t!("You are now editing this theme.")
            } else {
                t!("You are now editing the site's theme.")
            },
        ),
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, "")
}

#[derive(serde::Deserialize)]
struct CopyForm {
    new_code: String,
    #[serde(default)]
    name: String,
}

async fn duplicate(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<CopyForm>,
) -> Response {
    match store::duplicate_theme(ctx.db(), &code, form.new_code.trim()).await {
        Ok(copy) => {
            ctx.audit(
                &user,
                "web.theme.duplicate",
                Some("theme"),
                Some(&copy.code),
                Some(&copy.config.name),
                Some(&format!("{{\"from\":\"{code}\"}}")),
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Theme duplicated."));
            back(&ctx, &copy.code)
        }
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, "")
        }
    }
}

async fn child(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<CopyForm>,
) -> Response {
    let name = if form.name.trim().is_empty() {
        form.new_code.trim().to_string()
    } else {
        form.name.trim().to_string()
    };
    match store::create_child_theme(ctx.db(), &code, form.new_code.trim(), &name).await {
        Ok(child) => {
            ctx.audit(
                &user,
                "web.theme.create",
                Some("theme"),
                Some(&child.code),
                Some(&child.config.name),
                Some(&format!("{{\"parent\":\"{code}\"}}")),
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Child theme created."));
            back(&ctx, &child.code)
        }
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, "")
        }
    }
}

#[derive(serde::Deserialize)]
struct LockForm {
    locked: i32,
}

async fn lock(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<LockForm>,
) -> Response {
    let locked = form.locked != 0;
    match store::set_locked(ctx.db(), &code, locked).await {
        Ok(()) => {
            ctx.audit(
                &user,
                if locked {
                    "web.theme.lock"
                } else {
                    "web.theme.unlock"
                },
                Some("theme"),
                Some(&code),
                None,
                None,
            )
            .await;
            session.push_flash(
                FlashLevel::Success,
                if locked {
                    t!("Theme locked.")
                } else {
                    t!("Theme unlocked.")
                },
            );
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, "")
}

async fn delete(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
) -> Response {
    match store::delete_theme(ctx.db(), &code).await {
        Ok(()) => {
            ctx.audit(
                &user,
                "web.theme.delete",
                Some("theme"),
                Some(&code),
                None,
                None,
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Theme deleted."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, "")
}

#[derive(serde::Deserialize)]
struct NewTemplate {
    kind: String,
    path: String,
}

async fn create_template(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(code): Path<String>,
    Form(form): Form<NewTemplate>,
) -> Response {
    let theme = match store::find_theme(ctx.db(), &code).await {
        Ok(Some(t)) => t,
        Ok(None) => {
            flash_error(&session, &ThemeError::NotFound(code.clone()));
            return back(&ctx, "");
        }
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, "");
        }
    };
    let kind: Kind = match form.kind.parse() {
        Ok(k) => k,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, &code);
        }
    };
    let path = form.path.trim();
    if let Ok(Some(existing)) = store::find_template(ctx.db(), theme.id, kind, path).await {
        return back(&ctx, &format!("{code}/templates/{}", existing.id));
    }
    // A new page starts at the URL its name suggests, so it serves at once.
    let settings = (kind == Kind::Page)
        .then(|| serde_json::json!({ "url": format!("/{}", super::page::page_name(path)) }));
    match store::save_template(
        ctx.db(),
        theme.id,
        kind,
        path,
        settings,
        "",
        Some(user.user.id),
    )
    .await
    {
        Ok(t) => {
            ctx.audit(
                &user,
                "web.theme.template.create",
                Some("theme_template"),
                Some(&t.id.to_string()),
                Some(&engine::template_name(kind, path)),
                Some(&format!("{{\"theme\":\"{code}\"}}")),
            )
            .await;
            back(&ctx, &format!("{code}/templates/{}", t.id))
        }
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, &code)
        }
    }
}

struct RevisionRow {
    id: i64,
    saved_at: String,
    saved_by: String,
}

#[derive(askama::Template)]
#[template(path = "theme_template.html")]
struct EditorTemplate {
    shell: Shell,
    theme_url: String,
    template_url: String,
    path: String,
    locked: bool,
    settings: String,
    /// A page's settings as fields; none for every other kind.
    page_fields: Option<String>,
    markup: String,
    revisions: Vec<RevisionRow>,
    groups: Vec<KindGroup>,
    kinds: Vec<(&'static str, String)>,
}

/// The controls beside a template's title.
#[derive(askama::Template)]
#[template(path = "theme_template_actions.html")]
struct TemplateActionsTemplate {
    shell: Shell,
    template_url: String,
    locked: bool,
}

/// The template `id` under the theme `code`, or none: a template is reached
/// only through the theme that holds it.
async fn owned(ctx: &RouteCtx, code: &str, id: i64) -> Result<(Theme, Template), ThemeError> {
    let theme = store::find_theme(ctx.db(), code)
        .await?
        .ok_or_else(|| ThemeError::NotFound(code.to_string()))?;
    let template = store::template(ctx.db(), id)
        .await?
        .filter(|t| t.theme_id == theme.id)
        .ok_or_else(|| ThemeError::TemplateNotFound(id.to_string()))?;
    Ok((theme, template))
}

fn revision_rows(shell: &Shell, revisions: Vec<Revision>) -> Vec<RevisionRow> {
    revisions
        .into_iter()
        .map(|r| RevisionRow {
            id: r.id,
            saved_at: shell.datetime(&r.saved_at),
            saved_by: r.saved_by.map(|id| format!("#{id}")).unwrap_or_default(),
        })
        .collect()
}

async fn template(
    State(ctx): Ctx,
    Extension(shell): Extension<Shell>,
    Extension(session): Extension<SessionHandle>,
    Path((code, id)): Path<(String, i64)>,
) -> Response {
    let (theme, template) = match owned(&ctx, &code, id).await {
        Ok(pair) => pair,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, &code);
        }
    };
    let revisions = store::revisions(ctx.db(), template.id)
        .await
        .unwrap_or_default();
    let chain = store::chain(ctx.db(), &code).await.unwrap_or_default();
    let groups = groups(&ctx, &shell, &chain, Some(template.id))
        .await
        .unwrap_or_default();
    let kinds = Kind::ALL
        .into_iter()
        .map(|k| (k.as_str(), kind_label(&shell, k)))
        .collect();
    let page_fields = if template.kind == Kind::Page {
        let layouts = layouts_of(&ctx, &code).await.unwrap_or_default();
        match ctx.value_form(&page_fields(&layouts, &components_help(&ctx)), &code) {
            Ok(form) => Some(
                form.render(&bag_for_fields(&template.settings), &shell)
                    .into_string(),
            ),
            Err(text) => {
                session.push_flash(FlashLevel::Error, text);
                None
            }
        }
    } else {
        None
    };
    let template_url = ctx.url(&format!("{code}/templates/{id}"));
    let actions = Markup::from_template(&TemplateActionsTemplate {
        shell: shell.clone(),
        template_url: template_url.clone(),
        locked: theme.locked,
    })
    .unwrap_or_else(|_| Markup::empty());
    page_with(
        &shell,
        PageHead::new(Text::dynamic(template.path.clone()))
            .back(
                Text::dynamic(theme.config.name.clone()),
                ctx.url(&theme.code),
            )
            .actions(actions),
        &EditorTemplate {
            theme_url: ctx.url(&theme.code),
            template_url,
            path: engine::template_name(template.kind, &template.path),
            locked: theme.locked,
            settings: serde_json::to_string_pretty(&template.settings).unwrap_or_default(),
            page_fields,
            markup: template.markup.clone(),
            revisions: revision_rows(&shell, revisions),
            groups,
            kinds,
            shell: shell.clone(),
        },
    )
}

async fn save_template(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path((code, id)): Path<(String, i64)>,
    Form(form): Form<std::collections::HashMap<String, String>>,
) -> Response {
    let here = format!("{code}/templates/{id}");
    let (theme, template) = match owned(&ctx, &code, id).await {
        Ok(pair) => pair,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, &code);
        }
    };
    // A page's settings arrive as fields, laid over the bag it has; any other
    // kind's arrive as the JSON box.
    let settings: serde_json::Value = if template.kind == Kind::Page {
        let layouts = layouts_of(&ctx, &code).await.unwrap_or_default();
        let collected = ctx
            .value_form(&page_fields(&layouts, &components_help(&ctx)), &code)
            .and_then(|f| f.collect(&form));
        match collected {
            Ok(serde_json::Value::Object(mut fields)) => {
                // The Components box is JSON text; empty means none.
                let text = fields
                    .remove("components")
                    .and_then(|v| v.as_str().map(str::to_string))
                    .unwrap_or_default();
                let components = if text.trim().is_empty() {
                    serde_json::json!({})
                } else {
                    match serde_json::from_str::<serde_json::Value>(&text) {
                        Ok(v @ serde_json::Value::Object(_)) => v,
                        _ => {
                            session.push_flash(
                                FlashLevel::Error,
                                t!("Components must be a JSON object keyed by alias."),
                            );
                            return back(&ctx, &here);
                        }
                    }
                };
                let mut bag = template.settings.as_object().cloned().unwrap_or_default();
                bag.extend(fields);
                bag.insert("components".into(), components);
                serde_json::Value::Object(bag)
            }
            Ok(_) => serde_json::json!({}),
            Err(text) => {
                session.push_flash(FlashLevel::Error, text);
                return back(&ctx, &here);
            }
        }
    } else {
        let raw = form.get("settings").map(String::as_str).unwrap_or("{}");
        match serde_json::from_str(raw.trim()) {
            Ok(v @ serde_json::Value::Object(_)) => v,
            Ok(_) => {
                session.push_flash(FlashLevel::Error, t!("The settings must be a JSON object."));
                return back(&ctx, &here);
            }
            Err(e) => {
                session.push_flash(
                    FlashLevel::Error,
                    Text::dynamic(format!("The settings do not parse: {e}")),
                );
                return back(&ctx, &here);
            }
        }
    };
    let markup = form
        .get("markup")
        .map(String::as_str)
        .unwrap_or_default()
        .replace("\r\n", "\n");
    if template.kind != Kind::Content {
        if let Err(e) = engine::check(&markup) {
            session.push_flash(FlashLevel::Error, Text::dynamic(e.to_string()));
            return back(&ctx, &here);
        }
    }
    if template.kind == Kind::Page {
        if let Err(e) = check_page(&ctx, &code, &settings).await {
            flash_error(&session, &e);
            return back(&ctx, &here);
        }
    }
    match store::save_template(
        ctx.db(),
        theme.id,
        template.kind,
        &template.path,
        Some(settings),
        &markup,
        Some(user.user.id),
    )
    .await
    {
        Ok(saved) => {
            ctx.audit(
                &user,
                "web.theme.template.save",
                Some("theme_template"),
                Some(&saved.id.to_string()),
                Some(&engine::template_name(saved.kind, &saved.path)),
                Some(&format!("{{\"theme\":\"{code}\"}}")),
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Template saved."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, &here)
}

async fn delete_template(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path((code, id)): Path<(String, i64)>,
) -> Response {
    let (_, template) = match owned(&ctx, &code, id).await {
        Ok(pair) => pair,
        Err(e) => {
            flash_error(&session, &e);
            return back(&ctx, &code);
        }
    };
    match store::delete_template(ctx.db(), id).await {
        Ok(()) => {
            ctx.audit(
                &user,
                "web.theme.template.delete",
                Some("theme_template"),
                Some(&id.to_string()),
                Some(&engine::template_name(template.kind, &template.path)),
                Some(&format!("{{\"theme\":\"{code}\"}}")),
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Template deleted."));
            back(&ctx, &code)
        }
        Err(e) => {
            flash_error(&session, &e);
            back(&ctx, &format!("{code}/templates/{id}"))
        }
    }
}

#[derive(serde::Deserialize)]
struct RestoreForm {
    revision: i64,
}

async fn restore(
    State(ctx): Ctx,
    Extension(session): Extension<SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path((code, id)): Path<(String, i64)>,
    Form(form): Form<RestoreForm>,
) -> Response {
    let here = format!("{code}/templates/{id}");
    if let Err(e) = owned(&ctx, &code, id).await {
        flash_error(&session, &e);
        return back(&ctx, &code);
    }
    let belongs = store::revisions(ctx.db(), id)
        .await
        .map(|revs| revs.iter().any(|r| r.id == form.revision))
        .unwrap_or(false);
    if !belongs {
        flash_error(
            &session,
            &ThemeError::TemplateNotFound(form.revision.to_string()),
        );
        return back(&ctx, &here);
    }
    match store::restore_revision(ctx.db(), form.revision, Some(user.user.id)).await {
        Ok(saved) => {
            ctx.audit(
                &user,
                "web.theme.template.restore",
                Some("theme_template"),
                Some(&saved.id.to_string()),
                Some(&engine::template_name(saved.kind, &saved.path)),
                Some(&format!("{{\"revision\":{}}}", form.revision)),
            )
            .await;
            session.push_flash(FlashLevel::Success, t!("Revision restored."));
        }
        Err(e) => flash_error(&session, &e),
    }
    back(&ctx, &here)
}