Basic project functions

This commit is contained in:
Malte Schröder
2025-12-23 15:51:15 +01:00
commit 42cbeb9f1e
11 changed files with 6656 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target
.DS_Store
# These are backup files generated by rustfmt
**/*.rs.bk

265
AGENTS.md Normal file
View File

@@ -0,0 +1,265 @@
You are an expert [0.7 Dioxus](https://dioxuslabs.com/learn/0.7) assistant. Dioxus 0.7 changes every api in dioxus. Only use this up to date documentation. `cx`, `Scope`, and `use_state` are gone
Provide concise code examples with detailed descriptions
# Dioxus Dependency
You can add Dioxus to your `Cargo.toml` like this:
```toml
[dependencies]
dioxus = { version = "0.7.1" }
[features]
default = ["web", "webview", "server"]
web = ["dioxus/web"]
webview = ["dioxus/desktop"]
server = ["dioxus/server"]
```
# Launching your application
You need to create a main function that sets up the Dioxus runtime and mounts your root component.
```rust
use dioxus::prelude::*;
fn main() {
dioxus::launch(App);
}
#[component]
fn App() -> Element {
rsx! { "Hello, Dioxus!" }
}
```
Then serve with `dx serve`:
```sh
curl -sSL http://dioxus.dev/install.sh | sh
dx serve
```
# UI with RSX
```rust
rsx! {
div {
class: "container", // Attribute
color: "red", // Inline styles
width: if condition { "100%" }, // Conditional attributes
"Hello, Dioxus!"
}
// Prefer loops over iterators
for i in 0..5 {
div { "{i}" } // use elements or components directly in loops
}
if condition {
div { "Condition is true!" } // use elements or components directly in conditionals
}
{children} // Expressions are wrapped in brace
{(0..5).map(|i| rsx! { span { "Item {i}" } })} // Iterators must be wrapped in braces
}
```
# Assets
The asset macro can be used to link to local files to use in your project. All links start with `/` and are relative to the root of your project.
```rust
rsx! {
img {
src: asset!("/assets/image.png"),
alt: "An image",
}
}
```
## Styles
The `document::Stylesheet` component will inject the stylesheet into the `<head>` of the document
```rust
rsx! {
document::Stylesheet {
href: asset!("/assets/styles.css"),
}
}
```
# Components
Components are the building blocks of apps
* Component are functions annotated with the `#[component]` macro.
* The function name must start with a capital letter or contain an underscore.
* A component re-renders only under two conditions:
1. Its props change (as determined by `PartialEq`).
2. An internal reactive state it depends on is updated.
```rust
#[component]
fn Input(mut value: Signal<String>) -> Element {
rsx! {
input {
value,
oninput: move |e| {
*value.write() = e.value();
},
onkeydown: move |e| {
if e.key() == Key::Enter {
value.write().clear();
}
},
}
}
}
```
Each component accepts function arguments (props)
* Props must be owned values, not references. Use `String` and `Vec<T>` instead of `&str` or `&[T]`.
* Props must implement `PartialEq` and `Clone`.
* To make props reactive and copy, you can wrap the type in `ReadOnlySignal`. Any reactive state like memos and resources that read `ReadOnlySignal` props will automatically re-run when the prop changes.
# State
A signal is a wrapper around a value that automatically tracks where it's read and written. Changing a signal's value causes code that relies on the signal to rerun.
## Local State
The `use_signal` hook creates state that is local to a single component. You can call the signal like a function (e.g. `my_signal()`) to clone the value, or use `.read()` to get a reference. `.write()` gets a mutable reference to the value.
Use `use_memo` to create a memoized value that recalculates when its dependencies change. Memos are useful for expensive calculations that you don't want to repeat unnecessarily.
```rust
#[component]
fn Counter() -> Element {
let mut count = use_signal(|| 0);
let mut doubled = use_memo(move || count() * 2); // doubled will re-run when count changes because it reads the signal
rsx! {
h1 { "Count: {count}" } // Counter will re-render when count changes because it reads the signal
h2 { "Doubled: {doubled}" }
button {
onclick: move |_| *count.write() += 1, // Writing to the signal rerenders Counter
"Increment"
}
button {
onclick: move |_| count.with_mut(|count| *count += 1), // use with_mut to mutate the signal
"Increment with with_mut"
}
}
}
```
## Context API
The Context API allows you to share state down the component tree. A parent provides the state using `use_context_provider`, and any child can access it with `use_context`
```rust
#[component]
fn App() -> Element {
let mut theme = use_signal(|| "light".to_string());
use_context_provider(|| theme); // Provide a type to children
rsx! { Child {} }
}
#[component]
fn Child() -> Element {
let theme = use_context::<Signal<String>>(); // Consume the same type
rsx! {
div {
"Current theme: {theme}"
}
}
}
```
# Async
For state that depends on an asynchronous operation (like a network request), Dioxus provides a hook called `use_resource`. This hook manages the lifecycle of the async task and provides the result to your component.
* The `use_resource` hook takes an `async` closure. It re-runs this closure whenever any signals it depends on (reads) are updated
* The `Resource` object returned can be in several states when read:
1. `None` if the resource is still loading
2. `Some(value)` if the resource has successfully loaded
```rust
let mut dog = use_resource(move || async move {
// api request
});
match dog() {
Some(dog_info) => rsx! { Dog { dog_info } },
None => rsx! { "Loading..." },
}
```
# Routing
All possible routes are defined in a single Rust `enum` that derives `Routable`. Each variant represents a route and is annotated with `#[route("/path")]`. Dynamic Segments can capture parts of the URL path as parameters by using `:name` in the route string. These become fields in the enum variant.
The `Router<Route> {}` component is the entry point that manages rendering the correct component for the current URL.
You can use the `#[layout(NavBar)]` to create a layout shared between pages and place an `Outlet<Route> {}` inside your layout component. The child routes will be rendered in the outlet.
```rust
#[derive(Routable, Clone, PartialEq)]
enum Route {
#[layout(NavBar)] // This will use NavBar as the layout for all routes
#[route("/")]
Home {},
#[route("/blog/:id")] // Dynamic segment
BlogPost { id: i32 },
}
#[component]
fn NavBar() -> Element {
rsx! {
a { href: "/", "Home" }
Outlet<Route> {} // Renders Home or BlogPost
}
}
#[component]
fn App() -> Element {
rsx! { Router::<Route> {} }
}
```
```toml
dioxus = { version = "0.7.1", features = ["router"] }
```
# Fullstack
Fullstack enables server rendering and ipc calls. It uses Cargo features (`server` and a client feature like `web`) to split the code into a server and client binaries.
```toml
dioxus = { version = "0.7.1", features = ["fullstack"] }
```
## Server Functions
Use the `#[post]` / `#[get]` macros to define an `async` function that will only run on the server. On the server, this macro generates an API endpoint. On the client, it generates a function that makes an HTTP request to that endpoint.
```rust
#[post("/api/double/:path/&query")]
async fn double_server(number: i32, path: String, query: i32) -> Result<i32, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(number * 2)
}
```
## Hydration
Hydration is the process of making a server-rendered HTML page interactive on the client. The server sends the initial HTML, and then the client-side runs, attaches event listeners, and takes control of future rendering.
### Errors
The initial UI rendered by the component on the client must be identical to the UI rendered on the server.
* Use the `use_server_future` hook instead of `use_resource`. It runs the future on the server, serializes the result, and sends it to the client, ensuring the client has the data immediately for its first render.
* Any code that relies on browser-specific APIs (like accessing `localStorage`) must be run *after* hydration. Place this code inside a `use_effect` hook.

6001
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

22
Cargo.toml Normal file
View File

@@ -0,0 +1,22 @@
[package]
name = "mflow"
version = "0.1.0"
authors = ["malxte"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dioxus = { version = "0.7.1", features = [] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
getrandom = { version = "0.3", features = ["wasm_js"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
gloo-storage = "0.3"
[features]
default = ["desktop"]
web = ["dioxus/web"]
desktop = ["dioxus/desktop"]
mobile = ["dioxus/mobile"]

21
Dioxus.toml Normal file
View File

@@ -0,0 +1,21 @@
[application]
[web.app]
# HTML title tag content
title = "mflow"
# include `assets` in web platform
[web.resource]
# Additional CSS style files
style = []
# Additional JavaScript files
script = []
[web.resource.dev]
# Javascript code file
# serve: [dev-server] only
script = []

25
README.md Normal file
View File

@@ -0,0 +1,25 @@
# Development
Your new bare-bones project includes minimal organization with a single `main.rs` file and a few assets.
```
project/
├─ assets/ # Any assets that are used by the app should be placed here
├─ src/
│ ├─ main.rs # main.rs is the entry point to your application and currently contains all components for the app
├─ Cargo.toml # The Cargo.toml file defines the dependencies and feature flags for your project
```
### Serving Your App
Run the following command in the root of your project to start developing with the default platform:
```bash
dx serve
```
To run for a different platform, use the `--platform platform` flag. E.g.
```bash
dx serve --platform desktop
```

BIN
assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

157
assets/main.css Normal file
View File

@@ -0,0 +1,157 @@
body {
background-color: #0d1117;
color: #e6edf3;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial,
sans-serif;
margin: 0;
overflow: hidden;
}
#hero {
display: flex;
height: 100vh;
}
#sidebar {
width: 260px;
background-color: #161b22;
border-right: 1px solid #30363d;
display: flex;
flex-direction: column;
padding: 16px;
}
.project-list {
flex-grow: 1;
overflow-y: auto;
}
.project-row {
display: flex;
margin-bottom: 4px;
}
.project-item {
flex-grow: 1;
background: transparent;
border: none;
color: #c9d1d9;
text-align: left;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
}
.project-item:hover {
background-color: #21262d;
}
.project-item.active {
background-color: #238636;
color: white;
}
.delete-btn {
background: transparent;
border: none;
color: #8b949e;
cursor: pointer;
padding: 0 10px;
font-size: 18px;
}
.delete-btn:hover {
color: #f85149;
}
#add-project {
background-color: #21262d;
border: 1px solid #30363d;
color: #58a6ff;
padding: 10px;
border-radius: 6px;
cursor: pointer;
margin-top: 10px;
}
#open-project {
flex-grow: 1;
display: flex;
flex-direction: column;
padding: 40px;
}
.title-input {
background: transparent;
border: none;
font-size: 32px;
font-weight: bold;
color: white;
outline: none;
margin-bottom: 20px;
}
.content-editor {
background: transparent;
border: none;
color: #c9d1d9;
font-size: 18px;
line-height: 1.6;
flex-grow: 1;
resize: none;
outline: none;
}
.empty-state {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
color: #8b949e;
}
/* Modal */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
}
.modal-box {
background: #161b22;
padding: 24px;
border-radius: 12px;
border: 1px solid #30363d;
width: 300px;
text-align: center;
}
.modal-buttons {
display: flex;
gap: 10px;
justify-content: center;
margin-top: 20px;
}
.btn-confirm {
background: #da3633;
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
}
.btn-cancel {
background: #30363d;
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
}

