Skip to content

Commit

Permalink
refactor: remove dependency of Search in on_article_submit
Browse files Browse the repository at this point in the history
  • Loading branch information
Builditluc committed Aug 14, 2023
1 parent 5a1f133 commit b71ecb4
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 81 deletions.
12 changes: 5 additions & 7 deletions src/ui/article/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@ use crate::ui::utils::{display_dialog, display_error, display_message};
use crate::ui::views::{RootLayout, StatusBar};
use crate::wiki::article::link_data::InternalData;
use crate::wiki::article::{Article, Link, Property};
use crate::wiki::language::Language;
use crate::wiki::search::Namespace;
use crate::wiki::search::{Namespace, SearchResult};

use anyhow::{Context, Result};
use cursive::view::{Nameable, Resizable};
use cursive::views::{LastSizeView, LinearLayout, OnEventView, TextView};
use cursive::Cursive;
use url::Url;

mod content;
mod lines;
Expand All @@ -26,12 +24,12 @@ const SUPPORTED_NAMESPACES: [Namespace; 1] = [Namespace::Main];

/// Fetches an article from a given id and displays it. It's the on_submit callback for
/// the search results view
pub fn on_article_submit(siv: &mut Cursive, pageid: usize, endpoint: Url, language: Language) {
pub fn on_article_submit(siv: &mut Cursive, search_result: &SearchResult) {
let article = match Article::builder()
.pageid(pageid)
.endpoint(endpoint)
.pageid(search_result.pageid)
.endpoint(search_result.endpoint.clone())
.properties(ARTICLE_PROPERTIES.to_vec())
.language(language)
.language(search_result.language.clone())
.fetch()
.context("failed fetching the article")
{
Expand Down
41 changes: 18 additions & 23 deletions src/ui/search/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,28 +82,6 @@ pub fn display_search_results(siv: &mut Cursive, search: Search) -> Result<()> {

let query = search.query.clone();

// create the results view (SelectView)
let search_results_view = {
let endpoint = search.endpoint.clone();
let results = search.results.clone();
let language = search.language.clone();
let mut search_results_view = SelectView::<SearchResult>::new()
.on_select(on_result_select)
.on_submit(move |siv, x| {
on_article_submit(siv, x.pageid(), endpoint.clone(), language.clone())
});

// fill results view with results
for search_result in results.into_iter() {
search_results_view.add_item(search_result.title().to_string(), search_result);
}
search_results_view
}
.with_name(search_results_view_name)
.full_height()
.fixed_width(search_results_width)
.scrollable();

// create the preview view (TextView)
let search_result_preview = TextView::new("")
.h_align(HAlign::Left)
Expand All @@ -129,6 +107,23 @@ pub fn display_search_results(siv: &mut Cursive, search: Search) -> Result<()> {

debug!("created the views for the search results layout");

// create the results view (SelectView)
let search_results_view = {
let mut search_results_view = SelectView::<SearchResult>::new()
.on_select(on_result_select)
.on_submit(on_article_submit);

// fill results view with results
for search_result in search.results.into_iter() {
search_results_view.add_item(search_result.title.to_string(), search_result);
}
search_results_view
}
.with_name(search_results_view_name)
.full_height()
.fixed_width(search_results_width)
.scrollable();

// pack results view and continue button in a layout
let search_results_layout = LinearLayout::vertical()
.child(search_results_view)
Expand Down Expand Up @@ -189,7 +184,7 @@ pub fn display_more_search_results(siv: &mut Cursive, search: Search) -> Result<

// add the new results to the view
for search_result in search.results.clone().into_iter() {
search_results_views.add_item(search_result.title().to_string(), search_result)
search_results_views.add_item(search_result.title.to_string(), search_result)
}
debug!("added the results to the results view");

Expand Down
3 changes: 1 addition & 2 deletions src/ui/search/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ pub fn on_search(siv: &mut Cursive, query: &str) {
fn on_result_select(siv: &mut Cursive, item: &SearchResult) {
info!(
"selecting the item '{}', page id: '{}'",
item.title(),
item.pageid()
item.title, item.pageid,
);

let layer_len = siv.screen_mut().len();
Expand Down
12 changes: 6 additions & 6 deletions src/ui/search/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ pub fn generate_and_display_preview(
view_name: &str,
) -> Result<()> {
// check if we even have a preview snippet
if item.snippet().is_none() {
if item.snippet.is_none() {
bail!("no preview snippet found");
}

let snippet = item.snippet().unwrap();
let snippet = item.snippet.clone().unwrap();
let mut preview = StyledString::new();

log::debug!("snippet: '{}'", snippet);

// add the title of the item to the preview
preview.append_plain(format!("{}\n", item.title()));
preview.append_plain(format!("{}\n", item.title));

let split_snippet: Vec<&str> = snippet.split(r#"<span class="searchmatch">"#).collect();

Expand Down Expand Up @@ -64,17 +64,17 @@ pub fn generate_and_display_info(
) -> Result<()> {
let mut info = StyledString::new();

info.append_plain(&format!("Title: {}", item.title()));
info.append_plain(&format!("Title: {}", item.title));
debug!("added the title to the info");

// add the wordcount to the info if available
if let Some(wordcount) = item.wordcount() {
if let Some(ref wordcount) = item.wordcount {
info.append_plain(&format!("\nWord count: {} words", wordcount));
debug!("added the wordcount to the info");
}

// add the formatted timestamp to the info if available
if let Some(timestamp) = item.timestamp() {
if let Some(ref timestamp) = item.timestamp {
match DateTime::parse_from_rfc3339(timestamp) {
Ok(formatted_time) => info.append_plain(&format!(
"\nLast Edited: {}",
Expand Down
83 changes: 40 additions & 43 deletions src/wiki/search.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{Context, Result};
use reqwest::blocking::{Client, Response};
use serde::Deserialize;
use serde_repr::Deserialize_repr;
use std::fmt::Display;
use url::Url;
Expand Down Expand Up @@ -48,46 +47,19 @@ pub struct SearchContinue {
pub offset: usize,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Debug, Clone)]
pub struct SearchResult {
#[serde(rename = "ns")]
namespace: Namespace,
title: String,
pageid: usize,
size: Option<usize>,
wordcount: Option<usize>,
snippet: Option<String>,
timestamp: Option<String>,
}

impl SearchResult {
pub fn namespace(&self) -> Namespace {
self.namespace.clone()
}

pub fn title(&self) -> &str {
&self.title
}

pub fn pageid(&self) -> usize {
self.pageid
}

pub fn size(&self) -> Option<usize> {
self.size
}
pub namespace: Namespace,
pub title: String,
pub pageid: usize,

pub fn wordcount(&self) -> Option<usize> {
self.wordcount
}

pub fn snippet(&self) -> Option<&str> {
self.snippet.as_ref().map(|x| x as _)
}
pub language: Language,
pub endpoint: Url,

pub fn timestamp(&self) -> Option<&str> {
self.timestamp.as_ref().map(|x| x as _)
}
pub size: Option<usize>,
pub wordcount: Option<usize>,
pub snippet: Option<String>,
pub timestamp: Option<String>,
}

#[derive(Deserialize_repr, Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -564,14 +536,39 @@ impl SearchBuilder<WithQuery, WithEndpoint, WithLanguage> {
.and_then(|x| x.get("rewrittenquery"))
.and_then(|x| x.as_str().map(|x| x.to_string()));

let results: Vec<SearchResult> = serde_json::from_value(
res_json
let results: Vec<SearchResult> = {
let mut results: Vec<SearchResult> = Vec::new();
let results_json = res_json
.get("query")
.and_then(|x| x.get("search"))
.and_then(|x| x.as_array())
.ok_or_else(|| anyhow!("missing the search results"))?
.to_owned(),
)
.context("failed deserializing the search results")?;
.to_owned();

macro_rules! value_from_json {
($result: ident, $val: expr) => {
serde_json::from_value($result.get($val).map(|x| x.to_owned()).ok_or_else(
|| anyhow!("couldn't find '{}' in the result", stringify!($val)),
)?)?
};
}

for result in results_json.into_iter() {
results.push(SearchResult {
namespace: value_from_json!(result, "ns"),
title: value_from_json!(result, "title"),
pageid: value_from_json!(result, "pageid"),
language: self.language.0.clone(),
endpoint: self.endpoint.0.clone(),
size: value_from_json!(result, "size"),
wordcount: value_from_json!(result, "wordcount"),
snippet: value_from_json!(result, "snippet"),
timestamp: value_from_json!(result, "timestamp"),
})
}

results
};

Ok(Search {
complete: continue_offset.is_none(),
Expand Down

0 comments on commit b71ecb4

Please sign in to comment.