//! Spike 2, the composer and chat lines (plan section 6 step 1): //! gpui-component's multi-line input with emoji inserted at the caret from a //! picker (names from `voelin-ui-vm`'s emoji module), file and picture //! paste, Ctrl+Enter to send, IME preedit (the platform's, through GPUI's //! input handler), and chat lines made by `voelin-ui-vm` (`chat::line`: //! BBCode โ†’ `TextBlock`s of `TextRun`s) drawn as `StyledText` in //! `InteractiveText` with clickable links and inline colour emoji (the runs //! `voelin-ui-vm` marks as emoji in the colour emoji font). //! //! ```text //! spike-composer [--picker] [--seconds N] //! ``` //! //! Every event (sent, attached, emoji inserted, link clicked, the input's //! text and preedit) is a JSON line on stdout, which `drive.sh` checks. use std::ops::Range; use std::path::PathBuf; use std::sync::Arc; use std::time::Instant; use gpui_kit::component::ActiveTheme as _; use gpui_kit::component::input::{InputEvent, Textarea, TextareaState}; use gpui_kit::{ App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Font, FontStyle, FontWeight, Hsla, Image, ImageSource, InteractiveElement as _, InteractiveText, IntoElement, KeyBinding, ParentElement as _, Render, StatefulInteractiveElement as _, StrikethroughStyle, Styled as _, StyledText, TitlebarOptions, UnderlineStyle, Window, WindowBounds, WindowOptions, actions, div, img, point, px, rgb, size, svg, }; use serde_json::json; use voelin_model::{ChatMessage, ChatTarget}; use voelin_ui_vm::bridge::{ChatLine, TextBlock}; use voelin_ui_vm::chat; use voelin_ui_vm::emoji; actions!( spike_composer, [ /// Send the composer's text and attachments. Send, /// Open or close the emoji picker. TogglePicker, ] ); /// The messages the list starts with: what the chat must draw (styles, /// colours, masked and bare links, code, quotes, lists, emoji, a ZWJ /// sequence, a flag, CJK text, jumbo emoji). const SAMPLES: &[(&str, &str)] = &[ ( "Mira", "[url=https://example.com/raid]raid board[/url] for tonight (a masked link: asks before it opens)", ), ("Mira", "Raid tonight at [b]21:00[/b]! Bring the flask ๐ŸŽ‰"), ( "Mira", "[i]Bring[/i] [u]consumables[/u], [s]not[/s] snacks. Colours: [color=#e5484d]red[/color] [color=#46a758]green[/color]", ), ( "Jonas", "Patch notes: https://example.org/notes/2026-10, see `voice --fix` and [code]let gain = -6.0;\nmixer.set(gain);[/code]", ), ("Jonas", "[quote=Mira]Who brings the flask?[/quote]Me ๐Ÿ™‹ โ€” and a ๐Ÿ‘ฉโ€๐Ÿ’ป for the logs ๐Ÿ‡ซ๐Ÿ‡ท"), ("Aiko", "ๆ—ฅๆœฌ่ชžใฎใƒ†ใ‚ญใ‚นใƒˆใ€ไธญๆ–‡็š„ๆ–‡ๆœฌใ€ํ•œ๊ตญ์–ด ํ…์ŠคํŠธ โ€” CJK through the system fonts"), ("Aiko", "[list][*]first item[*]second with ๐Ÿ™‚[*]third[/list]"), // U+1F600 to U+1F640, which DejaVu Sans also has (in monochrome). ("Jonas", "Smileys DejaVu also has: ๐Ÿ˜€ ๐Ÿ˜‚ ๐Ÿ˜ ๐Ÿ™€, and one it lacks: ๐Ÿ™‚"), ("Aiko", "๐ŸŽ‰๐ŸŽ‰"), ( "Mira", "Join us: ts3server://voice.example.com?port=9987 or [url=javascript:alert(1)]this[/url] (refused)", ), ]; /// A file or picture waiting to go with the next message. #[derive(Clone)] enum Attachment { File(PathBuf), Picture(Arc), } /// The fonts chat runs are drawn in: the UI font (Inter and its fallback /// chain), the colour emoji font for the runs `voelin-ui-vm` marks as emoji /// (`TextRun.emoji`, the Twemoji key, is only used to know that), and the /// theme's monospace font for code. #[derive(Clone)] struct RunFonts { ui: Font, emoji: Font, mono: Font, } impl RunFonts { fn new(cx: &App) -> Self { Self { ui: spike_common::fonts::ui_font(), emoji: spike_common::fonts::emoji_font(), mono: Font { family: cx.theme().mono_font_family.clone(), ..spike_common::fonts::ui_font() }, } } } struct Composer { start: Instant, fonts: RunFonts, input: Entity, lines: Vec, previous: Option, attachments: Vec, picker_open: bool, picker: Vec, focus: FocusHandle, last_preedit: Option, } fn event(start: Instant, what: serde_json::Value) { let mut line = what; line["t"] = json!((start.elapsed().as_secs_f64() * 10.0).round() / 10.0); println!("{line}"); } fn hex(rgb_value: u32) -> Hsla { rgb(rgb_value).into() } impl Composer { fn new(window: &mut Window, cx: &mut Context) -> Self { let input = cx.new(|cx| { let mut state = TextareaState::new(window, cx).placeholder("Message #Lobby (Ctrl+Enter sends)"); state.set_auto_grow(1, 6, cx); state }); cx.subscribe_in(&input, window, |this: &mut Self, input, e: &InputEvent, _, cx| { if let InputEvent::Change = e { let value = input.read(cx).value().to_string(); event(this.start, json!({"event": "changed", "value": value})); } }) .detach(); // The preedit, read as the platform's IME sees it (the marked range of // GPUI's input handler) ten times a second: a preedit is not a change // of the input's value. cx.spawn_in(window, async move |this, cx| { loop { cx.background_executor().timer(std::time::Duration::from_millis(100)).await; if this.update_in(cx, |this, window, cx| this.poll_preedit(window, cx)).is_err() { break; } } }) .detach(); let mut lines = Vec::new(); let mut previous = None; for (i, (author, text)) in SAMPLES.iter().enumerate() { let message = ChatMessage { target: ChatTarget::Channel(1), author_name: (*author).to_owned(), author_uid: None, author_id: None, text: (*text).to_owned(), ts_ms: 1_792_830_000_000 + i as i64 * 60_000, via_relay: false, blocked: false, }; lines.push(chat::line(&message, previous.as_ref())); previous = Some(chat::Previous::of(&message)); } let picker = emoji::archive().category(0).into_iter().take(96).collect(); Self { start: Instant::now(), fonts: RunFonts::new(cx), input, lines, previous, attachments: Vec::new(), picker_open: spike_common::flag("picker"), picker, focus: cx.focus_handle(), last_preedit: None, } } /// Log the input's preedit (marked text) when it changes. fn poll_preedit(&mut self, window: &mut Window, cx: &mut Context) { let value = self.input.read(cx).value().to_string(); let marked = self.input.update(cx, |s, cx| { s.marked_text_range(window, cx).map(|r| { let utf16: Vec = value.encode_utf16().collect(); String::from_utf16_lossy(utf16.get(r).unwrap_or_default()) }) }); if marked != self.last_preedit { event(self.start, json!({"event": "preedit", "marked": marked, "value": value})); self.last_preedit = marked; } } fn send(&mut self, window: &mut Window, cx: &mut Context) { let text = self.input.read(cx).value().trim().to_owned(); if text.is_empty() && self.attachments.is_empty() { return; } let names: Vec = self .attachments .drain(..) .map(|a| match a { Attachment::File(p) => p.display().to_string(), Attachment::Picture(i) => { format!("picture ({:?}, {} bytes)", i.format, i.bytes.len()) } }) .collect(); let mut body = text.clone(); for name in &names { body.push_str(&format!("\n๐Ÿ“Ž {name}")); } let message = ChatMessage { target: ChatTarget::Channel(1), author_name: "me".into(), author_uid: None, author_id: None, text: body, ts_ms: 1_792_840_000_000, via_relay: false, blocked: false, }; self.lines.push(chat::line(&message, self.previous.as_ref())); self.previous = Some(chat::Previous::of(&message)); event(self.start, json!({"event": "sent", "text": text, "attachments": names})); self.input.update(cx, |s, cx| s.set_value("", window, cx)); cx.notify(); } fn insert_emoji(&mut self, text: &str, window: &mut Window, cx: &mut Context) { self.input.update(cx, |s, cx| { s.insert(text.to_owned(), window, cx); s.focus(window, cx); }); let value = self.input.read(cx).value().to_string(); event(self.start, json!({"event": "emoji inserted", "emoji": text, "value": value})); } /// A paste: pictures and files become attachments (and nothing is /// inserted); a path to an existing file in text does too; other text is /// pasted as usual. fn paste(&mut self, item: &gpui_kit::ClipboardItem, cx: &mut App) -> bool { let mut taken = Vec::new(); for entry in item.entries() { match entry { gpui_kit::ClipboardEntry::Image(image) => { taken.push(Attachment::Picture(Arc::new(image.clone()))) } gpui_kit::ClipboardEntry::ExternalPaths(paths) => { taken.extend(paths.paths().iter().cloned().map(Attachment::File)) } gpui_kit::ClipboardEntry::String(s) => { let paths: Vec = s .text() .lines() .map(|l| PathBuf::from(l.trim().trim_start_matches("file://"))) .collect(); if !paths.is_empty() && paths.iter().all(|p| p.is_absolute() && p.is_file()) { taken.extend(paths.into_iter().map(Attachment::File)); } } } } if taken.is_empty() { return false; } let names: Vec = taken .iter() .map(|a| match a { Attachment::File(p) => format!("file {}", p.display()), Attachment::Picture(i) => format!("picture {:?} {} bytes", i.format, i.bytes.len()), }) .collect(); event(self.start, json!({"event": "attached", "what": names})); self.attachments.extend(taken); cx.refresh_windows(); true } } /// A clickable range of a block: the link and whether it is masked. type Link = (Range, String, bool); /// One text block as GPUI text runs: the runs' text joined, each run with /// its font (emoji runs in the emoji font, code in the monospace one), colour /// (`base` unless the run has its own) and decoration, and the link ranges. fn gpui_runs( block: &TextBlock, fonts: &RunFonts, base: Hsla, ) -> (String, Vec, Vec) { let mut text = String::new(); let mut runs = Vec::new(); let mut links: Vec = Vec::new(); let line = |thickness| UnderlineStyle { thickness, ..Default::default() }; for run in &block.runs { let from = text.len(); text.push_str(&run.text); let range = from..text.len(); let mut font = if !run.emoji.is_empty() { fonts.emoji.clone() } else if run.code || block.kind == 2 { fonts.mono.clone() } else { fonts.ui.clone() }; if run.bold { font.weight = FontWeight::BOLD; } if run.italic { font.style = FontStyle::Italic; } let mut color = run.ink_dark.map_or(base, |ink| hex(ink.0 & 0xffffff)); let mut underline = run.underline.then(|| line(px(1.0))); if !run.link.is_empty() { color = hex(0x7aa2ff); underline = Some(line(px(1.0))); // Runs of one link follow each other: one clickable range. match links.last_mut() { Some((r, url, _)) if r.end == from && *url == *run.link => r.end = range.end, _ => links.push((range.clone(), run.link.to_string(), run.masked)), } } runs.push(gpui_kit::TextRun { len: range.len(), font, color, background_color: run.code.then(|| hex(0x1f2a3d)), underline, strikethrough: run .strike .then(|| StrikethroughStyle { thickness: px(1.0), ..Default::default() }), }); } (text, runs, links) } /// One text block of a line as styled text with its links clickable. fn block_text( start: Instant, id: (usize, usize), block: &TextBlock, jumbo: bool, fonts: &RunFonts, ) -> impl IntoElement { let base = if block.kind == 1 { hex(0xb4c0d3) } else { hex(0xe6edf7) }; let (text, runs, links) = gpui_runs(block, fonts, base); let ranges: Vec> = links.iter().map(|(r, _, _)| r.clone()).collect(); let targets: Vec<(String, bool)> = links.into_iter().map(|(_, u, m)| (u, m)).collect(); let styled = StyledText::new(text).with_runs(runs); let body = InteractiveText::new(("block", id.0 * 1000 + id.1), styled).on_click( ranges, move |i, _, _| { if let Some((url, masked)) = targets.get(i) { event( start, json!({"event": "link clicked", "url": url, "masked": masked, "asks_first": masked}), ); } }, ); let row = div().child(body); let row = if jumbo { row.text_size(px(40.0)) } else { row }; match block.kind { 1 => row.pl_3().border_l_2().border_color(rgb(0x3b4a63)), 2 => row.bg(rgb(0x111a2b)).px_2(), 3 => div().flex().gap_2().child("โ€ข").child(row), 4 => div().h(px(1.0)).w_full().bg(rgb(0x3b4a63)), _ => row, } } fn line_view(start: Instant, index: usize, line: &ChatLine, fonts: &RunFonts) -> impl IntoElement { let header = (!line.continued).then(|| { div() .flex() .gap_2() .child( div() .font_weight(FontWeight::SEMIBOLD) .text_color(hex(line.tint.0 & 0xffffff)) .child(line.author.to_string()), ) .child(div().text_xs().text_color(rgb(0x7d8aa3)).child(line.time.to_string())) }); let body = if line.rich { div() .flex() .flex_col() .children( line.blocks .iter() .enumerate() .map(|(b, block)| block_text(start, (index, b), block, line.jumbo, fonts)), ) .into_any_element() } else { div().child(line.text.to_string()).into_any_element() }; div().flex().flex_col().gap_1().children(header).child(body) } impl Render for Composer { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let start = self.start; let picker = self.picker_open.then(|| { div() .id("picker") .flex() .flex_wrap() .gap_1() .p_2() .max_h(px(180.0)) .overflow_y_scroll() .bg(rgb(0x131c2e)) .rounded_md() .children(self.picker.iter().enumerate().map(|(i, e)| { let text = e.text.clone(); div() .id(("emoji", i)) .w(px(34.0)) .h(px(34.0)) .flex() .items_center() .justify_center() .text_size(px(22.0)) .font_family(spike_common::fonts::EMOJI_FAMILY) .rounded_md() .hover(|s| s.bg(rgb(0x24324a))) .child(e.text.clone()) .on_click(cx.listener(move |this, _, window, cx| { this.insert_emoji(&text, window, cx) })) })) }); let attachments = (!self.attachments.is_empty()).then(|| { div().flex().gap_2().children(self.attachments.iter().enumerate().map(|(i, a)| { match a { Attachment::File(p) => div() .id(("attachment", i)) .px_2() .py_1() .rounded_md() .bg(rgb(0x1f2a3d)) .child(format!( "๐Ÿ“Ž {}", p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default() )) .into_any_element(), Attachment::Picture(image) => div() .id(("attachment", i)) .child(img(ImageSource::Image(image.clone())).w(px(96.0)).h(px(64.0))) .into_any_element(), } })) }); let input = self.input.clone(); div() .id("composer-root") .key_context("Composer") .track_focus(&self.focus) .on_action(cx.listener(|this, _: &Send, window, cx| this.send(window, cx))) .on_action(cx.listener(|this, _: &TogglePicker, _, cx| { this.picker_open = !this.picker_open; cx.notify(); })) .size_full() .flex() .flex_col() .bg(rgb(0x0b1220)) .text_color(rgb(0xe6edf7)) .font(spike_common::fonts::ui_font()) .child( div() .id("messages") .flex_1() .overflow_y_scroll() .p_4() .flex() .flex_col() .gap_3() .children( self.lines .iter() .enumerate() .map(|(i, l)| line_view(start, i, l, &self.fonts)), ), ) .child( div().p_3().flex().flex_col().gap_2().children(picker).children(attachments).child( div() .flex() .gap_2() .items_end() .child( div() .id("emoji-button") .size(px(36.0)) .flex() .items_center() .justify_center() .rounded_md() .bg(rgb(0x1f2a3d)) .child( svg() .path("voelin/smile.svg") .size(px(20.0)) .text_color(rgb(0xc8d3e6)), ) .on_click(cx.listener(|this, _, _, cx| { this.picker_open = !this.picker_open; cx.notify(); })), ) .child(div().flex_1().child(Textarea::new(&input).on_paste({ let this = cx.entity().downgrade(); move |item, _, cx| { this.update(cx, |this, cx| this.paste(item, cx)).unwrap_or(false) } }))) .child( div() .id("send") .px_3() .h(px(36.0)) .flex() .items_center() .rounded_md() .bg(rgb(0x3b6cf6)) .child( svg() .path("icons/send.svg") .size(px(18.0)) .text_color(rgb(0xffffff)), ) .on_click(cx.listener(|this, _, window, cx| this.send(window, cx))), ), ), ) } } fn main() -> anyhow::Result<()> { spike_common::init_logging(); let seconds: Option = spike_common::arg("seconds").map(|v| v.parse()).transpose()?; gpui_kit::application().with_assets(spike_common::assets::Assets::default()).run(move |cx| { gpui_kit::init(cx); let emoji_font = spike_common::fonts::load(cx); // The client is dark: gpui-component's inputs follow its theme. gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx); println!( "{}", json!({"event": "fonts", "ui": spike_common::fonts::UI_FAMILY, "emoji": emoji_font}) ); // After gpui-component's bindings, so Ctrl+Enter in the input is // Send rather than the input's own "secondary enter" (a newline). cx.bind_keys([ KeyBinding::new("ctrl-enter", Send, Some("Input")), KeyBinding::new("ctrl-e", TogglePicker, None), ]); let window = gpui_kit::open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(gpui_kit::Bounds { origin: point(px(20.0), px(40.0)), size: size(px(900.0), px(1000.0)), })), titlebar: Some(TitlebarOptions { title: Some("Composer (spike)".into()), ..Default::default() }), ..Default::default() }, cx, |window, cx| cx.new(|cx| Composer::new(window, cx)), ) .expect("a window"); // The input has focus from the start. let _ = window.0.update(cx, |_, window, cx| { window.dispatch_action(Box::new(gpui_kit::component::input::MoveToEnd), cx) }); // Which glyphs GPUI draws in colour (`ShapedGlyph::is_emoji`: from the // colour emoji font), for lines made by `voelin-ui-vm` and drawn as the // list draws them, once with the emoji runs in the emoji font and once // in the UI font and its fallback chain. let _ = window.0.update(cx, |_, window, cx| { let fonts = RunFonts::new(cx); let fallback = RunFonts { emoji: fonts.ui.clone(), ..fonts.clone() }; for sample in [ "a\u{1f600}b", "\u{1f602}\u{1f640}\u{1f642}\u{1f389}", "\u{1f469}\u{200d}\u{1f4bb}", ] { let message = ChatMessage { target: ChatTarget::Channel(1), author_name: "probe".into(), author_uid: None, author_id: None, text: sample.into(), ts_ms: 0, via_relay: false, blocked: false, }; let line = chat::line(&message, None); let count = |fonts: &RunFonts| { let (mut colour, mut glyphs) = (0, 0); for block in &line.blocks { let (text, runs, _) = gpui_runs(block, fonts, hex(0xffffff)); let layout = window.text_system().layout_line(&text, px(16.0), &runs, None); for run in &layout.runs { glyphs += run.glyphs.len(); colour += run.glyphs.iter().filter(|g| g.is_emoji).count(); } } json!({"colour_glyphs": colour, "glyphs": glyphs}) }; let emoji_runs: usize = line .blocks .iter() .flat_map(|b| &b.runs) .filter(|r| !r.emoji.is_empty()) .count(); println!( "{}", json!({ "event": "emoji probe", "text": sample, "emoji_runs": emoji_runs, "emoji_font": count(&fonts), "fallback_chain": count(&fallback), }) ); } }); let composer = window.1; let _ = window.0.update(cx, |_, window, cx| { let input = composer.read(cx).input.clone(); input.update(cx, |s, cx| s.focus(window, cx)); }); if let Some(seconds) = seconds { cx.spawn(async move |cx| { cx.background_executor().timer(std::time::Duration::from_secs(seconds)).await; cx.update(|cx| cx.quit()); }) .detach(); } }); Ok(()) }