6
projects.json Normal file
View File

@@ -0,0 +1,6 @@
[
{
"name": "Hallo der erste Test!",
"content": "Das ist mein erstes Projekt!"
}
]

16
src/main.rs Normal file
View File

@@ -0,0 +1,16 @@
use dioxus::prelude::*;
mod ui;
const MAIN_CSS: Asset = asset!("/assets/main.css");
fn main() {
dioxus::launch(App);
}
#[component]
fn App() -> Element {
rsx! {
document::Link { rel: "stylesheet", href: MAIN_CSS }
ui::Hero {}
}
}

136
src/ui.rs Normal file
View File

@@ -0,0 +1,136 @@
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(not(target_arch = "wasm32"))]
use std::fs;
#[cfg(target_arch = "wasm32")]
use gloo_storage::{LocalStorage, Storage};
#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)]
struct Project {
name: String,
content: String,
}
const STORAGE_KEY: &str = "mflow_projects";
#[component]
pub fn Hero() -> Element {
// --- Initiales Laden ---
let mut projects = use_signal(|| {
#[cfg(target_arch = "wasm32")]
{
LocalStorage::get::<Vec<Project>>(STORAGE_KEY).unwrap_or_default()
}
#[cfg(not(target_arch = "wasm32"))]
{
fs::read_to_string("projects.json")
.ok()
.and_then(|data| serde_json::from_str::<Vec<Project>>(&data).ok())
.unwrap_or_default()
}
});
let mut selected_index = use_signal(|| None::<usize>);
let mut show_confirm = use_signal(|| false);
let mut index_to_delete = use_signal(|| None::<usize>);
// --- Automatisches Speichern ---
use_effect(move || {
let current_projects = projects.read();
#[cfg(target_arch = "wasm32")]
{
let _ = LocalStorage::set(STORAGE_KEY, &*current_projects);
}
#[cfg(not(target_arch = "wasm32"))]
{
let data = serde_json::to_string_pretty(&*current_projects).unwrap_or_default();
let _ = fs::write("projects.json", data);
}
});
rsx! {
div { id: "hero",
// Sidebar
div { id: "sidebar",
h2 { "Projekte" }
div { class: "project-list",
for (i, project) in projects.read().iter().enumerate() {
div { class: "project-row",
button {
class: if selected_index() == Some(i) { "project-item active" } else { "project-item" },
onclick: move |_| selected_index.set(Some(i)),
"{project.name}"
}
button {
class: "delete-btn",
onclick: move |_| {
index_to_delete.set(Some(i));
show_confirm.set(true);
},
"×"
}
}
}
}
button { id: "add-project",
onclick: move |_| {
projects.write().push(Project { name: "Neues Projekt".into(), content: "".into() });
},
"+ Projekt hinzufügen"
}
}
// Editor Bereich
div { id: "open-project",
if let Some(idx) = selected_index() {
{
let name = projects.read()[idx].name.clone();
let content = projects.read()[idx].content.clone();
rsx! {
input {
class: "title-input",
value: "{name}",
oninput: move |e| projects.write()[idx].name = e.value()
}
textarea {
class: "content-editor",
value: "{content}",
placeholder: "Schreibe hier deine Notizen...",
oninput: move |e| projects.write()[idx].content = e.value()
}
}
}
} else {
div { class: "empty-state", "Wähle ein Projekt aus der Liste" }
}
}
// Bestätigungs-Modal
if show_confirm() {
div { class: "modal-overlay",
div { class: "modal-box",
h3 { "Projekt löschen?" }
p { "Diese Aktion kann nicht rückgängig gemacht werden." }
div { class: "modal-buttons",
button { class: "btn-cancel", onclick: move |_| show_confirm.set(false), "Abbrechen" }
button {
class: "btn-confirm",
onclick: move |_| {
if let Some(i) = index_to_delete() {
projects.write().remove(i);
selected_index.set(None);
}
show_confirm.set(false);
},
"Löschen"
}
}
}
}
}
}
}
}