table-editor 0.1.0

A local HTTP server and browser bundle for editing a repository's JSONL tables
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
//! The column schema a table sends to the browser.
//!
//! The schema is data, not code: it carries everything the editor needs to
//! render and validate a table, so the browser holds no per-repo knowledge. It
//! is rebuilt on every GET, which lets a table bake in anything derived from a
//! sibling table—an option list, a dependent option map, a column width—rather
//! than asking the browser to compute it.
//!
//! A `Schema` and its `Column`s are built through constructors rather than
//! filled in field by field, so a column that the browser could not render
//! cannot be described: the three column types that need data of their own—
//! `select`, `computed`, and `map`—take it as a constructor argument.

use std::collections::BTreeMap;

use serde::Serialize;

/// One table's presentation: the columns, how a new row starts, and any
/// completion lists the columns draw on.
///
/// The table's route segment and heading are not set here. They come from the
/// table's own `name` and `title`, which the server fills in on the way out, so
/// the two cannot disagree.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Schema {
    table: String,
    title: String,
    #[serde(skip_serializing_if = "is_false")]
    sortable: bool,
    columns: Vec<Column>,
    new_row: NewRow,
    datalists: BTreeMap<String, Datalist>,
}

impl Schema {
    pub fn new(columns: impl IntoIterator<Item = Column>) -> Self {
        Self {
            table: String::new(),
            title: String::new(),
            sortable: false,
            columns: columns.into_iter().collect(),
            new_row: NewRow::default(),
            datalists: BTreeMap::new(),
        }
    }

    /// Let the browser sort the view by any column. This is a view setting
    /// only: writes always send rows in their stored order, and drag reordering
    /// is disabled while a sort is active. Leave it off on a table whose row
    /// order is itself meaningful.
    pub fn sortable(mut self) -> Self {
        self.sortable = true;
        self
    }

    pub fn new_row(mut self, new_row: NewRow) -> Self {
        self.new_row = new_row;
        self
    }

    pub fn datalist(mut self, name: impl Into<String>, list: Datalist) -> Self {
        self.datalists.insert(name.into(), list);
        self
    }

    /// Stamp the schema with the table it describes.
    pub(crate) fn identify(&mut self, table: &str, title: &str) {
        self.table.clear();
        self.table.push_str(table);
        self.title.clear();
        self.title.push_str(title);
    }
}

/// How the browser renders and edits one column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ColumnType {
    /// A single-line value.
    String,
    /// A single-line value that grows to fill the row.
    Text,
    /// A single-line value whose spacing is significant, so it is not trimmed.
    SpacedString,
    /// A numeric value, stored as a number rather than a string.
    Number,
    /// A true-or-false value, stored as a JSON boolean. A bundle gives the
    /// cell an unset state beside the two and writes it as an absent field
    /// rather than as `false`, so a row nobody has answered is told apart from
    /// one answered no.
    Boolean,
    /// A value chosen from `options`, or from `options_by` when the list
    /// depends on another column.
    Select,
    /// A read-only value taken from the row's derivation by `from`.
    Computed,
    /// A key-to-value object, rendered as one chip per entry.
    Map,
}

/// One column of a table.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Column {
    field: String,
    label: String,
    #[serde(rename = "type")]
    kind: ColumnType,
    #[serde(skip_serializing_if = "is_false")]
    allow_empty: bool,
    #[serde(skip_serializing_if = "is_false")]
    wide: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    width_ch: Option<u16>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    options: Vec<SelectOption>,
    #[serde(skip_serializing_if = "Option::is_none")]
    options_by: Option<OptionsBy>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    cascades_to: Vec<String>,
    #[serde(skip_serializing_if = "is_false")]
    numeric_value: bool,
    #[serde(skip_serializing_if = "is_false")]
    int_only: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    datalist: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    from: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    speak: Option<Speak>,
    #[serde(skip_serializing_if = "Option::is_none")]
    href: Option<String>,
    #[serde(flatten)]
    map: Option<MapSpec>,
}

