dbl/
widget.rs

1//! URL Builders for badge, large and small widgets.
2
3use std::collections::HashMap;
4use url::{ParseError, Url};
5
6use crate::types::BotId;
7
8/// URL Builder for [badge widgets](https://top.gg/api/docs#widgets).
9pub enum Badge {
10    Owner,
11    Upvotes,
12    Servers,
13    Status,
14    Library,
15}
16
17impl Badge {
18    pub fn build<T>(&self, bot: T, show_avatar: bool) -> Result<Url, ParseError>
19    where
20        T: Into<BotId>,
21    {
22        let kind = match self {
23            Badge::Owner => "owner",
24            Badge::Library => "lib",
25            Badge::Servers => "servers",
26            Badge::Status => "status",
27            Badge::Upvotes => "upvotes",
28        };
29        let mut url = api!("/widget/{}/{}.svg", kind, bot.into());
30        if !show_avatar {
31            url.push_str("?noavatar=true");
32        }
33        Url::parse(&url)
34    }
35}
36
37/// URL Builder for [large widgets](https://top.gg/api/docs#widgets).
38pub struct LargeWidget(HashMap<&'static str, String>);
39/// URL Builder for [small widgets](https://top.gg/api/docs#widgets).
40pub struct SmallWidget(HashMap<&'static str, String>);
41
42macro_rules! impl_widget {
43    (
44        $widget:ident($cnt:expr) {
45            $(
46                $(#[$fn_meta:ident $($meta_args:tt)*])*
47                $fn:ident: $name:expr;
48            )+
49        }
50    ) => {
51        impl $widget {
52            pub fn new() -> Self {
53                $widget(HashMap::with_capacity($cnt))
54            }
55
56            /// Build the widget url.
57            pub fn build<T>(self, bot: T) -> Result<Url, ParseError>
58            where
59                T: Into<BotId>,
60            {
61                Url::parse_with_params(&api!("/widget/{}.svg", bot.into()), self.0)
62            }
63
64            $(
65                $(#[$fn_meta $($meta_args)*])*
66                pub fn $fn<T>(mut self, color: T) -> Self
67                where
68                    T: ToString,
69                {
70                    self.0.insert($name, color.to_string());
71                    self
72                }
73            )+
74        }
75
76        impl Default for $widget {
77            fn default() -> Self {
78                $widget::new()
79            }
80        }
81    };
82}
83
84impl_widget!(LargeWidget(7) {
85    top_color: "topcolor";
86    middle_color: "middlecolor";
87    username_color: "usernamecolor";
88    certified_color: "certifiedcolor";
89    data_color: "datacolor";
90    label_color: "labelcolor";
91    hightlight_color: "hightlightcolor";
92});
93
94impl_widget!(SmallWidget(5) {
95    avatarbg_color: "avatarbgcolor";
96    left_color: "leftcolor";
97    right_color: "rightcolor";
98    lefttext_color: "lefttextcolor";
99    righttext_color: "righttextcolor";
100});