diff --git a/.cargo/config b/.cargo/config deleted file mode 100644 index bba9c7fbd5b..00000000000 --- a/.cargo/config +++ /dev/null @@ -1,2 +0,0 @@ -[target.'cfg(target_arch = "wasm32")'] -runner = 'wasm-bindgen-test-runner' diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000000..7b1b2f31b4d --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +[target.'cfg(target_arch = "wasm32")'] +runner = 'wasm-bindgen-test-runner' + +[unstable] +doctest-xcompile = true +# [unstable] must be the last section -- ci/write-optimisation-flags.sh relies on it diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 3d0e5b28789..5a30865634c 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -8,7 +8,6 @@ Fixes #0000 -- [ ] I have run `cargo make pr-flow` - [ ] I have reviewed my own code - [ ] I have added tests diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 871868f0e19..619cfd96e24 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,5 +10,5 @@ updates: - package-ecosystem: "npm" directory: "/website" schedule: - interval: "daily" + interval: "monthly" target-branch: "master" diff --git a/.github/workflows/auto-approve-maintainer-pr.yml b/.github/workflows/auto-approve-maintainer-pr.yml index 8fbf2f846fa..c5632210dd3 100644 --- a/.github/workflows/auto-approve-maintainer-pr.yml +++ b/.github/workflows/auto-approve-maintainer-pr.yml @@ -5,6 +5,7 @@ on: pull_request_target jobs: auto-approve: runs-on: ubuntu-latest + if: github.event.pull_request.draft == false steps: - name: Check if organization member id: is_organization_member @@ -16,6 +17,6 @@ jobs: - name: Auto approve uses: hmarr/auto-approve-action@v2 - if: ${{ steps.is_organization_member.outputs.result == 'true' || github.actor == 'dependabot' }} + if: ${{ steps.is_organization_member.outputs.result == 'true' || github.actor == 'dependabot[bot]' }} with: github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/main-checks.yml b/.github/workflows/main-checks.yml index 8794ef1bd3c..5c3833a5835 100644 --- a/.github/workflows/main-checks.yml +++ b/.github/workflows/main-checks.yml @@ -25,7 +25,7 @@ jobs: uses: actions-rs/cargo@v1 with: command: clippy - args: --all-targets -- -D warnings + args: --all-targets --all-features -- -D warnings - name: Lint feature soundness run: | @@ -51,12 +51,11 @@ jobs: - uses: Swatinem/rust-cache@v1 - - name: Run clippy uses: actions-rs/cargo@v1 with: command: clippy - args: --all-targets --release -- -D warnings + args: --all-targets --all-features --release -- -D warnings - name: Lint feature soundness run: | @@ -67,46 +66,60 @@ jobs: cargo clippy --release --all-features --all-targets -- --deny=warnings working-directory: packages/yew + spell_check: + name: spellcheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Check spelling + run: | + sudo apt-get install aspell + ci/spellcheck.sh list doc_tests: name: Documentation Tests runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: Swatinem/rust-cache@v1 + - uses: actions-rs/toolchain@v1 with: toolchain: stable - target: wasm32-unknown-unknown override: true profile: minimal - - uses: Swatinem/rust-cache@v1 + - name: Install wasm-bindgen-test-runner + run: cargo install --git https://github.com/hamza1311/wasm-bindgen --branch respect-rustdoc-tmp-paths wasm-bindgen-cli - - name: Check spelling - run: | - sudo apt-get install aspell - ci/spellcheck.sh list + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + target: wasm32-unknown-unknown + override: true + profile: minimal + + - uses: browser-actions/setup-geckodriver@latest + - uses: nanasess/setup-chromedriver@v1 - name: Run doctest uses: actions-rs/cargo@v1 with: command: test - args: --doc + args: --doc --workspace --exclude yew --exclude changelog --exclude website-test --exclude ssr_router --exclude simple_ssr --target wasm32-unknown-unknown - name: Run website code snippet tests uses: actions-rs/cargo@v1 with: command: test - args: -p website-test + args: -p website-test --target wasm32-unknown-unknown - name: Run doctest - yew with features uses: actions-rs/cargo@v1 with: command: test - args: --doc --features doc_test --features wasm_test - - + args: -p yew --doc --all-features --target wasm32-unknown-unknown integration_tests: name: Integration Tests on ${{ matrix.toolchain }} @@ -128,23 +141,31 @@ jobs: override: true profile: minimal - - uses: jetli/wasm-pack-action@v0.3.0 - with: - version: "latest" + - uses: browser-actions/setup-geckodriver@latest + - uses: nanasess/setup-chromedriver@v1 - uses: Swatinem/rust-cache@v1 + - name: Install wasm-bindgen-cli + shell: bash + run: | + if [ ! -f "Cargo.lock" ]; then + cargo fetch + fi + VERSION=`cargo pkgid --frozen wasm-bindgen | cut -d ":" -f 3` + cargo install --version $VERSION wasm-bindgen-cli - name: Run tests - yew run: | cd packages/yew - wasm-pack test --chrome --firefox --headless -- --features "wasm_test" + CHROMEDRIVER=$(which chromedriver) cargo test --features csr,hydration,ssr --target wasm32-unknown-unknown + GECKODRIVER=$(which geckodriver) cargo test --features csr,hydration,ssr --target wasm32-unknown-unknown - name: Run tests - yew-router run: | cd packages/yew-router - wasm-pack test --chrome --firefox --headless - + CHROMEDRIVER=$(which chromedriver) cargo test --target wasm32-unknown-unknown + GECKODRIVER=$(which geckodriver) cargo test --target wasm32-unknown-unknown unit_tests: name: Unit Tests on ${{ matrix.toolchain }} @@ -170,13 +191,17 @@ jobs: - uses: Swatinem/rust-cache@v1 - - name: Run tests + - name: Run native tests uses: actions-rs/cargo@v1 with: command: test - args: --all-targets --workspace --exclude yew --exclude website-test - + args: --all-targets --workspace --exclude yew --exclude website-test --exclude ssr_router --exclude simple_ssr + - name: Run native tests for yew + uses: actions-rs/cargo@v1 + with: + command: test + args: -p yew --features "csr,ssr,hydration,tokio" test-lints: name: Test lints on nightly @@ -192,7 +217,6 @@ jobs: - uses: Swatinem/rust-cache@v1 - - name: Run tests uses: actions-rs/cargo@v1 with: diff --git a/.github/workflows/post-size-cmp.yml b/.github/workflows/post-size-cmp.yml index 57abec4ad01..e1c08f7a2b5 100644 --- a/.github/workflows/post-size-cmp.yml +++ b/.github/workflows/post-size-cmp.yml @@ -13,6 +13,9 @@ jobs: runs-on: ubuntu-latest steps: + - name: Download Repository + uses: actions/checkout@v2 + - if: github.event.workflow_run.event == 'pull_request' name: Download Artifact uses: Legit-Labs/action-download-artifact@v2 @@ -24,52 +27,7 @@ jobs: path: "size-cmp-info/" - name: Make pull request comment - run: | - from typing import Dict, List, Optional - - import os - import json - - with open("size-cmp-info/.SIZE_CMP_INFO") as f: - content = json.loads(f.read()) - - joined_sizes = content["sizes"] - issue_number = content["issue_number"] - - lines: List[str] = [] - - lines.append("### Size Comparison") - lines.append("") - lines.append("| examples | master (KB) | pull request (KB) | diff |") - lines.append("| --- | --- | --- | --- | ") - - for (i, sizes) in joined_sizes: - (master_size, pr_size) = sizes - diff: Optional[int] = None - - if master_size is not None and pr_size is not None: - diff = pr_size - master_size - - master_size_str = "N/A" if master_size is None else ( - f"{master_size / 1024:.3f}" if master_size != 0 else "0" - ) - pr_size_str = "N/A" if pr_size is None else ( - f"{pr_size / 1024:.3f}" if pr_size != 0 else "0" - ) - diff_str = "N/A" if diff is None else ( - f"{diff / 1024:.3f}" if diff < 0 else ( - f"+{diff / 1024:.3f}" if diff > 0 else "0" - ) - ) - lines.append(f"| {i} | {master_size_str} | {pr_size_str} | {diff_str} |") - - output = "\n".join(lines) - - with open(os.environ["GITHUB_ENV"], "a+") as f: - f.write(f"YEW_EXAMPLE_SIZES={json.dumps(output)}\n") - f.write(f"PR_NUMBER={issue_number}\n") - - shell: python3 {0} + run: python3 ci/make_example_size_cmt.py - name: Post Comment uses: actions/github-script@v6 diff --git a/.github/workflows/publish-examples.yml b/.github/workflows/publish-examples.yml index 69168f5269b..3a466bd5f56 100644 --- a/.github/workflows/publish-examples.yml +++ b/.github/workflows/publish-examples.yml @@ -12,62 +12,29 @@ jobs: env: # leave empty for / PUBLIC_URL_PREFIX: "" + RUSTUP_TOOLCHAIN: nightly steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: nightly target: wasm32-unknown-unknown + components: rust-src override: true profile: minimal + - name: Write optimisation flags + run: ./ci/write-optimisation-flags.sh + - uses: Swatinem/rust-cache@v1 - uses: jetli/trunk-action@v0.1.0 with: - # Optional version of trunk to install(eg. 'v0.8.1', 'latest') version: 'latest' - - - name: Build examples - run: | - output="$(pwd)/dist" - mkdir "$output" - - for path in examples/*; do - if [[ ! -d $path ]]; then - continue - fi - - example=$(basename "$path") - - # multi_thread doesn't work yet. See . - if [[ "$example" == "agents" ]]; then - continue - fi - - # web_worker_fib does not compile with trunk. See . - if [[ "$example" == "web_worker_fib" ]]; then - continue - fi - - # ssr does not need trunk - if [[ "$example" == "simple_ssr" ]]; then - continue - fi - - echo "building: $example" - ( - cd "$path" - dist_dir="$output/$example" - - trunk build --release --dist "$dist_dir" --public-url "$PUBLIC_URL_PREFIX/$example" - ) - done - - + run: ./ci/build-examples.sh - name: Deploy to Firebase uses: siku2/action-hosting-deploy@v0 diff --git a/.github/workflows/size-cmp.yml b/.github/workflows/size-cmp.yml index 305908d5fc8..932208eb8d4 100644 --- a/.github/workflows/size-cmp.yml +++ b/.github/workflows/size-cmp.yml @@ -6,7 +6,7 @@ on: branches: [master] paths: - .github/workflows/size-cmp.yml - - ci/collect_sizes.py + - "ci/**" - "packages/**" - "examples/**" - "Cargo.toml" @@ -56,35 +56,11 @@ jobs: version: 'latest' - name: Write optimisation flags for master - run: | - cat >> .cargo/config << EOF - [unstable] - build-std = ["std", "panic_abort"] - build-std-features = ["panic_immediate_abort"] - EOF - cat >> Cargo.toml << EOF - [profile.release] - lto = true - codegen-units = 1 - panic = "abort" - opt-level = "z" - EOF + run: ./ci/write-optimisation-flags.sh working-directory: yew-master - name: Write optimisation flags for pull request - run: | - cat >> .cargo/config << EOF - [unstable] - build-std = ["std", "panic_abort"] - build-std-features = ["panic_immediate_abort"] - EOF - cat >> Cargo.toml << EOF - [profile.release] - lto = true - codegen-units = 1 - panic = "abort" - opt-level = "z" - EOF + run: ./ci/write-optimisation-flags.sh working-directory: current-pr - name: Build master examples diff --git a/Cargo.toml b/Cargo.toml index 346ad4d0f37..bc3ed7f88e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ members = [ "packages/yew-router-macro", # Examples - "examples/agents", "examples/boids", "examples/contexts", "examples/counter", @@ -40,9 +39,9 @@ members = [ "examples/immutable", # Tools - "tools/changelog", - "tools/process-benchmark-results", "tools/benchmark-struct", "tools/benchmark-hooks", + "tools/changelog", + "tools/process-benchmark-results", "tools/website-test", ] diff --git a/Makefile.toml b/Makefile.toml index 3ef9b4de2e4..b7132665198 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -1,104 +1,90 @@ ###################### # # public tasks: -# * pr-flow -# * lint -# * lint-release -# * tests +# * checks-flow +# * lint +# * lint-release +# * format +# * test-flow +# * test +# * doc-test +# * website-test # +# packages/yew also contains `clippy-feature-soundness` to ensure everything is fine # Run `cargo make --list-all-steps` for more details. # ###################### [config] min_version = "0.32.4" +skip_core_tasks = true default_to_workspace = false [env] CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true CARGO_MAKE_CLIPPY_ARGS = "-- --deny=warnings" +CARGO_MAKE_WORKSPACE_SKIP_MEMBERS = [ + "examples/*", + "tools/*", +] [config.modify_core_tasks] private = true namespace = "core" -[tasks.pr-flow] -toolchain = "stable" -category = "Checks" -description = "Lint and test" -run_task = { name = ["lint", "lint-release", "tests"], fork = true } +# checks [tasks.lint] category = "Checks" -description = "Check formatting and run Clippy" -toolchain = "nightly" -run_task = { name = ["lint-flow"], fork = true } - -[tasks.tests] -category = "Testing" -description = "Run all tests" -dependencies = ["tests-setup"] -env = { CARGO_MAKE_WORKSPACE_SKIP_MEMBERS = ["**/examples/*", "**/packages/changelog"] } -run_task = { name = ["test-flow", "doc-test-flow", "ssr-test", "website-test"], fork = true } - -[tasks.lint-flow] -private = true -workspace = true -dependencies = ["core::check-format-flow", "core::clippy-flow"] +description = "Runs clippy" +command = "cargo" +args = ["clippy", "--", "--deny=warnings"] # Needed, because we have some code differences between debug and release builds [tasks.lint-release] category = "Checks" -workspace = true command = "cargo" args = ["clippy", "--all-targets", "--release", "--", "--deny=warnings"] -[tasks.tests-setup] -private = true -script_runner = "@duckscript" -script = [ - """ - test_flags = array --headless --firefox - yew_test_features = set wasm_test - - yew_test_flags = array_join ${test_flags} " " - echo "running tests with flags: ${yew_test_flags} and features: ${yew_test_features}" - - set_env YEW_TEST_FLAGS ${yew_test_flags} - set_env YEW_TEST_FEATURES ${yew_test_features} - """, -] +[tasks.format] +category = "Checks" +toolchain = "nightly" +env = { CARGO_MAKE_RUST_CHANNEL = "nightly" } -[tasks.test-flow] -private = true -workspace = true -dependencies = ["test"] + +[tasks.checks-flow] +category = "Checks" +description = "Runs clippy in debug and release mode and format all the code" +run_task = { name = ["lint", "lint-release", "format"], fork = true } + +# Tests [tasks.test] -private = true command = "cargo" args = ["test", "--all-targets"] - -[tasks.doc-test-flow] -private = true workspace = true -dependencies = ["doc-test"] [tasks.doc-test] -private = true command = "cargo" -args = ["test", "--doc"] +args = ["test", "--doc", "--all-features"] +workspace = true [tasks.website-test] command = "cargo" args = ["test", "-p", "website-test"] +[tasks.test-flow] +category = "Testing" +description = "Run all tests" +run_task = { name = ["test", "doc-test", "website-test"], fork = true, parallel = true } + +# misc + [tasks.generate-change-log] category = "Maintainer processes" toolchain = "stable" command = "cargo" -args = ["run","-p","changelog", "--release", "${@}"] +args = ["run", "-p", "changelog", "--release", "${@}"] -[tasks.ssr-test] -env = { CARGO_MAKE_WORKSPACE_INCLUDE_MEMBERS = ["**/packages/yew"] } -private = true -workspace = true +[tasks.default] +#run_task = { name = ["checks-flow", "test-flow"], fork = true } +dependencies = ["checks-flow", "test-flow"] diff --git a/ci/build-examples.sh b/ci/build-examples.sh new file mode 100755 index 00000000000..072d88ffeca --- /dev/null +++ b/ci/build-examples.sh @@ -0,0 +1,48 @@ +# Must be run from root of the repo: +# yew $ ./ci/build-examples.sh + +output="$(pwd)/dist" +mkdir -p "$output" + +failure=false +for path in examples/*; do + if [[ ! -d $path ]]; then + continue + fi + + example=$(basename "$path") + + # ssr does not need trunk + if [[ "$example" == "simple_ssr" || "$example" == "ssr_router" ]]; then + continue + fi + + echo "::group::Building $example" + if ! ( + set -e + # we are sure that $path exists + # shellcheck disable=SC2164 + cd "$path" + dist_dir="$output/$example" + if [[ "$example" == "boids" || "$example" == "password_strength" ]]; then + # works around issue rust-lang/rust#96486 + # where the compiler forgets to link some symbols connected to const_eval + # only an issue on nightly and with build-std enabled which we do for code size + # this deoptimizes only the examples that otherwise fail to build + export RUSTFLAGS="-Zshare-generics=n -Clto=thin" + fi + + trunk build --release --dist "$dist_dir" --public-url "$PUBLIC_URL_PREFIX$example" + + # check that there are no undefined symbols. Those generate an import .. from 'env', + # which isn't available in the browser. + { cat "$dist_dir"/*.js | grep -q -e "from 'env'" ; } && exit 1 || true + ) ; then + echo "::error ::$example failed to build" + failure=true + fi + echo "::endgroup::" +done +if [ "$failure" = true ] ; then + exit 1 +fi diff --git a/ci/collect_sizes.py b/ci/collect_sizes.py index 66a5126ce9d..71688b5b9a6 100644 --- a/ci/collect_sizes.py +++ b/ci/collect_sizes.py @@ -1,40 +1,52 @@ from typing import Dict, List, Optional +from pathlib import Path import glob import os import json -def find_example_sizes(parent_dir: str) -> Dict[str, int]: + +def find_example_sizes(parent_dir: Path) -> Dict[str, int]: example_sizes: Dict[str, int] = {} - for example_dir in os.listdir(f"{parent_dir}/examples"): - path = f"{parent_dir}/examples/{example_dir}" + for example_dir in (parent_dir / "examples").iterdir(): - if not os.path.isdir(path): + if not example_dir.is_dir(): + print(f"{example_dir} is not a directory.") continue - matches = glob.glob(f"{parent_dir}/examples/{example_dir}/dist/index*.wasm") + total_size = 0 - if not matches: - continue + # For examples with multiple bundles, we add them together. + for bundle in (example_dir / "dist").glob(f"*.wasm"): + size = bundle.stat().st_size + + print(f"{bundle} has a size of {size}.") - path = matches[0] + total_size += size - example_sizes[example_dir] = os.path.getsize(path) + if total_size > 0: + example_sizes[example_dir.name] = total_size return example_sizes -master_sizes = find_example_sizes("yew-master") -pr_sizes = find_example_sizes("current-pr") -example_names = sorted(set([*master_sizes.keys(), *pr_sizes.keys()])) +def main() -> None: + master_sizes = find_example_sizes(Path("yew-master")) + pr_sizes = find_example_sizes(Path("current-pr")) + + example_names = sorted(set([*master_sizes.keys(), *pr_sizes.keys()])) + + joined_sizes = [(i, [master_sizes.get(i), pr_sizes.get(i)]) for i in example_names] + + size_cmp_info = { + "sizes": joined_sizes, + "issue_number": os.environ["ISSUE_NUMBER"], + } -joined_sizes = [(i, [master_sizes.get(i), pr_sizes.get(i)]) for i in example_names] + with open(".SIZE_CMP_INFO", "w+") as f: + f.write(json.dumps(size_cmp_info, indent=4)) -size_cmp_info = { - "sizes": joined_sizes, - "issue_number": os.environ["ISSUE_NUMBER"], -} -with open(".SIZE_CMP_INFO", "w+") as f: - f.write(json.dumps(size_cmp_info)) +if __name__ == "__main__": + main() diff --git a/ci/make_example_size_cmt.py b/ci/make_example_size_cmt.py new file mode 100644 index 00000000000..7be01aed28f --- /dev/null +++ b/ci/make_example_size_cmt.py @@ -0,0 +1,103 @@ +from typing import Dict, List, Optional, Tuple + +import os +import json + + +header = "| examples | master (KB) | pull request (KB) | diff (KB) | diff (%) |" +sep = "| --- | --- | --- | --- | --- |" + + +def format_size(size: Optional[int]) -> str: + if size is None: + return "N/A" + + if size == 0: + return "0" + + return f"{size / 1024:.3f}" + + +def format_diff_size( + master_size: Optional[int], pr_size: Optional[int] +) -> Tuple[str, str, bool]: + if master_size is None or pr_size is None: + return ("N/A", "N/A", False) + + diff = pr_size - master_size + + if diff == 0: + return ("0", "0.000%", False) + + diff_percent = diff / master_size + + return (f"{diff / 1024:+.3f}", f"{diff_percent:+.3%}", abs(diff_percent) >= 0.01) + + +def main() -> None: + with open("size-cmp-info/.SIZE_CMP_INFO") as f: + content = json.loads(f.read()) + + joined_sizes = content["sizes"] + issue_number = content["issue_number"] + + lines: List[str] = [] + significant_lines: List[str] = [] + + lines.append("### Size Comparison") + lines.append("") + lines.append("
") + lines.append("") + lines.append(header) + lines.append(sep) + + for (i, sizes) in joined_sizes: + (master_size, pr_size) = sizes + + master_size_str = format_size(master_size) + pr_size_str = format_size(pr_size) + + (diff_str, diff_percent, diff_significant) = format_diff_size( + master_size, pr_size + ) + + line_str = ( + f"| {i} | {master_size_str} | {pr_size_str} | " + f"{diff_str} | {diff_percent} |" + ) + + lines.append(line_str) + + if diff_significant: + significant_lines.append(line_str) + + lines.append("") + lines.append("
") + lines.append("") + + if significant_lines: + + if len(significant_lines) == 1: + lines.append("⚠️ The following example has changed its size significantly:") + else: + lines.append( + "⚠️ The following examples have changed their size significantly:" + ) + lines.append("") + + lines.append(header) + lines.append(sep) + lines.extend(significant_lines) + + else: + lines.append("✅ None of the examples has changed their size significantly.") + + output = "\n".join(lines) + + with open(os.environ["GITHUB_ENV"], "a+") as f: + f.write(f"YEW_EXAMPLE_SIZES={json.dumps(output)}\n") + f.write(f"PR_NUMBER={issue_number}\n") + + +if __name__ == "__main__": + main() diff --git a/ci/write-optimisation-flags.sh b/ci/write-optimisation-flags.sh new file mode 100755 index 00000000000..678180bbe87 --- /dev/null +++ b/ci/write-optimisation-flags.sh @@ -0,0 +1,15 @@ +# Must be run from root of the repo: +# yew $ ./ci/write-optimisation-flags.sh + +# this goes in [unstable] section +cat >> .cargo/config.toml << EOF +build-std = ["std", "panic_abort"] +build-std-features = ["panic_immediate_abort"] +EOF +cat >> Cargo.toml << EOF +[profile.release] +lto = true +codegen-units = 1 +panic = "abort" +opt-level = "z" +EOF diff --git a/examples/README.md b/examples/README.md index 096ad80a0c9..968613ea3fa 100644 --- a/examples/README.md +++ b/examples/README.md @@ -29,7 +29,6 @@ As an example, check out the TodoMVC example here: ` support | -| [function_memory_game](function_memory_game) | F | Implementation of [Memory Game](https://github.com/bradlygreen/Memory-Game) | +| [suspense](suspense) | F | This is an example that demonstrates `` support | +| [function_memory_game](function_memory_game) | F | Implementation of [Memory Game](https://github.com/bradlygreen/Memory-Game) | | [timer](timer) | S | Demonstrates the use of the interval and timeout services | | [todomvc](todomvc) | S | Implementation of [TodoMVC](http://todomvc.com/) | | [two_apps](two_apps) | S | Runs two separate Yew apps which can communicate with each other | -| [web_worker_fib](web_worker_fib) | S | Calculate fibonacci value of a number in a web worker thread | +| [web_worker_fib](web_worker_fib) | S | Calculate fibonacci value of a number in a web worker thread using `gloo-worker` | | [webgl](webgl) | S | Controls a [WebGL canvas](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL) from Yew | ## Next steps diff --git a/examples/agents/Cargo.toml b/examples/agents/Cargo.toml deleted file mode 100644 index 168054447d2..00000000000 --- a/examples/agents/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "agents" -version = "0.1.0" -authors = ["Denis Kolodin "] -edition = "2021" -license = "MIT OR Apache-2.0" - -[dependencies] -log = "0.4" -serde = { version = "1.0", features = ["derive"] } -wasm-logger = "0.2" -yew = { path = "../../packages/yew", features = ["csr"] } -yew-agent = { path = "../../packages/yew-agent" } -gloo-timers = "0.2" diff --git a/examples/agents/README.md b/examples/agents/README.md deleted file mode 100644 index 5af88b9950d..00000000000 --- a/examples/agents/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Warning - -The agents example is a conceptual WIP and is currently blocked on [a future Trunk feature](https://github.com/thedodd/trunk/issues/46) - -There is an alternate agent example [here](https://github.com/yewstack/yew/tree/master/examples/web_worker_fib). - - -# Multi-Thread Example - -[![Demo](https://img.shields.io/website?label=demo&url=https%3A%2F%2Fexamples.yew.rs%2Fagents)](https://examples.yew.rs/agents) - - -## Concepts - -Uses an [Agent] that runs in a [Web Worker]. - -[agent]: https://yew.rs/docs/concepts/agents/ -[web worker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers diff --git a/examples/agents/index.html b/examples/agents/index.html deleted file mode 100644 index 6b929440c77..00000000000 --- a/examples/agents/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Yew • Multi-Thread - - - - - - - diff --git a/examples/agents/src/bin/app.rs b/examples/agents/src/bin/app.rs deleted file mode 100644 index 1d6a6ef9518..00000000000 --- a/examples/agents/src/bin/app.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - wasm_logger::init(wasm_logger::Config::default()); - yew::Renderer::::new().render(); -} diff --git a/examples/agents/src/bin/worker.rs b/examples/agents/src/bin/worker.rs deleted file mode 100644 index c7b2940504b..00000000000 --- a/examples/agents/src/bin/worker.rs +++ /dev/null @@ -1,7 +0,0 @@ -use agents::native_worker::Worker; -use yew_agent::PublicWorker; - -fn main() { - wasm_logger::init(wasm_logger::Config::default()); - Worker::register(); -} diff --git a/examples/agents/src/lib.rs b/examples/agents/src/lib.rs deleted file mode 100644 index e6e04410cd8..00000000000 --- a/examples/agents/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -pub mod native_worker; - -use std::rc::Rc; - -use yew::{html, Component, Context, Html}; -use yew_agent::{Bridge, Bridged}; - -pub enum Msg { - SendToWorker, - DataReceived, -} - -pub struct App { - worker: Box>, -} - -impl Component for App { - type Message = Msg; - type Properties = (); - - fn create(ctx: &Context) -> Self { - let link = ctx.link().clone(); - let callback = move |_| link.send_message(Msg::DataReceived); - let worker = native_worker::Worker::bridge(Rc::new(callback)); - - Self { worker } - } - - fn update(&mut self, _ctx: &Context, msg: Self::Message) -> bool { - match msg { - Msg::SendToWorker => { - self.worker.send(native_worker::Request::GetDataFromServer); - false - } - Msg::DataReceived => { - log::info!("DataReceived"); - false - } - } - } - - fn view(&self, ctx: &Context) -> Html { - html! { -
- -
- } - } -} diff --git a/examples/agents/src/native_worker.rs b/examples/agents/src/native_worker.rs deleted file mode 100644 index b121fdee617..00000000000 --- a/examples/agents/src/native_worker.rs +++ /dev/null @@ -1,64 +0,0 @@ -use gloo_timers::callback::Interval; -use serde::{Deserialize, Serialize}; -use yew_agent::{HandlerId, Public, WorkerLink}; - -#[derive(Serialize, Deserialize, Debug)] -pub enum Request { - GetDataFromServer, -} - -#[derive(Serialize, Deserialize, Debug)] -pub enum Response { - DataFetched, -} - -pub enum Msg { - Updating, -} - -pub struct Worker { - link: WorkerLink, - _interval: Interval, -} - -impl yew_agent::Worker for Worker { - type Input = Request; - type Message = Msg; - type Output = Response; - type Reach = Public; - - fn create(link: WorkerLink) -> Self { - let duration = 3; - - let interval = { - let link = link.clone(); - Interval::new(duration, move || link.send_message(Msg::Updating)) - }; - Self { - link, - _interval: interval, - } - } - - fn update(&mut self, msg: Self::Message) { - match msg { - Msg::Updating => { - log::info!("Tick..."); - } - } - } - - fn handle_input(&mut self, msg: Self::Input, who: HandlerId) { - log::info!("Request: {:?}", msg); - match msg { - Request::GetDataFromServer => { - // TODO fetch actual data - self.link.respond(who, Response::DataFetched); - } - } - } - - fn name_of_resource() -> &'static str { - "worker.js" - } -} diff --git a/examples/boids/src/slider.rs b/examples/boids/src/slider.rs index b1bb59a37c6..f9f09bb7609 100644 --- a/examples/boids/src/slider.rs +++ b/examples/boids/src/slider.rs @@ -79,6 +79,7 @@ impl Component for Slider {
Html { +#[function_component] +fn App() -> Html { let state = use_state(|| 0); let incr_counter = { diff --git a/examples/function_router/Cargo.toml b/examples/function_router/Cargo.toml index 9bc73d082da..313d21a7a37 100644 --- a/examples/function_router/Cargo.toml +++ b/examples/function_router/Cargo.toml @@ -19,5 +19,6 @@ instant = { version = "0.1", features = ["wasm-bindgen"] } [target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = { version = "0.2", features = ["js"] } -[features] -csr = ["yew/csr"] +[[bin]] +name = "function_router" +required-features = ["yew/csr"] diff --git a/examples/function_router/index.html b/examples/function_router/index.html index 2a75b730809..94d1b1d121c 100644 --- a/examples/function_router/index.html +++ b/examples/function_router/index.html @@ -11,7 +11,7 @@ href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css" /> - + diff --git a/examples/function_router/src/app.rs b/examples/function_router/src/app.rs index 0195eaac9ba..6f2140e5e77 100644 --- a/examples/function_router/src/app.rs +++ b/examples/function_router/src/app.rs @@ -37,7 +37,7 @@ pub fn App() -> Html {