Basic Calc functions
This commit is contained in:
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal 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
265
AGENTS.md
Normal 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.
|
||||
5982
Cargo.lock
generated
Normal file
5982
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
Normal file
16
Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "mcalc"
|
||||
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 = [] }
|
||||
|
||||
[features]
|
||||
default = ["desktop"]
|
||||
web = ["dioxus/web"]
|
||||
desktop = ["dioxus/desktop"]
|
||||
mobile = ["dioxus/mobile"]
|
||||
21
Dioxus.toml
Normal file
21
Dioxus.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[application]
|
||||
|
||||
[web.app]
|
||||
|
||||
# HTML title tag content
|
||||
title = "mcalc"
|
||||
|
||||
# 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 = []
|
||||
59
README.md
Normal file
59
README.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# mcalc - Simple Dioxus Calculator
|
||||
|
||||
A simple, modern, and beautiful calculator application built with Rust and Dioxus.
|
||||
|
||||
## Description
|
||||
|
||||
**mcalc** is a lightweight desktop calculator that demonstrates how to build a clean UI with state management in Dioxus. It features a modern dark mode design with glassmorphism effects and responsiveness.
|
||||
|
||||
## Features
|
||||
|
||||
- **Basic Arithmetic**: Addition, Subtraction, Multiplication, Division.
|
||||
- **Modern UI**: Clean typography, glassmorphism card, and neon accents.
|
||||
- **Interactive**: Hover effects and smooth animations.
|
||||
- **Responsive**: Adapts to window resizing.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Rust**: Core logic and safety.
|
||||
- **Dioxus**: UI framework (React-like for Rust).
|
||||
- **CSS3**: Custom styling with variables and flexbox/grid.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [Rust](https://www.rust-lang.org/tools/install) installed.
|
||||
- [Dioxus CLI](https://dioxuslabs.com/learn/0.6/getting_started) (optional but recommended for development).
|
||||
|
||||
```bash
|
||||
cargo install dioxus-cli
|
||||
```
|
||||
|
||||
### Running the App
|
||||
|
||||
1. **Clone the repository**:
|
||||
```bash
|
||||
git clone <repository_url>
|
||||
cd mcalc
|
||||
```
|
||||
|
||||
2. **Run with Cargo**:
|
||||
```bash
|
||||
cargo run
|
||||
```
|
||||
|
||||
**Or with Dioxus CLI (for hot reloading):**
|
||||
```bash
|
||||
dx serve
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/main.rs`: Entry point.
|
||||
- `src/ui.rs`: Main calculator component and logic.
|
||||
- `assets/main.css`: Styling and themes.
|
||||
|
||||
## License
|
||||
|
||||
MIT License
|
||||
BIN
assets/favicon.ico
Normal file
BIN
assets/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 130 KiB |
20
assets/header.svg
Normal file
20
assets/header.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 23 KiB |
195
assets/main.css
Normal file
195
assets/main.css
Normal file
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
Main Project Styles
|
||||
Simple, clean, and modern calculator design.
|
||||
*/
|
||||
|
||||
/* --- Variables --- */
|
||||
:root {
|
||||
/* Colors */
|
||||
--bg-main: #121212;
|
||||
--bg-card: rgba(30, 30, 35, 0.8);
|
||||
--bg-display: #1a1a1a;
|
||||
|
||||
--text-main: #ffffff;
|
||||
--text-muted: #a0a0a0;
|
||||
--text-black: #000000;
|
||||
|
||||
/* Button Colors */
|
||||
--btn-num-bg: #2d2d2d;
|
||||
--btn-num-hover: #3d3d3d;
|
||||
|
||||
--btn-op-bg: #ff9f0a;
|
||||
--btn-op-hover: #ffb03a;
|
||||
|
||||
--btn-clear-bg: #ff453a;
|
||||
--btn-clear-hover: #ff6961;
|
||||
|
||||
/* Layout & Effects */
|
||||
--radius-l: 24px;
|
||||
--radius-m: 16px;
|
||||
--shadow-heavy: 0 20px 50px rgba(0, 0, 0, 0.5);
|
||||
--shadow-light: 0 4px 6px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
/* --- Global Setup --- */
|
||||
body {
|
||||
background-color: var(--bg-main);
|
||||
background-image: radial-gradient(circle at 50% 0%, #2a2a35 0%, #121212 100%);
|
||||
color: var(--text-main);
|
||||
font-family: -apple-system, sans-serif;
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* --- App Container --- */
|
||||
.app-container {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
animation: fade-in 0.8s ease-out;
|
||||
}
|
||||
|
||||
/* --- Calculator Wrapper (The Card) --- */
|
||||
.calculator-wrap {
|
||||
background-color: var(--bg-card);
|
||||
backdrop-filter: blur(20px);
|
||||
width: 360px;
|
||||
padding: 24px;
|
||||
border-radius: var(--radius-l);
|
||||
box-shadow: var(--shadow-heavy);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
/* --- Display Area --- */
|
||||
.display-area {
|
||||
background-color: var(--bg-display);
|
||||
border-radius: var(--radius-m);
|
||||
padding: 24px;
|
||||
text-align: right;
|
||||
margin-bottom: 10px;
|
||||
min-height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
overflow: hidden;
|
||||
/* Hide if numbers get too long */
|
||||
}
|
||||
|
||||
.display-text {
|
||||
font-size: 3rem;
|
||||
font-weight: 300;
|
||||
white-space: nowrap;
|
||||
background: linear-gradient(180deg, #fff 0%, #e0e0e0 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
/* Fallback */
|
||||
}
|
||||
|
||||
.operator-symbol {
|
||||
color: var(--btn-op-bg);
|
||||
/* Use operator color for visibility */
|
||||
font-weight: 500;
|
||||
margin: 0 4px;
|
||||
/* Reset gradient text effect for symbol to make it solid color */
|
||||
-webkit-text-fill-color: var(--btn-op-bg);
|
||||
}
|
||||
|
||||
/* --- Keypad Grid --- */
|
||||
.keypad-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
/* --- Buttons --- */
|
||||
.calc-btn {
|
||||
border: none;
|
||||
outline: none;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 500;
|
||||
padding: 20px 0;
|
||||
border-radius: var(--radius-m);
|
||||
cursor: pointer;
|
||||
transition: transform 0.1s, filter 0.2s;
|
||||
box-shadow: var(--shadow-light);
|
||||
color: var(--text-main);
|
||||
position: relative;
|
||||
/* For overflow/effects */
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Button Interactions */
|
||||
.calc-btn:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
|
||||
.calc-btn:hover {
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
/* Button Variants */
|
||||
.btn-number {
|
||||
background-color: var(--btn-num-bg);
|
||||
}
|
||||
|
||||
.btn-operator {
|
||||
background-color: var(--btn-op-bg);
|
||||
color: var(--text-black);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-equals {
|
||||
grid-column: span 4;
|
||||
/* Full width */
|
||||
background-color: var(--btn-op-bg);
|
||||
color: var(--text-black);
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.btn-clear {
|
||||
background-color: var(--btn-clear-bg);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-zero {
|
||||
grid-column: span 2;
|
||||
/* Double width */
|
||||
text-align: left;
|
||||
padding-left: 32px;
|
||||
}
|
||||
|
||||
/* --- Animations --- */
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Responsiveness --- */
|
||||
@media (max-height: 700px) {
|
||||
.calculator-wrap {
|
||||
padding: 16px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.calc-btn {
|
||||
padding: 16px 0;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
16
src/main.rs
Normal file
16
src/main.rs
Normal 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::Calculator {}
|
||||
}
|
||||
}
|
||||
219
src/ui.rs
Normal file
219
src/ui.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
/// The main calculator component.
|
||||
/// We use `allow(non_snake_case)` because Dioxus components are typically CamelCase.
|
||||
#[allow(non_snake_case)]
|
||||
#[component]
|
||||
pub fn Calculator() -> Element {
|
||||
// --- State Management ---
|
||||
// `first_num`: Stores the first number entered.
|
||||
// `second_num`: Stores the second number entered.
|
||||
// `operator`: Stores the current operator (+, -, *, /).
|
||||
let mut first_num = use_signal(String::new);
|
||||
let mut second_num = use_signal(String::new);
|
||||
let mut operator = use_signal(String::new);
|
||||
|
||||
rsx! {
|
||||
// Main container for the calculator
|
||||
div { class: "app-container",
|
||||
div { class: "calculator-wrap",
|
||||
// Display Screen
|
||||
div { class: "display-area",
|
||||
div { class: "display-text",
|
||||
// Logic: If first number is empty, show "0"
|
||||
if first_num().is_empty() {
|
||||
"0"
|
||||
} else {
|
||||
"{first_num}"
|
||||
}
|
||||
" "
|
||||
span { class: "operator-symbol", "{operator}" }
|
||||
" "
|
||||
"{second_num}"
|
||||
}
|
||||
}
|
||||
|
||||
// Button Grid
|
||||
div { class: "keypad-grid",
|
||||
// --- Row 1 ---
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "7"),
|
||||
"7"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "8"),
|
||||
"8"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "9"),
|
||||
"9"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-operator",
|
||||
onclick: move |_| handle_operator(first_num, second_num, operator, "/"),
|
||||
"/"
|
||||
}
|
||||
|
||||
// --- Row 2 ---
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "4"),
|
||||
"4"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "5"),
|
||||
"5"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "6"),
|
||||
"6"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-operator",
|
||||
onclick: move |_| handle_operator(first_num, second_num, operator, "*"),
|
||||
"*"
|
||||
}
|
||||
|
||||
// --- Row 3 ---
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "1"),
|
||||
"1"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "2"),
|
||||
"2"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-number",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "3"),
|
||||
"3"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-operator",
|
||||
onclick: move |_| handle_operator(first_num, second_num, operator, "-"),
|
||||
"-"
|
||||
}
|
||||
|
||||
// --- Row 4 ---
|
||||
button {
|
||||
class: "calc-btn btn-number btn-zero",
|
||||
onclick: move |_| input_digit(first_num, second_num, operator, "0"),
|
||||
"0"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-clear",
|
||||
onclick: move |_| {
|
||||
first_num.set(String::new());
|
||||
second_num.set(String::new());
|
||||
operator.set(String::new());
|
||||
},
|
||||
"C"
|
||||
}
|
||||
button {
|
||||
class: "calc-btn btn-operator",
|
||||
onclick: move |_| handle_operator(first_num, second_num, operator, "+"),
|
||||
"+"
|
||||
}
|
||||
|
||||
// --- Row 5 (Equals) ---
|
||||
button {
|
||||
class: "calc-btn btn-equals",
|
||||
onclick: move |_| calculate_result(first_num, second_num, operator),
|
||||
"="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to add a digit to the current number
|
||||
fn input_digit(
|
||||
mut first_num: Signal<String>,
|
||||
mut second_num: Signal<String>,
|
||||
operator: Signal<String>,
|
||||
digit: &str,
|
||||
) {
|
||||
if operator().is_empty() {
|
||||
first_num.write().push_str(digit);
|
||||
} else {
|
||||
second_num.write().push_str(digit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper logic for operators
|
||||
fn handle_operator(
|
||||
first_num: Signal<String>,
|
||||
second_num: Signal<String>,
|
||||
mut operator: Signal<String>,
|
||||
op: &str,
|
||||
) {
|
||||
if !first_num().is_empty() && second_num().is_empty() {
|
||||
operator.set(op.to_string());
|
||||
} else if !second_num().is_empty() {
|
||||
// If we already have two numbers, calculate first, then set new operator
|
||||
calculate_result(first_num, second_num, operator);
|
||||
operator.set(op.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the calculation based on current state
|
||||
fn calculate_result(
|
||||
mut first_num: Signal<String>,
|
||||
mut second_num: Signal<String>,
|
||||
mut operator: Signal<String>,
|
||||
) {
|
||||
// Parse numbers
|
||||
let num1_str = first_num();
|
||||
let num2_str = second_num();
|
||||
let op = operator();
|
||||
|
||||
// If we don't have a second number, we can't calculate
|
||||
if num2_str.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to parse strings to floats
|
||||
let n1 = match num1_str.parse::<f64>() {
|
||||
Ok(n) => n,
|
||||
Err(_) => return, // Invalid number
|
||||
};
|
||||
|
||||
let n2 = match num2_str.parse::<f64>() {
|
||||
Ok(n) => n,
|
||||
Err(_) => return, // Invalid number
|
||||
};
|
||||
|
||||
// Calculate result
|
||||
let result = match op.as_str() {
|
||||
"+" => (n1 + n2).to_string(),
|
||||
"-" => (n1 - n2).to_string(),
|
||||
"*" => (n1 * n2).to_string(),
|
||||
"/" => {
|
||||
if n2 == 0.0 {
|
||||
"Error".to_string()
|
||||
} else {
|
||||
(n1 / n2).to_string()
|
||||
}
|
||||
}
|
||||
_ => return, // Unknown operator
|
||||
};
|
||||
|
||||
// Update state with result
|
||||
if result == "Error" {
|
||||
first_num.set(String::new());
|
||||
} else {
|
||||
first_num.set(result);
|
||||
}
|
||||
|
||||
// Reset others
|
||||
second_num.set(String::new());
|
||||
operator.set(String::new());
|
||||
}
|
||||
Reference in New Issue
Block a user