From fc7b2d678040d57ac91bb91f08f6f7293f371e48 Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sat, 7 Feb 2026 10:30:57 -0800 Subject: [PATCH] tutorial project for rust --- .gitignore | 1 + Cargo.lock | 969 ++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 10 + data/app.db | Bin 0 -> 16384 bytes learning/walkthrough.md | 123 +++++ src/db.rs | 140 ++++++ src/handlers.rs | 192 ++++++++ src/main.rs | 48 ++ src/views.rs | 248 ++++++++++ 9 files changed, 1731 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 data/app.db create mode 100644 learning/walkthrough.md create mode 100644 src/db.rs create mode 100644 src/handlers.rs create mode 100644 src/main.rs create mode 100644 src/views.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b8bbe01 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,969 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "CurseTechnique" +version = "0.1.0" +dependencies = [ + "axum", + "chrono", + "rusqlite", + "tokio", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "axum" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" + +[[package]] +name = "bumpalo" +version = "3.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "pin-utils", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "js-sys" +version = "0.3.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.180" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" + +[[package]] +name = "libsqlite3-sys" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rusqlite" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "syn" +version = "2.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "zerocopy" +version = "0.8.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff05f8caa9038894637571ae6b9e29466c1f4f829d26c9b28f869a29cbe3445" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5ae183f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "CurseTechnique" +version = "0.1.0" +edition = "2024" + +[dependencies] +axum = "0.8.1" +chrono = { version = "0.4.40", features = ["clock"] } +rusqlite = { version = "0.31.0", features = ["bundled"] } +tokio = { version = "1.44.0", features = ["full"] } diff --git a/data/app.db b/data/app.db new file mode 100644 index 0000000000000000000000000000000000000000..a15222f72f1f5699a6b19bb67d1c52c673af78dd GIT binary patch literal 16384 zcmeI(O>fgM7zc1W8QU~z-7cs?T%H~(wOWVTPHM#@#L7W}7Y!@+o9xMlZ`&$B-~PigKQm*sLxBJUAOHafKmY;|fB*y_0D;>P znClx^GtWOi^e3L2``+9c27%|uNjUZ8>}vnX@!U`*FRz)FFl<4M_Nlm_6`iQlR;$Tn zzCx7uU%p~jThH$8@qXyO8Ohn@NUc1bnY?^2Cxh#!`v384(HGdXbbSW9I~woqY<625ndpwB3nGViFL500bZa0SG_<0uX=z1Rwx`dm)g~b3A_4 QU(-{k_2^&xnYgw77lpRi`v3p{ literal 0 HcmV?d00001 diff --git a/learning/walkthrough.md b/learning/walkthrough.md new file mode 100644 index 0000000..d589956 --- /dev/null +++ b/learning/walkthrough.md @@ -0,0 +1,123 @@ +# CurseTechnique Codebase Walkthrough + +This document is a practical map of the app, aimed at learning-oriented Rust reading. + +## 1. High-level architecture + +The app uses a lightweight 4-layer layout: + +1. `src/main.rs` - startup and route wiring +2. `src/handlers.rs` - HTTP handlers and input validation +3. `src/db.rs` - SQLite queries and data structs +4. `src/views.rs` - HTML rendering (server-side string rendering) + +The goal is to keep each file focused and easy to read without adding extra frameworks. + +## 2. Request flow (end-to-end) + +Example: open `GET /day/2026-02-07` + +1. Route is defined in `src/main.rs` and points to `handlers::show_day_entries`. +2. `show_day_entries` in `src/handlers.rs` validates the date path param. +3. It calls `db::fetch_day_entries` in `src/db.rs` to load rows from SQLite. +4. It passes those rows to `views::render_day_page` in `src/views.rs`. +5. The rendered HTML is returned to the browser. + +Example: submit add-entry form `POST /day/{date}/add` + +1. Route points to `handlers::create_entry`. +2. Handler validates date and form fields (`name`, `calories`). +3. Handler calls `db::insert_entry`. +4. Handler redirects back to `/day/{date}`. + +## 3. File-by-file reading guide + +## `src/main.rs` + +Read this file first. It is intentionally small. + +- Creates data directory and opens SQLite DB. +- Calls DB init/seed helpers. +- Builds Axum router. +- Starts Tokio TCP listener. + +If you ever wonder "where is this endpoint connected?", this file is the source of truth. + +## `src/handlers.rs` + +This is the HTTP boundary. + +Core concepts here: + +- `AppState` holds shared DB connection behind `Arc>`. +- Each handler receives typed route/form data. +- Handlers do three steps: + 1. Validate input + 2. Call DB function + 3. Return HTML or redirect + +Useful helper functions: + +- `validate_date` ensures `YYYY-MM-DD` format. +- `parse_entry_form_fields` validates `name` + `calories`. +- `month_bounds` computes first/next month boundaries. + +## `src/db.rs` + +This file contains all SQL. + +Data structs: + +- `FoodEntry` represents one row. +- `DaySummary` represents aggregated values for calendar cards. + +Functions are split by intent: + +- Setup: `init_db`, `seed_db_if_empty` +- Reads: `fetch_month_summaries`, `fetch_day_entries` +- Writes: `insert_entry`, `update_entry`, `delete_entry` + +If behavior looks wrong (totals, filtering, ordering), start debugging here. + +## `src/views.rs` + +This file builds HTML strings for SSR. + +- `render_calendar_page` renders `/`. +- `render_day_page` renders `/day/{date}`. +- Small helpers reduce clutter: + - `render_day_card` + - `render_entry_rows` + - `entry_count_label` + - `escape_html` + +Important: `escape_html` is used when rendering user-provided food names. + +## 4. Key Rust patterns used + +- `Result` for explicit error handling. +- `?` operator to propagate errors. +- `Arc>` for shared mutable state across async handlers. +- Simple structs over tuple-heavy values for readability (`DaySummary`). +- Module organization (`mod db; mod handlers; mod views;`) to keep files focused. + +## 5. How to add a feature safely + +Use this checklist: + +1. Add/adjust SQL function in `db.rs`. +2. Add or update handler logic in `handlers.rs`. +3. Update route wiring in `main.rs` if endpoint path changes. +4. Update HTML output/forms in `views.rs`. +5. Run: + - `cargo fmt` + - `cargo check` + +## 6. Suggested beginner exercises + +1. Add a "notes" text column to food entries. +2. Show count of entries in the day header. +3. Add confirmation step on delete (simple query param or separate page). +4. Add a helper in handlers to prevent editing future dates. + +These exercises touch all 4 layers and are great practice for understanding the whole flow. diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..922fdfd --- /dev/null +++ b/src/db.rs @@ -0,0 +1,140 @@ +use std::collections::HashMap; + +use rusqlite::{Connection, params}; + +#[derive(Clone)] +/// A single food entry row from `food_entries`. +pub struct FoodEntry { + pub id: i64, + pub name: String, + pub calories: i64, +} + +#[derive(Clone, Copy)] +/// Aggregated daily values used by the calendar grid. +pub struct DaySummary { + pub entry_count: i64, + pub total_calories: i64, +} + +/// Creates tables/indexes if they do not already exist. +pub fn init_db(conn: &Connection) -> Result<(), rusqlite::Error> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS food_entries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + entry_date TEXT NOT NULL, + name TEXT NOT NULL, + calories INTEGER NOT NULL CHECK (calories >= 0), + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + CREATE INDEX IF NOT EXISTS idx_food_entries_entry_date ON food_entries(entry_date);", + )?; + + Ok(()) +} + +/// Placeholder seeding hook. Currently no-op unless you add seed inserts. +pub fn seed_db_if_empty(conn: &Connection) -> Result<(), rusqlite::Error> { + let count: i64 = conn.query_row("SELECT COUNT(*) FROM food_entries", [], |row| row.get(0))?; + if count > 0 { + return Ok(()); + } + + Ok(()) +} + +/// Returns one summary per date for the given half-open range [start_date, end_date). +pub fn fetch_month_summaries( + conn: &Connection, + start_date: &str, + end_date: &str, +) -> Result, rusqlite::Error> { + let mut statement = conn.prepare( + "SELECT entry_date, COUNT(*) as entry_count, SUM(calories) as total + FROM food_entries + WHERE entry_date >= ?1 AND entry_date < ?2 + GROUP BY entry_date", + )?; + let mut rows = statement.query(params![start_date, end_date])?; + + let mut totals = HashMap::::new(); + while let Some(row) = rows.next()? { + let date: String = row.get(0)?; + let entry_count: i64 = row.get(1)?; + let total_calories: i64 = row.get(2)?; + totals.insert( + date, + DaySummary { + entry_count, + total_calories, + }, + ); + } + + Ok(totals) +} + +/// Returns all entries for one day. +pub fn fetch_day_entries(conn: &Connection, date: &str) -> Result, rusqlite::Error> { + let mut statement = conn.prepare( + "SELECT id, name, calories + FROM food_entries + WHERE entry_date = ?1 + ORDER BY id", + )?; + + let iter = statement.query_map(params![date], |row| { + Ok(FoodEntry { + id: row.get(0)?, + name: row.get(1)?, + calories: row.get(2)?, + }) + })?; + + let mut entries = Vec::new(); + for row in iter { + entries.push(row?); + } + + Ok(entries) +} + +/// Inserts one entry for a date. +pub fn insert_entry( + conn: &Connection, + date: &str, + name: &str, + calories: i64, +) -> Result<(), rusqlite::Error> { + conn.execute( + "INSERT INTO food_entries (entry_date, name, calories) VALUES (?1, ?2, ?3)", + params![date, name, calories], + )?; + Ok(()) +} + +/// Updates one entry if both `id` and `date` match. +pub fn update_entry( + conn: &Connection, + date: &str, + id: i64, + name: &str, + calories: i64, +) -> Result<(), rusqlite::Error> { + conn.execute( + "UPDATE food_entries + SET name = ?1, calories = ?2 + WHERE id = ?3 AND entry_date = ?4", + params![name, calories, id, date], + )?; + Ok(()) +} + +/// Deletes one entry if both `id` and `date` match. +pub fn delete_entry(conn: &Connection, date: &str, id: i64) -> Result<(), rusqlite::Error> { + conn.execute( + "DELETE FROM food_entries WHERE id = ?1 AND entry_date = ?2", + params![id, date], + )?; + Ok(()) +} diff --git a/src/handlers.rs b/src/handlers.rs new file mode 100644 index 0000000..21b6266 --- /dev/null +++ b/src/handlers.rs @@ -0,0 +1,192 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use axum::extract::{Form, Path, State}; +use axum::http::StatusCode; +use axum::response::{Html, Redirect}; +use chrono::{Datelike, Local, NaiveDate}; +use rusqlite::Connection; +use tokio::sync::Mutex; + +use crate::db; +use crate::views::{self, CalendarCell, DayCard}; + +type AppError = (StatusCode, String); + +#[derive(Clone)] +/// Shared application state injected into each handler. +pub struct AppState { + pub db: Arc>, +} + +/// GET `/` - calendar overview for the current month. +pub async fn show_calendar(State(state): State) -> Result, AppError> { + let today = Local::now().date_naive(); + let (first_day, first_of_next_month, days_in_month) = month_bounds(today)?; + + let totals = { + let db_conn = state.db.lock().await; + db::fetch_month_summaries( + &db_conn, + &first_day.format("%Y-%m-%d").to_string(), + &first_of_next_month.format("%Y-%m-%d").to_string(), + ) + .map_err(internal_error)? + }; + + let mut cells = Vec::with_capacity(42); + + // Calendar starts on Sunday, so pad blank cells before day 1. + let first_weekday = first_day.weekday().num_days_from_sunday() as usize; + for _ in 0..first_weekday { + cells.push(CalendarCell::Padding); + } + + for day_num in 1..=days_in_month { + if let Some(date) = NaiveDate::from_ymd_opt(today.year(), today.month(), day_num as u32) { + let date_text = date.format("%Y-%m-%d").to_string(); + let summary = totals.get(&date_text); + + cells.push(CalendarCell::Day(DayCard { + date_text, + day_num: day_num as u32, + total: summary.map(|s| s.total_calories).unwrap_or(0), + entry_count: summary.map(|s| s.entry_count).unwrap_or(0), + is_today: date == today, + is_future: date > today, + })); + } + } + + // Pad trailing cells so the grid always ends on Saturday. + let total_cells = first_weekday + days_in_month as usize; + let tail_padding = (7 - (total_cells % 7)) % 7; + for _ in 0..tail_padding { + cells.push(CalendarCell::Padding); + } + + Ok(Html(views::render_calendar_page( + &today.format("%B %Y").to_string(), + &cells, + ))) +} + +/// GET `/day/{date}` - list/edit entries for one day. +pub async fn show_day_entries( + State(state): State, + Path(date_text): Path, +) -> Result, AppError> { + validate_date(&date_text)?; + + let entries = { + let db_conn = state.db.lock().await; + db::fetch_day_entries(&db_conn, &date_text).map_err(internal_error)? + }; + + Ok(Html(views::render_day_page(&date_text, &entries))) +} + +/// POST `/day/{date}/add` - create a new entry. +pub async fn create_entry( + State(state): State, + Path(date_text): Path, + Form(form): Form>, +) -> Result { + validate_date(&date_text)?; + let (name, calories) = parse_entry_form_fields(&form)?; + + let db_conn = state.db.lock().await; + db::insert_entry(&db_conn, &date_text, &name, calories).map_err(internal_error)?; + + Ok(Redirect::to(&format!("/day/{}", date_text))) +} + +/// POST `/day/{date}/entry/{id}/update` - edit an existing entry. +pub async fn edit_entry( + State(state): State, + Path((date_text, id)): Path<(String, i64)>, + Form(form): Form>, +) -> Result { + validate_date(&date_text)?; + let (name, calories) = parse_entry_form_fields(&form)?; + + let db_conn = state.db.lock().await; + db::update_entry(&db_conn, &date_text, id, &name, calories).map_err(internal_error)?; + + Ok(Redirect::to(&format!("/day/{}", date_text))) +} + +/// POST `/day/{date}/entry/{id}/delete` - remove an entry. +pub async fn remove_entry( + State(state): State, + Path((date_text, id)): Path<(String, i64)>, +) -> Result { + validate_date(&date_text)?; + + let db_conn = state.db.lock().await; + db::delete_entry(&db_conn, &date_text, id).map_err(internal_error)?; + + Ok(Redirect::to(&format!("/day/{}", date_text))) +} + +fn validate_date(date_text: &str) -> Result<(), AppError> { + NaiveDate::parse_from_str(date_text, "%Y-%m-%d") + .map(|_| ()) + .map_err(|_| { + ( + StatusCode::BAD_REQUEST, + "Date must be YYYY-MM-DD".to_string(), + ) + }) +} + +fn parse_entry_form_fields(form: &HashMap) -> Result<(String, i64), AppError> { + let name = form.get("name").map(|v| v.trim()).unwrap_or(""); + let calories = form + .get("calories") + .ok_or((StatusCode::BAD_REQUEST, "Calories are required".to_string()))? + .parse::() + .map_err(|_| { + ( + StatusCode::BAD_REQUEST, + "Calories must be a number".to_string(), + ) + })?; + + if name.is_empty() { + return Err((StatusCode::BAD_REQUEST, "Name is required".to_string())); + } + if calories < 0 { + return Err((StatusCode::BAD_REQUEST, "Calories must be >= 0".to_string())); + } + + Ok((name.to_string(), calories)) +} + +fn month_bounds(today: NaiveDate) -> Result<(NaiveDate, NaiveDate, i64), AppError> { + let first_day = NaiveDate::from_ymd_opt(today.year(), today.month(), 1).ok_or(( + StatusCode::INTERNAL_SERVER_ERROR, + "Invalid date".to_string(), + ))?; + + let (next_year, next_month) = if today.month() == 12 { + (today.year() + 1, 1) + } else { + (today.year(), today.month() + 1) + }; + + let first_of_next_month = NaiveDate::from_ymd_opt(next_year, next_month, 1).ok_or(( + StatusCode::INTERNAL_SERVER_ERROR, + "Invalid date".to_string(), + ))?; + + let days_in_month = (first_of_next_month - first_day).num_days(); + Ok((first_day, first_of_next_month, days_in_month)) +} + +fn internal_error(error: rusqlite::Error) -> AppError { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Database error: {}", error), + ) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..a336503 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,48 @@ +mod db; +mod handlers; +mod views; + +use std::fs; +use std::sync::Arc; + +use axum::Router; +use axum::routing::{get, post}; +use rusqlite::Connection; +use tokio::sync::Mutex; + +use crate::handlers::AppState; + +const DB_DIR: &str = "data"; +const DB_PATH: &str = "data/app.db"; +const LISTEN_ADDR: &str = "127.0.0.1:3000"; + +#[tokio::main] +async fn main() -> Result<(), Box> { + fs::create_dir_all(DB_DIR)?; + + let conn = Connection::open(DB_PATH)?; + db::init_db(&conn)?; + db::seed_db_if_empty(&conn)?; + + let state = AppState { + db: Arc::new(Mutex::new(conn)), + }; + + // Route wiring stays here so `main` is the single startup overview. + let app = Router::new() + .route("/", get(handlers::show_calendar)) + .route("/day/{date}", get(handlers::show_day_entries)) + .route("/day/{date}/add", post(handlers::create_entry)) + .route("/day/{date}/entry/{id}/update", post(handlers::edit_entry)) + .route( + "/day/{date}/entry/{id}/delete", + post(handlers::remove_entry), + ) + .with_state(state); + + let listener = tokio::net::TcpListener::bind(LISTEN_ADDR).await?; + println!("Listening on http://{}", LISTEN_ADDR); + axum::serve(listener, app).await?; + + Ok(()) +} diff --git a/src/views.rs b/src/views.rs new file mode 100644 index 0000000..9a02182 --- /dev/null +++ b/src/views.rs @@ -0,0 +1,248 @@ +use crate::db::FoodEntry; + +pub struct DayCard { + pub date_text: String, + pub day_num: u32, + pub total: i64, + pub entry_count: i64, + pub is_today: bool, + pub is_future: bool, +} + +pub enum CalendarCell { + Padding, + Day(DayCard), +} + +/// Renders the month calendar page. +pub fn render_calendar_page(month_label: &str, cells: &[CalendarCell]) -> String { + let mut items = String::new(); + for cell in cells { + match cell { + CalendarCell::Padding => items.push_str( + "
", + ), + CalendarCell::Day(day) => items.push_str(&render_day_card(day)), + } + } + + format!( + " + + + + + Hello Calories + + + +
+
+

