src/config/search.rs

381 lines · 10276 bytes

  1use crate::global::{
  2    structs::Message,
  3    traits::{AsUrlString, ConfigTrait, SearchFilterItem},
  4};
  5use serde::{Deserialize, Serialize};
  6use typemap::Key;
  7
  8// can be turned into URL Params for the search term with filters
  9/// Search query & filters
 10#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
 11pub struct Search {
 12    pub query: String,
 13    pub filters: SearchFilters,
 14}
 15
 16impl Key for Search {
 17    type Value = Self;
 18}
 19
 20impl ConfigTrait for Search {
 21    const LABEL: &'static str = "search";
 22}
 23
 24impl ToString for Search {
 25    fn to_string(&self) -> String {
 26        vec![
 27            format!("q={}", self.query),
 28            self.filters.sort.as_url_string(),
 29            self.filters.date.as_url_string(),
 30            self.filters.duration.as_url_string(),
 31            self.filters.r#type.as_url_string(),
 32        ]
 33        .join("&")
 34    }
 35}
 36
 37/// Search filters, read comments for function docs
 38#[derive(Default, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
 39pub struct SearchFilters {
 40    pub sort: SearchFilterSort,
 41    pub date: SearchFilterDate,
 42    pub duration: SearchFilterDuration,
 43    pub r#type: SearchFilterType,
 44}
 45
 46// These functions are used in the search filter item
 47// Think of the ordering of stuff in the popup menu
 48impl SearchFilters {
 49    // This function returns [(Option name, [Options])]
 50    // Option name is a string like "sory by" and "type"
 51    // Options are the options that you can select like "relevance" and "upload date" for sorting
 52    pub fn get_all() -> [(&'static str, Vec<&'static str>); 5] {
 53        [
 54            (SearchFilterSort::NAME, SearchFilterSort::ordering()),
 55            (SearchFilterDate::NAME, SearchFilterDate::ordering()),
 56            (SearchFilterDuration::NAME, SearchFilterDuration::ordering()),
 57            (SearchFilterType::NAME, SearchFilterType::ordering()),
 58            ("Reset filters", vec!["Are you sure?"]),
 59        ]
 60    }
 61
 62    // uses the index of the selected option name to get the index of the selected option
 63    // aka using the hover location of the left textlist to get the hover location of the right text list
 64    pub fn get_selected(&self, index: usize) -> usize {
 65        match index {
 66            0 => self.sort.selected_index(),
 67            1 => self.date.selected_index(),
 68            2 => self.duration.selected_index(),
 69            3 => self.r#type.selected_index(),
 70            4 => 0,
 71            _ => unreachable!("`{index}` is not a valid index"),
 72        }
 73    }
 74
 75    // saves the settings for a filter given the index of the option (among other options) and the index of the selected options
 76    //                           v left textlist   v right textlist
 77    pub fn set_index(&mut self, index_at: usize, set_index: usize, message: &mut Message) {
 78        match index_at {
 79            0 => self.sort = SearchFilterSort::at_index(set_index),
 80            1 => self.date = SearchFilterDate::at_index(set_index),
 81            2 => self.duration = SearchFilterDuration::at_index(set_index),
 82            3 => self.r#type = SearchFilterType::at_index(set_index),
 83            4 => {
 84                if set_index == 0 {
 85                    self.reset(message)
 86                } else {
 87                    unreachable!("index can only be `0` for option `4` (reset all)")
 88                }
 89            }
 90            _ => unreachable!("`{index_at}` is not a valid index"),
 91        }
 92    }
 93
 94    pub fn reset(&mut self, message: &mut Message) {
 95        *self = Self::default();
 96        *message = Message::Success(String::from("Search filters has been reset"));
 97    }
 98}
 99
