From 642dd8a80ce2e1212b8e30c1edabb32bdb416cfc Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Wed, 7 Dec 2022 00:16:34 +0100 Subject: [PATCH] Add frontend tests and other stuff --- .gitignore | 7 +- Cargo.lock | 131 +++++++---- Cargo.toml | 1 + README.md | 22 +- TODO.md | 2 + backend/sql/data_test.sql | 2 +- backend/sql/version_1.sql | 11 + backend/src/data/asynchronous.rs | 17 +- backend/src/data/db.rs | 92 ++++++-- backend/src/model.rs | 4 +- backend/src/services.rs | 16 +- backend/src/services/api.rs | 27 +++ backend/static/frontend.js | 294 ++++++++++++++++++++++++ backend/style.scss | 9 + backend/templates/base.html | 8 + backend/templates/base_with_header.html | 10 +- backend/templates/base_with_list.html | 11 +- frontend/Cargo.toml | 39 ++++ frontend/deploy.nu | 3 + frontend/index.js | 8 + frontend/package.json | 14 ++ frontend/src/lib.rs | 35 +++ frontend/src/utils.rs | 10 + frontend/start.nu | 1 + frontend/tests/web.rs | 13 ++ frontend/webpack.config.js | 28 +++ 26 files changed, 730 insertions(+), 85 deletions(-) create mode 100644 backend/src/services/api.rs create mode 100644 backend/static/frontend.js create mode 100644 frontend/Cargo.toml create mode 100644 frontend/deploy.nu create mode 100644 frontend/index.js create mode 100644 frontend/package.json create mode 100644 frontend/src/lib.rs create mode 100644 frontend/src/utils.rs create mode 100644 frontend/start.nu create mode 100644 frontend/tests/web.rs create mode 100644 frontend/webpack.config.js diff --git a/.gitignore b/.gitignore index 91ff291..8d38471 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,9 @@ style.css.map backend/static/style.css backend/file.db *.sqlite -conf.ron \ No newline at end of file +conf.ron + +*.wasm +node_modules +pkg +package-lock.json \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 5184cf7..2db1a4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -169,7 +169,7 @@ dependencies = [ "ahash", "bytes", "bytestring", - "cfg-if", + "cfg-if 1.0.0", "cookie", "derive_more", "encoding_rs", @@ -429,6 +429,12 @@ dependencies = [ "jobserver", ] +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + [[package]] name = "cfg-if" version = "1.0.0" @@ -523,6 +529,16 @@ dependencies = [ "xdg", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen", +] + [[package]] name = "convert_case" version = "0.4.0" @@ -561,7 +577,7 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -576,9 +592,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a41a86530d0fe7f5d9ea779916b7cadd2d4f9add748b99c2c029cbbdfaf453" +checksum = "bdf07d07d6531bfcdbe9b8b739b104610c6508dcc4d63b410585faf338241daf" dependencies = [ "cc", "cxxbridge-flags", @@ -588,9 +604,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06416d667ff3e3ad2df1cd8cd8afae5da26cf9cec4d0825040f88b5ca659a2f0" +checksum = "d2eb5b96ecdc99f72657332953d4d9c50135af1bac34277801cc3937906ebd39" dependencies = [ "cc", "codespan-reporting", @@ -603,15 +619,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "820a9a2af1669deeef27cb271f476ffd196a2c4b6731336011e0ba63e2c7cf71" +checksum = "ac040a39517fd1674e0f32177648334b0f4074625b5588a64519804ba0553b12" [[package]] name = "cxxbridge-macro" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08a6e2fcc370a089ad3b4aaf54db3b1b4cee38ddabce5896b33eb693275f470" +checksum = "1362b0ddcfc4eb0a1f57b68bd77dd99f0e826958a96abd0ae9bd092e114ffed6" dependencies = [ "proc-macro2", "quote", @@ -690,7 +706,7 @@ version = "0.8.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -779,6 +795,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "frontend" +version = "0.1.0" +dependencies = [ + "common", + "console_error_panic_hook", + "wasm-bindgen", + "web-sys", + "wee_alloc", +] + [[package]] name = "futures" version = "0.3.25" @@ -884,7 +911,7 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "wasi 0.11.0+wasi-snapshot-preview1", ] @@ -1063,7 +1090,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1159,9 +1186,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.137" +version = "0.2.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" +checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" [[package]] name = "libsqlite3-sys" @@ -1223,7 +1250,7 @@ version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1244,6 +1271,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +[[package]] +name = "memory_units" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" + [[package]] name = "mime" version = "0.3.16" @@ -1354,7 +1387,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "redox_syscall", "smallvec", @@ -1386,9 +1419,9 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" [[package]] name = "pest" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f400b0f7905bf702f9f3dc3df5a121b16c54e9e8012c082905fdf09a931861a" +checksum = "cc8bed3549e0f9b0a2a78bf7c0018237a2cdf085eecbbc048e52612438e4e9d0" dependencies = [ "thiserror", "ucd-trie", @@ -1396,9 +1429,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "423c2ba011d6e27b02b482a3707c773d19aec65cc024637aec44e19652e66f63" +checksum = "cdc078600d06ff90d4ed238f0119d84ab5d43dbaad278b0e33a8820293b32344" dependencies = [ "pest", "pest_generator", @@ -1406,9 +1439,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e64e6c2c85031c02fdbd9e5c72845445ca0a724d419aa0bc068ac620c9935c1" +checksum = "28a1af60b1c4148bb269006a750cff8e2ea36aff34d2d96cf7be0b14d1bed23c" dependencies = [ "pest", "pest_meta", @@ -1419,9 +1452,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57959b91f0a133f89a68be874a5c88ed689c19cd729ecdb5d762ebf16c64d662" +checksum = "fec8605d59fc2ae0c6c1aefc0c7c7a9769732017c0ce07f7a9cfffa7b4404f20" dependencies = [ "once_cell", "pest", @@ -1496,9 +1529,9 @@ dependencies = [ [[package]] name = "quoted_printable" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fee2dce59f7a43418e3382c766554c614e06a552d53a8f07ef499ea4b332c0f" +checksum = "20f14e071918cbeefc5edc986a7aa92c425dae244e003a35e1cdddb5ca39b5cb" [[package]] name = "r2d2" @@ -1667,9 +1700,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.36.4" +version = "0.36.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb93e85278e08bb5788653183213d3a60fc242b10cb9be96586f5a73dcb67c23" +checksum = "a3807b5d10909833d3e9acd1eb5fb988f79376ff10fce42937de71a449c4c588" dependencies = [ "bitflags", "errno", @@ -1745,18 +1778,18 @@ checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4" [[package]] name = "serde" -version = "1.0.148" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e53f64bb4ba0191d6d0676e1b141ca55047d83b74f5607e6d8eb88126c52c2dc" +checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.148" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55492425aa53521babf6137309e7d34c20bbfbbfcfe2c7f3a047fd1f6b92c0c" +checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4" dependencies = [ "proc-macro2", "quote", @@ -1792,7 +1825,7 @@ version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -1857,9 +1890,9 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" [[package]] name = "syn" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae548ec36cf198c0ef7710d3c230987c2d6d7bd98ad6edc0274462724c585ce" +checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908" dependencies = [ "proc-macro2", "quote", @@ -1950,9 +1983,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.22.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d76ce4a75fb488c605c54bf610f221cea8b0dafb53333c1a67e8ee199dcd2ae3" +checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46" dependencies = [ "autocfg", "bytes", @@ -1963,7 +1996,7 @@ dependencies = [ "pin-project-lite", "signal-hook-registry", "socket2", - "winapi", + "windows-sys", ] [[package]] @@ -1995,7 +2028,7 @@ version = "0.1.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "log", "pin-project-lite", "tracing-core", @@ -2028,9 +2061,9 @@ checksum = "a9b2228007eba4120145f785df0f6c92ea538f5a3635a612ecf4e334c8c1446d" [[package]] name = "typenum" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "ucd-trie" @@ -2133,7 +2166,7 @@ version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "wasm-bindgen-macro", ] @@ -2210,6 +2243,18 @@ dependencies = [ "webpki", ] +[[package]] +name = "wee_alloc" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "memory_units", + "winapi", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index cd3e08e..1686e30 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "backend", + "frontend", "common", ] diff --git a/README.md b/README.md index d78b1f1..cb02d2c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # Use cases ## Create a recipe + +To create a recipe the user must have an account. + +* The user (A group is automatically created) ## Create a groupe @@ -21,21 +25,29 @@ The toolchain for Raspberry Pi 64 bits is available here: https://gnutoolchains.com/raspberry64/ - ## How to install service on RPI Zero 1. Copy doc/recipes.service to /lib/systemd/system 2. Enabled it: #> systemctl enable recipes +## Backend + +Autoreload: https://actix.rs/docs/autoreload/ + +### Frontend + +## WebAssembly + +'frontend' project needs some tools to generate the WebAssembly stuff. Everything is explained here: https://rustwasm.github.io/wasm-bindgen/examples/hello-world.html + +To compile run 'wasm-pack build' in 'frontend' directory +To launch node run 'npm run start' in 'frontend/www' directory ## Useful URLs * Rust patterns : https://github.com/rust-unofficial/patterns/tree/master/patterns * Rusqlite (SQLite) : https://docs.rs/rusqlite/0.20.0/rusqlite/ - -## How to develop - -Autoreload: https://actix.rs/docs/autoreload/ +* Node install: https://nodejs.org/en/download/ diff --git a/TODO.md b/TODO.md index 0bb5b28..af94b71 100644 --- a/TODO.md +++ b/TODO.md @@ -1,8 +1,10 @@ +* Change all id to i64 * Try using WASM for all the client logic (test on signup page) * Describe the use cases. * Define the UI (mockups). * Two CSS: one for desktop and one for mobile * Define the logic behind each page and action. +* Add support to language into db model. [ok] Check cookie lifetime -> Session by default [ok] Asynchonous email sending and database requests diff --git a/backend/sql/data_test.sql b/backend/sql/data_test.sql index c5fe230..890baa5 100644 --- a/backend/sql/data_test.sql +++ b/backend/sql/data_test.sql @@ -1,7 +1,7 @@ INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) VALUES ( 1, - 'paul@test.org', + 'paul@atreides.com', 'paul', '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY', 0, diff --git a/backend/sql/version_1.sql b/backend/sql/version_1.sql index 93f567b..c3488db 100644 --- a/backend/sql/version_1.sql +++ b/backend/sql/version_1.sql @@ -42,10 +42,21 @@ CREATE TABLE [Recipe] ( [estimate_time] INTEGER, [description] TEXT, [servings] INTEGER DEFAULT 4, + [is_published] INTEGER NOT NULL DEFAULT FALSE, FOREIGN KEY([user_id]) REFERENCES [User]([id]) ON DELETE SET NULL ); +CREATE TABLE [Image] ( + [Id] INTEGER PRIMARY KEY, + [recipe_id] INTEGER NOT NULL, + [name] TEXT, + [description] TEXT, + [image] BLOB, + + FOREIGN KEY([recipe_id]) REFERENCES [Recipe]([id]) ON DELETE CASCADE +); + CREATE TABLE [RecipeTag] ( [id] INTEGER PRIMARY KEY, diff --git a/backend/src/data/asynchronous.rs b/backend/src/data/asynchronous.rs index 4dda803..a5a5cdf 100644 --- a/backend/src/data/asynchronous.rs +++ b/backend/src/data/asynchronous.rs @@ -49,17 +49,17 @@ fn combine_errors(error: std::result::Result = std::result::Result; impl Connection { - pub async fn get_all_recipe_titles_async(&self) -> Result> { + pub async fn get_all_recipe_titles_async(&self) -> Result> { let self_copy = self.clone(); web::block(move || { self_copy.get_all_recipe_titles().unwrap_or_default() }).await.map_err(DBAsyncError::from) } - pub async fn get_recipe_async(&self, id: i32) -> Result { + pub async fn get_recipe_async(&self, id: i64) -> Result { let self_copy = self.clone(); combine_errors(web::block(move || { self_copy.get_recipe(id).map_err(DBAsyncError::from) }).await) } - pub async fn load_user_async(&self, user_id: i32) -> Result { + pub async fn load_user_async(&self, user_id: i64) -> Result { let self_copy = self.clone(); combine_errors(web::block(move || { self_copy.load_user(user_id).map_err(DBAsyncError::from) }).await) } @@ -101,4 +101,15 @@ impl Connection { let token_copy = token.to_string(); combine_errors(web::block(move || { self_copy.sign_out(&token_copy).map_err(DBAsyncError::from) }).await) } + + pub async fn create_recipe_async(&self, user_id: i64) -> Result { + let self_copy = self.clone(); + combine_errors(web::block(move || { self_copy.create_recipe(user_id).map_err(DBAsyncError::from) }).await) + } + + pub async fn set_recipe_title_async(&self, recipe_id: i64, title: &str) -> Result<()> { + let self_copy = self.clone(); + let title_copy = title.to_string(); + combine_errors(web::block(move || { self_copy.set_recipe_title(recipe_id, &title_copy).map_err(DBAsyncError::from) }).await) + } } \ No newline at end of file diff --git a/backend/src/data/db.rs b/backend/src/data/db.rs index 0014f7f..f16487d 100644 --- a/backend/src/data/db.rs +++ b/backend/src/data/db.rs @@ -60,7 +60,7 @@ pub enum SignUpResult { pub enum ValidationResult { UnknownUser, ValidationExpired, - Ok(String, i32), // Returns token and user id. + Ok(String, i64), // Returns token and user id. } #[derive(Debug)] @@ -68,18 +68,17 @@ pub enum SignInResult { UserNotFound, WrongPassword, AccountNotValidated, - Ok(String, i32), // Returns token and user id. + Ok(String, i64), // Returns token and user id. } #[derive(Debug)] pub enum AuthenticationResult { NotValidToken, - Ok(i32), // Returns user id. + Ok(i64), // Returns user id. } #[derive(Clone)] pub struct Connection { - //con: rusqlite::Connection pool: Pool } @@ -106,13 +105,13 @@ impl Connection { fn create_connection(manager: SqliteConnectionManager) -> Result { let pool = r2d2::Pool::new(manager).unwrap(); let connection = Connection { pool }; - connection.create_or_update()?; + connection.create_or_update_db()?; Ok(connection) } /// Called after the connection has been established for creating or updating the database. /// The 'Version' table tracks the current state of the database. - fn create_or_update(&self) -> Result<()> { + fn create_or_update_db(&self) -> Result<()> { // Check the Database version. let mut con = self.pool.get()?; let tx = con.transaction()?; @@ -174,12 +173,12 @@ impl Connection { } } - pub fn get_all_recipe_titles(&self) -> Result> { + pub fn get_all_recipe_titles(&self) -> Result> { let con = self.pool.get()?; let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?; - let titles: std::result::Result, rusqlite::Error> = + let titles: std::result::Result, rusqlite::Error> = stmt.query_map([], |row| { Ok((row.get("id")?, row.get("title")?)) })?.collect(); @@ -198,7 +197,7 @@ impl Connection { Ok(recipes) } */ - pub fn get_recipe(&self, id: i32) -> Result { + pub fn get_recipe(&self, id: i64) -> Result { let con = self.pool.get()?; con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| { Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?)) @@ -216,7 +215,7 @@ impl Connection { }).map_err(DBError::from) } - pub fn load_user(&self, user_id: i32) -> Result { + pub fn load_user(&self, user_id: i64) -> Result { let con = self.pool.get()?; con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| { Ok(User { @@ -234,7 +233,7 @@ impl Connection { let tx = con.transaction()?; let token = match tx.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, Option>("validation_token")?)) + Ok((r.get::<&str, i64>("id")?, r.get::<&str, Option>("validation_token")?)) }).optional()? { Some((id, validation_token)) => { if validation_token.is_none() { @@ -261,7 +260,7 @@ impl Connection { let tx = con.transaction()?; let user_id = match tx.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, DateTime>("creation_datetime")?)) + Ok((r.get::<&str, i64>("id")?, r.get::<&str, DateTime>("creation_datetime")?)) }).optional()? { Some((id, creation_datetime)) => { if Utc::now() - creation_datetime > validation_time { @@ -283,7 +282,7 @@ impl Connection { let mut con = self.pool.get()?; let tx = con.transaction()?; match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option>("validation_token")?)) + Ok((r.get::<&str, i64>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option>("validation_token")?)) }).optional()? { Some((id, stored_password, validation_token)) => { if validation_token.is_some() { @@ -306,7 +305,7 @@ impl Connection { let mut con = self.pool.get()?; let tx = con.transaction()?; match tx.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, i32>("user_id")?)) + Ok((r.get::<&str, i64>("id")?, r.get::<&str, i64>("user_id")?)) }).optional()? { Some((login_id, user_id)) => { tx.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params![login_id, Utc::now(), ip, user_agent])?; @@ -322,7 +321,7 @@ impl Connection { let mut con = self.pool.get()?; let tx = con.transaction()?; match tx.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token], |r| { - Ok(r.get::<&str, i32>("id")?) + Ok(r.get::<&str, i64>("id")?) }).optional()? { Some(login_id) => { tx.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params![login_id])?; @@ -333,6 +332,33 @@ impl Connection { Ok(()) } + pub fn create_recipe(&self, user_id: i64) -> Result { + let con = self.pool.get()?; + + // Verify if an empty recipe already exists. Returns its id if one exists. + match con.query_row( + "SELECT [Recipe].[id] FROM [Recipe] + INNER JOIN [Image] ON [Image].[recipe_id] = [Recipe].[id] + INNER JOIN [Group] ON [Group].[recipe_id] = [Recipe].[id] + WHERE [Recipe].[user_id] = ?1 AND [Recipe].[estimate_time] = NULL AND [Recipe].[description] = NULL", + [user_id], + |r| { + Ok(r.get::<&str, i64>("id")?) + } + ).optional()? { + Some(recipe_id) => Ok(recipe_id), + None => { + con.execute("INSERT INTO [Recipe] ([user_id], [title]) VALUES (?1, '')", [user_id])?; + Ok(con.last_insert_rowid()) + }, + } + } + + pub fn set_recipe_title(&self, recipe_id: i64, title: &str) -> Result<()> { + let con = self.pool.get()?; + con.execute("UPDATE [Recipe] SET [title] = ?2 WHERE [id] = ?1", params![recipe_id, title]).map(|_n| ()).map_err(DBError::from) + } + /// Execute a given SQL file. pub fn execute_file + fmt::Display>(&self, file: P) -> Result<()> { let con = self.pool.get()?; @@ -348,7 +374,7 @@ impl Connection { } // Return the token. - fn create_login_token(tx: &rusqlite::Transaction, user_id: i32, ip: &str, user_agent: &str) -> Result { + fn create_login_token(tx: &rusqlite::Transaction, user_id: i64, ip: &str, user_agent: &str) -> Result { let token = generate_token(); tx.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params![user_id, Utc::now(), token, ip, user_agent])?; Ok(token) @@ -369,6 +395,7 @@ fn generate_token() -> String { #[cfg(test)] mod tests { use super::*; + use rusqlite::{Error, ErrorCode, ffi, types::Value}; #[test] fn sign_up() -> Result<()> { @@ -603,4 +630,37 @@ mod tests { Ok(()) } + + + #[test] + fn create_a_new_recipe_then_update_its_title() -> Result<()> { + let connection = Connection::new_in_memory()?; + + connection.execute_sql( + "INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token]) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + 1, + "paul@atreides.com", + "paul", + "$argon2id$v=19$m=4096,t=3,p=1$G4fjepS05MkRbTqEImUdYg$GGziE8uVQe1L1oFHk37lBno10g4VISnVqynSkLCH3Lc", + "2022-11-29 22:05:04.121407300+00:00", + Value::Null, + ] + )?; + + match connection.create_recipe(2) { + Err(DBError::SqliteError(Error::SqliteFailure(ffi::Error { code: ErrorCode::ConstraintViolation, extended_code: _ }, Some(_)))) => (), // Nominal case. + other => panic!("Creating a recipe with an inexistant user must fail: {:?}", other), + } + + let recipe_id = connection.create_recipe(1)?; + assert_eq!(recipe_id, 1); + + connection.set_recipe_title(recipe_id, "Crêpe")?; + + let recipe = connection.get_recipe(recipe_id)?; + assert_eq!(recipe.title, "Crêpe".to_string()); + + Ok(()) + } } diff --git a/backend/src/model.rs b/backend/src/model.rs index 719ed21..d0f95d2 100644 --- a/backend/src/model.rs +++ b/backend/src/model.rs @@ -1,5 +1,5 @@ pub struct Recipe { - pub id: i32, + pub id: i64, pub title: String, pub description: Option, pub estimate_time: Option, // [min]. @@ -10,7 +10,7 @@ pub struct Recipe { } impl Recipe { - pub fn new(id: i32, title: String, description: Option) -> Recipe { + pub fn new(id: i64, title: String, description: Option) -> Recipe { Recipe { id, title, diff --git a/backend/src/services.rs b/backend/src/services.rs index df81c43..2d69cc5 100644 --- a/backend/src/services.rs +++ b/backend/src/services.rs @@ -14,6 +14,8 @@ use crate::user::User; use crate::model; use crate::data::{db, asynchronous}; +mod api; + ///// UTILS ///// fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) { @@ -119,8 +121,8 @@ impl actix_web::error::ResponseError for ServiceError { #[template(path = "home.html")] struct HomeTemplate { user: Option, - recipes: Vec<(i32, String)>, - current_recipe_id: Option, + recipes: Vec<(i64, String)>, + current_recipe_id: Option, } #[get("/")] @@ -137,13 +139,13 @@ pub async fn home_page(req: HttpRequest, connection: web::Data) #[template(path = "view_recipe.html")] struct ViewRecipeTemplate { user: Option, - recipes: Vec<(i32, String)>, - current_recipe_id: Option, + recipes: Vec<(i64, String)>, + current_recipe_id: Option, current_recipe: model::Recipe, } #[get("/recipe/view/{id}")] -pub async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data) -> Result { +pub async fn view_recipe(req: HttpRequest, path: web::Path<(i64,)>, connection: web::Data) -> Result { let (id,)= path.into_inner(); let user = get_current_user(&req, connection.clone()).await; let recipes = connection.get_all_recipe_titles_async().await?; @@ -255,10 +257,10 @@ pub async fn sign_up_post(req: HttpRequest, form: web::Form, con Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => { let url = { let host = req.headers().get(header::HOST).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default(); - let port: Option = 'p: { + let port: Option = 'p: { let split_port: Vec<&str> = host.split(':').collect(); if split_port.len() == 2 { - if let Ok(p) = split_port[1].parse::() { + if let Ok(p) = split_port[1].parse::() { break 'p Some(p) } } diff --git a/backend/src/services/api.rs b/backend/src/services/api.rs new file mode 100644 index 0000000..aa160fc --- /dev/null +++ b/backend/src/services/api.rs @@ -0,0 +1,27 @@ +use actix_web::{http::{header, header::ContentType, StatusCode}, get, post, put, web, Responder, HttpRequest, HttpResponse, cookie::Cookie}; +use chrono::Duration; +use serde::Deserialize; +use log::{debug, error, log_enabled, info, Level}; + +use super::Result; +use crate::utils; +use crate::consts; +use crate::config::Config; +use crate::user::User; +use crate::model; +use crate::data::{db, asynchronous}; + +#[put("/ron-api/set-title")] +pub async fn set_title(req: HttpRequest, connection: web::Data) -> Result { + //req.app_config() + let id = 1; + let title = "XYZ".to_string(); + + //let recipes = connection.set_recipe_title_async(id, title).await?; + + Ok( + HttpResponse::Ok() + .content_type("application/ron") + .body("DATA") + ) +} \ No newline at end of file diff --git a/backend/static/frontend.js b/backend/static/frontend.js new file mode 100644 index 0000000..3386a53 --- /dev/null +++ b/backend/static/frontend.js @@ -0,0 +1,294 @@ + +let wasm; + +const cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +let cachedUint8Memory0 = new Uint8Array(); + +function getUint8Memory0() { + if (cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; +} + +function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +const heap = new Array(32).fill(undefined); + +heap.push(undefined, null, true, false); + +let heap_next = heap.length; + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +function getObject(idx) { return heap[idx]; } + +function dropObject(idx) { + if (idx < 36) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +let WASM_VECTOR_LEN = 0; + +const cachedTextEncoder = new TextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length); + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len); + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3); + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} +/** +* @param {string} name +*/ +export function greet(name) { + const ptr0 = passStringToWasm0(name, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1); + const len0 = WASM_VECTOR_LEN; + wasm.greet(ptr0, len0); +} + +/** +*/ +export function main() { + wasm.main(); +} + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + wasm.__wbindgen_export_2(addHeapObject(e)); + } +} + +function isLikeNone(x) { + return x === undefined || x === null; +} + +async function load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } +} + +function getImports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_alert_02b82f812a9453a9 = function(arg0, arg1) { + alert(getStringFromWasm0(arg0, arg1)); + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); + }; + imports.wbg.__wbg_log_4b5638ad60bdc54a = function(arg0) { + console.log(getObject(arg0)); + }; + imports.wbg.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); + }; + imports.wbg.__wbg_self_6d479506f72c6a71 = function() { return handleError(function () { + const ret = self.self; + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_window_f2557cc78490aceb = function() { return handleError(function () { + const ret = window.window; + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_globalThis_7f206bda628d5286 = function() { return handleError(function () { + const ret = globalThis.globalThis; + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_global_ba75c50d1cf384f4 = function() { return handleError(function () { + const ret = global.global; + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbindgen_is_undefined = function(arg0) { + const ret = getObject(arg0) === undefined; + return ret; + }; + imports.wbg.__wbg_newnoargs_b5b063fc6c2f0376 = function(arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }; + imports.wbg.__wbg_call_97ae9d8645dc388b = function() { return handleError(function (arg0, arg1) { + const ret = getObject(arg0).call(getObject(arg1)); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbindgen_object_clone_ref = function(arg0) { + const ret = getObject(arg0); + return addHeapObject(ret); + }; + imports.wbg.__wbg_instanceof_Window_acc97ff9f5d2c7b4 = function(arg0) { + let result; + try { + result = getObject(arg0) instanceof Window; + } catch { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_document_3ead31dbcad65886 = function(arg0) { + const ret = getObject(arg0).document; + return isLikeNone(ret) ? 0 : addHeapObject(ret); + }; + imports.wbg.__wbg_body_3cb4b4042b9a632b = function(arg0) { + const ret = getObject(arg0).body; + return isLikeNone(ret) ? 0 : addHeapObject(ret); + }; + imports.wbg.__wbg_createElement_976dbb84fe1661b5 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = getObject(arg0).createElement(getStringFromWasm0(arg1, arg2)); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbg_setinnerHTML_32081d8a164e6dc4 = function(arg0, arg1, arg2) { + getObject(arg0).innerHTML = getStringFromWasm0(arg1, arg2); + }; + imports.wbg.__wbg_appendChild_e513ef0e5098dfdd = function() { return handleError(function (arg0, arg1) { + const ret = getObject(arg0).appendChild(getObject(arg1)); + return addHeapObject(ret); + }, arguments) }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + imports.wbg.__wbindgen_rethrow = function(arg0) { + throw takeObject(arg0); + }; + + return imports; +} + +function initMemory(imports, maybe_memory) { + +} + +function finalizeInit(instance, module) { + wasm = instance.exports; + init.__wbindgen_wasm_module = module; + cachedUint8Memory0 = new Uint8Array(); + + wasm.__wbindgen_start(); + return wasm; +} + +function initSync(module) { + const imports = getImports(); + + initMemory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return finalizeInit(instance, module); +} + +async function init(input) { + if (typeof input === 'undefined') { + input = new URL('frontend_bg.wasm', import.meta.url); + } + const imports = getImports(); + + if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) { + input = fetch(input); + } + + initMemory(imports); + + const { instance, module } = await load(await input, imports); + + return finalizeInit(instance, module); +} + +export { initSync } +export default init; diff --git a/backend/style.scss b/backend/style.scss index 72565b6..4f7cc70 100644 --- a/backend/style.scss +++ b/backend/style.scss @@ -32,6 +32,15 @@ body { background-color: $background; margin: 0px; + .recipe-item { + padding: 4px; + } + + .recipe-item-current { + padding: 3px; + border: 1px solid white; + } + /* .header-container { diff --git a/backend/templates/base.html b/backend/templates/base.html index 9b7356d..6b8e1ad 100644 --- a/backend/templates/base.html +++ b/backend/templates/base.html @@ -8,6 +8,14 @@ + + {% block body_container %}{% endblock %} diff --git a/backend/templates/base_with_header.html b/backend/templates/base_with_header.html index 04cdd9f..e8ed659 100644 --- a/backend/templates/base_with_header.html +++ b/backend/templates/base_with_header.html @@ -2,13 +2,17 @@ {% block body_container %}
-

~~ Recettes de cuisine ~~

+ ~~ Recettes de cuisine ~~ + + Create a new recipe + {% match user %} {% when Some with (user) %} -
{{ user.email }} / Sign out
+ {{ user.email }} / Sign out {% when None %} - + Sign in / Sign up {% endmatch %} +
{% block main_container %}{% endblock %} diff --git a/backend/templates/base_with_list.html b/backend/templates/base_with_list.html index 715c9e7..e9db979 100644 --- a/backend/templates/base_with_list.html +++ b/backend/templates/base_with_list.html @@ -1,22 +1,25 @@ {% extends "base_with_header.html" %} +{% macro recipe_item(id, title, class) %} +{{ title }} +{% endmacro %} + {% block main_container %}
    {% for (id, title) in recipes %}
  • - {% let item_html = "{}"|format(id, title) %} {% match current_recipe_id %} {# Don't know how to avoid repetition: comparing (using '==' or .eq()) current_recipe_id.unwrap() and id doesn't work. Guards for match don't exist. See: https://github.com/djc/askama/issues/752 #} {% when Some (current_id) %} {% if current_id == id %} - [{{ item_html|escape("none") }}] + {% call recipe_item(id, title, "recipe-item-current") %} {% else %} - {{ item_html|escape("none") }} + {% call recipe_item(id, title, "recipe-item") %} {% endif %} {% when None %} - {{ item_html|escape("none") }} + {% call recipe_item(id, title, "recipe-item") %} {% endmatch %}
  • {% endfor %} diff --git a/frontend/Cargo.toml b/frontend/Cargo.toml new file mode 100644 index 0000000..374be95 --- /dev/null +++ b/frontend/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "frontend" +version = "0.1.0" +authors = ["Greg Burri "] +edition = "2021" + +[lib] +crate-type = ["cdylib"] + +[features] +default = ["console_error_panic_hook"] + +[dependencies] +common = {path = "../common"} + +wasm-bindgen = "0.2" +web-sys = { version = "0.3", features = ['console', 'Document', 'Element', 'HtmlElement', 'Node', 'Window'] } + +# The `console_error_panic_hook` crate provides better debugging of panics by +# logging them with `console.error`. This is great for development, but requires +# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for +# code size when deploying. +console_error_panic_hook = { version = "0.1", optional = true } + +# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size +# compared to the default allocator's ~10K. It is slower than the default +# allocator, however. +wee_alloc = { version = "0.4", optional = true } + +# [dev-dependencies] +# wasm-bindgen-test = "0.3" + +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = "s" +lto = true + +[package.metadata.wasm-pack.profile.release] +wasm-opt = false \ No newline at end of file diff --git a/frontend/deploy.nu b/frontend/deploy.nu new file mode 100644 index 0000000..ca50923 --- /dev/null +++ b/frontend/deploy.nu @@ -0,0 +1,3 @@ +wasm-pack build --target web +cp pkg/frontend.js ../backend/static +cp pkg/frontend_bg.wasm ../backend/static \ No newline at end of file diff --git a/frontend/index.js b/frontend/index.js new file mode 100644 index 0000000..ebc5567 --- /dev/null +++ b/frontend/index.js @@ -0,0 +1,8 @@ +// Note that a dynamic `import` statement here is required due to +// webpack/webpack#6615, but in theory `import { greet } from './pkg';` +// will work here one day as well! +const rust = import('./pkg'); + +rust + .then(m => m.greet('Paul!')) + .catch(console.error); \ No newline at end of file diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..ed1f2aa --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,14 @@ +{ + "scripts": { + "build": "webpack", + "serve": "webpack serve" + }, + "devDependencies": { + "@wasm-tool/wasm-pack-plugin": "1.5.0", + "html-webpack-plugin": "^5.3.2", + "text-encoding": "^0.7.0", + "webpack": "^5.75.0", + "webpack-cli": "^4.10.0", + "webpack-dev-server": "^3.11.2" + } +} diff --git a/frontend/src/lib.rs b/frontend/src/lib.rs new file mode 100644 index 0000000..1607fc0 --- /dev/null +++ b/frontend/src/lib.rs @@ -0,0 +1,35 @@ +mod utils; + +use wasm_bindgen::prelude::*; +use web_sys::console; + +// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global +// allocator. +#[cfg(feature = "wee_alloc")] +#[global_allocator] +static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; + +#[wasm_bindgen] +extern { + fn alert(s: &str); +} + +#[wasm_bindgen] +pub fn greet(name: &str) { + alert(&format!("Hello, {}!", name)); + console::log_1(&"Hello bg".into()); +} + +#[wasm_bindgen(start)] +pub fn main() -> Result<(), JsValue> { + let window = web_sys::window().expect("no global `window` exists"); + let document = window.document().expect("should have a document on window"); + let body = document.body().expect("document should have a body"); + + let val = document.create_element("p")?; + val.set_inner_html("Hello from Rust!"); + + body.append_child(&val)?; + + Ok(()) +} \ No newline at end of file diff --git a/frontend/src/utils.rs b/frontend/src/utils.rs new file mode 100644 index 0000000..b1d7929 --- /dev/null +++ b/frontend/src/utils.rs @@ -0,0 +1,10 @@ +pub fn set_panic_hook() { + // When the `console_error_panic_hook` feature is enabled, we can call the + // `set_panic_hook` function at least once during initialization, and then + // we will get better error messages if our code ever panics. + // + // For more details see + // https://github.com/rustwasm/console_error_panic_hook#readme + #[cfg(feature = "console_error_panic_hook")] + console_error_panic_hook::set_once(); +} diff --git a/frontend/start.nu b/frontend/start.nu new file mode 100644 index 0000000..eb1cffd --- /dev/null +++ b/frontend/start.nu @@ -0,0 +1 @@ +npm run serve \ No newline at end of file diff --git a/frontend/tests/web.rs b/frontend/tests/web.rs new file mode 100644 index 0000000..de5c1da --- /dev/null +++ b/frontend/tests/web.rs @@ -0,0 +1,13 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(target_arch = "wasm32")] + +extern crate wasm_bindgen_test; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen_test] +fn pass() { + assert_eq!(1 + 1, 2); +} diff --git a/frontend/webpack.config.js b/frontend/webpack.config.js new file mode 100644 index 0000000..40448a4 --- /dev/null +++ b/frontend/webpack.config.js @@ -0,0 +1,28 @@ +const path = require('path'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const webpack = require('webpack'); +const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); + +module.exports = { + entry: './index.js', + output: { + path: path.resolve(__dirname, 'dist'), + filename: 'index.js', + }, + plugins: [ + new HtmlWebpackPlugin(), + new WasmPackPlugin({ + crateDirectory: path.resolve(__dirname, ".") + }), + // Have this example work in Edge which doesn't ship `TextEncoder` or + // `TextDecoder` at this time. + new webpack.ProvidePlugin({ + TextDecoder: ['text-encoding', 'TextDecoder'], + TextEncoder: ['text-encoding', 'TextEncoder'] + }) + ], + mode: 'development', + experiments: { + asyncWebAssembly: true + } +}; \ No newline at end of file -- 2.45.2