This commit is contained in:
Dominic Grimm 2023-05-21 18:58:10 +02:00
commit e82f35da2a
No known key found for this signature in database
GPG key ID: B6FFE500AAD54A3A
78 changed files with 10821 additions and 0 deletions

3
frontend/.cargo/config Normal file
View file

@ -0,0 +1,3 @@
[build]
target = "wasm32-unknown-unknown"
rustflags = ["--cfg=web_sys_unstable_apis"]

10
frontend/.dockerignore Normal file
View file

@ -0,0 +1,10 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf
*.env
/examples/
Dockerfile
.dockerignore
README.md

1
frontend/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

2212
frontend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

35
frontend/Cargo.toml Normal file
View file

@ -0,0 +1,35 @@
[package]
name = "frontend"
version = "0.1.0"
edition = "2021"
build = "build.rs"
[profile.release]
lto = true
codegen-units = 1
opt-level = "z"
panic = "abort"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bounce = { version = "0.6.1", features = ["helmet"] }
cynic = { version = "2.2.8", features = ["http-reqwest"] }
gloo = "0.8.0"
implicit-clone = "0.3.5"
lazy_static = "1.4.0"
log = "0.4.17"
paste = "1.0.12"
reqwest = "0.11.18"
serde = { version = "1.0.163", features = ["derive"] }
serde_json = "1.0.96"
wasm-logger = "0.2.0"
web-sys = { version = "0.3.63", features = ["Window", "Location"] }
wee_alloc = "0.4.5"
yew = { version = "0.20.0", features = ["csr"] }
yew-router = "0.17.0"
yewdux = "0.9.2"
[build-dependencies]
cynic-querygen = "2.2.8"
cargo-emit = "0.2.1"

59
frontend/Dockerfile Normal file
View file

@ -0,0 +1,59 @@
FROM docker.io/alpine:3.18.0 as alpine
FROM docker.io/lukemathwalker/cargo-chef:latest-rust-1.69.0 as chef
FROM codycraven/sassc:3.6.1 as css
SHELL ["/bin/ash", "-eo", "pipefail", "-c"]
ENV PYTHONUNBUFFERED=1
RUN apk add --update --no-cache python3=3.7.10-r0
WORKDIR /usr/src/scss
COPY ./compile_css.py .
RUN chmod +x ./compile_css.py
COPY ./scss ./src
RUN ./compile_css.py ./src ./dist
FROM chef as planner
WORKDIR /usr/src/frontend
RUN mkdir src && touch src/main.rs
COPY ./Cargo.toml ./Cargo.lock ./
RUN cargo chef prepare --recipe-path recipe.json
FROM chef as builder
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
WORKDIR /usr/local/bin
ARG TRUNK_VERSION="v0.16.0"
RUN wget -qO- https://github.com/thedodd/trunk/releases/download/${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz | tar -xzf-
RUN rustup target add wasm32-unknown-unknown
WORKDIR /usr/src/frontend
COPY ./.cargo ./.cargo
COPY --from=planner /usr/src/frontend/recipe.json .
RUN cargo chef cook --release --recipe-path recipe.json
COPY ./build.rs .
COPY ./schema.graphql ./query.graphql ./
RUN cargo build --release --frozen --offline
COPY ./src ./src
RUN cargo build --release --frozen --offline
COPY --from=css /usr/src/scss/dist ./css
COPY ./index.html ./index.html
RUN trunk build --release
FROM git.dergrimm.net/dergrimm/minify:2.12.5 as public
WORKDIR /usr/src/public
COPY --from=builder /usr/src/frontend/dist .
RUN minify . -r -o .
FROM alpine as binaryen
SHELL ["/bin/ash", "-eo", "pipefail", "-c"]
WORKDIR /tmp
ARG BINARYEN_VERSION="110"
RUN wget -qO- https://github.com/WebAssembly/binaryen/releases/download/version_${BINARYEN_VERSION}/binaryen-version_${BINARYEN_VERSION}-x86_64-linux.tar.gz | tar -xzf-
RUN cp ./binaryen-version_${BINARYEN_VERSION}/bin/wasm-opt /usr/local/bin && \
rm -rf ./binaryen-version_${BINARYEN_VERSION}
WORKDIR /usr/src/public
COPY --from=public /usr/src/public .
RUN find . -name "*.wasm" -type f -print0 | xargs -0 -I % wasm-opt % -o % -O --intrinsic-lowering -Oz
FROM docker.io/openresty/openresty:1.21.4.1-0-alpine as runner
COPY ./nginx.conf /usr/local/openresty/nginx/conf/nginx.conf
COPY --from=binaryen /usr/src/public /var/www/html
EXPOSE 80

28
frontend/build.rs Normal file
View file

@ -0,0 +1,28 @@
use std::env;
use std::fs;
use std::path::Path;
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
let schema = fs::read_to_string(Path::new(&manifest_dir).join("schema.graphql")).unwrap();
let query = fs::read_to_string(Path::new(&manifest_dir).join("query.graphql")).unwrap();
let code = cynic_querygen::document_to_fragment_structs(
query,
schema,
&cynic_querygen::QueryGenOptions {
schema_path: "schema.graphql".to_string(),
query_module: "schema".to_string(),
},
)
.unwrap();
let patched_code = code
.replace("mod queries", "pub mod queries")
.replace("mod schema", "pub mod schema");
fs::write(Path::new(&out_dir).join("graphql.rs"), patched_code).unwrap();
cargo_emit::rerun_if_changed!("schema.graphql", "query.graphql");
}

