Skip to main content

graphrt_ffi/
ui.rs

1//! UI blocks (cards, charts, tables, stat tiles, diagrams) checked before an
2//! app renders them (feature `ui`). Without the feature, [`validate_ui_block`]
3//! reports that it is unavailable and runs emit no `Ui` events.
4
5use crate::GraphrtError;
6use crate::events::UiBlock;
7
8/// The checked block, or why it must not be shown.
9#[cfg(feature = "ui")]
10pub(crate) fn checked(json: &serde_json::Value) -> Result<UiBlock, String> {
11    let block = graphrt_ui::validate(json).map_err(|e| e.to_string())?;
12    Ok(UiBlock {
13        kind: block.kind().as_str().to_owned(),
14        title: block.title().map(str::to_owned),
15        json: block.as_json().to_string(),
16    })
17}
18
19/// Check a UI block (`{"$ui": "chart", "version": 1, ...}`) against its schema,
20/// for blocks an app receives outside a run (stored messages, a server).
21#[uniffi::export]
22pub fn validate_ui_block(block_json: String) -> Result<UiBlock, GraphrtError> {
23    #[cfg(feature = "ui")]
24    {
25        let json: serde_json::Value =
26            serde_json::from_str(&block_json).map_err(|e| GraphrtError::input(format!("block: {e}")))?;
27        checked(&json).map_err(GraphrtError::input)
28    }
29    #[cfg(not(feature = "ui"))]
30    {
31        let _ = block_json;
32        Err(GraphrtError::unsupported("UI block validation", "ui"))
33    }
34}
35
36#[cfg(all(test, feature = "ui"))]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn blocks_are_checked() {
42        let stats = r#"{"$ui": "stats", "version": 1, "title": "Today", "items": [{"label": "Orders", "value": 12}]}"#;
43        let block = validate_ui_block(stats.into()).unwrap();
44        assert_eq!((block.kind.as_str(), block.title.as_deref()), ("stats", Some("Today")));
45        assert!(validate_ui_block(r#"{"$ui": "stats", "version": 2}"#.into()).is_err());
46        assert!(validate_ui_block(r#"{"$ui": "slideshow", "version": 1}"#.into()).is_err());
47        assert!(validate_ui_block("[".into()).is_err());
48    }
49}