Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 148 additions & 60 deletions src/conversation/skills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::time::Duration;
use url::Url;

const CATALOG: &str = "https://skills.sh";
const PREFETCH_ROWS: usize = 5;
const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;

async fn fetch_catalog_response(url: Url) -> anyhow::Result<Vec<u8>> {
Expand Down Expand Up @@ -65,8 +66,8 @@ impl Skill {
let action = format!("Open {} on skills.sh", self.name);
h_flex()
.min_w_0()
.h_full()
.gap_3()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
Expand Down Expand Up @@ -117,9 +118,33 @@ struct CatalogPage {
has_more: bool,
}

#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Ranking {
#[default]
AllTime,
Trending,
Hot,
}

impl Ranking {
const TABS: [(Self, &'static str); 3] = [
(Self::AllTime, "All time"),
(Self::Trending, "Trending"),
(Self::Hot, "Hot"),
];

fn path(self) -> &'static str {
match self {
Self::AllTime => "all-time",
Self::Trending => "trending",
Self::Hot => "hot",
}
}
}

#[derive(Clone)]
enum Request {
Browse(usize),
Browse(Ranking, usize),
Search(String),
}

Expand All @@ -128,7 +153,9 @@ impl Request {
// Use the public directory endpoints used by the skills.sh website.
// The documented v1 endpoints require a Vercel project token.
let mut url = match &self {
Self::Browse(page) => Url::parse(&format!("{CATALOG}/api/skills/all-time/{page}"))?,
Self::Browse(ranking, page) => {
Url::parse(&format!("{CATALOG}/api/skills/{}/{page}", ranking.path()))?
}
Self::Search(_) => Url::parse(&format!("{CATALOG}/api/search"))?,
};
if let Self::Search(query) = &self {
Expand All @@ -144,11 +171,12 @@ pub(super) struct Skills {
input: Entity<InputState>,
executor: tokio::runtime::Handle,
query: String,
ranking: Ranking,
rows: Vec<Skill>,
next_page: Option<usize>,
failed: Option<Request>,
pending: Option<Task<()>>,
scroll: ScrollHandle,
scroll: UniformListScrollHandle,
detail: Option<SkillDetail>,
}

Expand All @@ -165,13 +193,9 @@ impl Skills {
let query = value.trim();
if view.query != query {
view.query = query.to_owned();
view.rows.clear();
view.next_page = None;
view.failed = None;
view.pending = None;
view.scroll.set_offset(Point::default());
view.reset_results();
if query.is_empty() {
view.load(Request::Browse(0), cx);
view.load(Request::Browse(view.ranking, 0), cx);
} else if query.chars().count() >= 2 {
view.load(Request::Search(query.to_owned()), cx);
}
Expand All @@ -184,15 +208,28 @@ impl Skills {
input,
executor,
query: String::new(),
ranking: Ranking::default(),
rows: Vec::new(),
next_page: None,
failed: None,
pending: None,
scroll: ScrollHandle::new(),
scroll: UniformListScrollHandle::new(),
detail: None,
}
}

fn reset_results(&mut self) {
self.rows.clear();
self.next_page = None;
self.failed = None;
self.pending = None;
self.scroll
.0
.borrow()
.base_handle
.set_offset(Point::default());
}

fn load(&mut self, request: Request, cx: &mut Context<Self>) {
self.failed = None;
let executor = self.executor.clone();
Expand All @@ -205,7 +242,7 @@ impl Skills {
match page {
Ok(Ok(page)) => {
view.next_page = match request {
Request::Browse(index) if page.has_more => Some(index + 1),
Request::Browse(_, index) if page.has_more => Some(index + 1),
_ => None,
};
view.rows.extend(page.skills);
Expand All @@ -218,6 +255,48 @@ impl Skills {
}));
cx.notify();
}

fn prefetch_next_page(&self, window: &Window, cx: &mut Context<Self>) {
let Some(page) = self.next_page else {
return;
};
if self.pending.is_some() || self.failed.is_some() {
return;
}

let ranking = self.ranking;
// Start the request after layout and recheck in case another pass queued it.
cx.defer_in(window, move |view, _, cx| {
if view.ranking == ranking
&& view.query.is_empty()
&& view.detail.is_none()
&& view.next_page == Some(page)
&& view.pending.is_none()
&& view.failed.is_none()
{
view.load(Request::Browse(ranking, page), cx);
}
});
}

fn catalog_footer(&self, status: Option<&'static str>, cx: &Context<Self>) -> Div {
h_flex()
.gap_2()
.when_some(status, |row, message| {
row.child(control!(message, hint(message, cx)))
})
.when_some(self.failed.clone(), |row, request| {
row.child(control!(
"Retry",
Button::new("retry-skills")
.small()
.label("Retry")
.on_click(cx.listener(move |view, _, _, cx| {
view.load(request.clone(), cx);
}))
))
})
}
}

impl Render for Skills {
Expand All @@ -242,6 +321,36 @@ impl Render for Skills {
None
};

let list = uniform_list(
"skills-results",
self.rows.len() + usize::from(status.is_some()),
cx.processor(move |view, range: std::ops::Range<usize>, window, cx| {
if !range.is_empty() && range.end.saturating_add(PREFETCH_ROWS) >= view.rows.len() {
view.prefetch_next_page(window, cx);
}
range
.map(|index| {
let row = match view.rows.get(index) {
Some(skill) => skill.row(index, cx),
None => view.catalog_footer(status, cx),
};
h_flex().w_full().h(rems(3.5)).justify_center().child(
v_flex()
.size_full()
.max_w(px(720.))
.px_4()
.justify_center()
.child(row),
)
})
.collect::<Vec<_>>()
}),
)
.size_full()
.pb_5()
.with_sizing_behavior(ListSizingBehavior::Auto)
.track_scroll(self.scroll.clone());

v_flex()
.flex_1()
.min_h_0()
Expand All @@ -260,58 +369,37 @@ impl Render for Skills {
.prefix(Icon::new(IconName::Search))
.cleanable(true)
))
.child(label(if browse {
"Popular skills"
} else {
"Search results"
})),
.when(browse, |header| {
header.child(h_flex().gap_1().children(Ranking::TABS.map(
|(ranking, title)| {
control!(
title,
crate::ui::choice(
ranking.path(),
title,
self.ranking == ranking
)
.on_click(cx.listener(
move |view, _, _, cx| {
if view.ranking != ranking {
view.ranking = ranking;
view.reset_results();
view.load(Request::Browse(ranking, 0), cx);
}
}
))
)
},
)))
})
.when(!browse, |header| header.child(label("Search results"))),
)
.child(
crate::ui::keyboard_scroll_area("skills-list", &self.scroll, window, cx)
crate::ui::keyboard_scroll_viewport("skills-list", &self.scroll, window, cx)
.w_full()
.flex_1()
.min_h_0()
.overflow_y_scroll()
.child(
v_flex().items_center().w_full().child(
v_flex()
.w_full()
.max_w(px(720.))
.px_4()
.pb_5()
.children(
self.rows
.iter()
.enumerate()
.map(|(index, skill)| skill.row(index, cx)),
)
.when_some(status, |list, message| {
list.child(control!(message, hint(message, cx).py_3()))
})
.when_some(self.failed.clone(), |list, request| {
list.child(
Button::new("retry-skills")
.small()
.label("Retry")
.on_click(cx.listener(move |view, _, _, cx| {
view.load(request.clone(), cx)
})),
)
})
.when(self.pending.is_none() && self.failed.is_none(), |list| {
list.when_some(self.next_page, |list, page| {
list.child(
Button::new("more-skills")
.small()
.label("Load more")
.on_click(cx.listener(move |view, _, _, cx| {
view.load(Request::Browse(page), cx)
})),
)
})
}),
),
),
.child(list),
)
}
}
Expand Down Expand Up @@ -343,7 +431,7 @@ impl Desktop {
let skills = self.skills.get_or_insert_with(|| {
cx.new(|cx| {
let mut skills = Skills::new(self.executor.clone(), window, cx);
skills.load(Request::Browse(0), cx);
skills.load(Request::Browse(skills.ranking, 0), cx);
skills
})
});
Expand Down
Loading