feat: with como_web
Some checks failed
continuous-integration/drone/push Build is failing

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2023-10-21 11:23:11 +02:00
parent 6e16fc6b2b
commit 71b5a63700
48 changed files with 7900 additions and 27 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
#[cfg(feature = "ssr")]
pub fn register() {}

View File

@@ -0,0 +1,55 @@
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use crate::common::layout::DashboardLayout;
use crate::routes::dash::home::DashHomePage;
use crate::routes::features_view::FeaturesView;
use crate::routes::home::HomePage;
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
view! {
<Stylesheet id="leptos" href="/pkg/como_web.css"/>
<Router>
<main>
<Routes>
<Route
path=""
view=|| {
view! { <HomePage/> }
}
/>
<Route
path="/dash"
view=|| {
view! { <DashboardLayout/> }
}
>
<Route
path=""
view=|| {
view! { <DashHomePage/> }
}
/>
<Route
path="home"
view=|| {
view! { <DashHomePage/> }
}
/>
</Route>
<Route
path="/features"
view=|| {
view! { <FeaturesView/> }
}
/>
</Routes>
</main>
</Router>
}
}

View File

@@ -0,0 +1,2 @@
pub mod layout;
pub mod graphql;

View File

@@ -0,0 +1 @@
pub type UUID = uuid::Uuid;

View File

@@ -0,0 +1,49 @@
use leptos::*;
use leptos_router::*;
use crate::features::command_line::CommandLine;
use crate::features::navbar_projects::NavbarProjects;
#[component]
pub fn DashNav() -> impl IntoView {
view! {
<nav class="min-w-[200px] p-4 space-y-4 h-screen sticky top-0 select-none bg-gray-800">
<div>
<a href="/dash/home" class="text-xl">
"como"
</a>
</div>
<div>
<a href="/dash/current" class="">
"inbox"
</a>
</div>
<div>
<p class="text-sm mb-0.5 dark:text-gray-500">"Favorites"</p>
<a href="/dash/current" class="dark:text-gray-300 pl-2">
"inbox"
</a>
</div>
<div>
<p class="text-sm mb-0.5 dark:text-gray-500">"Projects"</p>
<div class="pl-2 dark:text-gray-300">
<NavbarProjects/>
</div>
</div>
</nav>
}
}
#[component]
pub fn DashboardLayout() -> impl IntoView {
view! {
<div class="flex flex-row">
<DashNav/>
<div id="content" class="px-0.5 flex-grow">
<CommandLine>
<Outlet/>
</CommandLine>
</div>
</div>
}
}

View File

@@ -0,0 +1,43 @@
use cfg_if::cfg_if;
cfg_if! { if #[cfg(feature = "ssr")] {
use axum::{
body::{boxed, Body, BoxBody},
extract::State,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use leptos::{LeptosOptions, view};
use crate::app::App;
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else{
let handler = leptos_axum::render_app_to_stream(
options.to_owned(),
move || view!{ <App/> }
);
handler(req).await.into_response()
}
}
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<BoxBody>, (StatusCode, String)> {
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.map(boxed)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
}}

View File

@@ -0,0 +1,3 @@
pub mod command_line;
pub mod dashboard_list_view;
pub mod navbar_projects;

View File

@@ -0,0 +1,56 @@
use leptos::*;
#[derive(Clone, Debug)]
pub struct CommandLineState {
hidden: bool,
}
#[component]
pub fn CommandLineModalView() -> impl IntoView {
view! { <div>"modal"</div> }
}
#[component]
pub fn CommandLineModal() -> impl IntoView {
let state =
use_context::<RwSignal<CommandLineState>>().expect("command line state must be provided");
let (hidden, _) = create_slice(state, |state| state.hidden, |state, n| state.hidden = n);
view! {
{move || {
if !hidden.get() {
view! { <CommandLineModalView/> }
} else {
view! { }.into_view()
}
}}
}
}
#[component]
pub fn CommandLine(children: Children) -> impl IntoView {
let state = create_rw_signal(CommandLineState { hidden: true });
provide_context(state);
let (hidden, set_hidden) =
create_slice(state, |state| state.hidden, |state, n| state.hidden = n);
leptos_dom::helpers::window_event_listener(ev::keypress, move |event| {
if event.ctrl_key() {
match event.code().as_str() {
"KeyK" => {
set_hidden.set(!hidden.get());
//log!("toggle command")
}
_ => {}
}
}
});
view! {
<div>
<div>{children()}</div>
<CommandLineModal/>
</div>
}
}