26
frontend/compile_css.py Normal file
View file

@ -0,0 +1,26 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import sys
from pathlib import Path
EXTENSIONS = ("*.css", "*.sass", "*.scss")
def compile(p):
print("==========")
print(f"{p}:")
dist = Path(sys.argv[2], *p.with_suffix(".css").parts[1:])
print(f"\tWriting to: {dist}")
print(f"\tCreating dir: {dist.parent}")
dist.parent.mkdir(parents=True, exist_ok=True)
prompt = f"sassc {p} > {dist}"
print(f"\tInvoking sassc: {prompt}")
os.system(prompt)
for ext in EXTENSIONS:
for p in Path(sys.argv[1]).rglob(ext):
compile(p)

37
frontend/index.html Normal file
View file

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://kit.fontawesome.com/7efbac0aa5.js"
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bulmaswatch@0.8.1/lumen/bulmaswatch.min.css"
integrity="sha256-JlUFCH1GY5bKd0cOYm53u7NEGByTk/7uoe/yWouFKTo="
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bulma-switch@2.0.4/dist/css/bulma-switch.min.css"
integrity="sha256-8EYN3r3ZVCWlBZCQhQOhcPX/CLKL1TVzxxeR/HzR5vU="
crossorigin="anonymous"
/>
<link data-trunk rel="css" href="css/styles.css" />
</head>
<body>
<noscript>
<strong>
This website does not work without JavaScript and WebAssembly.
</strong>
<br />
I too don't like this technology stack
</noscript>
</body>
</html>

24
frontend/nginx.conf Normal file
View file

@ -0,0 +1,24 @@
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
server_tokens off;
more_clear_headers Server;
server {
listen 80;
root /var/www/html;
location / {
try_files $uri /index.html;
}
}
}

33
frontend/query.graphql Normal file
View file

@ -0,0 +1,33 @@
query Users {
users {
name
repositories {
id
name
url
}
}
}
query UserByName($name: String!) {
userByName(name: $name) {
repositories {
name
url
}
}
}
query VerifyLogin($username: String!, $password: String!) {
verifyLogin(username: $username, password: $password)
}
mutation CreateRepository($user: String!, $name: String!) {
createRepository(input: { user: $user, name: $name }) {
id
}
}
mutation DeleteRepository($id: UUID!) {
deleteRepository(id: $id)
}

37
frontend/schema.graphql Normal file
View file

@ -0,0 +1,37 @@
input CreateRepositoryInput {
user: String!
name: String!
}
type Mutation {
createRepository(input: CreateRepositoryInput!): Repository!
deleteRepository(id: UUID!): Boolean!
}
type Query {
ping: String!
verifyLogin(username: String!, password: String!): Boolean!
user(id: UUID!): User!
userByName(name: String!): User!
users: [User!]!
repository(id: UUID!): Repository!
repositories: [Repository!]!
}
type Repository {
id: UUID!
user: User!
name: String!
url(scheme: Boolean): String!
}
type User {
id: UUID!
name: String!
repositories: [Repository!]!
}
"""
UUID encoded as a string
"""
scalar UUID

58
frontend/scss/styles.scss Normal file
View file

@ -0,0 +1,58 @@
body {
display: flex;
flex-direction: column;
overflow-x: hidden;
min-height: 100vh;
}
#wrapper {
flex: 1;
}
#main {
margin: 2vh 0;
}
#notifications {
overflow: hidden;
position: fixed;
right: 0;
z-index: 100;
}
#notifications-column {
width: 100%;
margin: 5% 0 0 auto;
}
.notification-slide-from-right {
position: relative;
animation-name: slideFromRight;
animation-duration: 0.5s;
animation-timing-function: ease;
transition: all 1s ease-out;
margin-right: 5%;
}
@keyframes slideFromRight {
from {
opacity: 0;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
// .loader {
// width: 48px;
// height: 48px;
// border: 5px solid black;
// border-bottom-color: transparent;
// border-radius: 50%;
// display: inline-block;
// box-sizing: border-box;
// animation: rotation 1s linear infinite;
// }

View file

@ -0,0 +1,51 @@
use yew::prelude::*;
pub struct Footer;
impl Component for Footer {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<footer class={classes!("footer")}>
<div class={classes!("columns")}>
<div class={classes!("column", "is-three-quarters")}>
<h3 class={classes!("title", "is-3")}>{ "Gitea Pages" }</h3>
<p>
<a href="https://git.dergrimm.net/dergrimm/gitea_pages"><strong>{ "Gitea Pages" }</strong></a> { " by " }
<a href="https://dergrimm.net">{ "Dominic Grimm" }</a> { ". " }
{ "Source code is licensed under the " } <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">{ "GNU General Public License version 3" }</a> {"."}
</p>
</div>
<div class={classes!("column")}>
<p>
<a href="https://www.rust-lang.org/" target="_blank">
<figure class={classes!("image")}>
<img src="https://forthebadge.com/images/badges/made-with-rust.svg" />
</figure>
</a>
</p>
<p>
<figure class={classes!("image")}>
<img src="https://forthebadge.com/images/badges/no-ragrets.svg" />
</figure>
</p>
</div>
</div>
<hr />
<div>
<p>
{ "©2023 Dominic Grimm" }
</p>
</div>
</footer>
}
}
}

