quillmark_core/
quill.rs

1//! Quill template bundle types and implementations.
2
3use std::collections::HashMap;
4use std::error::Error as StdError;
5use std::path::{Path, PathBuf};
6
7use crate::value::QuillValue;
8
9/// UI-specific metadata for field rendering
10#[derive(Debug, Clone, PartialEq)]
11pub struct UiSchema {
12    /// Group name for organizing fields (e.g., "Personal Info", "Preferences")
13    pub group: Option<String>,
14    /// Order of the field in the UI (automatically generated based on field position in Quill.toml)
15    pub order: Option<i32>,
16}
17
18/// Schema definition for a card type (composable content blocks)
19#[derive(Debug, Clone, PartialEq)]
20pub struct CardSchema {
21    /// Card type name (e.g., "indorsements")
22    pub name: String,
23    /// Short label for the card type
24    pub title: Option<String>,
25    /// Detailed description of this card type
26    pub description: String,
27    /// UI-specific metadata for rendering
28    pub ui: Option<UiSchema>,
29    /// Field definitions for this card type
30    pub fields: HashMap<String, FieldSchema>,
31}
32
33/// Schema definition for a template field
34#[derive(Debug, Clone, PartialEq)]
35pub struct FieldSchema {
36    pub name: String,
37    /// Short label for the field (used in JSON Schema title)
38    pub title: Option<String>,
39    /// Field type hint (e.g., "string", "number", "boolean", "object", "array")
40    pub r#type: Option<String>,
41    /// Detailed description of the field (used in JSON Schema description)
42    pub description: String,
43    /// Default value for the field
44    pub default: Option<QuillValue>,
45    /// Example values for the field
46    pub examples: Option<QuillValue>,
47    /// UI-specific metadata for rendering
48    pub ui: Option<UiSchema>,
49    /// Whether this field is required (fields are optional by default)
50    pub required: bool,
51}
52
53impl FieldSchema {
54    /// Create a new FieldSchema with default values
55    pub fn new(name: String, description: String) -> Self {
56        Self {
57            name,
58            title: None,
59            r#type: None,
60            description,
61            default: None,
62            examples: None,
63            ui: None,
64            required: false,
65        }
66    }
67
68    /// Parse a FieldSchema from a QuillValue
69    pub fn from_quill_value(key: String, value: &QuillValue) -> Result<Self, String> {
70        let obj = value
71            .as_object()
72            .ok_or_else(|| "Field schema must be an object".to_string())?;
73
74        //Ensure only known keys are present
75        for key in obj.keys() {
76            match key.as_str() {
77                "name" | "title" | "type" | "description" | "examples" | "default" | "ui"
78                | "required" => {}
79                _ => {
80                    // Log warning but don't fail
81                    eprintln!("Warning: Unknown key '{}' in field schema", key);
82                }
83            }
84        }
85
86        let name = key.clone();
87
88        let title = obj
89            .get("title")
90            .and_then(|v| v.as_str())
91            .map(|s| s.to_string());
92
93        let description = obj
94            .get("description")
95            .and_then(|v| v.as_str())
96            .unwrap_or("")
97            .to_string();
98
99        let field_type = obj
100            .get("type")
101            .and_then(|v| v.as_str())
102            .map(|s| s.to_string());
103
104        let default = obj.get("default").map(|v| QuillValue::from_json(v.clone()));
105
106        let examples = obj
107            .get("examples")
108            .map(|v| QuillValue::from_json(v.clone()));
109
110        // Parse required field (fields are optional by default)
111        let required = obj
112            .get("required")
113            .and_then(|v| v.as_bool())
114            .unwrap_or(false);
115
116        // Parse UI metadata if present
117        let ui = if let Some(ui_value) = obj.get("ui") {
118            if let Some(ui_obj) = ui_value.as_object() {
119                let group = ui_obj
120                    .get("group")
121                    .and_then(|v| v.as_str())
122                    .map(|s| s.to_string());
123
124                // Validate that only known UI properties are present
125                for key in ui_obj.keys() {
126                    match key.as_str() {
127                        "group" => {}
128                        _ => {
129                            eprintln!(
130                                "Warning: Unknown UI property '{}'. Only 'group' is supported.",
131                                key
132                            );
133                        }
134                    }
135                }
136
137                Some(UiSchema {
138                    group,
139                    order: None, // Order is determined by position in Quill.toml
140                })
141            } else {
142                return Err("UI field must be an object".to_string());
143            }
144        } else {
145            None
146        };
147
148        Ok(Self {
149            name,
150            title,
151            r#type: field_type,
152            description,
153            default,
154            examples,
155            ui,
156            required,
157        })
158    }
159}
160
161/// A node in the file tree structure
162#[derive(Debug, Clone)]
163pub enum FileTreeNode {
164    /// A file with its contents
165    File {
166        /// The file contents as bytes or UTF-8 string
167        contents: Vec<u8>,
168    },
169    /// A directory containing other files and directories
170    Directory {
171        /// The files and subdirectories in this directory
172        files: HashMap<String, FileTreeNode>,
173    },
174}
175
176impl FileTreeNode {
177    /// Get a file or directory node by path
178    pub fn get_node<P: AsRef<Path>>(&self, path: P) -> Option<&FileTreeNode> {
179        let path = path.as_ref();
180
181        // Handle root path
182        if path == Path::new("") {
183            return Some(self);
184        }
185
186        // Split path into components
187        let components: Vec<_> = path
188            .components()
189            .filter_map(|c| {
190                if let std::path::Component::Normal(s) = c {
191                    s.to_str()
192                } else {
193                    None
194                }
195            })
196            .collect();
197
198        if components.is_empty() {
199            return Some(self);
200        }
201
202        // Navigate through the tree
203        let mut current_node = self;
204        for component in components {
205            match current_node {
206                FileTreeNode::Directory { files } => {
207                    current_node = files.get(component)?;
208                }
209                FileTreeNode::File { .. } => {
210                    return None; // Can't traverse into a file
211                }
212            }
213        }
214
215        Some(current_node)
216    }
217
218    /// Get file contents by path
219    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
220        match self.get_node(path)? {
221            FileTreeNode::File { contents } => Some(contents.as_slice()),
222            FileTreeNode::Directory { .. } => None,
223        }
224    }
225
226    /// Check if a file exists at the given path
227    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
228        matches!(self.get_node(path), Some(FileTreeNode::File { .. }))
229    }
230
231    /// Check if a directory exists at the given path
232    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
233        matches!(self.get_node(path), Some(FileTreeNode::Directory { .. }))
234    }
235
236    /// List all files in a directory (non-recursive)
237    pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
238        match self.get_node(dir_path) {
239            Some(FileTreeNode::Directory { files }) => files
240                .iter()
241                .filter_map(|(name, node)| {
242                    if matches!(node, FileTreeNode::File { .. }) {
243                        Some(name.clone())
244                    } else {
245                        None
246                    }
247                })
248                .collect(),
249            _ => Vec::new(),
250        }
251    }
252
253    /// List all subdirectories in a directory (non-recursive)
254    pub fn list_subdirectories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
255        match self.get_node(dir_path) {
256            Some(FileTreeNode::Directory { files }) => files
257                .iter()
258                .filter_map(|(name, node)| {
259                    if matches!(node, FileTreeNode::Directory { .. }) {
260                        Some(name.clone())
261                    } else {
262                        None
263                    }
264                })
265                .collect(),
266            _ => Vec::new(),
267        }
268    }
269
270    /// Insert a file or directory at the given path
271    pub fn insert<P: AsRef<Path>>(
272        &mut self,
273        path: P,
274        node: FileTreeNode,
275    ) -> Result<(), Box<dyn StdError + Send + Sync>> {
276        let path = path.as_ref();
277
278        // Split path into components
279        let components: Vec<_> = path
280            .components()
281            .filter_map(|c| {
282                if let std::path::Component::Normal(s) = c {
283                    s.to_str().map(|s| s.to_string())
284                } else {
285                    None
286                }
287            })
288            .collect();
289
290        if components.is_empty() {
291            return Err("Cannot insert at root path".into());
292        }
293
294        // Navigate to parent directory, creating directories as needed
295        let mut current_node = self;
296        for component in &components[..components.len() - 1] {
297            match current_node {
298                FileTreeNode::Directory { files } => {
299                    current_node =
300                        files
301                            .entry(component.clone())
302                            .or_insert_with(|| FileTreeNode::Directory {
303                                files: HashMap::new(),
304                            });
305                }
306                FileTreeNode::File { .. } => {
307                    return Err("Cannot traverse into a file".into());
308                }
309            }
310        }
311
312        // Insert the new node
313        let filename = &components[components.len() - 1];
314        match current_node {
315            FileTreeNode::Directory { files } => {
316                files.insert(filename.clone(), node);
317                Ok(())
318            }
319            FileTreeNode::File { .. } => Err("Cannot insert into a file".into()),
320        }
321    }
322
323    /// Parse a tree structure from JSON value
324    fn from_json_value(value: &serde_json::Value) -> Result<Self, Box<dyn StdError + Send + Sync>> {
325        if let Some(contents_str) = value.get("contents").and_then(|v| v.as_str()) {
326            // It's a file with string contents
327            Ok(FileTreeNode::File {
328                contents: contents_str.as_bytes().to_vec(),
329            })
330        } else if let Some(bytes_array) = value.get("contents").and_then(|v| v.as_array()) {
331            // It's a file with byte array contents
332            let contents: Vec<u8> = bytes_array
333                .iter()
334                .filter_map(|v| v.as_u64().and_then(|n| u8::try_from(n).ok()))
335                .collect();
336            Ok(FileTreeNode::File { contents })
337        } else if let Some(obj) = value.as_object() {
338            // It's a directory (either empty or with nested files)
339            let mut files = HashMap::new();
340            for (name, child_value) in obj {
341                files.insert(name.clone(), Self::from_json_value(child_value)?);
342            }
343            // Empty directories are valid
344            Ok(FileTreeNode::Directory { files })
345        } else {
346            Err(format!("Invalid file tree node: {:?}", value).into())
347        }
348    }
349
350    pub fn print_tree(&self) -> String {
351        self.__print_tree("", "", true)
352    }
353
354    pub fn __print_tree(&self, name: &str, prefix: &str, is_last: bool) -> String {
355        let mut result = String::new();
356
357        // Choose the appropriate tree characters
358        let connector = if is_last { "└── " } else { "├── " };
359        let extension = if is_last { "    " } else { "│   " };
360
361        match self {
362            FileTreeNode::File { .. } => {
363                result.push_str(&format!("{}{}{}\n", prefix, connector, name));
364            }
365            FileTreeNode::Directory { files } => {
366                // Add trailing slash for directories like `tree` does
367                result.push_str(&format!("{}{}{}/\n", prefix, connector, name));
368
369                let child_prefix = format!("{}{}", prefix, extension);
370                let count = files.len();
371
372                for (i, (child_name, node)) in files.iter().enumerate() {
373                    let is_last_child = i == count - 1;
374                    result.push_str(&node.__print_tree(child_name, &child_prefix, is_last_child));
375                }
376            }
377        }
378
379        result
380    }
381}
382
383/// Simple gitignore-style pattern matcher for .quillignore
384#[derive(Debug, Clone)]
385pub struct QuillIgnore {
386    patterns: Vec<String>,
387}
388
389impl QuillIgnore {
390    /// Create a new QuillIgnore from pattern strings
391    pub fn new(patterns: Vec<String>) -> Self {
392        Self { patterns }
393    }
394
395    /// Parse .quillignore content into patterns
396    pub fn from_content(content: &str) -> Self {
397        let patterns = content
398            .lines()
399            .map(|line| line.trim())
400            .filter(|line| !line.is_empty() && !line.starts_with('#'))
401            .map(|line| line.to_string())
402            .collect();
403        Self::new(patterns)
404    }
405
406    /// Check if a path should be ignored
407    pub fn is_ignored<P: AsRef<Path>>(&self, path: P) -> bool {
408        let path = path.as_ref();
409        let path_str = path.to_string_lossy();
410
411        for pattern in &self.patterns {
412            if self.matches_pattern(pattern, &path_str) {
413                return true;
414            }
415        }
416        false
417    }
418
419    /// Simple pattern matching (supports * wildcard and directory patterns)
420    fn matches_pattern(&self, pattern: &str, path: &str) -> bool {
421        // Handle directory patterns
422        if let Some(pattern_prefix) = pattern.strip_suffix('/') {
423            return path.starts_with(pattern_prefix)
424                && (path.len() == pattern_prefix.len()
425                    || path.chars().nth(pattern_prefix.len()) == Some('/'));
426        }
427
428        // Handle exact matches
429        if !pattern.contains('*') {
430            return path == pattern || path.ends_with(&format!("/{}", pattern));
431        }
432
433        // Simple wildcard matching
434        if pattern == "*" {
435            return true;
436        }
437
438        // Handle patterns with wildcards
439        let pattern_parts: Vec<&str> = pattern.split('*').collect();
440        if pattern_parts.len() == 2 {
441            let (prefix, suffix) = (pattern_parts[0], pattern_parts[1]);
442            if prefix.is_empty() {
443                return path.ends_with(suffix);
444            } else if suffix.is_empty() {
445                return path.starts_with(prefix);
446            } else {
447                return path.starts_with(prefix) && path.ends_with(suffix);
448            }
449        }
450
451        false
452    }
453}
454
455/// A quill template bundle.
456#[derive(Debug, Clone)]
457pub struct Quill {
458    /// Quill-specific metadata
459    pub metadata: HashMap<String, QuillValue>,
460    /// Name of the quill
461    pub name: String,
462    /// Backend identifier (e.g., "typst")
463    pub backend: String,
464    /// Plate template content (optional)
465    pub plate: Option<String>,
466    /// Markdown template content (optional)
467    pub example: Option<String>,
468    /// Field JSON schema (single source of truth for schema and defaults)
469    pub schema: QuillValue,
470    /// Cached default values extracted from schema (for performance)
471    pub defaults: HashMap<String, QuillValue>,
472    /// Cached example values extracted from schema (for performance)
473    pub examples: HashMap<String, Vec<QuillValue>>,
474    /// In-memory file system (tree structure)
475    pub files: FileTreeNode,
476}
477
478/// Quill configuration extracted from Quill.toml
479#[derive(Debug, Clone)]
480pub struct QuillConfig {
481    /// Human-readable name
482    pub name: String,
483    /// Description of the quill
484    pub description: String,
485    /// Backend identifier (e.g., "typst")
486    pub backend: String,
487    /// Semantic version of the quill
488    pub version: Option<String>,
489    /// Author of the quill
490    pub author: Option<String>,
491    /// Example markdown file
492    pub example_file: Option<String>,
493    /// Plate file
494    pub plate_file: Option<String>,
495    /// Field schemas
496    pub fields: HashMap<String, FieldSchema>,
497    /// Card schemas (composable content blocks)
498    pub cards: HashMap<String, CardSchema>,
499    /// Additional metadata from [Quill] section (excluding standard fields)
500    pub metadata: HashMap<String, QuillValue>,
501    /// Typst-specific configuration from `[typst]` section
502    pub typst_config: HashMap<String, QuillValue>,
503}
504
505impl QuillConfig {
506    /// Parse QuillConfig from TOML content
507    pub fn from_toml(toml_content: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
508        let quill_toml: toml::Value = toml::from_str(toml_content)
509            .map_err(|e| format!("Failed to parse Quill.toml: {}", e))?;
510
511        // Parse with toml_edit to get field order
512        let (field_order, card_order): (Vec<String>, Vec<String>) = toml_content
513            .parse::<toml_edit::DocumentMut>()
514            .ok()
515            .map(|doc| {
516                let f_order = doc
517                    .get("fields")
518                    .and_then(|item| item.as_table())
519                    .map(|table| table.iter().map(|(k, _)| k.to_string()).collect())
520                    .unwrap_or_default();
521
522                let s_order = doc
523                    .get("cards")
524                    .and_then(|item| item.as_table())
525                    .map(|table| table.iter().map(|(k, _)| k.to_string()).collect())
526                    .unwrap_or_default();
527
528                (f_order, s_order)
529            })
530            .unwrap_or_default();
531
532        // Extract [Quill] section (required)
533        let quill_section = quill_toml
534            .get("Quill")
535            .ok_or("Missing required [Quill] section in Quill.toml")?;
536
537        // Extract required fields
538        let name = quill_section
539            .get("name")
540            .and_then(|v| v.as_str())
541            .ok_or("Missing required 'name' field in [Quill] section")?
542            .to_string();
543
544        let backend = quill_section
545            .get("backend")
546            .and_then(|v| v.as_str())
547            .ok_or("Missing required 'backend' field in [Quill] section")?
548            .to_string();
549
550        let description = quill_section
551            .get("description")
552            .and_then(|v| v.as_str())
553            .ok_or("Missing required 'description' field in [Quill] section")?;
554
555        if description.trim().is_empty() {
556            return Err("'description' field in [Quill] section cannot be empty".into());
557        }
558        let description = description.to_string();
559
560        // Extract optional fields
561        let version = quill_section
562            .get("version")
563            .and_then(|v| v.as_str())
564            .map(|s| s.to_string());
565
566        let author = quill_section
567            .get("author")
568            .and_then(|v| v.as_str())
569            .map(|s| s.to_string());
570
571        let example_file = quill_section
572            .get("example_file")
573            .and_then(|v| v.as_str())
574            .map(|s| s.to_string());
575
576        let plate_file = quill_section
577            .get("plate_file")
578            .and_then(|v| v.as_str())
579            .map(|s| s.to_string());
580
581        // Extract additional metadata from [Quill] section (excluding standard fields)
582        let mut metadata = HashMap::new();
583        if let toml::Value::Table(table) = quill_section {
584            for (key, value) in table {
585                // Skip standard fields that are stored in dedicated struct fields
586                if key != "name"
587                    && key != "backend"
588                    && key != "description"
589                    && key != "version"
590                    && key != "author"
591                    && key != "example_file"
592                    && key != "plate_file"
593                {
594                    match QuillValue::from_toml(value) {
595                        Ok(quill_value) => {
596                            metadata.insert(key.clone(), quill_value);
597                        }
598                        Err(e) => {
599                            eprintln!("Warning: Failed to convert field '{}': {}", key, e);
600                        }
601                    }
602                }
603            }
604        }
605
606        // Extract [typst] section (optional)
607        let mut typst_config = HashMap::new();
608        if let Some(toml::Value::Table(table)) = quill_toml.get("typst") {
609            for (key, value) in table {
610                match QuillValue::from_toml(value) {
611                    Ok(quill_value) => {
612                        typst_config.insert(key.clone(), quill_value);
613                    }
614                    Err(e) => {
615                        eprintln!("Warning: Failed to convert typst field '{}': {}", key, e);
616                    }
617                }
618            }
619        }
620
621        // Extract [fields] section (optional)
622        let mut fields = HashMap::new();
623        if let Some(toml::Value::Table(fields_table)) = quill_toml.get("fields") {
624            let mut order_counter = 0;
625            for (field_name, field_schema) in fields_table {
626                // Determine order
627                let order = if let Some(idx) = field_order.iter().position(|k| k == field_name) {
628                    idx as i32
629                } else {
630                    let o = field_order.len() as i32 + order_counter;
631                    order_counter += 1;
632                    o
633                };
634
635                match QuillValue::from_toml(field_schema) {
636                    Ok(quill_value) => {
637                        match FieldSchema::from_quill_value(field_name.clone(), &quill_value) {
638                            Ok(mut schema) => {
639                                // Always set ui.order based on position in Quill.toml
640                                if schema.ui.is_none() {
641                                    schema.ui = Some(UiSchema {
642                                        group: None,
643                                        order: Some(order),
644                                    });
645                                } else if let Some(ui) = &mut schema.ui {
646                                    ui.order = Some(order);
647                                }
648
649                                fields.insert(field_name.clone(), schema);
650                            }
651                            Err(e) => {
652                                eprintln!(
653                                    "Warning: Failed to parse field schema '{}': {}",
654                                    field_name, e
655                                );
656                            }
657                        }
658                    }
659                    Err(e) => {
660                        eprintln!(
661                            "Warning: Failed to convert field schema '{}': {}",
662                            field_name, e
663                        );
664                    }
665                }
666            }
667        }
668
669        // Extract [cards] section (optional)
670        let mut cards: HashMap<String, CardSchema> = HashMap::new();
671        if let Some(toml::Value::Table(cards_table)) = quill_toml.get("cards") {
672            let current_field_count = fields.len() as i32;
673            let mut order_counter = 0;
674
675            for (card_name, card_value) in cards_table {
676                // Check for name collision with existing fields
677                if fields.contains_key(card_name) {
678                    return Err(format!(
679                        "Card definition '{}' conflicts with an existing field name",
680                        card_name
681                    )
682                    .into());
683                }
684
685                // Determine order (append after fields)
686                let order = if let Some(idx) = card_order.iter().position(|k| k == card_name) {
687                    current_field_count + idx as i32
688                } else {
689                    let o = current_field_count + card_order.len() as i32 + order_counter;
690                    order_counter += 1;
691                    o
692                };
693
694                // Parse card schema
695                let card_table = card_value
696                    .as_table()
697                    .ok_or_else(|| format!("Card definition '{}' must be a table", card_name))?;
698
699                let title = card_table
700                    .get("title")
701                    .and_then(|v| v.as_str())
702                    .map(|s| s.to_string());
703
704                let description = card_table
705                    .get("description")
706                    .and_then(|v| v.as_str())
707                    .unwrap_or("")
708                    .to_string();
709
710                // Parse UI metadata
711                let ui = if let Some(ui_value) = card_table.get("ui") {
712                    if let Some(ui_table) = ui_value.as_table() {
713                        let group = ui_table
714                            .get("group")
715                            .and_then(|v| v.as_str())
716                            .map(|s| s.to_string());
717                        Some(UiSchema {
718                            group,
719                            order: Some(order),
720                        })
721                    } else {
722                        None
723                    }
724                } else {
725                    Some(UiSchema {
726                        group: None,
727                        order: Some(order),
728                    })
729                };
730
731                // Parse [cards.X.fields.Y] - card field definitions
732                let mut card_fields: HashMap<String, FieldSchema> = HashMap::new();
733                if let Some(fields_value) = card_table.get("fields") {
734                    if let Some(fields_table) = fields_value.as_table() {
735                        for (field_name, field_value) in fields_table {
736                            match QuillValue::from_toml(field_value) {
737                                Ok(quill_value) => {
738                                    match FieldSchema::from_quill_value(
739                                        field_name.clone(),
740                                        &quill_value,
741                                    ) {
742                                        Ok(field_schema) => {
743                                            card_fields.insert(field_name.clone(), field_schema);
744                                        }
745                                        Err(e) => {
746                                            eprintln!(
747                                                "Warning: Failed to parse card field '{}.{}': {}",
748                                                card_name, field_name, e
749                                            );
750                                        }
751                                    }
752                                }
753                                Err(e) => {
754                                    eprintln!(
755                                        "Warning: Failed to convert card field '{}.{}': {}",
756                                        card_name, field_name, e
757                                    );
758                                }
759                            }
760                        }
761                    }
762                }
763
764                let card_schema = CardSchema {
765                    name: card_name.clone(),
766                    title,
767                    description,
768                    ui,
769                    fields: card_fields,
770                };
771
772                cards.insert(card_name.clone(), card_schema);
773            }
774        }
775
776        Ok(QuillConfig {
777            name,
778            description,
779            backend,
780            version,
781            author,
782            example_file,
783            plate_file,
784            fields,
785            cards,
786            metadata,
787            typst_config,
788        })
789    }
790}
791
792impl Quill {
793    /// Create a Quill from a directory path
794    pub fn from_path<P: AsRef<std::path::Path>>(
795        path: P,
796    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
797        use std::fs;
798
799        let path = path.as_ref();
800        let name = path
801            .file_name()
802            .and_then(|n| n.to_str())
803            .unwrap_or("unnamed")
804            .to_string();
805
806        // Load .quillignore if it exists
807        let quillignore_path = path.join(".quillignore");
808        let ignore = if quillignore_path.exists() {
809            let ignore_content = fs::read_to_string(&quillignore_path)
810                .map_err(|e| format!("Failed to read .quillignore: {}", e))?;
811            QuillIgnore::from_content(&ignore_content)
812        } else {
813            // Default ignore patterns
814            QuillIgnore::new(vec![
815                ".git/".to_string(),
816                ".gitignore".to_string(),
817                ".quillignore".to_string(),
818                "target/".to_string(),
819                "node_modules/".to_string(),
820            ])
821        };
822
823        // Load all files into a tree structure
824        let root = Self::load_directory_as_tree(path, path, &ignore)?;
825
826        // Create Quill from the file tree
827        Self::from_tree(root, Some(name))
828    }
829
830    /// Create a Quill from a tree structure
831    ///
832    /// This is the authoritative method for creating a Quill from an in-memory file tree.
833    ///
834    /// # Arguments
835    ///
836    /// * `root` - The root node of the file tree
837    /// * `_default_name` - Unused parameter kept for API compatibility (name always from Quill.toml)
838    ///
839    /// # Errors
840    ///
841    /// Returns an error if:
842    /// - Quill.toml is not found in the file tree
843    /// - Quill.toml is not valid UTF-8 or TOML
844    /// - The plate file specified in Quill.toml is not found or not valid UTF-8
845    /// - Validation fails
846    pub fn from_tree(
847        root: FileTreeNode,
848        _default_name: Option<String>,
849    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
850        // Read Quill.toml
851        let quill_toml_bytes = root
852            .get_file("Quill.toml")
853            .ok_or("Quill.toml not found in file tree")?;
854
855        let quill_toml_content = String::from_utf8(quill_toml_bytes.to_vec())
856            .map_err(|e| format!("Quill.toml is not valid UTF-8: {}", e))?;
857
858        // Parse TOML into QuillConfig
859        let config = QuillConfig::from_toml(&quill_toml_content)?;
860
861        // Construct Quill from QuillConfig
862        Self::from_config(config, root)
863    }
864
865    /// Create a Quill from a QuillConfig and file tree
866    ///
867    /// This method constructs a Quill from a parsed QuillConfig and validates
868    /// all file references.
869    ///
870    /// # Arguments
871    ///
872    /// * `config` - The parsed QuillConfig
873    /// * `root` - The root node of the file tree
874    ///
875    /// # Errors
876    ///
877    /// Returns an error if:
878    /// - The plate file specified in config is not found or not valid UTF-8
879    /// - The example file specified in config is not found or not valid UTF-8
880    /// - Schema generation fails
881    fn from_config(
882        config: QuillConfig,
883        root: FileTreeNode,
884    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
885        // Build metadata from config
886        let mut metadata = config.metadata.clone();
887
888        // Add backend to metadata
889        metadata.insert(
890            "backend".to_string(),
891            QuillValue::from_json(serde_json::Value::String(config.backend.clone())),
892        );
893
894        // Add description to metadata
895        metadata.insert(
896            "description".to_string(),
897            QuillValue::from_json(serde_json::Value::String(config.description.clone())),
898        );
899
900        // Add author if present
901        if let Some(ref author) = config.author {
902            metadata.insert(
903                "author".to_string(),
904                QuillValue::from_json(serde_json::Value::String(author.clone())),
905            );
906        }
907
908        // Add typst config to metadata with typst_ prefix
909        for (key, value) in &config.typst_config {
910            metadata.insert(format!("typst_{}", key), value.clone());
911        }
912
913        // Build JSON schema from field and card schemas
914        let schema = crate::schema::build_schema(&config.fields, &config.cards)
915            .map_err(|e| format!("Failed to build JSON schema from field schemas: {}", e))?;
916
917        // Read the plate content from plate file (if specified)
918        let plate_content: Option<String> = if let Some(ref plate_file_name) = config.plate_file {
919            let plate_bytes = root.get_file(plate_file_name).ok_or_else(|| {
920                format!("Plate file '{}' not found in file tree", plate_file_name)
921            })?;
922
923            let content = String::from_utf8(plate_bytes.to_vec()).map_err(|e| {
924                format!("Plate file '{}' is not valid UTF-8: {}", plate_file_name, e)
925            })?;
926            Some(content)
927        } else {
928            // No plate file specified
929            None
930        };
931
932        // Read the markdown example content if specified
933        let example_content = if let Some(ref example_file_name) = config.example_file {
934            root.get_file(example_file_name).and_then(|bytes| {
935                String::from_utf8(bytes.to_vec())
936                    .map_err(|e| {
937                        eprintln!(
938                            "Warning: Example file '{}' is not valid UTF-8: {}",
939                            example_file_name, e
940                        );
941                        e
942                    })
943                    .ok()
944            })
945        } else {
946            None
947        };
948
949        // Extract and cache defaults and examples from schema for performance
950        let defaults = crate::schema::extract_defaults_from_schema(&schema);
951        let examples = crate::schema::extract_examples_from_schema(&schema);
952
953        let quill = Quill {
954            metadata,
955            name: config.name,
956            backend: config.backend,
957            plate: plate_content,
958            example: example_content,
959            schema,
960            defaults,
961            examples,
962            files: root,
963        };
964
965        Ok(quill)
966    }
967
968    /// Create a Quill from a JSON representation
969    ///
970    /// Parses a JSON string into an in-memory file tree and validates it. The
971    /// precise JSON contract is documented in `designs/QUILL.md`.
972    /// The JSON format MUST have a root object with a `files` key. The optional
973    /// `metadata` key provides additional metadata that overrides defaults.
974    pub fn from_json(json_str: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
975        use serde_json::Value as JsonValue;
976
977        let json: JsonValue =
978            serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;
979
980        let obj = json.as_object().ok_or("Root must be an object")?;
981
982        // Extract metadata (optional)
983        let default_name = obj
984            .get("metadata")
985            .and_then(|m| m.get("name"))
986            .and_then(|v| v.as_str())
987            .map(String::from);
988
989        // Extract files (required)
990        let files_obj = obj
991            .get("files")
992            .and_then(|v| v.as_object())
993            .ok_or("Missing or invalid 'files' key")?;
994
995        // Parse file tree
996        let mut root_files = HashMap::new();
997        for (key, value) in files_obj {
998            root_files.insert(key.clone(), FileTreeNode::from_json_value(value)?);
999        }
1000
1001        let root = FileTreeNode::Directory { files: root_files };
1002
1003        // Create Quill from tree
1004        Self::from_tree(root, default_name)
1005    }
1006
1007    /// Recursively load all files from a directory into a tree structure
1008    fn load_directory_as_tree(
1009        current_dir: &Path,
1010        base_dir: &Path,
1011        ignore: &QuillIgnore,
1012    ) -> Result<FileTreeNode, Box<dyn StdError + Send + Sync>> {
1013        use std::fs;
1014
1015        if !current_dir.exists() {
1016            return Ok(FileTreeNode::Directory {
1017                files: HashMap::new(),
1018            });
1019        }
1020
1021        let mut files = HashMap::new();
1022
1023        for entry in fs::read_dir(current_dir)? {
1024            let entry = entry?;
1025            let path = entry.path();
1026            let relative_path = path
1027                .strip_prefix(base_dir)
1028                .map_err(|e| format!("Failed to get relative path: {}", e))?
1029                .to_path_buf();
1030
1031            // Check if this path should be ignored
1032            if ignore.is_ignored(&relative_path) {
1033                continue;
1034            }
1035
1036            // Get the filename
1037            let filename = path
1038                .file_name()
1039                .and_then(|n| n.to_str())
1040                .ok_or_else(|| format!("Invalid filename: {}", path.display()))?
1041                .to_string();
1042
1043            if path.is_file() {
1044                let contents = fs::read(&path)
1045                    .map_err(|e| format!("Failed to read file '{}': {}", path.display(), e))?;
1046
1047                files.insert(filename, FileTreeNode::File { contents });
1048            } else if path.is_dir() {
1049                // Recursively process subdirectory
1050                let subdir_tree = Self::load_directory_as_tree(&path, base_dir, ignore)?;
1051                files.insert(filename, subdir_tree);
1052            }
1053        }
1054
1055        Ok(FileTreeNode::Directory { files })
1056    }
1057
1058    /// Get the list of typst packages to download, if specified in Quill.toml
1059    pub fn typst_packages(&self) -> Vec<String> {
1060        self.metadata
1061            .get("typst_packages")
1062            .and_then(|v| v.as_array())
1063            .map(|arr| {
1064                arr.iter()
1065                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
1066                    .collect()
1067            })
1068            .unwrap_or_default()
1069    }
1070
1071    /// Get default values from the cached schema defaults
1072    ///
1073    /// Returns a reference to the pre-computed defaults HashMap that was extracted
1074    /// during Quill construction. This is more efficient than re-parsing the schema.
1075    ///
1076    /// This is used by `ParsedDocument::with_defaults()` to apply default values
1077    /// to missing fields.
1078    pub fn extract_defaults(&self) -> &HashMap<String, QuillValue> {
1079        &self.defaults
1080    }
1081
1082    /// Get example values from the cached schema examples
1083    ///
1084    /// Returns a reference to the pre-computed examples HashMap that was extracted
1085    /// during Quill construction. This is more efficient than re-parsing the schema.
1086    pub fn extract_examples(&self) -> &HashMap<String, Vec<QuillValue>> {
1087        &self.examples
1088    }
1089
1090    /// Get file contents by path (relative to quill root)
1091    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
1092        self.files.get_file(path)
1093    }
1094
1095    /// Check if a file exists in memory
1096    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
1097        self.files.file_exists(path)
1098    }
1099
1100    /// Check if a directory exists in memory
1101    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
1102        self.files.dir_exists(path)
1103    }
1104
1105    /// List files in a directory (non-recursive, returns file names only)
1106    pub fn list_files<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
1107        self.files.list_files(path)
1108    }
1109
1110    /// List subdirectories in a directory (non-recursive, returns directory names only)
1111    pub fn list_subdirectories<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
1112        self.files.list_subdirectories(path)
1113    }
1114
1115    /// List all files in a directory (returns paths relative to quill root)
1116    pub fn list_directory<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
1117        let dir_path = dir_path.as_ref();
1118        let filenames = self.files.list_files(dir_path);
1119
1120        // Convert filenames to full paths
1121        filenames
1122            .iter()
1123            .map(|name| {
1124                if dir_path == Path::new("") {
1125                    PathBuf::from(name)
1126                } else {
1127                    dir_path.join(name)
1128                }
1129            })
1130            .collect()
1131    }
1132
1133    /// List all directories in a directory (returns paths relative to quill root)
1134    pub fn list_directories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
1135        let dir_path = dir_path.as_ref();
1136        let subdirs = self.files.list_subdirectories(dir_path);
1137
1138        // Convert subdirectory names to full paths
1139        subdirs
1140            .iter()
1141            .map(|name| {
1142                if dir_path == Path::new("") {
1143                    PathBuf::from(name)
1144                } else {
1145                    dir_path.join(name)
1146                }
1147            })
1148            .collect()
1149    }
1150
1151    /// Get all files matching a pattern (supports glob-style wildcards)
1152    pub fn find_files<P: AsRef<Path>>(&self, pattern: P) -> Vec<PathBuf> {
1153        let pattern_str = pattern.as_ref().to_string_lossy();
1154        let mut matches = Vec::new();
1155
1156        // Compile the glob pattern
1157        let glob_pattern = match glob::Pattern::new(&pattern_str) {
1158            Ok(pat) => pat,
1159            Err(_) => return matches, // Invalid pattern returns empty results
1160        };
1161
1162        // Recursively search the tree for matching files
1163        Self::find_files_recursive(&self.files, Path::new(""), &glob_pattern, &mut matches);
1164
1165        matches.sort();
1166        matches
1167    }
1168
1169    /// Helper method to recursively search for files matching a pattern
1170    fn find_files_recursive(
1171        node: &FileTreeNode,
1172        current_path: &Path,
1173        pattern: &glob::Pattern,
1174        matches: &mut Vec<PathBuf>,
1175    ) {
1176        match node {
1177            FileTreeNode::File { .. } => {
1178                let path_str = current_path.to_string_lossy();
1179                if pattern.matches(&path_str) {
1180                    matches.push(current_path.to_path_buf());
1181                }
1182            }
1183            FileTreeNode::Directory { files } => {
1184                for (name, child_node) in files {
1185                    let child_path = if current_path == Path::new("") {
1186                        PathBuf::from(name)
1187                    } else {
1188                        current_path.join(name)
1189                    };
1190                    Self::find_files_recursive(child_node, &child_path, pattern, matches);
1191                }
1192            }
1193        }
1194    }
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199    use super::*;
1200    use std::fs;
1201    use tempfile::TempDir;
1202
1203    #[test]
1204    fn test_quillignore_parsing() {
1205        let ignore_content = r#"
1206# This is a comment
1207*.tmp
1208target/
1209node_modules/
1210.git/
1211"#;
1212        let ignore = QuillIgnore::from_content(ignore_content);
1213        assert_eq!(ignore.patterns.len(), 4);
1214        assert!(ignore.patterns.contains(&"*.tmp".to_string()));
1215        assert!(ignore.patterns.contains(&"target/".to_string()));
1216    }
1217
1218    #[test]
1219    fn test_quillignore_matching() {
1220        let ignore = QuillIgnore::new(vec![
1221            "*.tmp".to_string(),
1222            "target/".to_string(),
1223            "node_modules/".to_string(),
1224            ".git/".to_string(),
1225        ]);
1226
1227        // Test file patterns
1228        assert!(ignore.is_ignored("test.tmp"));
1229        assert!(ignore.is_ignored("path/to/file.tmp"));
1230        assert!(!ignore.is_ignored("test.txt"));
1231
1232        // Test directory patterns
1233        assert!(ignore.is_ignored("target"));
1234        assert!(ignore.is_ignored("target/debug"));
1235        assert!(ignore.is_ignored("target/debug/deps"));
1236        assert!(!ignore.is_ignored("src/target.rs"));
1237
1238        assert!(ignore.is_ignored("node_modules"));
1239        assert!(ignore.is_ignored("node_modules/package"));
1240        assert!(!ignore.is_ignored("my_node_modules"));
1241    }
1242
1243    #[test]
1244    fn test_in_memory_file_system() {
1245        let temp_dir = TempDir::new().unwrap();
1246        let quill_dir = temp_dir.path();
1247
1248        // Create test files
1249        fs::write(
1250            quill_dir.join("Quill.toml"),
1251            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1252        )
1253        .unwrap();
1254        fs::write(quill_dir.join("plate.typ"), "test plate").unwrap();
1255
1256        let assets_dir = quill_dir.join("assets");
1257        fs::create_dir_all(&assets_dir).unwrap();
1258        fs::write(assets_dir.join("test.txt"), "asset content").unwrap();
1259
1260        let packages_dir = quill_dir.join("packages");
1261        fs::create_dir_all(&packages_dir).unwrap();
1262        fs::write(packages_dir.join("package.typ"), "package content").unwrap();
1263
1264        // Load quill
1265        let quill = Quill::from_path(quill_dir).unwrap();
1266
1267        // Test file access
1268        assert!(quill.file_exists("plate.typ"));
1269        assert!(quill.file_exists("assets/test.txt"));
1270        assert!(quill.file_exists("packages/package.typ"));
1271        assert!(!quill.file_exists("nonexistent.txt"));
1272
1273        // Test file content
1274        let asset_content = quill.get_file("assets/test.txt").unwrap();
1275        assert_eq!(asset_content, b"asset content");
1276
1277        // Test directory listing
1278        let asset_files = quill.list_directory("assets");
1279        assert_eq!(asset_files.len(), 1);
1280        assert!(asset_files.contains(&PathBuf::from("assets/test.txt")));
1281    }
1282
1283    #[test]
1284    fn test_quillignore_integration() {
1285        let temp_dir = TempDir::new().unwrap();
1286        let quill_dir = temp_dir.path();
1287
1288        // Create .quillignore
1289        fs::write(quill_dir.join(".quillignore"), "*.tmp\ntarget/\n").unwrap();
1290
1291        // Create test files
1292        fs::write(
1293            quill_dir.join("Quill.toml"),
1294            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1295        )
1296        .unwrap();
1297        fs::write(quill_dir.join("plate.typ"), "test template").unwrap();
1298        fs::write(quill_dir.join("should_ignore.tmp"), "ignored").unwrap();
1299
1300        let target_dir = quill_dir.join("target");
1301        fs::create_dir_all(&target_dir).unwrap();
1302        fs::write(target_dir.join("debug.txt"), "also ignored").unwrap();
1303
1304        // Load quill
1305        let quill = Quill::from_path(quill_dir).unwrap();
1306
1307        // Test that ignored files are not loaded
1308        assert!(quill.file_exists("plate.typ"));
1309        assert!(!quill.file_exists("should_ignore.tmp"));
1310        assert!(!quill.file_exists("target/debug.txt"));
1311    }
1312
1313    #[test]
1314    fn test_find_files_pattern() {
1315        let temp_dir = TempDir::new().unwrap();
1316        let quill_dir = temp_dir.path();
1317
1318        // Create test directory structure
1319        fs::write(
1320            quill_dir.join("Quill.toml"),
1321            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1322        )
1323        .unwrap();
1324        fs::write(quill_dir.join("plate.typ"), "template").unwrap();
1325
1326        let assets_dir = quill_dir.join("assets");
1327        fs::create_dir_all(&assets_dir).unwrap();
1328        fs::write(assets_dir.join("image.png"), "png data").unwrap();
1329        fs::write(assets_dir.join("data.json"), "json data").unwrap();
1330
1331        let fonts_dir = assets_dir.join("fonts");
1332        fs::create_dir_all(&fonts_dir).unwrap();
1333        fs::write(fonts_dir.join("font.ttf"), "font data").unwrap();
1334
1335        // Load quill
1336        let quill = Quill::from_path(quill_dir).unwrap();
1337
1338        // Test pattern matching
1339        let all_assets = quill.find_files("assets/*");
1340        assert!(all_assets.len() >= 3); // At least image.png, data.json, fonts/font.ttf
1341
1342        let typ_files = quill.find_files("*.typ");
1343        assert_eq!(typ_files.len(), 1);
1344        assert!(typ_files.contains(&PathBuf::from("plate.typ")));
1345    }
1346
1347    #[test]
1348    fn test_new_standardized_toml_format() {
1349        let temp_dir = TempDir::new().unwrap();
1350        let quill_dir = temp_dir.path();
1351
1352        // Create test files using new standardized format
1353        let toml_content = r#"[Quill]
1354name = "my-custom-quill"
1355backend = "typst"
1356plate_file = "custom_plate.typ"
1357description = "Test quill with new format"
1358author = "Test Author"
1359"#;
1360        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1361        fs::write(
1362            quill_dir.join("custom_plate.typ"),
1363            "= Custom Template\n\nThis is a custom template.",
1364        )
1365        .unwrap();
1366
1367        // Load quill
1368        let quill = Quill::from_path(quill_dir).unwrap();
1369
1370        // Test that name comes from TOML, not directory
1371        assert_eq!(quill.name, "my-custom-quill");
1372
1373        // Test that backend is in metadata
1374        assert!(quill.metadata.contains_key("backend"));
1375        if let Some(backend_val) = quill.metadata.get("backend") {
1376            if let Some(backend_str) = backend_val.as_str() {
1377                assert_eq!(backend_str, "typst");
1378            } else {
1379                panic!("Backend value is not a string");
1380            }
1381        }
1382
1383        // Test that other fields are in metadata (but not version)
1384        assert!(quill.metadata.contains_key("description"));
1385        assert!(quill.metadata.contains_key("author"));
1386        assert!(!quill.metadata.contains_key("version")); // version should be excluded
1387
1388        // Test that plate template content is loaded correctly
1389        assert!(quill.plate.unwrap().contains("Custom Template"));
1390    }
1391
1392    #[test]
1393    fn test_typst_packages_parsing() {
1394        let temp_dir = TempDir::new().unwrap();
1395        let quill_dir = temp_dir.path();
1396
1397        let toml_content = r#"
1398[Quill]
1399name = "test-quill"
1400backend = "typst"
1401plate_file = "plate.typ"
1402description = "Test quill for packages"
1403
1404[typst]
1405packages = ["@preview/bubble:0.2.2", "@preview/example:1.0.0"]
1406"#;
1407
1408        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1409        fs::write(quill_dir.join("plate.typ"), "test").unwrap();
1410
1411        let quill = Quill::from_path(quill_dir).unwrap();
1412        let packages = quill.typst_packages();
1413
1414        assert_eq!(packages.len(), 2);
1415        assert_eq!(packages[0], "@preview/bubble:0.2.2");
1416        assert_eq!(packages[1], "@preview/example:1.0.0");
1417    }
1418
1419    #[test]
1420    fn test_template_loading() {
1421        let temp_dir = TempDir::new().unwrap();
1422        let quill_dir = temp_dir.path();
1423
1424        // Create test files with example specified
1425        let toml_content = r#"[Quill]
1426name = "test-with-template"
1427backend = "typst"
1428plate_file = "plate.typ"
1429example_file = "example.md"
1430description = "Test quill with template"
1431"#;
1432        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1433        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1434        fs::write(
1435            quill_dir.join("example.md"),
1436            "---\ntitle: Test\n---\n\nThis is a test template.",
1437        )
1438        .unwrap();
1439
1440        // Load quill
1441        let quill = Quill::from_path(quill_dir).unwrap();
1442
1443        // Test that example content is loaded and includes some the text
1444        assert!(quill.example.is_some());
1445        let example = quill.example.unwrap();
1446        assert!(example.contains("title: Test"));
1447        assert!(example.contains("This is a test template"));
1448
1449        // Test that plate template is still loaded
1450        assert_eq!(quill.plate.unwrap(), "plate content");
1451    }
1452
1453    #[test]
1454    fn test_template_optional() {
1455        let temp_dir = TempDir::new().unwrap();
1456        let quill_dir = temp_dir.path();
1457
1458        // Create test files without example specified
1459        let toml_content = r#"[Quill]
1460name = "test-without-template"
1461backend = "typst"
1462plate_file = "plate.typ"
1463description = "Test quill without template"
1464"#;
1465        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1466        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1467
1468        // Load quill
1469        let quill = Quill::from_path(quill_dir).unwrap();
1470
1471        // Test that example fields are None
1472        assert_eq!(quill.example, None);
1473
1474        // Test that plate template is still loaded
1475        assert_eq!(quill.plate.unwrap(), "plate content");
1476    }
1477
1478    #[test]
1479    fn test_from_tree() {
1480        // Create a simple in-memory file tree
1481        let mut root_files = HashMap::new();
1482
1483        // Add Quill.toml
1484        let quill_toml = r#"[Quill]
1485name = "test-from-tree"
1486backend = "typst"
1487plate_file = "plate.typ"
1488description = "A test quill from tree"
1489"#;
1490        root_files.insert(
1491            "Quill.toml".to_string(),
1492            FileTreeNode::File {
1493                contents: quill_toml.as_bytes().to_vec(),
1494            },
1495        );
1496
1497        // Add plate file
1498        let plate_content = "= Test Template\n\nThis is a test.";
1499        root_files.insert(
1500            "plate.typ".to_string(),
1501            FileTreeNode::File {
1502                contents: plate_content.as_bytes().to_vec(),
1503            },
1504        );
1505
1506        let root = FileTreeNode::Directory { files: root_files };
1507
1508        // Create Quill from tree
1509        let quill = Quill::from_tree(root, Some("test-from-tree".to_string())).unwrap();
1510
1511        // Validate the quill
1512        assert_eq!(quill.name, "test-from-tree");
1513        assert_eq!(quill.plate.unwrap(), plate_content);
1514        assert!(quill.metadata.contains_key("backend"));
1515        assert!(quill.metadata.contains_key("description"));
1516    }
1517
1518    #[test]
1519    fn test_from_tree_with_template() {
1520        let mut root_files = HashMap::new();
1521
1522        // Add Quill.toml with example specified
1523        let quill_toml = r#"[Quill]
1524name = "test-tree-template"
1525backend = "typst"
1526plate_file = "plate.typ"
1527example_file = "template.md"
1528description = "Test tree with template"
1529"#;
1530        root_files.insert(
1531            "Quill.toml".to_string(),
1532            FileTreeNode::File {
1533                contents: quill_toml.as_bytes().to_vec(),
1534            },
1535        );
1536
1537        // Add plate file
1538        root_files.insert(
1539            "plate.typ".to_string(),
1540            FileTreeNode::File {
1541                contents: b"plate content".to_vec(),
1542            },
1543        );
1544
1545        // Add template file
1546        let template_content = "# {{ title }}\n\n{{ body }}";
1547        root_files.insert(
1548            "template.md".to_string(),
1549            FileTreeNode::File {
1550                contents: template_content.as_bytes().to_vec(),
1551            },
1552        );
1553
1554        let root = FileTreeNode::Directory { files: root_files };
1555
1556        // Create Quill from tree
1557        let quill = Quill::from_tree(root, None).unwrap();
1558
1559        // Validate template is loaded
1560        assert_eq!(quill.example, Some(template_content.to_string()));
1561    }
1562
1563    #[test]
1564    fn test_from_json() {
1565        // Create JSON representation of a Quill using new format
1566        let json_str = r#"{
1567            "metadata": {
1568                "name": "test-from-json"
1569            },
1570            "files": {
1571                "Quill.toml": {
1572                    "contents": "[Quill]\nname = \"test-from-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill from JSON\"\n"
1573                },
1574                "plate.typ": {
1575                    "contents": "= Test Plate\n\nThis is test content."
1576                }
1577            }
1578        }"#;
1579
1580        // Create Quill from JSON
1581        let quill = Quill::from_json(json_str).unwrap();
1582
1583        // Validate the quill
1584        assert_eq!(quill.name, "test-from-json");
1585        assert!(quill.plate.unwrap().contains("Test Plate"));
1586        assert!(quill.metadata.contains_key("backend"));
1587    }
1588
1589    #[test]
1590    fn test_from_json_with_byte_array() {
1591        // Create JSON with byte array representation using new format
1592        let json_str = r#"{
1593            "files": {
1594                "Quill.toml": {
1595                    "contents": "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1596                },
1597                "plate.typ": {
1598                    "contents": "test plate"
1599                }
1600            }
1601        }"#;
1602
1603        // Create Quill from JSON
1604        let quill = Quill::from_json(json_str).unwrap();
1605
1606        // Validate the quill was created
1607        assert_eq!(quill.name, "test");
1608        assert_eq!(quill.plate.unwrap(), "test plate");
1609    }
1610
1611    #[test]
1612    fn test_from_json_missing_files() {
1613        // JSON without files field should fail
1614        let json_str = r#"{
1615            "metadata": {
1616                "name": "test"
1617            }
1618        }"#;
1619
1620        let result = Quill::from_json(json_str);
1621        assert!(result.is_err());
1622        // Should fail because there's no 'files' key
1623        assert!(result.unwrap_err().to_string().contains("files"));
1624    }
1625
1626    #[test]
1627    fn test_from_json_tree_structure() {
1628        // Test the new tree structure format
1629        let json_str = r#"{
1630            "files": {
1631                "Quill.toml": {
1632                    "contents": "[Quill]\nname = \"test-tree-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test tree JSON\"\n"
1633                },
1634                "plate.typ": {
1635                    "contents": "= Test Plate\n\nTree structure content."
1636                }
1637            }
1638        }"#;
1639
1640        let quill = Quill::from_json(json_str).unwrap();
1641
1642        assert_eq!(quill.name, "test-tree-json");
1643        assert!(quill.plate.unwrap().contains("Tree structure content"));
1644        assert!(quill.metadata.contains_key("backend"));
1645    }
1646
1647    #[test]
1648    fn test_from_json_nested_tree_structure() {
1649        // Test nested directories in tree structure
1650        let json_str = r#"{
1651            "files": {
1652                "Quill.toml": {
1653                    "contents": "[Quill]\nname = \"nested-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Nested test\"\n"
1654                },
1655                "plate.typ": {
1656                    "contents": "plate"
1657                },
1658                "src": {
1659                    "main.rs": {
1660                        "contents": "fn main() {}"
1661                    },
1662                    "lib.rs": {
1663                        "contents": "// lib"
1664                    }
1665                }
1666            }
1667        }"#;
1668
1669        let quill = Quill::from_json(json_str).unwrap();
1670
1671        assert_eq!(quill.name, "nested-test");
1672        // Verify nested files are accessible
1673        assert!(quill.file_exists("src/main.rs"));
1674        assert!(quill.file_exists("src/lib.rs"));
1675
1676        let main_rs = quill.get_file("src/main.rs").unwrap();
1677        assert_eq!(main_rs, b"fn main() {}");
1678    }
1679
1680    #[test]
1681    fn test_from_tree_structure_direct() {
1682        // Test using from_tree_structure directly
1683        let mut root_files = HashMap::new();
1684
1685        root_files.insert(
1686            "Quill.toml".to_string(),
1687            FileTreeNode::File {
1688                contents:
1689                    b"[Quill]\nname = \"direct-tree\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Direct tree test\"\n"
1690                        .to_vec(),
1691            },
1692        );
1693
1694        root_files.insert(
1695            "plate.typ".to_string(),
1696            FileTreeNode::File {
1697                contents: b"plate content".to_vec(),
1698            },
1699        );
1700
1701        // Add a nested directory
1702        let mut src_files = HashMap::new();
1703        src_files.insert(
1704            "main.rs".to_string(),
1705            FileTreeNode::File {
1706                contents: b"fn main() {}".to_vec(),
1707            },
1708        );
1709
1710        root_files.insert(
1711            "src".to_string(),
1712            FileTreeNode::Directory { files: src_files },
1713        );
1714
1715        let root = FileTreeNode::Directory { files: root_files };
1716
1717        let quill = Quill::from_tree(root, None).unwrap();
1718
1719        assert_eq!(quill.name, "direct-tree");
1720        assert!(quill.file_exists("src/main.rs"));
1721        assert!(quill.file_exists("plate.typ"));
1722    }
1723
1724    #[test]
1725    fn test_from_json_with_metadata_override() {
1726        // Test that metadata key overrides name from Quill.toml
1727        let json_str = r#"{
1728            "metadata": {
1729                "name": "override-name"
1730            },
1731            "files": {
1732                "Quill.toml": {
1733                    "contents": "[Quill]\nname = \"toml-name\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"TOML name test\"\n"
1734                },
1735                "plate.typ": {
1736                    "contents": "= plate"
1737                }
1738            }
1739        }"#;
1740
1741        let quill = Quill::from_json(json_str).unwrap();
1742        // Metadata name should be used as default, but Quill.toml takes precedence
1743        // when from_tree is called
1744        assert_eq!(quill.name, "toml-name");
1745    }
1746
1747    #[test]
1748    fn test_from_json_empty_directory() {
1749        // Test that empty directories are supported
1750        let json_str = r#"{
1751            "files": {
1752                "Quill.toml": {
1753                    "contents": "[Quill]\nname = \"empty-dir-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Empty directory test\"\n"
1754                },
1755                "plate.typ": {
1756                    "contents": "plate"
1757                },
1758                "empty_dir": {}
1759            }
1760        }"#;
1761
1762        let quill = Quill::from_json(json_str).unwrap();
1763        assert_eq!(quill.name, "empty-dir-test");
1764        assert!(quill.dir_exists("empty_dir"));
1765        assert!(!quill.file_exists("empty_dir"));
1766    }
1767
1768    #[test]
1769    fn test_dir_exists_and_list_apis() {
1770        let mut root_files = HashMap::new();
1771
1772        // Add Quill.toml
1773        root_files.insert(
1774            "Quill.toml".to_string(),
1775            FileTreeNode::File {
1776                contents: b"[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1777                    .to_vec(),
1778            },
1779        );
1780
1781        // Add plate file
1782        root_files.insert(
1783            "plate.typ".to_string(),
1784            FileTreeNode::File {
1785                contents: b"plate content".to_vec(),
1786            },
1787        );
1788
1789        // Add assets directory with files
1790        let mut assets_files = HashMap::new();
1791        assets_files.insert(
1792            "logo.png".to_string(),
1793            FileTreeNode::File {
1794                contents: vec![137, 80, 78, 71],
1795            },
1796        );
1797        assets_files.insert(
1798            "icon.svg".to_string(),
1799            FileTreeNode::File {
1800                contents: b"<svg></svg>".to_vec(),
1801            },
1802        );
1803
1804        // Add subdirectory in assets
1805        let mut fonts_files = HashMap::new();
1806        fonts_files.insert(
1807            "font.ttf".to_string(),
1808            FileTreeNode::File {
1809                contents: b"font data".to_vec(),
1810            },
1811        );
1812        assets_files.insert(
1813            "fonts".to_string(),
1814            FileTreeNode::Directory { files: fonts_files },
1815        );
1816
1817        root_files.insert(
1818            "assets".to_string(),
1819            FileTreeNode::Directory {
1820                files: assets_files,
1821            },
1822        );
1823
1824        // Add empty directory
1825        root_files.insert(
1826            "empty".to_string(),
1827            FileTreeNode::Directory {
1828                files: HashMap::new(),
1829            },
1830        );
1831
1832        let root = FileTreeNode::Directory { files: root_files };
1833        let quill = Quill::from_tree(root, None).unwrap();
1834
1835        // Test dir_exists
1836        assert!(quill.dir_exists("assets"));
1837        assert!(quill.dir_exists("assets/fonts"));
1838        assert!(quill.dir_exists("empty"));
1839        assert!(!quill.dir_exists("nonexistent"));
1840        assert!(!quill.dir_exists("plate.typ")); // file, not directory
1841
1842        // Test file_exists
1843        assert!(quill.file_exists("plate.typ"));
1844        assert!(quill.file_exists("assets/logo.png"));
1845        assert!(quill.file_exists("assets/fonts/font.ttf"));
1846        assert!(!quill.file_exists("assets")); // directory, not file
1847
1848        // Test list_files
1849        let root_files_list = quill.list_files("");
1850        assert_eq!(root_files_list.len(), 2); // Quill.toml and plate.typ
1851        assert!(root_files_list.contains(&"Quill.toml".to_string()));
1852        assert!(root_files_list.contains(&"plate.typ".to_string()));
1853
1854        let assets_files_list = quill.list_files("assets");
1855        assert_eq!(assets_files_list.len(), 2); // logo.png and icon.svg
1856        assert!(assets_files_list.contains(&"logo.png".to_string()));
1857        assert!(assets_files_list.contains(&"icon.svg".to_string()));
1858
1859        // Test list_subdirectories
1860        let root_subdirs = quill.list_subdirectories("");
1861        assert_eq!(root_subdirs.len(), 2); // assets and empty
1862        assert!(root_subdirs.contains(&"assets".to_string()));
1863        assert!(root_subdirs.contains(&"empty".to_string()));
1864
1865        let assets_subdirs = quill.list_subdirectories("assets");
1866        assert_eq!(assets_subdirs.len(), 1); // fonts
1867        assert!(assets_subdirs.contains(&"fonts".to_string()));
1868
1869        let empty_subdirs = quill.list_subdirectories("empty");
1870        assert_eq!(empty_subdirs.len(), 0);
1871    }
1872
1873    #[test]
1874    fn test_field_schemas_parsing() {
1875        let mut root_files = HashMap::new();
1876
1877        // Add Quill.toml with field schemas
1878        let quill_toml = r#"[Quill]
1879name = "taro"
1880backend = "typst"
1881plate_file = "plate.typ"
1882example_file = "taro.md"
1883description = "Test template for field schemas"
1884
1885[fields]
1886author = {description = "Author of document" }
1887ice_cream = {description = "favorite ice cream flavor"}
1888title = {description = "title of document" }
1889"#;
1890        root_files.insert(
1891            "Quill.toml".to_string(),
1892            FileTreeNode::File {
1893                contents: quill_toml.as_bytes().to_vec(),
1894            },
1895        );
1896
1897        // Add plate file
1898        let plate_content = "= Test Template\n\nThis is a test.";
1899        root_files.insert(
1900            "plate.typ".to_string(),
1901            FileTreeNode::File {
1902                contents: plate_content.as_bytes().to_vec(),
1903            },
1904        );
1905
1906        // Add template file
1907        root_files.insert(
1908            "taro.md".to_string(),
1909            FileTreeNode::File {
1910                contents: b"# Template".to_vec(),
1911            },
1912        );
1913
1914        let root = FileTreeNode::Directory { files: root_files };
1915
1916        // Create Quill from tree
1917        let quill = Quill::from_tree(root, Some("taro".to_string())).unwrap();
1918
1919        // Validate field schemas were parsed
1920        assert_eq!(quill.schema["properties"].as_object().unwrap().len(), 3);
1921        assert!(quill.schema["properties"]
1922            .as_object()
1923            .unwrap()
1924            .contains_key("author"));
1925        assert!(quill.schema["properties"]
1926            .as_object()
1927            .unwrap()
1928            .contains_key("ice_cream"));
1929        assert!(quill.schema["properties"]
1930            .as_object()
1931            .unwrap()
1932            .contains_key("title"));
1933
1934        // Verify author field schema
1935        let author_schema = quill.schema["properties"]["author"].as_object().unwrap();
1936        assert_eq!(author_schema["description"], "Author of document");
1937
1938        // Verify ice_cream field schema (no required field, should default to false)
1939        let ice_cream_schema = quill.schema["properties"]["ice_cream"].as_object().unwrap();
1940        assert_eq!(ice_cream_schema["description"], "favorite ice cream flavor");
1941
1942        // Verify title field schema
1943        let title_schema = quill.schema["properties"]["title"].as_object().unwrap();
1944        assert_eq!(title_schema["description"], "title of document");
1945    }
1946
1947    #[test]
1948    fn test_field_schema_struct() {
1949        // Test creating FieldSchema with minimal fields
1950        let schema1 = FieldSchema::new("test_name".to_string(), "Test description".to_string());
1951        assert_eq!(schema1.description, "Test description");
1952        assert_eq!(schema1.r#type, None);
1953        assert_eq!(schema1.examples, None);
1954        assert_eq!(schema1.default, None);
1955
1956        // Test parsing FieldSchema from YAML with all fields
1957        let yaml_str = r#"
1958description: "Full field schema"
1959type: "string"
1960examples:
1961  - "Example value"
1962default: "Default value"
1963"#;
1964        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml_str).unwrap();
1965        let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
1966        let schema2 = FieldSchema::from_quill_value("test_name".to_string(), &quill_value).unwrap();
1967        assert_eq!(schema2.name, "test_name");
1968        assert_eq!(schema2.description, "Full field schema");
1969        assert_eq!(schema2.r#type, Some("string".to_string()));
1970        assert_eq!(
1971            schema2
1972                .examples
1973                .as_ref()
1974                .and_then(|v| v.as_array())
1975                .and_then(|arr| arr.first())
1976                .and_then(|v| v.as_str()),
1977            Some("Example value")
1978        );
1979        assert_eq!(
1980            schema2.default.as_ref().and_then(|v| v.as_str()),
1981            Some("Default value")
1982        );
1983    }
1984
1985    #[test]
1986    fn test_quill_without_plate_file() {
1987        // Test creating a Quill without specifying a plate file
1988        let mut root_files = HashMap::new();
1989
1990        // Add Quill.toml without plate field
1991        let quill_toml = r#"[Quill]
1992name = "test-no-plate"
1993backend = "typst"
1994description = "Test quill without plate file"
1995"#;
1996        root_files.insert(
1997            "Quill.toml".to_string(),
1998            FileTreeNode::File {
1999                contents: quill_toml.as_bytes().to_vec(),
2000            },
2001        );
2002
2003        let root = FileTreeNode::Directory { files: root_files };
2004
2005        // Create Quill from tree
2006        let quill = Quill::from_tree(root, None).unwrap();
2007
2008        // Validate that plate is null (will use auto plate)
2009        assert!(quill.plate.clone().is_none());
2010        assert_eq!(quill.name, "test-no-plate");
2011    }
2012
2013    #[test]
2014    fn test_quill_config_from_toml() {
2015        // Test parsing QuillConfig from TOML content
2016        let toml_content = r#"[Quill]
2017name = "test-config"
2018backend = "typst"
2019description = "Test configuration parsing"
2020version = "1.0.0"
2021author = "Test Author"
2022plate_file = "plate.typ"
2023example_file = "example.md"
2024
2025[typst]
2026packages = ["@preview/bubble:0.2.2"]
2027
2028[fields]
2029title = {description = "Document title", type = "string"}
2030author = {description = "Document author"}
2031"#;
2032
2033        let config = QuillConfig::from_toml(toml_content).unwrap();
2034
2035        // Verify required fields
2036        assert_eq!(config.name, "test-config");
2037        assert_eq!(config.backend, "typst");
2038        assert_eq!(config.description, "Test configuration parsing");
2039
2040        // Verify optional fields
2041        assert_eq!(config.version, Some("1.0.0".to_string()));
2042        assert_eq!(config.author, Some("Test Author".to_string()));
2043        assert_eq!(config.plate_file, Some("plate.typ".to_string()));
2044        assert_eq!(config.example_file, Some("example.md".to_string()));
2045
2046        // Verify typst config
2047        assert!(config.typst_config.contains_key("packages"));
2048
2049        // Verify field schemas
2050        assert_eq!(config.fields.len(), 2);
2051        assert!(config.fields.contains_key("title"));
2052        assert!(config.fields.contains_key("author"));
2053
2054        let title_field = &config.fields["title"];
2055        assert_eq!(title_field.description, "Document title");
2056        assert_eq!(title_field.r#type, Some("string".to_string()));
2057    }
2058
2059    #[test]
2060    fn test_quill_config_missing_required_fields() {
2061        // Test that missing required fields result in error
2062        let toml_missing_name = r#"[Quill]
2063backend = "typst"
2064description = "Missing name"
2065"#;
2066        let result = QuillConfig::from_toml(toml_missing_name);
2067        assert!(result.is_err());
2068        assert!(result
2069            .unwrap_err()
2070            .to_string()
2071            .contains("Missing required 'name'"));
2072
2073        let toml_missing_backend = r#"[Quill]
2074name = "test"
2075description = "Missing backend"
2076"#;
2077        let result = QuillConfig::from_toml(toml_missing_backend);
2078        assert!(result.is_err());
2079        assert!(result
2080            .unwrap_err()
2081            .to_string()
2082            .contains("Missing required 'backend'"));
2083
2084        let toml_missing_description = r#"[Quill]
2085name = "test"
2086backend = "typst"
2087"#;
2088        let result = QuillConfig::from_toml(toml_missing_description);
2089        assert!(result.is_err());
2090        assert!(result
2091            .unwrap_err()
2092            .to_string()
2093            .contains("Missing required 'description'"));
2094    }
2095
2096    #[test]
2097    fn test_quill_config_empty_description() {
2098        // Test that empty description results in error
2099        let toml_empty_description = r#"[Quill]
2100name = "test"
2101backend = "typst"
2102description = "   "
2103"#;
2104        let result = QuillConfig::from_toml(toml_empty_description);
2105        assert!(result.is_err());
2106        assert!(result
2107            .unwrap_err()
2108            .to_string()
2109            .contains("description' field in [Quill] section cannot be empty"));
2110    }
2111
2112    #[test]
2113    fn test_quill_config_missing_quill_section() {
2114        // Test that missing [Quill] section results in error
2115        let toml_no_section = r#"[fields]
2116title = {description = "Title"}
2117"#;
2118        let result = QuillConfig::from_toml(toml_no_section);
2119        assert!(result.is_err());
2120        assert!(result
2121            .unwrap_err()
2122            .to_string()
2123            .contains("Missing required [Quill] section"));
2124    }
2125
2126    #[test]
2127    fn test_quill_from_config_metadata() {
2128        // Test that QuillConfig metadata flows through to Quill
2129        let mut root_files = HashMap::new();
2130
2131        let quill_toml = r#"[Quill]
2132name = "metadata-test"
2133backend = "typst"
2134description = "Test metadata flow"
2135author = "Test Author"
2136custom_field = "custom_value"
2137
2138[typst]
2139packages = ["@preview/bubble:0.2.2"]
2140"#;
2141        root_files.insert(
2142            "Quill.toml".to_string(),
2143            FileTreeNode::File {
2144                contents: quill_toml.as_bytes().to_vec(),
2145            },
2146        );
2147
2148        let root = FileTreeNode::Directory { files: root_files };
2149        let quill = Quill::from_tree(root, None).unwrap();
2150
2151        // Verify metadata includes backend and description
2152        assert!(quill.metadata.contains_key("backend"));
2153        assert!(quill.metadata.contains_key("description"));
2154        assert!(quill.metadata.contains_key("author"));
2155
2156        // Verify custom field is in metadata
2157        assert!(quill.metadata.contains_key("custom_field"));
2158        assert_eq!(
2159            quill.metadata.get("custom_field").unwrap().as_str(),
2160            Some("custom_value")
2161        );
2162
2163        // Verify typst config with typst_ prefix
2164        assert!(quill.metadata.contains_key("typst_packages"));
2165    }
2166
2167    #[test]
2168    fn test_extract_defaults_method() {
2169        // Test the extract_defaults method on Quill
2170        let mut root_files = HashMap::new();
2171
2172        let quill_toml = r#"[Quill]
2173name = "defaults-test"
2174backend = "typst"
2175description = "Test defaults extraction"
2176
2177[fields]
2178title = {description = "Title"}
2179author = {description = "Author", default = "Anonymous"}
2180status = {description = "Status", default = "draft"}
2181"#;
2182
2183        root_files.insert(
2184            "Quill.toml".to_string(),
2185            FileTreeNode::File {
2186                contents: quill_toml.as_bytes().to_vec(),
2187            },
2188        );
2189
2190        let root = FileTreeNode::Directory { files: root_files };
2191        let quill = Quill::from_tree(root, None).unwrap();
2192
2193        // Extract defaults
2194        let defaults = quill.extract_defaults();
2195
2196        // Verify only fields with defaults are returned
2197        assert_eq!(defaults.len(), 2);
2198        assert!(!defaults.contains_key("title")); // no default
2199        assert!(defaults.contains_key("author"));
2200        assert!(defaults.contains_key("status"));
2201
2202        // Verify default values
2203        assert_eq!(defaults.get("author").unwrap().as_str(), Some("Anonymous"));
2204        assert_eq!(defaults.get("status").unwrap().as_str(), Some("draft"));
2205    }
2206
2207    #[test]
2208    fn test_field_order_preservation() {
2209        let toml_content = r#"[Quill]
2210name = "order-test"
2211backend = "typst"
2212description = "Test field order"
2213
2214[fields]
2215first = {description = "First field"}
2216second = {description = "Second field"}
2217third = {description = "Third field", ui = {group = "Test Group"}}
2218fourth = {description = "Fourth field"}
2219"#;
2220
2221        let config = QuillConfig::from_toml(toml_content).unwrap();
2222
2223        // Check that fields have correct order based on TOML position
2224        // Order is automatically generated based on field position
2225
2226        let first = config.fields.get("first").unwrap();
2227        assert_eq!(first.ui.as_ref().unwrap().order, Some(0));
2228
2229        let second = config.fields.get("second").unwrap();
2230        assert_eq!(second.ui.as_ref().unwrap().order, Some(1));
2231
2232        let third = config.fields.get("third").unwrap();
2233        assert_eq!(third.ui.as_ref().unwrap().order, Some(2));
2234        assert_eq!(
2235            third.ui.as_ref().unwrap().group,
2236            Some("Test Group".to_string())
2237        );
2238
2239        let fourth = config.fields.get("fourth").unwrap();
2240        assert_eq!(fourth.ui.as_ref().unwrap().order, Some(3));
2241    }
2242
2243    #[test]
2244    fn test_quill_with_all_ui_properties() {
2245        let toml_content = r#"[Quill]
2246name = "full-ui-test"
2247backend = "typst"
2248description = "Test all UI properties"
2249
2250[fields.author]
2251description = "The full name of the document author"
2252type = "str"
2253
2254[fields.author.ui]
2255group = "Author Info"
2256"#;
2257
2258        let config = QuillConfig::from_toml(toml_content).unwrap();
2259
2260        let author_field = &config.fields["author"];
2261        let ui = author_field.ui.as_ref().unwrap();
2262        assert_eq!(ui.group, Some("Author Info".to_string()));
2263        assert_eq!(ui.order, Some(0)); // First field should have order 0
2264    }
2265    #[test]
2266    fn test_field_schema_with_title_and_description() {
2267        // Test parsing field with new schema format (title + description, no tooltip)
2268        let yaml = r#"
2269title: "Field Title"
2270description: "Detailed field description"
2271type: "string"
2272examples:
2273  - "Example value"
2274ui:
2275  group: "Test Group"
2276"#;
2277        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2278        let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2279        let schema = FieldSchema::from_quill_value("test_field".to_string(), &quill_value).unwrap();
2280
2281        assert_eq!(schema.title, Some("Field Title".to_string()));
2282        assert_eq!(schema.description, "Detailed field description");
2283
2284        assert_eq!(
2285            schema
2286                .examples
2287                .as_ref()
2288                .and_then(|v| v.as_array())
2289                .and_then(|arr| arr.first())
2290                .and_then(|v| v.as_str()),
2291            Some("Example value")
2292        );
2293
2294        let ui = schema.ui.as_ref().unwrap();
2295        assert_eq!(ui.group, Some("Test Group".to_string()));
2296    }
2297
2298    #[test]
2299    fn test_parse_card_field_type() {
2300        // Test that FieldSchema no longer supports type = "card" (cards are in CardSchema now)
2301        let yaml = r#"
2302type: "string"
2303title: "Simple Field"
2304description: "A simple string field"
2305"#;
2306        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2307        let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2308        let schema =
2309            FieldSchema::from_quill_value("simple_field".to_string(), &quill_value).unwrap();
2310
2311        assert_eq!(schema.name, "simple_field");
2312        assert_eq!(schema.r#type, Some("string".to_string()));
2313        assert_eq!(schema.title, Some("Simple Field".to_string()));
2314        assert_eq!(schema.description, "A simple string field");
2315    }
2316
2317    #[test]
2318    fn test_parse_card_with_fields_in_toml() {
2319        // Test parsing [cards] section with [cards.X.fields.Y] syntax
2320        let toml_content = r#"[Quill]
2321name = "cards-fields-test"
2322backend = "typst"
2323description = "Test [cards.X.fields.Y] syntax"
2324
2325[cards.endorsements]
2326title = "Endorsements"
2327description = "Chain of endorsements"
2328
2329[cards.endorsements.fields.name]
2330type = "string"
2331title = "Endorser Name"
2332description = "Name of the endorsing official"
2333required = true
2334
2335[cards.endorsements.fields.org]
2336type = "string"
2337title = "Organization"
2338description = "Endorser's organization"
2339default = "Unknown"
2340"#;
2341
2342        let config = QuillConfig::from_toml(toml_content).unwrap();
2343
2344        // Verify the card was parsed into config.cards
2345        assert!(config.cards.contains_key("endorsements"));
2346        let card = config.cards.get("endorsements").unwrap();
2347
2348        assert_eq!(card.name, "endorsements");
2349        assert_eq!(card.title, Some("Endorsements".to_string()));
2350        assert_eq!(card.description, "Chain of endorsements");
2351
2352        // Verify card fields
2353        assert_eq!(card.fields.len(), 2);
2354
2355        let name_field = card.fields.get("name").unwrap();
2356        assert_eq!(name_field.r#type, Some("string".to_string()));
2357        assert_eq!(name_field.title, Some("Endorser Name".to_string()));
2358        assert!(name_field.required);
2359
2360        let org_field = card.fields.get("org").unwrap();
2361        assert_eq!(org_field.r#type, Some("string".to_string()));
2362        assert!(org_field.default.is_some());
2363        assert_eq!(
2364            org_field.default.as_ref().unwrap().as_str(),
2365            Some("Unknown")
2366        );
2367    }
2368
2369    #[test]
2370    fn test_field_schema_ignores_unknown_keys() {
2371        // Test that unknown keys like "items" are now just warnings
2372        let yaml = r#"
2373type: "string"
2374description: "A string field"
2375items:
2376  sub_field:
2377    type: "string"
2378    description: "Nested field"
2379"#;
2380        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2381        let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2382        // This should now succeed since items is just an unknown key (warning only)
2383        let result = FieldSchema::from_quill_value("author".to_string(), &quill_value);
2384
2385        // The parsing should succeed, items is now just an unknown field
2386        assert!(result.is_ok());
2387        let schema = result.unwrap();
2388        assert_eq!(schema.r#type, Some("string".to_string()));
2389    }
2390
2391    #[test]
2392    fn test_quill_config_with_cards_section() {
2393        let toml_content = r#"[Quill]
2394name = "cards-test"
2395backend = "typst"
2396description = "Test [cards] section"
2397
2398[fields.regular]
2399description = "Regular field"
2400type = "string"
2401
2402[cards.indorsements]
2403title = "Routing Indorsements"
2404description = "Chain of endorsements"
2405
2406[cards.indorsements.fields.name]
2407title = "Name"
2408type = "string"
2409description = "Name field"
2410"#;
2411
2412        let config = QuillConfig::from_toml(toml_content).unwrap();
2413
2414        // Check regular field
2415        assert!(config.fields.contains_key("regular"));
2416        let regular = config.fields.get("regular").unwrap();
2417        assert_eq!(regular.r#type, Some("string".to_string()));
2418
2419        // Check card is in config.cards (not config.fields)
2420        assert!(config.cards.contains_key("indorsements"));
2421        let card = config.cards.get("indorsements").unwrap();
2422        assert_eq!(card.title, Some("Routing Indorsements".to_string()));
2423        assert_eq!(card.description, "Chain of endorsements");
2424        assert!(card.fields.contains_key("name"));
2425    }
2426
2427    #[test]
2428    fn test_quill_config_cards_empty_fields() {
2429        // Test that cards with no fields section are valid
2430        let toml_content = r#"[Quill]
2431name = "cards-empty-fields-test"
2432backend = "typst"
2433description = "Test cards without fields"
2434
2435[cards.myscope]
2436description = "My scope"
2437"#;
2438
2439        let config = QuillConfig::from_toml(toml_content).unwrap();
2440        let card = config.cards.get("myscope").unwrap();
2441        assert_eq!(card.name, "myscope");
2442        assert_eq!(card.description, "My scope");
2443        assert!(card.fields.is_empty());
2444    }
2445
2446    #[test]
2447    fn test_quill_config_card_collision() {
2448        // Test that scope name colliding with field name is an error
2449        let toml_content = r#"[Quill]
2450name = "collision-test"
2451backend = "typst"
2452description = "Test collision"
2453
2454[fields.conflict]
2455description = "Field"
2456type = "string"
2457
2458[cards.conflict]
2459description = "Card"
2460items = {}
2461"#;
2462
2463        let result = QuillConfig::from_toml(toml_content);
2464        assert!(result.is_err());
2465        assert!(result
2466            .unwrap_err()
2467            .to_string()
2468            .contains("conflicts with an existing field name"));
2469    }
2470
2471    #[test]
2472    fn test_quill_config_ordering_with_cards() {
2473        // Test that cards have proper UI ordering
2474        let toml_content = r#"[Quill]
2475name = "ordering-test"
2476backend = "typst"
2477description = "Test ordering"
2478
2479[fields.first]
2480description = "First"
2481
2482[cards.second]
2483description = "Second"
2484
2485[fields.zero]
2486description = "Zero"
2487"#;
2488
2489        let config = QuillConfig::from_toml(toml_content).unwrap();
2490
2491        let first = config.fields.get("first").unwrap();
2492        let zero = config.fields.get("zero").unwrap();
2493        let second = config.cards.get("second").unwrap(); // Cards are in config.cards now
2494
2495        // Check relative ordering
2496        let ord_first = first.ui.as_ref().unwrap().order.unwrap();
2497        let ord_zero = zero.ui.as_ref().unwrap().order.unwrap();
2498        let ord_second = second.ui.as_ref().unwrap().order.unwrap();
2499
2500        // toml_edit validation:
2501        // fields keys: ["first", "zero"] (0, 1)
2502        // cards keys: ["second"] (2)
2503
2504        assert!(ord_first < ord_second);
2505        assert!(ord_zero < ord_second);
2506
2507        // Within fields, "first" is before "zero"
2508        assert!(ord_first < ord_zero);
2509
2510        assert_eq!(ord_first, 0);
2511        assert_eq!(ord_zero, 1);
2512        assert_eq!(ord_second, 2);
2513    }
2514}