View File

@@ -0,0 +1,4 @@
pub mod dashboard_list_view;
pub mod gen;
pub use dashboard_list_view::*;

View File

@@ -0,0 +1,93 @@
use graphql_client::{GraphQLQuery, Response};
use leptos::*;
use crate::features::dashboard_list_view::gen::queries::get_projects_list_view::GetProjectsListViewGetProjectsItems;
use super::gen::queries::get_projects_list_view::{
GetProjectsListViewGetProjects, ResponseData, Variables,
};
use super::gen::queries::GetProjectsListView;
pub async fn get_projects_list() -> anyhow::Result<Vec<GetProjectsListViewGetProjects>> {
let request_body = GetProjectsListView::build_query(Variables {});
let payload = serde_json::to_string(&request_body)?;
let res = reqwasm::http::Request::post("http://localhost:3001/graphql")
.credentials(reqwasm::http::RequestCredentials::Include)
.body(payload)
.send()
.await?;
let response_body: Response<ResponseData> = res.json().await?;
Ok(response_body
.data
.ok_or(anyhow::anyhow!("failed to get projects list"))?
.get_projects)
}
#[component]
pub fn DashboardItemView(item: GetProjectsListViewGetProjectsItems) -> impl IntoView {
view! { <div class="dashboard-list-item dashboard-item">{item.title}</div> }
}
#[component]
pub fn DashboardProjectItemView(project: GetProjectsListViewGetProjects) -> impl IntoView {
view! {
<div class="dashboard-list-item dashboard-list-project">
<a href=format!("/dash/project/{}", & project.id) class="project-item flex flex-row">
<div class="space-x-2">
<span>{&project.name}</span>
<span class="text-gray-50">{project.items.len()}</span>
<span class="flex-grow"></span>
</div>
</a>
</div>
}
}
#[component]
pub fn DashboardListView(
projects: Resource<(), Vec<GetProjectsListViewGetProjects>>,
) -> impl IntoView {
let projects_view = move || {
projects.with(|projects| {
if projects.is_none() {
return Vec::new();
}
let projects = projects.as_ref().unwrap();
if projects.is_empty() {
return vec![view! { <div class="project-item">"No projects"</div> }.into_any()];
}
projects
.into_iter()
.filter(|project| !project.items.is_empty())
.map(|project| {
view! {
<div>
<DashboardProjectItemView project=project.clone()/>
{&project
.items
.clone()
.into_iter()
.map(|item| {
view! { <DashboardItemView item=item/> }
})
.collect::<Vec<_>>()
.into_view()}
</div>
}
.into_any()
})
.collect::<Vec<_>>()
})
};
view! {<div class="project-items">{projects_view}</div> }
}
#[component]
pub fn DashboardList() -> impl IntoView {
let projects = create_local_resource(|| (), |_| async { get_projects_list().await.unwrap() });
view! {<DashboardListView projects=projects/> }
}

View File

@@ -0,0 +1 @@
pub mod queries;

View File