Calorie Tracker

+

{}

+

Click any day to inspect all logged food entries.

+
+
+
+
+
+
Sun
+
Mon
+
Tue
+
Wed
+
Thu
+
Fri
+
Sat
+
+
+ {} +
+
+
+
+
+ +", + month_label, items + ) +} + +/// Renders the daily page with add/edit/delete forms. +pub fn render_day_page(date_text: &str, entries: &[FoodEntry]) -> String { + let daily_total: i64 = entries.iter().map(|entry| entry.calories).sum(); + let rows = render_entry_rows(date_text, entries); + + format!( + " + + + + + Day Entries + + + +
+ + + Back to calendar + +
+

{}

+

+ Daily total: {} cal +

+
+

Add entry

+
+ + +
+ +
+
+
+
+ + + + + {} +
EntryCalories
+
+
+
+ +", + date_text, daily_total, date_text, rows + ) +} + +fn render_day_card(day: &DayCard) -> String { + let entry_line = entry_count_label(day.entry_count); + + if day.is_future { + return format!( + "
+
+ {date} + {day_num} +
+
+

{total} cal

+

{entry_line}

+

Future

+
+
", + date = day.date_text, + day_num = day.day_num, + total = day.total, + entry_line = entry_line + ); + } + + let base_class = if day.is_today { + "group block h-32 rounded-2xl border border-teal-400 bg-teal-50 p-3 transition hover:-translate-y-0.5 hover:shadow-md" + } else { + "group block h-32 rounded-2xl border border-slate-200 bg-white p-3 transition hover:-translate-y-0.5 hover:shadow-md" + }; + + format!( + " +
+ {date} + {day_num} +
+
+

{total} cal

+

{entry_line}

+
+
", + class = base_class, + date = day.date_text, + day_num = day.day_num, + total = day.total, + entry_line = entry_line + ) +} + +fn escape_html(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('\"', """) + .replace('\'', "'") +} + +fn entry_count_label(entry_count: i64) -> String { + if entry_count == 0 { + "No entries".to_string() + } else if entry_count == 1 { + "1 entry".to_string() + } else { + format!("{} entries", entry_count) + } +} + +fn render_entry_rows(date_text: &str, entries: &[FoodEntry]) -> String { + let mut rows = String::new(); + + if entries.is_empty() { + rows.push_str( + "No entries yet for this day.", + ); + return rows; + } + + for entry in entries { + rows.push_str(&format!( + " + +
+ + +
+ +
+
+
+ +
+ + {calories} cal + ", + date = date_text, + id = entry.id, + name = escape_html(&entry.name), + calories = entry.calories + )); + } + + rows +}