impl Column {
    fn base(field: impl Into<String>, label: impl Into<String>, kind: ColumnType) -> Self {
        Self {
            field: field.into(),
            label: label.into(),
            kind,
            allow_empty: false,
            wide: false,
            width_ch: None,
            options: Vec::new(),
            options_by: None,
            cascades_to: Vec::new(),
            numeric_value: false,
            int_only: false,
            datalist: None,
            from: None,
            speak: None,
            href: None,
            map: None,
        }
    }

    pub fn string(field: impl Into<String>, label: impl Into<String>) -> Self {
        Self::base(field, label, ColumnType::String)
    }

    pub fn text(field: impl Into<String>, label: impl Into<String>) -> Self {
        Self::base(field, label, ColumnType::Text)
    }

    pub fn spaced_string(field: impl Into<String>, label: impl Into<String>) -> Self {
        Self::base(field, label, ColumnType::SpacedString)
    }

    pub fn number(field: impl Into<String>, label: impl Into<String>) -> Self {
        Self::base(field, label, ColumnType::Number)
    }

    /// A true-or-false value, which a bundle also lets stand unset. See
    /// [`ColumnType::Boolean`] for what unset is written as.
    pub fn boolean(field: impl Into<String>, label: impl Into<String>) -> Self {
        Self::base(field, label, ColumnType::Boolean)
    }

    /// A select over a fixed list of options.
    pub fn select(
        field: impl Into<String>,
        label: impl Into<String>,
        options: impl IntoIterator<Item = impl Into<SelectOption>>,
    ) -> Self {
        Self {
            options: options.into_iter().map(Into::into).collect(),
            ..Self::base(field, label, ColumnType::Select)
        }
    }

    /// A select whose options depend on another column's value.
    pub fn select_by(
        field: impl Into<String>,
        label: impl Into<String>,
        options_by: OptionsBy,
    ) -> Self {
        Self {
            options_by: Some(options_by),
            ..Self::base(field, label, ColumnType::Select)
        }
    }

    /// A read-only column showing `from` out of each row's derived object.
    pub fn computed(
        field: impl Into<String>,
        label: impl Into<String>,
        from: impl Into<String>,
    ) -> Self {
        Self {
            from: Some(from.into()),
            ..Self::base(field, label, ColumnType::Computed)
        }
    }

    /// A key-to-value object rendered as one chip per entry.
    pub fn map(field: impl Into<String>, label: impl Into<String>, spec: MapSpec) -> Self {
        Self {
            map: Some(spec),
            ..Self::base(field, label, ColumnType::Map)
        }
    }

    /// Offer a blank choice on a select whose value may legitimately be unset.
    pub fn allow_empty(mut self) -> Self {
        self.allow_empty = true;
        self
    }

    /// Let the column take the remaining width of the row.
    pub fn wide(mut self) -> Self {
        self.wide = true;
        self
    }

    /// Store the chosen option's value as a number rather than a string.
    pub fn numeric_value(mut self) -> Self {
        self.numeric_value = true;
        self
    }

    /// Confine a number column to whole numbers: a bundle rounds what the cell
    /// is given and steps it by one.
    pub fn int_only(mut self) -> Self {
        self.int_only = true;
        self
    }

    /// A fixed width in characters, for a column whose content the browser
    /// cannot measure.
    pub fn width_ch(mut self, width_ch: u16) -> Self {
        self.width_ch = Some(width_ch);
        self
    }

    /// Columns whose value is cleared when this one changes, because their
    /// options are drawn from it.
    pub fn cascades_to(mut self, fields: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.cascades_to = fields.into_iter().map(Into::into).collect();
        self
    }

    /// The completion list this column's input offers, named among the
    /// schema's `datalists`.
    pub fn datalist(mut self, name: impl Into<String>) -> Self {
        self.datalist = Some(name.into());
        self
    }

    /// Where the cell's play button sends the value to be spoken.
    pub fn speak(mut self, speak: Speak) -> Self {
        self.speak = Some(speak);
        self
    }

    /// Show this column's value as a link, to the URL held by another field of
    /// the same row.
    ///
    /// It is honoured where a cell is read rather than edited—a `computed`
    /// column of a table, every column of a view—and ignored elsewhere, since
    /// a cell being typed into cannot also be a link. A bundle opens it in a
    /// new tab, and follows only `http:` and `https:`, so a row carrying
    /// something else in that field is text rather than a way to run it.
    pub fn href(mut self, field: impl Into<String>) -> Self {
        self.href = Some(field.into());
        self
    }
}

