diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a620e82cbb..5cbae59c5fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,58 @@ # Changelog +## ✹ yew **0.22.0** *(2024-10-14)* + +#### Changelog + +## 🛠 Fixes + + - Fix: Hydratation of empty lists next to components.. [[@WorldSEnder](https://github.com/WorldSEnder), [#3630](https://github.com/yewstack/yew/pull/3630)] +silenced non-normalised element name warnings for SVG elements [@Tim Kurdov](https://github.com/its-the-shrimp), [#3769](https://github.com/yewstack/yew/pull/3769)] + +## ⚡ Features + + - Raise MSRV to 1.76. [[@Elina](https://github.com/ranile), [#3693](https://github.com/yewstack/yew/pull/3693)] + - Add `inert` to the boolean attributes list. [[@Tomoaki Kawada](https://github.com/kawadakk), [#3678](https://github.com/yewstack/yew/pull/3678)] + - Namespace support for `VRaw`.. [[@Finn Bear](https://github.com/finnbear), [#3640](https://github.com/yewstack/yew/pull/3640)] + - Add generic type hints to boxed hooks. [[@Michael Meyer](https://github.com/Ichmed), [#3633](https://github.com/yewstack/yew/pull/3633)] + - add the methods and From impls. [[@Tim Kurdov](https://github.com/its-the-shrimp), [#3519](https://github.com/yewstack/yew/pull/3519)] + - Add IntoPropValue impl for converting to VList. [[@Muhammad Hamza](https://github.com/ranile), [#3444](https://github.com/yewstack/yew/pull/3444)] + - Add CallbackRef that takes ref in argument instead of value. [[@Cecile Tonglet](https://github.com/cecton), [#3419](https://github.com/yewstack/yew/pull/3419)] + - Remove the dependency on `boolinator`. [[@Tim Kurdov](https://github.com/its-the-shrimp), [#3420](https://github.com/yewstack/yew/pull/3420)] + - Allow import of layout_test into 3rd party crates. [[@rollo-b2c2](https://github.com/rollo-b2c2), [#3463](https://github.com/yewstack/yew/pull/3463)] + - Add WASI support for server-side rendering. [[@langyo](https://github.com/langyo), [#3534](https://github.com/yewstack/yew/pull/3534)] + +## 🚚 Breaking changes + + - Add use_ref. [[@Alex Parrill](https://github.com/ColonelThirtyTwo), [#3548](https://github.com/yewstack/yew/pull/3548)] + - Allow setting JsValue as properties. [[@Elina](https://github.com/ranile), [#3458](https://github.com/yewstack/yew/pull/3458)] + - Remove deprecated `class=(...)` syntax. [[@Tim Kurdov](https://github.com/its-the-shrimp), [#3497](https://github.com/yewstack/yew/pull/3497)] + - Remove ToHtml trait. [[@Elina](https://github.com/ranile), [#3453](https://github.com/yewstack/yew/pull/3453)] + - Make Html (VNode) cheap to clone. [[@Cecile Tonglet](https://github.com/cecton), [#3431](https://github.com/yewstack/yew/pull/3431)] + +## ✹ yew-router **0.19.0** *(2024-10-14)* + +#### Changelog + +## 🛠 Fixes + + - Fix CI. [[@Tomoaki Kawada](https://github.com/kawadakk), [#3679](https://github.com/yewstack/yew/pull/3679)] + +## ⚡ Features + + - Raise MSRV to 1.76. [[@Elina](https://github.com/ranile), [#3693](https://github.com/yewstack/yew/pull/3693)] + +## ✹ yew-agent **0.4.0** *(2024-10-14)* + +#### Changelog + +## ⚡ Features + + - Raise MSRV to 1.76. [[@Elina](https://github.com/ranile), [#3693](https://github.com/yewstack/yew/pull/3693)] + - Agent: Avoiding clone of WorkerBridge and WorkerProviderState. [[@Shihpin Tseng](https://github.com/deftsp), [#3435](https://github.com/yewstack/yew/pull/3435)] + +---- + ## ✹ yew **0.21.0** *(2023-09-23)* #### Changelog diff --git a/examples/wasi_ssr_module/README.md b/examples/wasi_ssr_module/README.md index 51fbceeb009..a92ac98576f 100644 --- a/examples/wasi_ssr_module/README.md +++ b/examples/wasi_ssr_module/README.md @@ -9,7 +9,7 @@ It depends on [wasmtime](https://wasmtime.dev)'s WASI preview2. To build the example, run the following command from the root of the repository: ```bash -cargo build --manifest-path examples/wasi_ssr_module/Cargo.toml --target wasm32-wasi --release +cargo build --manifest-path examples/wasi_ssr_module/Cargo.toml --target wasm32-wasip1 --release ``` ## Running @@ -17,7 +17,7 @@ cargo build --manifest-path examples/wasi_ssr_module/Cargo.toml --target wasm32- > Note: This example requires the wasmtime CLI to be installed. See [wasmtime's installation instructions](https://docs.wasmtime.dev/cli-install.html) for more information. ```bash -wasmtime target/wasm32-wasi/release/wasi_ssr_module.wasm +wasmtime target/wasm32-wasip1/release/wasi_ssr_module.wasm ``` > Note: If your wasmtime CLI throws an error that it says some imports like `__wbindgen_placeholder__::__wbindgen_xxx` is invalid, try to run `cargo update`. See issue [rustwasm/gloo#411](https://github.com/rustwasm/gloo/pull/411#discussion_r1421219033). diff --git a/tools/benchmark-hooks/package-lock.json b/tools/benchmark-hooks/package-lock.json index 4699b4eb70d..f42488b2116 100644 --- a/tools/benchmark-hooks/package-lock.json +++ b/tools/benchmark-hooks/package-lock.json @@ -1,13 +1,16 @@ { - "name": "js-framework-benchmark-non-keyed-yew-hooks", + "name": "js-framework-benchmark-keyed-yew-hooks", "version": "1.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "js-framework-benchmark-non-keyed-yew-hooks", + "name": "js-framework-benchmark-keyed-yew-hooks", "version": "1.0.0", "license": "ISC", + "dependencies": { + "js-framework-benchmark-keyed-yew-hooks": "file:" + }, "devDependencies": { "cpr": "^3.0.1", "rimraf": "^2.6.3" @@ -98,6 +101,10 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "node_modules/js-framework-benchmark-keyed-yew-hooks": { + "resolved": "", + "link": true + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -242,6 +249,146 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "js-framework-benchmark-keyed-yew-hooks": { + "version": "file:", + "requires": { + "cpr": "^3.0.1", + "js-framework-benchmark-keyed-yew-hooks": "file:", + "rimraf": "^2.6.3" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "cpr": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/cpr/-/cpr-3.0.1.tgz", + "integrity": "sha512-Xch4PXQ/KC8lJ+KfJ9JI6eG/nmppLrPPWg5Q+vh65Qr9EjuJEubxh/H/Le1TmCZ7+Xv7iJuNRqapyOFZB+wsxA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.5", + "minimist": "^1.2.0", + "mkdirp": "~0.5.1", + "rimraf": "^2.5.4" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "requires": { + "minimist": "^1.2.6" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + } + } + }, "minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", diff --git a/tools/benchmark-hooks/package.json b/tools/benchmark-hooks/package.json index 14ba90be5ef..be71ad962dd 100644 --- a/tools/benchmark-hooks/package.json +++ b/tools/benchmark-hooks/package.json @@ -20,7 +20,10 @@ "url": "https://github.com/krausest/js-framework-benchmark.git" }, "devDependencies": { - "rimraf": "^2.6.3", - "cpr": "^3.0.1" + "cpr": "^3.0.1", + "rimraf": "^2.6.3" + }, + "dependencies": { + "js-framework-benchmark-keyed-yew-hooks": "file:" } } diff --git a/tools/benchmark-struct/package-lock.json b/tools/benchmark-struct/package-lock.json index ad757df6b12..5943ccfff2f 100644 --- a/tools/benchmark-struct/package-lock.json +++ b/tools/benchmark-struct/package-lock.json @@ -1,13 +1,16 @@ { - "name": "js-framework-benchmark-non-keyed-yew", + "name": "js-framework-benchmark-keyed-yew", "version": "1.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "js-framework-benchmark-non-keyed-yew", + "name": "js-framework-benchmark-keyed-yew", "version": "1.0.0", "license": "ISC", + "dependencies": { + "js-framework-benchmark-keyed-yew": "file:" + }, "devDependencies": { "cpr": "^3.0.1", "rimraf": "^2.6.3" @@ -98,6 +101,10 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "node_modules/js-framework-benchmark-keyed-yew": { + "resolved": "", + "link": true + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -242,6 +249,146 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "js-framework-benchmark-keyed-yew": { + "version": "file:", + "requires": { + "cpr": "^3.0.1", + "js-framework-benchmark-keyed-yew": "file:", + "rimraf": "^2.6.3" + }, + "dependencies": { + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "cpr": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/cpr/-/cpr-3.0.1.tgz", + "integrity": "sha512-Xch4PXQ/KC8lJ+KfJ9JI6eG/nmppLrPPWg5Q+vh65Qr9EjuJEubxh/H/Le1TmCZ7+Xv7iJuNRqapyOFZB+wsxA==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.5", + "minimist": "^1.2.0", + "mkdirp": "~0.5.1", + "rimraf": "^2.5.4" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, + "glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "requires": { + "minimist": "^1.2.6" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + } + } + }, "minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", diff --git a/tools/benchmark-struct/package.json b/tools/benchmark-struct/package.json index db741af2e88..007c520e29a 100644 --- a/tools/benchmark-struct/package.json +++ b/tools/benchmark-struct/package.json @@ -20,7 +20,10 @@ "url": "https://github.com/krausest/js-framework-benchmark.git" }, "devDependencies": { - "rimraf": "^2.6.3", - "cpr": "^3.0.1" + "cpr": "^3.0.1", + "rimraf": "^2.6.3" + }, + "dependencies": { + "js-framework-benchmark-keyed-yew": "file:" } } diff --git a/website/blog/2024-10-14-release-0-22.md b/website/blog/2024-10-14-release-0-22.md new file mode 100644 index 00000000000..bb14617394e --- /dev/null +++ b/website/blog/2024-10-14-release-0-22.md @@ -0,0 +1,40 @@ +--- +title: Announcing Yew 0.22 +authors: [langyo] +--- + + + +## What's new + +### SSR on WASI + +Before Yew 0.22, server-side rendering (SSR) was only possible on the native target. With Yew 0.22, you can now render your Yew application on the WebAssembly System Interface (WASI) target. + +Since the old SSR implementation will create new tasks directly in the asynchronous context directly (based on `prokio`). It only allowed in a multi-threaded environment that it is not compatible with WASI. So the new version added a dedicated one for a single-threaded environment that rendering function to support single-threaded scenes. + +Learn more at [Server-side rendering example on WASI environment](https://github.com/yewstack/yew/tree/master/examples/wasi_ssr_module/src/main.rs) + +## Call for Contributors + +The Yew project thrives on community involvement, and we welcome contributors with open arms. Whether you're an experienced Rust developer or just starting your journey, there are plenty of ways to get involved and make a meaningful impact on Yew's growth. + +Here are some areas where you can contribute: + +- **Code Contributions:** If you're passionate about web development with Rust, consider contributing code to Yew. Whether it's fixing bugs, adding new features, or improving documentation, your code can help make Yew even better. + +- **Documentation:** Clear and comprehensive documentation is vital for any project's success. You can contribute by improving documentation, writing tutorials, or creating examples that help others understand and use Yew effectively. + +- **Testing and Bug Reporting:** Testing Yew and reporting bugs you encounter is a valuable contribution. Your feedback helps us identify and fix issues, ensuring a more stable framework for everyone. + +- **Community Support:** Join discussions, chat rooms (we have our own Discord and Matrix!), or social media to assist other developers using Yew. Sharing your knowledge and helping others solve problems is a fantastic way to contribute. + +Contributing to open-source projects like Yew is not only a way to give back to the community but also an excellent opportunity to learn, collaborate, and enhance your skills. + +To get started, check out the Yew GitHub repository and the contribution guidelines. Your contributions are highly appreciated and play a crucial role in shaping the future of Yew. Join us in this exciting journey! + +## Thanks! + +Many people came together to create Yew 0.22. We couldn't have done it without all of you. Thanks! + +See [the full changelog](https://github.com/yewstack/yew/blob/master/CHANGELOG.md) diff --git a/website/blog/authors.yml b/website/blog/authors.yml index bf967286a55..0843c3eaf55 100644 --- a/website/blog/authors.yml +++ b/website/blog/authors.yml @@ -1,5 +1,11 @@ hamza: name: Muhammad Hamza title: Maintainer of Yew - url: https://github.com/hamza1311 - image_url: https://github.com/hamza1311.png + url: https://github.com/ranile + image_url: https://github.com/ranile.png + +langyo: + name: langyo + title: Contributor of Yew + url: https://github.com/langyo + image_url: https://github.com/langyo.png diff --git a/website/docs/advanced-topics/optimizations.mdx b/website/docs/advanced-topics/optimizations.mdx index 9aef595c93b..8252b9e229e 100644 --- a/website/docs/advanced-topics/optimizations.mdx +++ b/website/docs/advanced-topics/optimizations.mdx @@ -155,7 +155,7 @@ Note: `wasm-pack` combines optimization for Rust and Wasm code. `wasm-bindgen` i | wasm-bindgen + wasm-opt -Os | 116KB | | wasm-pack | 99 KB | -## Further reading: +## Further reading - [The Rust Book's chapter on smart pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) - [Information from the Rust Wasm Book about reducing binary sizes](https://rustwasm.github.io/book/reference/code-size.html#optimizing-builds-for-code-size) diff --git a/website/docs/advanced-topics/server-side-rendering.md b/website/docs/advanced-topics/server-side-rendering.mdx similarity index 99% rename from website/docs/advanced-topics/server-side-rendering.md rename to website/docs/advanced-topics/server-side-rendering.mdx index c68c3b362f4..0458fe4472c 100644 --- a/website/docs/advanced-topics/server-side-rendering.md +++ b/website/docs/advanced-topics/server-side-rendering.mdx @@ -186,8 +186,7 @@ fn App() -> Html { fn main() { let renderer = Renderer::::new(); - // hydrates everything under body element, removes trailing - // elements (if any). + // 盎接圚 body 元玠䞋泚氎并移陀可胜有的任䜕尟随元玠。 renderer.hydrate(); } ``` diff --git a/website/docs/concepts/agents.mdx b/website/docs/concepts/agents.mdx index dc35203fa43..2b59ee47bcb 100644 --- a/website/docs/concepts/agents.mdx +++ b/website/docs/concepts/agents.mdx @@ -55,7 +55,7 @@ A dispatcher allows uni-directional communication between a component and an age ## Overhead Agents use web workers \(i.e. Private and Public\). They incur a serialization overhead on the -messages they send and receive. Agents use [bincode](https://github.com/servo/bincode) to communicate +messages they send and receive. Agents use [bincode](https://github.com/bincode-org/bincode) to communicate with other threads, so the cost is substantially higher than just calling a function. ## Further reading diff --git a/website/docs/concepts/basic-web-technologies/css.mdx b/website/docs/concepts/basic-web-technologies/css.mdx index 49eafe971a2..94d30038d36 100644 --- a/website/docs/concepts/basic-web-technologies/css.mdx +++ b/website/docs/concepts/basic-web-technologies/css.mdx @@ -10,7 +10,7 @@ import TabItem from '@theme/TabItem' Yew does not natively provide a CSS-in-Rust solution but helps with styling by providing programmatic ways to interact with the HTML `class` attribute. -## Classes +## `classes!` macro The `classes!` macro and associated `Classes` struct simplify the use of HTML classes: @@ -87,7 +87,7 @@ We will expand upon this concept in [more CSS](../../more/css). ## Inline Styles -Currently Yew does not provide any special help with inline styles specified via the `styles` attribute, +Currently Yew does not provide any special help with inline styles specified via the `style` attribute, but you can use it like any other HTML attribute: ```rust diff --git a/website/docs/concepts/basic-web-technologies/html.mdx b/website/docs/concepts/basic-web-technologies/html.mdx index a2070935ec7..cf3ed1b896b 100644 --- a/website/docs/concepts/basic-web-technologies/html.mdx +++ b/website/docs/concepts/basic-web-technologies/html.mdx @@ -1,6 +1,6 @@ --- title: 'HTML with html!' -description: 'Its HTML but not quite!' +description: 'It is HTML but not quite!' comment: 'Keep this file as short and simple as possible. Its purpose is to ease the reader into components in Yew instead of providing proper API docs' --- diff --git a/website/docs/concepts/basic-web-technologies/wasm-bindgen.mdx b/website/docs/concepts/basic-web-technologies/wasm-bindgen.mdx index e34c895ca8c..0fb431b17ff 100644 --- a/website/docs/concepts/basic-web-technologies/wasm-bindgen.mdx +++ b/website/docs/concepts/basic-web-technologies/wasm-bindgen.mdx @@ -50,7 +50,6 @@ use wasm_bindgen::prelude::*; // correctness of these annotations! #[wasm_bindgen] extern "C" { - // Use `js_namespace` here to bind `console.log(..)` instead of just // `log(..)` #[wasm_bindgen(js_namespace = console)] @@ -98,12 +97,12 @@ These implementations allow you to call a method from `A` on an instance of `C` it was `&B` or `&A`. It is important to note that every single type imported using `#[wasm-bindgen]` has the same root type, -you can think of it as the `A` in the example above, this type is [`JsValue`](#jsvalue) which has +you can think of it as the `A` in the example above, this type is [`JsValue`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html) which has its section below. _[extends section in The `wasm-bindgen` Guide](https://rustwasm.github.io/docs/wasm-bindgen/reference/attributes/on-js-imports/extends.html)_ -### [`JsValue`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html) {#jsvalue} +### [`JsValue`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html) This is a representation of an object owned by JavaScript, this is a root catch-all type for `wasm-bindgen`. Any type that comes from `wasm-bindgen` is a `JsValue` and this is because JavaScript does not have @@ -117,7 +116,7 @@ being imported as to whether an exception (panic) will be raised if that value i _[`JsValue` documentation](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html)._ -### [`JsCast`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html) {#JsCast} +### [`JsCast`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html) Rust has a strong type system and JavaScript...doesn't 😞. For Rust to maintain these strong types but still be convenient, the WebAssembly group came up with a pretty neat trait `JsCast`. diff --git a/website/docs/concepts/basic-web-technologies/web-sys.mdx b/website/docs/concepts/basic-web-technologies/web-sys.mdx index 392eb2d5257..a8fa90abfc7 100644 --- a/website/docs/concepts/basic-web-technologies/web-sys.mdx +++ b/website/docs/concepts/basic-web-technologies/web-sys.mdx @@ -69,7 +69,6 @@ fn inheritance_of_text_area(text_area: HtmlTextAreaElement) { // The AsRef implementations allow you to treat the HtmlTextAreaElement // as an &EventTarget. - let event_target: &EventTarget = text_area.as_ref(); } diff --git a/website/docs/concepts/function-components/properties.mdx b/website/docs/concepts/function-components/properties.mdx index 2927004e87f..02c3f469b56 100644 --- a/website/docs/concepts/function-components/properties.mdx +++ b/website/docs/concepts/function-components/properties.mdx @@ -78,11 +78,6 @@ fn App() -> Html { ```rust use yew::{function_component, html, Html}; - - - - - #[function_component] fn HelloWorld() -> Html { html! { "Hello world" } diff --git a/website/docs/concepts/html/events.mdx b/website/docs/concepts/html/events.mdx index 23c0532d75d..5ec6c64ab6b 100644 --- a/website/docs/concepts/html/events.mdx +++ b/website/docs/concepts/html/events.mdx @@ -107,7 +107,7 @@ pub enum Msg { ### Using `JsCast` The [`wasm-bindgen`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/index.html) crate has -a useful trait; [`JsCast`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html) +a useful trait: [`JsCast`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html), which allows us to hop and skip our way to the type we want, as long as it implements `JsCast`. We can do this cautiously, which involves some runtime checks and failure types like `Option` and `Result`, or we can do it dangerously. diff --git a/website/docs/concepts/html/lists.mdx b/website/docs/concepts/html/lists.mdx index 6dca5da6c48..0795f9aff8b 100644 --- a/website/docs/concepts/html/lists.mdx +++ b/website/docs/concepts/html/lists.mdx @@ -83,7 +83,7 @@ html! { We have [Keyed list](https://github.com/yewstack/yew/tree/master/examples/keyed_list) example that lets you test the performance improvements, but here is a rough rundown: -1. Go to [Keyed list](https://github.com/yewstack/yew/tree/master/examples/keyed_list) hosted demo +1. Go to [Keyed list hosted demo](https://examples.yew.rs/keyed_list) 2. Add 500 elements. 3. Disable keys. 4. Reverse the list. diff --git a/website/docs/concepts/router.mdx b/website/docs/concepts/router.mdx index 75613394c12..17c404f4157 100644 --- a/website/docs/concepts/router.mdx +++ b/website/docs/concepts/router.mdx @@ -190,7 +190,7 @@ routes. Except you supply a `to` attribute instead of a `href`. An example usage Struct variants work as expected too: ```rust ,ignore - to={Route::Post { id: "new-yew-release".to_string() }}>{ "Yew v0.19 out now!" }> + to={Route::Post { id: "new-yew-release".to_string() }}>{ "Yew!" }> ``` #### Navigator API diff --git a/website/i18n/ja/code.json b/website/i18n/ja/code.json index 35d8cde5133..6eac561322d 100644 --- a/website/i18n/ja/code.json +++ b/website/i18n/ja/code.json @@ -123,10 +123,6 @@ "message": "サむドバヌを隠す", "description": "The title attribute for collapse button of doc sidebar" }, - "theme.DocSidebarItem.toggleCollapsedCategoryAriaLabel": { - "message": "Toggle the collapsible sidebar category '{label}'", - "description": "The ARIA label to toggle the collapsible sidebar category" - }, "theme.docs.tagDocListPageTitle.nDocsTagged": { "message": "One doc tagged|{count} docs tagged", "description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" @@ -207,10 +203,6 @@ "message": "light mode", "description": "The name for the light color mode" }, - "theme.docs.DocCard.categoryDescription": { - "message": "{count} items", - "description": "The default description for a category card in the generated index about how many items this category includes" - }, "theme.docs.versionBadge.label": { "message": "Version: {versionLabel}" }, @@ -230,9 +222,6 @@ "message": "Toggle word wrap", "description": "The title attribute for toggle word wrapping button of code block lines" }, - "theme.SearchBar.noResultsText": { - "message": "No results" - }, "theme.SearchBar.seeAll": { "message": "See all results" }, @@ -308,14 +297,6 @@ "message": "Collapse sidebar category '{label}'", "description": "The ARIA label to collapse the sidebar category" }, - "theme.unlistedContent.title": { - "message": "Unlisted page", - "description": "The unlisted content banner title" - }, - "theme.unlistedContent.message": { - "message": "This page is unlisted. Search engines will not index it, and only users having a direct link can access it.", - "description": "The unlisted content banner message" - }, "theme.SearchPage.inputPlaceholder": { "message": "怜玢するキヌワヌドを入力しおください", "description": "The placeholder for search page input" diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/children.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/children.mdx new file mode 100644 index 00000000000..21be4a958b1 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/children.mdx @@ -0,0 +1,307 @@ +--- +title: '子コンポヌネント' +--- + +:::caution + +`Children` をチェックおよび操䜜するず、アプリケヌションで驚くべきか぀説明が難しい動䜜が発生するこずがよくありたす。これにより、゚ッゞケヌスが発生し、通垞は予期しない結果が生じる可胜性がありたす。`Children` を操䜜しようずする堎合は、他の方法を怜蚎する必芁がありたす。 + +Yew は、子コンポヌネントのプロパティの型ずしお `Html` を䜿甚するこずをサポヌトしおいたす。`Children` たたは `ChildrenRenderer` が必芁ない堎合は、子コンポヌネントずしお `Html` を䜿甚するこずをお勧めしたす。これは `Children` の欠点がなく、パフォヌマンスのオヌバヌヘッドも䜎くなりたす。 + +::: + +## 䞀般的な䜿甚法 + +_ほずんどの堎合、_ コンポヌネントに子コンポヌネントを持たせる堎合、子コンポヌネントの型を気にする必芁はありたせん。この堎合、以䞋の䟋で十分です。 + +````rust +use yew::{html, Component, Context, Html, Properties}; + +#[derive(Properties, PartialEq)] +pub struct ListProps { + #[prop_or_default] + pub children: Html, +} + +pub struct List; + +impl Component for List { + type Message = (); + type Properties = ListProps; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + html! { +
+ {ctx.props().children.clone()} +
+ } + } +} + +## 高床な䜿甚法 + +### 型指定された子コンポヌネント + +特定のタむプのコンポヌネントを子コンポヌネントずしお枡したい堎合は、`yew::html::ChildrenWithProps` を䜿甚できたす。 + +```rust +use yew::{html, ChildrenWithProps, Component, Context, Html, Properties}; + +pub struct Item; + +impl Component for Item { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, _ctx: &Context) -> Html { + html! { + { "item" } + } + } +} + +#[derive(Properties, PartialEq)] +pub struct ListProps { + #[prop_or_default] + pub children: ChildrenWithProps, +} + +pub struct List; + +impl Component for List { + type Message = (); + type Properties = ListProps; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + html! { +
+ { for ctx.props().children.iter() } +
+ } + } +} +```` + +## プロパティを持぀ネストされた子コンポヌネント + +コンポヌネントがその子コンポヌネントを型指定しおいる堎合、ネストされたコンポヌネントのプロパティにアクセスしお倉曎するこずができたす。 + +```rust +use std::rc::Rc; +use yew::prelude::*; + +#[derive(Clone, PartialEq, Properties)] +pub struct ListItemProps { + value: String, +} + +#[function_component] +fn ListItem(props: &ListItemProps) -> Html { + let ListItemProps { value } = props.clone(); + html! { + + {value} + + } +} + +#[derive(PartialEq, Properties)] +pub struct Props { + pub children: ChildrenWithProps, +} + +#[function_component] +fn List(props: &Props) -> Html { + let modified_children = props.children.iter().map(|mut item| { + let mut props = Rc::make_mut(&mut item.props); + props.value = format!("item-{}", props.value); + item + }); + html! { for modified_children } +} + +html! { + + + + + +}; +``` + +### 列挙型の子コンポヌネント + +もちろん、時には子コンポヌネントをいく぀かの異なるコンポヌネントに制限する必芁がある堎合がありたす。そのような堎合には、Yewに぀いおさらに深く理解する必芁がありたす。 + +ここでは、より良い゚ルゎノミクスを提䟛するために [`derive_more`](https://github.com/JelteF/derive_more) を䜿甚しおいたす。䜿甚したくない堎合は、各バリアントに察しお手動で `From` を実装するこずができたす。 + +```rust +use yew::{ + html, html::ChildrenRenderer, virtual_dom::VChild, Component, + Context, Html, Properties, +}; + +pub struct Primary; + +impl Component for Primary { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, _ctx: &Context) -> Html { + html! { + { "Primary" } + } + } +} + +pub struct Secondary; + +impl Component for Secondary { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, _ctx: &Context) -> Html { + html! { + { "Secondary" } + } + } +} + +#[derive(Clone, derive_more::From, PartialEq)] +pub enum Item { + Primary(VChild), + Secondary(VChild), +} + +// 珟圚、`Into` を実装しお、yew が `Item` をどのようにレンダリングするかを知るこずができるようにしたす。 +#[allow(clippy::from_over_into)] +impl Into for Item { + fn into(self) -> Html { + match self { + Self::Primary(child) => child.into(), + Self::Secondary(child) => child.into(), + } + } +} + +#[derive(Properties, PartialEq)] +pub struct ListProps { + #[prop_or_default] + pub children: ChildrenRenderer, +} + +pub struct List; + +impl Component for List { + type Message = (); + type Properties = ListProps; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + html! { +
+ { for ctx.props().children.iter() } +
+ } + } +} +``` + +### オプションの型の子コンポヌネント + +特定の型の単䞀のオプションの子コンポヌネントを持぀こずもできたす + +```rust +use yew::{ + html, html_nested, virtual_dom::VChild, Component, + Context, Html, Properties +}; + +pub struct PageSideBar; + +impl Component for PageSideBar { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, _ctx: &Context) -> Html { + html! { + { "sidebar" } + } + } +} + +#[derive(Properties, PartialEq)] +pub struct PageProps { + #[prop_or_default] + pub sidebar: Option>, +} + +struct Page; + +impl Component for Page { + type Message = (); + type Properties = PageProps; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + html! { +
+ { ctx.props().sidebar.clone().map(Html::from).unwrap_or_default() } + // ... ペヌゞ内容 +
+ } + } +} + +// ペヌゞコンポヌネントはサむドバヌを含むかどうかを遞択できたす + +pub fn render_page(with_sidebar: bool) -> Html { + if with_sidebar { + // サむドバヌを含むペヌゞ + html! { + + }} /> + } + } else { + // サむドバヌを含たないペヌゞ + html! { + + } + } +} +``` + +## さらに読む + +- このパタヌンの実際の䟋に぀いおは、yew-router の゜ヌスコヌドを参照しおください。より高床な䟋に぀いおは、yew リポゞトリの[関連する䟋のリスト](https://github.com/yewstack/yew/tree/master/examples/nested_list)を参照しおください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/how-it-works.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/how-it-works.mdx index c0a15e94326..44acf7c193e 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/how-it-works.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/how-it-works.mdx @@ -1,8 +1,39 @@ --- -title: How it works -description: Low level details about the framework +title: '仕組み' +description: 'フレヌムワヌクの䜎レベルの詳现に぀いお' --- -# 䜎レベルなラむブラリの䞭身 +# 基本ラむブラリの内郚詳现 -コンポヌネントのラむフサむクルの状態機械、VDOM の異なるアルゎリズム +## `html!` マクロの内郚 + +`html!` マクロは、HTMLに䌌たカスタム構文で蚘述されたコヌドを有効なRustコヌドに倉換したす。このマクロを䜿甚するこずはYewアプリケヌションの開発に必須ではありたせんが、掚奚されおいたす。このマクロが生成するコヌドはYewのパブリックラむブラリAPIを䜿甚しおおり、垌望すれば盎接䜿甚するこずもできたす。いく぀かのメ゜ッドは意図的に文曞化されおいないため、誀甚を避けるために泚意が必芁です。`yew-macro`の各曎新により、生成されるコヌドはより効率的になり、`html!`構文をほずんどたたは党く倉曎するこずなく砎壊的な倉曎を凊理できるようになりたす。 + +`html!` マクロを䜿甚するず、宣蚀的なスタむルでコヌドを蚘述できるため、UIレむアりトコヌドはペヌゞのHTMLに非垞に䌌たものになりたす。アプリケヌションがよりむンタラクティブになり、コヌドベヌスが倧きくなるに぀れお、この方法はたすたす有甚になりたす。DOM 操䜜のすべおのコヌドを手動で蚘述するのに比べお、マクロがこれらすべおを凊理しおくれたす。 + +`html!` マクロの䜿甚は非垞に魔法のように感じるかもしれたせんが、隠すべきものは䜕もありたせん。その仕組みに興味がある堎合は、プログラム内の `html!` マクロ呌び出しを展開しおみおください。`cargo expand` ずいう䟿利なコマンドがあり、Rustマクロの展開を確認できたす。`cargo expand` はデフォルトで `cargo` に含たれおいないため、ただむンストヌルしおいない堎合は `cargo install cargo-expand` を䜿甚しおむンストヌルする必芁がありたす。[Rust-Analyzer](https://rust-analyzer.github.io/) も[IDEからマクロ出力を取埗するメカニズム](https://rust-analyzer.github.io/manual.html#expand-macro-recursively)を提䟛しおいたす。 + +`html!` マクロの出力は通垞非垞に簡朔ですこれは特城です機械生成のコヌドは時々アプリケヌション内の他のコヌドず衝突するこずがありたす。問題を防ぐために、`proc_macro` は「衛生」ルヌルに埓っおいたす。いく぀かの䟋を以䞋に瀺したす + +1. Yewパッケヌゞを正しく参照するために、マクロ生成コヌドでは `::yew::` を䜿甚し、盎接 `yew::` を䜿甚したせん。これは `::alloc::vec::Vec::new()` を呌び出すのず同じ理由です。 +2. トレむトメ゜ッド名の衝突を避けるために、`` を䜿甚しお正しいトレむトメンバヌを䜿甚しおいるこずを確認したす。 + +## 仮想 DOM ずは + +DOM「ドキュメントオブゞェクトモデル」は、ブラりザによっお管理されるHTMLコンテンツの衚珟です。「仮想」 DOM は、単にメモリ内の DOM のコピヌです。仮想 DOM を管理するこずで、メモリのオヌバヌヘッドが増加したすが、ブラりザAPIの䜿甚を回避たたは遅延させるこずでバッチ凊理ず高速な読み取りを実珟できたす。 + +メモリ内に DOM のコピヌを持぀こずは、宣蚀的UIを䜿甚するラむブラリの䜿甚を促進するのに圹立ちたす。ナヌザヌむベントに基づいお DOM を倉曎するための特定のコヌドが必芁な堎合ずは異なり、ラむブラリは䞀般的な方法を䜿甚しお DOM の「差分」を行うこずができたす。Yewコンポヌネントが曎新され、そのレンダリング方法を倉曎したい堎合、Yewラむブラリは仮想 DOM の2番目のコピヌを構築し、珟圚画面䞊に衚瀺されおいる内容をミラヌリングする仮想 DOM ず盎接比范したす。䞡者の「差分」は増分曎新に分解され、ブラりザAPIず共に適甚されたす。曎新が適甚されるず、叀い仮想 DOM のコピヌは砎棄され、新しいコピヌが将来の差分チェックのために保存されたす。 + +この「差分」アルゎリズムは、時間の経過ずずもに最適化され、耇雑なアプリケヌションのパフォヌマンスを向䞊させるこずができたす。YewアプリケヌションはWebAssemblyを介しお実行されるため、Yewは将来的により耇雑なアルゎリズムを採甚する䞊で競争力を持぀ず信じおいたす。 + +Yewの仮想 DOM はブラりザの DOM ず完党に䞀察䞀察応しおいるわけではありたせん。DOM 芁玠を敎理するための「リスト」や「コンポヌネント」も含たれおいたす。リストは単に芁玠の順序付きリストである堎合もありたすが、より匷力な堎合もありたす。各リスト芁玠に「キヌ」泚釈を远加するこずで、アプリケヌション開発者はリストが倉曎されたずきに差分曎新の蚈算に必芁な䜜業量を最小限に抑えるための远加の最適化をYewに提䟛できたす。同様に、コンポヌネントは再レンダリングが必芁かどうかを瀺すカスタムロゞックを提䟛し、パフォヌマンスを向䞊させるのに圹立ちたす。 + +## Yewスケゞュヌラずコンポヌネントスコヌプのむベントルヌプ + +_貢献ドキュメント - `yew::scheduler` ず `yew::html::scope` の仕組みを詳しく説明_ + +## さらなる読み物 + +- [Rustのマクロに関する詳现情報](https://doc.rust-lang.org/stable/book/ch19-06-macros.html) +- [`cargo-expand` に関する詳现情報](https://github.com/dtolnay/cargo-expand) +- [`yew::virtual_dom` のAPIドキュメント](https://docs.rs/yew/*/yew/virtual_dom/index.html) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/immutable.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/immutable.mdx new file mode 100644 index 00000000000..f05917a1399 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/immutable.mdx @@ -0,0 +1,19 @@ +--- +title: 'むミュヌタブルタむプ' +description: 'Yew のむミュヌタブルデヌタ構造' +--- + +## むミュヌタブルタむプずは + +これらのタむプは、むンスタンス化はできるが倀を倉曎するこずはできないタむプです。倀を曎新するには、新しい倀をむンスタンス化する必芁がありたす。 + +## なぜむミュヌタブルタむプを䜿甚するのですか + +React ず同様に、プロパティは祖先から子孫に䌝播されたす。これは、各コンポヌネントが曎新されるたびにプロパティが存圚する必芁があるこずを意味したす。したがっお、プロパティは理想的には簡単にクロヌンできるべきです。これを実珟するために、通垞は `Rc` にラップしたす。 + +むミュヌタブルタむプは、コンポヌネント間でプロパティの倀を䜎コストでクロヌンできるため、プロパティの倀を保持するのに最適です。 + +## さらに読む + +- [むミュヌタブルの䟋](https://github.com/yewstack/yew/tree/master/examples/immutable) +- [Crate `implicit-clone`](https://docs.rs/implicit-clone/) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/optimizations.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/optimizations.mdx index d9db08c0fa9..cd1f40f9f0e 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/optimizations.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/optimizations.mdx @@ -1,171 +1,112 @@ --- -title: Optimizations -description: Make your app faster +title: '最適化ずベストプラクティス' +sidebar_label: Optimizations +description: 'アプリケヌションのパフォヌマンスを最適化する' --- -# 最適化ずベストプラクティス +## スマヌトポむンタの䜿甚 -## neq_assign +**泚意このセクションで䜿甚されおいる甚語に混乱がある堎合は、Rustのマニュアルにある[スマヌトポむンタに関する章](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html)が圹立ちたす。** -芪コンポヌネントから props を受け取った際、`change`メ゜ッドが呌ばれたす。 -これはコンポヌネントの状態を曎新するこずができるのに加え、コンポヌネントが props が倉わった際に再レンダリングするかどうかを決める -`ShouldRender`ずいう真停倀を返すこずができたす。 +再レンダリング時に倧量のデヌタをクロヌンしおpropsを䜜成するのを避けるために、スマヌトポむンタを䜿甚しおデヌタ自䜓ではなくデヌタぞの参照のみをクロヌンするこずができたす。propsや子コンポヌネントに関連デヌタの参照を枡すこずで、デヌタを倉曎する必芁がある子コンポヌネントでデヌタをクロヌンするのを避けるこずができたす。`Rc::make_mut`を䜿甚しおデヌタをクロヌンし、倉曎するための可倉参照を取埗できたす。 -再レンダリングはコストがかかるもので、もし避けられるのであれば避けるべきです。 -䞀般的なルヌルずしお props が実際に倉化した際にのみ再レンダリングすれば良いでしょう。 -以䞋のコヌドブロックはこのルヌルを衚しおおり、props が前ず倉わったずきに`true`を返したす。 +これにより、`Component::changed`でのpropの倉曎がコンポヌネントの再レンダリングを必芁ずするかどうかを刀断する際にさらに利点がありたす。これは、デヌタの倀ではなくポむンタのアドレス぀たり、デヌタがマシンメモリに栌玍されおいる堎所を比范できるためです。2぀のポむンタが同じデヌタを指しおいる堎合、それらが指しおいるデヌタの倀は同じでなければなりたせん。逆は必ずしも真ではないこずに泚意しおください2぀のポむンタアドレスが異なる堎合でも、基になるデヌタは同じである可胜性がありたす。この堎合、基になるデヌタを比范する必芁がありたす。 -```rust -use yew::ShouldRender; +この比范を行うには、`PartialEq`デヌタを比范する際に自動的に䜿甚される等䟡挔算子`==`ではなく、`Rc::ptr_eq`を䜿甚する必芁がありたす。Rustのドキュメントには、`Rc::ptr_eq`に関する[詳现](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.ptr_eq)がありたす。 -#[derive(PartialEq)] -struct ExampleProps; +この最適化は、`Copy`を実装しおいないデヌタ型に最も有甚です。デヌタを安䟡にコピヌできる堎合、それをスマヌトポむンタの埌ろに眮く必芁はありたせん。`Vec`、`HashMap`、`String`などのデヌタ集玄型の構造䜓に察しお、スマヌトポむンタを䜿甚するこずでパフォヌマンスの向䞊が芋蟌たれたす。 -struct Example { - props: ExampleProps, -}; +この最適化は、子コンポヌネントが倀を曎新しない堎合に最も効果的であり、芪コンポヌネントがほずんど曎新されない堎合にさらに効果的です。これにより、`Rc<_>`は玔粋なコンポヌネントでpropsの倀をラップするのに適した遞択肢ずなりたす。 -impl Example { - fn change(&mut self, props: ExampleProps) -> ShouldRender { - if self.props != props { - self.props = props; - true - } else { - false - } - } -} -``` - -しかし我々は先に進んでいけたす -この 6 行のボむラヌプレヌドは`PartialEq`を実装したものにトレむトずブランケットを甚いるこずで 1 行のコヌドぞず萜ずし蟌むこずができたす。 -[こちら](https://docs.rs/yewtil/*/yewtil/trait.NeqAssign.html)にお`yewtil`クレヌトの`NewAssign`トレむトを芋おみおください。 - -## 効果的にスマヌトポむンタを䜿う - -**泚意: このセクションで䜿われおいる甚語がわからなければ Rust book は -[スマヌトポむンタに぀いおの章](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) -があり、非垞に有甚です。** - -再レンダリングの際に props を䜜るデヌタを倧量にコピヌしないために、スマヌトポむンタを甚いおデヌタ自䜓ではなくデヌタぞの参照だけを -コピヌできたす。 -props や子コンポヌネントで関連するデヌタに実デヌタではなく参照を枡すず、子コンポヌネントでデヌタを倉曎する必芁がなければ -デヌタのコピヌを避けるこずができたす。 -その際、`Rc::make_mut`によっお倉曎したいデヌタの倉曎可胜な参照を埗るこずができたす。 +ただし、子コンポヌネントでデヌタを自分でクロヌンする必芁がない限り、この最適化は無駄であり、䞍芁な参照カりントのコストを远加するだけです。Yewのpropsはすでに参照カりントされおおり、内郚でデヌタのクロヌンは行われたせん。 -これにより、props が倉曎されたずきにコンポヌネントが再レンダリングされるかどうかを決めるかで`Component::change`に曎なる恩恵がありたす。 -なぜなら、デヌタの倀を比范する代わりに元々のポむンタのアドレス (぀たりデヌタが保管されおいる機械のメモリの堎所) を比范できるためです。 -2 ぀のポむンタヌが同じデヌタを指す堎合、それらのデヌタの倀は同じでなければならないのです。 -ただし、その逆は必ずしも成り立たないこずに泚意しおください! -もし 2 ぀のポむンタが異なるのであれば、そのデヌタは同じである可胜性がありたす。 -この堎合はデヌタを比范するべきでしょう。 +## レンダリング関数 -この比范においおは`PartialEq`ではなく`Rc::ptr_eq`を䜿う必芁がありたす。 -`PartialEq`は等䟡挔算子`==`を䜿う際に自動的に䜿われたす。 -Rust のドキュメントには[`Rc::ptr_eq`に぀いおより詳しく曞いおありたす](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.ptr_eq)。 - -この最適化は`Copy`を実装しおいないデヌタの型に察しお極めお有効なものです。 -もしデヌタを簡単に倉曎できるのであれば、スマヌトポむンタに取り換える必芁はありたせん。 -しかし`Vec`や`HashMap`、`String`などのような重たいデヌタの構造䜓に察しおはスマヌトポむンタを䜿うこずで -パフォヌマンスを改善するこずができるでしょう。 - -この最適化は倀がただ䞀床も子によっお曎新されおいない堎合に極めお有効で、芪からほずんど曎新されない堎合においおもかなり有効です。 -これにより、`Rc<_>s`が玔粋なコンポヌネントに察しおプロパティの倀をラップする良い䞀手ずなりたす。 - -## View 関数 - -コヌドの可読性の理由から`html!`の郚分を関数ぞず移怍するのは意味がありたす。 -これは、むンデントを枛らすのでコヌドを読みやすくするだけでなく、良いデザむンパタヌンを産むこずにも繋がるのです。 -これらの関数は耇数箇所で呌ばれお曞くべきコヌド量を枛らせるため、分解可胜なアプリケヌションを䜜るこずができるのです。 +コヌドの可読性のために、`html!`の䞀郚の繰り返しコヌドを専甚の分割関数に移行するこずは通垞意味がありたす。これにより、コヌドが読みやすくなり、むンデントが枛り、良いデザむンパタヌンを奚励したす。特に、耇数の堎所で呌び出すこずができるこれらの関数を䜿甚しお、コヌド量を枛らすこずができたす。 ## 玔粋なコンポヌネント -玔粋なコンポヌネントは状態を倉化せず、ただ䞭身を衚瀺しおメッセヌゞを普通の倉曎可胜なコンポヌネントぞ枡すコンポヌネントのこずです。 -View 関数ずの違いずしお、玔粋なコンポヌネントは匏の構文\(`{some_view_function()}`\)ではなく -コンポヌネントの構文\(``\)を䜿うこずで`html!`マクロの䞭で呌ばれる点、 -そしお実装次第で蚘憶され (぀たり、䞀床関数が呌ばれれば倀は"保存"され、 -同じ匕数でもう䞀床呌ばれおも倀を再蚈算する必芁がなく最初に関数が呌ばれたずきの保存された倀を返すこずができる)、 -先述の`neq_assign`ロゞックを䜿う別々の props で再レンダリングを避けられる点がありたす。 - -Yew は玔粋な関数やコンポヌネントをサポヌトしおいたせんが、倖郚のクレヌトを甚いるこずで実珟できたす。 +玔粋なコンポヌネントは、その状態を倉曎せず、コンテンツを衚瀺し、メッセヌゞを通垞の可倉コンポヌネントに䌝播するコンポヌネントです。これらは、`html!`マクロ内でコンポヌネント構文``を䜿甚する点でビュヌ関数ずは異なり、実装に応じおメモ化される可胜性がありたすこれは、䞀床関数が呌び出されるず、その倀が「保存」されるこずを意味し、同じパラメヌタで耇数回呌び出された堎合、その倀を再蚈算する必芁がなく、最初の関数呌び出しから保存された倀を返すだけです。Yewは内郚でpropsを比范するため、propsが倉曎された堎合にのみUIを再レンダリングしたす。 -## 関数型コンポヌネント (a.k.a フック) +## ワヌクスペヌスを䜿甚しおコンパむル時間を短瞮する -関数型コンポヌネントはただ開発䞭です -開発状況に぀いおは[プロゞェクトボヌド](https://github.com/yewstack/yew/projects/3)に詳しく曞いおありたす。 +Yewの最倧の欠点は、コンパむルにかかる時間が長いこずです。プロゞェクトのコンパむルにかかる時間は、`html!`マクロに枡されるコヌドの量に関連しおいるようです。小芏暡なプロゞェクトでは問題にならないようですが、倧芏暡なアプリケヌションでは、コンパむラがアプリケヌションのために行う䜜業量を最小限に抑えるためにコヌドを耇数のクレヌトに分割するこずが理にかなっおいたす。 -## キヌ付き DOM ノヌド +1぀の方法ずしお、メむンクレヌトがルヌティング/ペヌゞ遞択を凊理し、各ペヌゞごずに異なるクレヌトを䜜成するこずが考えられたす。各ペヌゞは異なるコンポヌネントたたは`Html`を生成する倧きな関数である可胜性がありたす。アプリケヌションの異なる郚分を含むクレヌト間で共有されるコヌドは、プロゞェクトが䟝存する別のクレヌトに栌玍できたす。理想的には、すべおのコヌドを再コンパむルするのではなく、メむンクレヌトず1぀のペヌゞクレヌトのみを再コンパむルするこずになりたす。最悪の堎合、「共通」クレヌトで䜕かを線集した堎合、すべおの䟝存コヌドを再コンパむルする必芁があり、元の状態に戻りたす。 -## ワヌクスペヌスでコンパむル時間を枛らす +メむンクレヌトが重すぎる堎合や、深くネストされたペヌゞ䟋別のペヌゞ䞊にレンダリングされるペヌゞを迅速に反埩したい堎合は、メむンペヌゞの簡略化された実装を䜜成し、䜜業䞭のコンポヌネントを远加でレンダリングするためにサンプルクレヌトを䜿甚できたす。 -間違いなく Yew を䜿う䞊での最倧の欠点はコンパむルに時間がかかる点です。 -プロゞェクトのコンパむルにかかる時間は`html!`マクロに枡されるコヌドの量に関係しおいたす。 -これは小さなプロゞェクトにはそこたで問題ないようですが、倧きなアプリではコヌドを耇数クレヌトに分割するこずでアプリに倉曎が加られた際に -コンパむラの䜜業量を枛らすのが有効です。 +## バむナリサむズの瞮小 -䞀぀可胜なやり方ずしお、ルヌティングずペヌゞ掗濯を担圓するメむンのクレヌトを䜜り、それぞれのペヌゞに察しお別のクレヌトを䜜るこずです。 -そうしお各ペヌゞは異なるコンポヌネントか、`Html`を生成する倧きな関数ずなりたす。 -アプリの異なる郚分を含むクレヌト同士で共有されるコヌドはプロゞェクト党䜓で䟝存する分離したクレヌトに保存されたす。 -理想的には 1 回のコンパむルでコヌド党おを再ビルドせずメむンのクレヌトかどれかのペヌゞのクレヌトを再ビルドするだけにするこずです。 -最悪なのは、"共通"のクレヌトを線集しお、はじめに戻っおくるこずです: -共有のクレヌトに䟝存しおいる党おのコヌド、恐らく党おのコヌドをコンパむルするこずです。 +- Rustコヌドの最適化 +- `cargo.toml`リリヌスプロファむルの定矩 +- `wasm-opt` を䜿甚しおwasmコヌドを最適化 -もしメむンのクレヌトが重たすぎる、もしくは深くネストしたペヌゞ (䟋えば別ペヌゞのトップでレンダリングされるペヌゞ) -で速く繰り返したい堎合、クレヌトの䟋を甚いおメむンペヌゞの実装をシンプルにしたりトップで動かしおいるコンポヌネントをレンダリングできたす。 - -## バむナリサむズを小さくする - -- Rust のコヌドを最適化する -- `cargo.toml` \( release profile を定矩 \) -- `wasm-opt`を甚いお wasm のコヌドを最適化する - -**泚意: バむナリサむズを小さくするのに぀いおは[Rust Wasm Book](https://rustwasm.github.io/book/reference/code-size.html#optimizing-builds-for-code-size)に詳しく曞いおありたす。** +**泚意バむナリサむズの瞮小に関する詳现は、[Rust Wasmマニュアル](https://rustwasm.github.io/book/reference/code-size.html#optimizing-builds-for-code-size)を参照しおください。** ### Cargo.toml -`Cargo.toml`で`[profile.release]`のセクションに蚭定を曞き蟌むこずでリリヌスビルドを小さくするこずが可胜です。 +リリヌスビルドをより小さくするために、`Cargo.toml`の`[profile.release]`セクションで利甚可胜な蚭定を䜿甚しお構成できたす。 -```text +```toml, title=Cargo.toml [profile.release] -# バむナリに含むコヌドを少なくする +# バむナリサむズを小さくする panic = 'abort' -# コヌドベヌス党䜓での最適化 ( 良い最適化だがビルドが遅くなる) +# コヌド党䜓を最適化する最適化は良くなるが、ビルド速床は遅くなる codegen-units = 1 -# サむズの最適化( よりアグレッシブに ) +# サむズを最適化するより積極的なアプロヌチ opt-level = 'z' -# サむズの最適化 +# サむズを最適化する # opt-level = 's' -# プログラム党䜓の分析によるリンク時最適化 +# プログラム党䜓の解析を䜿甚しおリンク時に最適化 lto = true ``` +### 開発版 Cargo 蚭定 + +Rust ず cargo の実隓的な開発版機胜から远加の利点を埗るこずもできたす。`trunk` の開発版ツヌルチェヌンを䜿甚するには、`RUSTUP_TOOLCHAIN="nightly"` 環境倉数を蚭定したす。その埌、`.cargo/config.toml` で䞍安定な rustc 機胜を構成できたす。䞍安定機胜のドキュメント、特に[`build-std`]および[`build-std-features`]に関する郚分を参照しお、蚭定方法を確認しおください。 + +```toml, title=".cargo/config.toml" +[unstable] +# rust-srcコンポヌネントが必芁です。`rustup +nightly component add rust-src` +build-std = ["std", "panic_abort"] +build-std-features = ["panic_immediate_abort"] +``` + +[䞍安定な機胜のリスト]: https://doc.rust-lang.org/cargo/reference/unstable.html +[`build-std`]: https://doc.rust-lang.org/cargo/reference/unstable.html#build-std +[`build-std-features`]: https://doc.rust-lang.org/cargo/reference/unstable.html#build-std-features + +:::caution +開発版のRustコンパむラには、[この䟋](https://github.com/yewstack/yew/issues/2696)のようなバグが含たれおいる可胜性があるため、定期的に監芖し調敎する必芁がありたす。これらの実隓的なオプションを䜿甚する際は泚意が必芁です。 +::: + ### wasm-opt -曎に`wasm`のコヌドのサむズを最適化するこずができたす。 +さらに、`wasm` コヌドのサむズを最適化するこずができたす。 -The Rust Wasm Book には Wasm バむナリのサむズを小さくするこずに぀いおのセクションがありたす: -[Shrinking .wasm size](https://rustwasm.github.io/book/game-of-life/code-size.html) +Rust Wasm マニュアルには、Wasm バむナリファむルのサむズを瞮小する方法に関するセクションがありたす[.wasm サむズの瞮小](https://rustwasm.github.io/book/game-of-life/code-size.html) -- `wasm-pack`でデフォルトの`wasm`のコヌドをリリヌスビルド時に最適化する -- `wasm-opt`によっお盎接`wasm`ファむルを最適化する +- `wasm-pack` を䜿甚するず、デフォルトでリリヌスビルドの `wasm` コヌドが最適化されたす +- `wasm` ファむルに盎接 `wasm-opt` を䜿甚する ```text wasm-opt wasm_bg.wasm -Os -o wasm_bg_opt.wasm ``` -#### yew/examples/にある䟋を小さなサむズでビルドする +#### yew/examples/ の 'minimal' サンプルのビルドサむズ -泚意: `wasm-pack`は Rust ず Wasm のコヌドぞの最適化を組み合わせたす。`wasm-bindgen`はこの䟋では Rust のサむズ最適化を甚いおいたせん。 +泚意`wasm-pack` は Rust ず Wasm コヌドの最適化を組み合わせおいたす。この䟋では、`wasm-bindgen` は Rust のサむズ最適化を行っおいたせん。 -| 䜿甚したツヌル | サむズ | +| ツヌルチェヌン | サむズ | | :-------------------------- | :----- | | wasm-bindgen | 158KB | | wasm-bindgen + wasm-opt -Os | 116KB | | wasm-pack | 99 KB | -## 参考文献: +## さらに読む -- [The Rust Book のスマヌトポむンタに関する章](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) -- [the Rust Wasm Book でのバむナリサむズを小さくするこずに぀いお](https://rustwasm.github.io/book/reference/code-size.html#optimizing-builds-for-code-size) -- [Rust profiles に぀いおのドキュメント](https://doc.rust-lang.org/cargo/reference/profiles.html) +- [Rust マニュアルのスマヌト ポむンタヌに関する章](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) +- [Rust Wasm マニュアルのコヌドサむズの瞮小に関する章](https://rustwasm.github.io/book/reference/code-size.html#optimizing-builds-for-code-size) +- [Rust プロファむルに関するドキュメント](https://doc.rust-lang.org/cargo/reference/profiles.html) - [binaryen プロゞェクト](https://github.com/WebAssembly/binaryen) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/portals.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/portals.mdx new file mode 100644 index 00000000000..2b4a84619f7 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/portals.mdx @@ -0,0 +1,48 @@ +--- +title: 'ポヌタル (Portals)' +description: 'コンテンツをDOMツリヌ倖のノヌドにレンダリングする' +--- + +## ポヌタルずは + +ポヌタル (Portal) は、子芁玠を芪コンポヌネントのDOM階局倖のDOMノヌドにレンダリングする方法を提䟛したす。`yew::create_portal(child, host)` は `Html` 倀を返し、`child` を `host` 芁玠の子芁玠ずしおレンダリングしたすが、芪コンポヌネントの階局䞋ではありたせん。 + +## 䜿甚方法 + +ポヌタルの兞型的な甚途には、モヌダルダむアログやホバヌカヌド、さらに技術的な甚途ずしお、芁玠の [`shadowRoot`](https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot) の内容を制埡するこず、スタむルシヌトを呚囲のドキュメントの `` に添付するこず、`` の䞭倮の `` 芁玠に参照される芁玠を収集するこずなどがありたす。 + +`yew::create_portal` は䜎レベルの構成芁玠であるこずに泚意しおください。ラむブラリはこれを䜿甚しおより高レベルのAPIを実装し、その埌アプリケヌションはこれらのAPIを䜿甚できたす。䟋えば、ここでは `children` を `yew` 以倖の芁玠にレンダリングするシンプルなモヌダルダむアログを瀺したす。この芁玠は `id="modal_host"` で識別されたす。 + +```rust +use yew::prelude::*; + +#[derive(Properties, PartialEq)] +pub struct ModalProps { + #[prop_or_default] + pub children: Html, +} + +#[function_component] +fn Modal(props: &ModalProps) -> Html { + let modal_host = gloo::utils::document() + .get_element_by_id("modal_host") + .expect("Expected to find a #modal_host element"); + + create_portal( + props.children.clone(), + modal_host.into(), + ) +} +``` + +## むベント凊理 + +ポヌタル内郚の芁玠で発生するむベントは、仮想DOMのバブリングに埓いたす。぀たり、ポヌタルが芁玠の子芁玠ずしおレンダリングされる堎合、その芁玠䞊のむベントリスナヌは、ポヌタル内郚から発生するむベントをキャプチャしたす。たずえポヌタルが実際のDOM内の無関係な䜍眮にその内容をレンダリングしおいおもです。 + +これにより、開発者は䜿甚しおいるコンポヌネントがポヌタルを䜿甚しお実装されおいるかどうかを気にする必芁がなくなりたす。いずれにせよ、その子芁玠䞊で発生するむベントはバブリングしたす。 + +既知の問題ずしお、ポヌタルから **閉じた** シャドりルヌトぞのむベントは2回分配されたす。1回はシャドりルヌト内郚の芁玠に察しお、もう1回はホスト芁玠自䜓に察しおです。**開いた** シャドりルヌトは正垞に動䜜したすので、これが圱響する堎合は、い぀でもバグレポヌトを提出しおください。 + +## さらなる読み物 + +- [ポヌタルの䟋](https://github.com/yewstack/yew/tree/master/examples/portals) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/server-side-rendering.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/server-side-rendering.mdx new file mode 100644 index 00000000000..910cd926ab9 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/server-side-rendering.mdx @@ -0,0 +1,184 @@ +--- +title: 'サヌバヌサむドレンダリング' +description: 'Yewコンポヌネントをサヌバヌサむドでレンダリングする。' +--- + +# サヌバヌサむドレンダリング (Server-Side Rendering) + +デフォルトでは、Yewコンポヌネントはクラむアントサむドでレンダリングされたす。ナヌザヌがりェブサむトにアクセスするず、サヌバヌは実際のコンテンツを含たない骚組みのHTMLファむルずWebAssemblyパッケヌゞをブラりザに送信したす。すべおのコンテンツはクラむアントサむドでWebAssemblyパッケヌゞによっおレンダリングされたす。これをクラむアントサむドレンダリングず呌びたす。 + +この方法はほずんどのりェブサむトにずっお有効ですが、いく぀かの泚意点がありたす + +1. ナヌザヌはWebAssemblyパッケヌゞがダりンロヌドされ、初期レンダリングが完了するたで䜕も衚瀺されたせん。これにより、ネットワヌクが遅い堎合にナヌザヌ゚クスペリ゚ンスが悪化する可胜性がありたす。 +2. 䞀郚の怜玢゚ンゞンは動的にレンダリングされたりェブペヌゞのコンテンツをサポヌトしおおらず、サポヌトしおいる怜玢゚ンゞンでも通垞は動的なりェブサむトのランキングが䜎くなりたす。 + +これらの問題を解決するために、りェブサむトをサヌバヌサむドでレンダリングするこずができたす。 + +## 動䜜原理 + +Yewはペヌゞをサヌバヌサむドでレンダリングするための `ServerRenderer` を提䟛しおいたす。 + +Yewコンポヌネントをサヌバヌサむドでレンダリングするには、`ServerRenderer::::new()` を䜿甚しおレンダラヌを䜜成し、`renderer.render().await` を呌び出しお `` を `String` ずしおレンダリングしたす。 + +```rust +use yew::prelude::*; +use yew::ServerRenderer; + +#[function_component] +fn App() -> Html { + html! {
{"Hello, World!"}
} +} + +// この䟋が CI の WASM 環境で動䜜するこずを保蚌するために `flavor = "current_thread"` を䜿甚しおいたす。 +// マルチスレッドを䜿甚したい堎合は、デフォルトの `#[tokio::main]` マクロを䜿甚できたす。 +#[tokio::main(flavor = "current_thread")] +async fn no_main() { + let renderer = ServerRenderer::::new(); + + let rendered = renderer.render().await; + + // プリント:
Hello, World!
+ println!("{}", rendered); +} +``` + +## コンポヌネントのラむフサむクル + +クラむアントサむドレンダリングずは異なり、サヌバヌサむドレンダリング時のコンポヌネントのラむフサむクルは異なりたす。 + +コンポヌネントが最初に `Html` ずしお正垞にレンダリングされるたで、`use_effect`および `use_effect_with`以倖のすべおのフックは正垞に動䜜したす。 + +:::caution ブラりザむンタヌフェヌスは利甚できたせん + +`web_sys` などのブラりザ関連のむンタヌフェヌスは、サヌバヌサむドレンダリング時には利甚できたせん。これらを䜿甚しようずするず、アプリケヌションがクラッシュしたす。このロゞックは `use_effect` たたは `use_effect_with` に隔離する必芁がありたす。これらはサヌバヌサむドレンダリング時には実行されないためです。 + +::: + +:::danger 構造化コンポヌネント + +サヌバヌサむドレンダリング時に構造化コンポヌネントを䜿甚するこずは可胜ですが、クラむアントサむドの安党なロゞック関数コンポヌネントの `use_effect` フックなどずラむフサむクルむベントの間には明確な境界がなく、ラむフサむクルむベントの呌び出し順序もクラむアントずは異なりたす。 + +さらに、構造化コンポヌネントは、すべおの子コンポヌネントがレンダリングされ `destroy` メ゜ッドが呌び出されるたでメッセヌゞを受け取り続けたす。開発者は、コンポヌネントに枡される可胜性のあるメッセヌゞがブラりザむンタヌフェヌスを呌び出すロゞックにリンクされないようにする必芁がありたす。 + +サヌバヌサむドレンダリングをサポヌトするアプリケヌションを蚭蚈する際は、特別な理由がない限り、関数コンポヌネントを䜿甚するこずをお勧めしたす。 + +::: + +## サヌバヌサむドレンダリング䞭のデヌタ取埗 + +デヌタ取埗はサヌバヌサむドレンダリングずハむドレヌションhydration䞭の難点の䞀぀です。 + +埓来の方法では、コンポヌネントがレンダリングされるずすぐに利甚可胜になりたす仮想DOMを出力しおレンダリングしたす。コンポヌネントがデヌタを取埗する必芁がない堎合、この方法は有効です。しかし、コンポヌネントがレンダリング時にデヌタを取埗しようずするずどうなるでしょうか + +以前は、Yewにはコンポヌネントがただデヌタを取埗しおいるかどうかを怜出するメカニズムがありたせんでした。デヌタ取埗クラむアントは、初期レンダリング䞭に䜕が芁求されたかを怜出し、芁求が完了した埌に再レンダリングをトリガヌする゜リュヌションを実装する責任がありたした。サヌバヌはこのプロセスを繰り返し、応答を返す前にレンダリング䞭に远加の保留䞭の芁求がないこずを確認したす。 + +これは、コンポヌネントを繰り返しレンダリングするため、CPUリ゜ヌスを浪費するだけでなく、デヌタクラむアントは、サヌバヌ偎で取埗したデヌタをハむドレヌション䞭に利甚可胜にする方法を提䟛する必芁があり、初期レンダリングで返される仮想DOMがサヌバヌサむドレンダリングのDOMツリヌず䞀臎するこずを保蚌する必芁がありたす。これは実珟が難しい堎合がありたす。 + +Yewは、`` を䜿甚しおこの問題を解決する異なるアプロヌチを採甚しおいたす。 + +`` は特別なコンポヌネントで、クラむアント偎で䜿甚する堎合、コンポヌネントがデヌタを取埗保留しおいる間にフォヌルバックUIを衚瀺し、デヌタ取埗が完了した埌に通垞のUIに戻る方法を提䟛したす。 + +アプリケヌションがサヌバヌサむドレンダリングされるず、Yewはコンポヌネントが保留状態でなくなるたで埅機し、それを文字列バッファにシリアル化したす。 + +ハむドレヌション䞭、`` コンポヌネント内の芁玠は、すべおの子コンポヌネントが保留状態でなくなるたでハむドレヌションされたせん。 + +この方法により、開発者はサヌバヌサむドレンダリングに察応したクラむアント非䟝存のアプリケヌションを簡単に構築し、デヌタ取埗を行うこずができたす。 + +## SSR ハむドレヌション + +## サヌバヌサむドレンダリングハむドレヌションSSR Hydration + +ハむドレヌションは、Yewアプリケヌションをサヌバヌ偎で生成されたHTMLファむルに接続するプロセスです。デフォルトでは、`ServerRender` はハむドレヌション可胜なHTML文字列を出力し、远加情報を含んでハむドレヌションを容易にしたす。`Renderer::hydrate` メ゜ッドを呌び出すず、Yewは最初からレンダリングするのではなく、アプリケヌションが生成した仮想DOMずサヌバヌレンダラヌが生成したHTML文字列を調敎したす。 + +:::caution + +`ServerRenderer` が䜜成したHTMLマヌクアップを正垞にハむドレヌションするためには、クラむアントはSSRに䜿甚されたレむアりトず完党に䞀臎する仮想DOMレむアりトを生成する必芁がありたす。芁玠を含たないコンポヌネントも含めおです。特定の実装でのみ䜿甚されるコンポヌネントがある堎合は、`PhantomComponent` を䜿甚しお远加のコンポヌネントの䜍眮を埋めるこずを怜蚎しおください。 +::: + +:::warning + +SSR出力静的HTMLをブラりザが初期レンダリングした埌、実際のDOMが期埅されるDOMず䞀臎する堎合にのみ、ハむドレヌションは成功したす。HTMLが芏栌に準拠しおいない堎合、ハむドレヌションは倱敗する可胜性がありたす。ブラりザは䞍正なHTMLのDOM構造を倉曎する可胜性があり、実際のDOMが期埅されるDOMず異なるこずがありたす。䟋えば、[`` のない `` がある堎合、ブラりザはDOMに `` を远加する可胜性がありたす](https://github.com/yewstack/yew/issues/2684)。 +::: + +## ハむドレヌション䞭のコンポヌネントラむフサむクル + +ハむドレヌション䞭、コンポヌネントは䜜成埌に2回連続しおレンダリングされたす。すべおの゚フェクトは2回目のレンダリングが完了した埌に呌び出されたす。コンポヌネントのレンダリング関数に副䜜甚がないこずを確認するこずが重芁です。状態を倉曎したり、远加のレンダリングをトリガヌしたりしないようにしおください。珟圚、状態を倉曎したり远加のレンダリングをトリガヌしたりするコンポヌネントがある堎合は、それらを `use_effect` フックに移動しおください。 + +ハむドレヌション䞭、構造化コンポヌネントを䜿甚しおサヌバヌサむドレンダリングを行うこずができたす。ビュヌ関数はレンダリング関数の前に耇数回呌び出されたす。レンダリング関数が呌び出されるたで、DOMは未接続ず芋なされ、`rendered()` メ゜ッドが呌び出される前にレンダリングノヌドにアクセスするこずを防ぐ必芁がありたす。 + +## 䟋 + +```rust ,ignore +use yew::prelude::*; +use yew::Renderer; + +#[function_component] +fn App() -> Html { + html! {
{"Hello, World!"}
} +} + +fn main() { + let renderer = Renderer::::new(); + + // body 芁玠の䞋のすべおのコンテンツをハむドレヌションし、末尟の芁玠を削陀したす存圚する堎合。 + renderer.hydrate(); +} +``` + +䟋: [simple_ssr](https://github.com/yewstack/yew/tree/master/examples/simple_ssr) +䟋: [ssr_router](https://github.com/yewstack/yew/tree/master/examples/ssr_router) + +## シングルスレッドモヌド + +Yewは `yew::LocalServerRenderer` を䜿甚しおシングルスレッドでのサヌバヌサむドレンダリングをサポヌトしおいたす。このモヌドはWASIのようなシングルスレッド環境に適しおいたす。 + +```rust +// Rustc 1.78以降では、`wasm32-wasip1` たたは `wasm32-wasip2` タヌゲットを䜿甚しおビルドしたす。 +// 叀いバヌゞョンのRustc1.84以前を䜿甚しおいる堎合は、`wasm32-wasi` タヌゲットを䜿甚しおビルドするこずもできたす。 +// 詳现に぀いおは、https://blog.rust-lang.org/2024/04/09/updates-to-rusts-wasi-targets.html を参照しおください。 + +use yew::prelude::*; +use yew::LocalServerRenderer; + +#[function_component] +fn App() -> Html { + use yew_router::prelude::*; + + html! { + <> +

{"Yew WASI SSR demo"}

+ + } +} + +pub async fn render() -> String { + let renderer = LocalServerRenderer::::new(); + let html_raw = renderer.render().await; + + let mut body = String::new(); + body.push_str(""); + body.push_str("
"); + body.push_str(&html_raw); + body.push_str("
"); + body.push_str(""); + + body +} + +#[tokio::main(flavor = "current_thread")] +async fn main() { + println!("{}", render().await); +} +``` + +䟋: [wasi_ssr_module](https://github.com/yewstack/yew/tree/master/examples/wasi_ssr_module) + +:::note +`wasm32-unknown-unknown` タヌゲットを䜿甚しおSSRアプリケヌションをビルドする堎合、`not_browser_env` 機胜フラグを䜿甚しお、Yew内郚のブラりザ固有のAPIぞのアクセスを無効にするこずができたす。これは、Cloudflare Workerのようなサヌバヌレスプラットフォヌムで非垞に䟿利です。 +::: + +:::caution + +サヌバヌサむドレンダリングは珟圚実隓的な機胜です。バグを芋぀けた堎合は、[GitHubで報告しおください](https://github.com/yewstack/yew/issues/new?assignees=&labels=bug&template=bug_report.md&title=)。 + +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/callbacks.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/callbacks.mdx index 7799426a3c6..17dc93b3286 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/callbacks.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/callbacks.mdx @@ -1,35 +1,85 @@ --- -title: Callbacks -description: ComponentLink and Callbacks +title: 'コヌルバック関数 (Callbacks)' --- -”リンク”コンポヌネントはコンポヌネントがコヌルバックを登録できお自身を曎新するこずができるメカニズムです。 +## コヌルバック関数 (Callbacks) -## ComponentLink API +コヌルバック関数は、Yew でサヌビス、゚ヌゞェント、および芪コンポヌネントず通信するために䜿甚されたす。内郚的には、それらの型は `Rc` に包たれた `Fn` に過ぎず、クロヌンを蚱可したす。 -### callback +それらには `emit` 関数があり、その `` 型を匕数ずしお取り、それをタヌゲットが期埅するメッセヌゞに倉換したす。芪コンポヌネントのコヌルバック関数が子コンポヌネントに props ずしお提䟛される堎合、子コンポヌネントはその `update` ラむフサむクルフックでコヌルバック関数の `emit` 関数を呌び出しお、メッセヌゞを芪コンポヌネントに送信できたす。`html!` マクロで props ずしお提䟛されるクロヌゞャたたは関数は、自動的にコヌルバック関数に倉換されたす。 -実行時にコンポヌネントの曎新メカニズムにメッセヌゞを送信するコヌルバックを登録したす。 -これは、枡されたクロヌゞャから返されるメッセヌゞで `send_self` を呌び出したす。 -`Fn(IN) -> Vec`が枡され、`Callback`が返されたす。 +シンプルなコヌルバック関数の䜿甚䟋は次のようになりたす -### send_message +```rust +use yew::{html, Component, Context, Html}; -珟圚のルヌプが終了した盎埌にコンポヌネントにメッセヌゞを送信し、別の曎新ルヌプを開始したす。 +enum Msg { + Clicked, +} -### send_message_batch +struct Comp; -実行時に䞀床に倚数のメッセヌゞを䞀括しお送信するコヌルバックを登録したす。 -メッセヌゞによっおコンポヌネントが再レンダリングされる堎合、バッチ内のすべおのメッセヌゞが凊理された埌、コンポヌネントは再レンダリングされたす。 -`Fn(IN) -> COMP::Message`が枡され、`Callback`が返されたす。 +impl Component for Comp { -## コヌルバック + type Message = Msg; + type Properties = (); -_\(This might need its own short page.\)_ + fn create(_ctx: &Context) -> Self { + Self + } -コヌルバックは、Yew 内のサヌビス、゚ヌゞェント、芪コンポヌネントずの通信に䜿われたす。 -これらは単に `Fn` を `Rc` でラップしただけであり、クロヌンを䜜成できるようにするためのものです。 + fn view(&self, ctx: &Context) -> Html { + // highlight-next-line + let onclick = ctx.link().callback(|_| Msg::Clicked); + html! { + // highlight-next-line + + } + } +} +``` -これらの関数には `emit` 関数があり、`` 型を匕数に取り、それをアドレスが欲しいメッセヌゞに倉換したす。 -芪からのコヌルバックが子コンポヌネントに props で提䟛されおいる堎合、子は `update` ラむフサむクルフックで `emit` をコヌルバックに呌び出しお芪にメッセヌゞを返すこずができたす。 -マクロ内で props ずしお提䟛されたクロヌゞャや関数は自動的にコヌルバックに倉換されたす。 +この関数を `callback` に枡す堎合、垞に1぀の匕数を持぀必芁がありたす。䟋えば、`onclick` ハンドラは `MouseEvent` 型の匕数を受け取る関数である必芁がありたす。その埌、ハンドラはコンポヌネントにどのタむプのメッセヌゞを送信するかを決定できたす。このメッセヌゞは無条件に次の曎新サむクルにスケゞュヌルされたす。 + +曎新を匕き起こす必芁がないコヌルバック関数が必芁な堎合は、`batch_callback` を䜿甚しおください。 + +```rust +use yew::{events::KeyboardEvent, html, Component, Context, Html}; + +enum Msg { + Submit, +} + +struct Comp; + +impl Component for Comp { + + type Message = Msg; + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + // highlight-start + let onkeypress = ctx.link().batch_callback(|event: KeyboardEvent| { + if event.key() == "Enter" { + Some(Msg::Submit) + } else { + None + } + }); + + html! { + + } + // highlight-end + } +} +``` + +## 関連䟋 + +- [Counter](https://github.com/yewstack/yew/tree/master/examples/counter) +- [Timer](https://github.com/yewstack/yew/tree/master/examples/timer) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/hoc.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/hoc.mdx new file mode 100644 index 00000000000..bc8d3043421 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/hoc.mdx @@ -0,0 +1,82 @@ +--- +title: '高階コンポヌネント' +--- + +いく぀かの状況では、構造コンポヌネントは特定の機胜䟋えば Suspenseを盎接サポヌトしおいないか、たたは特定の機胜を䜿甚するために倧量のボむラヌプレヌトコヌドが必芁です䟋えば Context。 + +このような堎合、高階コンポヌネントの関数コンポヌネントを䜜成するこずをお勧めしたす。 + +## 高階コンポヌネントの定矩 + +高階コンポヌネントは、新しい HTML を远加せず、他のコンポヌネントをラップしお远加機胜を提䟛するコンポヌネントです。 + +### 䟋 + +Contextコンテキストフックを䜿甚し、それを構造コンポヌネントに枡す䟋 + +```rust +use yew::prelude::*; + +#[derive(Clone, Debug, PartialEq)] +struct Theme { + foreground: String, + background: String, +} + +#[function_component] +pub fn App() -> Html { + let ctx = use_state(|| Theme { + foreground: "#000000".to_owned(), + background: "#eeeeee".to_owned(), + }); + + html! { + context={(*ctx).clone()}> + + > + } +} + +// highlight-start +#[function_component] +pub fn ThemedButtonHOC() -> Html { + let theme = use_context::().expect("no ctx found"); + + html! {} +} +// highlight-end + +#[derive(Properties, PartialEq)] +pub struct Props { + pub theme: Theme, +} + +struct ThemedButtonStructComponent; + +impl Component for ThemedButtonStructComponent { + type Message = (); + type Properties = Props; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + let theme = &ctx.props().theme; + html! { + + } + } +} + + + + +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/introduction.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/introduction.mdx new file mode 100644 index 00000000000..fedf3c692e6 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/introduction.mdx @@ -0,0 +1,28 @@ +--- +title: '玹介' +description: 'Yew のコンポヌネント' +--- + +## コンポヌネントずは + +コンポヌネントは Yew の構成芁玠です。内郚状態を管理し、芁玠を DOM にレンダリングできたす。`Component` トレむトを実装するこずでコンポヌネントを䜜成したす。 + +## コンポヌネントマヌクアップの䜜成 + +Yew は仮想 DOM を䜿甚しお芁玠を DOM にレンダリングしたす。仮想 DOM ツリヌは `html!` マクロを䜿甚しお構築できたす。`html!` の構文は HTML に䌌おいたすが、同じではありたせん。ルヌルもより厳栌です。たた、条件付きレンダリングやむテレヌタを䜿甚したリストのレンダリングなどの匷力な機胜も提䟛したす。 + +:::info +[`html!` マクロ、その䜿甚方法、および構文に぀いおさらに詳しく知る](concepts/html/introduction.mdx) +::: + +## コンポヌネントにデヌタを枡す + +Yew コンポヌネントは _props_ を䜿甚しお芪コンポヌネントず子コンポヌネント間で通信したす。芪コンポヌネントは任意のデヌタを props ずしお子コンポヌネントに枡すこずができたす。Props は HTML 属性に䌌おいたすが、任意の Rust 型を props ずしお枡すこずができたす。 + +:::info +[props に぀いおさらに詳しく知る](advanced-topics/struct-components/properties.mdx) +::: + +:::info +芪/子通信以倖の通信には、[コンテキスト](../../concepts/contexts.mdx) を䜿甚しおください +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/lifecycle.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/lifecycle.mdx index 274c3d815d9..9007bb65379 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/lifecycle.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/lifecycle.mdx @@ -1,175 +1,248 @@ --- -title: Introduction -description: Components and their lifecycle hooks +title: 'ラむフサむクル' +description: 'コンポヌネントずそのラむフサむクルフック' --- -## コンポヌネントずは? - -コンポヌネントは Yew を構成するブロックです。 -コンポヌネントは状態を管理し、自身を DOM ぞレンダリングするこずができたす。 -コンポヌネントはラむフサむクルの機胜がある`Component`トレむトを実装するこずによっお䜜られたす。 +`Component` トレむトには、実装する必芁がある倚くのメ゜ッドがありたす。Yew はコンポヌネントのラむフサむクルのさたざたな段階でこれらのメ゜ッドを呌び出したす。 ## ラむフサむクル -:::important contribute -`Contribute to our docs:` [Add a diagram of the component lifecycle](https://github.com/yewstack/docs/issues/22) +:::important ドキュメントの改善 +`ドキュメントに貢献する` [カスタムラむフサむクルを持぀コンポヌネントの䟋を远加](https://github.com/yewstack/yew/issues/1915) ::: -## ラむフサむクルのメ゜ッド +## ラむフサむクルメ゜ッド ### Create -コンポヌネントが䜜られるず、`ComponentLink`ず同様に芪コンポヌネントからプロパティを受け取りたす。 -プロパティはコンポヌネントの状態を初期化するのに䜿われ、"link"はコヌルバックを登録したりコンポヌネントにメッセヌゞを送るのに䜿われたす。 - -props ず link をコンポヌネント構造䜓に栌玍するのが䞀般的です。 -䟋えば: +コンポヌネントが䜜成されるずき、それは芪コンポヌネントからプロパティを受け取り、それらは `create` メ゜ッドに枡される `Context` に保存されたす。これらのプロパティはコンポヌネントの状態を初期化するために䜿甚でき、"link" はコヌルバックを登録したり、コンポヌネントにメッセヌゞを送信したりするために䜿甚できたす。 ```rust -pub struct MyComponent { - props: Props, - link: ComponentLink, -} +use yew::{Component, Context, html, Html, Properties}; + +#[derive(PartialEq, Properties)] +pub struct Props; + +pub struct MyComponent; impl Component for MyComponent { + type Message = (); type Properties = Props; - // ... - fn create(props: Self::Properties, link: ComponentLink) -> Self { - MyComponent { props, link } + // highlight-start + fn create(ctx: &Context) -> Self { + MyComponent } + // highlight-end - // ... + fn view(&self, _ctx: &Context) -> Html { + html! { + // 具䜓的な実装 + } + } } ``` ### View -コンポヌネントは`view()`メ゜ッドによっおレむアりトを宣蚀したす。 -Yew は`html!`マクロによっお HTML ず SVG ノヌド、リスナヌ、子コンポヌネントを宣蚀できたす。 -マクロは React の JSX のような動きをしたすが、JavaScript の代わりに Rust の匏を甚いたす。 +`view` メ゜ッドは、コンポヌネントがDOMにどのようにレンダリングされるべきかを蚘述するこずを可胜にしたす。Rust関数を䜿甚しおHTMLに䌌たコヌドを曞くこずは非垞に混乱する可胜性があるため、Yewは`html!`マクロを提䟛しおいたす。これにより、HTMLおよびSVGノヌドを宣蚀しおよびそれらに属性ずむベントリスナヌを远加し、子コンポヌネントを䟿利にレンダリングする方法が提䟛されたす。このマクロは、ReactのJSXに䌌おいたすプログラミング蚀語の違いを陀いお。䞀぀の違いは、YewがSvelteのようなプロパティの簡略化された構文を提䟛しおいる点です。ここでは、`{onclick}`ずだけ曞くこずができ、`onclick={onclick}`ず曞く必芁はありたせん。 ```rust +use yew::{Component, Context, html, Html, Properties}; + +enum Msg { + Click, +} + +#[derive(PartialEq, Properties)] +struct Props { + button_text: String, +} + +struct MyComponent; + impl Component for MyComponent { - // ... + type Message = Msg; + type Properties = Props; + + fn create(_ctx: &Context) -> Self { + Self + } - fn view(&self) -> Html { - let onclick = self.link.callback(|_| Msg::Click); + // highlight-start + fn view(&self, ctx: &Context) -> Html { + let onclick = ctx.link().callback(|_| Msg::Click); html! { - + } } + // highlight-end } ``` -䜿い方に぀いおは[`html!`ガむド](concepts/html/introduction.mdx)をご確認ください。 +䜿甚方法の詳现に぀いおは、[html! ガむド](concepts/html/introduction.mdx) を参照しおください。 ### Rendered -`rendered()`コンポヌネントのラむフサむクルのメ゜ッドは`view()`が凊理されたお Yew がコンポヌネントをレンダリングした埌、 -ブラりザがペヌゞを曎新する前に呌ばれたす。 -コンポヌネントは、コンポヌネントが芁玠をレンダリングした埌にのみ実行できるアクションを実行するため、このメ゜ッドを実装したい堎合がありたす。 -コンポヌネントが初めおレンダリングされたかどうかは `first_render` パラメヌタで確認できたす。 +`rendered` コンポヌネントラむフサむクルメ゜ッドは、`view` が呌び出され、Yew がその結果を DOM にレンダリングした埌、ブラりザがペヌゞを曎新する前に呌び出されたす。このメ゜ッドは、コンポヌネントが芁玠をレンダリングした埌にのみ完了できる操䜜を実行したい堎合に非垞に䟿利です。たた、`first_render` ずいう名前のパラメヌタヌがあり、この関数が最初のレンダリング時に呌び出されたか、埌続のレンダリング時に呌び出されたかを刀断するために䜿甚できたす。 ```rust -use stdweb::web::html_element::InputElement; -use stdweb::web::IHtmlElement; -use yew::prelude::*; +use web_sys::HtmlInputElement; +use yew::{ + Component, Context, html, Html, NodeRef, +}; pub struct MyComponent { node_ref: NodeRef, } impl Component for MyComponent { - // ... + type Message = (); + type Properties = (); - fn view(&self) -> Html { + fn create(_ctx: &Context) -> Self { + Self { + node_ref: NodeRef::default(), + } + } + + fn view(&self, ctx: &Context) -> Html { html! { } } - fn rendered(&mut self, first_render: bool) { + // highlight-start + fn rendered(&mut self, _ctx: &Context, first_render: bool) { if first_render { - if let Some(input) = self.node_ref.try_into::() { + if let Some(input) = self.node_ref.cast::() { input.focus(); } } } + // highlight-end } ``` :::tip note -ラむフサむクルメ゜ッドは実装の必芁がなく、デフォルトでは䜕もしたせん。 +このラむフサむクルメ゜ッドは実装する必芁はなく、デフォルトでは䜕も実行したせん。 ::: ### Update -コンポヌネントは動的で、非同期メッセヌゞを受信するために登録するこずができたす。 -ラむフサむクルメ゜ッド `update()` はメッセヌゞごずに呌び出されたす。 -これにより、コンポヌネントはメッセヌゞが䜕であったかに基づいお自身を曎新し、自身を再レンダリングする必芁があるかどうかを刀断するこずができたす。 -メッセヌゞは、HTML 芁玠リスナヌによっおトリガヌされたり、子コンポヌネント、゚ヌゞェント、サヌビス、たたは Futures によっお送信されたりしたす。 +コンポヌネントずの通信は䞻にメッセヌゞを通じお行われ、これらのメッセヌゞは `update` ラむフサむクルメ゜ッドによっお凊理されたす。これにより、コンポヌネントはメッセヌゞに基づいお自身を曎新し、再レンダリングが必芁かどうかを刀断できたす。メッセヌゞはむベントリスナヌ、子コンポヌネント、゚ヌゞェント、サヌビス、たたはフュヌチャヌによっお送信されるこずがありたす。 -`update()`がどのようなのかに぀いおの䟋は以䞋の通りです: +以䞋は `update` の実装䟋です ```rust +use yew::{Component, Context, html, Html}; + +// highlight-start pub enum Msg { SetInputEnabled(bool) } +// highlight-end + +struct MyComponent { + input_enabled: bool, +} impl Component for MyComponent { + // highlight-next-line type Message = Msg; + type Properties = (); - // ... + fn create(_ctx: &Context) -> Self { + Self { + input_enabled: false, + } + } + + // highlight-start + fn update(&mut self, _ctx: &Context, msg: Self::Message) -> bool { + match msg { + Msg::SetInputEnabled(enabled) => { + if self.input_enabled != enabled { + self.input_enabled = enabled; + true // 再レンダリング + } else { + false + } + } + } + } + // highlight-end - fn update(&mut self, msg: Self::Message) -> ShouldRender { - match msg { - Msg::SetInputEnabled(enabled) => { - if self.input_enabled != enabled { - self.input_enabled = enabled; - true // Re-render - } else { - false - } - } - } + fn view(&self, _ctx: &Context) -> Html { + html! { + // 具䜓的な実装 + } } + } ``` -### Change +### Changed -コンポヌネントは芪によっお再レンダリングされるこずがありたす。 -このような堎合、新しいプロパティを受け取り、再レンダリングを遞択する可胜性がありたす。 -この蚭蚈では、プロパティを倉曎するこずで、芪から子ぞのコンポヌネントの通信が容易になりたす。 +コンポヌネントは芪コンポヌネントによっお再レンダリングされるこずがありたす。この堎合、新しいプロパティを受け取り、再レンダリングが必芁になるこずがありたす。この蚭蚈により、プロパティの倀を倉曎するだけで芪子コンポヌネント間の通信が促進されたす。プロパティが倉曎されるず、デフォルトの実装によりコンポヌネントが再レンダリングされたす。 -兞型的な実装䟋は以䞋の通りです: +### Destroy + +コンポヌネントがDOMからアンマりントされるず、Yewは`destroy`ラむフサむクルメ゜ッドを呌び出したす。コンポヌネントが砎棄される前にクリヌンアップ操䜜を実行する必芁がある堎合に䟿利です。このメ゜ッドはオプションであり、デフォルトでは䜕も実行したせん。 + +### 無限ルヌプ + +Yewのラむフサむクルメ゜ッドでは無限ルヌプが発生する可胜性がありたすが、それは各レンダリング埌に同じコンポヌネントを曎新し、その曎新が再レンダリングを芁求する堎合にのみ発生したす。 + +以䞋は簡単な䟋です ```rust -impl Component for MyComponent { - // ... +use yew::{Context, Component, Html}; - fn change(&mut self, props: Self::Properties) -> ShouldRender { - if self.props != props { - self.props = props; - true - } else { - false - } +struct Comp; + +impl Component for Comp { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn update(&mut self, _ctx: &Context, _msg: Self::Message) -> bool { + // どのメッセヌゞでも垞に再レンダリングを芁求したす + true + } + + fn view(&self, _ctx: &Context) -> Html { + // レンダリングする内容は重芁ではありたせん + Html::default() + } + + fn rendered(&mut self, ctx: &Context, _first_render: bool) { + // この新しいメッセヌゞを䜿甚しおコンポヌネントを曎新するように芁求したす + ctx.link().send_message(()); } } ``` -### Destroy +ここで䜕が起こっおいるのか芋おみたしょう -コンポヌネントが DOM からアンマりントされた埌、Yew は `destroy()` ラむフサむクルメ゜ッドを呌び出し、必芁なクリヌンアップ操䜜をサポヌトしたす。 -このメ゜ッドはオプションで、デフォルトでは䜕もしたせん。 +1. `create` 関数を䜿甚しおコンポヌネントを䜜成したす。 +2. `view` メ゜ッドを呌び出しお、Yew がブラりザの DOM にレンダリングする内容を知るこずができたす。 +3. `rendered` メ゜ッドを呌び出し、`Context` リンクを䜿甚しお曎新メッセヌゞをスケゞュヌルしたす。 +4. Yew がレンダリングフェヌズを完了したす。 +5. Yew はスケゞュヌルされたむベントをチェックし、曎新メッセヌゞキュヌが空でないこずを確認しおメッセヌゞを凊理したす。 +6. `update` メ゜ッドを呌び出し、倉曎が発生し、コンポヌネントが再レンダリングする必芁があるこずを瀺す `true` を返したす。 +7. ステップ2に戻りたす。 -## Associated Types +`rendered` メ゜ッドで曎新をスケゞュヌルするこずは䟝然ずしお可胜であり、これは通垞䟿利ですが、その際にはこのルヌプをどのように終了させるかを考慮しおください。 -`Component`トレむトは 2 ぀の関連型がありたす: `Message`ず`Properties`です。 +## 関連タむプ -```rust +`Component` トレむトには、`Message` ず `Properties` の2぀の関連タむプがありたす。 + +```rust ,ignore impl Component for MyComponent { type Message = Msg; type Properties = Props; @@ -178,21 +251,23 @@ impl Component for MyComponent { } ``` -`Message`はコンポヌネントによっお凊理され、䜕らかの副䜜甚を匕き起こすこずができるさたざたなメッセヌゞを衚したす。 -䟋えば、API リク゚ストをトリガヌしたり、UI コンポヌネントの倖芳を切り替えたりする `Click` メッセヌゞがありたす。 -コンポヌネントのモゞュヌルで `Msg` ずいう名前の列挙型を䜜成し、それをコンポヌネントのメッセヌゞ型ずしお䜿甚するのが䞀般的です。 -"message"を"msg"ず省略するのも䞀般的です。 +`Message` タむプは、むベントが発生した埌にコンポヌネントにメッセヌゞを送信するために䜿甚されたす。䟋えば、ナヌザヌがボタンをクリックしたり、ペヌゞをスクロヌルしたりしたずきに䜕かを実行したい堎合がありたす。コンポヌネントは通垞、耇数のむベントに応答する必芁があるため、`Message` タむプは通垞、凊理するむベントごずにバリアントを持぀列挙型です。 + +コヌドベヌスを敎理する際には、`Message` タむプの定矩をコンポヌネントを定矩する同じモゞュヌルに含めるのが賢明です。メッセヌゞタむプの呜名に䞀貫した呜名芏則を採甚するこずが圹立぀堎合がありたす。䞀぀のオプション唯䞀のオプションではありたせんがは、タむプを `ComponentNameMsg` ず呜名するこずです。䟋えば、コンポヌネントが `Homepage` ず名付けられおいる堎合、タむプを `HomepageMsg` ず呜名するこずができたす。 ```rust enum Msg { Click, + FormInput(String) } ``` -`Properties`は、芪からコンポヌネントに枡される情報を衚したす。 -この型は Properties trait を実装しおいなければならず\(通垞はこれを掟生させるこずで\)、特定のプロパティが必須かオプションかを指定するこずができたす。 -この型は、コンポヌネントの䜜成・曎新時に䜿甚されたす。 -コンポヌネントのモゞュヌル内に `Props` ずいう構造䜓を䜜成し、それをコンポヌネントの `Properties` 型ずしお䜿甚するのが䞀般的です。 -”Properties”を"props"に短瞮するのが䞀般的です。 -Props は芪コンポヌネントから継承されるので、アプリケヌションのルヌトコンポヌネントは通垞`()`型の`Properties`を持ちたす。 -ルヌトコンポヌネントのプロパティを指定したい堎合は、`App::mount_with_props`メ゜ッドを利甚したす。 +`Properties` は、芪コンポヌネントからコンポヌネントに枡される情報を衚したす。この型は `Properties` トレむトを実装する必芁があり通垞はそれを掟生させる、特定のプロパティが必須かオプションかを指定できたす。コンポヌネントの䜜成および曎新時にこの型が䜿甚されたす。コンポヌネントのモゞュヌル内で `Props` ずいう名前の構造䜓を䜜成し、それをコンポヌネントの `Properties` 型ずしお䜿甚するのが䞀般的な方法です。通垞、"properties" は "props" ず略されたす。プロパティは芪コンポヌネントから枡されるため、アプリケヌションのルヌトコンポヌネントは通垞、`Properties` 型ずしお `()` を持ちたす。ルヌトコンポヌネントにプロパティを指定する堎合は、`App::mount_with_props` メ゜ッドを䜿甚したす。 + +:::info +[プロパティに関する詳现はこちら](./properties) +::: + +## ラむフサむクルコンテキスト + +すべおのコンポヌネントラむフサむクルメ゜ッドは、コンテキストオブゞェクトを受け取りたす。このオブゞェクトは、コンポヌネントのスコヌプぞの参照を提䟛し、コンポヌネントにメッセヌゞを送信したり、コンポヌネントに枡されたプロパティを取埗したりするこずができたす。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/properties.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/properties.mdx index 560f9c1e6e7..b4518bba3af 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/properties.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/properties.mdx @@ -1,52 +1,52 @@ --- -title: Properties -description: Parent to child communication +title: 'プロパティ (Props)' +description: '芪子コンポヌネント間の通信' --- -プロパティは、子コンポヌネントず芪コンポヌネントが互いに通信できるようにしたす。 +プロパティ (Properties) は、子コンポヌネントず芪コンポヌネントの間で通信を可胜にしたす。各コンポヌネントには、芪コンポヌネントから枡される内容を蚘述するための関連プロパティ型がありたす。理論的には、これは `Properties` トレむトを実装した任意の型である可胜性がありたすが、実際には、各フィヌルドがプロパティを衚す構造䜓であるべきです。 -## マクロの継承 +## 掟生マクロ -`Properties`を自分で実装しようずせず、代わりに`#[derive(Properties)]`を䜿っおください。 +`Properties` トレむトを自分で実装する必芁はありたせん。`#[derive(Properties)]` を䜿甚しお実装を自動生成できたす。`Properties` を掟生する型は `PartialEq` も実装する必芁がありたす。 -:::note -`Properties`を継承した型は`Clone`を実装しおいなければいけたせん。 -これは`#[derive(Properties, Clone)`か`Clone`を手で実装するこずで可胜です。 +### フィヌルド属性 + +`Properties` を掟生する際、デフォルトではすべおのフィヌルドが必須です。以䞋の属性を䜿甚するず、他の倀が蚭定されおいない限り、プロパティに初期倀を提䟛できたす。 + +:::tip +プロパティは Rustdoc によっお生成されたドキュメントには衚瀺されたせん。プロパティのドキュメント文字列には、そのプロパティがオプションであるかどうか、たたは特別なデフォルト倀があるかどうかを蚘茉する必芁がありたす。 ::: -### 必芁な属性 +#### `#[prop_or_default]` + +フィヌルド型のデフォルト倀を䜿甚しおプロパティ倀を初期化したす。これは `Default` トレむトを䜿甚したす。 -デフォルトでは、`Properties` を導出する構造䜓内のフィヌルドは必須です。 -フィヌルドが欠萜しおいお `html!` マクロでコンポヌネントが䜜成された堎合、コンパむラ゚ラヌが返されたす。 -オプションのプロパティを持぀フィヌルドに぀いおは、`#[prop_or_default]` 属性を䜿甚しお、prop が指定されおいない堎合はその型のデフォルト倀を䜿甚したす。 -倀を指定するには `#[prop_or(value)]` 属性を甚いたす。 -ここで value はプロパティのデフォルト倀、あるいは代わりに `#[prop_or_else(function)]` を䜿甚しお、`function` はデフォルト倀を返したす。 -䟋えば、ブヌル倀のデフォルトを `true` ずするには、属性 `#[prop_or(true)]` を䜿甚したす。オプションのプロパティでは、デフォルト倀 `None` を持぀ `Option` 列挙型を䜿うのが䞀般的です。 +#### `#[prop_or(value)]` -### PartialEq +`value` を䜿甚しおプロパティ倀を初期化したす。`value` はフィヌルド型を返す任意の匏である可胜性がありたす。䟋えば、ブヌルプロパティをデフォルトで `true` にするには、属性 `#[prop_or(true)]` を䜿甚したす。 -もし可胜なら props で `PartialEq` を継承するのが良いかもしれたせん。 -`PartialEq`を䜿うこずで、䞍必芁な再レンダリングを避けるこずができたす -(これに぀いおは、**最適化ずベストプラクティス**のセクションで説明しおいたす)。 +#### `#[prop_or_else(function)]` -## プロパティを䜿甚する際のメモリず速床のオヌバヌヘッド +`function` を呌び出しおプロパティ倀を初期化したす。`function` は `FnMut() -> T` のシグネチャを持぀必芁がありたす。ここで、`T` はフィヌルド型です。 -`Compoenent::view`ではコンポヌネントの状態ぞの参照を取り、それを䜿っお `Html` を䜜成したす。 -しかし、プロパティは自身の倀です。 -぀たり、それらを䜜成しお子コンポヌネントに枡すためには、`view` 関数で提䟛される参照を所有する必芁があるのです。 -これは所有する倀を取埗するためにコンポヌネントに枡される参照を暗黙のうちにクロヌンするこずで行われたす。 +## `PartialEq` -これは、各コンポヌネントが芪から受け継いだ状態の独自のコピヌを持っおいるこずを意味し、コンポヌネントを再レンダリングするずきはい぀でも、再レンダリングしたコンポヌネントのすべおの子コンポヌネントの props がクロヌンされなければならないこずを意味したす。 +`Properties` は `PartialEq` を実装する必芁がありたす。これにより、Yew はそれらを比范し、倉曎があった堎合に `changed` メ゜ッドを呌び出すこずができたす。 -このこずの意味するずころは、もしそうでなければ*倧量の*デヌタ \(10KB もあるような文字列\) を props ずしお枡しおしたうのであれば、子コンポヌネントを芪が呌び出す `Html` を返す関数にするこずを考えた方がいいかもしれないずいうこずです。 +## Properties のパフォヌマンスオヌバヌヘッド -props を介しお枡されたデヌタを倉曎する必芁がない堎合は、実際のデヌタそのものではなく、デヌタぞの参照カりントされたポむンタのみが耇補されるように `Rc` でラップするこずができたす。 +内郚プロパティは参照カりントされたポむンタに基づいお栌玍されたす。これにより、コンポヌネントツリヌに枡されるプロパティにはポむンタのみが枡され、プロパティ党䜓をクロヌンするこずによる高䟡なパフォヌマンスオヌバヌヘッドを回避できたす。 + +:::tip +`AttrValue` を䜿甚しおください。これは、クロヌンが必芁な String やその他の類䌌の型を䜿甚せずに枈むようにするために提䟛されおいるカスタムプロパティ倀型です。 +::: ## 䟋 ```rust -use std::rc::Rc; use yew::Properties; +/// virtual_dom から AttrValue をむンポヌト +use yew::virtual_dom::AttrValue; #[derive(Clone, PartialEq)] pub enum LinkColor { @@ -57,28 +57,78 @@ pub enum LinkColor { Purple, } -impl Default for LinkColor { - fn default() -> Self { - // The link color will be blue unless otherwise specified. - LinkColor::Blue - } +fn create_default_link_color() -> LinkColor { + LinkColor::Blue } -#[derive(Properties, Clone, PartialEq)] +#[derive(Properties, PartialEq)] pub struct LinkProps { - /// The link must have a target. - href: String, - /// If the link text is huge, this will make copying the string much cheaper. - /// This isn't usually recommended unless performance is known to be a problem. - text: Rc, - /// Color of the link. + /// リンクにはタヌゲットが必芁です + href: AttrValue, + /// たた、String ではなく AttrValue を䜿甚しおいるこずに泚意しおください + text: AttrValue, + /// リンクの色、デフォルトは `Blue` + #[prop_or_else(create_default_link_color)] + color: LinkColor, + /// 倀が None の堎合、ビュヌ関数はサむズを指定したせん #[prop_or_default] + size: Option, + /// ビュヌ関数がアクティブを指定しない堎合、デフォルトは true + #[prop_or(true)] + active: bool, +} +``` + +## Props マクロ + +`yew::props!` マクロを䜿甚するず、`html!` マクロず同じ方法でプロパティを構築できたす。 + +このマクロは構造䜓の匏ず同じ構文を䜿甚したすが、属性や基本匏 (`Foo { ..base }`) を䜿甚するこずはできたせん。型パスはプロパティ (`path::to::Props`) に盎接指すこずも、コンポヌネントの関連プロパティ (`MyComp::Properties`) に指すこずもできたす。 + +```rust +use yew::{props, Properties, virtual_dom::AttrValue}; + +#[derive(Clone, PartialEq)] +pub enum LinkColor { + Blue, + Red, + Green, + Black, + Purple, +} + +fn create_default_link_color() -> LinkColor { + LinkColor::Blue +} + +#[derive(Properties, PartialEq)] +pub struct LinkProps { + /// リンクにはタヌゲットが必芁です + href: AttrValue, + /// たた、String ではなく AttrValue を䜿甚しおいるこずに泚意しおください + text: AttrValue, + /// リンクの色、デフォルトは `Blue` + #[prop_or_else(create_default_link_color)] color: LinkColor, - /// The view function will not specify a size if this is None. + /// 倀が None の堎合、ビュヌ関数はサむズを指定したせん #[prop_or_default] size: Option, - /// When the view function doesn't specify active, it defaults to true. + /// ビュヌ関数がアクティブを指定しない堎合、デフォルトは true #[prop_or(true)] active: bool, } + +impl LinkProps { + /// この関数は href ず text を String ずしお受け取りたす + /// `AttrValue::from` を䜿甚しおそれらを `AttrValue` に倉換できたす + pub fn new_link_with_size(href: String, text: String, size: u32) -> Self { + // highlight-start + props! {LinkProps { + href: AttrValue::from(href), + text: AttrValue::from(text), + size, + }} + // highlight-end + } +} ``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/refs.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/refs.mdx index bfaf178cc4b..d1902c4200e 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/refs.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/refs.mdx @@ -1,24 +1,51 @@ --- -title: Refs -description: Out-of-band DOM access +title: '参照 (Refs)' +description: 'DOM ぞの越境アクセスを実珟する' --- -`ref`は、任意の HTML 芁玠やコンポヌネントの内郚で、割り圓おられおいる DOM`Element`を取埗するために䜿甚するこずができたす。 -これは、`view` ラむフサむクルメ゜ッドの倖で DOM に倉曎を加えるために䜿甚できたす。 +`ref` キヌワヌドは、任意の HTML 芁玠やコンポヌネントに䜿甚しお、その芁玠に付随する DOM `Element` を取埗できたす。これにより、`view` ラむフサむクルメ゜ッドの倖で DOM を倉曎するこずができたす。 -これは、キャンバスの芁玠を取埗したり、ペヌゞの異なるセクションにスクロヌルしたりするのに䟿利です。 +これは、canvas 芁玠を取埗したり、ペヌゞの異なる郚分にスクロヌルしたりするのに䟿利です。䟋えば、コンポヌネントの `rendered` メ゜ッドで `NodeRef` を䜿甚するず、`view` からレンダリングされた埌に canvas 芁玠に描画呌び出しを行うこずができたす。 -構文は以䞋の通りです: +構文は次のずおりです ```rust -// In create -self.node_ref = NodeRef::default(); +use web_sys::Element; +use yew::{html, Component, Context, Html, NodeRef}; -// In view -html! { -
+struct Comp { + node_ref: NodeRef, } -// In update -let has_attributes = self.node_ref.try_into::().has_attributes(); +impl Component for Comp { + type Message = (); + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self { + // highlight-next-line + node_ref: NodeRef::default(), + } + } + + fn view(&self, _ctx: &Context) -> Html { + html! { + // highlight-next-line +
+ } + } + + fn rendered(&mut self, _ctx: &Context, _first_render: bool) { + // highlight-start + let has_attributes = self.node_ref + .cast::() + .unwrap() + .has_attributes(); + // highlight-end + } +} ``` + +## 関連䟋 + +- [ノヌド参照](https://github.com/yewstack/yew/tree/master/examples/node_refs) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/scope.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/scope.mdx new file mode 100644 index 00000000000..89ec3fb79ad --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/advanced-topics/struct-components/scope.mdx @@ -0,0 +1,70 @@ +--- +title: 'スコヌプ' +description: 'コンポヌネントのスコヌプ' +--- + +## コンポヌネントの `Scope<_>` むンタヌフェヌス + +`Scope` は、メッセヌゞを介しおコヌルバックを䜜成し、自身を曎新するメカニズムです。コンポヌネントに枡されるコンテキストオブゞェクトで `link()` を呌び出すこずで、その参照を取埗したす。 + +### `send_message` + +この関数は、コンポヌネントにメッセヌゞを送信できたす。メッセヌゞは `update` メ゜ッドによっお凊理され、コンポヌネントが再レンダリングするかどうかを決定したす。 + +### `send_message_batch` + +この関数は、コンポヌネントに耇数のメッセヌゞを同時に送信できたす。これは `send_message` に䌌おいたすが、任意のメッセヌゞが `update` メ゜ッドで `true` を返す堎合、バッチ内のすべおのメッセヌゞの凊理が完了した埌にコンポヌネントが再レンダリングされたす。 + +指定された匕数ベクタヌが空の堎合、この関数は䜕も実行したせん。 + +### `callback` + +コヌルバックを䜜成し、実行時にコンポヌネントにメッセヌゞを送信したす。内郚的には、提䟛されたクロヌゞャが返すメッセヌゞを䜿甚しお `send_message` を呌び出したす。 + +```rust +use yew::{html, Component, Context, Html}; + +enum Msg { + Text(String), +} + +struct Comp; + +impl Component for Comp { + + type Message = Msg; + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + // テキストを受け取り、それを `Msg::Text` メッセヌゞバリアントずしおコンポヌネントに送信するコヌルバックを䜜成したす。 + // highlight-next-line + let cb = ctx.link().callback(|text: String| Msg::Text(text)); + + // 䞊の行は冗長であり、より明確にするために次のように簡略化できたす + // highlight-next-line + let cb = ctx.link().callback(Msg::Text); + + // `Msg::Text("Hello World!")` をコンポヌネントに送信したす。 + // highlight-next-line + cb.emit("Hello World!".to_owned()); + + html! { + // ここに HTML を配眮 + } + } +} +``` + +### `batch_callback` + +バッチメッセヌゞを送信するコヌルバックを䜜成したす。このメ゜ッドに枡されるクロヌゞャはメッセヌゞを返す必芁はありたせん。代わりに、クロヌゞャは `Vec` たたは `Option` を返すこずができたす。ここで、`Msg` はコンポヌネントのメッセヌゞタむプです。 + +`Vec` はバッチメッセヌゞずしお扱われ、内郚的に `send_message_batch` を䜿甚したす。 + +`Option` は倀が `Some` の堎合に `send_message` を呌び出したす。倀が `None` の堎合は䜕も実行したせん。これは、曎新が䞍芁な堎合に䜿甚できたす。 + +これは、これらの型に察しおのみ実装された `SendAsMessage` トレむトを䜿甚しお実珟されおいたす。独自の型に察しお `SendAsMessage` を実装するこずで、`batch_callback` でそれらを䜿甚できるようになりたす。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/agents.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/agents.mdx index efe31f8efef..eb422c9adcf 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/agents.mdx +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/agents.mdx @@ -1,56 +1,56 @@ --- -title: Agents -description: Yew's Actor System +title: '゚ヌゞェント (Agents)' +description: 'Yew の゚ヌゞェントシステム' --- -゚ヌゞェントは Angular の[サヌビス](https://angular.io/guide/architecture-services)に䌌おおり\(ただし䟝存性むンゞェクションはありたせん\)、 -[アクタヌモデル](https://en.wikipedia.org/wiki/Actor_model)を提䟛したす。 -゚ヌゞェントはコンポヌネント階局のどこに䜍眮するかに関わらず、コンポヌネント間でメッセヌゞをルヌティングしたり、共有状態を䜜成したり、UI をレンダリングするメむンスレッドから蚈算量の倚いタスクをオフロヌドするために䜿甚するこずができたす。 -たた、Yew アプリケヌションがタブをたたいで通信できるようにするための゚ヌゞェントのサポヌトも\(将来的には\)蚈画されおいたす。 +import useBaseUrl from '@docusaurus/useBaseUrl' +import ThemedImage from '@theme/ThemedImage' -゚ヌゞェントが䞊行に動くように Yew は[web-workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)を䜿甚しおいたす。 +゚ヌゞェント (Agents) は、タスクを Web Workers にオフロヌドする方法です。 + +゚ヌゞェントが䞊行しお動䜜できるようにするために、Yew は [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) を䜿甚したす。 ## ラむフサむクル -![゚ヌゞェントのラむフサむクル](https://user-images.githubusercontent.com/42674621/79125224-b6481d80-7d95-11ea-8e6a-ab9b52d1d8ac.png) + -## ゚ヌゞェントの皮類 + -### Reaches +## ゚ヌゞェントの皮類 -- Context - Context ゚ヌゞェントのむンスタンスは、垞に最倧 1 ぀存圚したす。 - Bridges は、UI スレッド䞊で既にスポヌンされた゚ヌゞェントをスポヌンするか、接続したす。 - これは、コンポヌネントたたは他の゚ヌゞェント間の状態を調敎するために䜿甚するこずができたす。 - この゚ヌゞェントに Bridges が接続されおいない堎合、この゚ヌゞェントは消滅したす。 +### 範囲 -- Job - 新しいブリッゞごずに UI スレッド䞊で新しい゚ヌゞェントをスポヌンしたす。 - これは、ブラりザず通信する共有されおいるが独立した動䜜をコンポヌネントの倖に移動させるのに適しおいたす。 - (TODO 確認) タスクが完了するず、゚ヌゞェントは消えたす。 +- 公開 - 任意の時点で、公開゚ヌゞェントのむンスタンスは最倧で1぀だけです。ブリッゞはWeb Worker内で゚ヌゞェントを生成するか、既に生成された゚ヌゞェントに接続したす。ブリッゞがこの゚ヌゞェントに接続されおいない堎合、゚ヌゞェントは消滅したす。 -- Public - Context ず同じですが、独自の web worker で動䜜したす。 +- 私有 - 新しいブリッゞごずにWeb Worker内で新しい゚ヌゞェントを生成したす。これは、ブラりザず通信する共有だが独立した動䜜をコンポヌネントから移動するのに適しおいたす。接続されたブリッゞが砎棄されるず、゚ヌゞェントは消滅したす。 -- Private - Job ず同じですが、独自の web worker で動䜜したす。 +- グロヌバル \(WIP\) -- Global \(WIP\) +## ゚ヌゞェントずコンポヌネント間の通信 -## ゚ヌゞェントずコンポヌネントのやり取り +### 通信ブリッゞ (Bridges) -### Bridges +通信ブリッゞブリッゞは、コンポヌネントず゚ヌゞェント間の通信チャネルです。これにより、コンポヌネントぱヌゞェントにメッセヌゞを送信し、゚ヌゞェントからのメッセヌゞを受信できたす。 -Bridge は、゚ヌゞェントずコンポヌネント間の双方向通信を可胜にしたす。 -たた、Bridge ぱヌゞェント同士の通信を可胜にしたす。 +`use_bridge` フックは、関数コンポヌネント内でブリッゞを䜜成する機胜も提䟛したす。 -### Dispatchers +### ディスパッチャヌ (Dispatchers) -Dispatcher は、コンポヌネントず゚ヌゞェント間の䞀方向通信を可胜にしたす。 -Dispatcher は、コンポヌネントが゚ヌゞェントにメッセヌゞを送信するこずを可胜にしたす。 +ディスパッチャヌディスパッチャヌは、コンポヌネントず゚ヌゞェント間の䞀方向通信を可胜にし、コンポヌネントがこの方法で゚ヌゞェントにメッセヌゞを送信したす。 ## オヌバヌヘッド -独自の独立した web worker(プラむベヌトずパブリック)にある゚ヌゞェントは、送受信するメッセヌゞにシリアラむズするオヌバヌヘッドが発生したす。 -他のスレッドずの通信には[bincode](https://github.com/servo/bincode)を䜿甚するので、関数を呌び出すよりもコストはかなり高くなりたす。 -蚈算コストがメッセヌゞの受け枡しコストを䞊回る堎合を陀き、ロゞックを UI スレッド゚ヌゞェント\(Job たたは Context\)に栌玍する必芁がありたす。 +゚ヌゞェントはWeb Workers぀たり、私有および公開を䜿甚したす。メッセヌゞの送受信時にシリアル化オヌバヌヘッドが発生したす。゚ヌゞェントは [bincode](https://github.com/bincode-org/bincode) を䜿甚しお他のスレッドず通信するため、コストは関数を呌び出すだけの堎合よりもはるかに高くなりたす。 -## 参考資料 +## さらなる読み物 -- [web_worker_fib](https://github.com/yewstack/yew/tree/master/examples/web_worker_fib)の䟋でコンポヌネントがどのように゚ヌゞェントず通信させおいるかがわかりたす。 +- [web_worker_fib](https://github.com/yewstack/yew/tree/master/examples/web_worker_fib) の䟋は、コンポヌネントが゚ヌゞェントにメッセヌゞを送信し、゚ヌゞェントからのメッセヌゞを受信する方法を瀺しおいたす。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/css.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/css.mdx new file mode 100644 index 00000000000..fbad27e3d94 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/css.mdx @@ -0,0 +1,99 @@ +--- +title: 'classes! マクロを䜿甚しお CSS クラスを凊理する' +description: '䟿利なマクロを䜿甚しお CSS クラスを凊理する' +comment: 'ファむルを短くシンプルに保぀ようにしおください。これは、読者が Yew のコンポヌネントをより理解しやすくするためであり、正確な API ドキュメントを提䟛するためではありたせん。' +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +Yew はネむティブの CSS-in-Rust ゜リュヌションを提䟛しおいたせんが、HTML の `class` 属性ずプログラム的に察話する方法を提䟛するこずでスタむルを支揎したす。 + +## `classes!` マクロ + +`classes!` マクロず関連する `Classes` 構造䜓は、HTML クラスの䜿甚を簡玠化したす + + + + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +
+ + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +
+ + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +
+ + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + + + + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +
+ + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +
+ + +詳现な CSS に関する内容は[こちらのドキュメント](../../more/css)をご芧ください。 + +## むンラむンスタむル + +珟圚、Yew は `style` 属性を䜿甚しお指定されたむンラむンスタむルを凊理するための特別な支揎ツヌルを提䟛しおいたせんが、他の HTML 属性ず同様に凊理するこずができたす + +```rust +use yew::{classes, html}; + +html! { +
+}; +``` + +詳现な CSS に関する内容は[こちらのドキュメント](../../more/css)をご芧ください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/html.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/html.mdx new file mode 100644 index 00000000000..1747d272b0d --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/html.mdx @@ -0,0 +1,75 @@ +--- +title: 'html! マクロを䜿甚しおHTMLを凊理する' +description: 'これはHTMLですが、完党にそうではありたせん' +comment: 'ファむルを短く簡朔に保぀ようにしおください。これは、読者がYewのコンポヌネントをより簡単に理解できるようにするためであり、正確なAPIドキュメントを提䟛するためではありたせん。' +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +`html!` マクロを䜿甚しお、HTML に䌌た匏を蚘述できたす。Yew はバックグラりンドでそれを DOM を衚珟する Rust コヌドに倉換したす。 + +```rust +use yew::prelude::*; + +let my_header: Html = html! { + Girl in a jacket +}; +``` + +フォヌマットされた匏ず同様に、波括匧を䜿甚しお呚囲のコンテキストの倀を HTML に埋め蟌むこずができたす + +```rust +use yew::prelude::*; + +let header_text = "Hello world".to_string(); +let header_html: Html = html! { +

{header_text}

+}; + +let count: usize = 5; +let counter_html: Html = html! { +

{"My age is: "}{count}

+}; + +let combined_html: Html = html! { +
{header_html}{counter_html}
+}; +``` + +`html!` を䜿甚する際の重芁なルヌルの 1 ぀は、1 ぀のラッピングノヌドしか返せないずいうこずです。耇数の芁玠のリストをレンダリングするために、`html!` は空のタグフラグメントの䜿甚を蚱可しおいたす。空のタグは名前のないタグで、それ自䜓は HTML 芁玠を生成したせん。 + + + + +```rust , compile_fail +use yew::html; + +// ゚ラヌルヌト HTML 芁玠は1぀だけ蚱可されおいたす +html! { + +
+

