Skip to main content

quokka_admin/data/
sidebar_widget.rs

1use std::collections::HashMap;
2
3///
4/// Provides a way to add widgets to the sidebar by loading a template and populating it with the provided data.
5///
6/// For more-interactive widgets see the [AdminSidebarWidget::htmx] constructor which allows you to include a widget from any HTML-serving
7/// URL using htmx.
8///
9#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
10pub struct AdminSidebarWidget {
11    pub template: String,
12    pub data: HashMap<String, serde_json::Value>,
13}
14
15impl AdminSidebarWidget {
16    pub fn htmx(url: impl ToString) -> Self {
17        let mut data = HashMap::new();
18
19        data.insert("hx_get".to_string(), url.to_string().into());
20        data.insert("hx_trigger".to_string(), "load".to_string().into());
21
22        Self {
23            template: "partials/admin/htmx_widget".to_string(),
24            data,
25        }
26    }
27
28    pub fn new(template: impl ToString) -> Self {
29        Self {
30            template: template.to_string(),
31            ..Default::default()
32        }
33    }
34
35    pub fn data<S: serde::Serialize>(mut self, name: impl ToString, value: S) -> Self {
36        self.data.insert(
37            name.to_string(),
38            serde_json::to_value(value).unwrap_or_default(),
39        );
40
41        self
42    }
43
44    pub fn hx_trigger(mut self, trigger: impl ToString) -> Self {
45        self.data
46            .insert("hx_trigger".to_string(), trigger.to_string().into());
47
48        self
49    }
50}