/// One choice in a select. `label` is what the browser shows when it differs
/// from the stored value.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SelectOption {
    pub value: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

impl SelectOption {
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: None,
        }
    }

    pub fn labelled(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: Some(label.into()),
        }
    }
}

impl From<&str> for SelectOption {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for SelectOption {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&String> for SelectOption {
    fn from(value: &String) -> Self {
        Self::new(value.as_str())
    }
}

/// A select whose options depend on another column: the browser looks the row's
/// value of `field` up in `options`. A value with no entry offers no choices.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct OptionsBy {
    pub field: String,
    pub options: BTreeMap<String, Vec<SelectOption>>,
}

impl OptionsBy {
    pub fn new(field: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            options: BTreeMap::new(),
        }
    }

    pub fn with(
        mut self,
        value: impl Into<String>,
        options: impl IntoIterator<Item = impl Into<SelectOption>>,
    ) -> Self {
        self.insert(value, options);
        self
    }

    pub fn insert(
        &mut self,
        value: impl Into<String>,
        options: impl IntoIterator<Item = impl Into<SelectOption>>,
    ) {
        self.options
            .insert(value.into(), options.into_iter().map(Into::into).collect());
    }
}

/// Where a cell's play button sends its value. A bundle substitutes the
/// URL-encoded cell value for `{value}`, and lets a `localStorage` entry under
/// `storage_key` override the origin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Speak {
    pub url: String,
    pub storage_key: String,
}

impl Speak {
    pub fn new(url: impl Into<String>, storage_key: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            storage_key: storage_key.into(),
        }
    }
}

/// What a map's chips put before the value: the key's label, or the key
/// itself.
///
/// A key that stands for a long title makes for tall rows once a cell holds
/// several entries, and the label is in the panel either way, so a table whose
/// keys are short codes can show those instead.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ChipContent {
    /// The key's label, falling back to the key where it has none.
    #[default]
    Label,
    /// The key as it is stored.
    Key,
}

impl ChipContent {
    /// Whether this is what a chip shows unless a table says otherwise, which
    /// is the case the JSON leaves out.
    fn is_label(&self) -> bool {
        matches!(self, ChipContent::Label)
    }
}

/// The extra description a `map` column carries. A bundle renders one chip per
/// entry as `key: value`, drops an entry whose value is cleared, and writes a
/// map that empties as an absent field.
///
/// A key option carries a label of its own where the stored key is not what a
/// reader should see—a code beside the title it stands for, say—so
/// `key_options` takes the same `{ value, label }` pairs a select's options do,
/// and a bundle shows the label in place of the value it stores.
///
/// Both option lists are always written, empty or not, because together with
/// the two `allow_new_` flags they are what the control is made of. This is
/// unlike a select's `options`, which is omitted when empty because a select
/// carries `options_by` instead.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MapSpec {
    pub key_label: String,
    pub value_label: String,
    pub key_options: Vec<SelectOption>,
    pub value_options: Vec<SelectOption>,
    /// Let a key be typed that `key_options` does not list.
    pub allow_new_keys: bool,
    /// Let a value be typed that `value_options` does not list, which makes
    /// those options suggestions rather than the whole choice.
    pub allow_new_values: bool,
    /// What a chip shows before the value. Unlike the fields above, which
    /// together are what the control is made of, this is a preference about
    /// how a cell reads, so the usual case is left out of the JSON.
    #[serde(skip_serializing_if = "ChipContent::is_label")]
    pub chip: ChipContent,
}

impl MapSpec {
    pub fn new(key_label: impl Into<String>, value_label: impl Into<String>) -> Self {
        Self {
            key_label: key_label.into(),
            value_label: value_label.into(),
            key_options: Vec::new(),
            value_options: Vec::new(),
            allow_new_keys: false,
            allow_new_values: false,
            chip: ChipContent::Label,
        }
    }

    /// The keys a bundle offers. A plain string is a key that shows itself; a
    /// [`SelectOption::labelled`] key is shown by its label and stored by its
    /// value.
    pub fn key_options(mut self, keys: impl IntoIterator<Item = impl Into<SelectOption>>) -> Self {
        self.key_options = keys.into_iter().map(Into::into).collect();
        self
    }