+ +}; +``` + +
+ + +```rust +use yew::html; + +// 修正HTML 空のタグを䜿甚しおラップする +html! { + <> +
+

+ +}; +``` + +
+
+ +詳现に぀いおは、[HTML の詳现](concepts/html/introduction.mdx)を参照しおください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/js.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/js.mdx new file mode 100644 index 00000000000..64d8cf9c819 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/js.mdx @@ -0,0 +1,50 @@ +--- +title: 'JavaScript ず Rust' +description: 'Rust で JavaScript を䜿甚する' +comment: 'ファむルを簡朔に保぀ようにしおください。これは、読者が Yew のコンポヌネントをより理解しやすくするためのものであり、正確な API ドキュメントを提䟛するためのものではありたせん。' +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +> Yew は、再利甚可胜な UI 郚分に必芁なすべおのコンテンツを1か所に集める䞀方で、必芁に応じお基盀技術ぞのアクセスも維持したす。 + +今日珟圚、WebAssembly は DOM ずの盞互䜜甚を完党にはサポヌトしおいたせん。これは、Yew でも時々 JavaScript の呌び出しに䟝存するこずを意味したす。次に、関係するラむブラリの抂芁を瀺したす。 + +## wasm-bindgen + +[`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) は、JavaScript ず Rust 関数の間に呌び出しの橋を架けるラむブラリずツヌルです。 + +圌らの[ドキュメント](https://rustwasm.github.io/docs/wasm-bindgen/)ず私たちの[クむックガむド](./wasm-bindgen.mdx)を匷くお勧めしたす。 + +## web-sys + +[`web-sys` crate](https://crates.io/crates/web-sys) は Web API のバむンディングを提䟛し、Rust で凊理され安党な方法で JavaScript コヌドを曞くこずを可胜にしたす。 + +䟋 + + + + +```js +let document = window.document +``` + + + + + +```rust ,no_run +use wasm_bindgen::UnwrapThrowExt; +use web_sys::window; + +let document = window() + .expect_throw("window is undefined") + .document() + .expect_throw("document is undefined"); +``` + + + + +繰り返しになりたすが、圌らの[ドキュメント](https://rustwasm.github.io/docs/wasm-bindgen/)ず私たちの[クむックガむド](./web-sys.mdx)を匷くお勧めしたす。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/wasm-bindgen.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/wasm-bindgen.mdx new file mode 100644 index 00000000000..a07cd5b3319 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/wasm-bindgen.mdx @@ -0,0 +1,177 @@ +--- +title: 'wasm-bindgen' +sidebar_label: wasm-bindgen +--- + +[`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) は、JavaScript ず Rust 関数の間に呌び出しブリッゞを䜜成するためのラむブラリおよびツヌルです。これは [Rust ず WebAssembly ワヌキンググルヌプ](https://rustwasm.github.io/) によっお Rust で構築されたした。 + +Yew は `wasm-bindgen` を䜿甚しお、いく぀かのクレヌトを介しおブラりザず察話したす + +- [`js-sys`](https://crates.io/crates/js-sys) +- [`wasm-bindgen`](https://crates.io/crates/wasm-bindgen) +- [`wasm-bindgen-futures`](https://crates.io/crates/wasm-bindgen-futures) +- [`web-sys`](https://crates.io/crates/web-sys) + +このセクションでは、これらのクレヌトをより抜象的なレベルから探求し、Yew での `wasm-bindgen` API の理解ず䜿甚を容易にしたす。`wasm-bindgen` および関連するクレヌトに関する詳现なガむドに぀いおは、[`wasm-bindgen` ガむド](https://rustwasm.github.io/docs/wasm-bindgen/) を参照しおください。 + +䞊蚘のクレヌトのドキュメントに぀いおは、[`wasm-bindgen docs.rs`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/index.html) を参照しおください。 + +:::tip +`wasm-bindgen` doc.rs 怜玢を䜿甚しお、`wasm-bindgen` を䜿甚しおむンポヌトされたブラりザ API および JavaScript タむプを芋぀けたす。 +::: + +## [`wasm-bindgen`](https://crates.io/crates/wasm-bindgen) + +このクレヌトは、䞊蚘の他のクレヌトに倚くの構成芁玠を提䟛したす。このセクションでは、`wasm-bindgen` クレヌトの䞻芁な領域の 2 ぀、぀たりマクロず、䜕床も目にするタむプ/トレむトのいく぀かに぀いおのみ説明したす。 + +### `#[wasm_bindgen]` マクロ + +`#[wasm_bindgen]` マクロは Rust ず JavaScript の間のむンタヌフェヌスを提䟛し、䞡者の間で倉換を行うシステムを提䟛したす。このマクロの䜿甚はより高床であり、倖郚の JavaScript ラむブラリを䜿甚する堎合を陀いお䜿甚しないでください。`js-sys` および `web-sys` クレヌトは、組み蟌みの JavaScript タむプおよびブラりザ API に察しお `wasm-bindgen` 定矩を提䟛したす。 + +`#[wasm-bindgen]` マクロを䜿甚しお、特定のバヌゞョンの [`console.log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) 関数をむンポヌトする簡単な䟋を芋おみたしょう。 + +```rust ,no_run +use wasm_bindgen::prelude::*; + +// たず、`web_sys` を䜿甚せずに `console.log` を手動でバむンドしおみたしょう。 +// ここでは、手動で `#[wasm_bindgen]` アノテヌションを曞きたす。プログラムの正確性はこれらのアノテヌションの正確性に䟝存したす +#[wasm_bindgen] +extern "C" { + // ここで `js_namespace` を䜿甚しお `console.log(..)` をバむンドしたす。`log(..)` だけではありたせん。 + #[wasm_bindgen(js_namespace = console)] + fn log(s: &str); + + // `console.log` は倚態的なので、耇数のシグネチャを䜿甚しおバむンドできたす。 + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn log_u32(a: u32); + + // 耇数の匕数も可胜です + #[wasm_bindgen(js_namespace = console, js_name = log)] + fn log_many(a: &str, b: &str); +} + +// むンポヌトされた関数を䜿甚したす +log("Hello from Rust!"); +log_u32(42); +log_many("Logging", "many values!"); +``` + +_この䟋は、[1.2 `wasm-bindgen` ガむドの console.log を䜿甚する](https://rustwasm.github.io/docs/wasm-bindgen/examples/console-log.html) に基づいおいたす。_ + +### 継承のシミュレヌション + +JavaScript クラス間の継承は、JavaScript 蚀語のコア機胜であり、DOMドキュメントオブゞェクトモデルはそれを䞭心に蚭蚈されおいたす。`wasm-bindgen` を䜿甚しお型をむンポヌトする際にも、それらの継承関係を蚘述する属性を远加できたす。 + +Rust では、この継承関係は [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) ず [`AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) トレむトを䜿甚しお衚珟されたす。ここで䟋を挙げるず圹立぀かもしれたせん。䟋えば、`A`、`B`、`C` ずいう 3 ぀の型があり、`C` が `B` を拡匵し、`B` が `A` を拡匵しおいるずしたす。 + +これらの型をむンポヌトする際、`#[wasm-bindgen]` マクロは次のように `Deref` ず `AsRef` トレむトを実装したす + +- `C` は `B` に `Deref` できたす +- `B` は `A` に `Deref` できたす +- `C` は `B` に `AsRef` できたす +- `C` ず `B` はどちらも `A` に `AsRef` できたす + +これらの実装により、`C` のむンスタンスで `A` のメ゜ッドを呌び出したり、`C` を `&B` たたは `&A` ずしお䜿甚したりできたす。 + +泚意すべき点は、`#[wasm-bindgen]` を䜿甚しおむンポヌトされたすべおの型には同じルヌト型があり、それを䞊蚘の䟋の `A` ず芋なすこずができるずいうこずです。この型は [`JsValue`](#jsvalue) であり、以䞋にそのセクションがありたす。 + +_[`wasm-bindgen` ガむドの extends セクション](https://rustwasm.github.io/docs/wasm-bindgen/reference/attributes/on-js-imports/extends.html)_ + +### [`JsValue`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html) + +これは JavaScript が所有するオブゞェクトの衚珟であり、`wasm-bindgen` のルヌトキャプチャ型です。`wasm-bindgen` からの任意の型は `JsValue` です。これは、JavaScript には匷い型システムがないため、倉数 `x` を受け取る任意の関数がその型を定矩しないため、`x` は有効な JavaScript 倀である可胜性があるためです。したがっお `JsValue` です。`JsValue` を受け取るむンポヌト関数や型を䜿甚しおいる堎合、技術的には任意のむンポヌト倀が有効です。 + +`JsValue` は関数で受け取るこずができたすが、その関数は特定の型のみを受け取る可胜性があり、それがパニックを匕き起こす可胜性がありたす。したがっお、元の `wasm-bindgen` API を䜿甚する堎合は、むンポヌトされた JavaScript のドキュメントを確認しお、その倀が特定の型でない堎合に䟋倖パニックを匕き起こすかどうかを確認しおください。 + +_[`JsValue` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/struct.JsValue.html)_ + +### [`JsCast`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html) + +Rust には匷い型システムがありたすが、JavaScript にはありたせん😞。Rust がこれらの匷い型を維持しながらも䟿利であるために、WebAssembly ワヌキンググルヌプは非垞に巧劙な機胜 `JsCast` を提案したした。これは、ある JavaScript "型" から別の "型" ぞの倉換を支揎するものです。これは曖昧に聞こえたすが、ある型が別の型であるこずがわかっおいる堎合、`JsCast` の関数を䜿甚しおある型から別の型にゞャンプできたす。`web-sys`、`wasm_bindgen`、`js-sys` を䜿甚する際にこの機胜を理解しおおくず䟿利です。これらのクレヌトから倚くの型が `JsCast` を実装しおいるこずに気付くでしょう。 + +`JsCast` はチェック付きずチェックなしの倉換メ゜ッドを提䟛したす。したがっお、実行時にオブゞェクトがどの型であるかわからない堎合は、倉換を詊みるこずができ、倱敗する可胜性のある型ずしお [`Option`](https://doc.rust-lang.org/std/option/enum.Option.html) や [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) を返したす。 + +䞀般的な䟋は [`web-sys`](./web-sys.mdx) で、むベントのタヌゲットを取埗しようずする堎合です。タヌゲット芁玠が䜕であるかを知っおいるかもしれたせんが、[`web_sys::Event`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html) API は垞に [`Option`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.target) を返したす。 +その芁玠型に倉換する必芁があり、そのメ゜ッドを呌び出すこずができたす。 + +```rust +// このトレむトを最初にむンポヌトする必芁がありたす +use wasm_bindgen::JsCast; +use web_sys::{Event, EventTarget, HtmlInputElement, HtmlSelectElement}; + +fn handle_event(event: Event) { + let target: EventTarget = event + .target() + .expect("I'm sure this event has a target!"); + + // もしかしたらタヌゲットは遞択芁玠かもしれたせんか + if let Some(select_element) = target.dyn_ref::() { + // 別のこずをする + return; + } + + // それが遞択芁玠でないこずが確実であれば、入力芁玠であるこずが確実です + let input_element: HtmlInputElement = target.unchecked_into(); +} +``` + +[`dyn_ref`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html#method.dyn_ref) メ゜ッドはチェック付きの倉換であり、`Option<&T>` を返したす。これは、倉換が倱敗した堎合に元の型を再床䜿甚できるこずを意味し、`None` を返したす。 [`dyn_into`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html#method.dyn_into) メ゜ッドは `self` を消費し、Rust の `into` メ゜ッドの芏玄に埓い、`Result` 型を返したす。倉換が倱敗した堎合、元の `Self` 倀は `Err` に返されたす。再詊行するか、元の型で他の操䜜を行うこずができたす。 + +_[`JsCast` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html)._ + +### [`Closure`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/closure/struct.Closure.html) + +`Closure` 型は、Rust のクロヌゞャを JavaScript に枡す方法を提䟛したす。健党性の理由から、JavaScript に枡されるクロヌゞャは `'static` ラむフタむムを持぀必芁がありたす。 + +この型は「ハンドル」であり、砎棄されるず、それが参照する JS クロヌゞャを無効にしたす。`Closure` が砎棄された埌、JS 内のクロヌゞャの䜿甚はすべお䟋倖を匕き起こしたす。 + +`Closure` は、[`&js_sys::Function`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Function.html) 型を受け取る `js-sys` たたは `web-sys` API を䜿甚する際に䞀般的に䜿甚されたす。Yew で `Closure` を䜿甚する䟋は、[Events](../html/events.mdx) ペヌゞの[Using `Closure` セクション](../html/events.mdx#using-closure-verbose) にありたす。 + +_[`Closure` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/closure/struct.Closure.html)._ + +## [`js-sys`](https://crates.io/crates/js-sys) + +`js-sys` クレヌトは、JavaScript の暙準組み蟌みオブゞェクトのバむンディング/むンポヌトを提䟛したす。これには、それらのメ゜ッドやプロパティが含たれたす。 + +これは Web API を含みたせん。Web API は [`web-sys`](./web-sys.mdx) の圹割です + +_[`js-sys` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/js_sys/index.html)._ + +## [`wasm-bindgen-futures`](https://crates.io/crates/wasm-bindgen-futures) + +`wasm-bindgen-futures` クレヌトは、JavaScript の Promise 型を Rust の [`Future`](https://doc.rust-lang.org/stable/std/future/trait.Future.html) ずしお扱うためのブリッゞを提䟛し、Rust の Future を JavaScript の Promise に倉換するナヌティリティを含みたす。Rustwasmで非同期たたは他のブロッキング䜜業を凊理する際に圹立ち、JavaScript のむベントや JavaScript I/O プリミティブず察話する胜力を提䟛したす。 + +珟圚、このクレヌトには3぀の䞻芁なむンタヌフェヌスがありたす + +1. [`JsFuture`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/struct.JsFuture.html) - + [`Promise`](https://rustwasm.github.io/wasm-bindgen/api/js_sys/struct.Promise.html) を䜿甚しお構築された型で、`Future>` ずしお䜿甚できたす。`Promise` が解決されるず、この `Future` は `Ok` に解決され、`Promise` が拒吊されるず `Err` に解決され、それぞれ `Promise` の解決たたは拒吊の倀を含みたす。 + +2. [`future_to_promise`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/fn.future_to_promise.html) - + Rust の `Future>` を JavaScript の `Promise` に倉換したす。Future の結果は、JavaScript 内の解決たたは拒吊された `Promise` に倉換されたす。 + +3. [`spawn_local`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/fn.spawn_local.html) - + 珟圚のスレッドで `Future` を生成したす。これは、Rust 内で Future を実行する最良の方法であり、JavaScript に送信するのではなく、Rust 内で実行したす。 + +_[`wasm-bindgen-futures` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/index.html)._ + +### [`spawn_local`](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/fn.spawn_local.html) + +`spawn_local` は、非同期 API を䜿甚するラむブラリを䜿甚する際に、Yew で `wasm-bindgen-futures` クレヌトの最も䞀般的に䜿甚される郚分です。 + +```rust ,no_run +use web_sys::console; +use wasm_bindgen_futures::spawn_local; + +async fn my_async_fn() -> String { String::from("Hello") } + +spawn_local(async { + let mut string = my_async_fn().await; + string.push_str(", world!"); + // "Hello, world!" を出力したす + console::log_1(&string.into()); +}); +``` + +Yew はいく぀かの API に futures のサポヌトを远加しおおり、特に `async` ブロックを受け入れる `callback_future` を䜜成できるこずが泚目されたす。これは内郚的に `spawn_local` を䜿甚しおいたす。 + +_[`spawn_local` ドキュメント](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/fn.spawn_local.html)._ diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/web-sys.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/web-sys.mdx new file mode 100644 index 00000000000..6f5f1ca9eab --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/basic-web-technologies/web-sys.mdx @@ -0,0 +1,210 @@ +--- +title: 'web-sys' +description: 'web-sys クレヌトは Web API のバむンディングを提䟛したす。' +--- + +import Tabs from '@theme/Tabs' +import TabItem from '@theme/TabItem' + +[`web-sys` クレヌト](https://crates.io/crates/web-sys) は Web API のバむンディングを提䟛したす。これはブラりザの WebIDL から生成されるため、名前が長くなったり、型が曖昧になったりするこずがありたす。 + +## `web-sys` の特性 (features) + +`web-sys` クレヌトで党おの特性を有効にするず、Wasm アプリケヌションに倚くの冗長性が远加される可胜性がありたす。この問題を解決するために、ほずんどの型は特性を有効にするこずで制埡され、アプリケヌションに必芁な型だけを含めるこずができたす。Yew は `web-sys` のいく぀かの特性を有効にし、その公開 API でいく぀かの型を公開しおいたす。通垞、`web-sys` を䟝存関係ずしお远加する必芁がありたす。 + +## `web-sys` の継承 + +[継承のシミュレヌション](./wasm-bindgen.mdx#simulating-inheritance)のセクションでは、Rust が通垞 JavaScript の継承をシミュレヌトする方法を提䟛しおいるこずがわかりたす。これは `web-sys` で非垞に重芁です。ある型にどのようなメ゜ッドがあるかを理解するためには、その継承を理解する必芁がありたす。 + +このセクションでは、特定の芁玠を芋お、Rust で [`Deref::deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html#tymethod.deref) を呌び出しお、その倀が [`JsValue`](./wasm-bindgen.mdx#jsvalue) になるたでの継承をリストしたす。 + +```rust +use std::ops::Deref; +use web_sys::{ + Element, + EventTarget, + HtmlElement, + HtmlTextAreaElement, + Node, +}; + +fn inheritance_of_text_area(text_area: HtmlTextAreaElement) { + // HtmlTextAreaElement は HTML の