View file

@ -0,0 +1,18 @@
use yew::prelude::*;
pub struct Loading;
impl Component for Loading {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<p class={classes!("has-text-centered")}>{ "Loading..." }</p>
}
}
}

View file

@ -0,0 +1,13 @@
pub mod footer;
pub mod loading;
pub mod navbar;
pub mod notification;
pub mod notification_listing;
pub mod user_pane;
pub use footer::Footer;
pub use loading::Loading;
pub use navbar::Navbar;
pub use notification::Notification;
pub use notification_listing::NotificationListing;
pub use user_pane::UserPane;

View file

@ -0,0 +1,124 @@
use std::rc::Rc;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{routes, stores};
pub enum Msg {
UpdateUser(Rc<stores::User>),
BurgerClicked,
Logout,
}
pub struct Navbar {
user: Rc<stores::User>,
user_dispatch: Dispatch<stores::User>,
burger_active: bool,
}
impl Component for Navbar {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
Self {
user: user_dispatch.get(),
user_dispatch,
burger_active: false,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
self.user = x;
true
}
Msg::BurgerClicked => {
self.burger_active = !self.burger_active;
true
}
Msg::Logout => {
self.user_dispatch.set(stores::User(None));
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<header>
<nav
class={classes!("navbar", "is-primary")}
role="navigation"
aria-label="main navigation"
>
<div class={classes!("navbar-brand")}>
<Link<routes::Route> to={routes::Route::Index} classes={classes!("navbar-item")}>
<strong>{ "Gitea Pages" }</strong>
</Link<routes::Route>>
<a
role="button"
onclick={ctx.link().callback(|_| Msg::BurgerClicked)}
class={classes!("navbar-burger")}
aria-label="menu"
aria-expandable="false"
>
<span aria-hidden="true" />
<span aria-hidden="true" />
<span aria-hidden="true" />
</a>
</div>
<div
class={classes!(
"navbar-menu",
"is-white",
if self.burger_active { Some("is-active") } else { None }
)}
>
<div class={classes!("navbar-end")}>
<a
href="https://git.dergrimm.net/dergrimm/gitea_pages"
target="_blank"
class={classes!("navbar-item")}
>
{ "Info" }
</a>
<div class={classes!("navbar-item")}>
<div class={classes!("buttons")}>
if self.user.logged_in() {
<button
onclick={ctx.link().callback(|_| Msg::Logout)}
class={classes!("button")}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-right-from-bracket")} />
</span>
<span>{ "Logout" }</span>
</button>
} else {
<Link<routes::Route> to={routes::Route::Login} classes={classes!("button")}>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-right-to-bracket")} />
</span>
<span>{ "Login" }</span>
</Link<routes::Route>>
}
</div>
</div>
</div>
</div>
</nav>
</header>
}
}
}

View file

@ -0,0 +1,126 @@
use gloo::timers::callback::Interval;
use std::rc::Rc;
use yew::prelude::*;
use crate::{graphql, stores};
pub enum Msg {
Remove,
}
#[derive(Clone, PartialEq)]
pub enum NotificationType {
Dark,
Primary,
Link,
Info,
Success,
Warning,
Danger,
}
pub fn class_from_notification_type(x: &NotificationType) -> &'static str {
match x {
NotificationType::Dark => "is-dark",
NotificationType::Primary => "is-primary",
NotificationType::Link => "is-link",
NotificationType::Info => "is-info",
NotificationType::Success => "is-success",
NotificationType::Warning => "is-warning",
NotificationType::Danger => "is-danger",
}
}
pub fn name_from_notification_type(x: &NotificationType) -> &'static str {
match x {
NotificationType::Dark => "Info",
NotificationType::Primary => "Info",
NotificationType::Link => "Info",
NotificationType::Info => "Info",
NotificationType::Success => "Success",
NotificationType::Warning => "Warning",
NotificationType::Danger => "Error",
}
}
#[derive(Clone, PartialEq)]
pub enum NotificationMessage {
Text(Vec<String>),
GraphQLError(graphql::GraphQLError),
}
#[derive(Properties, PartialEq)]
pub struct Props {
pub notifications: Rc<stores::Notifications>,
pub index: usize,
pub remove: Rc<Callback<usize, ()>>,
}
pub struct Notification {
_interval: Interval,
}
impl Component for Notification {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
_interval: {
let link = ctx.link().clone();
Interval::new(15_000, move || link.send_message(Msg::Remove))
},
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Remove => {
ctx.props().remove.emit(ctx.props().index);
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let notif = &ctx.props().notifications.notifications[&ctx.props().index];
html! {
<div class={classes!("block", "notification-slide-from-right")}>
<article class={classes!("message", class_from_notification_type(&notif.notification_type))}>
<div class={classes!("message-header")}>
<p>{ name_from_notification_type(&notif.notification_type) }</p>
<button
class={classes!("delete")}
aria-label="delete"
onclick={ctx.link().callback(|_| Msg::Remove)}
/>
</div>
<div class={classes!("message-body")}>
if let Some(message) = &notif.message {
{
match message {
NotificationMessage::Text(x) => html! {
{
for x.iter().map(|s| html! {
<>
{ s }
<br />
</>
})
}
},
NotificationMessage::GraphQLError(x) => html! {
{ x }
},
}
}
}
</div>
</article>
</div>
}
}
}

View file

