Repository: jetli/create-yew-app Branch: master Commit: 1aa7cbdfc5eb Files: 28 Total size: 45.6 KB Directory structure: gitextract_tcaxl5i_/ ├── .github/ │ └── workflows/ │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── crates/ │ └── yew-app/ │ ├── .gitignore │ ├── Cargo.toml │ ├── LICENSE-APACHE │ ├── LICENSE-MIT │ ├── README.md │ ├── Trunk.toml │ ├── index.html │ ├── src/ │ │ ├── app/ │ │ │ ├── about.rs │ │ │ ├── home.rs │ │ │ └── mod.rs │ │ ├── components/ │ │ │ ├── mod.rs │ │ │ ├── nav.rs │ │ │ └── ui/ │ │ │ ├── button.rs │ │ │ └── mod.rs │ │ ├── lib.rs │ │ └── main.rs │ ├── tailwind.config.js │ ├── tailwind.css │ └── tests/ │ └── web.rs └── packages/ └── create-yew-app/ ├── README.md ├── createYewApp.js ├── index.js └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/rust.yml ================================================ name: Rust on: push: branches: [ master ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup toolchain uses: dtolnay/rust-toolchain@master with: toolchain: stable targets: wasm32-unknown-unknown components: rust-src - uses: jetli/wasm-pack-action@v0.4.0 with: # Optional version of wasm-pack to install(eg. '0.9.1', 'latest') version: 'latest' - uses: jetli/trunk-action@v0.5.0 with: # Optional version of trunk to install(eg. 'v0.16.0', 'latest') version: 'latest' - name: Cargo fmt & clippy run: | cargo fmt --all -- --check cargo clippy -- --deny=warnings - name: Tests run: | cd crates/yew-app cargo test - name: Run web tests run: | cd crates/yew-app && wasm-pack test --headless --chrome - name: Build app run: | cd crates/yew-app && trunk build --public-url=/create-yew-app/ - name: Deploy uses: JamesIves/github-pages-deploy-action@v4.2.2 with: branch: gh-pages folder: crates/yew-app/dist clean: true ================================================ FILE: .gitignore ================================================ # Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # JS .idea/ .vscode/ node_modules/ build dist pkg .cache .DS_Store my-app* lerna-debug.log npm-debug.log* yarn-debug.log* yarn-error.log* /.changelog .npm/ yarn.lock package-lock.json ================================================ FILE: Cargo.toml ================================================ [workspace] resolver = "2" members = ["crates/*"] ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Create Yew App Create Yew apps with no build configuration. - [Creating an App](#creating-an-app) – How to create a new app. - [Yew](https://github.com/yewstack/yew) - Rust / Wasm framework for building client web apps. - [Awesome Yew](https://github.com/jetli/awesome-yew) - A curated list of awesome things related to Yew / WebAssembly. - [Realworld example](https://github.com/jetli/rust-yew-realworld-example-app) - Exemplary real world app built with Rust + Yew + WebAssembly. [Check out a live demo](https://jetli.github.io/create-yew-app/) powered by Create Yew App. ## Quick Overview ```sh npx create-yew-app my-app cd my-app trunk serve ``` _([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f))_ Then open [http://localhost:8080/](http://localhost:8080/) to see your app.
When you’re ready to deploy to production, create a minified bundle with `trunk build`. ## Getting Started ### Install Rust wasm target ```sh rustup target add wasm32-unknown-unknown ``` ### Install [Trunk](https://trunkrs.dev). ## Creating an App **You’ll need to have Node 8.16.0 or Node 10.16.0 or later version on your local development machine** (but it’s not required on the server). You can use [nvm](https://github.com/creationix/nvm#installation) (macOS/Linux) or [nvm-windows](https://github.com/coreybutler/nvm-windows#node-version-manager-nvm-for-windows) to switch Node versions between different projects. To create a new app, you may choose one of the following methods: ### npx ```sh npx create-yew-app my-app ``` _([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) is a package runner tool that comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f))_ ### npm ```sh npm init yew-app my-app ``` _`npm init ` is available in npm 6+_ ### Yarn ```sh yarn create yew-app my-app ``` _[`yarn create `](https://yarnpkg.com/lang/en/docs/cli/create/) is available in Yarn 0.25+_ ### Project structure It will create a directory called `my-app` inside the current folder.
Inside that directory, it will generate the initial project structure and install the transitive dependencies: ``` my-app ├── README.md ├── .gitignore ├── Cargo.toml ├── index.html ├── LICENSE-APACHE ├── LICENSE-MIT ├── tailwind.config.js ├── tailwind.css ├── Trunk.toml ├── public │ ├── favicon.ico │ ├── logo.svg └── src ├── lib.rs ├── main.rs ├── app │ ├── about.rs │ ├── home.rs │ └── mod.rs └── components ├── nav.rs └── mod.rs ``` No configuration or complicated folder structures, only the files you need to build your app.
Once the installation is done, you can open your project folder: ```sh cd my-app ``` Inside the newly created project, you can run some built-in commands: ### `trunk serve` Runs the app in development mode.
Open [http://localhost:8080](http://localhost:8080) to view it in the browser. The page will automatically reload if you make changes to the code.
You will see the build errors and lint warnings in the console. ### `trunk build` Builds the app for production to the `dist` folder.
It correctly bundles Yew in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.
Your app is ready to be deployed. ### `wasm-pack test --headless --chrome` Runs the test watcher in an interactive mode.
By default, runs tests related to files changed since the last commit. # Contributing Feel free to take a look at the current issues in this repo for anything that currently needs to be worked on. You are also welcome to open a PR or a new issue if you see something is missing or could be improved upon. # License Apache License (Version 2.0) See [LICENSE](./LICENSE) for details. ================================================ FILE: crates/yew-app/.gitignore ================================================ # Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # JS node_modules /dist /pkg /wasm-pack.log .cache ================================================ FILE: crates/yew-app/Cargo.toml ================================================ [package] authors = ["You "] categories = ["wasm"] description = "My awesome Yew app." edition = "2021" license = "Apache-2.0/MIT" name = "yew-app" readme = "./README.md" repository = "https://github.com/jetli/create-yew-app.git" version = "0.1.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] log = "0.4" serde = "1" reqwest = { version = "0.12", features = ["json"] } yew = { version = "0.23", features = ["csr"] } yew-router = "0.20" yew-hooks = "0.6" wasm-bindgen = "0.2" wasm-logger = "0.2" [dev-dependencies] wasm-bindgen-test = "0.3" gloo-utils = "0.2" [dev-dependencies.web-sys] version = "0.3" features = ["Document", "Element", "HtmlCollection"] ================================================ FILE: crates/yew-app/LICENSE-APACHE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: crates/yew-app/LICENSE-MIT ================================================ Copyright (c) 2018 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: crates/yew-app/README.md ================================================ # My Awesome Yew App This is the official base template for [Create Yew App](https://github.com/jetli/create-yew-app). ## How to run in debug mode ```sh # Builds the project and opens it in a new browser tab. Auto-reloads when the project changes. trunk serve ``` ## How to build in release mode ```sh # Builds the project and places it into the `dist` folder. trunk build ``` ## How to run unit tests ```sh # Runs tests wasm-pack test --headless --chrome ``` ================================================ FILE: crates/yew-app/Trunk.toml ================================================ [build] target = "index.html" dist = "dist" ================================================ FILE: crates/yew-app/index.html ================================================ Yew App ================================================ FILE: crates/yew-app/src/app/about.rs ================================================ use serde::{de::DeserializeOwned, Deserialize, Serialize}; use yew::prelude::*; use yew_hooks::prelude::*; use crate::components::ui::button::Button; /// About page #[function_component(About)] pub fn about() -> Html { let state = use_async(async move { fetch_repo(("jetli/create-yew-app".to_string()).clone()).await }); let onclick = { let state = state.clone(); Callback::from(move |_| { state.run(); }) }; html! {

{ "Create Yew App" } { ", Set up a modern yew web app by running one command." }

{ if state.loading { html! { "Loading, wait a sec..." } } else { html! {} } }

{ if let Some(repo) = &state.data { html! { <>

{ "Repo name: " }{ &repo.name }

{ "Repo full name: " }{ &repo.full_name }

{ "Repo description: " }{ &repo.description }

} } else { html! {} } }

{ if let Some(error) = &state.error { match error { Error::DeserializeError => html! { "DeserializeError" }, Error::RequestError => html! { "RequestError" }, } } else { html! {} } }

{ "Edit " } { "src/app/about.rs" } { " and save to reload." }

} } async fn fetch_repo(repo: String) -> Result { fetch::(format!("https://api.github.com/repos/{}", repo)).await } /// You can use reqwest or other crates to fetch your api. async fn fetch(url: String) -> Result where T: DeserializeOwned, { let response = reqwest::get(url).await; if let Ok(data) = response { if let Ok(repo) = data.json::().await { Ok(repo) } else { Err(Error::DeserializeError) } } else { Err(Error::RequestError) } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] struct Repo { id: i32, name: String, full_name: String, description: String, } // You can use thiserror to define your errors. #[derive(Clone, Debug, PartialEq)] enum Error { RequestError, DeserializeError, // etc. } #[cfg(test)] mod tests { use std::time::Duration; use wasm_bindgen_test::*; use yew::platform::time::sleep; wasm_bindgen_test_configure!(run_in_browser); use super::About; #[wasm_bindgen_test] async fn _about_page_has_an_app_link() { yew::Renderer::::with_root( gloo_utils::document().get_element_by_id("output").unwrap(), ) .render(); sleep(Duration::ZERO).await; let app_links = gloo_utils::document().get_elements_by_tag_name("a"); assert_eq!(app_links.length(), 1); let link = app_links.item(0).expect("No app-link").inner_html(); assert_eq!(link, "Create Yew App"); } } ================================================ FILE: crates/yew-app/src/app/home.rs ================================================ use yew::prelude::*; use yew_hooks::prelude::*; use crate::components::ui::button::Button; /// Home page #[function_component(Home)] pub fn home() -> Html { let counter = use_counter(0); let onincrease = { let counter = counter.clone(); Callback::from(move |_| counter.increase()) }; let ondecrease = { let counter = counter.clone(); Callback::from(move |_| counter.decrease()) }; html! {

