1use std::cell::RefCell;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
8use crate::layout::{
9 Column, Container, FlexItemExt, LayoutExt, ResizeBar, ResizeBarStyle, ResizeDragPhase, Row,
10 ScrollView,
11};
12use crate::primitives::Icon;
13use crate::text::Text;
14use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
15use ailloli_ui_core::event::Event;
16use ailloli_ui_core::geometry::{Constraints, Rect, Size};
17use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
18use ailloli_ui_core::{
19 ChatItemId, ChatMessage, ChatMessageKind, ChatMessageStatus, ChatRole, ChatSessionState,
20 ChatSessionStatus, Color, FontId, TextStyle, Theme,
21};
22use ailloli_ui_runtime::component::{
23 ComponentNode, Context, IntoView, Signal, State, View, Widget,
24};
25use ailloli_ui_runtime::input::EventCtx;
26use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
27use ailloli_ui_runtime::scene::PaintCtx;
28use ailloli_ui_runtime::{DrawCmd, DrawRRect, DrawText};
29use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, TextSystem, WrapMode};
30use lucide_icons::Icon as LucideIcon;
31
32use super::button::{Button, ButtonVariant};
33use super::popup::PopupPlacement;
34use super::select::{Select, SelectSize};
35use super::text_input::{TextInput, TextInputStyle};
36
37pub type ChatWidgetActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatWidgetAction)>;
48pub type ChatWidgetSendHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
59pub type ChatWidgetCopyHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatItemId, String)>;
70pub type ChatWidgetRetryHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, ChatItemId)>;
81pub type ChatMessageRenderer<A> = Rc<dyn Fn(&ChatMessage) -> View<A>>;
93
94#[derive(Debug, Clone, PartialEq)]
95pub enum ChatWidgetAction {
122 Send {
124 text: String,
126 },
127 Copy {
129 item_id: ChatItemId,
131 text: String,
133 },
134 Retry {
136 item_id: ChatItemId,
138 },
139 SetComposerDraft {
141 text: String,
143 },
144 SetComposerPermission {
146 value: String,
148 },
149 SetComposerModel {
151 model_id: Option<String>,
153 },
154 SetComposerReasoning {
156 reasoning_level: Option<String>,
158 },
159 SetComposerHeight {
161 height: f32,
163 },
164 StopTurn,
166}
167
168impl Eq for ChatWidgetAction {}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ChatComposerOption {
184 pub value: String,
186 pub label: String,
188}
189
190impl ChatComposerOption {
191 pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
201 Self {
202 value: value.into(),
203 label: label.into(),
204 }
205 }
206}
207
208#[derive(Debug, Clone, PartialEq)]
209pub struct ChatComposerControls {
225 pub permission_options: Vec<ChatComposerOption>,
227 pub selected_permission: String,
229 pub model_options: Vec<ChatComposerOption>,
231 pub selected_model_id: Option<String>,
233 pub reasoning_options: Vec<ChatComposerOption>,
235 pub selected_reasoning_level: Option<String>,
237 pub permission_enabled: bool,
239 pub model_enabled: bool,
241 pub reasoning_enabled: bool,
243 pub running: bool,
245 pub height: f32,
247 pub min_height: f32,
249 pub max_height: f32,
251}
252
253impl Default for ChatComposerControls {
254 fn default() -> Self {
255 Self {
256 permission_options: vec![
257 ChatComposerOption::new("read_only", "read_only"),
258 ChatComposerOption::new("workspace_write", "write"),
259 ChatComposerOption::new("danger_full_access", "full_acess"),
260 ],
261 selected_permission: "read_only".into(),
262 model_options: Vec::new(),
263 selected_model_id: None,
264 reasoning_options: Vec::new(),
265 selected_reasoning_level: None,
266 permission_enabled: true,
267 model_enabled: true,
268 reasoning_enabled: false,
269 running: false,
270 height: 112.0,
271 min_height: 72.0,
272 max_height: 220.0,
273 }
274 }
275}
276
277impl ChatComposerControls {
278 pub fn clamped_height(&self) -> f32 {
295 if self.height.is_finite() {
296 self.height.clamp(self.min_height, self.max_height)
297 } else {
298 112.0
299 }
300 }
301}
302
303#[derive(Clone, Debug)]
304pub struct ChatWidgetStyle {
319 pub background: Color,
321 pub border: Border,
323 pub header_background: Color,
325 pub user_background: Color,
327 pub assistant_background: Color,
329 pub tool_background: Color,
331 pub error_background: Color,
333 pub text: TextStyle,
335 pub muted: TextStyle,
337 pub role_text: TextStyle,
339 pub input: TextInputStyle,
341 pub radius: Radius,
343 pub header_radius: f32,
345 pub message_radius: f32,
347 pub inline_button_radius: f32,
349 pub padding: f32,
351 pub gap: f32,
353 pub message_gap: f32,
355 pub height: f32,
357 pub width: f32,
359 pub compact: bool,
361}
362
363impl Default for ChatWidgetStyle {
364 fn default() -> Self {
365 Self::from_theme(Theme::default())
366 }
367}
368
369impl ChatWidgetStyle {
370 pub fn from_theme(theme: Theme) -> Self {
385 let palette = theme.palette();
386 let mut input = TextInputStyle::from_theme(theme);
387 input.text = TextStyle::new(FontId::Ui, 13, palette.text);
388 input.bg = Color::hex_rgb(0x111827);
389 Self {
390 background: Color::hex_rgb(0x0B1018),
391 border: Border::new(1.0, palette.border.with_alpha(0.78)),
392 header_background: Color::hex_rgb(0x111827),
393 user_background: palette.accent.with_alpha(0.22),
394 assistant_background: Color::hex_rgb(0x17202A),
395 tool_background: Color::hex_rgb(0x1E293B),
396 error_background: Color::hex_rgb(0x3A1717),
397 text: TextStyle::new(FontId::Ui, 13, palette.text),
398 muted: TextStyle::new(FontId::Ui, 11, palette.text_muted),
399 role_text: TextStyle::new(FontId::Ui, 11, palette.text_muted),
400 input,
401 radius: Radius::uniform(theme.radius().md),
402 header_radius: 6.0,
403 message_radius: 6.0,
404 inline_button_radius: 5.0,
405 padding: 8.0,
406 gap: 8.0,
407 message_gap: 6.0,
408 height: 260.0,
409 width: 520.0,
410 compact: false,
411 }
412 }
413
414 pub fn compact(mut self) -> Self {
429 self.compact = true;
430 self.padding = 6.0;
431 self.gap = 6.0;
432 self.message_gap = 4.0;
433 self.height = 190.0;
434 self
435 }
436}
437
438pub struct ChatWidget<A = ()> {
456 pub(crate) layout: LayoutStyle,
458 pub(crate) flex_item: FlexItemStyle,
460 session: Signal<Option<ChatSessionState>>,
462 draft: Signal<String>,
464 style: ChatWidgetStyle,
466 on_action: Option<ChatWidgetActionHandler<A>>,
468 on_send: Option<ChatWidgetSendHandler<A>>,
470 on_copy: Option<ChatWidgetCopyHandler<A>>,
472 on_retry: Option<ChatWidgetRetryHandler<A>>,
474 message_renderer: Option<ChatMessageRenderer<A>>,
476 composer_accessory: Option<View<A>>,
478 composer_controls: ChatComposerControls,
480 follow_latest: bool,
482}
483
484crate::impl_layout_builders!(ChatWidget);
485
486impl<A: 'static> ChatWidget<A> {
487 pub fn new(session: Option<ChatSessionState>, draft: impl Into<Signal<String>>) -> Self {
501 Self::bind_session(State::new(session).into_signal(), draft)
502 }
503
504 pub fn bind_session(
522 session: impl Into<Signal<Option<ChatSessionState>>>,
523 draft: impl Into<Signal<String>>,
524 ) -> Self {
525 let style = ChatWidgetStyle::default();
526 Self {
527 layout: LayoutStyle::default()
528 .width(style.width)
529 .height(style.height),
530 flex_item: FlexItemStyle::default(),
531 session: session.into(),
532 draft: draft.into(),
533 style,
534 on_action: None,
535 on_send: None,
536 on_copy: None,
537 on_retry: None,
538 message_renderer: None,
539 composer_accessory: None,
540 composer_controls: ChatComposerControls::default(),
541 follow_latest: true,
542 }
543 }
544
545 pub fn chat_style(mut self, style: ChatWidgetStyle) -> Self {
559 self.layout = self.layout.width(style.width).height(style.height);
560 self.style = style;
561 self
562 }
563
564 pub fn compact(mut self, compact: bool) -> Self {
578 self.style.compact = compact;
579 self
580 }
581
582 pub fn on_action(mut self, f: impl Fn(ChatWidgetAction) -> A + 'static) -> Self {
596 self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
597 self
598 }
599
600 pub fn on_action_ctx(
615 mut self,
616 f: impl Fn(&mut EventCtx<A>, ChatWidgetAction) + 'static,
617 ) -> Self {
618 self.on_action = Some(Rc::new(f));
619 self
620 }
621
622 pub fn on_send(mut self, f: impl Fn(String) -> A + 'static) -> Self {
638 self.on_send = Some(Rc::new(move |ctx, text| ctx.dispatch(f(text))));
639 self
640 }
641
642 pub fn on_send_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
654 self.on_send = Some(Rc::new(f));
655 self
656 }
657
658 pub fn on_copy(mut self, f: impl Fn(ChatItemId, String) -> A + 'static) -> Self {
673 self.on_copy = Some(Rc::new(move |ctx, item_id, text| {
674 ctx.dispatch(f(item_id, text))
675 }));
676 self
677 }
678
679 pub fn on_copy_ctx(
691 mut self,
692 f: impl Fn(&mut EventCtx<A>, ChatItemId, String) + 'static,
693 ) -> Self {
694 self.on_copy = Some(Rc::new(f));
695 self
696 }
697
698 pub fn on_retry(mut self, f: impl Fn(ChatItemId) -> A + 'static) -> Self {
712 self.on_retry = Some(Rc::new(move |ctx, item_id| ctx.dispatch(f(item_id))));
713 self
714 }
715
716 pub fn on_retry_ctx(mut self, f: impl Fn(&mut EventCtx<A>, ChatItemId) + 'static) -> Self {
728 self.on_retry = Some(Rc::new(f));
729 self
730 }
731
732 pub fn message_renderer(mut self, f: impl Fn(&ChatMessage) -> View<A> + 'static) -> Self {
747 self.message_renderer = Some(Rc::new(f));
748 self
749 }
750
751 pub fn composer_accessory(mut self, accessory: View<A>) -> Self {
763 self.composer_accessory = Some(accessory);
764 self
765 }
766
767 pub fn composer_controls(mut self, controls: ChatComposerControls) -> Self {
783 self.composer_controls = controls;
784 self
785 }
786
787 pub fn follow_latest(mut self, enabled: bool) -> Self {
799 self.follow_latest = enabled;
800 self
801 }
802}
803
804impl<A: 'static> IntoView<A> for ChatWidget<A> {
805 fn into_view(self) -> View<A> {
806 let layout = self.layout;
807 finish_view_sized(
808 View::component(ChatWidgetComponent {
809 layout,
810 session: self.session,
811 draft: self.draft,
812 style: self.style,
813 on_action: self.on_action,
814 on_send: self.on_send,
815 on_copy: self.on_copy,
816 on_retry: self.on_retry,
817 message_renderer: self.message_renderer,
818 composer_accessory: self.composer_accessory,
819 composer_controls: self.composer_controls,
820 follow_latest: self.follow_latest,
821 }),
822 self.flex_item,
823 LayoutSizeHint::from_layout(layout),
824 )
825 }
826}
827
828struct ChatWidgetComponent<A> {
830 layout: LayoutStyle,
832 session: Signal<Option<ChatSessionState>>,
834 draft: Signal<String>,
836 style: ChatWidgetStyle,
838 on_action: Option<ChatWidgetActionHandler<A>>,
840 on_send: Option<ChatWidgetSendHandler<A>>,
842 on_copy: Option<ChatWidgetCopyHandler<A>>,
844 on_retry: Option<ChatWidgetRetryHandler<A>>,
846 message_renderer: Option<ChatMessageRenderer<A>>,
848 composer_accessory: Option<View<A>>,
850 composer_controls: ChatComposerControls,
852 follow_latest: bool,
854}
855
856struct ChatWidgetHandlers<A> {
858 on_action: Option<ChatWidgetActionHandler<A>>,
860 on_send: Option<ChatWidgetSendHandler<A>>,
862 on_copy: Option<ChatWidgetCopyHandler<A>>,
864 on_retry: Option<ChatWidgetRetryHandler<A>>,
866}
867
868impl<A> Clone for ChatWidgetHandlers<A> {
869 fn clone(&self) -> Self {
871 Self {
872 on_action: self.on_action.clone(),
873 on_send: self.on_send.clone(),
874 on_copy: self.on_copy.clone(),
875 on_retry: self.on_retry.clone(),
876 }
877 }
878}
879
880impl<A: 'static> ComponentNode<A> for ChatWidgetComponent<A> {
881 fn build(&self, context: &mut Context<A>) -> View<A> {
883 let composer_resize_start_height = context.signal(None::<f32>);
884 let mut content = Column::new()
885 .fill()
886 .gap(self.style.gap)
887 .child(self.header())
888 .child(self.messages().fill());
889 let mut composer_area = Column::new().fill_width();
890 if let Some(accessory) = self.composer_accessory.clone() {
891 composer_area = composer_area.child(accessory);
892 }
893 composer_area = composer_area
894 .child(self.composer_resize_bar(composer_resize_start_height))
895 .child(self.composer());
896 content = content.child(composer_area);
897
898 let mut root = Container::new()
899 .background(self.style.background)
900 .border(self.style.border.widths.top, self.style.border.colors.top)
901 .radius(self.style.radius.tl)
902 .padding(self.style.padding)
903 .clip_children(true)
904 .child(content);
905 *root.layout_mut() = self.layout;
906 root.into_view()
907 }
908}
909
910impl<A: 'static> ChatWidgetComponent<A> {
911 fn handlers(&self) -> ChatWidgetHandlers<A> {
913 ChatWidgetHandlers {
914 on_action: self.on_action.clone(),
915 on_send: self.on_send.clone(),
916 on_copy: self.on_copy.clone(),
917 on_retry: self.on_retry.clone(),
918 }
919 }
920
921 fn header(&self) -> View<A> {
923 let session = self.session.clone();
924 let title = session.to_text_with(|session| {
925 let (title, status, count) = session
926 .as_ref()
927 .map(|session| {
928 (
929 session.title.clone(),
930 session_status_label(session.status).to_string(),
931 session.messages.len(),
932 )
933 })
934 .unwrap_or_else(|| ("No session".into(), "idle".into(), 0));
935 format!("{title} - {status} - {count} msg")
936 });
937 Container::new()
938 .fill_width()
939 .height(if self.style.compact { 32.0 } else { 40.0 })
940 .background(self.style.header_background)
941 .radius(self.style.header_radius)
942 .padding(6.0)
943 .child(
944 Row::new().gap(8.0).fill_width().child(
945 Container::new()
946 .fill_width()
947 .child(Text::new(title).style(self.style.text).nowrap()),
948 ),
949 )
950 .into_view()
951 }
952
953 fn messages(&self) -> View<A> {
955 if self.message_renderer.is_none() {
956 return ScrollView::vertical()
957 .follow_end(self.follow_latest)
958 .child(
959 View::leaf(ChatMessagesWidget {
960 layout: LayoutStyle::default().fill_width(),
961 session: self.session.clone(),
962 style: self.style.clone(),
963 handlers: self.handlers(),
964 geometry: Rc::new(RefCell::new(ChatMessagesGeometry::default())),
965 })
966 .fill_width(),
967 )
968 .fill_width()
969 .into_view();
970 }
971
972 let mut list = Column::new().gap(self.style.message_gap).fill_width();
973 let session = self.session.read();
974 match &session {
975 Some(session) if !session.messages.is_empty() => {
976 for message in &session.messages {
977 let rendered = self
978 .message_renderer
979 .as_ref()
980 .map(|renderer| renderer(message))
981 .unwrap_or_else(|| self.message_bubble(message));
982 list = list.child(rendered);
983 }
984 }
985 Some(_) => {
986 list = list.child(Text::new("No messages yet").style(self.style.muted));
987 }
988 None => {
989 list = list.child(Text::new("No chat session").style(self.style.muted));
990 }
991 }
992
993 ScrollView::vertical()
994 .follow_end(self.follow_latest)
995 .child(list)
996 .fill_width()
997 .into_view()
998 }
999
1000 fn message_bubble(&self, message: &ChatMessage) -> View<A> {
1002 let background = message_background(&self.style, message);
1003 let role = format!(
1004 "{} / {}{}",
1005 role_label(message.role),
1006 kind_label(message.kind),
1007 status_suffix(message.status)
1008 );
1009 let copy = ChatWidgetAction::Copy {
1010 item_id: message.id.clone(),
1011 text: message.text.clone(),
1012 };
1013 let copy_handlers = self.handlers();
1014 let mut actions = Row::new()
1015 .gap(6.0)
1016 .child(action_button("Copy", copy, copy_handlers));
1017 if message_is_retryable(message) {
1018 actions = actions.child(action_button(
1019 "Retry",
1020 ChatWidgetAction::Retry {
1021 item_id: message.id.clone(),
1022 },
1023 self.handlers(),
1024 ));
1025 }
1026 Container::new()
1027 .fill_width()
1028 .background(background)
1029 .radius(self.style.message_radius)
1030 .padding(if self.style.compact { 6.0 } else { 8.0 })
1031 .child(
1032 Column::new()
1033 .gap(4.0)
1034 .fill_width()
1035 .child(Text::new(role).style(self.style.role_text).nowrap())
1036 .child(
1037 Text::new(if message.text.is_empty() {
1038 "...".to_string()
1039 } else {
1040 message.text.clone()
1041 })
1042 .style(self.style.text)
1043 .wrap_anywhere(),
1044 )
1045 .child(actions),
1046 )
1047 .into_view()
1048 }
1049
1050 fn composer_resize_bar(&self, resize_start_height: Signal<Option<f32>>) -> View<A> {
1052 let current_height = self.composer_controls.clamped_height();
1053 let resize_handlers = self.handlers();
1054 ResizeBar::<A>::horizontal()
1055 .fill_width()
1056 .height(8.0)
1057 .resize_bar_style(ResizeBarStyle {
1058 hit_thickness: 8.0,
1059 line_thickness: 2.0,
1060 idle_color: self.style.input.border_focused,
1061 hover_color: self.style.input.border_focused,
1062 active_color: self.style.input.border_focused,
1063 ..ResizeBarStyle::default()
1064 })
1065 .on_resize_ctx(move |ctx, event| {
1066 let drag_start_height = match event.phase {
1067 ResizeDragPhase::Start => {
1068 resize_start_height.set(Some(current_height));
1069 current_height
1070 }
1071 ResizeDragPhase::Drag | ResizeDragPhase::End => {
1072 resize_start_height.read().unwrap_or(current_height)
1073 }
1074 };
1075 emit_chat_widget_action(
1076 ctx,
1077 &resize_handlers,
1078 ChatWidgetAction::SetComposerHeight {
1079 height: drag_start_height - event.total_delta,
1080 },
1081 );
1082 if event.phase == ResizeDragPhase::End {
1083 resize_start_height.set(None);
1084 }
1085 })
1086 .into_view()
1087 .key("ailloli_ui-chat-composer-resize-bar")
1088 }
1089
1090 fn composer(&self) -> View<A> {
1092 let draft = self.draft.clone();
1093 let handlers = self.handlers();
1094 let controls = self.composer_controls.clone();
1095 let draft_handlers = self.handlers();
1096 let height = controls.clamped_height();
1097 let content_height = (height - 14.0).max(0.0);
1098 let input_height = (content_height - 34.0).max(0.0);
1099 let selected_permission = controls.selected_permission.clone();
1100 let selected_model = controls.selected_model_id.clone().unwrap_or_default();
1101 let selected_reasoning = controls
1102 .selected_reasoning_level
1103 .clone()
1104 .unwrap_or_default();
1105 let mut permission_select = Select::<String, A>::new()
1106 .placeholder("permissions")
1107 .selected(selected_permission)
1108 .popup_placement(PopupPlacement::Top)
1109 .select_size(SelectSize::Compact)
1110 .width(122.0)
1111 .height(30.0)
1112 .disabled(controls.running || !controls.permission_enabled);
1113 for option in &controls.permission_options {
1114 permission_select =
1115 permission_select.option(option.value.clone(), option.label.clone());
1116 }
1117 let permission_handlers = self.handlers();
1118 permission_select = permission_select.on_change_ctx(move |ctx, value| {
1119 emit_chat_widget_action(
1120 ctx,
1121 &permission_handlers,
1122 ChatWidgetAction::SetComposerPermission { value },
1123 );
1124 });
1125
1126 let mut model_select = Select::<String, A>::new()
1127 .placeholder("model")
1128 .selected(selected_model)
1129 .popup_placement(PopupPlacement::Top)
1130 .select_size(SelectSize::Compact)
1131 .fill_width()
1132 .height(30.0)
1133 .disabled(controls.running || !controls.model_enabled)
1134 .option(String::new(), "Provider default");
1135 for option in &controls.model_options {
1136 model_select = model_select.option(option.value.clone(), option.label.clone());
1137 }
1138 let model_handlers = self.handlers();
1139 model_select = model_select.on_change_ctx(move |ctx, value| {
1140 emit_chat_widget_action(
1141 ctx,
1142 &model_handlers,
1143 ChatWidgetAction::SetComposerModel {
1144 model_id: (!value.is_empty()).then_some(value),
1145 },
1146 );
1147 });
1148
1149 let mut reasoning_select = Select::<String, A>::new()
1150 .placeholder("reasoning")
1151 .selected(selected_reasoning)
1152 .popup_placement(PopupPlacement::Top)
1153 .select_size(SelectSize::Compact)
1154 .width(92.0)
1155 .height(30.0)
1156 .disabled(
1157 controls.running
1158 || !controls.reasoning_enabled
1159 || controls.reasoning_options.is_empty(),
1160 )
1161 .option(String::new(), "default");
1162 for option in &controls.reasoning_options {
1163 reasoning_select = reasoning_select.option(option.value.clone(), option.label.clone());
1164 }
1165 let reasoning_handlers = self.handlers();
1166 reasoning_select = reasoning_select.on_change_ctx(move |ctx, value| {
1167 emit_chat_widget_action(
1168 ctx,
1169 &reasoning_handlers,
1170 ChatWidgetAction::SetComposerReasoning {
1171 reasoning_level: (!value.is_empty()).then_some(value),
1172 },
1173 );
1174 });
1175
1176 let button_handlers = handlers.clone();
1177 let running = controls.running;
1178 let button_icon = if running {
1179 LucideIcon::SquareStop
1180 } else {
1181 LucideIcon::Play
1182 };
1183 let button_variant = if running {
1184 ButtonVariant::Destructive
1185 } else {
1186 ButtonVariant::Primary
1187 };
1188
1189 Container::new()
1190 .fill_width()
1191 .height(height)
1192 .background(self.style.input.bg)
1193 .border(1.0, self.style.input.border)
1194 .radius(self.style.inline_button_radius)
1195 .padding(6.0)
1196 .clip_children(true)
1197 .child(
1198 Column::new()
1199 .gap(4.0)
1200 .fill_width()
1201 .child(
1202 TextInput::<A>::new()
1203 .bind(self.draft.clone())
1204 .multiline()
1205 .placeholder("Ask...")
1206 .input_style(TextInputStyle {
1207 bg: Color::TRANSPARENT,
1208 border: Color::TRANSPARENT,
1209 border_focused: Color::TRANSPARENT,
1210 radius: 0.0,
1211 ..self.style.input
1212 })
1213 .on_change_ctx(move |ctx, text| {
1214 emit_chat_widget_action(
1215 ctx,
1216 &draft_handlers,
1217 ChatWidgetAction::SetComposerDraft { text },
1218 );
1219 })
1220 .height(input_height)
1221 .fill_width()
1222 .into_view()
1223 .key("ailloli_ui-chat-composer-input"),
1224 )
1225 .child(
1226 Row::new()
1227 .gap(6.0)
1228 .fill_width()
1229 .child(
1230 permission_select
1231 .into_view()
1232 .key("ailloli_ui-chat-composer-permission-select"),
1233 )
1234 .child(
1235 model_select
1236 .into_view()
1237 .key("ailloli_ui-chat-composer-model-select"),
1238 )
1239 .child(
1240 reasoning_select
1241 .into_view()
1242 .key("ailloli_ui-chat-composer-reasoning-select"),
1243 )
1244 .child(
1245 Button::new()
1246 .variant(button_variant)
1247 .width(32.0)
1248 .height(30.0)
1249 .radius(self.style.inline_button_radius)
1250 .child(
1251 Icon::lucide(button_icon)
1252 .size(15.0)
1253 .into_view()
1254 .key("ailloli_ui-chat-composer-turn-button-icon"),
1255 )
1256 .on_click_ctx(move |ctx| {
1257 if running {
1258 emit_chat_widget_action(
1259 ctx,
1260 &button_handlers,
1261 ChatWidgetAction::StopTurn,
1262 );
1263 return;
1264 }
1265 let text = draft.read();
1266 if text.trim().is_empty() {
1267 return;
1268 }
1269 emit_chat_widget_action(
1270 ctx,
1271 &button_handlers,
1272 ChatWidgetAction::Send { text },
1273 );
1274 })
1275 .into_view()
1276 .key("ailloli_ui-chat-composer-turn-button"),
1277 ),
1278 ),
1279 )
1280 .into_view()
1281 }
1282}
1283
1284struct ChatMessagesWidget<A> {
1286 layout: LayoutStyle,
1288 session: Signal<Option<ChatSessionState>>,
1290 style: ChatWidgetStyle,
1292 handlers: ChatWidgetHandlers<A>,
1294 geometry: Rc<RefCell<ChatMessagesGeometry>>,
1296}
1297
1298#[derive(Clone, Default)]
1299struct ChatMessagesGeometry {
1301 width: f32,
1303 items: Vec<ChatMessageGeometry>,
1305 total_height: f32,
1307}
1308
1309#[derive(Clone)]
1310struct ChatMessageGeometry {
1312 item_id: ChatItemId,
1314 role_text: String,
1316 body_text: String,
1318 y: f32,
1320 height: f32,
1322 role_height: f32,
1324 body_height: f32,
1326 role_layout: Arc<PreparedTextLayout>,
1328 body_layout: Arc<PreparedTextLayout>,
1330 copy_rect: Rect,
1332 retry_rect: Option<Rect>,
1334}
1335
1336impl<A: 'static> Widget<A> for ChatMessagesWidget<A> {
1337 fn debug_name(&self) -> &'static str {
1339 "ChatMessages"
1340 }
1341
1342 fn layout(
1344 &self,
1345 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1346 ctx: &mut LayoutCtx<'_>,
1347 _children: &mut [LayoutChild],
1348 constraints: Constraints,
1349 ) -> LayoutResult {
1350 let width = constraints.max_w.max(0.0);
1351 let session = self.session.read();
1352 let geometry = match session.as_ref() {
1353 Some(session) if !session.messages.is_empty() => measure_chat_messages_geometry(
1354 ctx.text_system.as_deref_mut(),
1355 session,
1356 &self.style,
1357 width,
1358 ),
1359 _ => ChatMessagesGeometry {
1360 width,
1361 items: Vec::new(),
1362 total_height: self.style.text.px_size as f32 * 1.6,
1363 },
1364 };
1365 let height = match session.as_ref() {
1366 Some(session) if !session.messages.is_empty() => geometry.total_height,
1367 _ => self.style.text.px_size as f32 * 1.6,
1368 };
1369 *self.geometry.borrow_mut() = geometry;
1370 let size = apply_layout_size(Size::new(width, height.max(24.0)), self.layout, constraints);
1371 let viewport = Rect::new(0.0, 0.0, size.w, size.h);
1372 LayoutResult {
1373 size,
1374 children: Vec::new(),
1375 paint_bounds: viewport,
1376 visual_bounds: viewport,
1377 overlay_hit_bounds: Vec::new(),
1378 clip: None,
1379 is_window_root_clip: false,
1380 artifact: None,
1381 }
1382 }
1383
1384 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1386 let session = self.session.read();
1387 match session.as_ref() {
1388 Some(session) if !session.messages.is_empty() => {
1389 let Some(geometry) = self.geometry_for_paint(ctx, session, bounds.w) else {
1390 return;
1391 };
1392 for (message, item) in session.messages.iter().zip(geometry.items.iter()) {
1393 paint_message(
1394 ctx,
1395 bounds.x,
1396 bounds.y,
1397 bounds.w,
1398 &self.style,
1399 message,
1400 item,
1401 );
1402 }
1403 }
1404 Some(_) => paint_plain_text(
1405 ctx,
1406 "No messages yet",
1407 bounds.x,
1408 bounds.y,
1409 bounds.w,
1410 self.style.muted,
1411 ),
1412 None => paint_plain_text(
1413 ctx,
1414 "No chat session",
1415 bounds.x,
1416 bounds.y,
1417 bounds.w,
1418 self.style.muted,
1419 ),
1420 }
1421 }
1422
1423 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1425 let Event::Pointer(PointerEvent::Button {
1426 pos,
1427 button: MouseButton::Left,
1428 pressed: true,
1429 ..
1430 }) = event
1431 else {
1432 return;
1433 };
1434 if !bounds.contains(pos.x, pos.y) {
1435 return;
1436 }
1437 let Some(action) = self.action_at(bounds, pos.x, pos.y) else {
1438 return;
1439 };
1440 emit_chat_widget_action(ctx, &self.handlers, action);
1441 ctx.request_repaint();
1442 ctx.stop_propagation();
1443 }
1444}
1445
1446impl<A> ChatMessagesWidget<A> {
1447 fn geometry_for_paint(
1452 &self,
1453 ctx: &mut PaintCtx<'_>,
1454 session: &ChatSessionState,
1455 width: f32,
1456 ) -> Option<ChatMessagesGeometry> {
1457 let cached = self.geometry.borrow().clone();
1458 if cached.matches(session, width) {
1459 return Some(cached);
1460 }
1461
1462 let geometry = measure_chat_messages_geometry(
1463 ctx.text_system.as_deref_mut(),
1464 session,
1465 &self.style,
1466 width,
1467 );
1468 if geometry.matches(session, width) {
1469 *self.geometry.borrow_mut() = geometry.clone();
1470 Some(geometry)
1471 } else {
1472 None
1473 }
1474 }
1475
1476 fn action_at(&self, bounds: Rect, x: f32, y: f32) -> Option<ChatWidgetAction> {
1478 let session = self.session.read()?;
1479 let geometry = self.geometry.borrow();
1480 if !geometry.matches(&session, bounds.w) {
1481 return None;
1482 }
1483 let local_x = x - bounds.x;
1484 let local_y = y - bounds.y;
1485 for (message, item) in session.messages.iter().zip(geometry.items.iter()) {
1486 if item.copy_rect.contains(local_x, local_y) {
1487 return Some(ChatWidgetAction::Copy {
1488 item_id: message.id.clone(),
1489 text: message.text.clone(),
1490 });
1491 }
1492 if message_is_retryable(message)
1493 && item
1494 .retry_rect
1495 .is_some_and(|retry| retry.contains(local_x, local_y))
1496 {
1497 return Some(ChatWidgetAction::Retry {
1498 item_id: message.id.clone(),
1499 });
1500 }
1501 }
1502 None
1503 }
1504}
1505
1506fn paint_message(
1508 ctx: &mut PaintCtx<'_>,
1509 x: f32,
1510 y: f32,
1511 width: f32,
1512 style: &ChatWidgetStyle,
1513 message: &ChatMessage,
1514 geometry: &ChatMessageGeometry,
1515) -> f32 {
1516 let padding = message_padding(style);
1517 let message_y = y + geometry.y;
1518 let rect = Rect::new(x, message_y, width.max(0.0), geometry.height);
1519 debug_assert!(geometry.body_height >= 0.0);
1520
1521 ctx.push(DrawCmd::RRect(DrawRRect {
1522 rect,
1523 radius: style.message_radius,
1524 color: message_background(style, message),
1525 }));
1526 paint_layout(
1527 ctx,
1528 geometry.role_layout.clone(),
1529 x + padding,
1530 message_y + padding,
1531 style.role_text.color,
1532 );
1533 paint_layout(
1534 ctx,
1535 geometry.body_layout.clone(),
1536 x + padding,
1537 message_y + padding + geometry.role_height + 4.0,
1538 style.text.color,
1539 );
1540 paint_inline_button(
1541 ctx,
1542 rect_to_absolute(geometry.copy_rect, x, y),
1543 "Copy",
1544 style,
1545 );
1546 if let Some(retry) = geometry.retry_rect {
1547 paint_inline_button(ctx, rect_to_absolute(retry, x, y), "Retry", style);
1548 }
1549
1550 geometry.height
1551}
1552
1553fn paint_plain_text(
1555 ctx: &mut PaintCtx<'_>,
1556 text: &str,
1557 x: f32,
1558 y: f32,
1559 width: f32,
1560 style: TextStyle,
1561) {
1562 if let Some(layout) = layout_text(ctx, text, style, width, WrapMode::NoWrap) {
1563 paint_layout(ctx, layout, x, y, style.color);
1564 }
1565}
1566
1567fn paint_inline_button(ctx: &mut PaintCtx<'_>, rect: Rect, label: &str, style: &ChatWidgetStyle) {
1569 ctx.push(DrawCmd::RRect(DrawRRect {
1570 rect,
1571 radius: style.inline_button_radius,
1572 color: style.header_background.with_alpha(0.72),
1573 }));
1574 if let Some(layout) = layout_text(ctx, label, style.muted, rect.w, WrapMode::NoWrap) {
1575 let text_y = rect.y + (rect.h - text_layout_height(Some(&layout), style.muted)) * 0.5;
1576 paint_layout(ctx, layout, rect.x + 8.0, text_y, style.muted.color);
1577 }
1578}
1579
1580fn layout_text(
1584 ctx: &mut PaintCtx<'_>,
1585 text: &str,
1586 style: TextStyle,
1587 max_width: f32,
1588 wrap_mode: WrapMode,
1589) -> Option<Arc<PreparedTextLayout>> {
1590 let ts = ctx.text_system.as_deref_mut()?;
1591 Some(ts.layout_cached(TextLayoutParams {
1592 text,
1593 style,
1594 max_width: Some(max_width.max(0.0)),
1595 wrap_mode,
1596 }))
1597}
1598
1599fn paint_layout(
1601 ctx: &mut PaintCtx<'_>,
1602 layout: Arc<PreparedTextLayout>,
1603 x: f32,
1604 y: f32,
1605 color: Color,
1606) {
1607 let baseline = layout
1608 .lines
1609 .first()
1610 .map(|line| line.baseline_y)
1611 .unwrap_or(0.0);
1612 ctx.push(DrawCmd::Text(DrawText {
1613 pos: [x, y + baseline],
1614 color,
1615 decoration: ailloli_ui_core::TextDecoration::None,
1616 layout,
1617 }));
1618}
1619
1620fn text_layout_height(layout: Option<&Arc<PreparedTextLayout>>, style: TextStyle) -> f32 {
1622 layout
1623 .map(|layout| layout.metrics.height)
1624 .unwrap_or(style.px_size as f32 * 1.25)
1625}
1626
1627impl ChatMessagesGeometry {
1628 fn matches(&self, session: &ChatSessionState, width: f32) -> bool {
1632 if (self.width - width).abs() > 0.5 || self.items.len() != session.messages.len() {
1633 return false;
1634 }
1635 self.items
1636 .iter()
1637 .zip(session.messages.iter())
1638 .all(|(item, message)| {
1639 item.item_id == message.id
1640 && item.role_text == message_role_text(message)
1641 && item.body_text == message_body_text(message)
1642 })
1643 }
1644}
1645
1646fn measure_chat_messages_geometry(
1648 text_system: Option<&mut TextSystem>,
1649 session: &ChatSessionState,
1650 style: &ChatWidgetStyle,
1651 width: f32,
1652) -> ChatMessagesGeometry {
1653 if let Some(text_system) = text_system {
1654 measure_chat_messages_geometry_with_text_system(text_system, session, style, width)
1655 } else {
1656 let mut text_system = TextSystem::new();
1657 measure_chat_messages_geometry_with_text_system(&mut text_system, session, style, width)
1658 }
1659}
1660
1661fn measure_chat_messages_geometry_with_text_system(
1663 text_system: &mut TextSystem,
1664 session: &ChatSessionState,
1665 style: &ChatWidgetStyle,
1666 width: f32,
1667) -> ChatMessagesGeometry {
1668 let mut y = 0.0;
1669 let mut items = Vec::with_capacity(session.messages.len());
1670 for (idx, message) in session.messages.iter().enumerate() {
1671 if idx > 0 {
1672 y += style.message_gap;
1673 }
1674 let item = measure_message_geometry(text_system, message, style, width, y);
1675 y += item.height;
1676 items.push(item);
1677 }
1678 ChatMessagesGeometry {
1679 width,
1680 items,
1681 total_height: y,
1682 }
1683}
1684
1685fn measure_message_geometry(
1687 text_system: &mut TextSystem,
1688 message: &ChatMessage,
1689 style: &ChatWidgetStyle,
1690 width: f32,
1691 y: f32,
1692) -> ChatMessageGeometry {
1693 let padding = message_padding(style);
1694 let content_width = (width - padding * 2.0).max(0.0);
1695 let role_text = message_role_text(message);
1696 let body_text = message_body_text(message);
1697 let role_layout = text_system.layout_cached(TextLayoutParams {
1698 text: &role_text,
1699 style: style.role_text,
1700 max_width: Some(content_width),
1701 wrap_mode: WrapMode::NoWrap,
1702 });
1703 let body_layout = text_system.layout_cached(TextLayoutParams {
1704 text: &body_text,
1705 style: style.text,
1706 max_width: Some(content_width),
1707 wrap_mode: WrapMode::WordOrAnywhere,
1708 });
1709 let role_height = text_layout_height(Some(&role_layout), style.role_text);
1710 let body_height = text_layout_height(Some(&body_layout), style.text);
1711 let action_y = y + padding + role_height + 4.0 + body_height + 6.0;
1712 let copy_rect = Rect::new(padding, action_y, 48.0, action_button_height());
1713 let retry_rect = message_is_retryable(message)
1714 .then(|| Rect::new(padding + 54.0, action_y, 50.0, action_button_height()));
1715 ChatMessageGeometry {
1716 item_id: message.id.clone(),
1717 role_text,
1718 body_text,
1719 y,
1720 height: padding * 2.0 + role_height + 4.0 + body_height + 6.0 + action_button_height(),
1721 role_height,
1722 body_height,
1723 role_layout,
1724 body_layout,
1725 copy_rect,
1726 retry_rect,
1727 }
1728}
1729
1730fn rect_to_absolute(rect: Rect, x: f32, y: f32) -> Rect {
1732 Rect::new(x + rect.x, y + rect.y, rect.w, rect.h)
1733}
1734
1735fn message_role_text(message: &ChatMessage) -> String {
1737 format!(
1738 "{} / {}{}",
1739 role_label(message.role),
1740 kind_label(message.kind),
1741 status_suffix(message.status)
1742 )
1743}
1744
1745fn message_body_text(message: &ChatMessage) -> String {
1747 if message.text.is_empty() {
1748 "...".to_string()
1749 } else {
1750 message.text.clone()
1751 }
1752}
1753
1754fn message_is_retryable(message: &ChatMessage) -> bool {
1756 match message.role {
1757 ChatRole::User => true,
1758 ChatRole::Assistant => message.request_id.is_some(),
1759 ChatRole::System | ChatRole::Tool => false,
1760 }
1761}
1762
1763fn message_padding(style: &ChatWidgetStyle) -> f32 {
1765 if style.compact {
1766 6.0
1767 } else {
1768 8.0
1769 }
1770}
1771
1772fn action_button_height() -> f32 {
1774 22.0
1775}
1776
1777fn action_button<A: 'static>(
1779 label: &'static str,
1780 action: ChatWidgetAction,
1781 handlers: ChatWidgetHandlers<A>,
1782) -> Button<A> {
1783 Button::with_label_variant(label, ButtonVariant::Ghost)
1784 .height(24.0)
1785 .on_click_ctx(move |ctx| {
1786 emit_chat_widget_action(ctx, &handlers, action.clone());
1787 })
1788}
1789
1790fn emit_chat_widget_action<A>(
1792 ctx: &mut EventCtx<A>,
1793 handlers: &ChatWidgetHandlers<A>,
1794 action: ChatWidgetAction,
1795) {
1796 if let Some(handler) = &handlers.on_action {
1797 handler(ctx, action.clone());
1798 }
1799 match action {
1800 ChatWidgetAction::Send { text } => {
1801 if let Some(handler) = &handlers.on_send {
1802 handler(ctx, text);
1803 }
1804 }
1805 ChatWidgetAction::Copy { item_id, text } => {
1806 if let Some(handler) = &handlers.on_copy {
1807 handler(ctx, item_id, text);
1808 }
1809 }
1810 ChatWidgetAction::Retry { item_id } => {
1811 if let Some(handler) = &handlers.on_retry {
1812 handler(ctx, item_id);
1813 }
1814 }
1815 ChatWidgetAction::SetComposerDraft { .. }
1816 | ChatWidgetAction::SetComposerPermission { .. }
1817 | ChatWidgetAction::SetComposerModel { .. }
1818 | ChatWidgetAction::SetComposerReasoning { .. }
1819 | ChatWidgetAction::SetComposerHeight { .. }
1820 | ChatWidgetAction::StopTurn => {}
1821 }
1822}
1823
1824fn message_background(style: &ChatWidgetStyle, message: &ChatMessage) -> Color {
1826 if message.kind == ChatMessageKind::Error || message.status == ChatMessageStatus::Failed {
1827 return style.error_background;
1828 }
1829 match message.role {
1830 ChatRole::User => style.user_background,
1831 ChatRole::Assistant => style.assistant_background,
1832 ChatRole::System | ChatRole::Tool => style.tool_background,
1833 }
1834}
1835
1836fn role_label(role: ChatRole) -> &'static str {
1838 match role {
1839 ChatRole::System => "system",
1840 ChatRole::User => "user",
1841 ChatRole::Assistant => "assistant",
1842 ChatRole::Tool => "tool",
1843 }
1844}
1845
1846fn kind_label(kind: ChatMessageKind) -> &'static str {
1848 match kind {
1849 ChatMessageKind::Text => "text",
1850 ChatMessageKind::Reasoning => "reasoning",
1851 ChatMessageKind::Command => "command",
1852 ChatMessageKind::FileChange => "file",
1853 ChatMessageKind::ToolCall => "tool",
1854 ChatMessageKind::Status => "status",
1855 ChatMessageKind::Error => "error",
1856 }
1857}
1858
1859fn status_suffix(status: ChatMessageStatus) -> &'static str {
1861 match status {
1862 ChatMessageStatus::Pending => " pending",
1863 ChatMessageStatus::Streaming => " streaming",
1864 ChatMessageStatus::Complete => "",
1865 ChatMessageStatus::Failed => " failed",
1866 }
1867}
1868
1869fn session_status_label(status: ChatSessionStatus) -> &'static str {
1871 match status {
1872 ChatSessionStatus::Idle => "idle",
1873 ChatSessionStatus::Ready => "ready",
1874 ChatSessionStatus::Running => "running",
1875 ChatSessionStatus::Waiting => "waiting",
1876 ChatSessionStatus::Failed => "failed",
1877 ChatSessionStatus::Completed => "completed",
1878 }
1879}