@ -0,0 +1,58 @@
use std::rc::Rc;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{components, stores};
pub enum Msg {
UpdateNotifications(Rc<stores::Notifications>),
Remove(usize),
}
pub struct NotificationListing {
notifications: Rc<stores::Notifications>,
notifications_dispatch: Dispatch<stores::Notifications>,
}
impl Component for NotificationListing {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let notifications_dispatch =
Dispatch::subscribe(ctx.link().callback(Msg::UpdateNotifications));
Self {
notifications: notifications_dispatch.get(),
notifications_dispatch,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateNotifications(x) => {
self.notifications = x;
true
}
Msg::Remove(i) => {
self.notifications_dispatch
.reduce_mut(|notifs| notifs.notifications.remove(&i));
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let remove = Rc::new(ctx.link().callback(Msg::Remove));
html! {
{
for self.notifications.notifications.iter().rev().map(|(i, _)| html! {
<components::Notification notifications={self.notifications.clone()} index={i} remove={remove.clone()} />
})
}
}
}
}

View file

@ -0,0 +1,76 @@
use yew::prelude::*;
#[derive(PartialEq)]
pub struct Repository {
pub name: String,
pub url: Option<String>,
}
#[derive(Properties, PartialEq)]
pub struct Props {
pub name: AttrValue,
pub repositories: Vec<Repository>,
pub on_click: Option<Callback<usize>>,
}
pub enum Msg {
Emit(usize),
}
pub struct UserPane;
impl Component for UserPane {
type Message = Msg;
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Emit(i) => {
ctx.props().on_click.as_ref().unwrap().emit(i);
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<nav class={classes!("panel")}>
<p class={classes!("panel-heading")}>
{ &ctx.props().name }
</p>
{
for ctx.props().repositories.iter().enumerate().map(|(i, repo)| html! {
if let Some(url) = &repo.url {
<a
class={classes!("panel-block", "is-active")}
href={url.to_owned()}
target="_blank"
>
<span class={classes!("panel-icon")}>
<i class={classes!("fa-solid", "fa-book")} />
</span>
{ &repo.name }
</a>
} else {
<a
class={classes!("panel-block", "is-active")}
onclick={ctx.link().callback(move |_| Msg::Emit(i))}
>
<span class={classes!("panel-icon")}>
<i class={classes!("fa-solid", "fa-book")} />
</span>
{ &repo.name }
</a>
}
})
}
</nav>
}
}
}

99
frontend/src/graphql.rs Normal file
View file

@ -0,0 +1,99 @@
use lazy_static::lazy_static;
use serde::Deserialize;
use std::future::Future;
use std::pin::Pin;
use crate::stores;
lazy_static! {
pub static ref URL: String = format!(
"{}/graphql",
web_sys::window().unwrap().location().origin().unwrap()
);
}
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
pub trait ReqwestExt {
fn run_graphql<ResponseData, Vars, Extensions>(
self,
operation: cynic::Operation<ResponseData, Vars>,
) -> BoxFuture<
'static,
Result<cynic::GraphQlResponse<ResponseData, Extensions>, cynic::http::CynicReqwestError>,
>
where
Vars: serde::Serialize,
ResponseData: serde::de::DeserializeOwned + 'static,
Extensions: serde::de::DeserializeOwned + 'static;
}
impl ReqwestExt for reqwest::RequestBuilder {
fn run_graphql<ResponseData, Vars, Extensions>(
self,
operation: cynic::Operation<ResponseData, Vars>,
) -> BoxFuture<
'static,
Result<cynic::GraphQlResponse<ResponseData, Extensions>, cynic::http::CynicReqwestError>,
>
where
Vars: serde::Serialize,
ResponseData: serde::de::DeserializeOwned + 'static,
Extensions: serde::de::DeserializeOwned + 'static,
{
let builder = self.json(&operation);
Box::pin(async move {
match builder.send().await {
Ok(response) => {
let status = response.status();
if !status.is_success() {
let body_string = response.text().await?;
match serde_json::from_str::<cynic::GraphQlResponse<ResponseData, Extensions>>(
&body_string,
) {
Ok(response) => return Ok(response),
Err(_) => {
return Err(cynic::http::CynicReqwestError::ErrorResponse(
status,
body_string,
));
}
};
}
response
.json::<cynic::GraphQlResponse<ResponseData, Extensions>>()
.await
.map_err(cynic::http::CynicReqwestError::ReqwestError)
}
Err(e) => Err(cynic::http::CynicReqwestError::ReqwestError(e)),
}
})
}
}
pub fn client(user: Option<&stores::UserData>) -> reqwest::RequestBuilder {
let client = reqwest::Client::new().post(URL.as_str());
if let Some(x) = user {
client.basic_auth(&x.username, Some(&x.password))
} else {
client
}
}
#[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct ErrorExtensions {
#[serde(rename = "type")]
pub error_type: String,
}
pub type GraphQLError = cynic::GraphQlError<ErrorExtensions>;
pub type GraphQLResponse<T> = cynic::GraphQlResponse<T, ErrorExtensions>;
pub type GraphQLResult<T> = Result<GraphQLResponse<T>, cynic::http::CynicReqwestError>;
include!(concat!(env!("OUT_DIR"), "/graphql.rs"));
pub struct Uuid(pub String);
cynic::impl_scalar!(Uuid, schema::UUID);

View file