100#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
101pub enum SearchFilterSort {
102    Relevance,
103    Rating,
104    Date,
105    Views,
106}
107
108#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
109pub enum SearchFilterDate {
110    None,
111    Hour,
112    Day,
113    Week,
114    Month,
115    Year,
116}
117
118#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
119pub enum SearchFilterDuration {
120    None,
121    Short,
122    Medium,
123    Long,
124}
125
126#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
127pub enum SearchFilterType {
128    All,
129    Video,
130    Channel,
131    Playlist,
132}
133
134impl Default for SearchFilterSort {
135    fn default() -> Self {
136        Self::Relevance
137    }
138}
139
140impl Default for SearchFilterDate {
141    fn default() -> Self {
142        Self::None
143    }
144}
145
146impl Default for SearchFilterDuration {
147    fn default() -> Self {
148        Self::None
149    }
150}
151
152impl Default for SearchFilterType {
153    fn default() -> Self {
154        Self::All
155    }
156}
157
158impl ToString for SearchFilterSort {
159    fn to_string(&self) -> String {
160        match self {
161            Self::Relevance => String::from("relevance"),
162            Self::Rating => String::from("rating"),
163            Self::Date => String::from("date"),
164            Self::Views => String::from("views"),
165        }
166    }
167}
168
169impl ToString for SearchFilterDate {
170    fn to_string(&self) -> String {
171        match self {
172            Self::None => String::from("none"),
173            Self::Hour => String::from("hour"),
174            Self::Day => String::from("day"),
175            Self::Week => String::from("week"),
176            Self::Month => String::from("month"),
177            Self::Year => String::from("year"),
178        }
179    }
180}
181
182impl ToString for SearchFilterDuration {
183    fn to_string(&self) -> String {
184        match self {
185            Self::None => String::from("none"),
186            Self::Short => String::from("short"),
187            Self::Medium => String::from("medium"),
188            Self::Long => String::from("long"),
189        }
190    }
191}
192
193impl ToString for SearchFilterType {
194    fn to_string(&self) -> String {
195        match self {
196            Self::All => String::from("all"),
197            Self::Video => String::from("video"),
198            Self::Channel => String::from("channel"),
199            Self::Playlist => String::from("playlist"),
200        }
201    }
202}
203
204impl AsUrlString for SearchFilterSort {
205    const TAG: &'static str = "sort";
206}
207
208impl AsUrlString for SearchFilterDate {
209    const TAG: &'static str = "date";
210}
211
212impl AsUrlString for SearchFilterDuration {
213    const TAG: &'static str = "duration";
214}
215
216impl AsUrlString for SearchFilterType {
217    const TAG: &'static str = "type";
218}
219
220const SORT_ORDERING: [SearchFilterSort; 4] = [
221    SearchFilterSort::Relevance,
222    SearchFilterSort::Rating,
223    SearchFilterSort::Date,
224    SearchFilterSort::Views,
225];
226const DATE_ORDERING: [SearchFilterDate; 6] = [
227    SearchFilterDate::None,
228    SearchFilterDate::Hour,
229    SearchFilterDate::Day,
230    SearchFilterDate::Week,
231    SearchFilterDate::Month,
232    SearchFilterDate::Year,
233];
234const DURATION_ORDERING: [SearchFilterDuration; 4] = [
235    SearchFilterDuration::None,
236    SearchFilterDuration::Short,
237    SearchFilterDuration::Medium,
238    SearchFilterDuration::Long,
239];
240const TYPE_ORDERING: [SearchFilterType; 4] = [
241    SearchFilterType::All,
242    SearchFilterType::Video,
243    SearchFilterType::Channel,
244    SearchFilterType::Playlist,
245];
246
247impl SearchFilterItem for SearchFilterSort {
248    const NAME: &'static str = "Sort by";
249
250    fn option_name(&self) -> &'static str {
251        match self {
252            Self::Relevance => "Relevance",
253            Self::Rating => "Rating",
254            Self::Date => "Upload date",
255            Self::Views => "View count",
256        }
257    }
258
259    fn ordering() -> Vec<&'static str> {
260        SORT_ORDERING
261            .iter()
262            .map(|item| item.option_name())
263            .collect::<Vec<_>>()
264    }
265
266    fn selected_index(&self) -> usize {
267        match self {
268            Self::Relevance => 0,
269            Self::Rating => 1,
270            Self::Date => 2,
271            Self::Views => 3,
272        }
273    }
274
275    fn at_index(index: usize) -> Self {
276        SORT_ORDERING[index]
277    }
278}
279
280impl SearchFilterItem for SearchFilterDate {
281    const NAME: &'static str = "Upload date";
282
283    fn option_name(&self) -> &'static str {
284        match self {
285            Self::None => "Any date",
286            Self::Hour => "Last hour",
287            Self::Day => "Today",
288            Self::Week => "This week",
289            Self::Month => "This month",
290            Self::Year => "This year",
291        }
292    }
293
294    fn ordering() -> Vec<&'static str> {
295        DATE_ORDERING
296            .iter()
297            .map(|item| item.option_name())
298            .collect::<Vec<_>>()
299    }
300
301    fn selected_index(&self) -> usize {
302        match self {
303            Self::None => 0,
304            Self::Hour => 1,
305            Self::Day => 2,
306            Self::Week => 3,
307            Self::Month => 4,
308            Self::Year => 5,
309        }
310    }
311
312    fn at_index(index: usize) -> Self {
313        DATE_ORDERING[index]
314    }
315}
316
317impl SearchFilterItem for SearchFilterDuration {
318    const NAME: &'static str = "Duration";
319
320    fn option_name(&self) -> &'static str {
321        match self {
322            Self::None => "Any duration",
323            Self::Short => "Short (< 4 minutes)",
324            Self::Medium => "Medium (4 - 20 minutes)",
325            Self::Long => "Long (> 20 minutes)",
326        }
327    }
328
329    fn ordering() -> Vec<&'static str> {
330        DURATION_ORDERING
331            .iter()
332            .map(|item| item.option_name())
333            .collect::<Vec<_>>()
334    }
335
336    fn selected_index(&self) -> usize {
337        match self {
338            Self::None => 0,
339            Self::Short => 1,
340            Self::Medium => 2,
341            Self::Long => 3,
342        }
343    }
344
345    fn at_index(index: usize) -> Self {
346        DURATION_ORDERING[index]
347    }
348}
349
350impl SearchFilterItem for SearchFilterType {
351    const NAME: &'static str = "Type";
352
353    fn option_name(&self) -> &'static str {
354        match self {
355            Self::All => "Any type",
356            Self::Video => "Video",
357            Self::Channel => "Channel",
358            Self::Playlist => "Playlist",
359        }
360    }
361
362    fn ordering() -> Vec<&'static str> {
363        TYPE_ORDERING
364            .iter()
365            .map(|item| item.option_name())
366            .collect::<Vec<_>>()
367    }
368
369    fn selected_index(&self) -> usize {
370        match self {
371            Self::All => 0,
372            Self::Video => 1,
373            Self::Channel => 2,
374            Self::Playlist => 3,
375        }
376    }
377
378    fn at_index(index: usize) -> Self {
379        TYPE_ORDERING[index]
380    }
381}