diff --git a/crates/floatile-cli/tests/ai_balance.rs b/crates/floatile-cli/tests/ai_balance.rs index 1c432e2..ded5f48 100644 --- a/crates/floatile-cli/tests/ai_balance.rs +++ b/crates/floatile-cli/tests/ai_balance.rs @@ -2,6 +2,10 @@ #![allow(clippy::unwrap_used)] use std::path::PathBuf; +use std::{collections::BTreeSet, io::Read}; + +use floatile_ui_schema::JsonSchema; +use floatile_ui_schema::ir::{Component, PropValue, UiDocument}; #[test] fn ai_balance_reference_builds_without_secret_material() { @@ -31,5 +35,109 @@ fn ai_balance_reference_builds_without_secret_material() { "reference package contains forbidden credential marker" ); } + assert_pp_m6_ui_contract(&package); let _ = std::fs::remove_file(output); } + +fn assert_pp_m6_ui_contract(package: &[u8]) { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(package)).unwrap(); + let names = (0..archive.len()) + .map(|index| archive.by_index(index).unwrap().name().to_owned()) + .collect::>(); + assert!( + names + .iter() + .all(|name| !name.ends_with(".slint") && !name.ends_with(".html")), + "PP-M6 reference package must not ship third-party Slint or HTML" + ); + + let mut ftui = String::new(); + archive + .by_name("ui/widget.ftui") + .unwrap() + .read_to_string(&mut ftui) + .unwrap(); + let document: UiDocument = serde_json::from_str(&ftui).unwrap(); + floatile_ui_schema::validate_document(&document).unwrap(); + assert_eq!(document.ui_api_version, floatile_ui_schema::UI_API_VERSION); + + let mut kinds = BTreeSet::new(); + let mut labeled_metrics = 0; + let mut uses_theme_token = false; + collect_ui_evidence( + &document.root, + &mut kinds, + &mut labeled_metrics, + &mut uses_theme_token, + ); + for required in [ + "If", + "Column", + "Responsive", + "List", + "Badge", + "Progress", + "Sparkline", + "Text", + ] { + assert!( + kinds.contains(required), + "missing PP-M6 component {required}" + ); + } + assert!(labeled_metrics >= 2, "metric/chart labels must be explicit"); + assert!( + uses_theme_token, + "reference must consume a host theme token" + ); + + let JsonSchema::Object { properties, .. } = &document.state.schema else { + panic!("AI Balance state schema must be an object"); + }; + assert_bounded_array(properties.get("entries"), 256); + assert_bounded_array(properties.get("trend"), 128); +} + +fn collect_ui_evidence( + component: &Component, + kinds: &mut BTreeSet, + labeled_metrics: &mut usize, + uses_theme_token: &mut bool, +) { + kinds.insert(component.kind.clone()); + if matches!(component.kind.as_str(), "Progress" | "Gauge") + && component.props.contains_key("accessibilityLabel") + { + *labeled_metrics += 1; + } + if component.kind == "Sparkline" && component.props.contains_key("label") { + *labeled_metrics += 1; + } + *uses_theme_token |= matches!( + component.props.get("colorToken"), + Some(PropValue::Literal(value)) if value.as_str().is_some() + ); + for child in &component.children { + collect_ui_evidence(child, kinds, labeled_metrics, uses_theme_token); + } + for branch in [component.then.as_deref(), component.else_.as_deref()] + .into_iter() + .flatten() + { + collect_ui_evidence(branch, kinds, labeled_metrics, uses_theme_token); + } + if let Some(template) = component.template.as_deref() { + collect_ui_evidence(template, kinds, labeled_metrics, uses_theme_token); + } +} + +fn assert_bounded_array(schema: Option<&JsonSchema>, limit: usize) { + let Some(JsonSchema::Array { + max_items: Some(max_items), + .. + }) = schema + else { + panic!("PP-M6 collection state must declare maxItems"); + }; + assert!(*max_items <= limit, "array budget exceeds {limit}"); +} diff --git a/crates/floatile-renderer/src/lib.rs b/crates/floatile-renderer/src/lib.rs index 9878e82..ea8622b 100644 --- a/crates/floatile-renderer/src/lib.rs +++ b/crates/floatile-renderer/src/lib.rs @@ -16,4 +16,4 @@ pub mod error; pub mod render; pub use error::RendererError; -pub use render::{BindingSlot, EventSlot, RenderedComponent, render_component}; +pub use render::{BindingSlot, BindingValueType, EventSlot, RenderedComponent, render_component}; diff --git a/crates/floatile-renderer/src/render.rs b/crates/floatile-renderer/src/render.rs index b78c223..4210f03 100644 --- a/crates/floatile-renderer/src/render.rs +++ b/crates/floatile-renderer/src/render.rs @@ -20,6 +20,19 @@ pub struct BindingSlot { pub path: String, /// 生成的宿主属性名(如 `prop_time`)。 pub prop: String, + /// Slint 投影值类型;运行时必须按此类型转换权威 State。 + pub value_type: BindingValueType, +} + +/// renderer 与 shell 共享的有限 State 投影类型。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum BindingValueType { + String, + Boolean, + Number, + StringList, + NumberList, } /// 一个输入事件:声明事件名 → 生成的回调名。 @@ -46,7 +59,15 @@ pub struct RenderedComponent { pub fn render_component(doc: &UiDocument) -> Result { // renderer 独立复验(CLI/runtime 通过不代表本层可跳过)。 validate_document(doc)?; - let mut ctx = Ctx::default(); + let mut ctx = Ctx { + ui_minor: doc + .ui_api_version + .split('.') + .nth(1) + .and_then(|minor| minor.parse().ok()) + .unwrap_or_default(), + ..Default::default() + }; let body = render_node(&doc.root, &mut ctx, 0)?; let bindings: Vec = ctx.bindings.into_values().collect(); let events: Vec = ctx.events.values().cloned().collect(); @@ -65,6 +86,7 @@ struct Ctx { events: BTreeMap, nodes: usize, callback_counter: usize, + ui_minor: u64, } fn wrap_component(body: &str, bindings: &[BindingSlot], callbacks: &[EventSlot]) -> String { @@ -73,7 +95,17 @@ fn wrap_component(body: &str, bindings: &[BindingSlot], callbacks: &[EventSlot]) // `export` 让宿主的 `slint!` 能 `import` 本组件并把权威 State 投影到其绑定槽位。 out.push_str("export component ClockPluginUI inherits Rectangle {\n"); for slot in bindings { - out.push_str(&format!(" in property {}: \"\";\n", slot.prop)); + let (kind, default) = match slot.value_type { + BindingValueType::String => ("string", "\"\""), + BindingValueType::Boolean => ("bool", "false"), + BindingValueType::Number => ("float", "0"), + BindingValueType::StringList => ("[string]", "[]"), + BindingValueType::NumberList => ("[float]", "[]"), + }; + out.push_str(&format!( + " in property <{kind}> {}: {default};\n", + slot.prop + )); } for slot in callbacks { out.push_str(&format!(" callback {};\n", slot.callback)); @@ -108,11 +140,15 @@ fn render_node(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result render_layout(comp, ctx, depth, "VerticalLayout"), "Row" => render_layout(comp, ctx, depth, "HorizontalLayout"), "Stack" => render_layout(comp, ctx, depth, "StackLayout"), - "Grid" => render_layout(comp, ctx, depth, "GridLayout"), + "Grid" => render_grid(comp, ctx, depth), + "Responsive" => render_responsive(comp, ctx, depth), + "List" => render_list(comp, ctx, depth), + "Sparkline" => render_sparkline(comp, ctx), "Text" => render_text(comp, ctx), "Button" => render_button(comp, ctx), "Toggle" => render_toggle(comp, ctx), "Progress" => render_meter(comp, ctx, false), + "Badge" => render_badge(comp, ctx), "Gauge" => render_meter(comp, ctx, true), "If" => render_if(comp, ctx, depth), "ForEach" => render_foreach(comp, ctx, depth), @@ -123,6 +159,167 @@ fn render_node(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result Result { + let breakpoint = comp + .props + .get("breakpoint") + .and_then(|value| match value { + PropValue::Literal(value) => value.as_f64(), + PropValue::Binding(_) => None, + }) + .ok_or_else(|| RendererError::BindingError("Responsive 缺少 breakpoint".to_owned()))?; + let mut children = String::new(); + for child in &comp.children { + children.push_str(&render_node(child, ctx, depth + 1)?); + children.push('\n'); + } + let props = render_layout_props(comp)?; + Ok(format!( + "if root.width < {breakpoint}px: VerticalLayout {{\n{props}{children}}}\nif root.width >= {breakpoint}px: HorizontalLayout {{\n{props}{children}}}\n" + )) +} + +fn render_sparkline(comp: &Component, ctx: &mut Ctx) -> Result { + let label = match comp.props.get("label") { + Some(PropValue::Binding(Binding::State { bind })) => { + format!( + "root.{}", + binding_slot(bind, BindingValueType::String, ctx)?.prop + ) + } + Some(PropValue::Literal(value)) => encode_string(value.as_str().ok_or_else(|| { + RendererError::BindingError("Sparkline.label 必须是 string".to_owned()) + })?)?, + _ => { + return Err(RendererError::BindingError( + "Sparkline 缺少 label prop".to_owned(), + )); + } + }; + let color = match comp.props.get("tone") { + Some(PropValue::Literal(value)) => match value.as_str() { + Some("success") => "#247a45", + Some("warning") => "#a86600", + Some("danger") => "#a33a3a", + Some("info") | None => "#2f6feb", + Some(other) => { + return Err(RendererError::BindingError(format!( + "Sparkline.tone 不支持 `{other}`" + ))); + } + }, + None => "#2f6feb", + Some(PropValue::Binding(_)) => { + return Err(RendererError::BindingError( + "Sparkline.tone 不允许绑定".to_owned(), + )); + } + }; + let bars = match comp.props.get("values") { + Some(PropValue::Binding(Binding::State { bind })) => { + let values = format!( + "root.{}", + binding_slot(bind, BindingValueType::NumberList, ctx)?.prop + ); + format!( + " for value in {values}: Rectangle {{\n width: 4px;\n height: parent.height * ((value < 0 ? 0 : (value > 100 ? 100 : value)) / 100);\n background: {color};\n }}\n" + ) + } + Some(PropValue::Literal(value)) => { + let values = value.as_array().ok_or_else(|| { + RendererError::BindingError("Sparkline.values 必须是 number array".to_owned()) + })?; + let mut bars = String::new(); + for value in values { + let value = value.as_f64().ok_or_else(|| { + RendererError::BindingError("Sparkline.values 必须是 number array".to_owned()) + })?; + let value = value.clamp(0.0, 100.0); + bars.push_str(&format!( + " Rectangle {{ width: 4px; height: parent.height * {value} / 100; background: {color}; }}\n" + )); + } + bars + } + Some(PropValue::Binding(Binding::Item { .. })) | None => { + return Err(RendererError::BindingError( + "Sparkline.values 缺少受支持的值".to_owned(), + )); + } + }; + Ok(format!( + "Rectangle {{\n height: 48px;\n accessible-role: image;\n accessible-label: {label};\n HorizontalLayout {{\n spacing: 2px;\n alignment: end;\n{bars} }}\n}}\n" + )) +} + +/// Grid:把声明式 columns 转为 Slint 的显式 Row 分组,避免忽略列数语义。 +fn render_grid(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result { + let columns = comp + .props + .get("columns") + .and_then(|value| match value { + PropValue::Literal(value) => value.as_u64(), + PropValue::Binding(_) => None, + }) + .unwrap_or(1) as usize; + let props = render_layout_props(comp)?; + let mut rows = String::new(); + for row in comp.children.chunks(columns) { + rows.push_str(" Row {\n"); + for child in row { + let rendered = render_node(child, ctx, depth + 1)?; + for line in rendered.lines() { + rows.push_str(" "); + rows.push_str(line); + rows.push('\n'); + } + } + rows.push_str(" }\n"); + } + Ok(format!("GridLayout {{\n{props}{rows}}}\n")) +} + +fn render_list(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result { + let Some(items) = comp.props.get("items") else { + return render_layout(comp, ctx, depth, "VerticalLayout"); + }; + if !comp.children.is_empty() { + return Err(RendererError::BindingError( + "List 使用 items 时不能同时声明静态 children".to_owned(), + )); + } + match items { + PropValue::Binding(Binding::State { bind }) => { + let slot = binding_slot(bind, BindingValueType::StringList, ctx)?; + Ok(format!( + "VerticalLayout {{\n for item in root.{}: Text {{ text: item; }}\n}}\n", + slot.prop + )) + } + PropValue::Binding(Binding::Item { .. }) => Err(RendererError::BindingError( + "List.items 不支持 ForEach item 绑定".to_owned(), + )), + PropValue::Literal(value) => { + let array = value.as_array().ok_or_else(|| { + RendererError::BindingError("List.items 必须是字符串数组".to_owned()) + })?; + let mut children = String::new(); + for item in array { + let text = item.as_str().ok_or_else(|| { + RendererError::BindingError("List.items 必须是字符串数组".to_owned()) + })?; + children.push_str(&format!(" Text {{ text: {}; }}\n", encode_string(text)?)); + } + Ok(format!("VerticalLayout {{\n{children}}}\n")) + } + } +} + /// 布局容器:展开 children,并映射公共样式 props。 fn render_layout( comp: &Component, @@ -164,7 +361,7 @@ fn render_text(comp: &Component, ctx: &mut Ctx) -> Result }; match prop { PropValue::Binding(Binding::State { bind }) => { - let slot = binding_slot(bind, ctx)?; + let slot = binding_slot(bind, BindingValueType::String, ctx)?; let mut out = String::from(" Text {\n"); out.push_str(&format!(" text: root.{0};\n", slot.prop)); out.push_str(&text_style_props(comp)?); @@ -192,7 +389,13 @@ fn render_text(comp: &Component, ctx: &mut Ctx) -> Result fn text_style_props(comp: &Component) -> Result { let mut out = String::new(); - if let Some(PropValue::Literal(v)) = comp.props.get("color") + if let Some(PropValue::Literal(v)) = comp.props.get("colorToken") + && let Some(token) = v.as_str() + { + let color = floatile_ui_schema::theme::color_token(token) + .ok_or_else(|| RendererError::EncodeError(format!("未知宿主主题 token `{token}`")))?; + out.push_str(&format!(" color: {};\n", color.value)); + } else if let Some(PropValue::Literal(v)) = comp.props.get("color") && let Some(s) = v.as_str() { out.push_str(&format!(" color: {0};\n", color_literal(s)?)); @@ -212,7 +415,7 @@ fn text_style_props(comp: &Component) -> Result { fn render_button(comp: &Component, ctx: &mut Ctx) -> Result { let label = match comp.props.get("label") { Some(PropValue::Binding(Binding::State { bind })) => { - let slot = binding_slot(bind, ctx)?; + let slot = binding_slot(bind, BindingValueType::String, ctx)?; format!("root.{0}", slot.prop) } Some(PropValue::Binding(Binding::Item { item })) => item.clone(), @@ -226,6 +429,8 @@ fn render_button(comp: &Component, ctx: &mut Ctx) -> Result Result Result { let checked = match comp.props.get("checked") { Some(PropValue::Binding(Binding::State { bind })) => { - let slot = binding_slot(bind, ctx)?; + let slot = binding_slot(bind, BindingValueType::Boolean, ctx)?; format!("root.{0}", slot.prop) } Some(PropValue::Binding(Binding::Item { item })) => item.clone(), @@ -263,9 +468,15 @@ fn render_toggle(comp: &Component, ctx: &mut Ctx) -> Result String { fn render_meter(comp: &Component, ctx: &mut Ctx, _gauge: bool) -> Result { let value = match comp.props.get("value") { Some(PropValue::Binding(Binding::State { bind })) => { - let slot = binding_slot(bind, ctx)?; - format!("root.{0}", slot.prop) + let slot = binding_slot(bind, BindingValueType::Number, ctx)?; + format!( + "(root.{0} < 0 ? 0 : (root.{0} > 100 ? 100 : root.{0}))", + slot.prop + ) } Some(PropValue::Binding(Binding::Item { .. })) => { return Err(RendererError::BindingError( @@ -301,7 +515,7 @@ fn render_meter(comp: &Component, ctx: &mut Ctx, _gauge: bool) -> Result { return Err(RendererError::BindingError( @@ -309,7 +523,15 @@ fn render_meter(comp: &Component, ctx: &mut Ctx, _gauge: bool) -> Result Result Result { + match comp.props.get(prop) { + Some(PropValue::Binding(Binding::State { bind })) => { + let slot = binding_slot(bind, BindingValueType::String, ctx)?; + Ok(format!("root.{0}", slot.prop)) + } + Some(PropValue::Binding(Binding::Item { item })) => Ok(item.clone()), + Some(PropValue::Literal(value)) => encode_string(&value_to_string(value)?), + None => Err(RendererError::BindingError(format!( + "{} 缺少 {prop} prop", + comp.kind + ))), + } +} + +fn render_accessibility_label(comp: &Component, ctx: &mut Ctx) -> Result { + if ctx.ui_minor < 6 && !comp.props.contains_key("accessibilityLabel") { + return encode_string(&comp.kind); + } + render_string_prop(comp, "accessibilityLabel", ctx) +} + +/// Badge:宿主语义 tone 映射到固定主题色,不接受插件提供的颜色源码。 +fn render_badge(comp: &Component, ctx: &mut Ctx) -> Result { + let label = match comp.props.get("label") { + Some(PropValue::Binding(Binding::State { bind })) => { + let slot = binding_slot(bind, BindingValueType::String, ctx)?; + format!("root.{0}", slot.prop) + } + Some(PropValue::Binding(Binding::Item { item })) => item.clone(), + Some(PropValue::Literal(value)) => encode_string(&value_to_string(value)?)?, + None => { + return Err(RendererError::BindingError( + "Badge 缺少 label prop".to_owned(), + )); + } + }; + let tone = match comp.props.get("tone") { + None => "neutral", + Some(PropValue::Literal(value)) => value + .as_str() + .ok_or_else(|| RendererError::BindingError("Badge tone 必须是字符串".to_owned()))?, + Some(PropValue::Binding(_)) => { + return Err(RendererError::BindingError( + "Badge tone 不允许运行时绑定".to_owned(), + )); + } + }; + let background = match tone { + "neutral" => "#3b4351", + "info" => "#245ea8", + "success" => "#247a45", + "warning" => "#8a6418", + "danger" => "#9b3030", + other => { + return Err(RendererError::EncodeError(format!( + "Badge tone `{other}` 不在允许集合" + ))); + } + }; + Ok(format!( + " Rectangle {{\n border-radius: 8px;\n background: {background};\n height: 20px;\n Text {{\n text: {label};\n color: white;\n horizontal-alignment: center;\n vertical-alignment: center;\n }}\n }}\n" + )) +} + /// If:when 布尔绑定 → Slint `if` 结构。 fn render_if(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result { let Some(Binding::State { bind }) = &comp.when else { @@ -331,20 +624,18 @@ fn render_if(comp: &Component, ctx: &mut Ctx, depth: usize) -> Result Result Result { } /// 登记一个 State 绑定并返回生成的属性名(同路径复用同一属性)。 -fn binding_slot(bind: &str, ctx: &mut Ctx) -> Result { +fn binding_slot( + bind: &str, + value_type: BindingValueType, + ctx: &mut Ctx, +) -> Result { PathSegments::parse(bind).map_err(|e| RendererError::BindingError(format!("{bind}: {e}")))?; if let Some(slot) = ctx.bindings.get(bind) { + if slot.value_type != value_type { + return Err(RendererError::BindingError(format!( + "{bind} 被用于不兼容的投影类型" + ))); + } return Ok(slot.clone()); } if ctx.bindings.len() >= MAX_BINDINGS { @@ -403,6 +703,7 @@ fn binding_slot(bind: &str, ctx: &mut Ctx) -> Result let slot = BindingSlot { path: bind.to_owned(), prop, + value_type, }; ctx.bindings.insert(bind.to_owned(), slot.clone()); Ok(slot) @@ -506,7 +807,7 @@ mod tests { UiDocument { ui_api_version: floatile_ui_schema::UI_API_VERSION.into(), state: floatile_ui_schema::ir::StateSchema { - initial: json!({"time": "00:00:00", "running": false, "items": []}), + initial: json!({"time": "00:00:00", "running": false, "items": [], "trend": []}), schema: floatile_ui_schema::JsonSchema::Object { required: vec![], properties: BTreeMap::from([ @@ -526,6 +827,13 @@ mod tests { }), }, ), + ( + "trend".into(), + floatile_ui_schema::JsonSchema::Array { + max_items: Some(16), + items: Box::new(floatile_ui_schema::JsonSchema::Number), + }, + ), ]), additional_properties: false, }, @@ -603,6 +911,7 @@ mod tests { vec![BindingSlot { path: "$.time".into(), prop: "prop_time".into(), + value_type: BindingValueType::String, }] ); } @@ -646,9 +955,9 @@ mod tests { #[test] fn rejects_registry_but_unmapped_component() { - // registry 通过、但 renderer 尚未映射的组件(如 Scroll/List)由 renderer 层拒绝。 + // registry 通过、但 renderer 尚未映射的组件(如 Scroll)由 renderer 层拒绝。 let root = Component { - kind: "List".into(), + kind: "Scroll".into(), ..Default::default() }; let err = render_component(&doc(root)).unwrap_err(); @@ -717,11 +1026,11 @@ mod tests { }; let rendered = render_component(&doc(root)).unwrap(); let src = &rendered.source; + assert!(src.contains("if root.prop_running:"), "缺少 if 分支: {src}"); assert!( - src.contains("if root.prop_running: {"), - "缺少 if 分支: {src}" + src.contains("if !root.prop_running:"), + "缺少 else 分支: {src}" ); - assert!(src.contains("else {"), "缺少 else 分支: {src}"); assert!( src.contains("text: root.prop_time;"), "then 分支应渲染 time 绑定" @@ -774,12 +1083,18 @@ mod tests { fn renders_toggle_event_slot() { let root = Component { kind: "Toggle".into(), - props: BTreeMap::from([( - "checked".into(), - PropValue::Binding(Binding::State { - bind: "$.running".into(), - }), - )]), + props: BTreeMap::from([ + ( + "checked".into(), + PropValue::Binding(Binding::State { + bind: "$.running".into(), + }), + ), + ( + "accessibilityLabel".into(), + PropValue::Literal(json!("Timer running")), + ), + ]), events: BTreeMap::from([( "toggle".into(), floatile_ui_schema::ir::EmittedEvent { @@ -802,6 +1117,17 @@ mod tests { ); let rendered = render_component(&d).unwrap(); assert!(rendered.source.contains("TouchArea")); + assert!(rendered.source.contains("accessible-role: switch")); + assert!( + rendered + .source + .contains("accessible-checked: root.prop_running") + ); + assert!( + rendered + .source + .contains("accessible-label: \"Timer running\"") + ); // checked 绑定经受限三元映射为颜色(布尔 → 亮/暗色),无直接属性引用。 assert!( rendered @@ -816,4 +1142,198 @@ mod tests { }] ); } + + #[test] + fn renders_typed_boolean_and_number_slots() { + let root = column(vec![ + Component { + kind: "If".into(), + when: Some(Binding::State { + bind: "$.running".into(), + }), + then: Some(Box::new(text_bind("$.time"))), + ..Default::default() + }, + Component { + kind: "Progress".into(), + props: BTreeMap::from([ + ( + "value".into(), + PropValue::Binding(Binding::State { + bind: "$.percent".into(), + }), + ), + ( + "accessibilityLabel".into(), + PropValue::Literal(json!("Timer progress")), + ), + ]), + ..Default::default() + }, + ]); + let mut document = doc(root); + if let floatile_ui_schema::JsonSchema::Object { properties, .. } = + &mut document.state.schema + { + properties.insert("percent".into(), floatile_ui_schema::JsonSchema::Number); + } + document.state.initial["percent"] = json!(42.0); + let rendered = render_component(&document).unwrap(); + assert!(rendered.source.contains("in property prop_running")); + assert!(rendered.source.contains("in property prop_percent")); + assert!( + rendered + .source + .contains("accessible-role: progress-indicator") + ); + assert!( + rendered + .source + .contains("accessible-label: \"Timer progress\"") + ); + assert!(rendered.source.contains( + "width: parent.width * ((root.prop_percent < 0 ? 0 : (root.prop_percent > 100 ? 100 : root.prop_percent)) / 100)" + )); + } + + #[test] + fn renders_badge_with_host_owned_tone() { + let root = Component { + kind: "Badge".into(), + props: BTreeMap::from([ + ( + "label".into(), + PropValue::Binding(Binding::State { + bind: "$.time".into(), + }), + ), + ("tone".into(), PropValue::Literal(json!("success"))), + ]), + ..Default::default() + }; + let rendered = render_component(&doc(root)).unwrap(); + assert!(rendered.source.contains("background: #247a45")); + assert!(rendered.source.contains("text: root.prop_time")); + } + + #[test] + fn rejects_badge_tone_outside_host_palette() { + let root = Component { + kind: "Badge".into(), + props: BTreeMap::from([ + ("label".into(), PropValue::Literal(json!("unsafe"))), + ( + "tone".into(), + PropValue::Literal(json!("url(plugin-input)")), + ), + ]), + ..Default::default() + }; + let error = render_component(&doc(root)).unwrap_err(); + assert_eq!(error.code(), "RNDR_INVALID_IR"); + } + + #[test] + fn renders_bounded_string_list_model() { + let root = Component { + kind: "List".into(), + props: BTreeMap::from([( + "items".into(), + PropValue::Binding(Binding::State { + bind: "$.items".into(), + }), + )]), + ..Default::default() + }; + let mut document = doc_with_items(); + document.root = root; + let rendered = render_component(&document).unwrap(); + assert!( + rendered + .source + .contains("in property <[string]> prop_items") + ); + assert!(rendered.source.contains("for item in root.prop_items")); + assert_eq!( + rendered.bindings[0].value_type, + BindingValueType::StringList + ); + } + + #[test] + fn renders_grid_columns_as_explicit_rows() { + let child = |label: &str| Component { + kind: "Text".into(), + props: BTreeMap::from([("text".into(), PropValue::Literal(json!(label)))]), + ..Default::default() + }; + let root = Component { + kind: "Grid".into(), + props: BTreeMap::from([("columns".into(), PropValue::Literal(json!(2)))]), + children: vec![child("one"), child("two"), child("three")], + ..Default::default() + }; + let rendered = render_component(&doc(root)).unwrap(); + assert!(rendered.source.contains("GridLayout")); + assert_eq!(rendered.source.matches("Row {").count(), 2); + } + + #[test] + fn renders_accessible_bounded_sparkline() { + let root = Component { + kind: "Sparkline".into(), + props: BTreeMap::from([ + ( + "values".into(), + PropValue::Binding(Binding::State { + bind: "$.trend".into(), + }), + ), + ("label".into(), PropValue::Literal(json!("Usage trend"))), + ("tone".into(), PropValue::Literal(json!("info"))), + ]), + ..Default::default() + }; + let rendered = render_component(&doc(root)).unwrap(); + assert!(rendered.source.contains("in property <[float]> prop_trend")); + assert!(rendered.source.contains("accessible-role: image")); + assert!( + rendered + .source + .contains("accessible-label: \"Usage trend\"") + ); + assert_eq!( + rendered.bindings[0].value_type, + BindingValueType::NumberList + ); + } + + #[test] + fn renders_responsive_layout_from_host_width() { + let root = Component { + kind: "Responsive".into(), + props: BTreeMap::from([("breakpoint".into(), PropValue::Literal(json!(420)))]), + children: vec![text_bind("$.time")], + ..Default::default() + }; + let rendered = render_component(&doc(root)).unwrap(); + assert!(rendered.source.contains("if root.width < 420px")); + assert!(rendered.source.contains("if root.width >= 420px")); + assert_eq!(rendered.bindings.len(), 1); + } + + #[test] + fn resolves_named_text_color_from_host_registry() { + let root = Component { + kind: "Text".into(), + props: BTreeMap::from([ + ("text".into(), PropValue::Literal(json!("balance"))), + ("colorToken".into(), PropValue::Literal(json!("accent"))), + ]), + ..Default::default() + }; + let rendered = render_component(&doc(root)).unwrap(); + assert!(rendered.source.contains("color: #89b4fa")); + assert!(!rendered.source.contains("accent")); + } } diff --git a/crates/floatile-sdk/src/view.rs b/crates/floatile-sdk/src/view.rs index b52ceca..ce21b88 100644 --- a/crates/floatile-sdk/src/view.rs +++ b/crates/floatile-sdk/src/view.rs @@ -35,6 +35,59 @@ pub fn stack(children: Vec) -> View { } } +/// Grid 容器:列数是受验证的静态布局提示。 +pub fn grid(columns: u32, children: Vec) -> View { + let mut props = std::collections::BTreeMap::new(); + props.insert( + "columns".into(), + PropValue::Literal(serde_json::json!(columns)), + ); + View { + kind: "Grid".into(), + props, + children, + ..Default::default() + } +} + +/// 响应式容器:窗口宽度低于 breakpoint 时纵向,否则横向。 +pub fn responsive(breakpoint: f64, children: Vec) -> View { + View { + kind: "Responsive".into(), + props: std::collections::BTreeMap::from([( + "breakpoint".into(), + PropValue::Literal(serde_json::json!(breakpoint)), + )]), + children, + ..Default::default() + } +} + +/// 静态 List 容器。 +pub fn list(children: Vec) -> View { + View { + kind: "List".into(), + children, + ..Default::default() + } +} + +/// 动态字符串 List:绑定具有显式 `maxItems` 的 string array State。 +pub fn list_bind(path: &str) -> View { + let mut props = std::collections::BTreeMap::new(); + props.insert( + "items".into(), + PropValue::Binding(Binding::State { + bind: path.to_owned(), + }), + ); + View { + kind: "List".into(), + props, + ..Default::default() + } +} + /// Text 组件:绑定 State 路径。 pub fn text_bind(path: &str) -> View { let mut props = std::collections::BTreeMap::new(); @@ -79,6 +132,114 @@ pub fn button(label: &str) -> View { } } +/// Badge 组件:标签绑定 State 路径,tone 只能使用宿主定义的语义值。 +pub fn badge_bind(path: &str, tone: &str) -> View { + let mut props = std::collections::BTreeMap::new(); + props.insert( + "label".into(), + PropValue::Binding(Binding::State { + bind: path.to_owned(), + }), + ); + props.insert( + "tone".into(), + PropValue::Literal(serde_json::Value::String(tone.to_owned())), + ); + View { + kind: "Badge".into(), + props, + ..Default::default() + } +} + +/// Progress 组件:绑定 0..=100 的数值 State 路径,并提供无障碍标签。 +pub fn progress_bind_labeled(path: &str, accessibility_label: &str) -> View { + let props = std::collections::BTreeMap::from([ + ( + "value".into(), + PropValue::Binding(Binding::State { + bind: path.to_owned(), + }), + ), + ( + "accessibilityLabel".into(), + PropValue::Literal(serde_json::Value::String(accessibility_label.to_owned())), + ), + ]); + View { + kind: "Progress".into(), + props, + ..Default::default() + } +} + +/// Progress 兼容构造器;新代码应使用 [`progress_bind_labeled`] 提供上下文标签。 +pub fn progress_bind(path: &str) -> View { + progress_bind_labeled(path, "Progress") +} + +/// Sparkline:绑定有界 number array,并提供屏幕阅读器可用的替代标签。 +pub fn sparkline_bind(path: &str, label: &str, tone: &str) -> View { + let props = std::collections::BTreeMap::from([ + ( + "values".into(), + PropValue::Binding(Binding::State { + bind: path.to_owned(), + }), + ), + ( + "label".into(), + PropValue::Literal(serde_json::Value::String(label.to_owned())), + ), + ( + "tone".into(), + PropValue::Literal(serde_json::Value::String(tone.to_owned())), + ), + ]); + View { + kind: "Sparkline".into(), + props, + ..Default::default() + } +} + +/// If 控制节点:按 boolean State 绑定选择 then/else 分支。 +pub fn if_bind(path: &str, then_view: View, else_view: Option) -> View { + View { + kind: "If".into(), + when: Some(Binding::State { + bind: path.to_owned(), + }), + then: Some(Box::new(then_view)), + else_: else_view.map(Box::new), + ..Default::default() + } +} + +/// 标准 loading/empty/error/content 四态页面。 +/// +/// 优先级固定为 loading → error → empty → content,避免多个状态同时为真时 +/// 呈现不确定结果。三个路径都必须绑定 boolean State 字段。 +pub fn page_state( + loading_path: &str, + error_path: &str, + empty_path: &str, + loading: View, + error: View, + empty: View, + content: View, +) -> View { + if_bind( + loading_path, + loading, + Some(if_bind( + error_path, + error, + Some(if_bind(empty_path, empty, Some(content))), + )), + ) +} + /// 设置布局 props(padding、gap 等)。 pub fn with_props( mut view: View, @@ -90,6 +251,15 @@ pub fn with_props( view } +/// 为支持该 prop 的组件选择宿主命名颜色 token。 +pub fn with_color_token(mut view: View, token: &str) -> View { + view.props.insert( + "colorToken".into(), + PropValue::Literal(serde_json::Value::String(token.to_owned())), + ); + view +} + /// 从 View(根组件)+ State schema + 事件声明 构造 `widget.ftui` 文档。 pub fn into_document( root: View, @@ -107,3 +277,101 @@ pub fn into_document( root, } } + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn page_state_has_deterministic_priority() { + let view = page_state( + "$.loading", + "$.error", + "$.empty", + text_literal("loading"), + text_literal("error"), + text_literal("empty"), + text_literal("content"), + ); + assert_eq!(view.kind, "If"); + assert_eq!( + view.when, + Some(Binding::State { + bind: "$.loading".into() + }) + ); + let error_branch = view.else_.expect("page state 必须包含 error 分支"); + assert_eq!( + error_branch.when, + Some(Binding::State { + bind: "$.error".into() + }) + ); + let empty_branch = error_branch.else_.expect("page state 必须包含 empty 分支"); + assert_eq!( + empty_branch.when, + Some(Binding::State { + bind: "$.empty".into() + }) + ); + } + + #[test] + fn badge_and_progress_builders_emit_registry_components() { + let badge = badge_bind("$.status", "success"); + assert_eq!(badge.kind, "Badge"); + let progress = progress_bind("$.percent"); + assert_eq!(progress.kind, "Progress"); + assert_eq!( + progress.props.get("accessibilityLabel"), + Some(&PropValue::Literal(serde_json::json!("Progress"))) + ); + let labeled = progress_bind_labeled("$.percent", "Upload completion"); + assert_eq!( + labeled.props.get("accessibilityLabel"), + Some(&PropValue::Literal(serde_json::json!("Upload completion"))) + ); + } + + #[test] + fn list_and_grid_builders_emit_bounded_layout_contract() { + let list = list_bind("$.items"); + assert_eq!(list.kind, "List"); + let grid = grid(2, vec![text_literal("one"), text_literal("two")]); + assert_eq!(grid.kind, "Grid"); + assert_eq!( + grid.props.get("columns"), + Some(&PropValue::Literal(serde_json::json!(2))) + ); + } + + #[test] + fn sparkline_builder_includes_accessible_label() { + let sparkline = sparkline_bind("$.trend", "Usage trend", "info"); + assert_eq!(sparkline.kind, "Sparkline"); + assert_eq!( + sparkline.props.get("label"), + Some(&PropValue::Literal(serde_json::json!("Usage trend"))) + ); + } + + #[test] + fn responsive_builder_includes_static_breakpoint() { + let view = responsive(420.0, vec![text_literal("content")]); + assert_eq!(view.kind, "Responsive"); + assert_eq!( + view.props.get("breakpoint"), + Some(&PropValue::Literal(serde_json::json!(420.0))) + ); + } + + #[test] + fn color_token_builder_uses_named_host_token() { + let view = with_color_token(text_literal("balance"), "accent"); + assert_eq!( + view.props.get("colorToken"), + Some(&PropValue::Literal(serde_json::json!("accent"))) + ); + } +} diff --git a/crates/floatile-shell/src/runtime_ui.rs b/crates/floatile-shell/src/runtime_ui.rs index fc900de..d163917 100644 --- a/crates/floatile-shell/src/runtime_ui.rs +++ b/crates/floatile-shell/src/runtime_ui.rs @@ -19,14 +19,15 @@ use std::path::PathBuf; use std::sync::Arc; use floatile_platform::{PlatformCapabilities, set_always_on_top}; -use floatile_renderer::{BindingSlot, EventSlot, RenderedComponent, render_component}; +use floatile_renderer::{ + BindingSlot, BindingValueType, EventSlot, RenderedComponent, render_component, +}; +use floatile_ui_schema::path::PathSegments; use floatile_ui_schema::{MAX_IR_BYTES, UiDocument, validate_document}; use serde_json::Value; use slint::winit_030::WinitWindowAccessor; use slint_interpreter::{Compiler, ComponentDefinition, ComponentInstance, Value as UiValue}; -use crate::{PluginBinding, resolve_binding_string}; - /// renderer 声明的宿主组件名(单一事实源,随 renderer 命名演进)。 pub const PLUGIN_COMPONENT_NAME: &str = "ClockPluginUI"; @@ -181,14 +182,9 @@ impl RuntimePluginWindow { /// runtime 的权威 State(NFR-SEC-01)。 pub fn project_state(&self, state: &Value) -> Result<(), RuntimeUiError> { for slot in &self.bindings { - let binding = PluginBinding { - path: slot.path.clone(), - prop: slot.prop.clone(), - }; - let text = resolve_binding_string(&binding, state) - .map_err(|e| RuntimeUiError::Projection(format!("{}: {e}", slot.prop)))?; + let value = project_binding_value(slot, state)?.into_ui_value(); self.instance - .set_property(&slot.prop, UiValue::String(text.into())) + .set_property(&slot.prop, value) .map_err(|e| RuntimeUiError::Projection(format!("{}: {e}", slot.prop)))?; } Ok(()) @@ -232,6 +228,107 @@ impl RuntimePluginWindow { } } +#[derive(Debug)] +enum ProjectedValue { + String(String), + Boolean(bool), + Number(f64), + StringList(Vec), + NumberList(Vec), +} + +impl ProjectedValue { + fn into_ui_value(self) -> UiValue { + match self { + Self::String(value) => UiValue::String(value.into()), + Self::Boolean(value) => UiValue::Bool(value), + Self::Number(value) => UiValue::Number(value), + Self::StringList(values) => UiValue::Model(slint::ModelRc::new(slint::VecModel::from( + values + .into_iter() + .map(|value| UiValue::String(value.into())) + .collect::>(), + ))), + Self::NumberList(values) => UiValue::Model(slint::ModelRc::new(slint::VecModel::from( + values.into_iter().map(UiValue::Number).collect::>(), + ))), + } + } +} + +fn project_binding_value( + slot: &BindingSlot, + state: &Value, +) -> Result { + let segments = PathSegments::parse(&slot.path) + .map_err(|error| RuntimeUiError::Projection(format!("{}: {error}", slot.prop)))?; + let mut current = state; + for segment in segments.segments() { + current = current.get(segment).ok_or_else(|| { + RuntimeUiError::Projection(format!("{}: State 字段 `{segment}` 缺失", slot.prop)) + })?; + } + match slot.value_type { + BindingValueType::String => current + .as_str() + .map(|value| ProjectedValue::String(value.to_owned())) + .ok_or_else(|| RuntimeUiError::Projection(format!("{}: 期望 string", slot.prop))), + BindingValueType::Boolean => current + .as_bool() + .map(ProjectedValue::Boolean) + .ok_or_else(|| RuntimeUiError::Projection(format!("{}: 期望 boolean", slot.prop))), + BindingValueType::Number => current + .as_f64() + .map(ProjectedValue::Number) + .ok_or_else(|| RuntimeUiError::Projection(format!("{}: 期望 number", slot.prop))), + BindingValueType::StringList => { + let items = current.as_array().ok_or_else(|| { + RuntimeUiError::Projection(format!("{}: 期望 string array", slot.prop)) + })?; + if items.len() > floatile_ui_schema::MAX_LIST_ITEMS { + return Err(RuntimeUiError::Projection(format!( + "{}: List 项数超过 {}", + slot.prop, + floatile_ui_schema::MAX_LIST_ITEMS + ))); + } + let values = items + .iter() + .map(|item| { + item.as_str().map(str::to_owned).ok_or_else(|| { + RuntimeUiError::Projection(format!("{}: List item 期望 string", slot.prop)) + }) + }) + .collect::, _>>()?; + Ok(ProjectedValue::StringList(values)) + } + BindingValueType::NumberList => { + let items = current.as_array().ok_or_else(|| { + RuntimeUiError::Projection(format!("{}: 期望 number array", slot.prop)) + })?; + if items.len() > floatile_ui_schema::MAX_CHART_POINTS { + return Err(RuntimeUiError::Projection(format!( + "{}: Sparkline 采样点超过 {}", + slot.prop, + floatile_ui_schema::MAX_CHART_POINTS + ))); + } + let values = items + .iter() + .map(|item| { + item.as_f64().ok_or_else(|| { + RuntimeUiError::Projection(format!( + "{}: Sparkline point 期望 number", + slot.prop + )) + }) + }) + .collect::, _>>()?; + Ok(ProjectedValue::NumberList(values)) + } + } +} + /// 把 interpreter 回调参数序列化为 JSON(供 `ui-event.payload-json`)。 /// /// Slint `Value` 大多可直接 JSON 序列化;不能序列化的标量走显式降级,绝不 panic。 @@ -359,11 +456,212 @@ mod tests { assert!(rendered.source.contains(PLUGIN_COMPONENT_NAME)); } + #[test] + fn typed_projection_preserves_boolean_and_number_values() { + let state = serde_json::json!({ + "loading": true, + "percent": 42.5, + "items": ["one", "two"], + "trend": [10.0, 42.5] + }); + let boolean = BindingSlot { + path: "$.loading".into(), + prop: "prop_loading".into(), + value_type: BindingValueType::Boolean, + }; + let number = BindingSlot { + path: "$.percent".into(), + prop: "prop_percent".into(), + value_type: BindingValueType::Number, + }; + let list = BindingSlot { + path: "$.items".into(), + prop: "prop_items".into(), + value_type: BindingValueType::StringList, + }; + let trend = BindingSlot { + path: "$.trend".into(), + prop: "prop_trend".into(), + value_type: BindingValueType::NumberList, + }; + assert!(matches!( + project_binding_value(&boolean, &state).unwrap(), + ProjectedValue::Boolean(true) + )); + assert!(matches!( + project_binding_value(&number, &state).unwrap(), + ProjectedValue::Number(value) if value == 42.5 + )); + assert!(matches!( + project_binding_value(&list, &state).unwrap(), + ProjectedValue::StringList(values) if values == ["one", "two"] + )); + assert!(matches!( + project_binding_value(&list, &state) + .unwrap() + .into_ui_value(), + UiValue::Model(_) + )); + assert!(matches!( + project_binding_value(&trend, &state).unwrap(), + ProjectedValue::NumberList(values) if values == [10.0, 42.5] + )); + } + #[test] fn compile_component_succeeds_without_display() { // ADR-0002 核心断言:纯编译不需要窗口 backend,无头 CI 可直接跑。 let rendered = render_ftui(&ftui_bytes(&clock_ftui())).unwrap(); - let definition = compile_component(&rendered).unwrap(); + let definition = compile_component(&rendered) + .unwrap_or_else(|error| panic!("{error}\n{}", rendered.source)); + assert_eq!(definition.name(), PLUGIN_COMPONENT_NAME); + } + + #[test] + fn compile_typed_page_state_and_metrics_without_display() { + let mut document = clock_ftui(); + document.state.initial = serde_json::json!({ + "time": "ok", + "running": true, + "percent": 42.5, + "items": ["one", "two"], + "trend": [10.0, 42.5] + }); + if let JsonSchema::Object { properties, .. } = &mut document.state.schema { + properties.insert("percent".into(), JsonSchema::Number); + properties.insert( + "items".into(), + JsonSchema::Array { + max_items: Some(16), + items: Box::new(JsonSchema::String { + max_length: Some(64), + }), + }, + ); + properties.insert( + "trend".into(), + JsonSchema::Array { + max_items: Some(16), + items: Box::new(JsonSchema::Number), + }, + ); + } + document.root = Component { + kind: "Column".into(), + children: vec![ + Component { + kind: "If".into(), + when: Some(floatile_ui_schema::ir::Binding::State { + bind: "$.running".into(), + }), + then: Some(Box::new(Component { + kind: "Badge".into(), + props: BTreeMap::from([ + ( + "label".into(), + PropValue::Binding(floatile_ui_schema::ir::Binding::State { + bind: "$.time".into(), + }), + ), + ( + "tone".into(), + PropValue::Literal(serde_json::json!("success")), + ), + ]), + ..Default::default() + })), + ..Default::default() + }, + Component { + kind: "Progress".into(), + props: BTreeMap::from([ + ( + "value".into(), + PropValue::Binding(floatile_ui_schema::ir::Binding::State { + bind: "$.percent".into(), + }), + ), + ( + "accessibilityLabel".into(), + PropValue::Literal(serde_json::json!("Completion")), + ), + ]), + ..Default::default() + }, + Component { + kind: "List".into(), + props: BTreeMap::from([( + "items".into(), + PropValue::Binding(floatile_ui_schema::ir::Binding::State { + bind: "$.items".into(), + }), + )]), + ..Default::default() + }, + Component { + kind: "Grid".into(), + props: BTreeMap::from([( + "columns".into(), + PropValue::Literal(serde_json::json!(2)), + )]), + children: vec![ + Component { + kind: "Text".into(), + props: BTreeMap::from([( + "text".into(), + PropValue::Literal(serde_json::json!("one")), + )]), + ..Default::default() + }, + Component { + kind: "Text".into(), + props: BTreeMap::from([( + "text".into(), + PropValue::Literal(serde_json::json!("two")), + )]), + ..Default::default() + }, + ], + ..Default::default() + }, + Component { + kind: "Sparkline".into(), + props: BTreeMap::from([ + ( + "values".into(), + PropValue::Binding(floatile_ui_schema::ir::Binding::State { + bind: "$.trend".into(), + }), + ), + ( + "label".into(), + PropValue::Literal(serde_json::json!("Usage trend")), + ), + ]), + ..Default::default() + }, + Component { + kind: "Responsive".into(), + props: BTreeMap::from([( + "breakpoint".into(), + PropValue::Literal(serde_json::json!(420)), + )]), + children: vec![Component { + kind: "Text".into(), + props: BTreeMap::from([( + "text".into(), + PropValue::Literal(serde_json::json!("responsive")), + )]), + ..Default::default() + }], + ..Default::default() + }, + ], + ..Default::default() + }; + let rendered = render_ftui(&ftui_bytes(&document)).unwrap(); + let definition = compile_component(&rendered) + .unwrap_or_else(|error| panic!("{error}\n{}", rendered.source)); assert_eq!(definition.name(), PLUGIN_COMPONENT_NAME); } @@ -802,15 +1100,11 @@ pub async fn spawn_runtime_ui_with_https( )); break; }; - // 沿 renderer binding 槽位解析为 (prop, text),在 UI 线程投影。 + // 沿 renderer binding 槽位解析为类型化值,在 UI 线程投影。 let mut projections = Vec::new(); for slot in &bindings { - let binding = PluginBinding { - path: slot.path.clone(), - prop: slot.prop.clone(), - }; - match resolve_binding_string(&binding, &update.state) { - Ok(text) => projections.push((slot.prop.clone(), text)), + match project_binding_value(slot, &update.state) { + Ok(value) => projections.push((slot.prop.clone(), value)), Err(error) => tracing::warn!( seq = update.seq, %error, @@ -823,8 +1117,8 @@ pub async fn spawn_runtime_ui_with_https( } let weak = weak.clone(); if let Err(error) = weak.upgrade_in_event_loop(move |instance| { - for (prop, text) in projections { - let _ = instance.set_property(&prop, UiValue::String(text.into())); + for (prop, value) in projections { + let _ = instance.set_property(&prop, value.into_ui_value()); } }) { tracing::debug!(%error, "event loop delivery failed; stopping bridge"); diff --git a/crates/floatile-ui-schema/src/lib.rs b/crates/floatile-ui-schema/src/lib.rs index 63387e6..df173b9 100644 --- a/crates/floatile-ui-schema/src/lib.rs +++ b/crates/floatile-ui-schema/src/lib.rs @@ -13,6 +13,7 @@ pub mod patch; pub mod path; pub mod registry; pub mod schema; +pub mod theme; pub mod validate; pub use error::UiSchemaError; @@ -23,7 +24,7 @@ pub use schema::{JsonSchema, validate_value}; pub use validate::validate_document; /// 当前受支持的 UI IR 版本(独立于 WIT/manifest/SDK/plugin version)。 -pub const UI_API_VERSION: &str = "1.0.0"; +pub const UI_API_VERSION: &str = "1.6.0"; // ---- P0 初始预算(ui-ir-v1 §10;evil/clock/10-instance 数据后才能冻结)---- @@ -39,3 +40,7 @@ pub const MAX_BINDINGS: usize = 512; pub const MAX_EVENT_DECLS: usize = 128; /// asset 引用数量上限。 pub const MAX_ASSET_REFS: usize = 64; +/// 单个动态 List 的字符串项上限。 +pub const MAX_LIST_ITEMS: usize = 256; +/// 单个 Sparkline 的数值采样点上限。 +pub const MAX_CHART_POINTS: usize = 128; diff --git a/crates/floatile-ui-schema/src/registry.rs b/crates/floatile-ui-schema/src/registry.rs index 03dee8a..e206160 100644 --- a/crates/floatile-ui-schema/src/registry.rs +++ b/crates/floatile-ui-schema/src/registry.rs @@ -57,6 +57,8 @@ pub struct PropSchema { pub types: &'static [JsonType], /// 是否允许 State/Item 绑定(如 `Text.text`、`Toggle.checked`)。 pub allow_binding: bool, + /// 首次引入该 prop 的 UI API 1.x minor。 + pub introduced_minor: u64, pub optional: bool, } @@ -80,6 +82,8 @@ pub enum ComponentKind { #[derive(Debug, Clone)] pub struct ComponentSpec { pub name: &'static str, + /// 首次引入该组件的 UI API 1.x minor。 + pub introduced_minor: u64, pub props: Vec, pub input_events: &'static [&'static str], pub children: ChildrenPolicy, @@ -102,48 +106,56 @@ const COMMON_ELEMENT_PROPS: &[PropSchema] = &[ name: "padding", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "gap", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "width", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "height", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "opacity", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "radius", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "color", types: &[JsonType::String], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "border", types: &[JsonType::String], allow_binding: false, + introduced_minor: 0, optional: true, }, ]; @@ -168,11 +180,26 @@ fn build_registry() -> Vec { name: "columns", types: &[JsonType::Integer], allow_binding: false, + introduced_minor: 0, optional: true, }], &[], ); element(&mut specs, "Scroll", ChildrenPolicy::Many, &[], &[]); + element_since( + &mut specs, + "Responsive", + 4, + ChildrenPolicy::Many, + &[PropSchema { + name: "breakpoint", + types: &[JsonType::Number], + allow_binding: false, + introduced_minor: 4, + optional: false, + }], + &[], + ); element( &mut specs, @@ -183,12 +210,21 @@ fn build_registry() -> Vec { name: "text", types: &[JsonType::String], allow_binding: true, + introduced_minor: 0, optional: false, }, PropSchema { name: "style", types: &[JsonType::String], allow_binding: false, + introduced_minor: 0, + optional: true, + }, + PropSchema { + name: "colorToken", + types: &[JsonType::String], + allow_binding: false, + introduced_minor: 5, optional: true, }, ], @@ -203,12 +239,14 @@ fn build_registry() -> Vec { name: "name", types: &[JsonType::String], allow_binding: true, + introduced_minor: 0, optional: false, }, PropSchema { name: "size", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, ], @@ -223,18 +261,21 @@ fn build_registry() -> Vec { name: "asset", types: &[JsonType::String], allow_binding: false, + introduced_minor: 0, optional: false, }, PropSchema { name: "width", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, PropSchema { name: "height", types: &[JsonType::Number], allow_binding: false, + introduced_minor: 0, optional: true, }, ], @@ -249,6 +290,7 @@ fn build_registry() -> Vec { name: "label", types: &[JsonType::String], allow_binding: true, + introduced_minor: 0, optional: false, }], &["activate"], @@ -257,12 +299,22 @@ fn build_registry() -> Vec { &mut specs, "Toggle", ChildrenPolicy::Forbidden, - &[PropSchema { - name: "checked", - types: &[JsonType::Boolean], - allow_binding: true, - optional: false, - }], + &[ + PropSchema { + name: "checked", + types: &[JsonType::Boolean], + allow_binding: true, + introduced_minor: 0, + optional: false, + }, + PropSchema { + name: "accessibilityLabel", + types: &[JsonType::String], + allow_binding: true, + introduced_minor: 6, + optional: true, + }, + ], &["toggle"], ); @@ -270,31 +322,117 @@ fn build_registry() -> Vec { &mut specs, "Progress", ChildrenPolicy::Forbidden, - &[PropSchema { - name: "value", - types: &[JsonType::Number], - allow_binding: true, - optional: false, - }], + &[ + PropSchema { + name: "value", + types: &[JsonType::Number], + allow_binding: true, + introduced_minor: 0, + optional: false, + }, + PropSchema { + name: "accessibilityLabel", + types: &[JsonType::String], + allow_binding: true, + introduced_minor: 6, + optional: true, + }, + ], + &[], + ); + element_since( + &mut specs, + "Badge", + 1, + ChildrenPolicy::Forbidden, + &[ + PropSchema { + name: "label", + types: &[JsonType::String], + allow_binding: true, + introduced_minor: 0, + optional: false, + }, + PropSchema { + name: "tone", + types: &[JsonType::String], + allow_binding: false, + introduced_minor: 0, + optional: true, + }, + ], &[], ); element( &mut specs, "Gauge", ChildrenPolicy::Forbidden, + &[ + PropSchema { + name: "value", + types: &[JsonType::Number], + allow_binding: true, + introduced_minor: 0, + optional: false, + }, + PropSchema { + name: "accessibilityLabel", + types: &[JsonType::String], + allow_binding: true, + introduced_minor: 6, + optional: true, + }, + ], + &[], + ); + element( + &mut specs, + "List", + ChildrenPolicy::Many, &[PropSchema { - name: "value", - types: &[JsonType::Number], + name: "items", + types: &[JsonType::Array], allow_binding: true, - optional: false, + introduced_minor: 2, + optional: true, }], &[], ); - element(&mut specs, "List", ChildrenPolicy::Many, &[], &[]); + element_since( + &mut specs, + "Sparkline", + 3, + ChildrenPolicy::Forbidden, + &[ + PropSchema { + name: "values", + types: &[JsonType::Array], + allow_binding: true, + introduced_minor: 3, + optional: false, + }, + PropSchema { + name: "label", + types: &[JsonType::String], + allow_binding: true, + introduced_minor: 3, + optional: false, + }, + PropSchema { + name: "tone", + types: &[JsonType::String], + allow_binding: false, + introduced_minor: 3, + optional: true, + }, + ], + &[], + ); // 控制组件(Canvas/Path 在 renderer spike 通过前不启用)。 specs.push(ComponentSpec { name: "If", + introduced_minor: 0, props: Vec::new(), input_events: &[], children: ChildrenPolicy::Forbidden, @@ -302,6 +440,7 @@ fn build_registry() -> Vec { }); specs.push(ComponentSpec { name: "ForEach", + introduced_minor: 0, props: Vec::new(), input_events: &[], children: ChildrenPolicy::Forbidden, @@ -316,12 +455,24 @@ fn element( children: ChildrenPolicy, props: &[PropSchema], events: &'static [&'static str], +) { + element_since(out, name, 0, children, props, events); +} + +fn element_since( + out: &mut Vec, + name: &'static str, + introduced_minor: u64, + children: ChildrenPolicy, + props: &[PropSchema], + events: &'static [&'static str], ) { let mut all = Vec::with_capacity(COMMON_ELEMENT_PROPS.len() + props.len()); all.extend_from_slice(COMMON_ELEMENT_PROPS); all.extend_from_slice(props); out.push(ComponentSpec { name, + introduced_minor, props: all, input_events: events, children, @@ -354,6 +505,85 @@ pub fn validate_literal( expected, }); } + if spec.name == "Badge" + && prop.name == "tone" + && let Some(value) = json.as_str() + && !["neutral", "info", "success", "warning", "danger"].contains(&value) + { + return Err(UiSchemaError::InvalidPropType { + prop: "Badge.tone".to_owned(), + expected: vec!["neutral|info|success|warning|danger".to_owned()], + }); + } + if spec.name == "List" + && prop.name == "items" + && let Some(items) = json.as_array() + && (items.len() > crate::MAX_LIST_ITEMS || items.iter().any(|item| !item.is_string())) + { + return Err(UiSchemaError::InvalidPropType { + prop: "List.items".to_owned(), + expected: vec![format!( + "string array with at most {} items", + crate::MAX_LIST_ITEMS + )], + }); + } + if spec.name == "Sparkline" + && prop.name == "values" + && let Some(items) = json.as_array() + && (items.len() > crate::MAX_CHART_POINTS + || items.iter().any(|item| item.as_f64().is_none())) + { + return Err(UiSchemaError::InvalidPropType { + prop: "Sparkline.values".to_owned(), + expected: vec![format!( + "number array with at most {} points", + crate::MAX_CHART_POINTS + )], + }); + } + if spec.name == "Sparkline" + && prop.name == "tone" + && let Some(value) = json.as_str() + && !["info", "success", "warning", "danger"].contains(&value) + { + return Err(UiSchemaError::InvalidPropType { + prop: "Sparkline.tone".to_owned(), + expected: vec!["info|success|warning|danger".to_owned()], + }); + } + if spec.name == "Grid" + && prop.name == "columns" + && let Some(columns) = json.as_u64() + && !(1..=16).contains(&columns) + { + return Err(UiSchemaError::InvalidPropType { + prop: "Grid.columns".to_owned(), + expected: vec!["integer from 1 through 16".to_owned()], + }); + } + if spec.name == "Responsive" + && prop.name == "breakpoint" + && let Some(breakpoint) = json.as_f64() + && !(240.0..=1920.0).contains(&breakpoint) + { + return Err(UiSchemaError::InvalidPropType { + prop: "Responsive.breakpoint".to_owned(), + expected: vec!["number from 240 through 1920".to_owned()], + }); + } + if prop.name == "colorToken" + && let Some(token) = json.as_str() + && crate::theme::color_token(token).is_none() + { + return Err(UiSchemaError::InvalidPropType { + prop: format!("{}.colorToken", spec.name), + expected: crate::theme::COLOR_TOKENS + .iter() + .map(|token| token.name.to_owned()) + .collect(), + }); + } Ok(()) } @@ -366,7 +596,7 @@ mod tests { fn registry_has_expected_v1_components() { for name in [ "Row", "Column", "Stack", "Grid", "Scroll", "Text", "Icon", "Image", "Button", - "Toggle", "Progress", "Gauge", "List", "If", "ForEach", + "Toggle", "Progress", "Badge", "Gauge", "List", "If", "ForEach", ] { assert!(find(name).is_ok(), "missing component {name}"); } diff --git a/crates/floatile-ui-schema/src/theme.rs b/crates/floatile-ui-schema/src/theme.rs new file mode 100644 index 0000000..95deb98 --- /dev/null +++ b/crates/floatile-ui-schema/src/theme.rs @@ -0,0 +1,54 @@ +//! UI theme token registry(guest-safe 单一语义源)。 + +/// P0 固定主题 token;值由宿主 renderer 消费,插件只持有稳定名称。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ThemeColorToken { + pub name: &'static str, + pub value: &'static str, +} + +pub const COLOR_TOKENS: &[ThemeColorToken] = &[ + ThemeColorToken { + name: "foreground", + value: "#cdd6f4", + }, + ThemeColorToken { + name: "muted", + value: "#9399b2", + }, + ThemeColorToken { + name: "accent", + value: "#89b4fa", + }, + ThemeColorToken { + name: "positive", + value: "#a6e3a1", + }, + ThemeColorToken { + name: "warning", + value: "#f9e2af", + }, + ThemeColorToken { + name: "danger", + value: "#f38ba8", + }, +]; + +pub fn color_token(name: &str) -> Option<&'static ThemeColorToken> { + COLOR_TOKENS.iter().find(|token| token.name == name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_names_and_values_are_bounded_literals() { + for token in COLOR_TOKENS { + assert!(!token.name.is_empty()); + assert_eq!(token.value.len(), 7); + assert!(token.value.starts_with('#')); + assert!(token.value[1..].chars().all(|ch| ch.is_ascii_hexdigit())); + } + } +} diff --git a/crates/floatile-ui-schema/src/validate.rs b/crates/floatile-ui-schema/src/validate.rs index 52618d1..cd84991 100644 --- a/crates/floatile-ui-schema/src/validate.rs +++ b/crates/floatile-ui-schema/src/validate.rs @@ -17,7 +17,7 @@ use crate::{ /// 校验一个完整的 `widget.ftui` 文档。 pub fn validate_document(doc: &UiDocument) -> Result<(), UiSchemaError> { - check_api_version(&doc.ui_api_version)?; + let ui_minor = check_api_version(&doc.ui_api_version)?; check_ir_size(doc)?; if doc.events.len() > MAX_EVENT_DECLS { @@ -40,17 +40,22 @@ pub fn validate_document(doc: &UiDocument) -> Result<(), UiSchemaError> { nodes: 0, bindings: 0, asset_refs: 0, + ui_minor, }; validate_component(&doc.root, &doc.state.schema, None, &mut ctx, 1) } /// 校验 uiApiVersion:只接受 major 1(`1` 或 `1.x.y`)。 -fn check_api_version(version: &str) -> Result<(), UiSchemaError> { - let major = version.split('.').next().unwrap_or(""); - if major == "1" { - Ok(()) - } else { - Err(UiSchemaError::UnsupportedApiVersion(version.to_owned())) +fn check_api_version(version: &str) -> Result { + let mut parts = version.split('.'); + if parts.next() != Some("1") { + return Err(UiSchemaError::UnsupportedApiVersion(version.to_owned())); + } + match parts.next() { + None => Ok(0), + Some(minor) => minor + .parse::() + .map_err(|_| UiSchemaError::UnsupportedApiVersion(version.to_owned())), } } @@ -100,6 +105,7 @@ struct Ctx<'a> { nodes: usize, bindings: usize, asset_refs: usize, + ui_minor: u64, } fn validate_component( @@ -122,6 +128,12 @@ fn validate_component( ))); } let spec = registry::find(&comp.kind)?; + if spec.introduced_minor > ctx.ui_minor { + return Err(UiSchemaError::UnsupportedApiVersion(format!( + "{} requires 1.{}.0", + comp.kind, spec.introduced_minor + ))); + } match spec.kind { ComponentKind::If => validate_if(comp, state_schema, ctx, depth), ComponentKind::ForEach => validate_foreach(comp, state_schema, ctx, depth), @@ -160,6 +172,12 @@ fn validate_element( component: comp.kind.clone(), prop: name.clone(), })?; + if prop.introduced_minor > ctx.ui_minor { + return Err(UiSchemaError::UnsupportedApiVersion(format!( + "{}.{} requires 1.{}.0", + comp.kind, name, prop.introduced_minor + ))); + } match value { PropValue::Binding(binding) => { if !prop.allow_binding { @@ -190,8 +208,28 @@ fn validate_element( }); } } + if ctx.ui_minor >= 6 + && matches!(comp.kind.as_str(), "Toggle" | "Progress" | "Gauge") + && !comp.props.contains_key("accessibilityLabel") + { + return Err(UiSchemaError::MissingProp { + component: comp.kind.clone(), + prop: "accessibilityLabel".to_owned(), + }); + } + if comp.props.contains_key("color") && comp.props.contains_key("colorToken") { + return Err(UiSchemaError::InvalidPropType { + prop: format!("{}.color", comp.kind), + expected: vec!["color or colorToken, not both".to_owned()], + }); + } // 子组件策略。 + if comp.kind == "List" && comp.props.contains_key("items") && !comp.children.is_empty() { + return Err(UiSchemaError::InvalidChildren( + "List 使用 items 时不能同时声明静态 children".to_owned(), + )); + } match spec.children { ChildrenPolicy::Forbidden => { if !comp.children.is_empty() { @@ -258,10 +296,10 @@ fn validate_binding( component: &str, prop_name: &str, ) -> Result<(), UiSchemaError> { - let target_type = match binding { + let target_schema = match binding { Binding::State { bind } => { let segs = path::PathSegments::parse(bind)?; - path::json_type(path::resolve(state_schema, segs.segments())?).to_owned() + path::resolve(state_schema, segs.segments())? } Binding::Item { item } => { let item_schema = item_schema.ok_or_else(|| { @@ -270,13 +308,44 @@ fn validate_binding( )) })?; if item == "value" { - path::json_type(item_schema).to_owned() + item_schema } else { let segs = path::PathSegments::parse(&format!("$.{item}"))?; - path::json_type(path::resolve(item_schema, segs.segments())?).to_owned() + path::resolve(item_schema, segs.segments())? } } }; + if component == "List" && prop_name == "items" { + match target_schema { + JsonSchema::Array { + max_items: Some(max_items), + items, + } if *max_items <= crate::MAX_LIST_ITEMS + && matches!(items.as_ref(), JsonSchema::String { .. }) => {} + _ => { + return Err(UiSchemaError::BindingTypeMismatch(format!( + "List.items 必须绑定 maxItems <= {} 的 string array", + crate::MAX_LIST_ITEMS + ))); + } + } + } + if component == "Sparkline" && prop_name == "values" { + match target_schema { + JsonSchema::Array { + max_items: Some(max_items), + items, + } if *max_items <= crate::MAX_CHART_POINTS + && matches!(items.as_ref(), JsonSchema::Number | JsonSchema::Integer) => {} + _ => { + return Err(UiSchemaError::BindingTypeMismatch(format!( + "Sparkline.values 必须绑定 maxItems <= {} 的 number array", + crate::MAX_CHART_POINTS + ))); + } + } + } + let target_type = path::json_type(target_schema).to_owned(); let allowed = prop.types.iter().any(|t| { t.name() == target_type || (matches!(t, JsonType::Number) && target_type == "integer") }); @@ -410,7 +479,7 @@ mod tests { fn valid_doc() -> UiDocument { UiDocument { - ui_api_version: "1.0.0".into(), + ui_api_version: crate::UI_API_VERSION.into(), state: StateSchema { initial: json!({"time": "--:--:--", "running": false, "zones": []}), schema: clock_schema(), @@ -734,11 +803,206 @@ mod tests { )); } + #[test] + fn contract_vector_component_minor_gate() { + let badge = Component { + kind: "Badge".into(), + props: BTreeMap::from([("label".into(), PropValue::Literal(json!("ok")))]), + ..Default::default() + }; + let mut old = with_single(badge.clone()); + old.ui_api_version = "1.0.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + let mut current = with_single(badge); + current.ui_api_version = "1.1.0".into(); + assert!(validate_document(¤t).is_ok()); + } + + #[test] + fn contract_vector_list_items_minor_and_budget_gate() { + let list = Component { + kind: "List".into(), + props: BTreeMap::from([( + "items".into(), + PropValue::Binding(Binding::State { + bind: "$.zones".into(), + }), + )]), + ..Default::default() + }; + let mut old = with_single(list.clone()); + old.ui_api_version = "1.1.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + let current = with_single(list.clone()); + assert!(validate_document(¤t).is_ok()); + + let mut unbounded = with_single(list); + if let JsonSchema::Object { properties, .. } = &mut unbounded.state.schema { + properties.insert( + "zones".into(), + JsonSchema::Array { + max_items: None, + items: Box::new(JsonSchema::String { + max_length: Some(64), + }), + }, + ); + } + assert!(matches!( + validate_document(&unbounded), + Err(UiSchemaError::BindingTypeMismatch(_)) + )); + } + + #[test] + fn contract_vector_sparkline_requires_bounded_numbers_and_label() { + let sparkline = Component { + kind: "Sparkline".into(), + props: BTreeMap::from([ + ( + "values".into(), + PropValue::Binding(Binding::State { + bind: "$.trend".into(), + }), + ), + ("label".into(), PropValue::Literal(json!("Usage trend"))), + ]), + ..Default::default() + }; + let mut current = with_single(sparkline.clone()); + if let JsonSchema::Object { properties, .. } = &mut current.state.schema { + properties.insert( + "trend".into(), + JsonSchema::Array { + max_items: Some(16), + items: Box::new(JsonSchema::Number), + }, + ); + } + current.state.initial["trend"] = json!([]); + assert!(validate_document(¤t).is_ok()); + + let mut old = current.clone(); + old.ui_api_version = "1.2.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + + let mut missing_label = current; + missing_label.root.children[0].props.remove("label"); + assert!(matches!( + validate_document(&missing_label), + Err(UiSchemaError::MissingProp { .. }) + )); + } + + #[test] + fn contract_vector_responsive_minor_and_breakpoint_gate() { + let responsive = Component { + kind: "Responsive".into(), + props: BTreeMap::from([("breakpoint".into(), PropValue::Literal(json!(420)))]), + children: vec![text(PropValue::Literal(json!("content")))], + ..Default::default() + }; + assert!(validate_document(&with_single(responsive.clone())).is_ok()); + + let mut old = with_single(responsive.clone()); + old.ui_api_version = "1.3.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + + let mut invalid = with_single(responsive); + invalid.root.children[0] + .props + .insert("breakpoint".into(), PropValue::Literal(json!(120))); + assert!(matches!( + validate_document(&invalid), + Err(UiSchemaError::InvalidPropType { .. }) + )); + } + + #[test] + fn contract_vector_theme_token_minor_and_name_gate() { + let themed = text(PropValue::Literal(json!("balance"))); + let mut current = with_single(themed.clone()); + current.root.children[0] + .props + .insert("colorToken".into(), PropValue::Literal(json!("accent"))); + assert!(validate_document(¤t).is_ok()); + + let mut old = current.clone(); + old.ui_api_version = "1.4.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + + current.root.children[0] + .props + .insert("colorToken".into(), PropValue::Literal(json!("plugin-css"))); + assert!(matches!( + validate_document(¤t), + Err(UiSchemaError::InvalidPropType { .. }) + )); + } + + #[test] + fn contract_vector_control_accessibility_label_minor_gate() { + for kind in ["Toggle", "Progress", "Gauge"] { + let value_prop = if kind == "Toggle" { "checked" } else { "value" }; + let value = if kind == "Toggle" { + json!(true) + } else { + json!(42) + }; + let control = Component { + kind: kind.into(), + props: BTreeMap::from([ + (value_prop.into(), PropValue::Literal(value)), + ( + "accessibilityLabel".into(), + PropValue::Literal(json!(format!("{kind} status"))), + ), + ]), + ..Default::default() + }; + assert!(validate_document(&with_single(control.clone())).is_ok()); + + let mut old = with_single(control.clone()); + old.ui_api_version = "1.5.0".into(); + assert!(matches!( + validate_document(&old), + Err(UiSchemaError::UnsupportedApiVersion(_)) + )); + + let mut legacy = with_single(control.clone()); + legacy.ui_api_version = "1.5.0".into(); + legacy.root.children[0].props.remove("accessibilityLabel"); + assert!(validate_document(&legacy).is_ok()); + + let mut missing = with_single(control); + missing.root.children[0].props.remove("accessibilityLabel"); + assert!(matches!( + validate_document(&missing), + Err(UiSchemaError::MissingProp { prop, .. }) if prop == "accessibilityLabel" + )); + } + } + #[test] fn contract_vector_positive_components() { // 正例:registry 元素组件结构合法。 for kind in [ - "Text", "Button", "Toggle", "Progress", "Gauge", "Icon", "Image", + "Text", "Button", "Toggle", "Progress", "Badge", "Gauge", "Icon", "Image", ] { let root = Component { kind: kind.into(), diff --git a/docs/plugin-sdk/manifest-v1.md b/docs/plugin-sdk/manifest-v1.md index 29496fa..a977a14 100644 --- a/docs/plugin-sdk/manifest-v1.md +++ b/docs/plugin-sdk/manifest-v1.md @@ -38,7 +38,7 @@ manifest 是安装与运行时的显式事实,不是开发者主要编辑界 "name": "Floatile Labs" }, "engineApiVersion": "1.2.0", - "uiApiVersion": "1.0.0", + "uiApiVersion": "1.6.0", "type": "widget", "entrypoints": { "ui": "ui/widget.ftui", diff --git a/docs/plugin-sdk/sdk-developer-experience.md b/docs/plugin-sdk/sdk-developer-experience.md index 5e4e31a..d34be93 100644 --- a/docs/plugin-sdk/sdk-developer-experience.md +++ b/docs/plugin-sdk/sdk-developer-experience.md @@ -145,14 +145,21 @@ P0 首批组件限定为: | 布局 | `Row`、`Column`、`Stack`、`Grid`、`Scroll` | | 内容 | `Text`、`Icon`、受限 `Image` | | 交互 | `Button`、`Toggle` | -| 数据 | `Progress`、`Gauge`、`List` | +| 数据 | `Badge`、`Progress`、`Gauge`、`List` | | 控制 | `If`、`ForEach`、State binding、event | | 样式 | spacing、size、color token、border、radius、opacity | | 动画 | 有限的 enter/exit/value transition | | 扩展 | 受预算约束的 `Canvas`/`Path`(可在 P0 后半加入) | 组件属性由机器可读 schema 定义,Rust/TypeScript 类型和文档从同一源生成。P0 不加入 TextInput、 -富文本、WebView、地图、视频、自定义字体和任意 SVG;出现真实需求后单独评审。 +UI API 1.1 提供 `page_state` 组合 loading/error/empty/content,并为 `Badge`、`Progress` 提供 Rust +builder;boolean/number State 通过类型化 binding slot 投影,不退化为字符串。UI API 1.2 提供 +`grid`、`list`、`list_bind`,动态列表只接受具有显式项数预算的字符串数组;UI API 1.3 增加 +`sparkline_bind`,用有界数值数组和必填可访问标签表达监控趋势;UI API 1.4 增加 `responsive`,按 +宿主窗口逻辑宽度在纵向与横向布局间切换;UI API 1.5 增加 `with_color_token`,插件只能选择 +宿主命名 palette;UI API 1.6 要求 `Toggle`、`Progress`、`Gauge` 提供无障碍标签,并提供 +`progress_bind_labeled` builder。富文本、WebView、地图、 +视频、自定义字体和任意 SVG;出现真实需求后单独评审。 ## 5. Context API diff --git a/docs/plugin-sdk/ui-ir-v1.md b/docs/plugin-sdk/ui-ir-v1.md index 990815a..79e9a5d 100644 --- a/docs/plugin-sdk/ui-ir-v1.md +++ b/docs/plugin-sdk/ui-ir-v1.md @@ -2,7 +2,7 @@ > 状态:Proposed(renderer spike、schema 实现和正反例通过后冻结) > 文件:`ui/widget.ftui` -> 版本:`uiApiVersion = 1.0.0` +> 版本:`uiApiVersion = 1.6.0` > 关联:ADR-0001、FR-PLUGIN-01、F11 `floatile-ui-schema` 已实现 IR 类型、组件 registry v1、State/Event JSON Schema 校验、JSONPath 绑定 @@ -27,7 +27,7 @@ P0 可以使用 canonical JSON 编码,后续可换二进制编码,但 v1 语 ```json { - "uiApiVersion": "1.0.0", + "uiApiVersion": "1.6.0", "state": { "initial": { "time": "--:--:--", @@ -161,7 +161,7 @@ P0 candidate: Layout: Row Column Stack Grid Scroll Content: Text Icon Image Interaction: Button Toggle -Data: Progress Gauge List +Data: Badge Progress Gauge List Control: If ForEach Extension: Canvas Path(通过 renderer spike 后再启用) ``` @@ -245,7 +245,7 @@ P0 比较: - 输出是纯文本:所有字符串字面量经结构化转义,组件名/属性名/回调名由 renderer 生成, 插件不能定义标识符,杜绝把 IR 原始文本拼进 Slint 语法位置。 - 组件映射(v1 子集):Column→`VerticalLayout`、Row→`HorizontalLayout`、Stack/Grid→布局容器; - Text/Button/Toggle/Progress/Gauge→宿主基础元素;If→`if` 结构、ForEach→`for` 循环(模板内 item + Text/Button/Toggle/Badge/Progress/Gauge→宿主基础元素;If→`if` 结构、ForEach→`for` 循环(模板内 item 绑定进入独立命名空间)。公共样式 prop(padding/gap/color/opacity 等)映射为受限 Slint 属性。 Canvas/Path 等未映射组件稳定拒绝(`RNDR_UNSUPPORTED_COMPONENT`)。 - 输出 `component ClockPluginUI`(非 Window 内容组件,遵循 renderer 中立)+ binding/event 槽位: @@ -254,6 +254,65 @@ P0 比较: - 恶意 IR(超节点/深度/绑定、未知组件、病态字面量)在 renderer 层拒绝并以固定码 (`RNDR_*`)返回,不泄漏宿主内部。 +### 12.2 UI API 1.1 状态与指标切片 + +- renderer binding slot 携带 `string`、`boolean` 或 `number` 类型;shell 必须按槽位类型投影权威 + State,不得把 boolean/number 转成自由文本后交给 Slint 猜测。 +- `Badge` 使用宿主语义 tone:`neutral`、`info`、`success`、`warning`、`danger`;插件不得提供颜色 + 源码。未知 tone 在 schema/CLI/runtime 复验阶段拒绝。 +- `Progress.value` 是 0..100 的 number 语义;renderer 将数值映射为百分比长度,插件不能注入长度 + 表达式。 +- Rust SDK 的 `page_state` 用嵌套 `If` 组合 loading/error/empty/content,固定优先级为 + loading → error → empty → content;三个判定路径都必须绑定 boolean State。 + +### 12.3 UI API 1.2 集合布局切片 + +- `List.items` 可以绑定具有显式 `maxItems <= 256` 的 string array State;renderer 生成受控 Slint + model,shell worker 只跨线程传递 `Vec`,并在 UI 线程构造 model。 +- `List` 的动态 `items` 与静态 `children` 互斥,避免重复扩张节点;字面量 items 同样执行项数与类型 + 校验。 +- `Grid.columns` 是 1..=16 的静态布局提示;Rust SDK 提供 `grid`、`list` 和 `list_bind` builder。 + +### 12.4 UI API 1.3 监控图表切片 + +- `Sparkline.values` 接受 literal 或 State 绑定的 number array;动态 schema 必须声明 + `maxItems <= 128`,运行时投影仍复验类型与数量。 +- 每个点按 `0..=100` 归一化显示,越界值只在展示层 clamp,不修改权威 State。 +- `Sparkline.label` 是必填替代文本并映射到 Slint accessibility tree;纯视觉图表不得省略标签。 +- `tone` 只接受 `info|success|warning|danger`,由宿主映射固定主题色,不接受插件绘图源码、CSS、 + shader 或任意颜色表达式。 +- Rust SDK 提供 `sparkline_bind` builder;AI Balance 参考插件用该组件表达余额利用率趋势。 + +### 12.5 UI API 1.4 响应式布局切片 + +- `Responsive.breakpoint` 是 `240..=1920` 的静态逻辑像素阈值;低于阈值时 children 使用纵向布局, + 否则使用横向布局。 +- 窗口宽度只由宿主 renderer 的 `root.width` 消费,不进入 guest State,也不向插件暴露原生窗口句柄、 + 显示器或平台 API。 +- compact/wide 两个 Slint 分支互斥并复用同一受验证子树;binding/event 槽位去重,运行时最坏节点数 + 仍按单个 children 子树计入预算。 +- Rust SDK 提供 `responsive` builder;AI Balance 参考插件在窄窗口与宽窗口间切换监控内容排列。 + +### 12.6 UI API 1.5 宿主主题 token 切片 + +- `Text.colorToken` 只接受 UI schema registry 中的命名 token:`foreground`、`muted`、`accent`、 + `positive`、`warning`、`danger`;名称与受限颜色值由 guest-safe 单一源定义。 +- `colorToken` 与自定义 `color` 互斥;未知 token、旧 minor 和同时声明两者都在 renderer 前拒绝。 +- renderer 把 token 解析为宿主拥有的颜色字面量,生成的 Slint 不包含插件 token 原文,更不接受 CSS、 + selector、shader 或 Slint 表达式。 +- P0 使用固定宿主 palette;随系统主题动态切换仍未实现,不得把固定 token 支持描述为动态主题完成。 +- Rust SDK 提供 `with_color_token`;AI Balance 用 `accent` 表达余额主指标。 + +### 12.7 UI API 1.6 控件无障碍语义切片 + +- `Toggle`、`Progress`、`Gauge` 在 1.6 文档中必须声明 `accessibilityLabel`;标签可以是受类型校验的 + string literal 或 State/item binding,不能注入平台无障碍 API。 +- renderer 将 `Toggle` 映射为 `switch` role 与 checked state,将 `Progress`/`Gauge` 映射为 + `progress-indicator` role、0..100 value range;`Button.label` 同时作为可见文本和无障碍名称。 +- 1.0–1.5 文档不追溯要求新属性,renderer 为旧控件保留组件名 fallback;1.6 起缺失标签在渲染前拒绝。 +- Rust SDK 的 `progress_bind_labeled` 提供显式上下文标签,兼容的 `progress_bind` 使用通用 fallback; + AI Balance 参考插件使用显式标签。 + ## 13. Contract tests - canonical valid clock/system-monitor/countdown fixtures; diff --git a/docs/product/plugin-platform-roadmap.md b/docs/product/plugin-platform-roadmap.md index d2d001a..2711105 100644 --- a/docs/product/plugin-platform-roadmap.md +++ b/docs/product/plugin-platform-roadmap.md @@ -172,7 +172,7 @@ exit code。生成项目必须只依赖可获得的 SDK,并能从干净目录 | PP-M3 | Capability Registry 单源 | 已完成(自动化契约验证) | 统一 capability 元数据,生成/校验 manifest、Broker、SDK 映射与 contract vectors | 注册表/WIT/manifest/CLI/Broker 动态覆盖测试;恶意插件和配额测试证明默认拒绝 | `core`、`services`、plugin API、SDK、CLI | | PP-M4 | Rust 作者闭环 | 已完成(自动化契约与 Xvfb 验证;公开发布受许可门阻断) | 可发布方式待许可决定的 SDK 解析、生成模板修复、dev/test/preview/build/install/run/inspect | 干净目录中的示例插件无需仓库私有路径即可完成全流程;JSON 契约有测试 | SDK、CLI、runtime、shell、docs | | PP-M5 | 外部数据平台 | 已完成(自动化契约验证) | Connection、Credential Vault、HTTPS Broker、调度、缓存、重试、限流和连接健康状态 | AI 余额参考插件只使用通用能力,且 secret 不进入 guest、日志、State 或包 | `core`、`store`、`services`、shell、WIT、SDK | -| PP-M6 | UI 平台 | 规划中 | loading/empty/error、列表/网格、badge、progress、sparkline/chart、主题与响应式布局 | 参考插件无需第三方 Slint/HTML 即可表达监控型 UI;预算和无障碍语义有契约 | UI schema、renderer、SDK、shell | +| PP-M6 | UI 平台 | 已完成(自动化契约验证) | loading/empty/error、列表/网格、badge、progress、sparkline/chart、主题与响应式布局 | 参考插件无需第三方 Slint/HTML 即可表达监控型 UI;预算和无障碍语义有契约 | UI schema、renderer、SDK、shell | | PP-M7 | SDK 与语言生态 | 规划中 | Rust API 稳定化;在工具链可行后接入 TypeScript;生成文档、迁移指南和 conformance kit | 双语言通过相同 contract vectors、恶意输入和端到端示例;不存在宿主语义分叉 | SDK、plugin API、CLI、CI | | PP-M8 | 分发与信任 | 规划中 | publisher/signing、来源与信任、权限 diff、兼容性解析、更新/回滚和可恢复安装 | 安装与升级能解释权限变化和失败原因;篡改/降级/回滚路径有测试 | CLI、core、store、shell、distribution | | PP-M9 | 组合与自动化 | 规划中 | 宿主事件、定时/系统触发、受控 pub/sub、工作流和通知 | 插件间不直接持有句柄;事件有 schema、scope、背压、循环检测和审计 | core、runtime、services、WIT、SDK | @@ -180,7 +180,7 @@ exit code。生成项目必须只依赖可获得的 SDK,并能从干净目录 ### 7.1 当前基线与最近顺序 -截至 2026-08-27,仓库已具备统一 UI IR、WIT 形状、Wasmtime actor、基础 capability 类型与 Broker、 +截至 2026-08-28,仓库已具备统一 UI IR、WIT 形状、Wasmtime actor、基础 capability 类型与 Broker、 部分宿主服务、Rust SDK、包校验/安装和第三方运行时窗口等基础。PP-M1 已打通自动化的 持久多实例生命周期:`floatile instance` 提供创建、枚举、读取、配置、启停和删除; CLI 与 shell 共用安装目录 digest/身份/Config schema 复验;shell 后台监督器在不阻塞 Slint @@ -213,6 +213,11 @@ Config Schema 表单、observed 状态和手动 retry;Linux X11/Xvfb 已自动 runtime。包扫描、host/guest 契约、Broker 恶意路径及全 workspace 门禁证明 secret 不进入 guest、日志、 State 或包。平台 Keyring、完整连接管理产品入口和真实 provider 人工网络证据属于后续增强与环境证据, 不改变 PP-M5 通用能力退出门的完成状态; +- PP-M6 已通过 UI API 1.1–1.6 交付状态页组合、有界列表/网格、badge/progress、受预算约束的 + sparkline、响应式容器、宿主主题 token 与控件无障碍语义。AI Balance 的真实包验收会读取并复验 + `widget.ftui`,证明参考插件覆盖上述监控 UI 契约且包内不含第三方 `.slint`/HTML;schema、renderer、 + SDK 与 shell 的契约/真实 Slint 无头编译测试均通过。真实屏幕阅读器行为、跨平台视觉与完整无障碍仍属 + PP-M10 环境验收,不把它们误记为 PP-M6 自动化契约证据; - TypeScript runtime 的 ADR-0003 spike 结论是 no-go,不能把语言目标标记为完成; - 设置、连接管理、权限解释和开发诊断还没有完整产品入口。 diff --git a/plugins/ai-balance-wasm/src/lib.rs b/plugins/ai-balance-wasm/src/lib.rs index fdabaa2..4bd94f5 100644 --- a/plugins/ai-balance-wasm/src/lib.rs +++ b/plugins/ai-balance-wasm/src/lib.rs @@ -14,6 +14,12 @@ const CONNECTION_ID: u64 = 1; pub struct BalanceState { pub balance: String, pub status: String, + pub utilization: f64, + pub loading: bool, + pub error: bool, + pub empty: bool, + pub entries: Vec, + pub trend: Vec, } #[derive(Debug)] @@ -44,10 +50,12 @@ impl AiBalance { fn refresh(&self, ctx: &mut Context) { match ctx.http().submit("balance", CONNECTION_ID, &[]) { Ok(_) => { - let _ = ctx.state().update(r#"{"status":"loading"}"#); + let _ = ctx + .state() + .update(r#"{"status":"loading","loading":true,"error":false,"empty":false}"#); } Err(_) => { - let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + mark_error(ctx, "unavailable"); } } let _ = ctx.timer().schedule(60_000); @@ -59,10 +67,29 @@ impl Widget for AiBalance { type Event = BalanceEvent; fn view(_state: &Self::State) -> View { - view::column(vec![ - view::text_bind("$.balance"), - view::text_bind("$.status"), - ]) + view::page_state( + "$.loading", + "$.error", + "$.empty", + view::text_literal("Loading balance…"), + view::column(vec![ + view::badge_bind("$.status", "danger"), + view::text_literal("Balance is temporarily unavailable"), + ]), + view::text_literal("No balance data yet"), + view::responsive( + 420.0, + vec![ + view::column(vec![ + view::with_color_token(view::text_bind("$.balance"), "accent"), + view::badge_bind("$.status", "success"), + view::progress_bind_labeled("$.utilization", "Balance utilization"), + view::sparkline_bind("$.trend", "Recent balance utilization", "info"), + ]), + view::list_bind("$.entries"), + ], + ), + ) } fn start(&mut self, ctx: &mut Context) { @@ -76,12 +103,12 @@ impl Widget for AiBalance { match ctx.http().take_result(id) { Ok(response) => update_balance(ctx, response), Err(_) => { - let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + mark_error(ctx, "unavailable"); } } } BalanceEvent::Completed(_, _) => { - let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + mark_error(ctx, "unavailable"); } } } @@ -90,22 +117,46 @@ impl Widget for AiBalance { } fn update_balance(ctx: &mut Context, response: host_http::HttpResponse) { + if response.status == 204 { + let _ = ctx + .state() + .update(r#"{"status":"empty","loading":false,"error":false,"empty":true}"#); + return; + } let parsed = serde_json::from_slice::(&response.body); let balance = parsed .ok() .and_then(|value| value.get("balance").cloned()) - .map(|value| value.to_string()); + .and_then(|value| value.as_f64()); match balance { Some(balance) => { - let patch = serde_json::json!({ "balance": balance, "status": "ok" }); + let utilization = balance.clamp(0.0, 100.0); + let patch = serde_json::json!({ + "balance": format!("{balance:.2}"), + "status": "ok", + "utilization": utilization, + "loading": false, + "error": false, + "empty": false, + "entries": [format!("Current balance: {balance:.2}")], + "trend": [utilization * 0.8, utilization * 0.9, utilization] + }); let _ = ctx.state().update(&patch.to_string()); } - None => { - let _ = ctx.state().update(r#"{"status":"invalid-response"}"#); - } + None => mark_error(ctx, "invalid-response"), } } +fn mark_error(ctx: &mut Context, status: &str) { + let patch = serde_json::json!({ + "status": status, + "loading": false, + "error": true, + "empty": false + }); + let _ = ctx.state().update(&patch.to_string()); +} + #[cfg(target_arch = "wasm32")] impl_export_widget!(AiBalance);