use std::fmt;
use std::sync::Arc;
use orbit_orm::{Database, Error};
use crate::policy::ActingUser;
use crate::query::ListQuery;
use crate::runtime_resource::{Row, RuntimeData, RuntimeFuture};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct StatWidget {
pub label: &'static str,
pub value: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LatestRecords {
pub title: &'static str,
pub columns: &'static [&'static str],
pub limit: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stat {
label: String,
value: String,
description: Option<String>,
}
impl Stat {
pub fn make(label: impl Into<String>, value: impl ToString) -> Self {
Stat {
label: label.into(),
value: value.to_string(),
description: None,
}
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn get_label(&self) -> &str {
&self.label
}
pub fn get_value(&self) -> &str {
&self.value
}
pub fn get_description(&self) -> Option<&str> {
self.description.as_deref()
}
}
impl From<StatWidget> for Stat {
fn from(widget: StatWidget) -> Self {
Stat::make(widget.label, widget.value)
}
}
pub trait StatsOverviewWidget: Send + Sync + 'static {
fn stats<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, Vec<Stat>>;
fn can_view(&self, user: &ActingUser) -> bool {
let _ = user;
true
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListWidgetRow {
label: String,
value: Option<String>,
url: Option<String>,
}
impl ListWidgetRow {
pub fn make(label: impl Into<String>) -> Self {
ListWidgetRow {
label: label.into(),
value: None,
url: None,
}
}
pub fn value(mut self, value: impl ToString) -> Self {
self.value = Some(value.to_string());
self
}
pub fn url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
pub fn get_label(&self) -> &str {
&self.label
}
pub fn get_value(&self) -> Option<&str> {
self.value.as_deref()
}
pub fn get_url(&self) -> Option<&str> {
self.url.as_deref().filter(|url| safe_url(url))
}
}
pub fn safe_url(url: &str) -> bool {
let lower = url.trim_start().to_ascii_lowercase();
!url.chars().any(char::is_control)
&& ((lower.starts_with('/') && !lower.starts_with("//") && !lower.starts_with("/\\"))
|| lower.starts_with("https://")
|| lower.starts_with("http://"))
}
type RowsFn = Arc<
dyn for<'a> Fn(&'a Database, &'a ActingUser) -> RuntimeFuture<'a, Vec<ListWidgetRow>>
+ Send
+ Sync,
>;
type ViewRule = Arc<dyn Fn(&ActingUser) -> bool + Send + Sync>;
#[derive(Clone)]
pub struct ListWidget {
title: String,
rows: Option<RowsFn>,
empty_state: String,
can_view: Option<ViewRule>,
}
impl fmt::Debug for ListWidget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ListWidget")
.field("title", &self.title)
.field("rows", &self.rows.is_some())
.field("empty_state", &self.empty_state)
.field("can_view", &self.can_view.is_some())
.finish()
}
}
pub const DEFAULT_EMPTY_STATE: &str = "Nothing to show yet.";
impl ListWidget {
pub fn make(title: impl Into<String>) -> Self {
ListWidget {
title: title.into(),
rows: None,
empty_state: DEFAULT_EMPTY_STATE.to_string(),
can_view: None,
}
}
pub fn rows<F>(mut self, rows: F) -> Self
where
F: for<'a> Fn(&'a Database, &'a ActingUser) -> RuntimeFuture<'a, Vec<ListWidgetRow>>
+ Send
+ Sync
+ 'static,
{
self.rows = Some(Arc::new(rows));
self
}
pub fn rows_from<M>(self, data: Arc<dyn RuntimeData>, query: ListQuery, map: M) -> Self
where
M: Fn(&Row) -> ListWidgetRow + Send + Sync + 'static,
{
let map = Arc::new(map);
self.rows(move |db, user| {
let data = Arc::clone(&data);
let query = query.clone();
let map = Arc::clone(&map);
Box::pin(async move {
let page = data.list_for(db, user, &query).await?;
Ok(page.rows.iter().map(|row| map(row)).collect())
})
})
}
pub fn empty_state(mut self, text: impl Into<String>) -> Self {
self.empty_state = text.into();
self
}
pub fn can_view(mut self, rule: impl Fn(&ActingUser) -> bool + Send + Sync + 'static) -> Self {
self.can_view = Some(Arc::new(rule));
self
}
pub fn get_title(&self) -> &str {
&self.title
}
pub fn get_empty_state(&self) -> &str {
&self.empty_state
}
pub fn is_visible_to(&self, user: &ActingUser) -> bool {
self.can_view.as_ref().is_none_or(|rule| rule(user))
}
pub async fn load(
&self,
db: &Database,
user: &ActingUser,
) -> Result<Vec<ListWidgetRow>, Error> {
match &self.rows {
Some(rows) => rows(db, user).await,
None => Ok(Vec::new()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormWidget {
title: String,
resource: String,
fields: Vec<String>,
hidden: Vec<(String, String)>,
submit_label: String,
}
impl FormWidget {
pub fn make(title: impl Into<String>, slug: impl Into<String>) -> Self {
FormWidget {
title: title.into(),
resource: slug.into(),
fields: Vec::new(),
hidden: Vec::new(),
submit_label: "Save".to_string(),
}
}
pub fn fields<I, S>(mut self, names: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.fields = names.into_iter().map(Into::into).collect();
self
}
pub fn hidden(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.hidden.push((name.into(), value.into()));
self
}
pub fn submit_label(mut self, label: impl Into<String>) -> Self {
self.submit_label = label.into();
self
}
pub fn get_title(&self) -> &str {
&self.title
}
pub fn get_resource(&self) -> &str {
&self.resource
}
pub fn get_fields(&self) -> &[String] {
&self.fields
}
pub fn get_hidden(&self) -> &[(String, String)] {
&self.hidden
}
pub fn get_submit_label(&self) -> &str {
&self.submit_label
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_paths_and_web_urls_are_linked() {
assert!(safe_url("/admin/posts/1/edit"));
assert!(safe_url("https://example.test/a"));
assert!(safe_url("HTTP://example.test"));
assert!(!safe_url("javascript:alert(1)"));
assert!(!safe_url(" JavaScript:alert(1)"));
assert!(!safe_url("//evil.test"));
assert!(!safe_url("/\\evil.test"));
assert!(!safe_url("data:text/html,x"));
assert!(!safe_url("/a\nb"));
assert_eq!(ListWidgetRow::make("x").url("javascript:x").get_url(), None);
}
}