@@ -0,0 +1,81 @@
#![allow(clippy::all, warnings)]
pub struct GetProjectsListView;
pub mod get_projects_list_view {
#![allow(dead_code)]
use std::result::Result;
pub const OPERATION_NAME: &str = "GetProjectsListView";
pub const QUERY : & str = "query GetProjectsListView {\n getProjects {\n id\n name\n\n items {\n id\n title\n description\n state\n }\n }\n}\n" ;
use super::*;
use serde::{Deserialize, Serialize};
#[allow(dead_code)]
type Boolean = bool;
#[allow(dead_code)]
type Float = f64;
#[allow(dead_code)]
type Int = i64;
#[allow(dead_code)]
type ID = String;
type UUID = crate::common::graphql::UUID;
#[derive(Clone, Debug)]
pub enum ItemState {
CREATED,
DONE,
ARCHIVED,
DELETED,
Other(String),
}
impl ::serde::Serialize for ItemState {
fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_str(match *self {
ItemState::CREATED => "CREATED",
ItemState::DONE => "DONE",
ItemState::ARCHIVED => "ARCHIVED",
ItemState::DELETED => "DELETED",
ItemState::Other(ref s) => &s,
})
}
}
impl<'de> ::serde::Deserialize<'de> for ItemState {
fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s: String = ::serde::Deserialize::deserialize(deserializer)?;
match s.as_str() {
"CREATED" => Ok(ItemState::CREATED),
"DONE" => Ok(ItemState::DONE),
"ARCHIVED" => Ok(ItemState::ARCHIVED),
"DELETED" => Ok(ItemState::DELETED),
_ => Ok(ItemState::Other(s)),
}
}
}
#[derive(Serialize, Clone, Debug)]
pub struct Variables;
#[derive(Deserialize, Clone, Debug)]
pub struct ResponseData {
#[serde(rename = "getProjects")]
pub get_projects: Vec<GetProjectsListViewGetProjects>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct GetProjectsListViewGetProjects {
pub id: UUID,
pub name: String,
pub items: Vec<GetProjectsListViewGetProjectsItems>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct GetProjectsListViewGetProjectsItems {
pub id: UUID,
pub title: String,
pub description: Option<String>,
pub state: ItemState,
}
}
impl graphql_client::GraphQLQuery for GetProjectsListView {
type Variables = get_projects_list_view::Variables;
type ResponseData = get_projects_list_view::ResponseData;
fn build_query(variables: Self::Variables) -> ::graphql_client::QueryBody<Self::Variables> {
graphql_client::QueryBody {
variables,
query: get_projects_list_view::QUERY,
operation_name: get_projects_list_view::OPERATION_NAME,
}
}
}

View File

@@ -0,0 +1,13 @@
query GetProjectsListView {
getProjects {
id
name
items {
id
title
description
state
}
}
}

View File

@@ -0,0 +1,4 @@
pub mod gen;
pub mod navbar_projects;
pub use navbar_projects::*;

View File

@@ -0,0 +1 @@
pub mod queries;

View File

@@ -0,0 +1,43 @@
#![allow(clippy::all, warnings)]
pub struct GetProjectsListView;
pub mod get_projects_list_view {
#![allow(dead_code)]
use std::result::Result;
pub const OPERATION_NAME: &str = "GetProjectsListView";
pub const QUERY: &str =
"query GetProjectsListView {\n getProjects {\n id\n name\n }\n}\n";
use super::*;
use serde::{Deserialize, Serialize};
#[allow(dead_code)]
type Boolean = bool;
#[allow(dead_code)]
type Float = f64;
#[allow(dead_code)]
type Int = i64;
#[allow(dead_code)]
type ID = String;
type UUID = crate::common::graphql::UUID;
#[derive(Serialize, Clone, Debug)]
pub struct Variables;
#[derive(Deserialize, Clone, Debug)]
pub struct ResponseData {
#[serde(rename = "getProjects")]
pub get_projects: Vec<GetProjectsListViewGetProjects>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct GetProjectsListViewGetProjects {
pub id: UUID,
pub name: String,
}
}
impl graphql_client::GraphQLQuery for GetProjectsListView {
type Variables = get_projects_list_view::Variables;
type ResponseData = get_projects_list_view::ResponseData;
fn build_query(variables: Self::Variables) -> ::graphql_client::QueryBody<Self::Variables> {
graphql_client::QueryBody {
variables,
query: get_projects_list_view::QUERY,
operation_name: get_projects_list_view::OPERATION_NAME,
}
}
}

View File

@@ -0,0 +1,6 @@
query GetProjectsListView {
getProjects {
id
name
}
}

View File

@@ -0,0 +1,69 @@
use graphql_client::{GraphQLQuery, Response};
use leptos::*;
use crate::features::navbar_projects::gen::queries::get_projects_list_view::{
ResponseData, Variables,
};
use crate::features::navbar_projects::gen::queries::GetProjectsListView;
use super::gen::queries::get_projects_list_view::GetProjectsListViewGetProjects;
pub async fn get_projects_list() -> anyhow::Result<Vec<GetProjectsListViewGetProjects>> {
let request_body = GetProjectsListView::build_query(Variables {});
let payload = serde_json::to_string(&request_body)?;
let res = reqwasm::http::Request::post("http://localhost:3001/graphql")
.credentials(reqwasm::http::RequestCredentials::Include)
.body(payload)
.send()
.await?;
let response_body: Response<ResponseData> = res.json().await?;
Ok(response_body
.data
.ok_or(anyhow::anyhow!("failed to get projects list"))?
.get_projects)
}
#[component]
pub fn NavbarProjectsView(
projects: Resource<(), Vec<GetProjectsListViewGetProjects>>,
) -> impl IntoView {
let projects_view = move || {
projects.with(|projects| {
if projects.is_none() {
return Vec::new()
}
let projects = projects.as_ref().unwrap();
if projects.is_empty() {
return vec![view! { <div class="project-item">"No projects"</div> }.into_any()];
}
projects
.into_iter()
.map(|project| {
view! {
<a href=format!("/dash/project/{}", & project.id) class="project-item">
<div class="project-item-name hover:dark:bg-blue-700 rounded-md p-0.5 px-2">
{&project.name}
</div>
</a>
}.into_any()
})
.collect::<Vec<_>>()
})
};
view! { <div class="project-items space-y-1">{projects_view}</div> }
}
#[component]
pub fn NavbarProjects() -> impl IntoView {
let projects =
create_local_resource(|| (), |_| async { get_projects_list().await.unwrap() });
view! { <NavbarProjectsView projects=projects/> }
}

View File

@@ -0,0 +1,27 @@
pub mod api;
pub mod app;
pub mod common;
pub mod fallback;
pub mod features;
pub mod routes;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "hydrate")] {
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub fn hydrate() {
use app::*;
use leptos::*;
console_error_panic_hook::set_once();
leptos::mount_to_body(move || {
view! { <App/> }
});
}
}
}