@ -0,0 +1,32 @@
use yew::prelude::*;
use crate::components;
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct Base;
impl Component for Base {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<div id="wrapper">
<components::Navbar />
{ for ctx.props().children.iter() }
</div>
<components::Footer />
</>
}
}
}

View file

@ -0,0 +1,63 @@
use std::rc::Rc;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{routes, stores};
pub enum Msg {
UpdateUser(Rc<stores::User>),
}
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct LoggedIn {
user: Rc<stores::User>,
_user_dispatch: Dispatch<stores::User>,
}
impl Component for LoggedIn {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
let user = user_dispatch.get();
if !user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Login);
}
Self {
user,
_user_dispatch: user_dispatch,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
let prev = self.user.logged_in();
self.user = x;
if !self.user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Login);
}
prev != self.user.logged_in()
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
if self.user.logged_in() {
{ for ctx.props().children.iter() }
}
}
}
}

View file

@ -0,0 +1,39 @@
use yew::prelude::*;
use crate::{components, layouts};
#[derive(Properties, PartialEq)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct Main;
impl Component for Main {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<layouts::Base>
<div class={classes!("columns", "is-centered")}>
<main id="main" class={classes!("column", "is-four-fifths")}>
{ for ctx.props().children.iter() }
</main>
</div>
</layouts::Base>
<div id="notifications" class={classes!("columns")}>
<div id="notifications-column" class={classes!("column", "is-one-third")}>
<components::NotificationListing />
</div>
</div>
</>
}
}
}

View file

@ -0,0 +1,9 @@
pub mod base;
pub mod logged_in;
pub mod main;
pub mod not_found;
pub use base::Base;
pub use logged_in::LoggedIn;
pub use main::Main;
pub use not_found::NotFound;

View file

@ -0,0 +1,49 @@
use bounce::helmet::Helmet;
use yew::prelude::*;
use yew_router::prelude::*;
use crate::routes;
#[derive(Properties, PartialEq)]
pub struct Props {
pub message: AttrValue,
#[prop_or(true)]
pub ellipsis: bool,
}
pub struct NotFound;
impl Component for NotFound {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<Helmet>
<title>{ &ctx.props().message }</title>
</Helmet>
<div class={classes!("has-text-centered")}>
<h1 class={classes!("title", "my-auto")}>
<i>
{ &ctx.props().message }
if ctx.props().ellipsis {
{ "..." }
}
</i>
</h1>
<p>
<Link<routes::Route> to={routes::Route::Index}>
{ "Back to home" }
</Link<routes::Route>>
</p>
</div>
</>
}
}
}

5
frontend/src/lib.rs Normal file
View file

@ -0,0 +1,5 @@
pub mod components;
pub mod graphql;
pub mod layouts;
pub mod routes;
pub mod stores;

46
frontend/src/main.rs Normal file
View file

@ -0,0 +1,46 @@
use bounce::{helmet::HelmetBridge, BounceRoot};
use implicit_clone::unsync::IString;
use yew::prelude::*;
use yew_router::prelude::*;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
use frontend::{layouts, routes};
pub const DEFAULT_TITLE: &str = "Gitea Pages";
fn format_title(title: IString) -> IString {
IString::from(format!("{} | {}", title, DEFAULT_TITLE))
}
struct App;
impl Component for App {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<BrowserRouter>
<BounceRoot>
<HelmetBridge default_title={DEFAULT_TITLE} {format_title} />
<layouts::Main>
<Switch<routes::Route> render={routes::switch} />
</layouts::Main>
</BounceRoot>
</BrowserRouter>
}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::Renderer::<App>::new().render();
}

View file

