src/config/search.rs

376 lines · 10304 bytes

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