quillmark-core 0.95.1

Core types and functionality for the Quillmark schema-driven document engine
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
//! Schema construction utilities for Quill bundles.
//!
//! This module contains `build_transform_schema`, which maps the abstract
//! [`FieldSchema`] / [`FieldType`] model to a JSON-Schema-shaped
//! [`QuillValue`]. The schema is backend-agnostic (no Typst specifics);
//! backends consume it to drive per-field transforms such as markdown →
//! backend-markup conversion.

use super::{FieldSchema, FieldType, QuillConfig};
use crate::value::QuillValue;

/// The `contentMediaType` marking a richtext field in the transform schema. The
/// value crossing the seam for such a field is canonical Content-JSON (an
/// object), not a string — backends classify on this media type to lower the
/// content rather than a scalar.
pub const CONTENT_MEDIA_TYPE: &str = "application/quillmark-content+json";

/// Transform-schema keyword marking a single-`Para` richtext field (`inline: true`
/// in Quill.yaml). Blueprint still emits `richtext(inline)<markdown>`; this key
/// is the JSON Schema–shaped wire for editor and backend consumers.
pub const QUILLMARK_INLINE_KEY: &str = "quillmark:inline";

/// Transform-schema keyword marking a `plaintext` field — the literal-codec
/// sibling of richtext. It rides the same [`CONTENT_MEDIA_TYPE`], so backends
/// lower it identically; this annotation only tells editors to mount a
/// formatting-free surface and to author/project through the literal codec.
pub const QUILLMARK_PLAIN_KEY: &str = "quillmark:plain";