@ -0,0 +1,429 @@
use bounce::helmet::Helmet;
use cynic::{MutationBuilder, QueryBuilder};
use std::rc::Rc;
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
stores,
};
pub enum Msg {
Void,
UpdateUser(Rc<stores::User>),
LoadUsers,
UsersDone(graphql::GraphQLResult<graphql::queries::Users>),
OpenNewModal,
CloseNewModal,
NewModalSubmit,
NewModalSubmitDone(graphql::GraphQLResult<graphql::queries::CreateRepository>),
OpenEditModal(usize, usize),
CloseEditModal,
Delete,
DeleteDone(graphql::GraphQLResult<graphql::queries::DeleteRepository>),
}
pub struct Index {
notifications_dispatch: Dispatch<stores::Notifications>,
user: Rc<stores::User>,
_user_dispatch: Dispatch<stores::User>,
loading: bool,
users: Vec<graphql::queries::User>,
new_modal: bool,
new_modal_save_loading: bool,
new_modal_user: NodeRef,
new_modal_repo: NodeRef,
delete_modal: Option<(usize, usize)>,
delete_modal_delete_loading: bool,
}
impl Component for Index {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let notifications_dispatch = Dispatch::subscribe(ctx.link().callback(|_| Msg::Void));
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
ctx.link().send_message(Msg::LoadUsers);
Self {
notifications_dispatch,
user: user_dispatch.get(),
_user_dispatch: user_dispatch,
loading: false,
users: vec![],
new_modal: false,
new_modal_save_loading: false,
new_modal_user: NodeRef::default(),
new_modal_repo: NodeRef::default(),
delete_modal: None,
delete_modal_delete_loading: false,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Void => false,
Msg::UpdateUser(x) => {
self.user = x;
true
}
Msg::LoadUsers => {
self.loading = true;
let client = graphql::client(None);
let operation = graphql::queries::Users::build(());
ctx.link().send_future(async move {
Msg::UsersDone(client.run_graphql(operation).await)
});
true
}
Msg::UsersDone(x) => {
self.loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
false
} else {
let data = resp.data.unwrap();
self.users = data.users;
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
Msg::OpenNewModal => {
self.new_modal = true;
true
}
Msg::CloseNewModal => {
self.new_modal = false;
self.new_modal_save_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Msg::NewModalSubmit => {
let user = match self.new_modal_user.cast::<HtmlInputElement>() {
Some(x) => x.value(),
None => return false,
};
let name = match self.new_modal_repo.cast::<HtmlInputElement>() {
Some(x) => x.value(),
None => return false,
};
self.new_modal_save_loading = true;
let operation = graphql::queries::CreateRepository::build(
graphql::queries::CreateRepositoryVariables { user, name },
);
let client = graphql::client(self.user.0.as_ref());
ctx.link().send_future(async move {
Msg::NewModalSubmitDone(client.run_graphql(operation).await)
});
true
}
Msg::NewModalSubmitDone(x) => {
self.new_modal_save_loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification {
notification_type: components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::GraphQLError(e)),
});
}
});
true
} else {
ctx.link().send_message(Msg::CloseNewModal);
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
Msg::OpenEditModal(i, j) => {
self.delete_modal = Some((i, j));
true
}
Msg::CloseEditModal => {
self.delete_modal = None;
self.delete_modal_delete_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Msg::Delete => {
let modal = self.delete_modal.unwrap();
self.delete_modal_delete_loading = true;
let operation = graphql::queries::DeleteRepository::build(
graphql::queries::DeleteRepositoryVariables {
id: self.users[modal.0].repositories[modal.1].id.to_owned(),
},
);
let client = graphql::client(self.user.0.as_ref());
ctx.link().send_future(async move {
Msg::DeleteDone(client.run_graphql(operation).await)
});
true
}
Msg::DeleteDone(x) => match x {
Ok(_) => {
self.delete_modal = None;
self.delete_modal_delete_loading = false;
ctx.link().send_message(Msg::LoadUsers);
true
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type: components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::Text(
vec![e.to_string()],
)),
});
});
false
}
},
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<Helmet>
<title>{ "Home" }</title>
</Helmet>
<div class={classes!("columns", "is-centered")}>
<div class={classes!("column", "is-half")}>
<div class={classes!("columns", "is-multiline")}>
<div class={classes!("column", "is-full")}>
<button
class={classes!("button", "is-primary", "is-fullwidth")}
onclick={ctx.link().callback(|_| Msg::OpenNewModal)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-plus")} />
</span>
<span>{ "New" }</span>
</button>
</div>
if self.loading {
<div class={classes!("column", "is-full")}>
<components::Loading />
</div>
} else {
{
for self.users.iter().enumerate().map(|(i, user)| html! {
<div class={classes!("column", "is-full")}>
<components::UserPane
name={user.name.to_owned()}
repositories={user.repositories
.iter()
.map(|repo| components::user_pane::Repository {
name: repo.name.to_owned(),
url: None,
})
.collect::<Vec<_>>()
}
on_click={ctx.link().callback(move |j| Msg::OpenEditModal(i, j))}
/>
</div>
})
}
}
</div>
</div>
</div>
if self.new_modal {
<div class={classes!("modal", "is-active")}>
<div class={classes!("modal-background")} onclick={ctx.link().callback(|_| Msg::CloseNewModal)} />
<div class={classes!("modal-card")}>
<header class={classes!("modal-card-head")}>
<p class={classes!("modal-card-title")}>
{ "Edit" }
</p>
<button
class={classes!("delete")}
aria-label="close"
onclick={ctx.link().callback(|_| Msg::CloseNewModal)}
/>
</header>
<section class={classes!("modal-card-body")}>
<table class={classes!("table", "is-bordered", "is-striped", "is-hoverable", "is-fullwidth")}>
<tbody>
<tr>
<th>{ "User" }</th>
<td>
<input
class={classes!("input")}
type="text"
required=true
placeholder="User"
ref={self.new_modal_user.clone()}
/>
</td>
</tr>
<tr>
<th>{ "Repository" }</th>
<td>
<input
class={classes!("input")}
type="text"
required=true
placeholder="Repository"
ref={self.new_modal_repo.clone()}
/>
</td>
</tr>
</tbody>
</table>
</section>
<footer class={classes!("modal-card-foot")}>
<div class={classes!("field", "is-grouped")}>
<p class={classes!("control")}>
<button
class={classes!(
"button",
"is-success",
if self.new_modal_save_loading { Some("is-loading") } else { None }
)}
onclick={ctx.link().callback(|_| Msg::NewModalSubmit)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-check")} />
</span>
<span>{ "Save" }</span>
</button>
</p>
<p class={classes!("control")}>
<button class={classes!("button")} onclick={ctx.link().callback(|_| Msg::CloseNewModal)}>
{ "Cancel" }
</button>
</p>
</div>
</footer>
</div>
</div>
}
if let Some(modal) = &self.delete_modal {
<div class={classes!("modal", "is-active")}>
<div class={classes!("modal-background")} onclick={ctx.link().callback(|_| Msg::CloseEditModal)} />
<div class={classes!("modal-card")}>
<header class={classes!("modal-card-head")}>
<p class={classes!("modal-card-title")}>
{ "Edit" }
</p>
<button
class={classes!("delete")}
aria-label="close"
onclick={ctx.link().callback(|_| Msg::CloseEditModal)}
/>
</header>
<section class={classes!("modal-card-body")}>
<p>
{ &self.users[modal.0].name }
{ "/" }
{ &self.users[modal.0].repositories[modal.1].name }
</p>
</section>
<footer class={classes!("modal-card-foot")}>
<div class={classes!("field", "is-grouped")}>
<p class={classes!("control")}>
<button
class={classes!(
"button",
"is-danger",
if self.delete_modal_delete_loading { Some("is-loading") } else { None }
)}
onclick={ctx.link().callback(|_| Msg::Delete)}
>
<span class={classes!("icon", "is-small")}>
<i class={classes!("fa-solid", "fa-trash")} />
</span>
<span>{ "Delete" }</span>
</button>
</p>
<p class={classes!("control")}>
<button class={classes!("button")} onclick={ctx.link().callback(|_| Msg::CloseEditModal)}>
{ "Cancel" }
</button>
</p>
</div>
</footer>
</div>
</div>
}
</>
}
}
}

