1use std::cell::RefCell;
2use std::rc::Rc;
3use std::sync::Arc;
4
5use anyhow::{bail, Context as _, Result};
6use futures::AsyncReadExt as _;
7use gpui::{AppContext, DismissEvent, FocusHandle, FocusableView, Task, View, WeakModel, WeakView};
8use html_to_markdown::{convert_html_to_markdown, markdown, TagHandler};
9use http_client::{AsyncBody, HttpClientWithUrl};
10use picker::{Picker, PickerDelegate};
11use ui::{prelude::*, ListItem, ViewContext};
12use workspace::Workspace;
13
14use crate::context_picker::{ConfirmBehavior, ContextPicker};
15use crate::context_store::ContextStore;
16
17pub struct FetchContextPicker {
18 picker: View<Picker<FetchContextPickerDelegate>>,
19}
20
21impl FetchContextPicker {
22 pub fn new(
23 context_picker: WeakView<ContextPicker>,
24 workspace: WeakView<Workspace>,
25 context_store: WeakModel<ContextStore>,
26 confirm_behavior: ConfirmBehavior,
27 cx: &mut ViewContext<Self>,
28 ) -> Self {
29 let delegate = FetchContextPickerDelegate::new(
30 context_picker,
31 workspace,
32 context_store,
33 confirm_behavior,
34 );
35 let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
36
37 Self { picker }
38 }
39}
40
41impl FocusableView for FetchContextPicker {
42 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
43 self.picker.focus_handle(cx)
44 }
45}
46
47impl Render for FetchContextPicker {
48 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
49 self.picker.clone()
50 }
51}
52
53#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
54enum ContentType {
55 Html,
56 Plaintext,
57 Json,
58}
59
60pub struct FetchContextPickerDelegate {
61 context_picker: WeakView<ContextPicker>,
62 workspace: WeakView<Workspace>,
63 context_store: WeakModel<ContextStore>,
64 confirm_behavior: ConfirmBehavior,
65 url: String,
66}
67
68impl FetchContextPickerDelegate {
69 pub fn new(
70 context_picker: WeakView<ContextPicker>,
71 workspace: WeakView<Workspace>,
72 context_store: WeakModel<ContextStore>,
73 confirm_behavior: ConfirmBehavior,
74 ) -> Self {
75 FetchContextPickerDelegate {
76 context_picker,
77 workspace,
78 context_store,
79 confirm_behavior,
80 url: String::new(),
81 }
82 }
83
84 async fn build_message(http_client: Arc<HttpClientWithUrl>, url: &str) -> Result<String> {
85 let prefixed_url = if !url.starts_with("https://") && !url.starts_with("http://") {
86 Some(format!("https://{url}"))
87 } else {
88 None
89 };
90 let url = prefixed_url.as_deref().unwrap_or(url);
91
92 let mut response = http_client.get(&url, AsyncBody::default(), true).await?;
93
94 let mut body = Vec::new();
95 response
96 .body_mut()
97 .read_to_end(&mut body)
98 .await
99 .context("error reading response body")?;
100
101 if response.status().is_client_error() {
102 let text = String::from_utf8_lossy(body.as_slice());
103 bail!(
104 "status error {}, response: {text:?}",
105 response.status().as_u16()
106 );
107 }
108
109 let Some(content_type) = response.headers().get("content-type") else {
110 bail!("missing Content-Type header");
111 };
112 let content_type = content_type
113 .to_str()
114 .context("invalid Content-Type header")?;
115 let content_type = match content_type {
116 "text/html" => ContentType::Html,
117 "text/plain" => ContentType::Plaintext,
118 "application/json" => ContentType::Json,
119 _ => ContentType::Html,
120 };
121
122 match content_type {
123 ContentType::Html => {
124 let mut handlers: Vec<TagHandler> = vec![
125 Rc::new(RefCell::new(markdown::WebpageChromeRemover)),
126 Rc::new(RefCell::new(markdown::ParagraphHandler)),
127 Rc::new(RefCell::new(markdown::HeadingHandler)),
128 Rc::new(RefCell::new(markdown::ListHandler)),
129 Rc::new(RefCell::new(markdown::TableHandler::new())),
130 Rc::new(RefCell::new(markdown::StyledTextHandler)),
131 ];
132 if url.contains("wikipedia.org") {
133 use html_to_markdown::structure::wikipedia;
134
135 handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaChromeRemover)));
136 handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaInfoboxHandler)));
137 handlers.push(Rc::new(
138 RefCell::new(wikipedia::WikipediaCodeHandler::new()),
139 ));
140 } else {
141 handlers.push(Rc::new(RefCell::new(markdown::CodeHandler)));
142 }
143
144 convert_html_to_markdown(&body[..], &mut handlers)
145 }
146 ContentType::Plaintext => Ok(std::str::from_utf8(&body)?.to_owned()),
147 ContentType::Json => {
148 let json: serde_json::Value = serde_json::from_slice(&body)?;
149
150 Ok(format!(
151 "```json\n{}\n```",
152 serde_json::to_string_pretty(&json)?
153 ))
154 }
155 }
156 }
157}
158
159impl PickerDelegate for FetchContextPickerDelegate {
160 type ListItem = ListItem;
161
162 fn match_count(&self) -> usize {
163 if self.url.is_empty() {
164 0
165 } else {
166 1
167 }
168 }
169
170 fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
171 "Enter the URL that you would like to fetch".into()
172 }
173
174 fn selected_index(&self) -> usize {
175 0
176 }
177
178 fn set_selected_index(&mut self, _ix: usize, _cx: &mut ViewContext<Picker<Self>>) {}
179
180 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
181 "Enter a URL…".into()
182 }
183
184 fn update_matches(&mut self, query: String, _cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
185 self.url = query;
186
187 Task::ready(())
188 }
189
190 fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
191 let Some(workspace) = self.workspace.upgrade() else {
192 return;
193 };
194
195 let http_client = workspace.read(cx).client().http_client().clone();
196 let url = self.url.clone();
197 let confirm_behavior = self.confirm_behavior;
198 cx.spawn(|this, mut cx| async move {
199 let text = Self::build_message(http_client, &url).await?;
200
201 this.update(&mut cx, |this, cx| {
202 this.delegate
203 .context_store
204 .update(cx, |context_store, _cx| {
205 if context_store.includes_url(&url).is_none() {
206 context_store.insert_fetched_url(url, text);
207 }
208 })?;
209
210 match confirm_behavior {
211 ConfirmBehavior::KeepOpen => {}
212 ConfirmBehavior::Close => this.delegate.dismissed(cx),
213 }
214
215 anyhow::Ok(())
216 })??;
217
218 anyhow::Ok(())
219 })
220 .detach_and_log_err(cx);
221 }
222
223 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
224 self.context_picker
225 .update(cx, |this, cx| {
226 this.reset_mode();
227 cx.emit(DismissEvent);
228 })
229 .ok();
230 }
231
232 fn render_match(
233 &self,
234 ix: usize,
235 selected: bool,
236 cx: &mut ViewContext<Picker<Self>>,
237 ) -> Option<Self::ListItem> {
238 let added = self.context_store.upgrade().map_or(false, |context_store| {
239 context_store.read(cx).includes_url(&self.url).is_some()
240 });
241
242 Some(
243 ListItem::new(ix)
244 .inset(true)
245 .toggle_state(selected)
246 .child(Label::new(self.url.clone()))
247 .when(added, |child| {
248 child.disabled(true).end_slot(
249 h_flex()
250 .gap_1()
251 .child(
252 Icon::new(IconName::Check)
253 .size(IconSize::Small)
254 .color(Color::Success),
255 )
256 .child(Label::new("Added").size(LabelSize::Small)),
257 )
258 }),
259 )
260 }
261}