/// Build a JSON-Schema-shaped descriptor of a [`QuillConfig`]'s main + card fields.
///
/// The descriptor marks richtext fields with `contentMediaType:
/// application/quillmark-content+json` (see [`CONTENT_MEDIA_TYPE`]) and
/// date/date-time fields with the corresponding JSON Schema `format`.
///
/// `$body` is injected into a kind's `properties` only when that kind's
/// `body.enabled` is not `false`. A body-disabled kind's `$body` is absent,
/// not present-and-empty: absence cascades through the `__meta__` address
/// tables so `form-field(field:)` rejects `$body` addresses on that
/// kind at compile time, matching `Quill::validate`'s hard error on authored
/// body content for the same kind.
pub fn build_transform_schema(config: &QuillConfig) -> QuillValue {
    fn field_to_schema(field: &FieldSchema) -> serde_json::Value {
        let mut schema = serde_json::Map::new();
        match field.r#type {
            FieldType::String => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("string".to_string()),
                );
            }
            FieldType::RichText { inline } => {
                // The content crosses the seam as a JSON object (canonical
                // Content-JSON), not a string; `type: object` + the richtext
                // media type is how a backend classifies it to lower the content.
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("object".to_string()),
                );
                schema.insert(
                    "contentMediaType".to_string(),
                    serde_json::Value::String(CONTENT_MEDIA_TYPE.to_string()),
                );
                if inline {
                    schema.insert(
                        QUILLMARK_INLINE_KEY.to_string(),
                        serde_json::Value::Bool(true),
                    );
                }
            }
            FieldType::PlainText { inline } => {
                // Plaintext rides the *same* content and media type as richtext, so
                // a backend classifies and lowers it identically — no backend edit.
                // The distinction (literal codec, no formatting) is carried by the
                // `quillmark:plain` annotation, which only editors consult.
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("object".to_string()),
                );
                schema.insert(
                    "contentMediaType".to_string(),
                    serde_json::Value::String(CONTENT_MEDIA_TYPE.to_string()),
                );
                schema.insert(QUILLMARK_PLAIN_KEY.to_string(), serde_json::Value::Bool(true));
                if inline {
                    schema.insert(
                        QUILLMARK_INLINE_KEY.to_string(),
                        serde_json::Value::Bool(true),
                    );
                }
            }
            FieldType::Enum => {
                // The promoted token projects to the idiomatic JSON-Schema
                // spelling `{type: string, enum: [...]}` — exactly what a backend
                // dispatches on today (a plain string), plus the finite domain.
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("string".to_string()),
                );
                if let Some(values) = &field.enum_values {
                    schema.insert(
                        "enum".to_string(),
                        serde_json::Value::Array(
                            values
                                .iter()
                                .map(|v| serde_json::Value::String(v.clone()))
                                .collect(),
                        ),
                    );
                }
            }
            FieldType::Number => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("number".to_string()),
                );
            }
            FieldType::Integer => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("integer".to_string()),
                );
            }
            FieldType::Boolean => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("boolean".to_string()),
                );
            }
            FieldType::Array => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("array".to_string()),
                );
                // The element schema is emitted recursively, so a scalar
                // element yields `items: {type: string}` (and a richtext element
                // carries its `contentMediaType`), while an object element yields
                // `items: {type: object, properties: …}`.
                if let Some(items) = &field.items {
                    schema.insert("items".to_string(), field_to_schema(items));
                }
            }
            FieldType::Object => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("object".to_string()),
                );
                if let Some(properties) = &field.properties {
                    let mut props = serde_json::Map::new();
                    for (name, prop) in properties {
                        props.insert(name.clone(), field_to_schema(prop));
                    }
                    schema.insert("properties".to_string(), serde_json::Value::Object(props));
                }
            }
            // Distinct markers for the two date types drive the Typst backend's
            // per-type lowering (3-component vs 6-component `datetime(..)`). This
            // is the internal transform schema; the marker precedent is
            // `quillmark:inline`.
            FieldType::Date => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("string".to_string()),
                );
                schema.insert(
                    "format".to_string(),
                    serde_json::Value::String("date".to_string()),
                );
            }
            FieldType::DateTime => {
                schema.insert(
                    "type".to_string(),
                    serde_json::Value::String("string".to_string()),
                );
                schema.insert(
                    "format".to_string(),
                    serde_json::Value::String("date-time".to_string()),
                );
            }
        }
        serde_json::Value::Object(schema)
    }

    let mut properties = serde_json::Map::new();
    for (name, field) in &config.main.fields {
        properties.insert(name.clone(), field_to_schema(field));
    }
    if config.main.body_enabled() {
        properties.insert(
            "$body".to_string(),
            serde_json::json!({ "type": "object", "contentMediaType": CONTENT_MEDIA_TYPE }),
        );
    }

    let mut defs = serde_json::Map::new();
    for card in &config.card_kinds {
        let mut card_properties = serde_json::Map::new();
        for (name, field) in &card.fields {
            card_properties.insert(name.clone(), field_to_schema(field));
        }
        if card.body_enabled() {
            card_properties.insert(
                "$body".to_string(),
                serde_json::json!({ "type": "object", "contentMediaType": CONTENT_MEDIA_TYPE }),
            );
        }
        defs.insert(
            format!("{}_card", card.name),
            serde_json::json!({
                "type": "object",
                "properties": card_properties,
            }),
        );
    }

    QuillValue::from_json(serde_json::json!({
        "type": "object",
        "properties": properties,
        "$defs": defs,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn build_from_yaml(yaml: &str) -> QuillValue {
        let config = QuillConfig::from_yaml(yaml).expect("yaml parses");
        build_transform_schema(&config)
    }

    #[test]
    fn typed_table_emits_items_with_object_and_properties() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    refs:
      type: array
      items:
        type: object
        properties:
          org: { type: string }
          year: { type: integer }
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let refs = &json["properties"]["refs"];
        assert_eq!(refs["type"], "array");
        assert_eq!(refs["items"]["type"], "object");
        assert_eq!(refs["items"]["properties"]["org"]["type"], "string");
        assert_eq!(refs["items"]["properties"]["year"]["type"], "integer");
    }

    #[test]
    fn scalar_array_emits_items_with_element_type() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    counts:
      type: array
      items: { type: integer }
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let counts = &json["properties"]["counts"];
        assert_eq!(counts["type"], "array");
        assert_eq!(counts["items"]["type"], "integer");
    }

    #[test]
    fn markdown_array_emits_items_with_content_media_type() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    sections:
      type: array
      items: { type: richtext }
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let sections = &json["properties"]["sections"];
        assert_eq!(sections["type"], "array");
        assert_eq!(sections["items"]["type"], "object");
        assert_eq!(sections["items"]["contentMediaType"], CONTENT_MEDIA_TYPE);
    }

    #[test]
    fn typed_dict_emits_object_with_properties() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    address:
      type: object
      properties:
        street: { type: string }
        city: { type: string }
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let address = &json["properties"]["address"];
        assert_eq!(address["type"], "object");
        assert_eq!(address["properties"]["street"]["type"], "string");
        assert_eq!(address["properties"]["city"]["type"], "string");
    }

    #[test]
    fn injects_body_as_markdown_for_main_and_each_card_kind() {
        let yaml = r#"
quill:
  name: example
  version: 0.1.0
  backend: typst
  description: example

main:
  fields:
    title:
      type: string

card_kinds:
  indorsement:
    fields:
      signature_block:
        type: string
  note:
    fields:
      author:
        type: string
"#;

        let schema = build_from_yaml(yaml);
        let json = schema.as_json();

        let main_body = &json["properties"]["$body"];
        assert_eq!(main_body["type"], "object");
        assert_eq!(main_body["contentMediaType"], CONTENT_MEDIA_TYPE);

        for def_name in ["indorsement_card", "note_card"] {
            let card_body = &json["$defs"][def_name]["properties"]["$body"];
            assert_eq!(
                card_body["type"], "object",
                "{def_name} $body type should be object"
            );
            assert_eq!(
                card_body["contentMediaType"], CONTENT_MEDIA_TYPE,
                "{def_name} $body should be richtext"
            );
        }
    }

    #[test]
    fn inline_richtext_emits_quillmark_inline() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    subject:
      type: richtext
      inline: true
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let subject = &json["properties"]["subject"];
        assert_eq!(subject["type"], "object");
        assert_eq!(subject["contentMediaType"], CONTENT_MEDIA_TYPE);
        assert_eq!(subject[QUILLMARK_INLINE_KEY], true);
    }

    #[test]
    fn inline_richtext_array_items_emit_quillmark_inline() {
        let yaml = r#"
quill:
  name: x
  version: 1.0.0
  backend: typst
  description: x
main:
  fields:
    refs:
      type: array
      items:
        type: richtext
        inline: true
"#;
        let schema = build_from_yaml(yaml);
        let json = schema.as_json();
        let items = &json["properties"]["refs"]["items"];
        assert_eq!(items[QUILLMARK_INLINE_KEY], true);
    }

    #[test]
    fn body_disabled_kind_omits_body_from_schema() {
        let yaml = r#"
quill:
  name: example
  version: 0.1.0
  backend: typst
  description: example

main:
  body:
    enabled: false
  fields:
    title:
      type: string

card_kinds:
  indorsement:
    body:
      enabled: false
    fields:
      signature_block:
        type: string
  note:
    fields:
      author:
        type: string
"#;

        let schema = build_from_yaml(yaml);
        let json = schema.as_json();

        assert!(
            json["properties"].get("$body").is_none(),
            "body-disabled main should not carry $body"
        );
        assert!(
            json["$defs"]["indorsement_card"]["properties"]
                .get("$body")
                .is_none(),
            "body-disabled card kind should not carry $body"
        );
        assert!(
            json["$defs"]["note_card"]["properties"]
                .get("$body")
                .is_some(),
            "body-enabled card kind should still carry $body"
        );
    }
}