app: Extract the form component from the user details page

This commit is contained in:
Valentin Tolmer 2021-09-19 13:44:58 +02:00 committed by nitnelave
parent 5943df6443
commit 14be1170f2
6 changed files with 320 additions and 160 deletions

82
Cargo.lock generated
View File

@ -1483,6 +1483,12 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "if_chain"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.7.0" version = "1.7.0"
@ -1750,14 +1756,20 @@ dependencies = [
"graphql_client", "graphql_client",
"http", "http",
"jwt", "jwt",
"lazy_static",
"lldap_auth", "lldap_auth",
"rand 0.8.4", "rand 0.8.4",
"regex",
"serde", "serde",
"serde_json", "serde_json",
"validator",
"validator_derive",
"wasm-bindgen", "wasm-bindgen",
"web-sys", "web-sys",
"yew", "yew",
"yew-router", "yew-router",
"yew_form",
"yew_form_derive",
] ]
[[package]] [[package]]
@ -2017,8 +2029,9 @@ dependencies = [
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.3.2" version = "0.3.3"
source = "git+https://github.com/nitnelave/num-bigint/?branch=0.3.2-patch#e56d6cca158ec358a48daadf58c070f40a6976ca" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f6f7833f2cbf2360a6cfd58cd41a53aa7a90bd4c202f5b1c7dd2ed73c57b2c3"
dependencies = [ dependencies = [
"autocfg 1.0.1", "autocfg 1.0.1",
"num-integer", "num-integer",
@ -2876,7 +2889,7 @@ dependencies = [
"log", "log",
"md-5", "md-5",
"memchr", "memchr",
"num-bigint 0.3.2", "num-bigint 0.3.3",
"once_cell", "once_cell",
"parking_lot", "parking_lot",
"percent-encoding", "percent-encoding",
@ -3439,6 +3452,48 @@ dependencies = [
"getrandom 0.2.3", "getrandom 0.2.3",
] ]
[[package]]
name = "validator"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d0f08911ab0fee2c5009580f04615fa868898ee57de10692a45da0c3bcc3e5e"
dependencies = [
"idna",
"lazy_static",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_types",
]
[[package]]
name = "validator_derive"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d85135714dba11a1bd0b3eb1744169266f1a38977bf4e3ff5e2e1acb8c2b7eee"
dependencies = [
"if_chain",
"lazy_static",
"proc-macro-error",
"proc-macro2",
"quote",
"regex",
"syn",
"validator_types",
]
[[package]]
name = "validator_types"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded9d97e1d42327632f5f3bae6403c04886e2de3036261ef42deebd931a6a291"
dependencies = [
"proc-macro2",
"syn",
]
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@ -3681,6 +3736,27 @@ dependencies = [
"nom 5.1.2", "nom 5.1.2",
] ]
[[package]]
name = "yew_form"
version = "0.1.8"
source = "git+https://github.com/sassman/yew_form/?rev=67050812695b7a8a90b81b0637e347fc6629daed#67050812695b7a8a90b81b0637e347fc6629daed"
dependencies = [
"validator",
"validator_derive",
"yew",
]
[[package]]
name = "yew_form_derive"
version = "0.1.8"
source = "git+https://github.com/sassman/yew_form/?rev=67050812695b7a8a90b81b0637e347fc6629daed#67050812695b7a8a90b81b0637e347fc6629daed"
dependencies = [
"proc-macro2",
"quote",
"syn",
"yew_form",
]
[[package]] [[package]]
name = "zeroize" name = "zeroize"
version = "1.4.1" version = "1.4.1"

View File

@ -5,7 +5,11 @@ members = [
"app" "app"
] ]
#TODO: remove once https://github.com/rust-num/num-bigint/issues/218 is fixed # TODO: remove when there's a new release.
[patch.crates-io.num-bigint] [patch.crates-io.yew_form]
git = 'https://github.com/nitnelave/num-bigint/' git = 'https://github.com/sassman/yew_form/'
branch = '0.3.2-patch' rev = '67050812695b7a8a90b81b0637e347fc6629daed'
[patch.crates-io.yew_form_derive]
git = 'https://github.com/sassman/yew_form/'
rev = '67050812695b7a8a90b81b0637e347fc6629daed'

View File

@ -6,15 +6,21 @@ edition = "2018"
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
http = "0.2.4" graphql_client = "0.10"
http = "0.2"
jwt = "0.13" jwt = "0.13"
lazy_static = "*"
rand = "0.8" rand = "0.8"
regex = "*"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
validator = "*"
validator_derive = "*"
wasm-bindgen = "0.2" wasm-bindgen = "0.2"
yew = "0.18" yew = "0.18"
yew-router = "0.15" yew-router = "0.15"
graphql_client = "0.10.0" yew_form = "0.1.8"
yew_form_derive = "*"
[dependencies.web-sys] [dependencies.web-sys]
version = "0.3" version = "0.3"

View File

@ -7,4 +7,5 @@ pub mod logout;
pub mod router; pub mod router;
pub mod select; pub mod select;
pub mod user_details; pub mod user_details;
pub mod user_details_form;
pub mod user_table; pub mod user_table;

View File

@ -2,10 +2,11 @@ use crate::{
components::{ components::{
add_user_to_group::AddUserToGroupComponent, add_user_to_group::AddUserToGroupComponent,
router::{AppRoute, NavButton}, router::{AppRoute, NavButton},
user_details_form::UserDetailsForm,
}, },
infra::api::HostService, infra::api::HostService,
}; };
use anyhow::{anyhow, bail, Error, Result}; use anyhow::{bail, Error, Result};
use graphql_client::GraphQLQuery; use graphql_client::GraphQLQuery;
use yew::{ use yew::{
prelude::*, prelude::*,
@ -24,16 +25,6 @@ pub struct GetUserDetails;
pub type User = get_user_details::GetUserDetailsUser; pub type User = get_user_details::GetUserDetailsUser;
pub type Group = get_user_details::GetUserDetailsUserGroups; pub type Group = get_user_details::GetUserDetailsUserGroups;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "../schema.graphql",
query_path = "queries/update_user.graphql",
response_derives = "Debug",
variables_derives = "Clone",
custom_scalars_module = "crate::infra::graphql"
)]
pub struct UpdateUser;
#[derive(GraphQLQuery)] #[derive(GraphQLQuery)]
#[graphql( #[graphql(
schema_path = "../schema.graphql", schema_path = "../schema.graphql",
@ -51,12 +42,8 @@ pub struct UserDetails {
/// The user info. If none, the error is in `error`. If `error` is None, then we haven't /// The user info. If none, the error is in `error`. If `error` is None, then we haven't
/// received the server response yet. /// received the server response yet.
user: Option<User>, user: Option<User>,
// Needed for the form.
node_ref: NodeRef,
/// Error message displayed to the user. /// Error message displayed to the user.
error: Option<Error>, error: Option<Error>,
/// The request, while we're waiting for the server to reply.
update_request: Option<update_user::UpdateUserInput>,
/// True iff we just finished updating the user, to display a successful message. /// True iff we just finished updating the user, to display a successful message.
update_successful: bool, update_successful: bool,
is_admin: bool, is_admin: bool,
@ -71,10 +58,6 @@ pub struct UserDetails {
pub enum Msg { pub enum Msg {
/// Received the user details response, either the user data or an error. /// Received the user details response, either the user data or an error.
UserDetailsResponse(Result<get_user_details::ResponseData>), UserDetailsResponse(Result<get_user_details::ResponseData>),
/// The user changed some fields and submitted the form for update.
SubmitUserUpdateForm,
/// Response after updating the user's details.
UpdateFinished(Result<update_user::ResponseData>),
SubmitRemoveGroup(Group), SubmitRemoveGroup(Group),
RemoveGroupResponse(Result<remove_user_from_group::ResponseData>), RemoveGroupResponse(Result<remove_user_from_group::ResponseData>),
OnError(Error), OnError(Error),
@ -87,11 +70,6 @@ pub struct Props {
pub is_admin: bool, pub is_admin: bool,
} }
#[allow(clippy::ptr_arg)]
fn not_empty(s: &String) -> bool {
!s.is_empty()
}
impl UserDetails { impl UserDetails {
fn get_user_details(&mut self) { fn get_user_details(&mut self) {
self._task = HostService::graphql_query::<GetUserDetails>( self._task = HostService::graphql_query::<GetUserDetails>(
@ -108,78 +86,6 @@ impl UserDetails {
.ok(); .ok();
} }
fn submit_user_update_form(&mut self) -> Result<bool> {
let base_user = self.user.as_ref().unwrap();
let mut user_input = update_user::UpdateUserInput {
id: self.username.clone(),
email: None,
displayName: None,
firstName: None,
lastName: None,
};
let mut should_send_form = false;
let email = get_element("email")
.filter(not_empty)
.ok_or_else(|| anyhow!("Missing email"))?;
if base_user.email != email {
should_send_form = true;
user_input.email = Some(email);
}
if base_user.display_name != get_element_or_empty("display_name") {
should_send_form = true;
user_input.displayName = Some(get_element_or_empty("display_name"));
}
if base_user.first_name != get_element_or_empty("first_name") {
should_send_form = true;
user_input.firstName = Some(get_element_or_empty("first_name"));
}
if base_user.last_name != get_element_or_empty("last_name") {
should_send_form = true;
user_input.lastName = Some(get_element_or_empty("last_name"));
}
if !should_send_form {
return Ok(false);
}
self.update_request = Some(user_input.clone());
let req = update_user::Variables { user: user_input };
self._task = Some(HostService::graphql_query::<UpdateUser>(
req,
self.link.callback(Msg::UpdateFinished),
"Error trying to update user",
)?);
Ok(false)
}
fn user_update_finished(&mut self, r: Result<update_user::ResponseData>) -> Result<bool> {
match r {
Err(e) => return Err(e),
Ok(_) => {
ConsoleService::log("Successfully updated user");
self.update_successful = true;
let User {
id,
display_name,
first_name,
last_name,
email,
creation_date,
groups,
} = self.user.take().unwrap();
let new_user = self.update_request.take().unwrap();
self.user = Some(User {
id,
email: new_user.email.unwrap_or(email),
display_name: new_user.displayName.unwrap_or(display_name),
first_name: new_user.firstName.unwrap_or(first_name),
last_name: new_user.lastName.unwrap_or(last_name),
creation_date,
groups,
});
}
};
Ok(true)
}
fn submit_remove_group(&mut self, group: Group) -> Result<bool> { fn submit_remove_group(&mut self, group: Group) -> Result<bool> {
self._task = HostService::graphql_query::<RemoveUserFromGroup>( self._task = HostService::graphql_query::<RemoveUserFromGroup>(
remove_user_from_group::Variables { remove_user_from_group::Variables {
@ -208,8 +114,6 @@ impl UserDetails {
bail!("Error getting user details: {}", e); bail!("Error getting user details: {}", e);
} }
}, },
Msg::SubmitUserUpdateForm => return self.submit_user_update_form(),
Msg::UpdateFinished(r) => return self.user_update_finished(r),
Msg::SubmitRemoveGroup(group) => return self.submit_remove_group(group), Msg::SubmitRemoveGroup(group) => return self.submit_remove_group(group),
Msg::RemoveGroupResponse(response) => { Msg::RemoveGroupResponse(response) => {
response?; response?;
@ -225,39 +129,6 @@ impl UserDetails {
Ok(true) Ok(true)
} }
fn view_form(&self, u: &User) -> Html {
html! {
<form ref=self.node_ref.clone() onsubmit=self.link.callback(|e: FocusEvent| { e.prevent_default(); Msg::SubmitUserUpdateForm })>
<div>
<span>{"User ID: "}</span>
<span>{&u.id}</span>
</div>
<div>
<label for="email">{"Email: "}</label>
<input type="text" id="email" value={u.email.clone()} />
</div>
<div>
<label for="display_name">{"Display name: "}</label>
<input type="text" id="display_name" value={u.display_name.clone()} />
</div>
<div>
<label for="first_name">{"First name: "}</label>
<input type="text" id="first_name" value={u.first_name.clone()} />
</div>
<div>
<label for="last_name">{"Last name: "}</label>
<input type="text" id="last_name" value={u.last_name.clone()} />
</div>
<div>
<span>{"Creation date: "}</span>
<span>{&u.creation_date.with_timezone(&chrono::Local)}</span>
</div>
<div>
<button type="submit">{"Update"}</button>
</div>
</form>
}
}
fn view_messages(&self, error: &Option<Error>) -> Html { fn view_messages(&self, error: &Option<Error>) -> Html {
if self.update_successful { if self.update_successful {
html! { html! {
@ -319,22 +190,6 @@ impl UserDetails {
} }
} }
fn get_element(name: &str) -> Option<String> {
use wasm_bindgen::JsCast;
Some(
web_sys::window()?
.document()?
.get_element_by_id(name)?
.dyn_into::<web_sys::HtmlInputElement>()
.ok()?
.value(),
)
}
fn get_element_or_empty(name: &str) -> String {
get_element(name).unwrap_or_default()
}
impl Component for UserDetails { impl Component for UserDetails {
type Message = Msg; type Message = Msg;
type Properties = Props; type Properties = Props;
@ -343,11 +198,9 @@ impl Component for UserDetails {
let mut table = Self { let mut table = Self {
link, link,
username: props.username, username: props.username,
node_ref: NodeRef::default(),
_task: None, _task: None,
user: None, user: None,
error: None, error: None,
update_request: None,
update_successful: false, update_successful: false,
is_admin: props.is_admin, is_admin: props.is_admin,
group_to_remove: None, group_to_remove: None,
@ -379,11 +232,13 @@ impl Component for UserDetails {
(Some(u), error) => { (Some(u), error) => {
html! { html! {
<div> <div>
{self.view_form(u)} <UserDetailsForm
user=u.clone()
on_error=self.link.callback(Msg::OnError)/>
{self.view_messages(error)} {self.view_messages(error)}
{self.view_group_memberships(u)} {self.view_group_memberships(u)}
<div> <div>
<NavButton route=AppRoute::ChangePassword(self.username.clone())>{"Change password"}</NavButton> <NavButton route=AppRoute::ChangePassword(u.id.clone())>{"Change password"}</NavButton>
</div> </div>
</div> </div>
} }

View File

@ -0,0 +1,218 @@
use crate::{components::user_details::User, infra::api::HostService};
use anyhow::{Error, Result};
use graphql_client::GraphQLQuery;
use validator_derive::Validate;
use yew::{
prelude::*,
services::{fetch::FetchTask, ConsoleService},
};
use yew_form_derive::Model;
lazy_static::lazy_static! {
static ref EMAIL_RE: regex::Regex = regex::Regex::new("^[^@]+@[^@]+\\.[^@]+$").unwrap();
}
/// The fields of the form, with the editable details and the constraints.
#[derive(Model, Validate, PartialEq, Clone)]
pub struct UserModel {
#[validate(regex(path = "EMAIL_RE", message = "Enter a valid email"))]
email: String,
#[validate(length(min = 1, message = "Display name is required"))]
display_name: String,
first_name: String,
last_name: String,
}
/// The GraphQL query sent to the server to update the user details.
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "../schema.graphql",
query_path = "queries/update_user.graphql",
response_derives = "Debug",
variables_derives = "Clone,PartialEq",
custom_scalars_module = "crate::infra::graphql"
)]
pub struct UpdateUser;
/// A [yew::Component] to display the user details, with a form allowing to edit them.
pub struct UserDetailsForm {
link: ComponentLink<Self>,
props: Props,
form: yew_form::Form<UserModel>,
/// True if we just successfully updated the user, to display a success message.
just_updated: bool,
_task: Option<FetchTask>,
}
pub enum Msg {
/// A form field changed.
Update,
/// The "Submit" button was clicked.
SubmitClicked,
/// We got the response from the server about our update message.
UserUpdated(Result<update_user::ResponseData>),
}
#[derive(yew::Properties, Clone, PartialEq)]
pub struct Props {
/// The current user details.
pub user: User,
/// Callback to report errors (e.g. server error).
pub on_error: Callback<Error>,
}
impl Component for UserDetailsForm {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
let model = UserModel {
email: props.user.email.clone(),
display_name: props.user.display_name.clone(),
first_name: props.user.first_name.clone(),
last_name: props.user.last_name.clone(),
};
Self {
link,
form: yew_form::Form::new(model),
props,
just_updated: false,
_task: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
self.just_updated = false;
match self.handle_msg(msg) {
Err(e) => {
ConsoleService::error(&e.to_string());
self.props.on_error.emit(e);
true
}
Ok(b) => b,
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Field = yew_form::Field<UserModel>;
html! {
<>
<form>
<div class="form-group">
<span>{"User ID: "}</span>
<span>{&self.props.user.id}</span>
</div>
<div class="form-group">
<label for="email">{"Email: "}</label>
<Field form=&self.form field_name="email" oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("email")}
</div>
</div>
<div class="form-group">
<label for="display_name">{"Display Name: "}</label>
<Field form=&self.form field_name="display_name" oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("display_name")}
</div>
</div>
<div class="form-group">
<label for="first_name">{"First Name: "}</label>
<Field form=&self.form field_name="first_name" oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("first_name")}
</div>
</div>
<div class="form-group">
<label for="last_name">{"Last Name: "}</label>
<Field form=&self.form field_name="last_name" oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("last_name")}
</div>
</div>
<div class="form-group">
<span>{"Creation date: "}</span>
<span>{&self.props.user.creation_date.with_timezone(&chrono::Local)}</span>
</div>
<div class="form-group">
<button type="button" onclick=self.link.callback(|e: MouseEvent| {e.prevent_default(); Msg::SubmitClicked})>{"Update"}</button>
</div>
</form>
<div hidden=!self.just_updated>
<span>{"User successfully updated!"}</span>
</div>
</>
}
}
}
impl UserDetailsForm {
fn handle_msg(&mut self, msg: <Self as Component>::Message) -> Result<bool> {
match msg {
Msg::Update => Ok(true),
Msg::SubmitClicked => self.submit_user_update_form(),
Msg::UserUpdated(response) => self.user_update_finished(response),
}
}
fn submit_user_update_form(&mut self) -> Result<bool> {
let base_user = &self.props.user;
let mut user_input = update_user::UpdateUserInput {
id: self.props.user.id.clone(),
email: None,
displayName: None,
firstName: None,
lastName: None,
};
let default_user_input = user_input.clone();
let model = self.form.model();
let email = model.email;
if base_user.email != email {
user_input.email = Some(email);
}
if base_user.display_name != model.display_name {
user_input.displayName = Some(model.display_name);
}
if base_user.first_name != model.first_name {
user_input.firstName = Some(model.first_name);
}
if base_user.last_name != model.last_name {
user_input.lastName = Some(model.last_name);
}
// Nothing changed.
if user_input == default_user_input {
return Ok(false);
}
let req = update_user::Variables { user: user_input };
self._task = Some(HostService::graphql_query::<UpdateUser>(
req,
self.link.callback(Msg::UserUpdated),
"Error trying to update user",
)?);
Ok(false)
}
fn user_update_finished(&mut self, r: Result<update_user::ResponseData>) -> Result<bool> {
match r {
Err(e) => return Err(e),
Ok(_) => {
let model = self.form.model();
self.props.user = User {
id: self.props.user.id.clone(),
email: model.email,
display_name: model.display_name,
first_name: model.first_name,
last_name: model.last_name,
creation_date: self.props.user.creation_date,
groups: self.props.user.groups.clone(),
};
self.just_updated = true;
}
};
Ok(true)
}
}