    pub fn value_options(
        mut self,
        values: impl IntoIterator<Item = impl Into<SelectOption>>,
    ) -> Self {
        self.value_options = values.into_iter().map(Into::into).collect();
        self
    }

    pub fn allow_new_keys(mut self) -> Self {
        self.allow_new_keys = true;
        self
    }

    pub fn allow_new_values(mut self) -> Self {
        self.allow_new_values = true;
        self
    }

    /// Show the stored key on a chip rather than its label, which keeps a cell
    /// of several entries short where the labels are long. The panel that
    /// edits the entries shows both either way.
    pub fn chips_show_key(mut self) -> Self {
        self.chip = ChipContent::Key;
        self
    }
}

/// How a new row starts: take `defaults`, then overwrite each field named in
/// `carry_forward` with the value the last row that has one carries, so a run
/// of rows sharing a genre or a publisher is typed once.
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct NewRow {
    pub defaults: serde_json::Map<String, serde_json::Value>,
    pub carry_forward: Vec<String>,
}

impl NewRow {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with(mut self, field: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
        self.defaults.insert(field.into(), value.into());
        self
    }

    pub fn carry_forward(mut self, fields: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.carry_forward = fields.into_iter().map(Into::into).collect();
        self
    }
}

/// A completion list a column's input draws on, in one of two forms: a fixed
/// list the server computed, or one the browser computes live from the rows on
/// screen.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Datalist {
    /// A list the server built, typically from a sibling table.
    Fixed { options: Vec<String> },
    /// A list built from the rows on screen.
    Live { from_rows: FromRows },
}

impl Datalist {
    pub fn fixed(options: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self::Fixed {
            options: options.into_iter().map(Into::into).collect(),
        }
    }

    pub fn from_rows(
        fields: impl IntoIterator<Item = impl Into<String>>,
        separator: impl Into<String>,
    ) -> Self {
        Self::Live {
            from_rows: FromRows {
                fields: fields.into_iter().map(Into::into).collect(),
                separator: separator.into(),
            },
        }
    }
}

/// A completion list the browser builds from the rows on screen: trim each
/// named field, drop the row when the first field is blank, join the non-blank
/// ones with `separator`, then dedupe and sort.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FromRows {
    pub fields: Vec<String>,
    pub separator: String,
}

