// 市集 (plan C1, laid out like OpenBot's marketplace): one window for what can be added to the // bots — 連接器 (MCP), 技能, Bot 範本 — as cards: a tile, the name, whose it is, one line of what // it does, and one button at the right (加入/安裝/建立, or a grey 已加入). A row of three larger // 精選 cards comes first while nothing is searched. The left column has a search, the three kinds // with their counts and what is already added (a connector with a problem in red), each opening // its own page in 設定. The buttons do what the settings pages' do (channels_ui): a connector // that needs a key opens 新增連接器 filled in; a skill from GitHub installs in the background // (how it went shows above the cards); a template makes the bot and opens its editor. use super::channels_ui::Page; use super::*; use crate::icons::Icon; #[derive(Default)] pub(super) struct MarketUi { pub open: bool, kind: Kind, query: String, } #[derive(Default, Clone, Copy, PartialEq)] enum Kind { #[default] Connectors, Skills, Bots, } const KINDS: [(Kind, &str, &str); 3] = [ (Kind::Connectors, "連接器", "讓 Bot 用別的服務的工具:檔案、網頁、GitHub…(MCP)"), (Kind::Skills, "技能", "做某件事的做法,所有 Bot 共用:要用時才讀完整的(SKILL.md)"), (Kind::Bots, "Bot 範本", "照範本建一個新的 Bot:名字、指示、頭像都先填好,之後可以改"), ]; #[derive(Clone)] enum Act { Mcp(usize), Builtin(&'static str), Remote(&'static str), Template(usize), } #[derive(Clone)] enum Tile { Letter(Color32), Icon(Icon, Color32), Face(&'static str, &'static str), } #[derive(Clone)] struct Card { name: String, by: &'static str, tag: &'static str, about: String, tile: Tile, added: bool, button: &'static str, act: Act, } /// The tiles' colours: one per name, from the bots' own. fn tile_colour(name: &str) -> Color32 { let h = name.bytes().fold(7u32, |a, b| a.wrapping_mul(31).wrapping_add(b as u32)); crate::avatar::color(crate::avatar::COLORS[1 + (h as usize % (crate::avatar::COLORS.len() - 1))].0) } const CARD_MIN_W: f32 = 300.0; const CARD_H: f32 = 92.0; const TALL_H: f32 = 132.0; impl App { fn market_cards(&self, kind: Kind) -> Vec { match kind { Kind::Connectors => crate::mcp::MARKET .iter() .enumerate() .map(|(i, (name, desc, _, needs))| Card { name: name.to_string(), by: "官方", tag: if needs.is_empty() { "" } else { "要金鑰" }, about: desc.to_string(), tile: Tile::Letter(tile_colour(name)), added: self.state.mcp_servers.iter().any(|s| s.name == *name), button: "加入", act: Act::Mcp(i), }) .collect(), Kind::Skills => { let mut v: Vec = crate::skills::BUILTIN_SKILLS .iter() .map(|b| Card { name: b.slug.to_string(), by: "內建", tag: "", about: if b.title == b.slug { b.summary.to_string() } else { format!("{} — {}", b.title, b.summary) }, tile: Tile::Icon(Icon::Sparkle, tile_colour(b.slug)), added: self.state.skills.iter().any(|s| s.name == b.slug), button: "加入", act: Act::Builtin(b.slug), }) .collect(); v.extend(crate::skills::REMOTE_MARKET.iter().map(|r| Card { name: r.name.to_string(), by: "Anthropic", tag: "", about: r.summary.trim_start_matches("Anthropic 官方:").to_string(), tile: Tile::Icon(Icon::Sparkle, tile_colour(r.name)), added: self.state.skills.iter().any(|s| s.name == r.name), button: "安裝", act: Act::Remote(r.source), })); v } Kind::Bots => crate::memory::TEMPLATES .iter() .enumerate() .map(|(i, tp)| Card { name: tp.name.to_string(), by: "範本", tag: "", about: tp.description.to_string(), tile: Tile::Face(tp.shape, tp.color), added: false, button: "建立", act: Act::Template(i) }) .collect(), } } /// The window. pub(super) fn market_window(&mut self, ctx: &egui::Context) { if !self.market.open { return; } let p = self.pal; let body_h = dialog_max_height(ctx) - 48.0; let q = self.market.query.trim().to_lowercase(); let matches = |c: &Card| q.is_empty() || c.name.to_lowercase().contains(&q) || c.about.to_lowercase().contains(&q); let counts: Vec = KINDS.iter().map(|(k, _, _)| self.market_cards(*k).iter().filter(|c| matches(c)).count()).collect(); let cards: Vec = self.market_cards(self.market.kind).into_iter().filter(|c| matches(c)).collect(); let errors: Vec = self.ch.mcp_errors.lock().map(|e| e.iter().map(|(n, _)| n.clone()).collect()).unwrap_or_default(); let skill_busy = self.ch.skill_busy.load(Ordering::SeqCst); let note = self.ch.skill_note.lock().ok().and_then(|n| n.clone()); let mut act: Option = None; let mut go: Option<(u8, Page)> = None; let closed = dialog(ctx, "market", "市集", 960.0, true, p, |ui| { Frame::new().inner_margin(Margin { left: 16, right: 0, top: 10, bottom: 0 }).show(ui, |ui| { ui.horizontal_top(|ui| { // Left: the search, the kinds, what is added. ui.vertical(|ui| { ui.set_width(200.0); ui.add(egui::TextEdit::singleline(&mut self.market.query).hint_text(t("搜尋市集")).desired_width(196.0)); ui.add_space(8.0); for (i, (k, label, _)) in KINDS.iter().enumerate() { let (rect, r) = ui.allocate_exact_size(vec2(196.0, 30.0), egui::Sense::click()); let on = self.market.kind == *k; if on || r.hovered() { ui.painter().rect_filled(rect, R_M, if on { p.active } else { p.hover }); } ui.painter().text(rect.left_center() + vec2(10.0, 0.0), egui::Align2::LEFT_CENTER, t(label), egui::FontId::proportional(FONT_SM), p.text); ui.painter().text(rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, counts[i].to_string(), egui::FontId::proportional(FONT_XS), p.text3); if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() { self.market.kind = *k; } } ui.add_space(12.0); ui.label(RichText::new(t("已安裝")).size(FONT_XS).color(p.text3)); ui.add_space(2.0); let row = |ui: &mut egui::Ui, name: &str, dot: Color32, sub: &str| { let (rect, r) = ui.allocate_exact_size(vec2(196.0, 26.0), egui::Sense::click()); if r.hovered() { ui.painter().rect_filled(rect, R_M, p.hover); } ui.painter().circle_filled(rect.left_center() + vec2(14.0, 0.0), 4.0, dot); let name = super::sidebar_ui::shorten_width(ui, name, 120.0, FONT_SM); ui.painter().text(rect.left_center() + vec2(26.0, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(FONT_SM), p.text); ui.painter().text(rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, t(sub), egui::FontId::proportional(FONT_XS), p.text3); r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() }; let mut shown = 0; for s in &self.state.mcp_servers { let bad = errors.contains(&s.name); if row( ui, &s.name, if bad { p.danger } else if s.enabled { p.up } else { p.text3 }, if bad { "有問題" } else { "連接器" }, ) { go = Some((1, Page::Item(s.name.clone()))); } shown += 1; } for s in self.state.skills.iter().take(8) { if row(ui, &s.name, p.text3, "技能") { go = Some((2, Page::Item(s.name.clone()))); } shown += 1; } if self.state.skills.len() > 8 { let more = format!("{} {}", t("還有"), self.state.skills.len() - 8); if row(ui, &more, Color32::TRANSPARENT, "技能") { go = Some((2, Page::List)); } } if shown == 0 { hint(ui, "還沒有加入任何東西", p); } }); ui.add_space(12.0); // Right: what this kind is, then the cards. (Given its height: a column in a row // only gets the row's.) ui.allocate_ui_with_layout(vec2(ui.available_width(), body_h - 20.0), Layout::top_down(Align::Min), |ui| { ui.set_min_height(body_h - 20.0); let (_, label, about) = KINDS.iter().find(|(k, _, _)| *k == self.market.kind).copied().unwrap_or(KINDS[0]); Frame::new().inner_margin(Margin { left: 20, right: 20, top: 0, bottom: 0 }).show(ui, |ui| { ui.label(RichText::new(t(label)).size(FONT_H3).family(crate::bold()).color(p.text)); ui.label(RichText::new(t(about)).size(FONT_SM).color(p.text2)); if self.market.kind == Kind::Skills { if skill_busy { ui.label(RichText::new(t("正在安裝技能…")).size(FONT_SM).color(p.text2)); } else if let Some((ok, words)) = ¬e { ui.label(RichText::new(words).size(FONT_SM).color(if *ok { p.up } else { p.danger })); } } }); // The cards get the rest of the column (the note above can add a line). let rest = (ui.available_height() - 12.0).max(120.0); dialog_body(ui, "market-body", rest, |ui| { if cards.is_empty() { hint(ui, "沒有符合的項目", p); return; } let avail = ui.available_width(); if q.is_empty() && cards.len() > 3 { ui.label(RichText::new(t("精選")).size(FONT_SM).family(crate::bold()).color(p.text2)); ui.add_space(4.0); let w = ((avail - 20.0) / 3.0).floor(); // What isn't added yet first: nothing to do on a 已加入 one. let mut featured: Vec<&Card> = cards.iter().filter(|c| !c.added).chain(cards.iter().filter(|c| c.added)).collect(); featured.truncate(3); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 10.0; for c in featured { if self.market_card(ui, c, w, true, skill_busy) { act = Some(c.act.clone()); } } }); ui.add_space(14.0); ui.label(RichText::new(t("全部")).size(FONT_SM).family(crate::bold()).color(p.text2)); ui.add_space(4.0); } let cols = ((avail + 10.0) / (CARD_MIN_W + 10.0)).floor().max(1.0) as usize; let w = ((avail - 10.0 * (cols - 1) as f32) / cols as f32).floor(); for chunk in cards.chunks(cols) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 10.0; for c in chunk { if self.market_card(ui, c, w, false, skill_busy) { act = Some(c.act.clone()); } } }); ui.add_space(10.0); } }); }); }); }); }); if let Some(a) = act { self.market_act(ctx, a); } if let Some((sub, page)) = go { self.market.open = false; self.show_settings = true; self.settings_tab = SettingsTab::Channels; self.ch.sub = sub; if sub == 1 { self.ch.mcp_page = page; } else { self.ch.skill_page = page; } } if closed { self.market.open = false; } } /// What a card's button does. fn market_act(&mut self, ctx: &egui::Context, a: Act) { match a { Act::Mcp(i) => { let (name, _, cmd, needs) = crate::mcp::MARKET[i]; // One that needs a key: its form, in 設定, filled in. if self.mcp_market_add(name, cmd, needs) { self.market.open = false; self.show_settings = true; self.settings_tab = SettingsTab::Channels; self.ch.sub = 1; } } Act::Builtin(slug) => self.skill_add_builtin(slug), Act::Remote(src) => self.skill_install(src.to_string(), ctx), Act::Template(i) => { let tp = &crate::memory::TEMPLATES[i]; let id = self.state.next_id; let sel = self.state.selected; let _ = crate::appctl::apply(&mut self.state, sel, "create_bot", &serde_json::json!({"template": tp.name}).to_string()); if self.state.bot(id).is_some() { self.state.selected = id; self.edit_bot = self.state.bot(id).cloned().map(|b| (b, false)); self.market.open = false; } self.mark(); } } } /// One card; true when its button was pressed. `tall`: a 精選 one — the tile on top, two lines /// of what it does. fn market_card(&mut self, ui: &mut egui::Ui, c: &Card, w: f32, tall: bool, busy: bool) -> bool { let p = self.pal; let h = if tall { TALL_H } else { CARD_H }; let (rect, _) = ui.allocate_exact_size(vec2(w, h), egui::Sense::hover()); ui.painter().rect_filled(rect, R_L, p.elevated); ui.painter().rect_stroke(rect, R_L, Stroke::new(1.0, p.border), egui::StrokeKind::Inside); let pad = 14.0; let tile = egui::Rect::from_min_size(rect.min + vec2(pad, pad), vec2(40.0, 40.0)); match &c.tile { Tile::Letter(col) | Tile::Icon(_, col) => { ui.painter().rect_filled(tile, R_M, col.gamma_multiply(0.16)); if let Tile::Icon(icon, _) = &c.tile { crate::icons::paint(ui.painter(), egui::Rect::from_center_size(tile.center(), vec2(20.0, 20.0)), *icon, *col); } else { let letter: String = c.name.chars().next().map(|ch| ch.to_uppercase().collect()).unwrap_or_default(); ui.painter().text(tile.center(), egui::Align2::CENTER_CENTER, letter, egui::FontId::new(FONT_H3, crate::bold()), *col); } } Tile::Face(shape, colour) => crate::avatar::paint(ui.painter(), tile, shape, crate::avatar::color(colour)), } // The button, top right. let btn = egui::Rect::from_min_size(egui::pos2(rect.right() - pad - 64.0, rect.top() + pad + 5.0), vec2(64.0, 30.0)); let mut pressed = false; if c.added { ui.painter().text(btn.center(), egui::Align2::CENTER_CENTER, t("已加入"), egui::FontId::proportional(FONT_XS), p.text3); } else { // (One skill installs at a time.) let enabled = !(busy && matches!(c.act, Act::Remote(_))); // (In a child: `put` would move the row's cursor and push the next card away.) let mut at = ui.new_child(egui::UiBuilder::new().max_rect(btn).layout(Layout::centered_and_justified(egui::Direction::TopDown))); pressed = at.add_enabled(enabled, secondary_button(c.button)).on_disabled_hover_text(t("正在安裝另一個技能")).clicked(); } // Name and whose: beside the tile (a compact card), under it (a tall one). let (x, y) = if tall { (rect.left() + pad, tile.bottom() + 8.0) } else { (tile.right() + 12.0, rect.top() + pad + 2.0) }; let name_w = if tall { w - 2.0 * pad } else { btn.left() - 10.0 - x }; let name = super::sidebar_ui::shorten_width(ui, &c.name, name_w, FONT_BASE); let name_g = ui.painter().layout_no_wrap(name, egui::FontId::new(FONT_BASE, crate::bold()), p.text); let name_end = x + name_g.size().x; ui.painter().galley(egui::pos2(x, y), name_g, p.text); let by = if c.tag.is_empty() { t(c.by) } else { format!("{} · {}", t(c.by), t(c.tag)) }; if tall { ui.painter().text(egui::pos2(name_end + 8.0, y + 3.0), egui::Align2::LEFT_TOP, by, egui::FontId::proportional(FONT_XS), p.text3); } else { ui.painter().text(egui::pos2(x, y + 22.0), egui::Align2::LEFT_TOP, by, egui::FontId::proportional(FONT_XS), p.text3); } // What it does: one line under the tile (compact), two under the name (tall). let about_y = if tall { y + 24.0 } else { tile.bottom() + 10.0 }; let mut job = egui::text::LayoutJob::simple(c.about.clone(), egui::FontId::proportional(FONT_SM), p.text2, w - 2.0 * pad); job.wrap = egui::text::TextWrapping { max_width: w - 2.0 * pad, max_rows: if tall { 2 } else { 1 }, break_anywhere: true, overflow_character: Some('…') }; let g = ui.painter().layout_job(job); ui.painter().galley(egui::pos2(rect.left() + pad, about_y), g, p.text2); // Everything it says, under the pointer. ui.interact(rect, egui::Id::unique(("market-card", &c.name)), egui::Sense::hover()).on_hover_text(format!("{}\n{}", c.name, c.about)); pressed } }