use std::sync::Arc;
use serde_json::{json, Value};
use crate::components::{
Button, Column, Component, Grid, IntoBox, Layout, Panel, Row, Tabs, WithLayout,
};
use crate::context::Context;
use crate::events::{EventName, WireEvent};
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ThemeMode {
Dark,
Light,
#[default]
System,
}
#[derive(Clone, Debug)]
pub struct Theme {
pub mode: ThemeMode,
pub primary: Option<String>,
pub radius: Option<String>,
pub font: Option<String>,
pub toggle: bool,
}
impl Default for Theme {
fn default() -> Self {
Self {
mode: ThemeMode::System,
primary: None,
radius: None,
font: None,
toggle: true,
}
}
}
impl Theme {
pub fn dark() -> Self {
Self {
mode: ThemeMode::Dark,
..Default::default()
}
}
pub fn light() -> Self {
Self {
mode: ThemeMode::Light,
..Default::default()
}
}
pub fn system() -> Self {
Self {
mode: ThemeMode::System,
..Default::default()
}
}
pub fn tokyo_night() -> Self {
Self {
mode: ThemeMode::Dark,
primary: Some("#7aa2f7".into()),
radius: Some("10px".into()),
font: Some("Inter, system-ui, sans-serif".into()),
toggle: true,
}
}
pub fn nord() -> Self {
Self {
mode: ThemeMode::Dark,
primary: Some("#88c0d0".into()),
radius: Some("8px".into()),
font: Some("Inter, system-ui, sans-serif".into()),
toggle: true,
}
}
pub fn cyberpunk() -> Self {
Self {
mode: ThemeMode::Dark,
primary: Some("#f43f5e".into()),
radius: Some("4px".into()),
font: Some("JetBrains Mono, Fira Code, monospace".into()),
toggle: true,
}
}
pub fn catppuccin_mocha() -> Self {
Self {
mode: ThemeMode::Dark,
primary: Some("#cba6f7".into()),
radius: Some("12px".into()),
font: Some("Inter, system-ui, sans-serif".into()),
toggle: true,
}
}
pub fn corporate() -> Self {
Self {
mode: ThemeMode::Light,
primary: Some("#2563eb".into()),
radius: Some("6px".into()),
font: Some("Roboto, Inter, system-ui, sans-serif".into()),
toggle: true,
}
}
pub fn primary(mut self, p: impl Into<String>) -> Self {
self.primary = Some(p.into());
self
}
pub fn radius(mut self, r: impl Into<String>) -> Self {
self.radius = Some(r.into());
self
}
pub fn font(mut self, f: impl Into<String>) -> Self {
self.font = Some(f.into());
self
}
pub fn toggle(mut self, enabled: bool) -> Self {
self.toggle = enabled;
self
}
}
pub type HandlerFn = Arc<dyn Fn(&mut Context) -> Result<()> + Send + Sync>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunCond {
Always,
Success,
Failure,
}
pub struct Sibling {
pub on: RunCond,
pub f: HandlerFn,
}
pub struct HandlerDef {
pub event: EventName,
pub component: Option<String>,
pub f: HandlerFn,
pub inputs: Option<Vec<String>>,
pub outputs: Option<Vec<String>>,
pub chain: Vec<Sibling>,
}
#[derive(Clone, Debug)]
pub struct PageDef {
pub route: String,
pub title: String,
pub icon: Option<String>,
pub id: String,
pub required_role: Option<String>,
}
pub struct App {
pub title: String,
pub subtitle: String,
pub root: Column,
pub pages: Vec<PageDef>,
pub handlers: Vec<HandlerDef>,
pub live: bool,
pub run_label: String,
pub run_button: Option<String>,
pub verbose: bool,
pub api_key: Option<String>,
pub allow_cors: bool,
pub enable_docs: bool,
pub isolated_sessions: bool,
pub theme: Theme,
pub max_width: Option<u32>,
pub mcp_tools: Vec<crate::mcp::McpTool>,
pub enable_mcp: bool,
pub wasm_registry: std::sync::Arc<crate::wasm::WasmRegistry>,
pub auth_config: crate::auth::AuthConfig,
}
pub struct PageBuilder {
pub(crate) id: String,
pub(crate) icon: Option<String>,
pub(crate) children: Vec<Box<dyn Component>>,
pub(crate) gap: f64,
pub(crate) required_role: Option<String>,
}
impl PageBuilder {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
icon: None,
children: Vec::new(),
gap: 16.0,
required_role: None,
}
}
pub fn icon(&mut self, icon: impl Into<String>) -> &mut Self {
self.icon = Some(icon.into());
self
}
pub fn require_role(&mut self, role: impl Into<String>) -> &mut Self {
self.required_role = Some(role.into());
self
}
pub fn gap(&mut self, g: f64) -> &mut Self {
self.gap = g;
self
}
pub fn item(&mut self, c: impl IntoBox) -> &mut Self {
self.children.push(c.into_box());
self
}
pub fn row(&mut self, task: impl FnOnce(&mut RowBuilder)) -> &mut Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut r = Row::new(format!("{}-row-{}", self.id, self.children.len())).gap(b.gap);
for c in b.children {
r.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(r));
} else {
self.children
.push(Box::new(WithLayout::new(r).set_layout(b.layout)));
}
self
}
pub fn column(&mut self, task: impl FnOnce(&mut RowBuilder)) -> &mut Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut col = Column::new(format!("{}-col-{}", self.id, self.children.len())).gap(b.gap);
for c in b.children {
col.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(col));
} else {
self.children
.push(Box::new(WithLayout::new(col).set_layout(b.layout)));
}
self
}
pub fn grid(&mut self, columns: usize, task: impl FnOnce(&mut RowBuilder)) -> &mut Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut g = Grid::new(format!("{}-grid-{}", self.id, self.children.len()))
.columns(columns)
.gap(b.gap);
for c in b.children {
g.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(g));
} else {
self.children
.push(Box::new(WithLayout::new(g).set_layout(b.layout)));
}
self
}
pub fn panel(
&mut self,
label: impl Into<String>,
task: impl FnOnce(&mut RowBuilder),
) -> &mut Self {
let label = label.into();
let mut b = RowBuilder::default();
task(&mut b);
let mut p = Panel::new(format!("{}-panel-{}", self.id, label))
.label(label)
.gap(b.gap);
for c in b.children {
p.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(p));
} else {
self.children
.push(Box::new(WithLayout::new(p).set_layout(b.layout)));
}
self
}
pub fn tabs(&mut self, task: impl FnOnce(Tabs) -> Tabs) -> &mut Self {
let t = task(Tabs::new(format!(
"{}-tabs-{}",
self.id,
self.children.len()
)));
self.children.push(Box::new(t));
self
}
}
pub struct RowBuilder {
pub(crate) children: Vec<Box<dyn Component>>,
pub(crate) gap: f64,
pub(crate) layout: Layout,
}
impl Default for RowBuilder {
fn default() -> Self {
Self {
children: Vec::new(),
gap: 16.0,
layout: Layout::default(),
}
}
}
impl RowBuilder {
pub fn item(&mut self, c: impl IntoBox) {
self.children.push(c.into_box());
}
pub fn tabs(&mut self, task: impl FnOnce(Tabs) -> Tabs) {
let t = task(Tabs::new(format!("tabs-{}", self.children.len())));
self.children.push(Box::new(t));
}
pub fn row(&mut self, task: impl FnOnce(&mut RowBuilder)) {
let mut b = RowBuilder::default();
task(&mut b);
let mut r = Row::new(format!("row-{}", self.children.len())).gap(b.gap);
for c in b.children {
r.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(r));
} else {
self.children
.push(Box::new(WithLayout::new(r).set_layout(b.layout)));
}
}
pub fn column(&mut self, task: impl FnOnce(&mut RowBuilder)) {
let mut b = RowBuilder::default();
task(&mut b);
let mut col = Column::new(format!("col-{}", self.children.len())).gap(b.gap);
for c in b.children {
col.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(col));
} else {
self.children
.push(Box::new(WithLayout::new(col).set_layout(b.layout)));
}
}
pub fn grid(&mut self, columns: usize, task: impl FnOnce(&mut RowBuilder)) {
let mut b = RowBuilder::default();
task(&mut b);
let mut g = Grid::new(format!("grid-{}", self.children.len()))
.columns(columns)
.gap(b.gap);
for c in b.children {
g.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(g));
} else {
self.children
.push(Box::new(WithLayout::new(g).set_layout(b.layout)));
}
}
pub fn panel(&mut self, label: impl Into<String>, task: impl FnOnce(&mut RowBuilder)) {
let label = label.into();
let mut b = RowBuilder::default();
task(&mut b);
let mut p = Panel::new(format!("panel-{}", label))
.label(label)
.gap(b.gap);
for c in b.children {
p.children.push(c);
}
if b.layout == Layout::default() {
self.children.push(Box::new(p));
} else {
self.children
.push(Box::new(WithLayout::new(p).set_layout(b.layout)));
}
}
pub fn gap(&mut self, g: f64) {
self.gap = g;
}
pub fn width(&mut self, w: u32) {
self.layout.width = Some(w);
}
pub fn height(&mut self, h: u32) {
self.layout.height = Some(h);
}
pub fn max_width(&mut self, mw: u32) {
self.layout.max_width = Some(mw);
}
pub fn max_height(&mut self, mh: u32) {
self.layout.max_height = Some(mh);
}
pub fn scale(&mut self, s: u32) {
self.layout.scale = Some(s);
}
pub fn min_width(&mut self, w: u32) {
self.layout.min_width = Some(w);
}
}
impl App {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
subtitle: String::new(),
root: Column::new("root").gap(16.0),
pages: Vec::new(),
handlers: Vec::new(),
live: false,
run_label: "Run".to_string(),
run_button: None,
verbose: true,
api_key: None,
allow_cors: true,
enable_docs: true,
isolated_sessions: true,
theme: Theme::default(),
max_width: None,
mcp_tools: Vec::new(),
enable_mcp: true,
wasm_registry: std::sync::Arc::new(crate::wasm::WasmRegistry::new()),
auth_config: crate::auth::AuthConfig::default(),
}
}
pub fn auth(mut self, config: crate::auth::AuthConfig) -> Self {
self.auth_config = config;
self
}
pub fn auth_provider(mut self, provider: crate::auth::AuthProvider) -> Self {
self.auth_config.enabled = true;
self.auth_config.providers.push(provider);
self
}
pub fn wasm_plugin(mut self, id: impl Into<String>, plugin: crate::wasm::WasmPlugin) -> Self {
if let Some(reg) = std::sync::Arc::get_mut(&mut self.wasm_registry) {
reg.register(id, plugin);
} else {
let mut reg = (*self.wasm_registry).clone();
reg.register(id, plugin);
self.wasm_registry = std::sync::Arc::new(reg);
}
self
}
pub fn page(
mut self,
route: impl Into<String>,
title: impl Into<String>,
task: impl FnOnce(&mut PageBuilder),
) -> Self {
let route = route.into();
let title = title.into();
let mut b = PageBuilder::new(format!("page-{}", self.pages.len()));
task(&mut b);
let mut page_col = Column::new(&b.id).gap(b.gap);
for c in b.children {
page_col.push(c);
}
self.pages.push(PageDef {
route,
title,
icon: b.icon,
id: b.id,
required_role: b.required_role,
});
self.root.push(Box::new(page_col));
self
}
pub fn page_with_icon(
self,
route: impl Into<String>,
title: impl Into<String>,
icon: impl Into<String>,
task: impl FnOnce(&mut PageBuilder),
) -> Self {
let icon_str = icon.into();
self.page(route, title, |p| {
p.icon(icon_str);
task(p);
})
}
pub fn max_width(mut self, mw: u32) -> Self {
self.max_width = Some(mw);
self
}
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
pub fn tabs(mut self, task: impl FnOnce(Tabs) -> Tabs) -> Self {
let t = task(Tabs::new(format!("tabs-{}", self.root.children().len())));
self.root.push(Box::new(t));
self
}
pub fn mcp_tool(
mut self,
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
handler: impl Fn(Value) -> Result<Value> + Send + Sync + 'static,
) -> Self {
self.mcp_tools.push(crate::mcp::McpTool::new(
name,
description,
input_schema,
handler,
));
self
}
pub fn mcp(mut self, enable: bool) -> Self {
self.enable_mcp = enable;
self
}
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn cors(mut self, allow: bool) -> Self {
self.allow_cors = allow;
self
}
pub fn docs(mut self, enable: bool) -> Self {
self.enable_docs = enable;
self
}
pub fn isolate_sessions(mut self, isolate: bool) -> Self {
self.isolated_sessions = isolate;
self
}
pub fn subtitle(mut self, s: impl Into<String>) -> Self {
self.subtitle = s.into();
self
}
pub fn quiet(mut self) -> Self {
self.verbose = false;
self
}
pub fn live(mut self) -> Self {
self.live = true;
self
}
pub fn run_label(mut self, s: impl Into<String>) -> Self {
self.run_label = s.into();
self
}
#[allow(clippy::should_implement_trait)]
pub fn add(mut self, c: impl IntoBox) -> Self {
self.root.push(c.into_box());
self
}
pub fn item(mut self, c: impl IntoBox) -> Self {
self.root.push(c.into_box());
self
}
pub fn row(mut self, task: impl FnOnce(&mut RowBuilder)) -> Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut row = Row::new(format!("row-{}", b.children.len())).gap(b.gap);
for c in b.children {
row.children.push(c);
}
let built: Box<dyn Component> = if b.layout == Layout::default() {
Box::new(row)
} else {
Box::new(WithLayout::new(row).set_layout(b.layout))
};
self.root.push(built);
self
}
pub fn column(mut self, task: impl FnOnce(&mut RowBuilder)) -> Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut col = Column::new(format!("col-{}", b.children.len())).gap(b.gap);
for c in b.children {
col.children.push(c);
}
let built: Box<dyn Component> = if b.layout == Layout::default() {
Box::new(col)
} else {
Box::new(WithLayout::new(col).set_layout(b.layout))
};
self.root.push(built);
self
}
pub fn grid(mut self, columns: usize, task: impl FnOnce(&mut RowBuilder)) -> Self {
let mut b = RowBuilder::default();
task(&mut b);
let mut g = Grid::new(format!("grid-{}", b.children.len()))
.columns(columns)
.gap(b.gap);
for c in b.children {
g.children.push(c);
}
let built: Box<dyn Component> = if b.layout == Layout::default() {
Box::new(g)
} else {
Box::new(WithLayout::new(g).set_layout(b.layout))
};
self.root.push(built);
self
}
pub fn panel(mut self, label: impl Into<String>, task: impl FnOnce(&mut RowBuilder)) -> Self {
let label = label.into();
let mut b = RowBuilder::default();
task(&mut b);
let mut p = Panel::new(format!("panel-{}", label))
.label(label)
.gap(b.gap);
for c in b.children {
p.children.push(c);
}
let built: Box<dyn Component> = if b.layout == Layout::default() {
Box::new(p)
} else {
Box::new(WithLayout::new(p).set_layout(b.layout))
};
self.root.push(built);
self
}
pub fn on_submit(
mut self,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event: EventName::Submit,
component: None,
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
let btn = Button::new("run").label(self.run_label.clone()).primary();
self.run_button = Some("run".to_string());
self.root.push(Box::new(btn));
self
}
pub fn on_load(
mut self,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event: EventName::Load,
component: None,
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
self
}
pub fn on_change(
mut self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event: EventName::Change,
component: Some(id.into()),
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
self
}
pub fn on_click(
mut self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event: EventName::Click,
component: Some(id.into()),
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
self
}
pub fn on(
mut self,
event: &str,
ids: impl IntoIterator<Item = impl Into<String>>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
let ev = match event {
"click" => EventName::Click,
"change" => EventName::Change,
"play" => EventName::Play,
"pause" => EventName::Pause,
"stop" => EventName::Stop,
"stream" => EventName::Stream,
_ => return self,
};
let shared: HandlerFn = Arc::new(f);
for id in ids {
self.handlers.push(HandlerDef {
event: ev.clone(),
component: Some(id.into()),
f: Arc::clone(&shared),
inputs: None,
outputs: None,
chain: Vec::new(),
});
}
self
}
pub fn on_play(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::Play, Some(id.into()), f)
}
pub fn on_pause(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::Pause, Some(id.into()), f)
}
pub fn on_stop(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::Stop, Some(id.into()), f)
}
pub fn on_stream(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::Stream, Some(id.into()), f)
}
pub fn on_vad(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::Vad, Some(id.into()), f)
}
pub fn on_audio_stream(
self,
id: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.register(EventName::AudioChunk, Some(id.into()), f)
}
fn register(
mut self,
event: EventName,
component: Option<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event,
component,
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
self
}
pub fn on_event(
mut self,
name: impl Into<String>,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.handlers.push(HandlerDef {
event: EventName::Custom(name.into()),
component: None,
f: Arc::new(f),
inputs: None,
outputs: None,
chain: Vec::new(),
});
self
}
pub fn flow(mut self, inputs: &[&str], outputs: &[&str]) -> Self {
if let Some(h) = self.handlers.last_mut() {
h.inputs = Some(inputs.iter().map(|s| s.to_string()).collect());
h.outputs = Some(outputs.iter().map(|s| s.to_string()).collect());
}
self
}
pub fn then(mut self, f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static) -> Self {
self.chain_link(RunCond::Always, f);
self
}
pub fn success(
mut self,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.chain_link(RunCond::Success, f);
self
}
pub fn failure(
mut self,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.chain_link(RunCond::Failure, f);
self
}
fn chain_link(
&mut self,
on: RunCond,
f: impl Fn(&mut Context) -> Result<()> + Send + Sync + 'static,
) {
if let Some(h) = self.handlers.last_mut() {
h.chain.push(Sibling { on, f: Arc::new(f) });
}
}
pub async fn serve(self, addr: impl Into<String>) -> Result<()> {
crate::server::serve(self, addr.into()).await
}
pub fn launch(self, addr: impl Into<String>) -> Result<()> {
if tokio::runtime::Handle::try_current().is_ok() {
tokio::task::block_in_place(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async move { crate::server::serve(self, addr.into()).await })
})
} else {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
rt.block_on(async move { crate::server::serve(self, addr.into()).await })
}
}
pub fn render_html_bundle(&self) -> String {
crate::server::render_standalone_html(self)
}
pub fn launch_desktop(self, addr: impl Into<String>) -> Result<()> {
let addr_str: String = addr.into();
let target_url = if addr_str.starts_with("0.0.0.0:") {
format!(
"http://localhost:{}",
addr_str.trim_start_matches("0.0.0.0:")
)
} else if !addr_str.starts_with("http://") && !addr_str.starts_with("https://") {
format!("http://{addr_str}")
} else {
addr_str.clone()
};
let url_to_open = target_url.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(300));
open_native_window(&url_to_open);
});
self.launch(addr_str)
}
}
fn open_native_window(url: &str) {
#[cfg(target_os = "windows")]
{
let candidates = [
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
];
let mut launched = false;
for path in &candidates {
if std::path::Path::new(path).exists() {
let app_arg = format!("--app={url}");
let size_arg = "--window-size=1050,800";
if std::process::Command::new(path)
.args([&app_arg, size_arg])
.spawn()
.is_ok()
{
launched = true;
break;
}
}
}
if !launched {
let _ = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", &format!("Start-Process '{url}'")])
.spawn();
}
}
#[cfg(target_os = "macos")]
{
let _ = std::process::Command::new("open").arg(url).spawn();
}
#[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
{
let _ = std::process::Command::new("xdg-open").arg(url).spawn();
}
}
pub(crate) fn process_event(ev: &WireEvent, app: &App, ctx: &mut Context) -> Value {
let mut error: Option<Error> = None;
for h in handlers_for_client(ev, app) {
ctx.set_flow(h.inputs.as_deref(), h.outputs.as_deref());
if let Err(e) = run_handler(h, ctx) {
error = Some(e);
break;
}
}
ctx.set_flow(None, None);
if error.is_none() {
let mut budget = 0usize;
loop {
let emitted = ctx.take_emitted();
if emitted.is_empty() {
break;
}
budget += emitted.len();
if budget > 64 {
error = Some(Error::from("event loop guard reached"));
break;
}
for (name, _data) in emitted {
for h in handlers_for_custom(app, &name) {
if let Err(e) = (h.f)(ctx) {
error = Some(e);
break;
}
}
if error.is_some() {
break;
}
}
if error.is_some() {
break;
}
}
}
if let Some(e) = error {
return json!({ "t": "error", "m": e.to_string() });
}
let all = ctx.take_all();
let u: Vec<Value> = all
.into_iter()
.map(|(id, patch)| json!({ "id": id, "p": patch }))
.collect();
json!({ "t": "update", "u": u })
}
fn run_handler(h: &HandlerDef, ctx: &mut Context) -> Result<()> {
let mut error: Option<Error> = (h.f)(ctx).err();
for sib in &h.chain {
let should_run = match sib.on {
RunCond::Always => true,
RunCond::Success => error.is_none(),
RunCond::Failure => error.is_some(),
};
if !should_run {
continue;
}
if let Err(e) = (sib.f)(ctx) {
if error.is_none() {
error = Some(e);
}
} else if sib.on == RunCond::Failure {
error = None;
}
}
match error {
Some(e) => Err(e),
None => Ok(()),
}
}
fn handlers_for_client<'a>(ev: &WireEvent, app: &'a App) -> Vec<&'a HandlerDef> {
app.handlers
.iter()
.filter(|h| match &h.event {
EventName::Submit => {
app.run_button.as_deref() == Some(ev.c.as_str()) || (app.live && ev.e == "change")
}
EventName::Change => ev.e == "change" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Click => ev.e == "click" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Play => ev.e == "play" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Pause => ev.e == "pause" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Stop => ev.e == "stop" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Stream => ev.e == "stream" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Vad => ev.e == "vad" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::AudioChunk => ev.e == "audio_chunk" && h.component.as_deref() == Some(ev.c.as_str()),
EventName::Load => ev.e == "load",
EventName::Custom(_) => false,
})
.collect()
}
fn handlers_for_custom<'a>(app: &'a App, name: &str) -> Vec<&'a HandlerDef> {
app.handlers
.iter()
.filter(|h| matches!(&h.event, EventName::Custom(n) if n == name))
.collect()
}