fn is_false(value: &bool) -> bool {
    !*value
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    /// A worked example: a select with a fixed option list that cascades into a
    /// dependent one, a computed width, a wide text column, and no datalists.
    fn books_schema() -> Schema {
        let mut schema = Schema::new([
            Column::string("title", "Title"),
            Column::select("genre", "Genre", ["Reference", "Travel"])
                .allow_empty()
                .cascades_to(["subgenre"]),
            Column::select_by(
                "subgenre",
                "Subgenre",
                OptionsBy::new("genre")
                    .with("Reference", ["Natural History"])
                    .with("Travel", ["Field Guides"]),
            )
            .allow_empty()
            .width_ch(18),
            Column::select("format", "Format", ["Hardcover", "Paperback", "Folio"]),
            Column::number("copies", "Copies").int_only(),
            Column::boolean("lent", "Lent"),
            Column::text("comment", "Comment").wide(),
        ])
        .new_row(
            NewRow::new()
                .with("title", "")
                .with("genre", "")
                .with("subgenre", "")
                .with("format", "Paperback")
                .with("copies", 1)
                .with("comment", ""),
        );
        schema.identify("books", "Books");
        schema
    }

    #[test]
    fn schema_serializes_to_the_documented_shape() {
        assert_eq!(
            serde_json::to_value(books_schema()).unwrap(),
            json!({
              "table": "books",
              "title": "Books",
              "columns": [
                { "field": "title", "label": "Title", "type": "string" },
                { "field": "genre", "label": "Genre", "type": "select", "allow_empty": true,
                  "options": [{ "value": "Reference" }, { "value": "Travel" }],
                  "cascades_to": ["subgenre"] },
                { "field": "subgenre", "label": "Subgenre", "type": "select", "allow_empty": true,
                  "width_ch": 18,
                  "options_by": { "field": "genre",
                    "options": { "Reference": [{ "value": "Natural History" }],
                                 "Travel": [{ "value": "Field Guides" }] } } },
                { "field": "format", "label": "Format", "type": "select",
                  "options": [{ "value": "Hardcover" }, { "value": "Paperback" }, { "value": "Folio" }] },
                { "field": "copies", "label": "Copies", "type": "number", "int_only": true },
                { "field": "lent", "label": "Lent", "type": "boolean" },
                { "field": "comment", "label": "Comment", "type": "text", "wide": true }
              ],
              "new_row": { "defaults": { "title": "", "genre": "", "subgenre": "", "format": "Paperback",
                                         "copies": 1, "comment": "" },
                           "carry_forward": [] },
              "datalists": {}
            })
        );
    }

    #[test]
    fn identify_replaces_whatever_was_there() {
        let mut schema = Schema::new([]);
        schema.identify("first", "First");
        schema.identify("second", "Second");
        let json = serde_json::to_value(schema).unwrap();
        assert_eq!(json["table"], "second");
        assert_eq!(json["title"], "Second");
    }

    #[test]
    fn map_column_serializes_to_the_documented_shape() {
        let column = Column::map(
            "shelved",
            "Shelved",
            MapSpec::new("Branch", "Count")
                .key_options(["Central", "Eastside", "Harbour"])
                .value_options(["None", "One", "Several"]),
        );

        assert_eq!(
            serde_json::to_value(column).unwrap(),
            json!({ "field": "shelved", "label": "Shelved", "type": "map",
                    "key_label": "Branch", "value_label": "Count",
                    "key_options": [{ "value": "Central" }, { "value": "Eastside" },
                                    { "value": "Harbour" }],
                    "value_options": [{ "value": "None" }, { "value": "One" },
                                      { "value": "Several" }],
                    "allow_new_keys": false, "allow_new_values": false })
        );
    }

    #[test]
    fn a_chip_shows_the_key_only_where_a_table_asks_for_it() {
        let by_label = serde_json::to_value(MapSpec::new("Branch", "Count")).unwrap();
        assert!(by_label.get("chip").is_none());

        let by_key =
            serde_json::to_value(MapSpec::new("Branch", "Count").chips_show_key()).unwrap();
        assert_eq!(by_key["chip"], "key");
    }

    #[test]
    fn a_maps_option_lists_are_written_even_when_empty() {
        assert_eq!(
            serde_json::to_value(MapSpec::new("Branch", "Count")).unwrap(),
            json!({ "key_label": "Branch", "value_label": "Count",
                    "key_options": [], "value_options": [],
                    "allow_new_keys": false, "allow_new_values": false })
        );

        // Unlike a select, whose options are omitted when it has none.
        let select = serde_json::to_value(Column::select_by(
            "subgenre",
            "Subgenre",
            OptionsBy::new("genre"),
        ))
        .unwrap();
        assert!(select.get("options").is_none());
    }

    #[test]
    fn a_map_key_can_show_a_label_beside_the_stored_value() {
        let spec = MapSpec::new("Branch", "Count")
            .key_options([SelectOption::labelled("hb", "Harbour"), "Central".into()]);

        assert_eq!(
            serde_json::to_value(spec).unwrap()["key_options"],
            json!([{ "value": "hb", "label": "Harbour" }, { "value": "Central" }])
        );
    }

    #[test]
    fn a_map_can_take_values_its_options_do_not_list() {
        let open = serde_json::to_value(
            MapSpec::new("Branch", "Note")
                .value_options(["None"])
                .allow_new_values(),
        )
        .unwrap();
        assert_eq!(open["allow_new_values"], true);
        assert_eq!(open["value_options"], json!([{ "value": "None" }]));
    }

    #[test]
    fn column_types_serialize_in_kebab_case() {
        for (column, name) in [
            (Column::string("f", "F"), "string"),
            (Column::text("f", "F"), "text"),
            (Column::spaced_string("f", "F"), "spaced-string"),
            (Column::number("f", "F"), "number"),
            (Column::boolean("f", "F"), "boolean"),
            (Column::select("f", "F", ["a"]), "select"),
            (Column::select_by("f", "F", OptionsBy::new("g")), "select"),
            (Column::computed("f", "F", "k"), "computed"),
            (Column::map("f", "F", MapSpec::new("K", "V")), "map"),
        ] {
            assert_eq!(serde_json::to_value(column).unwrap()["type"], name);
        }
    }

    #[test]
    fn int_only_is_omitted_unless_set() {
        let plain = serde_json::to_value(Column::number("copies", "Copies")).unwrap();
        assert!(plain.get("int_only").is_none());

        let whole = serde_json::to_value(Column::number("copies", "Copies").int_only()).unwrap();
        assert_eq!(whole["int_only"], true);
    }

    #[test]
    fn a_select_always_carries_one_source_of_options() {
        let fixed = serde_json::to_value(Column::select("f", "F", ["a"])).unwrap();
        assert!(fixed.get("options").is_some());
        assert!(fixed.get("options_by").is_none());

        let dependent =
            serde_json::to_value(Column::select_by("f", "F", OptionsBy::new("g"))).unwrap();
        assert!(dependent.get("options").is_none());
        assert!(dependent.get("options_by").is_some());
    }

    #[test]
    fn absent_options_are_omitted_rather_than_null() {
        let json = serde_json::to_value(Column::string("title", "Title")).unwrap();
        let object = json.as_object().unwrap();
        assert_eq!(
            object.keys().map(String::as_str).collect::<Vec<_>>(),
            ["field", "label", "type"]
        );
    }

    #[test]
    fn computed_column_names_its_derived_key() {
        let json = serde_json::to_value(Column::computed("age", "Age", "age_years")).unwrap();
        assert_eq!(json["type"], "computed");
        assert_eq!(json["from"], "age_years");
    }

    #[test]
    fn a_column_names_the_datalist_its_input_offers() {
        let column = Column::string("author_last", "Author").datalist("author-names");
        assert_eq!(
            serde_json::to_value(column).unwrap()["datalist"],
            "author-names"
        );
    }

    #[test]
    fn labelled_and_numeric_options_carry_both_halves() {
        let column = Column::select(
            "month",
            "Month",
            [SelectOption::labelled("1", "January (1)")],
        )
        .numeric_value();
        let json = serde_json::to_value(column).unwrap();
        assert_eq!(
            json["options"][0],
            json!({ "value": "1", "label": "January (1)" })
        );
        assert_eq!(json["numeric_value"], true);
    }

    #[test]
    fn speak_carries_the_url_template_and_storage_key() {
        let column = Column::string("pronunciation", "Pronunciation").speak(Speak::new(
            "http://127.0.0.1:8765/say?text={value}",
            "speech-service-url",
        ));
        assert_eq!(
            serde_json::to_value(column).unwrap()["speak"],
            json!({ "url": "http://127.0.0.1:8765/say?text={value}",
                    "storage_key": "speech-service-url" })
        );
    }

    #[test]
    fn both_datalist_forms_serialize_by_their_own_key() {
        let schema = Schema::new([])
            .datalist("genre-names", Datalist::fixed(["Reference", "Travel"]))
            .datalist(
                "author-names",
                Datalist::from_rows(["author_first", "author_last"], " "),
            );

        assert_eq!(
            serde_json::to_value(schema).unwrap()["datalists"],
            json!({
                "genre-names": { "options": ["Reference", "Travel"] },
                "author-names": { "from_rows": { "fields": ["author_first", "author_last"],
                                                 "separator": " " } }
            })
        );
    }

    #[test]
    fn sortable_is_omitted_unless_set() {
        let plain = serde_json::to_value(Schema::new([])).unwrap();
        assert!(plain.get("sortable").is_none());

        let sorted = serde_json::to_value(Schema::new([]).sortable()).unwrap();
        assert_eq!(sorted["sortable"], true);
    }

    #[test]
    fn new_row_carries_defaults_and_carried_fields() {
        let new_row = NewRow::new()
            .with("genre", "Reference")
            .with("copies", 1)
            .carry_forward(["genre", "subgenre", "format"]);
        assert_eq!(
            serde_json::to_value(new_row).unwrap(),
            json!({ "defaults": { "genre": "Reference", "copies": 1 },
                    "carry_forward": ["genre", "subgenre", "format"] })
        );
    }
}