View file

@ -0,0 +1,237 @@
use bounce::helmet::Helmet;
use cynic::QueryBuilder;
use std::rc::Rc;
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yew_router::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
routes, stores,
};
pub enum Msg {
UpdateUser(Rc<stores::User>),
UpdateNotifications(Rc<stores::Notifications>),
Login,
LoginDone {
user_data: stores::UserData,
result: graphql::GraphQLResult<graphql::queries::VerifyLogin>,
},
}
pub struct Login {
user: Rc<stores::User>,
user_dispatch: Dispatch<stores::User>,
notifications: Rc<stores::Notifications>,
notifications_dispatch: Dispatch<stores::Notifications>,
username: NodeRef,
password: NodeRef,
loading: bool,
error: Option<&'static str>,
}
impl Component for Login {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let user_dispatch = Dispatch::subscribe(ctx.link().callback(Msg::UpdateUser));
let notifications_dispatch =
Dispatch::subscribe(ctx.link().callback(Msg::UpdateNotifications));
Self {
user: user_dispatch.get(),
user_dispatch,
notifications: notifications_dispatch.get(),
notifications_dispatch,
username: NodeRef::default(),
password: NodeRef::default(),
loading: false,
error: None,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateUser(x) => {
self.error = None;
let prev = self.user.logged_in();
self.user = x;
prev != self.user.logged_in()
}
Msg::UpdateNotifications(x) => {
self.notifications = x;
false
}
Msg::Login => {
self.error = None;
let username = match self.username.cast::<HtmlInputElement>().map(|x| x.value()) {
Some(x) => {
if x.is_empty() {
return false;
} else {
x
}
}
None => {
return false;
}
};
let password = match self.password.cast::<HtmlInputElement>().map(|x| x.value()) {
Some(x) => {
if x.is_empty() {
return false;
} else {
x
}
}
None => {
return false;
}
};
self.loading = true;
let operation =
graphql::queries::VerifyLogin::build(graphql::queries::VerifyLoginVariables {
username: username.to_owned(),
password: password.to_owned(),
});
ctx.link().send_future(async move {
Msg::LoginDone {
user_data: stores::UserData { username, password },
result: graphql::client(None).run_graphql(operation).await,
}
});
true
}
Msg::LoginDone { user_data, result } => {
self.loading = false;
match result {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
true
} else if resp.data.unwrap().verify_login {
self.error = None;
self.user_dispatch.set(stores::User(Some(user_data)));
false
} else {
const MESSAGE: &str = "Username or password not correct";
self.error = Some(MESSAGE);
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type:
components::notification::NotificationType::Danger,
message: Some(
components::notification::NotificationMessage::Text(vec![
MESSAGE.to_string(),
]),
),
});
});
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification {
notification_type:
components::notification::NotificationType::Danger,
message: Some(components::notification::NotificationMessage::Text(
vec![e.to_string()],
)),
});
});
false
}
}
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
if self.user.logged_in() {
ctx.link().navigator().unwrap().push(&routes::Route::Index);
}
html! {
<>
<Helmet>
<title>{ "Login" }</title>
</Helmet>
<div class={classes!("columns", "is-centered", "my-auto")}>
<div class={classes!("column", "is-half", "box")}>
<div class={classes!("p-4")}>
<form onsubmit={ctx.link().callback(|e: SubmitEvent| { e.prevent_default(); Msg::Login })}>
<div class={classes!("field")}>
<p class={classes!("control", "has-icons-left")}>
<input
class={classes!("input")}
type="text"
placeholder="Username"
ref={self.username.clone()}
/>
<span class={classes!("icon", "is-small", "is-left")}>
<i class={classes!("fa-solid", "fa-envelope")} />
</span>
</p>
</div>
<div class={classes!("field")}>
<p class={classes!("control", "has-icons-left")}>
<input
class={classes!("input")}
type="password"
placeholder="Password"
ref={self.password.clone()}
/>
<span class={classes!("icon", "is-small", "is-left")}>
<i class={classes!("fa-solid", "fa-lock")} />
</span>
</p>
</div>
<div class={classes!("field")}>
<p class={classes!("control")}>
<button
type="submit"
class={classes!("button", "is-success", "is-fullwidth", if self.loading { Some("is-loading") } else { None })}
>
{ "Login" }
</button>
</p>
</div>
if let Some(message) = self.error {
<p class={classes!("help", "is-danger")}>
{ message }
</p>
}
</form>
</div>
</div>
</div>
</>
}
}
}

