
There's still a bit more work to do on this, but this PR is compiling (with warnings) after eliminating the key types. When the tasks below are complete, this will be the new narrative for GPUI: - `Entity<T>` - This replaces `View<T>`/`Model<T>`. It represents a unit of state, and if `T` implements `Render`, then `Entity<T>` implements `Element`. - `&mut App` This replaces `AppContext` and represents the app. - `&mut Context<T>` This replaces `ModelContext` and derefs to `App`. It is provided by the framework when updating an entity. - `&mut Window` Broken out of `&mut WindowContext` which no longer exists. Every method that once took `&mut WindowContext` now takes `&mut Window, &mut App` and every method that took `&mut ViewContext<T>` now takes `&mut Window, &mut Context<T>` Not pictured here are the two other failed attempts. It's been quite a month! Tasks: - [x] Remove `View`, `ViewContext`, `WindowContext` and thread through `Window` - [x] [@cole-miller @mikayla-maki] Redraw window when entities change - [x] [@cole-miller @mikayla-maki] Get examples and Zed running - [x] [@cole-miller @mikayla-maki] Fix Zed rendering - [x] [@mikayla-maki] Fix todo! macros and comments - [x] Fix a bug where the editor would not be redrawn because of view caching - [x] remove publicness window.notify() and replace with `AppContext::notify` - [x] remove `observe_new_window_models`, replace with `observe_new_models` with an optional window - [x] Fix a bug where the project panel would not be redrawn because of the wrong refresh() call being used - [x] Fix the tests - [x] Fix warnings by eliminating `Window` params or using `_` - [x] Fix conflicts - [x] Simplify generic code where possible - [x] Rename types - [ ] Update docs ### issues post merge - [x] Issues switching between normal and insert mode - [x] Assistant re-rendering failure - [x] Vim test failures - [x] Mac build issue Release Notes: - N/A --------- Co-authored-by: Antonio Scandurra <me@as-cii.com> Co-authored-by: Cole Miller <cole@zed.dev> Co-authored-by: Mikayla <mikayla@zed.dev> Co-authored-by: Joseph <joseph@zed.dev> Co-authored-by: max <max@zed.dev> Co-authored-by: Michael Sloan <michael@zed.dev> Co-authored-by: Mikayla Maki <mikaylamaki@Mikaylas-MacBook-Pro.local> Co-authored-by: Mikayla <mikayla.c.maki@gmail.com> Co-authored-by: joão <joao@zed.dev>
180 lines
5.8 KiB
Rust
180 lines
5.8 KiB
Rust
use std::cell::RefCell;
|
|
use std::rc::Rc;
|
|
use std::sync::atomic::AtomicBool;
|
|
use std::sync::Arc;
|
|
|
|
use anyhow::{anyhow, bail, Context, Result};
|
|
use assistant_slash_command::{
|
|
ArgumentCompletion, SlashCommand, SlashCommandOutput, SlashCommandOutputSection,
|
|
SlashCommandResult,
|
|
};
|
|
use futures::AsyncReadExt;
|
|
use gpui::{Task, WeakEntity};
|
|
use html_to_markdown::{convert_html_to_markdown, markdown, TagHandler};
|
|
use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
|
|
use language::{BufferSnapshot, LspAdapterDelegate};
|
|
use ui::prelude::*;
|
|
use workspace::Workspace;
|
|
|
|
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
|
|
enum ContentType {
|
|
Html,
|
|
Plaintext,
|
|
Json,
|
|
}
|
|
|
|
pub struct FetchSlashCommand;
|
|
|
|
impl FetchSlashCommand {
|
|
async fn build_message(http_client: Arc<HttpClientWithUrl>, url: &str) -> Result<String> {
|
|
let mut url = url.to_owned();
|
|
if !url.starts_with("https://") && !url.starts_with("http://") {
|
|
url = format!("https://{url}");
|
|
}
|
|
|
|
let mut response = http_client.get(&url, AsyncBody::default(), true).await?;
|
|
|
|
let mut body = Vec::new();
|
|
response
|
|
.body_mut()
|
|
.read_to_end(&mut body)
|
|
.await
|
|
.context("error reading response body")?;
|
|
|
|
if response.status().is_client_error() {
|
|
let text = String::from_utf8_lossy(body.as_slice());
|
|
bail!(
|
|
"status error {}, response: {text:?}",
|
|
response.status().as_u16()
|
|
);
|
|
}
|
|
|
|
let Some(content_type) = response.headers().get("content-type") else {
|
|
bail!("missing Content-Type header");
|
|
};
|
|
let content_type = content_type
|
|
.to_str()
|
|
.context("invalid Content-Type header")?;
|
|
let content_type = match content_type {
|
|
"text/html" => ContentType::Html,
|
|
"text/plain" => ContentType::Plaintext,
|
|
"application/json" => ContentType::Json,
|
|
_ => ContentType::Html,
|
|
};
|
|
|
|
match content_type {
|
|
ContentType::Html => {
|
|
let mut handlers: Vec<TagHandler> = vec![
|
|
Rc::new(RefCell::new(markdown::WebpageChromeRemover)),
|
|
Rc::new(RefCell::new(markdown::ParagraphHandler)),
|
|
Rc::new(RefCell::new(markdown::HeadingHandler)),
|
|
Rc::new(RefCell::new(markdown::ListHandler)),
|
|
Rc::new(RefCell::new(markdown::TableHandler::new())),
|
|
Rc::new(RefCell::new(markdown::StyledTextHandler)),
|
|
];
|
|
if url.contains("wikipedia.org") {
|
|
use html_to_markdown::structure::wikipedia;
|
|
|
|
handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaChromeRemover)));
|
|
handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaInfoboxHandler)));
|
|
handlers.push(Rc::new(
|
|
RefCell::new(wikipedia::WikipediaCodeHandler::new()),
|
|
));
|
|
} else {
|
|
handlers.push(Rc::new(RefCell::new(markdown::CodeHandler)));
|
|
}
|
|
|
|
convert_html_to_markdown(&body[..], &mut handlers)
|
|
}
|
|
ContentType::Plaintext => Ok(std::str::from_utf8(&body)?.to_owned()),
|
|
ContentType::Json => {
|
|
let json: serde_json::Value = serde_json::from_slice(&body)?;
|
|
|
|
Ok(format!(
|
|
"```json\n{}\n```",
|
|
serde_json::to_string_pretty(&json)?
|
|
))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl SlashCommand for FetchSlashCommand {
|
|
fn name(&self) -> String {
|
|
"fetch".into()
|
|
}
|
|
|
|
fn description(&self) -> String {
|
|
"Insert fetched URL contents".into()
|
|
}
|
|
|
|
fn icon(&self) -> IconName {
|
|
IconName::Globe
|
|
}
|
|
|
|
fn menu_text(&self) -> String {
|
|
self.description()
|
|
}
|
|
|
|
fn requires_argument(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
fn complete_argument(
|
|
self: Arc<Self>,
|
|
_arguments: &[String],
|
|
_cancel: Arc<AtomicBool>,
|
|
_workspace: Option<WeakEntity<Workspace>>,
|
|
_window: &mut Window,
|
|
_cx: &mut App,
|
|
) -> Task<Result<Vec<ArgumentCompletion>>> {
|
|
Task::ready(Ok(Vec::new()))
|
|
}
|
|
|
|
fn run(
|
|
self: Arc<Self>,
|
|
arguments: &[String],
|
|
_context_slash_command_output_sections: &[SlashCommandOutputSection<language::Anchor>],
|
|
_context_buffer: BufferSnapshot,
|
|
workspace: WeakEntity<Workspace>,
|
|
_delegate: Option<Arc<dyn LspAdapterDelegate>>,
|
|
_: &mut Window,
|
|
cx: &mut App,
|
|
) -> Task<SlashCommandResult> {
|
|
let Some(argument) = arguments.first() else {
|
|
return Task::ready(Err(anyhow!("missing URL")));
|
|
};
|
|
let Some(workspace) = workspace.upgrade() else {
|
|
return Task::ready(Err(anyhow!("workspace was dropped")));
|
|
};
|
|
|
|
let http_client = workspace.read(cx).client().http_client();
|
|
let url = argument.to_string();
|
|
|
|
let text = cx.background_executor().spawn({
|
|
let url = url.clone();
|
|
async move { Self::build_message(http_client, &url).await }
|
|
});
|
|
|
|
let url = SharedString::from(url);
|
|
cx.foreground_executor().spawn(async move {
|
|
let text = text.await?;
|
|
if text.trim().is_empty() {
|
|
bail!("no textual content found");
|
|
}
|
|
|
|
let range = 0..text.len();
|
|
Ok(SlashCommandOutput {
|
|
text,
|
|
sections: vec![SlashCommandOutputSection {
|
|
range,
|
|
icon: IconName::Globe,
|
|
label: format!("fetch {}", url).into(),
|
|
metadata: None,
|
|
}],
|
|
run_commands_in_text: false,
|
|
}
|
|
.to_event_stream())
|
|
})
|
|
}
|
|
}
|