View File

@@ -0,0 +1,45 @@
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{extract::Extension, routing::post, Router};
use como_web::app::*;
use como_web::fallback::file_and_error_handler;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
use tracing_subscriber::EnvFilter;
std::env::set_var("COMO_GATEWAY_URL", "https://api.como.i.kjuulh.io/graphql");
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.init();
let conf = get_configuration(None).await.unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
como_web::api::register();
let app = Router::new()
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
.leptos_routes(&leptos_options.clone(), routes, || view! { <App/> })
.fallback(file_and_error_handler)
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
// log!("listening on http://{}", &addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}

View File

@@ -0,0 +1,3 @@
pub mod dash;
pub mod features_view;
pub mod home;

View File

@@ -0,0 +1 @@
pub mod home;

View File

@@ -0,0 +1,12 @@
use leptos::*;
use crate::features::dashboard_list_view::DashboardList;
#[component]
pub fn DashHomePage() -> impl IntoView {
view! {
<div class="home-dash">
<DashboardList/>
</div>
}
}

View File

@@ -0,0 +1,43 @@
use leptos::*;
use uuid::Uuid;
use crate::features::navbar_projects::gen::queries::get_projects_list_view::GetProjectsListViewGetProjects;
use crate::features::navbar_projects::NavbarProjectsView;
#[component]
pub fn FeaturesView() -> impl IntoView {
let projects = create_local_resource(
|| (),
|_| async {
vec![
GetProjectsListViewGetProjects {
id: Uuid::new_v4(),
name: "some-name".to_string(),
},
GetProjectsListViewGetProjects {
id: Uuid::new_v4(),
name: "some-other-name".to_string(),
},
]
},
);
let emptyProjects: Resource<(), Vec<GetProjectsListViewGetProjects>> =
create_local_resource(|| (), |_| async { Vec::new() });
view! {
<div>
<div class="space-y-5 p-2">
<h1>"NavbarProjects"</h1>
<h2>"Projects"</h2>
<div class="feature-case">
<NavbarProjectsView projects=projects/>
</div>
<h2>"no projects"</h2>
<div class="feature-case">
<NavbarProjectsView projects=emptyProjects/>
</div>
</div>
</div>
}
}

View File

@@ -0,0 +1,27 @@
use leptos::*;
#[component]
pub fn Navbar() -> impl IntoView {
view! {
<div class="flex flex-row justify-between items-center bg-gray-800 p-4">
<div class="flex flex-row items-center">
<div class="text-2xl text-white font-bold">"Como - Todo"</div>
</div>
<div class="flex flex-row items-center space-x-4">
<div class="text-xl text-white font-bold cursor-pointer">
<a href="http://localhost:3001/auth/zitadel?return_url=http://localhost:3000/dash/home">
"Enter"
</a>
</div>
</div>
</div>
}
}
#[component]
pub fn HomePage() -> impl IntoView {
view! {
<Navbar/>
<h1 class="text-xl text-red-50">"Welcome to Leptos!"</h1>
}
}