From 549cb2e0b70cc55a7d02042680d3f0cdfd7143d1 Mon Sep 17 00:00:00 2001 From: "Spencer C. Imbleau" Date: Mon, 15 Apr 2024 16:21:44 -0400 Subject: [PATCH] build: initial release --- .cargo/config.toml | 2 + .github/workflows/ci.yml | 67 ++++++++++ .github/workflows/web-demo.yml | 67 ++++++++++ .gitignore | 1 + CHANGELOG.md | 15 +++ Cargo.lock | 217 +++++++++++++++++++++++++++++++++ Cargo.toml | 17 +++ LICENSE-APACHE | 176 ++++++++++++++++++++++++++ LICENSE-MIT | 19 +++ README.md | 66 ++++++++++ examples/simple.rs | 16 +++ rustfmt.toml | 6 + src/error.rs | 9 ++ src/lib.rs | 61 +++++++++ tests/tests.rs | 29 +++++ 15 files changed, 768 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/web-demo.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 examples/simple.rs create mode 100644 rustfmt.toml create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 tests/tests.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..758ed61 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.wasm32-unknown-unknown] +runner = "wasm-server-runner" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c04e3bd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,67 @@ +name: CI +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Setup | Checkout + uses: actions/checkout@v4 + + - name: Setup | Toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: clippy,rustfmt + + - name: Rust Cache + uses: Swatinem/rust-cache@v2 + + - name: Build | Clippy + run: cargo clippy -- -D warnings + + - name: Build | Rustfmt + run: cargo fmt --all -- --check + + check: + runs-on: ubuntu-latest + steps: + - name: Setup | Checkout + uses: actions/checkout@v4 + + - name: Setup | Rust + uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + + - name: Rust Cache + uses: Swatinem/rust-cache@v2 + + - name: Build | Check (native) + run: cargo check + + - name: Build | Check (wasm) + run: cargo check --target wasm32-unknown-unknown + + test: + needs: [check] + runs-on: ubuntu-latest + steps: + - name: Setup | Checkout + uses: actions/checkout@v4 + + - name: Setup | Rust + uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + + - name: Setup | wasm-pack + uses: jetli/wasm-pack-action@v0.4.0 + + - name: Rust Cache + uses: Swatinem/rust-cache@v2 + + - name: Build | Test (native) + run: cargo test --all + + - name: Build | Test (wasm) + run: wasm-pack test --node \ No newline at end of file diff --git a/.github/workflows/web-demo.yml b/.github/workflows/web-demo.yml new file mode 100644 index 0000000..3b7d0a6 --- /dev/null +++ b/.github/workflows/web-demo.yml @@ -0,0 +1,67 @@ +name: Web Demo Update + +on: + push: + branches: + - main + +jobs: + release-web: + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: install stable toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + + - name: install wasm-bindgen + uses: jetli/wasm-bindgen-action@v0.2.0 + with: + version: 'latest' + + - name: build (wasm) + run: cargo build --example simple --release --target wasm32-unknown-unknown + + - name: package wasm + run: | + mkdir public + wasm-bindgen --target web --out-dir public target/wasm32-unknown-unknown/release/examples/simple.wasm --no-typescript + cat << EOF > public/index.html + + Replace HTML Demo + + + + + + + + + This application needs JavaScript and WebAssembly to run. + + + EOF + + - name: Setup Pages + uses: actions/configure-pages@v4 + + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: './public' + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9745a68 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + + + +## Unreleased + +## 0.1.0 + +- Initialize release diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..48aeead --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,217 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "bumpalo" +version = "3.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[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", + "wasm-bindgen", +] + +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "proc-macro2" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "replace_html" +version = "0.1.0" +dependencies = [ + "thiserror", + "wasm-bindgen-test", + "web-sys", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "syn" +version = "2.0.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + +[[package]] +name = "wasm-bindgen-test" +version = "0.3.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9bf62a58e0780af3e852044583deee40983e5886da43a271dd772379987667b" +dependencies = [ + "console_error_panic_hook", + "js-sys", + "scoped-tls", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f89739351a2e03cb94beb799d47fb2cac01759b40ec441f7de39b00cbf7ef0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "web-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +dependencies = [ + "js-sys", + "wasm-bindgen", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1eb95a4 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "replace_html" +description = "A simple, minimal crate to replace HTML in wasm32 environments." +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" +repository = "https://github.com/loopystudios/replace_html" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies] +thiserror = "1.0.58" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +web-sys = { version = "0.3", features = ['Window', 'Document', 'HtmlElement'] } + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +wasm-bindgen-test = "0.3.42" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..2bb9ad2 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + 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 \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..6802bc4 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +MIT License + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..0a20d0b --- /dev/null +++ b/README.md @@ -0,0 +1,66 @@ +
+ +# Replace HTML + +**A simple, minimal crate to replace HTML in wasm32 environments.** + +[![Discord](https://img.shields.io/discord/913957940560531456.svg?label=Loopy&logo=discord&logoColor=ffffff&color=ffffff&labelColor=000000)](https://discord.gg/zrjnQzdjCB) +[![MIT/Apache 2.0](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](#license) +[![Build status](https://github.com/loopystudios/replace_html/workflows/CI/badge.svg)](https://github.com/loopystudios/replace_html/actions) +[![dependency status](https://deps.rs/repo/github/loopystudios/replace_html/status.svg)](https://deps.rs/repo/github/loopystudios/replace_html) +[![Crates.io](https://img.shields.io/crates/v/replace_html.svg)](https://crates.io/crates/replace_html) +[![Docs](https://img.shields.io/docsrs/replace_html)](https://docs.rs/replace_html) + +
+ +Quickstart to run demo: + +- **Web** + +```shell +# Make sure the Rust toolchain supports the wasm32 target +rustup target add wasm32-unknown-unknown + +# Install `wasm-server-runner` for the example +cargo install wasm-server-runner + +cargo run --target wasm32-unknown-unknown --example simple +``` + +There is also a web demo [available here](https://loopystudios.github.io/replace_html). + +## Usage + +```rust +#[cfg(target_arch = "wasm32")] +fn main() { + replace_html::replace_by_id("body", "Your platform is not supported!").unwrap(); +} +#[cfg(not(target_arch = "wasm32"))] +fn main() { + // Proceed to run your application... +} +``` + +## Community + +All Loopy projects and development happens in the [Loopy Discord](https://discord.gg/zrjnQzdjCB). The discord is open to the public. + +Contributions are welcome by pull request. The [Rust code of conduct](https://www.rust-lang.org/policies/code-of-conduct) applies. + +## License + +Licensed under either of + +- Apache License, Version 2.0 + ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license + ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/examples/simple.rs b/examples/simple.rs new file mode 100644 index 0000000..f0f55df --- /dev/null +++ b/examples/simple.rs @@ -0,0 +1,16 @@ +fn main() { + let html = r#" + +

+ This was injected by Rust! +

+ "#; + + if let Err(e) = replace_html::replace_body(html) { + eprintln!("Failed to replace HTML: {e}"); + }; +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..988685b --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,6 @@ +max_width = 100 +# TODO: comment_width = 100 - Wait for this to be stable +# TODO: wrap_comments = true - Wait for this to be stable +use_field_init_shorthand = true +newline_style = "Unix" +# TODO: imports_granularity = "Crate" - Wait for this to be stable. diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..6b76284 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,9 @@ +#[derive(Debug, thiserror::Error, PartialEq, Eq, Clone)] +pub enum ReplaceHtmlError { + #[error("The element was not found: '{0}'")] + ElementNotFound(String), + #[error("HTML could not be replaced because the environment is headless.")] + HeadlessEnvironment, + #[error("Replacing HTML only works on `wasm32` architecture.")] + TargetNotSupported, +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..d2097c8 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,61 @@ +//! Easily replace HTML in wasm32 environments. +//! +//! # Usage +//! ```rust +//! #[cfg(target_arch = "wasm32")] +//! fn main() { +//! replace_html::replace_by_id("body", "Your platform is not supported!").unwrap(); +//! } +//! #[cfg(not(target_arch = "wasm32"))] +//! fn main() { +//! // Proceed to run your application... +//! } +//! ``` + +mod error; +pub use error::ReplaceHtmlError; + +/// Replace the inner HTML of the document body. +#[cfg(target_arch = "wasm32")] +pub fn replace_body(html: impl Into) -> Result<(), ReplaceHtmlError> { + let body = web_sys::window() + .and_then(|w| w.document()) + .and_then(|d| d.body()) + .ok_or(ReplaceHtmlError::HeadlessEnvironment)?; + body.set_inner_html(&html.into()); + Ok(()) +} + +/// Replace the inner HTML of an element by ID. +#[cfg(target_arch = "wasm32")] +pub fn replace_by_id( + id: impl Into, + html: impl Into, +) -> Result<(), ReplaceHtmlError> { + let id = id.into(); + let dom = web_sys::window() + .and_then(|w| w.document()) + .ok_or(ReplaceHtmlError::HeadlessEnvironment)?; + let element = dom + .get_element_by_id(&id) + .ok_or(ReplaceHtmlError::ElementNotFound(id))?; + element.set_inner_html(&html.into()); + Ok(()) +} + +/// Replace the inner HTML of an element by ID. +#[cfg(not(target_arch = "wasm32"))] +#[allow(unused_variables)] +pub fn replace_by_id( + id: impl Into, + html: impl Into, +) -> Result<(), ReplaceHtmlError> { + Err(ReplaceHtmlError::TargetNotSupported) +} + +/// Replace the inner HTML of the document body. +#[cfg(not(target_arch = "wasm32"))] +#[allow(unused_variables)] +pub fn replace_body(html: impl Into) -> Result<(), ReplaceHtmlError> { + Err(ReplaceHtmlError::TargetNotSupported) +} diff --git a/tests/tests.rs b/tests/tests.rs new file mode 100644 index 0000000..833d076 --- /dev/null +++ b/tests/tests.rs @@ -0,0 +1,29 @@ +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn replace_by_id_test() { + assert_eq!( + replace_html::ReplaceHtmlError::TargetNotSupported, + replace_html::replace_by_id("test", "").unwrap_err() + ); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn replace_body_test() { + assert_eq!( + replace_html::ReplaceHtmlError::TargetNotSupported, + replace_html::replace_body("").unwrap_err() + ); +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen_test::wasm_bindgen_test] +fn replace_by_id_test() { + _ = replace_html::replace_by_id("test", ""); +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen_test::wasm_bindgen_test] +fn replace_body_test() { + _ = replace_html::replace_body(""); +}