Yew

{ "Learn Yew" }

{ *counter }

{ "Edit " } { "src/app/home.rs" } { " and save to reload." }

} } ================================================ FILE: crates/yew-app/src/app/mod.rs ================================================ use yew::prelude::*; use yew_router::prelude::*; pub mod about; pub mod home; use crate::components::nav::Nav; use about::About; use home::Home; /// App routes #[derive(Routable, Debug, Clone, PartialEq, Eq)] pub enum AppRoute { #[at("/about")] About, #[not_found] #[at("/page-not-found")] PageNotFound, #[at("/")] Home, } /// Switch app routes pub fn switch(routes: AppRoute) -> Html { match routes.clone() { AppRoute::Home => html! { }, AppRoute::About => html! { }, AppRoute::PageNotFound => html! { "Page not found" }, } } /// Root app component #[function_component(App)] pub fn app() -> Html { html! {
} } ================================================ FILE: crates/yew-app/src/components/mod.rs ================================================ pub mod nav; pub mod ui; ================================================ FILE: crates/yew-app/src/components/nav.rs ================================================ use yew::prelude::*; use yew_router::prelude::*; use crate::app::AppRoute; /// Nav component #[function_component(Nav)] pub fn nav() -> Html { html! {
} } ================================================ FILE: crates/yew-app/src/components/ui/button.rs ================================================ use yew::prelude::*; #[derive(Properties, Clone, PartialEq)] pub struct ButtonProps { #[prop_or_default] pub onclick: Callback, #[prop_or_default] pub disabled: bool, #[prop_or_default] pub button_ref: NodeRef, #[prop_or_default] pub children: Children, } #[function_component] pub fn Button(props: &ButtonProps) -> Html { html! { } } ================================================ FILE: crates/yew-app/src/components/ui/mod.rs ================================================ pub mod button; ================================================ FILE: crates/yew-app/src/lib.rs ================================================ pub mod app; pub mod components; ================================================ FILE: crates/yew-app/src/main.rs ================================================ use yew_app::app::App; // This is the entry point for the web app fn main() { wasm_logger::init(wasm_logger::Config::default()); yew::Renderer::::new().render(); } ================================================ FILE: crates/yew-app/tailwind.config.js ================================================ module.exports = { mode: "jit", content: { files: ["src/**/*.rs", "**/*.html"], }, darkMode: "class", // 'media' or 'class' theme: { container: { center: true, padding: '2rem', screens: { '2xl': '1400px' } }, extend: {}, }, variants: { extend: {}, }, plugins: [], }; ================================================ FILE: crates/yew-app/tailwind.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: crates/yew-app/tests/web.rs ================================================ use std::time::Duration; use wasm_bindgen_test::*; use yew::platform::time::sleep; wasm_bindgen_test_configure!(run_in_browser); use yew_app::app::App; #[wasm_bindgen_test] async fn _app_has_a_home_page() { yew::Renderer::::with_root(gloo_utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::ZERO).await; let learn_yew = gloo_utils::document() .get_element_by_id("learn_yew") .expect("No learn yew anchor or no home page") .inner_html(); assert_eq!(learn_yew, "Learn Yew"); } ================================================ FILE: packages/create-yew-app/README.md ================================================ # create-yew-app This package includes the global command for [Create Yew App](https://github.com/jetli/create-yew-app).
Please refer to its documentation: - [Quick Overview](https://github.com/jetli/create-yew-app#quick-overview) – How to create a new app. - [Creating an App](https://github.com/jetli/create-yew-app#creating-an-app) – How to develop apps bootstrapped with Create Yew App. ## Getting Started ### Install Rust wasm target ```sh rustup target add wasm32-unknown-unknown ``` ### Install [Trunk](https://trunkrs.dev) ### Creating an App ```sh npx create-yew-app my-app cd my-app trunk serve ``` Then open [http://localhost:8080/](http://localhost:8080/) to see your app.
When you’re ready to deploy to production, create a minified bundle with `trunk build`. ================================================ FILE: packages/create-yew-app/createYewApp.js ================================================ #!/usr/bin/env node 'use strict'; const { execSync } = require("child_process"); const spawn = require('cross-spawn'); const chalk = require('chalk'); const fs = require("fs"); const path = require("path"); const cpr = require("cpr"); const rimraf = require("rimraf"); // Check if a tool is present. function isPresent(dep) { try { execSync(dep, {stdio: 'ignore'}); return true; } catch (err) { return false; } } // Run a tool function run(cmd, args, opts) { const output = spawn.sync(cmd, args, opts); if (output.error != null) { throw output.error; } if (output.status !== 0) { throw new Error("Bad error code when running `" + cmd + " " + args.join(" ") + "`: " + output.status); } } // Check required tools if (!isPresent("git --version")) { console.log('\n git is required, see: https://git-scm.com/downloads'); process.exit(1); } if (!isPresent("cargo --version")) { console.log('\n Rust/Cargo is required, see: https://www.rust-lang.org/tools/install'); process.exit(1); } if (!isPresent("trunk --version")) { console.log('\n Trunk is required, see: https://trunkrs.dev'); process.exit(1); } const args = process.argv.slice(2); let folderName = '.'; // Make a dir for the app if (args.length >= 1) { folderName = args[0]; if (!fs.existsSync(folderName)) { fs.mkdirSync(folderName); } } let rootFolder = path.resolve(folderName); let gitFolder = path.join(folderName, ".git-clone"); console.log(); console.log(` Creating a new Yew app in ${chalk.green(rootFolder)}. `); console.log(); // This uses --no-tags and --depth 1 in order to make the cloning faster run("git", ["clone", "--no-tags", "--depth", "1", "https://github.com/jetli/create-yew-app.git", gitFolder]); // Copies the yew-app folder cpr(path.join(gitFolder, "crates/yew-app"), folderName, {}, function (err, files) { // Removes the git folder regardless of whether cpr succeeded or not rimraf.sync(gitFolder); if (err) { throw err; } else { console.log(" 🦀 Rust + 🕸 WebAssembly + Yew = ❤️ "); console.log(); console.log(" Installing dependencies... "); // Install wasm-pack if (!isPresent("wasm-pack --version")) { run("cargo", ["install", "wasm-pack"]); } console.log(" Installed dependencies ✅ "); console.log(); // Git init run("git", ["init"], { cwd: folderName, stdio: 'ignore' }); console.log(" Initialized a git repository ✅ "); console.log(); console.log(` Success! 🎉 Created ${folderName} at ${chalk.green(rootFolder)}`); console.log(' Inside that directory, you can run several commands:'); console.log(); console.log(chalk.cyan(' trunk serve')); console.log(' Starts the development server.'); console.log(); console.log(chalk.cyan(' trunk build')); console.log(' Bundles the app into static files for production.'); console.log(); console.log(chalk.cyan(' wasm-pack test --headless --chrome')); console.log(' Starts the test runner.'); console.log(); console.log(' We suggest that you begin by typing:'); console.log(); console.log(chalk.cyan(' cd'), folderName); console.log(chalk.cyan(' trunk serve')); console.log(); console.log(' Happy hacking! 😎 '); console.log(); } }); ================================================ FILE: packages/create-yew-app/index.js ================================================ #!/usr/bin/env node 'use strict'; var currentNodeVersion = process.versions.node; var semver = currentNodeVersion.split('.'); var major = semver[0]; if (major < 8) { console.error( 'You are running Node ' + currentNodeVersion + '.\n' + 'Create React App requires Node 8 or higher. \n' + 'Please update your version of Node.' ); process.exit(1); } require('./createYewApp'); ================================================ FILE: packages/create-yew-app/package.json ================================================ { "name": "create-yew-app", "version": "0.2.0", "description": "Set up a modern Yew web app by running one command. ", "bin": { "create-yew-app": "./index.js" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/jetli/create-yew-app.git", "directory": "packages/create-yew-app" }, "files": [ "index.js", "createYewApp.js" ], "keywords": [ "yew", "create-yew-app", "wasm", "webassembly", "wasm-bindgen", "wasm-pack", "rust" ], "author": "Jet Li ", "license": "Apache-2.0", "engines": { "node": ">=8" }, "bugs": { "url": "https://github.com/jetli/create-yew-app/issues" }, "homepage": "https://github.com/jetli/create-yew-app#readme", "dependencies": { "chalk": "3.0.0", "cpr": "^3.0.1", "cross-spawn": "^7.0.3", "rimraf": "^3.0.0" } }