Satisfy clippy

This commit is contained in:
Adrian Wozniak 2020-06-13 19:01:58 +02:00
parent 54734ea7c5
commit 4b436e953e
29 changed files with 135 additions and 161 deletions

11
.github/FUNDING.yml vendored
View File

@ -1,11 +0,0 @@
# These are supported funding model platforms
github: []
patreon: Tsumanu
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username

View File

@ -1,9 +1,9 @@
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc}; use std::sync::{mpsc, Arc};
use std::time::Duration; use std::time::Duration;
use std::{error::Error, io, thread}; use std::{error::Error, io /*, thread*/};
use termion::input::TermRead; // use termion::input::TermRead;
use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen}; use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen};
use tui::{ use tui::{
backend::TermionBackend, backend::TermionBackend,
@ -37,48 +37,50 @@ pub enum Event<I> {
/// type is handled in its own thread and returned to a common `Receiver` /// type is handled in its own thread and returned to a common `Receiver`
pub struct Events { pub struct Events {
rx: mpsc::Receiver<Event<Key>>, rx: mpsc::Receiver<Event<Key>>,
input_handle: thread::JoinHandle<()>, // input_handle: thread::JoinHandle<()>,
ignore_exit_key: Arc<AtomicBool>, ignore_exit_key: Arc<AtomicBool>,
tick_handle: thread::JoinHandle<()>, // tick_handle: thread::JoinHandle<()>,
}
impl Default for Events {
fn default() -> Events {
Events::with_config(Config::default())
}
} }
impl Events { impl Events {
pub fn new() -> Events { pub fn with_config(_config: Config) -> Events {
Events::with_config(Config::default()) let (_tx, rx) = mpsc::channel();
}
pub fn with_config(config: Config) -> Events {
let (tx, rx) = mpsc::channel();
let ignore_exit_key = Arc::new(AtomicBool::new(false)); let ignore_exit_key = Arc::new(AtomicBool::new(false));
let input_handle = { // let input_handle = {
let tx = tx.clone(); // let tx = tx.clone();
let ignore_exit_key = ignore_exit_key.clone(); // let ignore_exit_key = ignore_exit_key.clone();
thread::spawn(move || { // thread::spawn(move || {
let stdin = io::stdin(); // let stdin = io::stdin();
for evt in stdin.keys() { // for evt in stdin.keys() {
if let Ok(key) = evt { // if let Ok(key) = evt {
if let Err(err) = tx.send(Event::Input(key)) { // if let Err(err) = tx.send(Event::Input(key)) {
eprintln!("{}", err); // eprintln!("{}", err);
return; // return;
} // }
if !ignore_exit_key.load(Ordering::Relaxed) && key == config.exit_key { // if !ignore_exit_key.load(Ordering::Relaxed) && key == config.exit_key {
return; // return;
} // }
} // }
} // }
}) // })
}; // };
let tick_handle = { // let tick_handle = {
thread::spawn(move || loop { // thread::spawn(move || loop {
tx.send(Event::Tick).unwrap(); // tx.send(Event::Tick).unwrap();
thread::sleep(config.tick_rate); // thread::sleep(config.tick_rate);
}) // })
}; // };
Events { Events {
rx, rx,
ignore_exit_key, ignore_exit_key,
input_handle, // input_handle,
tick_handle, // tick_handle,
} }
} }
@ -130,7 +132,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut terminal = Terminal::new(backend)?; let mut terminal = Terminal::new(backend)?;
terminal.hide_cursor()?; terminal.hide_cursor()?;
let events = Events::new(); let events = Events::default();
// App // App
let mut app = App { let mut app = App {

View File

@ -63,9 +63,9 @@ fn build_page_content(model: &mut Model) {
let s: String = seed::document().location().unwrap().to_string().into(); let s: String = seed::document().location().unwrap().to_string().into();
let url = seed::Url::from_str(s.as_str()).unwrap(); let url = seed::Url::from_str(s.as_str()).unwrap();
let search = url.search(); let search = url.search();
let values = search.get("token").map(|v| v.clone()).unwrap_or_default(); let values = search.get("token").cloned().unwrap_or_default();
let mut content = InvitePage::default(); let mut content = InvitePage::default();
content.token = values.get(0).map(|s| s.clone()).unwrap_or_default(); content.token = values.get(0).cloned().unwrap_or_default();
model.page_content = PageContent::Invite(Box::new(content)); model.page_content = PageContent::Invite(Box::new(content));
} }
@ -97,7 +97,7 @@ pub fn view(model: &Model) -> Node<Msg> {
outer_layout(model, "invite", vec![form]) outer_layout(model, "invite", vec![form])
} }
fn submit(_page: &Box<InvitePage>) -> Node<Msg> { fn submit(_page: &InvitePage) -> Node<Msg> {
let submit = StyledButton::build() let submit = StyledButton::build()
.text("Accept") .text("Accept")
.primary() .primary()
@ -106,7 +106,7 @@ fn submit(_page: &Box<InvitePage>) -> Node<Msg> {
StyledField::build().input(submit).build().into_node() StyledField::build().input(submit).build().into_node()
} }
fn token_field(page: &Box<InvitePage>) -> Node<Msg> { fn token_field(page: &InvitePage) -> Node<Msg> {
let token = StyledInput::build(FieldId::Invite(InviteFieldId::Token)) let token = StyledInput::build(FieldId::Invite(InviteFieldId::Token))
.valid(!page.token_touched || is_token(page.token.as_str()) && page.error.is_none()) .valid(!page.token_touched || is_token(page.token.as_str()) && page.error.is_none())
.value(page.token.as_str()) .value(page.token.as_str())

View File

@ -129,7 +129,7 @@ fn update(msg: Msg, model: &mut model::Model, orders: &mut impl Orders<Msg>) {
ws::update(ws_msg, model, orders); ws::update(ws_msg, model, orders);
} }
WebSocketChanged::WebSocketMessageLoaded(v) => { WebSocketChanged::WebSocketMessageLoaded(v) => {
if let Ok(m) = bincode::deserialize(v.clone().as_slice()) { if let Ok(m) = bincode::deserialize(v.as_slice()) {
match m { match m {
WsMsg::Ping | WsMsg::Pong => { WsMsg::Ping | WsMsg::Pong => {
orders.perform_cmd(cmds::timeout(1000, || { orders.perform_cmd(cmds::timeout(1000, || {
@ -285,7 +285,7 @@ fn window_events(_model: &Model) -> Vec<EventHandler<Msg>> {
move |event: web_sys::KeyboardEvent| { move |event: web_sys::KeyboardEvent| {
let tag_name: String = seed::document() let tag_name: String = seed::document()
.active_element() .active_element()
.map(|el| el.tag_name().to_string()) .map(|el| el.tag_name())
.unwrap_or_default(); .unwrap_or_default();
let key = match tag_name.to_lowercase().as_str() { let key = match tag_name.to_lowercase().as_str() {
"input" | "textarea" => "".to_string(), "input" | "textarea" => "".to_string(),

View File

@ -300,7 +300,7 @@ impl ProjectSettingsPage {
name: Some(name.clone()), name: Some(name.clone()),
url: Some(url.clone()), url: Some(url.clone()),
description: Some(description.clone()), description: Some(description.clone()),
category: Some(category.clone()), category: Some(*category),
time_tracking: Some(*time_tracking), time_tracking: Some(*time_tracking),
}, },
description_mode: EditorMode::View, description_mode: EditorMode::View,
@ -444,8 +444,8 @@ pub struct ReportsPage {
pub last_day: NaiveDate, pub last_day: NaiveDate,
} }
impl ReportsPage { impl Default for ReportsPage {
pub fn new() -> Self { fn default() -> Self {
let first_day = chrono::Utc::today().with_day(1).unwrap().naive_local(); let first_day = chrono::Utc::today().with_day(1).unwrap().naive_local();
let last_day = (first_day + chrono::Duration::days(32)) let last_day = (first_day + chrono::Duration::days(32))
.with_day(1) .with_day(1)

View File

@ -45,16 +45,15 @@ pub fn update(msg: Msg, model: &mut crate::model::Model, orders: &mut impl Order
orders.perform_cmd(update_avatar(fd, model.host_url.clone())); orders.perform_cmd(update_avatar(fd, model.host_url.clone()));
orders.skip(); orders.skip();
} }
Msg::WebSocketChange(WebSocketChanged::WsMsg(ws_msg)) => match ws_msg { Msg::WebSocketChange(WebSocketChanged::WsMsg(ws_msg)) => {
WsMsg::AvatarUrlChanged(user_id, avatar_url) => { if let WsMsg::AvatarUrlChanged(user_id, avatar_url) = ws_msg {
if let Some(me) = model.user.as_mut() { if let Some(me) = model.user.as_mut() {
if me.id == user_id { if me.id == user_id {
profile_page.avatar.url = Some(avatar_url.clone()); profile_page.avatar.url = Some(avatar_url);
} }
} }
} }
_ => (), }
},
Msg::ProjectChanged(Some(project)) => { Msg::ProjectChanged(Some(project)) => {
profile_page.current_project.values = vec![project.id as u32]; profile_page.current_project.values = vec![project.id as u32];
} }

View File

@ -79,7 +79,7 @@ pub fn view(model: &Model) -> Node<Msg> {
inner_layout(model, "profile", vec![content]) inner_layout(model, "profile", vec![content])
} }
fn build_current_project(model: &Model, page: &Box<ProfilePage>) -> Node<Msg> { fn build_current_project(model: &Model, page: &ProfilePage) -> Node<Msg> {
let inner = if model.projects.len() <= 1 { let inner = if model.projects.len() <= 1 {
let name = model let name = model
.project .project

View File

@ -214,7 +214,7 @@ fn project_issue_list(model: &Model, status: &jirs_data::IssueStatus) -> Node<Ms
} }
#[inline] #[inline]
fn issue_filter_with_avatars(issue: &Issue, user_ids: &Vec<UserId>) -> bool { fn issue_filter_with_avatars(issue: &Issue, user_ids: &[UserId]) -> bool {
if user_ids.is_empty() { if user_ids.is_empty() {
return true; return true;
} }

View File

@ -88,7 +88,7 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
name: page.payload.name.clone(), name: page.payload.name.clone(),
url: page.payload.url.clone(), url: page.payload.url.clone(),
description: page.payload.description.clone(), description: page.payload.description.clone(),
category: page.payload.category.clone(), category: page.payload.category,
time_tracking: Some(page.time_tracking.value.into()), time_tracking: Some(page.time_tracking.value.into()),
}), }),
model.ws.as_ref(), model.ws.as_ref(),
@ -129,7 +129,7 @@ pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
.map(|is| (is.id, is.position)) .map(|is| (is.id, is.position))
{ {
send_ws_msg( send_ws_msg(
WsMsg::IssueStatusUpdate(id, name.to_string(), pos), WsMsg::IssueStatusUpdate(id, name, pos),
model.ws.as_ref(), model.ws.as_ref(),
orders, orders,
); );

View File

@ -18,8 +18,8 @@ use crate::shared::styled_textarea::StyledTextarea;
use crate::shared::{inner_layout, ToChild, ToNode}; use crate::shared::{inner_layout, ToChild, ToNode};
use crate::{model, FieldId, Msg, PageChanged, ProjectFieldId, ProjectPageChange}; use crate::{model, FieldId, Msg, PageChanged, ProjectFieldId, ProjectPageChange};
static TIME_TRACKING_FIBONACCI: &'static str = "Tracking employees time carries the risk of having them feel like they are being spied on. This is one of the most common fears that employees have when a time tracking system is implemented. No one likes to feel like theyre always being watched."; static TIME_TRACKING_FIBONACCI: &str = "Tracking employees time carries the risk of having them feel like they are being spied on. This is one of the most common fears that employees have when a time tracking system is implemented. No one likes to feel like theyre always being watched.";
static TIME_TRACKING_HOURLY: &'static str = "Employees may feel intimidated by demands to track their time. Or they could feel that theyre constantly being watched and evaluated. And for overly ambitious managers, employee time tracking may open the doors to excessive micromanaging."; static TIME_TRACKING_HOURLY: &str = "Employees may feel intimidated by demands to track their time. Or they could feel that theyre constantly being watched and evaluated. And for overly ambitious managers, employee time tracking may open the doors to excessive micromanaging.";
pub fn view(model: &model::Model) -> Node<Msg> { pub fn view(model: &model::Model) -> Node<Msg> {
let page = match &model.page_content { let page = match &model.page_content {
@ -100,7 +100,7 @@ pub fn view(model: &model::Model) -> Node<Msg> {
} }
/// Build project name input with styled field wrapper /// Build project name input with styled field wrapper
fn name_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> { fn name_field(page: &ProjectSettingsPage) -> Node<Msg> {
let name = StyledTextarea::build(FieldId::ProjectSettings(ProjectFieldId::Name)) let name = StyledTextarea::build(FieldId::ProjectSettings(ProjectFieldId::Name))
.value(page.payload.name.as_ref().cloned().unwrap_or_default()) .value(page.payload.name.as_ref().cloned().unwrap_or_default())
.height(39) .height(39)
@ -117,7 +117,7 @@ fn name_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> {
} }
/// Build project url input with styled field wrapper /// Build project url input with styled field wrapper
fn url_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> { fn url_field(page: &ProjectSettingsPage) -> Node<Msg> {
let url = StyledTextarea::build(FieldId::ProjectSettings(ProjectFieldId::Url)) let url = StyledTextarea::build(FieldId::ProjectSettings(ProjectFieldId::Url))
.height(39) .height(39)
.max_height(39) .max_height(39)
@ -134,7 +134,7 @@ fn url_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> {
} }
/// Build project description text area with styled field wrapper /// Build project description text area with styled field wrapper
fn description_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> { fn description_field(page: &ProjectSettingsPage) -> Node<Msg> {
let description = StyledEditor::build(FieldId::ProjectSettings(ProjectFieldId::Description)) let description = StyledEditor::build(FieldId::ProjectSettings(ProjectFieldId::Description))
.text( .text(
page.payload page.payload
@ -156,7 +156,7 @@ fn description_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> {
} }
/// Build project category dropdown with styled field wrapper /// Build project category dropdown with styled field wrapper
fn category_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> { fn category_field(page: &ProjectSettingsPage) -> Node<Msg> {
let category = StyledSelect::build(FieldId::ProjectSettings(ProjectFieldId::Category)) let category = StyledSelect::build(FieldId::ProjectSettings(ProjectFieldId::Category))
.opened(page.project_category_state.opened) .opened(page.project_category_state.opened)
.text_filter(page.project_category_state.text_filter.as_str()) .text_filter(page.project_category_state.text_filter.as_str())
@ -185,7 +185,7 @@ fn category_field(page: &Box<ProjectSettingsPage>) -> Node<Msg> {
} }
/// Build draggable columns preview with option to remove and add new columns /// Build draggable columns preview with option to remove and add new columns
fn columns_section(model: &Model, page: &Box<ProjectSettingsPage>) -> Node<Msg> { fn columns_section(model: &Model, page: &ProjectSettingsPage) -> Node<Msg> {
let width = 100f64 / (model.issue_statuses.len() + 1) as f64; let width = 100f64 / (model.issue_statuses.len() + 1) as f64;
let column_style = format!("width: calc({width}% - 10px)", width = width); let column_style = format!("width: calc({width}% - 10px)", width = width);
let mut per_column_issue_count = HashMap::new(); let mut per_column_issue_count = HashMap::new();

View File

@ -8,11 +8,8 @@ use crate::ws::enqueue_ws_msg;
use crate::{Msg, WebSocketChanged}; use crate::{Msg, WebSocketChanged};
pub fn update(msg: Msg, model: &mut crate::model::Model, orders: &mut impl Orders<Msg>) { pub fn update(msg: Msg, model: &mut crate::model::Model, orders: &mut impl Orders<Msg>) {
match msg { if let Msg::ChangePage(Page::Reports) = msg {
Msg::ChangePage(Page::Reports) => { build_page_content(model);
build_page_content(model);
}
_ => (),
} }
let page = match &mut model.page_content { let page = match &mut model.page_content {
@ -40,7 +37,7 @@ pub fn update(msg: Msg, model: &mut crate::model::Model, orders: &mut impl Order
} }
fn build_page_content(model: &mut Model) { fn build_page_content(model: &mut Model) {
model.page_content = PageContent::Reports(Box::new(ReportsPage::new())) model.page_content = PageContent::Reports(Box::new(ReportsPage::default()))
} }
fn init_load(model: &mut Model, orders: &mut impl Orders<Msg>) { fn init_load(model: &mut Model, orders: &mut impl Orders<Msg>) {

View File

@ -24,14 +24,14 @@ pub fn view(model: &Model) -> Node<Msg> {
let this_month_updated = this_month_updated(model, page); let this_month_updated = this_month_updated(model, page);
let graph = this_month_graph(page, &this_month_updated); let graph = this_month_graph(page, &this_month_updated);
let list = issue_list(page, &this_month_updated); let list = issue_list(page, this_month_updated.as_slice());
let body = section![class!["top"], h1![class!["header"], "Reports"], graph, list]; let body = section![class!["top"], h1![class!["header"], "Reports"], graph, list];
inner_layout(model, "reports", vec![body]) inner_layout(model, "reports", vec![body])
} }
fn this_month_graph(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -> Node<Msg> { fn this_month_graph(page: &ReportsPage, this_month_updated: &[&Issue]) -> Node<Msg> {
let mut dominant = 0; let mut dominant = 0;
let mut issues: HashMap<u32, Vec<&Issue>> = HashMap::new(); let mut issues: HashMap<u32, Vec<&Issue>> = HashMap::new();
@ -93,7 +93,7 @@ fn this_month_graph(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -
let on_hover: EventHandler<Msg> = mouse_ev(Ev::MouseEnter, move |_| { let on_hover: EventHandler<Msg> = mouse_ev(Ev::MouseEnter, move |_| {
Some(Msg::PageChanged(PageChanged::Reports( Some(Msg::PageChanged(PageChanged::Reports(
ReportsPageChange::DayHovered(Some(day.clone())), ReportsPageChange::DayHovered(Some(day)),
))) )))
}); });
let on_blur: EventHandler<Msg> = mouse_ev(Ev::MouseLeave, move |_| { let on_blur: EventHandler<Msg> = mouse_ev(Ev::MouseLeave, move |_| {
@ -101,8 +101,8 @@ fn this_month_graph(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -
ReportsPageChange::DayHovered(None), ReportsPageChange::DayHovered(None),
))) )))
}); });
let selected = page.selected_day.clone(); let selected = page.selected_day;
let current_date = day.clone(); let current_date = day;
let on_click: EventHandler<Msg> = mouse_ev(Ev::MouseLeave, move |_| { let on_click: EventHandler<Msg> = mouse_ev(Ev::MouseLeave, move |_| {
Some(Msg::PageChanged(PageChanged::Reports( Some(Msg::PageChanged(PageChanged::Reports(
ReportsPageChange::DaySelected(match selected { ReportsPageChange::DaySelected(match selected {
@ -147,9 +147,9 @@ fn this_month_graph(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -
] ]
} }
fn issue_list(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -> Node<Msg> { fn issue_list(page: &ReportsPage, this_month_updated: &[&Issue]) -> Node<Msg> {
let mut children: Vec<Node<Msg>> = vec![]; let mut children: Vec<Node<Msg>> = vec![];
for issue in this_month_updated.into_iter() { for issue in this_month_updated {
let date = issue.updated_at.date(); let date = issue.updated_at.date();
let day = date.format("%Y-%m-%d").to_string(); let day = date.format("%Y-%m-%d").to_string();
let active_class = match (page.hovered_day.as_ref(), page.selected_day.as_ref()) { let active_class = match (page.hovered_day.as_ref(), page.selected_day.as_ref()) {
@ -192,7 +192,7 @@ fn issue_list(page: &Box<ReportsPage>, this_month_updated: &Vec<&Issue>) -> Node
] ]
} }
fn this_month_updated<'a>(model: &'a Model, page: &Box<ReportsPage>) -> Vec<&'a Issue> { fn this_month_updated<'a>(model: &'a Model, page: &ReportsPage) -> Vec<&'a Issue> {
model model
.issues .issues
.iter() .iter()

View File

@ -9,20 +9,17 @@ use crate::ws::enqueue_ws_msg;
use crate::{Msg, WebSocketChanged}; use crate::{Msg, WebSocketChanged};
pub fn update(msg: &Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { pub fn update(msg: &Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
match msg { if let Msg::WebSocketChange(WebSocketChanged::WsMsg(WsMsg::AuthorizeLoaded(Ok(_)))) = msg {
Msg::WebSocketChange(WebSocketChanged::WsMsg(WsMsg::AuthorizeLoaded(Ok(_)))) => { enqueue_ws_msg(
enqueue_ws_msg( vec![
vec![ WsMsg::UserProjectsLoad,
WsMsg::UserProjectsLoad, WsMsg::ProjectsLoad,
WsMsg::ProjectsLoad, WsMsg::MessagesRequest,
WsMsg::MessagesRequest, WsMsg::ProjectUsersRequest,
WsMsg::ProjectUsersRequest, ],
], model.ws.as_ref(),
model.ws.as_ref(), orders,
orders, );
);
}
_ => (),
} }
} }

View File

@ -30,14 +30,14 @@ pub fn update(msg: &Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
match msg { match msg {
Msg::MessageInvitationApproved(token) => { Msg::MessageInvitationApproved(token) => {
send_ws_msg( send_ws_msg(
WsMsg::InvitationAcceptRequest(token.clone()), WsMsg::InvitationAcceptRequest(*token),
model.ws.as_ref(), model.ws.as_ref(),
orders, orders,
); );
} }
Msg::MessageInvitationDismiss(token) => { Msg::MessageInvitationDismiss(token) => {
send_ws_msg( send_ws_msg(
WsMsg::InvitationRejectRequest(token.clone()), WsMsg::InvitationRejectRequest(*token),
model.ws.as_ref(), model.ws.as_ref(),
orders, orders,
); );
@ -138,14 +138,11 @@ fn messages_tooltip_popup(model: &Model) -> Node<Msg> {
}); });
let mut messages: Vec<Node<Msg>> = vec![]; let mut messages: Vec<Node<Msg>> = vec![];
for (idx, message) in model.messages.iter().enumerate() { for (idx, message) in model.messages.iter().enumerate() {
match message_ui(model, message) { if let Some(message_ui) = message_ui(model, message) {
Some(message_ui) => { messages.push(message_ui);
messages.push(message_ui); if idx != model.messages.len() - 1 {
if idx != model.messages.len() - 1 { messages.push(divider());
messages.push(divider());
}
} }
None => (),
}; };
} }
let body = div![on_click, class!["messagesList"], messages]; let body = div![on_click, class!["messagesList"], messages];
@ -172,7 +169,7 @@ fn message_ui(model: &Model, message: &Message) -> Option<Node<Msg>> {
} = message; } = message;
let message_id = *id; let message_id = *id;
let hyperlink = if hyper_link.is_empty() && !hyper_link.starts_with("#") { let hyperlink = if hyper_link.is_empty() && !hyper_link.starts_with('#') {
empty![] empty![]
} else { } else {
let link_icon = StyledIcon::build(Icon::Link).build().into_node(); let link_icon = StyledIcon::build(Icon::Link).build().into_node();
@ -206,7 +203,7 @@ fn message_ui(model: &Model, message: &Message) -> Option<Node<Msg>> {
let node = match message_type { let node = match message_type {
MessageType::ReceivedInvitation => { MessageType::ReceivedInvitation => {
let token: InvitationToken = match hyper_link.trim_start_matches("#").parse() { let token: InvitationToken = match hyper_link.trim_start_matches('#').parse() {
Err(_) => return None, Err(_) => return None,
Ok(n) => n, Ok(n) => n,
}; };
@ -218,7 +215,7 @@ fn message_ui(model: &Model, message: &Message) -> Option<Node<Msg>> {
.on_click(mouse_ev(Ev::Click, move |ev| { .on_click(mouse_ev(Ev::Click, move |ev| {
ev.stop_propagation(); ev.stop_propagation();
ev.prevent_default(); ev.prevent_default();
Some(Msg::MessageInvitationApproved(token.clone())) Some(Msg::MessageInvitationApproved(token))
})) }))
.build() .build()
.into_node(); .into_node();
@ -349,7 +346,7 @@ fn parse_description(model: &Model, desc: &str) -> Node<Msg> {
} }
fn parse_email(word: &str) -> Option<&str> { fn parse_email(word: &str) -> Option<&str> {
if word.starts_with("@<") && word.ends_with(">") { if word.starts_with("@<") && word.ends_with('>') {
Some(&word[2..(word.len() - 1)]) Some(&word[2..(word.len() - 1)])
} else { } else {
None None

View File

@ -102,7 +102,7 @@ impl ToNode for ChildBuilder {
} = self; } = self;
let id = field_id.as_ref().map(|f| f.to_string()).unwrap_or_default(); let id = field_id.as_ref().map(|f| f.to_string()).unwrap_or_default();
let field_id_clone = field_id.clone(); let field_id_clone = field_id.as_ref().cloned();
let handler: EventHandler<Msg> = mouse_ev(Ev::Click, move |_| { let handler: EventHandler<Msg> = mouse_ev(Ev::Click, move |_| {
field_id_clone.map(|field_id| Msg::U32InputChanged(field_id, value)) field_id_clone.map(|field_id| Msg::U32InputChanged(field_id, value))
}); });

View File

@ -25,7 +25,7 @@ impl StyledImageInputState {
Msg::FileInputChanged(field_id, files) if field_id == &self.field_id => { Msg::FileInputChanged(field_id, files) if field_id == &self.field_id => {
self.file = files.get(0).cloned(); self.file = files.get(0).cloned();
} }
_ => return, _ => {}
} }
} }
} }

View File

@ -649,11 +649,9 @@ fn second_row(values: &StyledRte) -> Node<Msg> {
]]) ]])
.add_child({ .add_child({
let body: Vec<Node<Msg>> = (0..rows) let body: Vec<Node<Msg>> = (0..rows)
.into_iter()
.map(|_row| { .map(|_row| {
let tds: Vec<Node<Msg>> = (0..cols) let tds: Vec<Node<Msg>> = (0..cols)
.into_iter() .map(|_col| td![" "])
.map(|_col| td![format!(" ")])
.collect(); .collect();
tr![tds] tr![tds]
}) })

View File

@ -22,12 +22,9 @@ pub fn update(msg: Msg, model: &mut model::Model, orders: &mut impl Orders<Msg>)
return; return;
} }
match msg { if let Msg::ChangePage(Page::SignIn) = msg {
Msg::ChangePage(Page::SignIn) => { build_page_content(model);
build_page_content(model); return;
return;
}
_ => (),
}; };
let page = match &mut model.page_content { let page = match &mut model.page_content {

View File

@ -19,12 +19,9 @@ pub fn update(msg: Msg, model: &mut model::Model, orders: &mut impl Orders<Msg>)
return; return;
} }
match msg { if let Msg::ChangePage(Page::SignUp) = msg {
Msg::ChangePage(Page::SignUp) => { build_page_content(model);
build_page_content(model); return;
return;
}
_ => (),
}; };
let page = match &mut model.page_content { let page = match &mut model.page_content {

View File

@ -24,7 +24,7 @@ pub fn flush_queue(model: &mut Model, orders: &mut impl Orders<Msg>) {
pub fn enqueue_ws_msg(v: Vec<WsMsg>, ws: Option<&WebSocket>, orders: &mut impl Orders<Msg>) { pub fn enqueue_ws_msg(v: Vec<WsMsg>, ws: Option<&WebSocket>, orders: &mut impl Orders<Msg>) {
for msg in v { for msg in v {
send_ws_msg(msg, ws.clone(), orders); send_ws_msg(msg, ws, orders);
} }
} }

View File

@ -42,7 +42,7 @@ pub fn build_pool() -> DbPool {
dotenv::dotenv().ok(); dotenv::dotenv().ok();
let config = Configuration::read(); let config = Configuration::read();
let manager = ConnectionManager::<PgConnection>::new(config.database_url.clone()); let manager = ConnectionManager::<PgConnection>::new(config.database_url);
r2d2::Pool::builder() r2d2::Pool::builder()
.build(manager) .build(manager)
.unwrap_or_else(|e| panic!("Failed to create pool. {}", e)) .unwrap_or_else(|e| panic!("Failed to create pool. {}", e))

View File

@ -55,7 +55,7 @@ impl Handler<Invite> for MailExecutor {
transport transport
.send(email.into()) .send(email.into())
.and_then(|_| Ok(())) .map(|_| ())
.map_err(|e| format!("Mailer: {}", e)) .map_err(|e| format!("Mailer: {}", e))
} }
} }

View File

@ -54,7 +54,7 @@ impl Handler<Welcome> for MailExecutor {
transport transport
.send(email.into()) .send(email.into())
.and_then(|_| Ok(())) .map(|_| ())
.map_err(|e| format!("Mailer: {}", e)) .map_err(|e| format!("Mailer: {}", e))
} }
} }

View File

@ -164,7 +164,7 @@ async fn handle_image(
bind = web_config.bind, bind = web_config.bind,
port = match web_config.port.as_str() { port = match web_config.port.as_str() {
"80" | "443" => "".to_string(), "80" | "443" => "".to_string(),
p @ _ => format!(":{}", p), p => format!(":{}", p),
}, },
client_path = filesystem.client_path, client_path = filesystem.client_path,
user_id = user_id, user_id = user_id,

View File

@ -80,7 +80,7 @@ impl WsHandler<CreateInvitation> for WebSocketActor {
} }
// If user exists then send message to him // If user exists then send message to him
match block_on(self.db.send(crate::db::messages::CreateMessage { if let Ok(Ok(message)) = block_on(self.db.send(crate::db::messages::CreateMessage {
receiver: CreateMessageReceiver::Lookup { name, email }, receiver: CreateMessageReceiver::Lookup { name, email },
sender_id: user_id, sender_id: user_id,
summary: "You have been invited to project".to_string(), summary: "You have been invited to project".to_string(),
@ -88,13 +88,10 @@ impl WsHandler<CreateInvitation> for WebSocketActor {
message_type: MessageType::ReceivedInvitation, message_type: MessageType::ReceivedInvitation,
hyper_link: format!("#{}", invitation.bind_token), hyper_link: format!("#{}", invitation.bind_token),
})) { })) {
Ok(Ok(message)) => { self.addr.do_send(InnerMsg::SendToUser(
self.addr.do_send(InnerMsg::SendToUser( message.receiver_id,
message.receiver_id, WsMsg::Message(message),
WsMsg::Message(message), ));
));
}
_ => {}
} }
Ok(Some(WsMsg::InvitationSendSuccess)) Ok(Some(WsMsg::InvitationSendSuccess))
@ -154,9 +151,10 @@ pub struct AcceptInvitation {
impl WsHandler<AcceptInvitation> for WebSocketActor { impl WsHandler<AcceptInvitation> for WebSocketActor {
fn handle_msg(&mut self, msg: AcceptInvitation, ctx: &mut Self::Context) -> WsResult { fn handle_msg(&mut self, msg: AcceptInvitation, ctx: &mut Self::Context) -> WsResult {
let AcceptInvitation { invitation_token } = msg; let AcceptInvitation { invitation_token } = msg;
let token = match block_on(self.db.send(invitations::AcceptInvitation { let token = match block_on(
invitation_token: invitation_token.clone(), self.db
})) { .send(invitations::AcceptInvitation { invitation_token }),
) {
Ok(Ok(token)) => token, Ok(Ok(token)) => token,
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
@ -172,7 +170,7 @@ impl WsHandler<AcceptInvitation> for WebSocketActor {
token: invitation_token, token: invitation_token,
user_id: token.user_id, user_id: token.user_id,
})) }))
.unwrap_or(Ok(vec![])) .unwrap_or_else(|_| Ok(vec![]))
.unwrap_or_default() .unwrap_or_default()
{ {
match block_on(self.db.send(crate::db::messages::MarkMessageSeen { match block_on(self.db.send(crate::db::messages::MarkMessageSeen {

View File

@ -14,11 +14,11 @@ impl WsHandler<LoadMessages> for WebSocketActor {
Ok(Ok(v)) => Ok(Some(WsMsg::MessagesResponse(v))), Ok(Ok(v)) => Ok(Some(WsMsg::MessagesResponse(v))),
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
return Ok(None); Ok(None)
} }
Err(e) => { Err(e) => {
error!("{}", e); error!("{}", e);
return Ok(None); Ok(None)
} }
} }
} }
@ -38,11 +38,11 @@ impl WsHandler<MarkMessageSeen> for WebSocketActor {
Ok(Ok(id)) => Ok(Some(WsMsg::MessageMarkedSeen(id))), Ok(Ok(id)) => Ok(Some(WsMsg::MessageMarkedSeen(id))),
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
return Ok(None); Ok(None)
} }
Err(e) => { Err(e) => {
error!("{}", e); error!("{}", e);
return Ok(None); Ok(None)
} }
} }
} }

View File

@ -358,7 +358,10 @@ impl Handler<InnerMsg> for WsServer {
debug!("receive {:?}", msg); debug!("receive {:?}", msg);
match msg { match msg {
InnerMsg::Join(project_id, user_id, recipient) => { InnerMsg::Join(project_id, user_id, recipient) => {
let v = self.sessions.entry(user_id).or_insert(vec![]); let v = self
.sessions
.entry(user_id)
.or_insert_with(Default::default);
v.push(recipient); v.push(recipient);
self.ensure_room(project_id); self.ensure_room(project_id);
@ -378,7 +381,7 @@ impl Handler<InnerMsg> for WsServer {
room.remove(&user_id); room.remove(&user_id);
self.sessions.remove(&user_id); self.sessions.remove(&user_id);
} else { } else {
let v = self.sessions.entry(user_id).or_insert(vec![]); let v = self.sessions.entry(user_id).or_insert_with(Vec::new);
v.remove_item(&recipient); v.remove_item(&recipient);
} }
} }
@ -414,7 +417,7 @@ impl WsServer {
self.rooms.entry(room).or_insert_with(HashMap::new); self.rooms.entry(room).or_insert_with(HashMap::new);
} }
fn send_to_recipients(&self, recipients: &Vec<Recipient<InnerMsg>>, msg: &WsMsg) { fn send_to_recipients(&self, recipients: &[Recipient<InnerMsg>], msg: &WsMsg) {
for recipient in recipients.iter() { for recipient in recipients.iter() {
match recipient.do_send(InnerMsg::Transfer(msg.clone())) { match recipient.do_send(InnerMsg::Transfer(msg.clone())) {
Ok(_) => debug!("msg sent"), Ok(_) => debug!("msg sent"),

View File

@ -17,11 +17,11 @@ impl WsHandler<LoadUserProjects> for WebSocketActor {
Ok(Ok(v)) => Ok(Some(WsMsg::UserProjectsLoaded(v))), Ok(Ok(v)) => Ok(Some(WsMsg::UserProjectsLoaded(v))),
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
return Ok(None); Ok(None)
} }
Err(e) => { Err(e) => {
error!("{}", e); error!("{}", e);
return Ok(None); Ok(None)
} }
} }
} }
@ -44,11 +44,11 @@ impl WsHandler<SetCurrentUserProject> for WebSocketActor {
} }
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
return Ok(None); Ok(None)
} }
Err(e) => { Err(e) => {
error!("{}", e); error!("{}", e);
return Ok(None); Ok(None)
} }
} }
} }

View File

@ -126,11 +126,11 @@ impl WsHandler<RemoveInvitedUser> for WebSocketActor {
Ok(Ok(_users)) => Ok(Some(WsMsg::InvitedUserRemoveSuccess(invited_id))), Ok(Ok(_users)) => Ok(Some(WsMsg::InvitedUserRemoveSuccess(invited_id))),
Ok(Err(e)) => { Ok(Err(e)) => {
error!("{:?}", e); error!("{:?}", e);
return Ok(None); Ok(None)
} }
Err(e) => { Err(e) => {
error!("{}", e); error!("{}", e);
return Ok(None); Ok(None)
} }
} }
} }