View file

@ -0,0 +1,48 @@
use yew::prelude::*;
use yew_router::prelude::*;
use crate::layouts;
pub mod index;
pub mod login;
pub mod not_found;
pub mod user;
pub use index::Index;
pub use login::Login;
pub use not_found::NotFound;
pub use user::User;
#[derive(Clone, Routable, PartialEq, Eq, Debug)]
pub enum Route {
#[at("/")]
Index,
// #[at("/user/:name")]
// User { name: String },
#[at("/login")]
Login,
#[not_found]
#[at("/404")]
NotFound,
}
pub fn switch(route: Route) -> Html {
match route {
Route::Index => html! {
<layouts::LoggedIn>
<Index />
</layouts::LoggedIn>
},
// Route::User { name } => html! {
// <User {name} />
// },
Route::Login => html! {
<Login />
},
Route::NotFound => html! {
<NotFound />
},
}
}

View file

@ -0,0 +1,20 @@
use yew::prelude::*;
use crate::layouts;
pub struct NotFound;
impl Component for NotFound {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<layouts::NotFound message="Page not found" />
}
}
}

143
frontend/src/routes/user.rs Normal file
View file

@ -0,0 +1,143 @@
use bounce::helmet::Helmet;
use cynic::QueryBuilder;
use yew::prelude::*;
use yewdux::prelude::*;
use crate::{
components,
graphql::{self, ReqwestExt},
stores,
};
#[derive(Properties, PartialEq)]
pub struct Props {
pub name: AttrValue,
}
pub enum Msg {
Void,
Done(graphql::GraphQLResult<graphql::queries::UserByName>),
}
struct Repository {
name: String,
url: String,
}
pub struct User {
notifications_dispatch: Dispatch<stores::Notifications>,
loading: bool,
repositories: Vec<Repository>,
}
impl Component for User {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let operation =
graphql::queries::UserByName::build(graphql::queries::UserByNameVariables {
name: ctx.props().name.to_string(),
});
let client = graphql::client(None);
ctx.link()
.send_future(async move { Msg::Done(client.run_graphql(operation).await) });
Self {
notifications_dispatch: Dispatch::subscribe(ctx.link().callback(|_| Msg::Void)),
loading: true,
repositories: vec![],
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Void => false,
Msg::Done(x) => {
self.loading = false;
match x {
Ok(resp) => {
if let Some(errors) = resp.errors {
self.notifications_dispatch.reduce_mut(|notifs| {
for e in errors {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::GraphQLError(
e,
),
)));
}
});
false
} else {
self.repositories = resp
.data
.unwrap()
.user_by_name
.repositories
.into_iter()
.map(|repo| Repository {
name: repo.name,
url: repo.url,
})
.collect();
true
}
}
Err(e) => {
self.notifications_dispatch.reduce_mut(|notifs| {
notifs.push(stores::Notification::danger(Some(
components::notification::NotificationMessage::Text(vec![
e.to_string()
]),
)));
});
false
}
}
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let name = &ctx.props().name;
html! {
<>
<Helmet>
<title>{ name }</title>
</Helmet>
<div class={classes!("columns", "is-centered")}>
<div class={classes!("column", "is-half")}>
<div class={classes!("columns", "is-multiline")}>
if self.loading {
<div class={classes!("column", "is-full")}>
<components::Loading />
</div>
} else {
<div class={classes!("column", "is-full")}>
<components::UserPane
name={&ctx.props().name}
repositories={
self.repositories
.iter()
.map(|repo| components::user_pane::Repository {
name: repo.name.to_owned(),
url: Some(repo.url.to_owned())
})
.collect::<Vec<_>>()
}
/>
</div>
}
</div>
</div>
</div>
</>
}
}
}

67
frontend/src/stores.rs Normal file
View file

@ -0,0 +1,67 @@
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::num::Wrapping;
use yewdux::prelude::*;
use crate::components;
#[derive(PartialEq, Serialize, Deserialize, Debug)]
pub struct UserData {
pub username: String,
pub password: String,
}
#[derive(Default, PartialEq, Serialize, Deserialize, Store, Debug)]
#[store(storage = "local")]
pub struct User(pub Option<UserData>);
impl User {
pub fn logged_in(&self) -> bool {
self.0.is_some()
}
}
#[derive(Clone, PartialEq)]
pub struct Notification {
pub notification_type: components::notification::NotificationType,
pub message: Option<components::notification::NotificationMessage>,
}
macro_rules! from_notification_types {
($($type:ident),*) => {
$(
paste::item! {
pub fn [<$type:snake>](message: Option<components::notification::NotificationMessage>) -> Self {
Self {
notification_type: components::notification::NotificationType::$type,
message,
}
}
}
)*
};
}
impl Notification {
from_notification_types!(Dark, Primary, Link, Info, Success, Warning, Danger);
}
#[derive(Default, Clone, PartialEq, Store)]
pub struct Notifications {
counter: Wrapping<usize>,
pub notifications: BTreeMap<usize, Notification>,
}
impl Notifications {
fn inc(&mut self) {
self.counter += 1;
}
pub fn push(&mut self, notif: Notification) -> usize {
let id = self.counter.0;
self.notifications.insert(id, notif);
self.inc();
id
}
}