Skip to main content

rustxform_core/
lib.rs

1//! Core data model shared across the rustxform pipeline.
2//!
3//! These types are the normalized, backend-agnostic representation of an
4//! XLSForm after parsing and before XForm emission. They grow as later phases
5//! add groups, repeats, translations and parameters.
6
7/// Form-level settings, sourced from the XLSForm `settings` sheet.
8#[derive(Debug, Clone, Default, PartialEq, Eq)]
9pub struct Settings {
10    /// Form identifier (`form_id`); defaults to `data` when absent.
11    pub form_id: Option<String>,
12    /// Human-readable form title.
13    pub title: Option<String>,
14    /// Form version string.
15    pub version: Option<String>,
16    /// Default language label, e.g. `French (fr)`.
17    pub default_language: Option<String>,
18    /// `instance_name` expression (populates `meta/instanceName`), if any.
19    pub instance_name: Option<String>,
20    /// `style` setting (becomes the body `class`), if any.
21    pub style: Option<String>,
22    /// `public_key` for encrypted submissions (`base64RsaPublicKey`), if any.
23    pub public_key: Option<String>,
24    /// `submission_url` (the `<submission action>`), if any.
25    pub submission_url: Option<String>,
26    /// `auto_send` setting (`orx:auto-send`), if any.
27    pub auto_send: Option<String>,
28    /// `auto_delete` setting (`orx:auto-delete`), if any.
29    pub auto_delete: Option<String>,
30}
31
32/// Localizable text from a `label`/`hint` column family.
33///
34/// A plain `label` column fills [`default`](Self::default); language-qualified
35/// `label::Lang` columns fill [`langs`](Self::langs). The two are mutually
36/// exclusive in practice.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct Localized {
39    /// Text from an unqualified column, if any.
40    pub default: Option<String>,
41    /// Per-language texts `(language, text)`, in language order.
42    pub langs: Vec<(String, String)>,
43}
44
45impl Localized {
46    /// `true` when no text is present at all.
47    #[must_use]
48    pub fn is_empty(&self) -> bool {
49        self.default.is_none() && self.langs.is_empty()
50    }
51
52    /// `true` when language-qualified texts are present.
53    #[must_use]
54    pub fn is_multilingual(&self) -> bool {
55        !self.langs.is_empty()
56    }
57
58    /// The unqualified single-language text, if any.
59    #[must_use]
60    pub fn single(&self) -> Option<&str> {
61        self.default.as_deref()
62    }
63
64    /// The text for a given language, if any.
65    #[must_use]
66    pub fn for_lang(&self, lang: &str) -> Option<&str> {
67        self.langs
68            .iter()
69            .find(|(l, _)| l == lang)
70            .map(|(_, t)| t.as_str())
71    }
72}
73
74/// The resolved semantics of a question's `type` column.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum Kind {
77    /// A built-in type with a fixed XForm mapping.
78    Builtin(Builtin),
79    /// A `select_one` / `select_multiple` / `rank` over a choice list or file.
80    Select {
81        /// Which selection control this is.
82        select: SelectType,
83        /// The instance id: a choice-list name, or an external file's stem.
84        list: String,
85        /// External source filename for `select_*_from_file`; `None` inline.
86        file: Option<String>,
87    },
88    /// An `osm <tagset>` capture: an `osm/*` upload with tag children.
89    Osm {
90        /// Name of the tag list (from the `osm` sheet).
91        tagset: String,
92    },
93    /// A type token not yet supported; emitted as a plain string bind.
94    Unknown(String),
95}
96
97/// Which selection control a [`Kind::Select`] renders as.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum SelectType {
100    /// `select_one` → `<select1>`.
101    One,
102    /// `select_multiple` → `<select>`.
103    Multiple,
104    /// `rank` → `<odk:rank>`.
105    Rank,
106}
107
108/// The XForm body control a built-in question renders as.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum Control {
111    /// `<input>`.
112    Input,
113    /// `<range>` (uses `start`/`end`/`step` from `parameters`).
114    Range,
115    /// `<trigger>` (e.g. `acknowledge`).
116    Trigger,
117    /// `<upload>` with the given `mediatype`.
118    Upload {
119        /// The `mediatype` attribute, e.g. `image/*`.
120        mediatype: &'static str,
121    },
122}
123
124/// A metadata preload binding (`jr:preload` + `jr:preloadParams`).
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct Preload {
127    /// The `jr:preload` value, e.g. `timestamp` or `property`.
128    pub preload: &'static str,
129    /// The `jr:preloadParams` value, e.g. `start` or `deviceid`.
130    pub params: &'static str,
131}
132
133/// A label media attachment: a form (`image`/`audio`/`video`) and its file(s),
134/// which may be single- or multi-language.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Media {
137    /// The media form: `image`, `audio` or `video`.
138    pub form: String,
139    /// Filenames, single (unqualified) or per-language.
140    pub files: Localized,
141}
142
143/// The XForm mapping for a built-in question type.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct Builtin {
146    /// Body control, or `None` for data-only types (`calculate`, preloads).
147    pub control: Option<Control>,
148    /// XForm bind data type (e.g. `string`, `int`, `binary`).
149    pub bind_type: &'static str,
150    /// Whether the bind is read-only.
151    pub readonly: bool,
152    /// Metadata preload, if this type is a preload.
153    pub preload: Option<Preload>,
154    /// A model-level action this type emits (e.g. `odk:recordaudio`).
155    pub action: Option<Action>,
156}
157
158/// A model-level action element bound to a question.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct Action {
161    /// Element name, e.g. `odk:recordaudio` or `odk:setgeopoint`.
162    pub element: &'static str,
163    /// The `event` attribute, e.g. `odk-instance-load`.
164    pub event: &'static str,
165}
166
167/// A single survey question from the `survey` sheet.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct Question {
170    /// Resolved type semantics.
171    pub kind: Kind,
172    /// Node name; becomes the instance element name.
173    pub name: String,
174    /// Label text (single- or multi-language).
175    pub label: Localized,
176    /// Hint text (single- or multi-language).
177    pub hint: Localized,
178    /// `guidance_hint` text: a secondary hint rendered via an itext
179    /// `<value form="guidance">` (single- or multi-language).
180    pub guidance_hint: Localized,
181    /// `appearance` column value, if any.
182    pub appearance: Option<String>,
183    /// Expression from the `calculation` column, if any.
184    pub calculation: Option<String>,
185    /// Expression from the `relevant` column, if any.
186    pub relevant: Option<String>,
187    /// Expression from the `constraint` column, if any.
188    pub constraint: Option<String>,
189    /// Raw `required` column value (e.g. `yes` or an expression), if any.
190    pub required: Option<String>,
191    /// Raw `read_only` column value, if any.
192    pub readonly: Option<String>,
193    /// `constraint_message` column (single- or multi-language).
194    pub constraint_message: Localized,
195    /// `required_message` column (single- or multi-language).
196    pub required_message: Localized,
197    /// Parsed `parameters` column, as `(key, value)` pairs.
198    pub parameters: Vec<(String, String)>,
199    /// Label media (images/audio/video), possibly per-language.
200    pub media: Vec<Media>,
201    /// Default value (`default` column), placed in the primary instance.
202    pub default: Option<String>,
203    /// `choice_filter` expression for cascading selects, if any.
204    pub choice_filter: Option<String>,
205    /// `save_to` column: the entity property this answer populates, if any.
206    pub save_to: Option<String>,
207    /// `trigger` column: names a node whose change drives this question's
208    /// `calculation` via an `odk:setvalue` action instead of a calculate bind.
209    pub trigger: Option<String>,
210}
211
212impl Question {
213    /// The value of a parameter from the `parameters` column, if present.
214    #[must_use]
215    pub fn parameter(&self, key: &str) -> Option<&str> {
216        self.parameters
217            .iter()
218            .find(|(k, _)| k == key)
219            .map(|(_, v)| v.as_str())
220    }
221}
222
223/// One option within a choice list.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct Choice {
226    /// Stored value (`name` column).
227    pub name: String,
228    /// Display label (single- or multi-language).
229    pub label: Localized,
230    /// Extra columns `(name, value)` for cascading filters, in header order.
231    pub extra: Vec<(String, String)>,
232}
233
234/// A named list of choices from the `choices` sheet.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct ChoiceList {
237    /// List name referenced by `select_*` questions.
238    pub name: String,
239    /// Options in sheet order.
240    pub items: Vec<Choice>,
241}
242
243/// A container of child nodes: a group (`<group>`) or a repeat (`<repeat>`).
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub struct Container {
246    /// Node name; becomes the enclosing instance element.
247    pub name: String,
248    /// Default-language label, if any.
249    pub label: Option<String>,
250    /// `appearance` column value (e.g. `field-list`), if any.
251    pub appearance: Option<String>,
252    /// `repeat_count` expression (repeats only), if any.
253    pub count: Option<String>,
254    /// Ordered child nodes.
255    pub children: Vec<Node>,
256}
257
258/// A node in the survey tree: a question, a group, or a repeat.
259#[expect(
260    clippy::large_enum_variant,
261    reason = "Question is by far the most common node; boxing it would add an allocation on the common path"
262)]
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub enum Node {
265    /// A leaf question.
266    Question(Question),
267    /// A non-repeating group of nodes.
268    Group(Container),
269    /// A repeating group of nodes.
270    Repeat(Container),
271}
272
273/// An ODK Entities declaration (the `entities` sheet): the survey creates an
274/// entity in a dataset when submitted.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct Entity {
277    /// Target dataset name.
278    pub dataset: String,
279    /// Label expression for the entity, if any.
280    pub label: Option<String>,
281    /// `entity_id` expression: present ⇒ update mode, absent ⇒ create.
282    pub entity_id: Option<String>,
283    /// `create_if` condition expression, if any.
284    pub create_if: Option<String>,
285    /// `update_if` condition expression, if any.
286    pub update_if: Option<String>,
287}
288
289/// A parsed XLSForm survey: settings, a node tree and choice lists.
290#[derive(Debug, Clone, Default, PartialEq, Eq)]
291pub struct Survey {
292    /// Form-level settings.
293    pub settings: Settings,
294    /// Ordered top-level nodes.
295    pub children: Vec<Node>,
296    /// Choice lists from the `choices` sheet.
297    pub choices: Vec<ChoiceList>,
298    /// Declared languages, in order; empty for a single-language form.
299    pub languages: Vec<String>,
300    /// Entities declaration from the `entities` sheet, if any.
301    pub entity: Option<Entity>,
302    /// Whether an `audit` metadata question is present.
303    pub audit: bool,
304    /// `xml-external` instance ids (each loads `jr://file/<id>.xml`).
305    pub external_instances: Vec<String>,
306    /// OSM tag lists from the `osm` sheet.
307    pub osm_tags: Vec<ChoiceList>,
308}
309
310impl Survey {
311    /// Return the choice list with the given name, if present.
312    #[must_use]
313    pub fn choice_list(&self, name: &str) -> Option<&ChoiceList> {
314        self.choices.iter().find(|c| c.name == name)
315    }
316}
317
318/// Resolve a single XLSForm type token to its built-in XForm mapping.
319///
320/// Returns `None` for `select_*` (handled separately) and unknown tokens.
321/// The table grows as later phases add question kinds.
322#[must_use]
323pub fn resolve_builtin(kind: &str) -> Option<Builtin> {
324    let b = |control, bind_type, readonly, preload| Builtin {
325        control,
326        bind_type,
327        readonly,
328        preload,
329        action: None,
330    };
331    let input = Some(Control::Input);
332    let preload = |preload, params| Some(Preload { preload, params });
333
334    Some(match kind {
335        "text" => b(input, "string", false, None),
336        "integer" => b(input, "int", false, None),
337        "decimal" => b(input, "decimal", false, None),
338        "range" => b(Some(Control::Range), "int", false, None),
339        "date" => b(input, "date", false, None),
340        "time" => b(input, "time", false, None),
341        "dateTime" => b(input, "dateTime", false, None),
342        "geopoint" => b(input, "geopoint", false, None),
343        "geotrace" => b(input, "geotrace", false, None),
344        "geoshape" => b(input, "geoshape", false, None),
345        "barcode" => b(input, "barcode", false, None),
346        "note" => b(input, "string", true, None),
347        "acknowledge" => b(Some(Control::Trigger), "string", false, None),
348        "image" => b(
349            Some(Control::Upload {
350                mediatype: "image/*",
351            }),
352            "binary",
353            false,
354            None,
355        ),
356        "audio" => b(
357            Some(Control::Upload {
358                mediatype: "audio/*",
359            }),
360            "binary",
361            false,
362            None,
363        ),
364        "video" => b(
365            Some(Control::Upload {
366                mediatype: "video/*",
367            }),
368            "binary",
369            false,
370            None,
371        ),
372        "file" => b(
373            Some(Control::Upload {
374                mediatype: "application/*",
375            }),
376            "binary",
377            false,
378            None,
379        ),
380        "calculate" => b(None, "string", false, None),
381        "hidden" => b(None, "string", false, None),
382        "start" => b(None, "dateTime", false, preload("timestamp", "start")),
383        "end" => b(None, "dateTime", false, preload("timestamp", "end")),
384        "today" => b(None, "date", false, preload("date", "today")),
385        "deviceid" => b(None, "string", false, preload("property", "deviceid")),
386        "username" => b(None, "string", false, preload("property", "username")),
387        "phonenumber" => b(None, "string", false, preload("property", "phonenumber")),
388        "email" => b(None, "string", false, preload("property", "email")),
389        "simserial" => b(None, "string", false, preload("property", "simserial")),
390        "subscriberid" => b(None, "string", false, preload("property", "subscriberid")),
391        "background-audio" => Builtin {
392            control: None,
393            bind_type: "binary",
394            readonly: false,
395            preload: None,
396            action: Some(Action {
397                element: "odk:recordaudio",
398                event: "odk-instance-load",
399            }),
400        },
401        "start-geopoint" => Builtin {
402            control: None,
403            bind_type: "geopoint",
404            readonly: false,
405            preload: None,
406            action: Some(Action {
407                element: "odk:setgeopoint",
408                event: "odk-instance-first-load",
409            }),
410        },
411        // Passive geopoint capture triggered by another field's change; the
412        // `odk:setgeopoint` action is emitted on that trigger node, not here.
413        "background-geopoint" => b(None, "geopoint", false, None),
414        _ => return None,
415    })
416}