├── .github
└── workflows
│ ├── examples.yml
│ └── test_analyzer.yml
├── .gitignore
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── analyzer
├── .gitignore
├── jest.config.js
├── package-lock.json
├── package.json
└── src
│ ├── __test__
│ ├── anonymous_props.test.ts
│ ├── anonymous_props.tsx
│ ├── bar-direct_arrow_explicit.tsx
│ ├── foo-direct_arrow_explicit.d.ts
│ ├── foo-direct_arrow_explicit.tsx
│ ├── foo-indirect_arrow_explicit.tsx
│ ├── foo-indirect_function_explicit.tsx
│ ├── foo-indirect_function_inferred.tsx
│ ├── foo.components.json
│ ├── foo.test.ts
│ ├── foo.types.json
│ ├── renamed_component.test.ts
│ └── renamed_component.tsx
│ ├── index.ts
│ └── typescript.js
├── examples
├── bad_button
│ ├── bad_button
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Trunk.toml
│ │ ├── index.html
│ │ ├── src
│ │ │ ├── app.rs
│ │ │ └── main.rs
│ │ └── static
│ │ │ ├── react-dom.development.js
│ │ │ └── react.development.js
│ └── js_package
│ │ ├── .gitignore
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ └── src
│ │ └── index.tsx
└── material_ui
│ ├── package-lock.json
│ └── package.json
└── reacty_yew
├── .gitignore
├── Cargo.lock
├── Cargo.toml
└── src
├── analyzer.rs
├── js
├── index.js
├── typescript.js
└── update_source.sh
└── lib.rs
/.github/workflows/examples.yml:
--------------------------------------------------------------------------------
1 | name: Examples
2 |
3 | on: [push]
4 |
5 | jobs:
6 | test:
7 | name: Build examples
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 | - uses: actions-rs/toolchain@v1
12 | with:
13 | toolchain: stable
14 | target: wasm32-unknown-unknown
15 | - uses: actions/setup-node@v2-beta
16 | with:
17 | node-version: '14'
18 |
19 | - run: npm install
20 | working-directory: examples/bad_button/js_package
21 | - run: npm run build
22 | working-directory: examples/bad_button/js_package
23 | - run: cargo build --target wasm32-unknown-unknown
24 | working-directory: examples/bad_button/bad_button
25 |
26 |
--------------------------------------------------------------------------------
/.github/workflows/test_analyzer.yml:
--------------------------------------------------------------------------------
1 | name: Test TS analyzer
2 |
3 | on: [push]
4 |
5 | jobs:
6 | test:
7 | name: Test TS analyzer
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 | - uses: actions/setup-node@v2-beta
12 | with:
13 | node-version: '14'
14 |
15 | - run: npm install
16 | working-directory: analyzer
17 | - run: npm run test
18 | working-directory: analyzer
19 |
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 The reacty_yew contributors.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## reacty_yew - Generate Yew components from React component via Typescript type definitions
2 |
3 | This is a proof of concept for automatically generating [Yew](https://yew.rs/) components from React components that have Typescript type definitions. Many parts are missing and this **likely shouldn't be used in production!**
4 |
5 | [Announcement blog post with a bit more information](https://www.hobofan.com/blog/2020-11-10-reacty_yew/)
6 |
7 | ## Showcase
8 |
9 | For the full example see [./examples/bad_button](./examples/bad_button).
10 |
11 | Given a React component:
12 |
13 | ```tsx
14 | import * as React from "react";
15 |
16 | interface BadButtonProps {
17 | color?: string,
18 | text: string,
19 | }
20 |
21 | const BadButton = (props: BadButtonProps): JSX.Element => {
22 | return (
23 | window.alert("Click!")}
26 | >
27 | {props.text}
28 |
29 | );
30 |
31 | };
32 |
33 | export { BadButton };
34 | ```
35 |
36 | An invocation of the `react_component_mod!` macro (takes as input the name of the module to generate, path to the type declarations and the JS global (UMD) that holds the React components) generates a module:
37 |
38 | ```rust
39 | react_component_mod!(
40 | bad_button;
41 | types = "../js_package/dist/index.d.ts",
42 | global = "BadButtonLib"
43 | );
44 | ```
45 |
46 | You can directly use the generated component `BadButton` in a Yew component:
47 |
48 | ```rust
49 | use yew::prelude::*;
50 | use crate::bad_button::BadButton;
51 |
52 | // ...
53 | fn view(&self) -> Html {
54 | html! {
55 |
56 |
57 |
58 | }
59 | }
60 | // ...
61 | ```
62 |
--------------------------------------------------------------------------------
/analyzer/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .cache/
3 | build/
4 |
5 | src/index.js
6 |
--------------------------------------------------------------------------------
/analyzer/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "roots": [
3 | "/src"
4 | ],
5 | "testMatch": [
6 | "**/__tests__/**/*.+(ts|tsx|js)",
7 | "**/?(*.)+(spec|test).+(ts|tsx|js)"
8 | ],
9 | "transform": {
10 | "^.+\\.(ts|tsx)$": "ts-jest"
11 | },
12 | }
--------------------------------------------------------------------------------
/analyzer/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rust-typescript-bridge",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "build/index.js",
6 | "source": "src/index.ts",
7 | "scripts": {
8 | "build": "tsc src/index.ts --m commonjs",
9 | "test": "node_modules/.bin/jest"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {},
15 | "devDependencies": {
16 | "@types/jest": "^26.0.15",
17 | "@types/node": "^14.14.6",
18 | "jest": "^26.6.3",
19 | "microbundle": "^0.12.4",
20 | "react": "^17.0.1",
21 | "react-dom": "^17.0.1",
22 | "react-planet": "^1.0.1",
23 | "ts-jest": "^26.4.3",
24 | "typescript": "^4.0.5"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/anonymous_props.test.ts:
--------------------------------------------------------------------------------
1 | import * as ts from "typescript";
2 | import * as fs from "fs";
3 | import * as path from "path";
4 | import { generateDocumentation } from '../index';
5 |
6 | const nullPrinter = (key, value) => typeof value === 'undefined' ? null : value;
7 |
8 | test('Anonymous props', () => {
9 | let [components, types] = generateDocumentation(
10 | [path.join(__dirname, './anonymous_props.tsx')],
11 | {
12 | target: ts.ScriptTarget.ES5,
13 | module: ts.ModuleKind.CommonJS
14 | }
15 | );
16 |
17 | components = JSON.parse(JSON.stringify(components, nullPrinter, 4));
18 | types = JSON.parse(JSON.stringify(types, nullPrinter, 4));
19 |
20 | const expectedComponents = [
21 | {
22 | name: "Foo",
23 | propsName: "__type",
24 | }
25 | ];
26 | const expectedTypes = [
27 | {
28 | name: "__type",
29 | properties: [
30 | {
31 | complexType: null,
32 | intrinsicType: "number",
33 | name: "radius",
34 | optional: false,
35 | }
36 | ]
37 | }
38 | ];
39 |
40 | expect(components).toEqual(expectedComponents);
41 | expect(types).toEqual(expectedTypes);
42 | });
43 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/anonymous_props.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | export const Foo = (props: { radius: number }): JSX.Element => {
4 | return (
5 |
6 | {props.radius.toString()}
7 |
8 | );
9 | }
10 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/bar-direct_arrow_explicit.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | interface MyPlanetProps {
4 | radius: number,
5 | radius2?: number,
6 | complex?: OtherType,
7 | }
8 |
9 | interface OtherType {
10 | foo: string,
11 | }
12 |
13 | export const Foo = (props: MyPlanetProps): JSX.Element => {
14 | return (
15 |
16 | {props.radius.toString()}
17 |
18 | );
19 | }
20 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo-direct_arrow_explicit.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | interface MyPlanetProps {
3 | radius: number,
4 | radius2?: number,
5 | complex?: OtherType,
6 | }
7 |
8 | type OtherType = {
9 | foo: string,
10 | }
11 |
12 | export declare const Foo: (props: MyPlanetProps) => JSX.Element;
13 | export {};
14 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo-direct_arrow_explicit.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | // import type { FunctionComponent } from "react";
3 | // import { Planet } from 'react-planet';
4 |
5 | interface MyPlanetProps {
6 | radius: number,
7 | radius2?: number,
8 | complex?: OtherType,
9 | }
10 |
11 | type OtherType = {
12 | foo: string,
13 | }
14 |
15 | export const Foo = (props: MyPlanetProps): JSX.Element => {
16 | return (
17 |
18 | {props.radius.toString()}
19 |
20 | );
21 | }
22 |
23 | // export { Foo }
24 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo-indirect_arrow_explicit.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | // import type { FunctionComponent } from "react";
3 | // import { Planet } from 'react-planet';
4 |
5 | interface MyPlanetProps {
6 | radius: number,
7 | radius2?: number,
8 | complex?: OtherType,
9 | }
10 |
11 | type OtherType = {
12 | foo: string,
13 | }
14 |
15 | const Foo = (props: MyPlanetProps): JSX.Element => {
16 | return (
17 |
18 | {props.radius.toString()}
19 |
20 | );
21 | }
22 |
23 | export { Foo }
24 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo-indirect_function_explicit.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | // import type { FunctionComponent } from "react";
3 | // import { Planet } from 'react-planet';
4 |
5 | interface MyPlanetProps {
6 | radius: number,
7 | radius2?: number,
8 | complex?: OtherType,
9 | }
10 |
11 | type OtherType = {
12 | foo: string,
13 | }
14 |
15 | function Foo(props: MyPlanetProps): JSX.Element {
16 | return (
17 |
18 | {props.radius.toString()}
19 |
20 | );
21 | }
22 |
23 | export { Foo }
24 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo-indirect_function_inferred.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 | // import type { FunctionComponent } from "react";
3 | // import { Planet } from 'react-planet';
4 |
5 | interface MyPlanetProps {
6 | radius: number,
7 | radius2?: number,
8 | complex?: OtherType,
9 | }
10 |
11 | type OtherType = {
12 | foo: string,
13 | }
14 |
15 | function Foo(props: MyPlanetProps) {
16 | return (
17 |
18 | {props.radius.toString()}
19 |
20 | );
21 | }
22 |
23 | export { Foo }
24 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo.components.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "Foo",
4 | "propsName": "MyPlanetProps"
5 | }
6 | ]
7 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo.test.ts:
--------------------------------------------------------------------------------
1 | import * as ts from "typescript";
2 | import * as fs from "fs";
3 | import * as path from "path";
4 | import { generateDocumentation } from '../index';
5 |
6 | const nullPrinter = (key, value) => typeof value === 'undefined' ? null : value;
7 |
8 | const testFoo = (caseName, fileName) => {
9 | test(caseName, () => {
10 | let [components, types] = generateDocumentation(
11 | [path.join(__dirname, fileName)],
12 | {
13 | target: ts.ScriptTarget.ES5,
14 | module: ts.ModuleKind.CommonJS
15 | }
16 | );
17 |
18 | components = JSON.parse(JSON.stringify(components, nullPrinter, 4));
19 | types = JSON.parse(JSON.stringify(types, nullPrinter, 4));
20 |
21 | const expectedComponents = JSON.parse(fs.readFileSync(path.join(__dirname, "./foo.components.json"), 'utf8'));
22 | const expectedTypes = JSON.parse(fs.readFileSync(path.join(__dirname, "./foo.types.json"), 'utf8'));
23 |
24 | expect(components).toEqual(expectedComponents);
25 | expect(types).toEqual(expectedTypes);
26 | });
27 | }
28 |
29 | testFoo(
30 | 'direct export - arrow function - explicit return type',
31 | './foo-direct_arrow_explicit.tsx',
32 | );
33 |
34 | testFoo(
35 | 'direct export - arrow function - explicit return type - via .d.ts',
36 | './foo-direct_arrow_explicit.d.ts',
37 | );
38 |
39 | testFoo(
40 | 'indirect export - arrow function - explicit return type',
41 | './foo-indirect_arrow_explicit.tsx',
42 | );
43 |
44 | testFoo(
45 | 'indirect export - normal function - explicit return type',
46 | './foo-indirect_function_explicit.tsx',
47 | );
48 |
49 | testFoo(
50 | 'indirect export - normal function - inferred return type',
51 | './foo-indirect_function_inferred.tsx',
52 | );
53 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/foo.types.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "OtherType",
4 | "properties": [
5 | {
6 | "complexType": null,
7 | "intrinsicType": "string",
8 | "name": "foo",
9 | "optional": false
10 | }
11 | ]
12 | },
13 | {
14 | "name": "MyPlanetProps",
15 | "properties": [
16 | {
17 | "complexType": null,
18 | "intrinsicType": "number",
19 | "name": "radius",
20 | "optional": false
21 | },
22 | {
23 | "complexType": null,
24 | "intrinsicType": "number",
25 | "name": "radius2",
26 | "optional": true
27 | },
28 | {
29 | "complexType": "OtherType",
30 | "intrinsicType": null,
31 | "name": "complex",
32 | "optional": true
33 | }
34 | ]
35 | }
36 | ]
37 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/renamed_component.test.ts:
--------------------------------------------------------------------------------
1 | import * as ts from "typescript";
2 | import * as fs from "fs";
3 | import * as path from "path";
4 | import { generateDocumentation } from '../index';
5 |
6 | const nullPrinter = (key, value) => typeof value === 'undefined' ? null : value;
7 |
8 | test('Renamed component', () => {
9 | let [components, types] = generateDocumentation(
10 | [path.join(__dirname, './renamed_component.tsx')],
11 | {
12 | target: ts.ScriptTarget.ES5,
13 | module: ts.ModuleKind.CommonJS
14 | }
15 | );
16 |
17 | components = JSON.parse(JSON.stringify(components, nullPrinter, 4));
18 | types = JSON.parse(JSON.stringify(types, nullPrinter, 4));
19 |
20 | const expectedComponents = [
21 | {
22 | name: "RenamedComponent",
23 | propsName: "OriginalNamedProps",
24 | }
25 | ];
26 | const expectedTypes = [
27 | {
28 | name: "OriginalNamedProps",
29 | properties: [
30 | {
31 | complexType: null,
32 | intrinsicType: "number",
33 | name: "radius",
34 | optional: false,
35 | }
36 | ]
37 | }
38 | ];
39 |
40 | expect(components).toEqual(expectedComponents);
41 | expect(types).toEqual(expectedTypes);
42 | });
43 |
--------------------------------------------------------------------------------
/analyzer/src/__test__/renamed_component.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | interface OriginalNamedProps {
4 | radius: number,
5 | }
6 |
7 | const Foo = (props: OriginalNamedProps): JSX.Element => {
8 | return (
9 |
10 | {props.radius.toString()}
11 |
12 | );
13 | }
14 |
15 | export { Foo as RenamedComponent }
16 |
--------------------------------------------------------------------------------
/analyzer/src/index.ts:
--------------------------------------------------------------------------------
1 | import * as ts from "typescript";
2 | import * as fs from "fs";
3 |
4 | const util = require('util')
5 | const log = util.debuglog('fortest')
6 |
7 | // log((node.parent as any).fileName)
8 | // if ((node.parent as any).fileName === '/Users/hobofan/hobofan/reacty_yew/analyzer/src/__test__/foo-indirect_function_inferred.tsx') {
9 | // log(node.kind);
10 | // }
11 |
12 | interface DocEntry {
13 | name?: string;
14 | fileName?: string;
15 | documentation?: string;
16 | type?: string;
17 | constructors?: DocEntry[];
18 | parameters?: DocEntry[];
19 | returnType?: string;
20 | }
21 |
22 | interface SimpleType {
23 | name: string,
24 | properties: Array<{
25 | name: string,
26 | optional: boolean,
27 | intrinsicType?: string,
28 | complexType?: string,
29 | }>
30 | }
31 |
32 | interface Component {
33 | name: string,
34 | props: string,
35 | }
36 |
37 | /** Generate documentation for all classes in a set of .ts files */
38 | function generateDocumentation(
39 | fileNames: string[],
40 | options: ts.CompilerOptions
41 | ): [Component[], SimpleType[]] {
42 | // Build a program using the set of root file names in fileNames
43 | let program = ts.createProgram(fileNames, options);
44 |
45 | // Get the checker, we will use it to find more about classes
46 | let checker = program.getTypeChecker();
47 | let output: DocEntry[] = [];
48 | const types: SimpleType[] = [];
49 | const components = [];
50 |
51 | // Visit every sourceFile in the program
52 | for (const sourceFile of program.getSourceFiles()) {
53 | // if (sourceFile.isDeclarationFile) {
54 | // Walk the tree to search for classes
55 | ts.forEachChild(sourceFile, visit);
56 | // }
57 | }
58 |
59 | return [components, types];
60 |
61 | /** visit nodes finding exported classes */
62 | function visit(node: ts.Node) {
63 | // Only consider exported nodes
64 | if (!isNodeExported(node)) {
65 | return;
66 | }
67 |
68 | if (ts.isClassDeclaration(node) && node.name) {
69 | // This is a top level class, get its symbol
70 | let symbol = checker.getSymbolAtLocation(node.name);
71 | if (symbol) {
72 | output.push(serializeClass(symbol));
73 | }
74 | // No need to walk any further, class expressions/inner declarations
75 | // cannot be exported
76 | } else if (ts.isModuleDeclaration(node)) {
77 | // This is a namespace, visit its children
78 | ts.forEachChild(node, visit);
79 | }
80 |
81 | if (ts.isVariableStatement(node)) {
82 | node.declarationList.declarations.forEach((subnode) => {
83 | const initializer = subnode.initializer || subnode.type;
84 | if (initializer && (initializer as any).parameters && isFunctionalComponent(initializer)) {
85 | let propsName;
86 | (initializer as any).parameters.forEach((param) => {
87 | const typeNode = param.type;
88 | const typ = checker.getTypeFromTypeNode(typeNode);
89 | const simpleType = typeToSimpleType(typ);
90 |
91 | types.push(simpleType);
92 | propsName = simpleType.name;
93 | });
94 |
95 | const componentExportedName = exportedNameForSymbol(subnode as any, node);
96 | const component = {
97 | name: componentExportedName,
98 | propsName,
99 | }
100 | components.push(component);
101 | }
102 | })
103 | }
104 |
105 | if (ts.isFunctionDeclaration(node)) {
106 | if(isFunctionalComponent(node)) {
107 | let propsName;
108 | node.parameters.forEach((param) => {
109 | const typeNode = param.type;
110 | const typ = checker.getTypeFromTypeNode(typeNode);
111 | const simpleType = typeToSimpleType(typ);
112 |
113 | types.push(simpleType);
114 | propsName = simpleType.name;
115 | })
116 |
117 | const component = {
118 | name: node.name.escapedText,
119 | propsName,
120 | }
121 | components.push(component);
122 | }
123 | }
124 |
125 | }
126 |
127 | function isFunctionalComponent(node: ts.Node): boolean {
128 | const signatureDeclaration = node as ts.SignatureDeclaration;
129 | const isElementSymbolWithJsxParent = (returnType) => {
130 | if (
131 | returnType.symbol &&
132 | returnType.symbol.parent &&
133 | returnType.symbol.escapedText === 'Element' &&
134 | returnType.symbol.parent.escapedText === 'JSX'
135 | ) {
136 | return true;
137 | }
138 | if (
139 | returnType.symbol &&
140 | returnType.symbol.parent &&
141 | returnType.symbol.escapedName === 'Element' &&
142 | returnType.symbol.parent.escapedName === 'JSX'
143 | ) {
144 | return true;
145 | }
146 |
147 | return false;
148 | }
149 |
150 | if (ts.isFunctionLike(node)) {
151 | const returnType = checker.getSignatureFromDeclaration(signatureDeclaration).getReturnType();
152 | if (isElementSymbolWithJsxParent(returnType)) {
153 | return true;
154 | }
155 | }
156 |
157 | const typeName = (node as any).type.typeName;
158 | if (typeName && ts.isQualifiedName(typeName)) {
159 | if (
160 | ts.isIdentifier(typeName.left) &&
161 | typeName.left.escapedText === 'JSX' &&
162 | typeName.right.escapedText === 'Element'
163 | ) {
164 | return true;
165 | }
166 | }
167 |
168 | return false;
169 | }
170 |
171 | function typeToSimpleType(type: ts.Type): SimpleType {
172 | let typeName;
173 | if (type.aliasSymbol) {
174 | typeName = type.aliasSymbol.escapedName;
175 | }
176 | if (!typeName) {
177 | typeName = type.symbol.escapedName as string
178 | }
179 |
180 | const simpleType: SimpleType = {
181 | name: typeName,
182 | properties: [],
183 | };
184 |
185 | type.symbol.members.forEach((symbol, key) => {
186 | const checkedType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!) as any;
187 | const {intrinsicName} = checkedType;
188 | const optional = checker.isOptionalParameter((symbol as any).declarations[0]);
189 | let complexType;
190 | if (checkedType.aliasSymbol) {
191 | complexType = checkedType.aliasSymbol.escapedName;
192 |
193 | const simpleType = typeToSimpleType(checkedType);
194 | types.push(simpleType);
195 | }
196 |
197 | const property = {
198 | name: key as string,
199 | intrinsicType: intrinsicName,
200 | complexType,
201 | optional,
202 | };
203 | simpleType.properties.push(property);
204 | });
205 |
206 | return simpleType;
207 | }
208 |
209 | function exportedNameForSymbol(symbol: ts.Symbol, fileNode: ts.Node): string {
210 | const localName = (symbol.name as any).escapedText
211 | let exportedName;
212 | (fileNode.parent as any).symbol.exports.forEach((value, key) => {
213 | // Follow exported symbol to original symbol
214 | try {
215 | const aliasedSymbol = checker.getAliasedSymbol(value);
216 | if(aliasedSymbol.escapedName === localName) {
217 | exportedName = value.escapedName;
218 | }
219 | } catch { }
220 | });
221 | return exportedName || localName;
222 | }
223 |
224 | /** Serialize a symbol into a json object */
225 | function serializeSymbol(symbol: ts.Symbol): DocEntry {
226 | return {
227 | name: symbol.getName(),
228 | documentation: ts.displayPartsToString(symbol.getDocumentationComment(checker)),
229 | type: checker.typeToString(
230 | checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!)
231 | )
232 | };
233 | }
234 |
235 | /** Serialize a class symbol information */
236 | function serializeClass(symbol: ts.Symbol) {
237 | let details = serializeSymbol(symbol);
238 |
239 | // Get the construct signatures
240 | let constructorType = checker.getTypeOfSymbolAtLocation(
241 | symbol,
242 | symbol.valueDeclaration!
243 | );
244 | details.constructors = constructorType
245 | .getConstructSignatures()
246 | .map(serializeSignature);
247 | return details;
248 | }
249 |
250 | /** Serialize a signature (call or construct) */
251 | function serializeSignature(signature: ts.Signature) {
252 | return {
253 | parameters: signature.parameters.map(serializeSymbol),
254 | returnType: checker.typeToString(signature.getReturnType()),
255 | documentation: ts.displayPartsToString(signature.getDocumentationComment(checker))
256 | };
257 | }
258 |
259 | /** True if this is visible outside this file, false otherwise */
260 | function isNodeExported(node: ts.Node): boolean {
261 | return (
262 | (ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export) !== 0 ||
263 | (!!node.parent && node.parent.kind === ts.SyntaxKind.SourceFile)
264 | );
265 | }
266 | }
267 |
268 | if (require.main === module) {
269 | const [components, types] = generateDocumentation(process.argv.slice(2), {
270 | target: ts.ScriptTarget.ES5,
271 | module: ts.ModuleKind.CommonJS
272 | });
273 |
274 | // print out the doc
275 | const nullPrinter = (key, value) => typeof value === 'undefined' ? null : value;
276 | console.log(JSON.stringify({
277 | "types": types,
278 | "components": components,
279 | }, nullPrinter, 4));
280 | // fs.writeFileSync(
281 | // "types.json",
282 | // JSON.stringify(types, nullPrinter, 4)
283 | // );
284 | // fs.writeFileSync(
285 | // "components.json",
286 | // JSON.stringify(components, nullPrinter, 4)
287 | // );
288 | }
289 |
290 | export { generateDocumentation };
291 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | dist/
3 |
4 | Cargo.lock
5 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "bad_button"
3 | version = "0.1.0"
4 | authors = ["Maximilian Goisser "]
5 | edition = "2018"
6 |
7 |
8 | [dependencies]
9 | reacty_yew = { path = "../../../reacty_yew" }
10 |
11 | serde = { version = "1.0", features = ["derive"] }
12 | wasm-bindgen = { version = "0.2.68", features = ["serde-serialize"] }
13 | yew = "0.17.3"
14 |
15 | console_error_panic_hook = { version = "0.1.6" }
16 | wasm-logger = { version = "0.2" }
17 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/Trunk.toml:
--------------------------------------------------------------------------------
1 | [serve]
2 | # Open a browser tab once the initial build is complete.
3 | open = true
4 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Yew • With React
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/src/app.rs:
--------------------------------------------------------------------------------
1 | use yew::prelude::*;
2 |
3 | use crate::bad_button::BadButton;
4 |
5 | pub struct App {
6 | // link: ComponentLink,
7 | }
8 |
9 | impl Component for App {
10 | type Message = ();
11 | type Properties = ();
12 |
13 | fn create(_: Self::Properties, _link: ComponentLink) -> Self {
14 | App {}
15 | }
16 |
17 | fn change(&mut self, _new_props: Self::Properties) -> ShouldRender {
18 | true
19 | }
20 |
21 | fn update(&mut self, _msg: Self::Message) -> ShouldRender {
22 | true
23 | }
24 |
25 | fn view(&self) -> Html {
26 | html! {
27 |
28 | {"This button!"}
29 |
30 |
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/src/main.rs:
--------------------------------------------------------------------------------
1 | #![recursion_limit = "512"]
2 | use reacty_yew::react_component_mod;
3 |
4 | mod app;
5 | react_component_mod!(
6 | bad_button;
7 | types = "../js_package/dist/index.d.ts",
8 | global = "BadButtonLib"
9 | );
10 |
11 | // This is the entry point for the web app
12 | fn main() {
13 | set_panic_hook();
14 | wasm_logger::init(wasm_logger::Config::default());
15 | yew::start_app::();
16 | }
17 |
18 | pub fn set_panic_hook() {
19 | // When the `console_error_panic_hook` feature is enabled, we can call the
20 | // `set_panic_hook` function at least once during initialization, and then
21 | // we will get better error messages if our code ever panics.
22 | //
23 | // For more details see
24 | // https://github.com/rustwasm/console_error_panic_hook#readme
25 | console_error_panic_hook::set_once();
26 | }
27 |
--------------------------------------------------------------------------------
/examples/bad_button/bad_button/static/react.development.js:
--------------------------------------------------------------------------------
1 | /** @license React v17.0.1
2 | * react.development.js
3 | *
4 | * Copyright (c) Facebook, Inc. and its affiliates.
5 | *
6 | * This source code is licensed under the MIT license found in the
7 | * LICENSE file in the root directory of this source tree.
8 | */
9 | (function (global, factory) {
10 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
11 | typeof define === 'function' && define.amd ? define(['exports'], factory) :
12 | (global = global || self, factory(global.React = {}));
13 | }(this, (function (exports) { 'use strict';
14 |
15 | // TODO: this is special because it gets imported during build.
16 | var ReactVersion = '17.0.1';
17 |
18 | // ATTENTION
19 | // When adding new symbols to this file,
20 | // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
21 | // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
22 | // nor polyfill, then a plain number is used for performance.
23 | var REACT_ELEMENT_TYPE = 0xeac7;
24 | var REACT_PORTAL_TYPE = 0xeaca;
25 | exports.Fragment = 0xeacb;
26 | exports.StrictMode = 0xeacc;
27 | exports.Profiler = 0xead2;
28 | var REACT_PROVIDER_TYPE = 0xeacd;
29 | var REACT_CONTEXT_TYPE = 0xeace;
30 | var REACT_FORWARD_REF_TYPE = 0xead0;
31 | exports.Suspense = 0xead1;
32 | var REACT_SUSPENSE_LIST_TYPE = 0xead8;
33 | var REACT_MEMO_TYPE = 0xead3;
34 | var REACT_LAZY_TYPE = 0xead4;
35 | var REACT_BLOCK_TYPE = 0xead9;
36 | var REACT_SERVER_BLOCK_TYPE = 0xeada;
37 | var REACT_FUNDAMENTAL_TYPE = 0xead5;
38 | var REACT_SCOPE_TYPE = 0xead7;
39 | var REACT_OPAQUE_ID_TYPE = 0xeae0;
40 | var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
41 | var REACT_OFFSCREEN_TYPE = 0xeae2;
42 | var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
43 |
44 | if (typeof Symbol === 'function' && Symbol.for) {
45 | var symbolFor = Symbol.for;
46 | REACT_ELEMENT_TYPE = symbolFor('react.element');
47 | REACT_PORTAL_TYPE = symbolFor('react.portal');
48 | exports.Fragment = symbolFor('react.fragment');
49 | exports.StrictMode = symbolFor('react.strict_mode');
50 | exports.Profiler = symbolFor('react.profiler');
51 | REACT_PROVIDER_TYPE = symbolFor('react.provider');
52 | REACT_CONTEXT_TYPE = symbolFor('react.context');
53 | REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
54 | exports.Suspense = symbolFor('react.suspense');
55 | REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
56 | REACT_MEMO_TYPE = symbolFor('react.memo');
57 | REACT_LAZY_TYPE = symbolFor('react.lazy');
58 | REACT_BLOCK_TYPE = symbolFor('react.block');
59 | REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
60 | REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
61 | REACT_SCOPE_TYPE = symbolFor('react.scope');
62 | REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
63 | REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
64 | REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
65 | REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
66 | }
67 |
68 | var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
69 | var FAUX_ITERATOR_SYMBOL = '@@iterator';
70 | function getIteratorFn(maybeIterable) {
71 | if (maybeIterable === null || typeof maybeIterable !== 'object') {
72 | return null;
73 | }
74 |
75 | var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
76 |
77 | if (typeof maybeIterator === 'function') {
78 | return maybeIterator;
79 | }
80 |
81 | return null;
82 | }
83 |
84 | var hasOwnProperty = Object.prototype.hasOwnProperty;
85 |
86 | var _assign = function (to, from) {
87 | for (var key in from) {
88 | if (hasOwnProperty.call(from, key)) {
89 | to[key] = from[key];
90 | }
91 | }
92 | };
93 |
94 | var assign = Object.assign || function (target, sources) {
95 | if (target == null) {
96 | throw new TypeError('Object.assign target cannot be null or undefined');
97 | }
98 |
99 | var to = Object(target);
100 |
101 | for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
102 | var nextSource = arguments[nextIndex];
103 |
104 | if (nextSource != null) {
105 | _assign(to, Object(nextSource));
106 | }
107 | }
108 |
109 | return to;
110 | };
111 |
112 | /**
113 | * Keeps track of the current dispatcher.
114 | */
115 | var ReactCurrentDispatcher = {
116 | /**
117 | * @internal
118 | * @type {ReactComponent}
119 | */
120 | current: null
121 | };
122 |
123 | /**
124 | * Keeps track of the current batch's configuration such as how long an update
125 | * should suspend for if it needs to.
126 | */
127 | var ReactCurrentBatchConfig = {
128 | transition: 0
129 | };
130 |
131 | /**
132 | * Keeps track of the current owner.
133 | *
134 | * The current owner is the component who should own any components that are
135 | * currently being constructed.
136 | */
137 | var ReactCurrentOwner = {
138 | /**
139 | * @internal
140 | * @type {ReactComponent}
141 | */
142 | current: null
143 | };
144 |
145 | var ReactDebugCurrentFrame = {};
146 | var currentExtraStackFrame = null;
147 | function setExtraStackFrame(stack) {
148 | {
149 | currentExtraStackFrame = stack;
150 | }
151 | }
152 |
153 | {
154 | ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
155 | {
156 | currentExtraStackFrame = stack;
157 | }
158 | }; // Stack implementation injected by the current renderer.
159 |
160 |
161 | ReactDebugCurrentFrame.getCurrentStack = null;
162 |
163 | ReactDebugCurrentFrame.getStackAddendum = function () {
164 | var stack = ''; // Add an extra top frame while an element is being validated
165 |
166 | if (currentExtraStackFrame) {
167 | stack += currentExtraStackFrame;
168 | } // Delegate to the injected renderer-specific implementation
169 |
170 |
171 | var impl = ReactDebugCurrentFrame.getCurrentStack;
172 |
173 | if (impl) {
174 | stack += impl() || '';
175 | }
176 |
177 | return stack;
178 | };
179 | }
180 |
181 | /**
182 | * Used by act() to track whether you're inside an act() scope.
183 | */
184 | var IsSomeRendererActing = {
185 | current: false
186 | };
187 |
188 | var ReactSharedInternals = {
189 | ReactCurrentDispatcher: ReactCurrentDispatcher,
190 | ReactCurrentBatchConfig: ReactCurrentBatchConfig,
191 | ReactCurrentOwner: ReactCurrentOwner,
192 | IsSomeRendererActing: IsSomeRendererActing,
193 | // Used by renderers to avoid bundling object-assign twice in UMD bundles:
194 | assign: assign
195 | };
196 |
197 | {
198 | ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
199 | }
200 |
201 | // by calls to these methods by a Babel plugin.
202 | //
203 | // In PROD (or in packages without access to React internals),
204 | // they are left as they are instead.
205 |
206 | function warn(format) {
207 | {
208 | for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
209 | args[_key - 1] = arguments[_key];
210 | }
211 |
212 | printWarning('warn', format, args);
213 | }
214 | }
215 | function error(format) {
216 | {
217 | for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
218 | args[_key2 - 1] = arguments[_key2];
219 | }
220 |
221 | printWarning('error', format, args);
222 | }
223 | }
224 |
225 | function printWarning(level, format, args) {
226 | // When changing this logic, you might want to also
227 | // update consoleWithStackDev.www.js as well.
228 | {
229 | var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
230 | var stack = ReactDebugCurrentFrame.getStackAddendum();
231 |
232 | if (stack !== '') {
233 | format += '%s';
234 | args = args.concat([stack]);
235 | }
236 |
237 | var argsWithFormat = args.map(function (item) {
238 | return '' + item;
239 | }); // Careful: RN currently depends on this prefix
240 |
241 | argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
242 | // breaks IE9: https://github.com/facebook/react/issues/13610
243 | // eslint-disable-next-line react-internal/no-production-logging
244 |
245 | Function.prototype.apply.call(console[level], console, argsWithFormat);
246 | }
247 | }
248 |
249 | var didWarnStateUpdateForUnmountedComponent = {};
250 |
251 | function warnNoop(publicInstance, callerName) {
252 | {
253 | var _constructor = publicInstance.constructor;
254 | var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
255 | var warningKey = componentName + "." + callerName;
256 |
257 | if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
258 | return;
259 | }
260 |
261 | error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
262 |
263 | didWarnStateUpdateForUnmountedComponent[warningKey] = true;
264 | }
265 | }
266 | /**
267 | * This is the abstract API for an update queue.
268 | */
269 |
270 |
271 | var ReactNoopUpdateQueue = {
272 | /**
273 | * Checks whether or not this composite component is mounted.
274 | * @param {ReactClass} publicInstance The instance we want to test.
275 | * @return {boolean} True if mounted, false otherwise.
276 | * @protected
277 | * @final
278 | */
279 | isMounted: function (publicInstance) {
280 | return false;
281 | },
282 |
283 | /**
284 | * Forces an update. This should only be invoked when it is known with
285 | * certainty that we are **not** in a DOM transaction.
286 | *
287 | * You may want to call this when you know that some deeper aspect of the
288 | * component's state has changed but `setState` was not called.
289 | *
290 | * This will not invoke `shouldComponentUpdate`, but it will invoke
291 | * `componentWillUpdate` and `componentDidUpdate`.
292 | *
293 | * @param {ReactClass} publicInstance The instance that should rerender.
294 | * @param {?function} callback Called after component is updated.
295 | * @param {?string} callerName name of the calling function in the public API.
296 | * @internal
297 | */
298 | enqueueForceUpdate: function (publicInstance, callback, callerName) {
299 | warnNoop(publicInstance, 'forceUpdate');
300 | },
301 |
302 | /**
303 | * Replaces all of the state. Always use this or `setState` to mutate state.
304 | * You should treat `this.state` as immutable.
305 | *
306 | * There is no guarantee that `this.state` will be immediately updated, so
307 | * accessing `this.state` after calling this method may return the old value.
308 | *
309 | * @param {ReactClass} publicInstance The instance that should rerender.
310 | * @param {object} completeState Next state.
311 | * @param {?function} callback Called after component is updated.
312 | * @param {?string} callerName name of the calling function in the public API.
313 | * @internal
314 | */
315 | enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
316 | warnNoop(publicInstance, 'replaceState');
317 | },
318 |
319 | /**
320 | * Sets a subset of the state. This only exists because _pendingState is
321 | * internal. This provides a merging strategy that is not available to deep
322 | * properties which is confusing. TODO: Expose pendingState or don't use it
323 | * during the merge.
324 | *
325 | * @param {ReactClass} publicInstance The instance that should rerender.
326 | * @param {object} partialState Next partial state to be merged with state.
327 | * @param {?function} callback Called after component is updated.
328 | * @param {?string} Name of the calling function in the public API.
329 | * @internal
330 | */
331 | enqueueSetState: function (publicInstance, partialState, callback, callerName) {
332 | warnNoop(publicInstance, 'setState');
333 | }
334 | };
335 |
336 | var emptyObject = {};
337 |
338 | {
339 | Object.freeze(emptyObject);
340 | }
341 | /**
342 | * Base class helpers for the updating state of a component.
343 | */
344 |
345 |
346 | function Component(props, context, updater) {
347 | this.props = props;
348 | this.context = context; // If a component has string refs, we will assign a different object later.
349 |
350 | this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
351 | // renderer.
352 |
353 | this.updater = updater || ReactNoopUpdateQueue;
354 | }
355 |
356 | Component.prototype.isReactComponent = {};
357 | /**
358 | * Sets a subset of the state. Always use this to mutate
359 | * state. You should treat `this.state` as immutable.
360 | *
361 | * There is no guarantee that `this.state` will be immediately updated, so
362 | * accessing `this.state` after calling this method may return the old value.
363 | *
364 | * There is no guarantee that calls to `setState` will run synchronously,
365 | * as they may eventually be batched together. You can provide an optional
366 | * callback that will be executed when the call to setState is actually
367 | * completed.
368 | *
369 | * When a function is provided to setState, it will be called at some point in
370 | * the future (not synchronously). It will be called with the up to date
371 | * component arguments (state, props, context). These values can be different
372 | * from this.* because your function may be called after receiveProps but before
373 | * shouldComponentUpdate, and this new state, props, and context will not yet be
374 | * assigned to this.
375 | *
376 | * @param {object|function} partialState Next partial state or function to
377 | * produce next partial state to be merged with current state.
378 | * @param {?function} callback Called after state is updated.
379 | * @final
380 | * @protected
381 | */
382 |
383 | Component.prototype.setState = function (partialState, callback) {
384 | if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {
385 | {
386 | throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." );
387 | }
388 | }
389 |
390 | this.updater.enqueueSetState(this, partialState, callback, 'setState');
391 | };
392 | /**
393 | * Forces an update. This should only be invoked when it is known with
394 | * certainty that we are **not** in a DOM transaction.
395 | *
396 | * You may want to call this when you know that some deeper aspect of the
397 | * component's state has changed but `setState` was not called.
398 | *
399 | * This will not invoke `shouldComponentUpdate`, but it will invoke
400 | * `componentWillUpdate` and `componentDidUpdate`.
401 | *
402 | * @param {?function} callback Called after update is complete.
403 | * @final
404 | * @protected
405 | */
406 |
407 |
408 | Component.prototype.forceUpdate = function (callback) {
409 | this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
410 | };
411 | /**
412 | * Deprecated APIs. These APIs used to exist on classic React classes but since
413 | * we would like to deprecate them, we're not going to move them over to this
414 | * modern base class. Instead, we define a getter that warns if it's accessed.
415 | */
416 |
417 |
418 | {
419 | var deprecatedAPIs = {
420 | isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
421 | replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
422 | };
423 |
424 | var defineDeprecationWarning = function (methodName, info) {
425 | Object.defineProperty(Component.prototype, methodName, {
426 | get: function () {
427 | warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
428 |
429 | return undefined;
430 | }
431 | });
432 | };
433 |
434 | for (var fnName in deprecatedAPIs) {
435 | if (deprecatedAPIs.hasOwnProperty(fnName)) {
436 | defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
437 | }
438 | }
439 | }
440 |
441 | function ComponentDummy() {}
442 |
443 | ComponentDummy.prototype = Component.prototype;
444 | /**
445 | * Convenience component with default shallow equality check for sCU.
446 | */
447 |
448 | function PureComponent(props, context, updater) {
449 | this.props = props;
450 | this.context = context; // If a component has string refs, we will assign a different object later.
451 |
452 | this.refs = emptyObject;
453 | this.updater = updater || ReactNoopUpdateQueue;
454 | }
455 |
456 | var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
457 | pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
458 |
459 | assign(pureComponentPrototype, Component.prototype);
460 |
461 | pureComponentPrototype.isPureReactComponent = true;
462 |
463 | // an immutable object with a single mutable value
464 | function createRef() {
465 | var refObject = {
466 | current: null
467 | };
468 |
469 | {
470 | Object.seal(refObject);
471 | }
472 |
473 | return refObject;
474 | }
475 |
476 | function getWrappedName(outerType, innerType, wrapperName) {
477 | var functionName = innerType.displayName || innerType.name || '';
478 | return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
479 | }
480 |
481 | function getContextName(type) {
482 | return type.displayName || 'Context';
483 | }
484 |
485 | function getComponentName(type) {
486 | if (type == null) {
487 | // Host root, text node or just invalid type.
488 | return null;
489 | }
490 |
491 | {
492 | if (typeof type.tag === 'number') {
493 | error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
494 | }
495 | }
496 |
497 | if (typeof type === 'function') {
498 | return type.displayName || type.name || null;
499 | }
500 |
501 | if (typeof type === 'string') {
502 | return type;
503 | }
504 |
505 | switch (type) {
506 | case exports.Fragment:
507 | return 'Fragment';
508 |
509 | case REACT_PORTAL_TYPE:
510 | return 'Portal';
511 |
512 | case exports.Profiler:
513 | return 'Profiler';
514 |
515 | case exports.StrictMode:
516 | return 'StrictMode';
517 |
518 | case exports.Suspense:
519 | return 'Suspense';
520 |
521 | case REACT_SUSPENSE_LIST_TYPE:
522 | return 'SuspenseList';
523 | }
524 |
525 | if (typeof type === 'object') {
526 | switch (type.$$typeof) {
527 | case REACT_CONTEXT_TYPE:
528 | var context = type;
529 | return getContextName(context) + '.Consumer';
530 |
531 | case REACT_PROVIDER_TYPE:
532 | var provider = type;
533 | return getContextName(provider._context) + '.Provider';
534 |
535 | case REACT_FORWARD_REF_TYPE:
536 | return getWrappedName(type, type.render, 'ForwardRef');
537 |
538 | case REACT_MEMO_TYPE:
539 | return getComponentName(type.type);
540 |
541 | case REACT_BLOCK_TYPE:
542 | return getComponentName(type._render);
543 |
544 | case REACT_LAZY_TYPE:
545 | {
546 | var lazyComponent = type;
547 | var payload = lazyComponent._payload;
548 | var init = lazyComponent._init;
549 |
550 | try {
551 | return getComponentName(init(payload));
552 | } catch (x) {
553 | return null;
554 | }
555 | }
556 | }
557 | }
558 |
559 | return null;
560 | }
561 |
562 | var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
563 | var RESERVED_PROPS = {
564 | key: true,
565 | ref: true,
566 | __self: true,
567 | __source: true
568 | };
569 | var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
570 |
571 | {
572 | didWarnAboutStringRefs = {};
573 | }
574 |
575 | function hasValidRef(config) {
576 | {
577 | if (hasOwnProperty$1.call(config, 'ref')) {
578 | var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
579 |
580 | if (getter && getter.isReactWarning) {
581 | return false;
582 | }
583 | }
584 | }
585 |
586 | return config.ref !== undefined;
587 | }
588 |
589 | function hasValidKey(config) {
590 | {
591 | if (hasOwnProperty$1.call(config, 'key')) {
592 | var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
593 |
594 | if (getter && getter.isReactWarning) {
595 | return false;
596 | }
597 | }
598 | }
599 |
600 | return config.key !== undefined;
601 | }
602 |
603 | function defineKeyPropWarningGetter(props, displayName) {
604 | var warnAboutAccessingKey = function () {
605 | {
606 | if (!specialPropKeyWarningShown) {
607 | specialPropKeyWarningShown = true;
608 |
609 | error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
610 | }
611 | }
612 | };
613 |
614 | warnAboutAccessingKey.isReactWarning = true;
615 | Object.defineProperty(props, 'key', {
616 | get: warnAboutAccessingKey,
617 | configurable: true
618 | });
619 | }
620 |
621 | function defineRefPropWarningGetter(props, displayName) {
622 | var warnAboutAccessingRef = function () {
623 | {
624 | if (!specialPropRefWarningShown) {
625 | specialPropRefWarningShown = true;
626 |
627 | error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
628 | }
629 | }
630 | };
631 |
632 | warnAboutAccessingRef.isReactWarning = true;
633 | Object.defineProperty(props, 'ref', {
634 | get: warnAboutAccessingRef,
635 | configurable: true
636 | });
637 | }
638 |
639 | function warnIfStringRefCannotBeAutoConverted(config) {
640 | {
641 | if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
642 | var componentName = getComponentName(ReactCurrentOwner.current.type);
643 |
644 | if (!didWarnAboutStringRefs[componentName]) {
645 | error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
646 |
647 | didWarnAboutStringRefs[componentName] = true;
648 | }
649 | }
650 | }
651 | }
652 | /**
653 | * Factory method to create a new React element. This no longer adheres to
654 | * the class pattern, so do not use new to call it. Also, instanceof check
655 | * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
656 | * if something is a React Element.
657 | *
658 | * @param {*} type
659 | * @param {*} props
660 | * @param {*} key
661 | * @param {string|object} ref
662 | * @param {*} owner
663 | * @param {*} self A *temporary* helper to detect places where `this` is
664 | * different from the `owner` when React.createElement is called, so that we
665 | * can warn. We want to get rid of owner and replace string `ref`s with arrow
666 | * functions, and as long as `this` and owner are the same, there will be no
667 | * change in behavior.
668 | * @param {*} source An annotation object (added by a transpiler or otherwise)
669 | * indicating filename, line number, and/or other information.
670 | * @internal
671 | */
672 |
673 |
674 | var ReactElement = function (type, key, ref, self, source, owner, props) {
675 | var element = {
676 | // This tag allows us to uniquely identify this as a React Element
677 | $$typeof: REACT_ELEMENT_TYPE,
678 | // Built-in properties that belong on the element
679 | type: type,
680 | key: key,
681 | ref: ref,
682 | props: props,
683 | // Record the component responsible for creating this element.
684 | _owner: owner
685 | };
686 |
687 | {
688 | // The validation flag is currently mutative. We put it on
689 | // an external backing store so that we can freeze the whole object.
690 | // This can be replaced with a WeakMap once they are implemented in
691 | // commonly used development environments.
692 | element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
693 | // the validation flag non-enumerable (where possible, which should
694 | // include every environment we run tests in), so the test framework
695 | // ignores it.
696 |
697 | Object.defineProperty(element._store, 'validated', {
698 | configurable: false,
699 | enumerable: false,
700 | writable: true,
701 | value: false
702 | }); // self and source are DEV only properties.
703 |
704 | Object.defineProperty(element, '_self', {
705 | configurable: false,
706 | enumerable: false,
707 | writable: false,
708 | value: self
709 | }); // Two elements created in two different places should be considered
710 | // equal for testing purposes and therefore we hide it from enumeration.
711 |
712 | Object.defineProperty(element, '_source', {
713 | configurable: false,
714 | enumerable: false,
715 | writable: false,
716 | value: source
717 | });
718 |
719 | if (Object.freeze) {
720 | Object.freeze(element.props);
721 | Object.freeze(element);
722 | }
723 | }
724 |
725 | return element;
726 | };
727 | /**
728 | * Create and return a new ReactElement of the given type.
729 | * See https://reactjs.org/docs/react-api.html#createelement
730 | */
731 |
732 | function createElement(type, config, children) {
733 | var propName; // Reserved names are extracted
734 |
735 | var props = {};
736 | var key = null;
737 | var ref = null;
738 | var self = null;
739 | var source = null;
740 |
741 | if (config != null) {
742 | if (hasValidRef(config)) {
743 | ref = config.ref;
744 |
745 | {
746 | warnIfStringRefCannotBeAutoConverted(config);
747 | }
748 | }
749 |
750 | if (hasValidKey(config)) {
751 | key = '' + config.key;
752 | }
753 |
754 | self = config.__self === undefined ? null : config.__self;
755 | source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
756 |
757 | for (propName in config) {
758 | if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
759 | props[propName] = config[propName];
760 | }
761 | }
762 | } // Children can be more than one argument, and those are transferred onto
763 | // the newly allocated props object.
764 |
765 |
766 | var childrenLength = arguments.length - 2;
767 |
768 | if (childrenLength === 1) {
769 | props.children = children;
770 | } else if (childrenLength > 1) {
771 | var childArray = Array(childrenLength);
772 |
773 | for (var i = 0; i < childrenLength; i++) {
774 | childArray[i] = arguments[i + 2];
775 | }
776 |
777 | {
778 | if (Object.freeze) {
779 | Object.freeze(childArray);
780 | }
781 | }
782 |
783 | props.children = childArray;
784 | } // Resolve default props
785 |
786 |
787 | if (type && type.defaultProps) {
788 | var defaultProps = type.defaultProps;
789 |
790 | for (propName in defaultProps) {
791 | if (props[propName] === undefined) {
792 | props[propName] = defaultProps[propName];
793 | }
794 | }
795 | }
796 |
797 | {
798 | if (key || ref) {
799 | var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
800 |
801 | if (key) {
802 | defineKeyPropWarningGetter(props, displayName);
803 | }
804 |
805 | if (ref) {
806 | defineRefPropWarningGetter(props, displayName);
807 | }
808 | }
809 | }
810 |
811 | return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
812 | }
813 | function cloneAndReplaceKey(oldElement, newKey) {
814 | var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
815 | return newElement;
816 | }
817 | /**
818 | * Clone and return a new ReactElement using element as the starting point.
819 | * See https://reactjs.org/docs/react-api.html#cloneelement
820 | */
821 |
822 | function cloneElement(element, config, children) {
823 | if (!!(element === null || element === undefined)) {
824 | {
825 | throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
826 | }
827 | }
828 |
829 | var propName; // Original props are copied
830 |
831 | var props = assign({}, element.props); // Reserved names are extracted
832 |
833 |
834 | var key = element.key;
835 | var ref = element.ref; // Self is preserved since the owner is preserved.
836 |
837 | var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
838 | // transpiler, and the original source is probably a better indicator of the
839 | // true owner.
840 |
841 | var source = element._source; // Owner will be preserved, unless ref is overridden
842 |
843 | var owner = element._owner;
844 |
845 | if (config != null) {
846 | if (hasValidRef(config)) {
847 | // Silently steal the ref from the parent.
848 | ref = config.ref;
849 | owner = ReactCurrentOwner.current;
850 | }
851 |
852 | if (hasValidKey(config)) {
853 | key = '' + config.key;
854 | } // Remaining properties override existing props
855 |
856 |
857 | var defaultProps;
858 |
859 | if (element.type && element.type.defaultProps) {
860 | defaultProps = element.type.defaultProps;
861 | }
862 |
863 | for (propName in config) {
864 | if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
865 | if (config[propName] === undefined && defaultProps !== undefined) {
866 | // Resolve default props
867 | props[propName] = defaultProps[propName];
868 | } else {
869 | props[propName] = config[propName];
870 | }
871 | }
872 | }
873 | } // Children can be more than one argument, and those are transferred onto
874 | // the newly allocated props object.
875 |
876 |
877 | var childrenLength = arguments.length - 2;
878 |
879 | if (childrenLength === 1) {
880 | props.children = children;
881 | } else if (childrenLength > 1) {
882 | var childArray = Array(childrenLength);
883 |
884 | for (var i = 0; i < childrenLength; i++) {
885 | childArray[i] = arguments[i + 2];
886 | }
887 |
888 | props.children = childArray;
889 | }
890 |
891 | return ReactElement(element.type, key, ref, self, source, owner, props);
892 | }
893 | /**
894 | * Verifies the object is a ReactElement.
895 | * See https://reactjs.org/docs/react-api.html#isvalidelement
896 | * @param {?object} object
897 | * @return {boolean} True if `object` is a ReactElement.
898 | * @final
899 | */
900 |
901 | function isValidElement(object) {
902 | return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
903 | }
904 |
905 | var SEPARATOR = '.';
906 | var SUBSEPARATOR = ':';
907 | /**
908 | * Escape and wrap key so it is safe to use as a reactid
909 | *
910 | * @param {string} key to be escaped.
911 | * @return {string} the escaped key.
912 | */
913 |
914 | function escape(key) {
915 | var escapeRegex = /[=:]/g;
916 | var escaperLookup = {
917 | '=': '=0',
918 | ':': '=2'
919 | };
920 | var escapedString = key.replace(escapeRegex, function (match) {
921 | return escaperLookup[match];
922 | });
923 | return '$' + escapedString;
924 | }
925 | /**
926 | * TODO: Test that a single child and an array with one item have the same key
927 | * pattern.
928 | */
929 |
930 |
931 | var didWarnAboutMaps = false;
932 | var userProvidedKeyEscapeRegex = /\/+/g;
933 |
934 | function escapeUserProvidedKey(text) {
935 | return text.replace(userProvidedKeyEscapeRegex, '$&/');
936 | }
937 | /**
938 | * Generate a key string that identifies a element within a set.
939 | *
940 | * @param {*} element A element that could contain a manual key.
941 | * @param {number} index Index that is used if a manual key is not provided.
942 | * @return {string}
943 | */
944 |
945 |
946 | function getElementKey(element, index) {
947 | // Do some typechecking here since we call this blindly. We want to ensure
948 | // that we don't block potential future ES APIs.
949 | if (typeof element === 'object' && element !== null && element.key != null) {
950 | // Explicit key
951 | return escape('' + element.key);
952 | } // Implicit key determined by the index in the set
953 |
954 |
955 | return index.toString(36);
956 | }
957 |
958 | function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
959 | var type = typeof children;
960 |
961 | if (type === 'undefined' || type === 'boolean') {
962 | // All of the above are perceived as null.
963 | children = null;
964 | }
965 |
966 | var invokeCallback = false;
967 |
968 | if (children === null) {
969 | invokeCallback = true;
970 | } else {
971 | switch (type) {
972 | case 'string':
973 | case 'number':
974 | invokeCallback = true;
975 | break;
976 |
977 | case 'object':
978 | switch (children.$$typeof) {
979 | case REACT_ELEMENT_TYPE:
980 | case REACT_PORTAL_TYPE:
981 | invokeCallback = true;
982 | }
983 |
984 | }
985 | }
986 |
987 | if (invokeCallback) {
988 | var _child = children;
989 | var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
990 | // so that it's consistent if the number of children grows:
991 |
992 | var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
993 |
994 | if (Array.isArray(mappedChild)) {
995 | var escapedChildKey = '';
996 |
997 | if (childKey != null) {
998 | escapedChildKey = escapeUserProvidedKey(childKey) + '/';
999 | }
1000 |
1001 | mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
1002 | return c;
1003 | });
1004 | } else if (mappedChild != null) {
1005 | if (isValidElement(mappedChild)) {
1006 | mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
1007 | // traverseAllChildren used to do for objects as children
1008 | escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
1009 | mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
1010 | escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
1011 | }
1012 |
1013 | array.push(mappedChild);
1014 | }
1015 |
1016 | return 1;
1017 | }
1018 |
1019 | var child;
1020 | var nextName;
1021 | var subtreeCount = 0; // Count of children found in the current subtree.
1022 |
1023 | var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
1024 |
1025 | if (Array.isArray(children)) {
1026 | for (var i = 0; i < children.length; i++) {
1027 | child = children[i];
1028 | nextName = nextNamePrefix + getElementKey(child, i);
1029 | subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
1030 | }
1031 | } else {
1032 | var iteratorFn = getIteratorFn(children);
1033 |
1034 | if (typeof iteratorFn === 'function') {
1035 | var iterableChildren = children;
1036 |
1037 | {
1038 | // Warn about using Maps as children
1039 | if (iteratorFn === iterableChildren.entries) {
1040 | if (!didWarnAboutMaps) {
1041 | warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
1042 | }
1043 |
1044 | didWarnAboutMaps = true;
1045 | }
1046 | }
1047 |
1048 | var iterator = iteratorFn.call(iterableChildren);
1049 | var step;
1050 | var ii = 0;
1051 |
1052 | while (!(step = iterator.next()).done) {
1053 | child = step.value;
1054 | nextName = nextNamePrefix + getElementKey(child, ii++);
1055 | subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
1056 | }
1057 | } else if (type === 'object') {
1058 | var childrenString = '' + children;
1059 |
1060 | {
1061 | {
1062 | throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). If you meant to render a collection of children, use an array instead." );
1063 | }
1064 | }
1065 | }
1066 | }
1067 |
1068 | return subtreeCount;
1069 | }
1070 |
1071 | /**
1072 | * Maps children that are typically specified as `props.children`.
1073 | *
1074 | * See https://reactjs.org/docs/react-api.html#reactchildrenmap
1075 | *
1076 | * The provided mapFunction(child, index) will be called for each
1077 | * leaf child.
1078 | *
1079 | * @param {?*} children Children tree container.
1080 | * @param {function(*, int)} func The map function.
1081 | * @param {*} context Context for mapFunction.
1082 | * @return {object} Object containing the ordered map of results.
1083 | */
1084 | function mapChildren(children, func, context) {
1085 | if (children == null) {
1086 | return children;
1087 | }
1088 |
1089 | var result = [];
1090 | var count = 0;
1091 | mapIntoArray(children, result, '', '', function (child) {
1092 | return func.call(context, child, count++);
1093 | });
1094 | return result;
1095 | }
1096 | /**
1097 | * Count the number of children that are typically specified as
1098 | * `props.children`.
1099 | *
1100 | * See https://reactjs.org/docs/react-api.html#reactchildrencount
1101 | *
1102 | * @param {?*} children Children tree container.
1103 | * @return {number} The number of children.
1104 | */
1105 |
1106 |
1107 | function countChildren(children) {
1108 | var n = 0;
1109 | mapChildren(children, function () {
1110 | n++; // Don't return anything
1111 | });
1112 | return n;
1113 | }
1114 |
1115 | /**
1116 | * Iterates through children that are typically specified as `props.children`.
1117 | *
1118 | * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
1119 | *
1120 | * The provided forEachFunc(child, index) will be called for each
1121 | * leaf child.
1122 | *
1123 | * @param {?*} children Children tree container.
1124 | * @param {function(*, int)} forEachFunc
1125 | * @param {*} forEachContext Context for forEachContext.
1126 | */
1127 | function forEachChildren(children, forEachFunc, forEachContext) {
1128 | mapChildren(children, function () {
1129 | forEachFunc.apply(this, arguments); // Don't return anything.
1130 | }, forEachContext);
1131 | }
1132 | /**
1133 | * Flatten a children object (typically specified as `props.children`) and
1134 | * return an array with appropriately re-keyed children.
1135 | *
1136 | * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
1137 | */
1138 |
1139 |
1140 | function toArray(children) {
1141 | return mapChildren(children, function (child) {
1142 | return child;
1143 | }) || [];
1144 | }
1145 | /**
1146 | * Returns the first child in a collection of children and verifies that there
1147 | * is only one child in the collection.
1148 | *
1149 | * See https://reactjs.org/docs/react-api.html#reactchildrenonly
1150 | *
1151 | * The current implementation of this function assumes that a single child gets
1152 | * passed without a wrapper, but the purpose of this helper function is to
1153 | * abstract away the particular structure of children.
1154 | *
1155 | * @param {?object} children Child collection structure.
1156 | * @return {ReactElement} The first and only `ReactElement` contained in the
1157 | * structure.
1158 | */
1159 |
1160 |
1161 | function onlyChild(children) {
1162 | if (!isValidElement(children)) {
1163 | {
1164 | throw Error( "React.Children.only expected to receive a single React element child." );
1165 | }
1166 | }
1167 |
1168 | return children;
1169 | }
1170 |
1171 | function createContext(defaultValue, calculateChangedBits) {
1172 | if (calculateChangedBits === undefined) {
1173 | calculateChangedBits = null;
1174 | } else {
1175 | {
1176 | if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') {
1177 | error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits);
1178 | }
1179 | }
1180 | }
1181 |
1182 | var context = {
1183 | $$typeof: REACT_CONTEXT_TYPE,
1184 | _calculateChangedBits: calculateChangedBits,
1185 | // As a workaround to support multiple concurrent renderers, we categorize
1186 | // some renderers as primary and others as secondary. We only expect
1187 | // there to be two concurrent renderers at most: React Native (primary) and
1188 | // Fabric (secondary); React DOM (primary) and React ART (secondary).
1189 | // Secondary renderers store their context values on separate fields.
1190 | _currentValue: defaultValue,
1191 | _currentValue2: defaultValue,
1192 | // Used to track how many concurrent renderers this context currently
1193 | // supports within in a single renderer. Such as parallel server rendering.
1194 | _threadCount: 0,
1195 | // These are circular
1196 | Provider: null,
1197 | Consumer: null
1198 | };
1199 | context.Provider = {
1200 | $$typeof: REACT_PROVIDER_TYPE,
1201 | _context: context
1202 | };
1203 | var hasWarnedAboutUsingNestedContextConsumers = false;
1204 | var hasWarnedAboutUsingConsumerProvider = false;
1205 | var hasWarnedAboutDisplayNameOnConsumer = false;
1206 |
1207 | {
1208 | // A separate object, but proxies back to the original context object for
1209 | // backwards compatibility. It has a different $$typeof, so we can properly
1210 | // warn for the incorrect usage of Context as a Consumer.
1211 | var Consumer = {
1212 | $$typeof: REACT_CONTEXT_TYPE,
1213 | _context: context,
1214 | _calculateChangedBits: context._calculateChangedBits
1215 | }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
1216 |
1217 | Object.defineProperties(Consumer, {
1218 | Provider: {
1219 | get: function () {
1220 | if (!hasWarnedAboutUsingConsumerProvider) {
1221 | hasWarnedAboutUsingConsumerProvider = true;
1222 |
1223 | error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');
1224 | }
1225 |
1226 | return context.Provider;
1227 | },
1228 | set: function (_Provider) {
1229 | context.Provider = _Provider;
1230 | }
1231 | },
1232 | _currentValue: {
1233 | get: function () {
1234 | return context._currentValue;
1235 | },
1236 | set: function (_currentValue) {
1237 | context._currentValue = _currentValue;
1238 | }
1239 | },
1240 | _currentValue2: {
1241 | get: function () {
1242 | return context._currentValue2;
1243 | },
1244 | set: function (_currentValue2) {
1245 | context._currentValue2 = _currentValue2;
1246 | }
1247 | },
1248 | _threadCount: {
1249 | get: function () {
1250 | return context._threadCount;
1251 | },
1252 | set: function (_threadCount) {
1253 | context._threadCount = _threadCount;
1254 | }
1255 | },
1256 | Consumer: {
1257 | get: function () {
1258 | if (!hasWarnedAboutUsingNestedContextConsumers) {
1259 | hasWarnedAboutUsingNestedContextConsumers = true;
1260 |
1261 | error('Rendering is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');
1262 | }
1263 |
1264 | return context.Consumer;
1265 | }
1266 | },
1267 | displayName: {
1268 | get: function () {
1269 | return context.displayName;
1270 | },
1271 | set: function (displayName) {
1272 | if (!hasWarnedAboutDisplayNameOnConsumer) {
1273 | warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
1274 |
1275 | hasWarnedAboutDisplayNameOnConsumer = true;
1276 | }
1277 | }
1278 | }
1279 | }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
1280 |
1281 | context.Consumer = Consumer;
1282 | }
1283 |
1284 | {
1285 | context._currentRenderer = null;
1286 | context._currentRenderer2 = null;
1287 | }
1288 |
1289 | return context;
1290 | }
1291 |
1292 | var Uninitialized = -1;
1293 | var Pending = 0;
1294 | var Resolved = 1;
1295 | var Rejected = 2;
1296 |
1297 | function lazyInitializer(payload) {
1298 | if (payload._status === Uninitialized) {
1299 | var ctor = payload._result;
1300 | var thenable = ctor(); // Transition to the next state.
1301 |
1302 | var pending = payload;
1303 | pending._status = Pending;
1304 | pending._result = thenable;
1305 | thenable.then(function (moduleObject) {
1306 | if (payload._status === Pending) {
1307 | var defaultExport = moduleObject.default;
1308 |
1309 | {
1310 | if (defaultExport === undefined) {
1311 | error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
1312 | 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
1313 | }
1314 | } // Transition to the next state.
1315 |
1316 |
1317 | var resolved = payload;
1318 | resolved._status = Resolved;
1319 | resolved._result = defaultExport;
1320 | }
1321 | }, function (error) {
1322 | if (payload._status === Pending) {
1323 | // Transition to the next state.
1324 | var rejected = payload;
1325 | rejected._status = Rejected;
1326 | rejected._result = error;
1327 | }
1328 | });
1329 | }
1330 |
1331 | if (payload._status === Resolved) {
1332 | return payload._result;
1333 | } else {
1334 | throw payload._result;
1335 | }
1336 | }
1337 |
1338 | function lazy(ctor) {
1339 | var payload = {
1340 | // We use these fields to store the result.
1341 | _status: -1,
1342 | _result: ctor
1343 | };
1344 | var lazyType = {
1345 | $$typeof: REACT_LAZY_TYPE,
1346 | _payload: payload,
1347 | _init: lazyInitializer
1348 | };
1349 |
1350 | {
1351 | // In production, this would just set it on the object.
1352 | var defaultProps;
1353 | var propTypes; // $FlowFixMe
1354 |
1355 | Object.defineProperties(lazyType, {
1356 | defaultProps: {
1357 | configurable: true,
1358 | get: function () {
1359 | return defaultProps;
1360 | },
1361 | set: function (newDefaultProps) {
1362 | error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
1363 |
1364 | defaultProps = newDefaultProps; // Match production behavior more closely:
1365 | // $FlowFixMe
1366 |
1367 | Object.defineProperty(lazyType, 'defaultProps', {
1368 | enumerable: true
1369 | });
1370 | }
1371 | },
1372 | propTypes: {
1373 | configurable: true,
1374 | get: function () {
1375 | return propTypes;
1376 | },
1377 | set: function (newPropTypes) {
1378 | error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
1379 |
1380 | propTypes = newPropTypes; // Match production behavior more closely:
1381 | // $FlowFixMe
1382 |
1383 | Object.defineProperty(lazyType, 'propTypes', {
1384 | enumerable: true
1385 | });
1386 | }
1387 | }
1388 | });
1389 | }
1390 |
1391 | return lazyType;
1392 | }
1393 |
1394 | function forwardRef(render) {
1395 | {
1396 | if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
1397 | error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
1398 | } else if (typeof render !== 'function') {
1399 | error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
1400 | } else {
1401 | if (render.length !== 0 && render.length !== 2) {
1402 | error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
1403 | }
1404 | }
1405 |
1406 | if (render != null) {
1407 | if (render.defaultProps != null || render.propTypes != null) {
1408 | error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
1409 | }
1410 | }
1411 | }
1412 |
1413 | var elementType = {
1414 | $$typeof: REACT_FORWARD_REF_TYPE,
1415 | render: render
1416 | };
1417 |
1418 | {
1419 | var ownName;
1420 | Object.defineProperty(elementType, 'displayName', {
1421 | enumerable: false,
1422 | configurable: true,
1423 | get: function () {
1424 | return ownName;
1425 | },
1426 | set: function (name) {
1427 | ownName = name;
1428 |
1429 | if (render.displayName == null) {
1430 | render.displayName = name;
1431 | }
1432 | }
1433 | });
1434 | }
1435 |
1436 | return elementType;
1437 | }
1438 |
1439 | // Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
1440 |
1441 | var enableScopeAPI = false; // Experimental Create Event Handle API.
1442 |
1443 | function isValidElementType(type) {
1444 | if (typeof type === 'string' || typeof type === 'function') {
1445 | return true;
1446 | } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
1447 |
1448 |
1449 | if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) {
1450 | return true;
1451 | }
1452 |
1453 | if (typeof type === 'object' && type !== null) {
1454 | if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
1455 | return true;
1456 | }
1457 | }
1458 |
1459 | return false;
1460 | }
1461 |
1462 | function memo(type, compare) {
1463 | {
1464 | if (!isValidElementType(type)) {
1465 | error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
1466 | }
1467 | }
1468 |
1469 | var elementType = {
1470 | $$typeof: REACT_MEMO_TYPE,
1471 | type: type,
1472 | compare: compare === undefined ? null : compare
1473 | };
1474 |
1475 | {
1476 | var ownName;
1477 | Object.defineProperty(elementType, 'displayName', {
1478 | enumerable: false,
1479 | configurable: true,
1480 | get: function () {
1481 | return ownName;
1482 | },
1483 | set: function (name) {
1484 | ownName = name;
1485 |
1486 | if (type.displayName == null) {
1487 | type.displayName = name;
1488 | }
1489 | }
1490 | });
1491 | }
1492 |
1493 | return elementType;
1494 | }
1495 |
1496 | function resolveDispatcher() {
1497 | var dispatcher = ReactCurrentDispatcher.current;
1498 |
1499 | if (!(dispatcher !== null)) {
1500 | {
1501 | throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." );
1502 | }
1503 | }
1504 |
1505 | return dispatcher;
1506 | }
1507 |
1508 | function useContext(Context, unstable_observedBits) {
1509 | var dispatcher = resolveDispatcher();
1510 |
1511 | {
1512 | if (unstable_observedBits !== undefined) {
1513 | error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://reactjs.org/link/rules-of-hooks' : '');
1514 | } // TODO: add a more generic warning for invalid values.
1515 |
1516 |
1517 | if (Context._context !== undefined) {
1518 | var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
1519 | // and nobody should be using this in existing code.
1520 |
1521 | if (realContext.Consumer === Context) {
1522 | error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
1523 | } else if (realContext.Provider === Context) {
1524 | error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
1525 | }
1526 | }
1527 | }
1528 |
1529 | return dispatcher.useContext(Context, unstable_observedBits);
1530 | }
1531 | function useState(initialState) {
1532 | var dispatcher = resolveDispatcher();
1533 | return dispatcher.useState(initialState);
1534 | }
1535 | function useReducer(reducer, initialArg, init) {
1536 | var dispatcher = resolveDispatcher();
1537 | return dispatcher.useReducer(reducer, initialArg, init);
1538 | }
1539 | function useRef(initialValue) {
1540 | var dispatcher = resolveDispatcher();
1541 | return dispatcher.useRef(initialValue);
1542 | }
1543 | function useEffect(create, deps) {
1544 | var dispatcher = resolveDispatcher();
1545 | return dispatcher.useEffect(create, deps);
1546 | }
1547 | function useLayoutEffect(create, deps) {
1548 | var dispatcher = resolveDispatcher();
1549 | return dispatcher.useLayoutEffect(create, deps);
1550 | }
1551 | function useCallback(callback, deps) {
1552 | var dispatcher = resolveDispatcher();
1553 | return dispatcher.useCallback(callback, deps);
1554 | }
1555 | function useMemo(create, deps) {
1556 | var dispatcher = resolveDispatcher();
1557 | return dispatcher.useMemo(create, deps);
1558 | }
1559 | function useImperativeHandle(ref, create, deps) {
1560 | var dispatcher = resolveDispatcher();
1561 | return dispatcher.useImperativeHandle(ref, create, deps);
1562 | }
1563 | function useDebugValue(value, formatterFn) {
1564 | {
1565 | var dispatcher = resolveDispatcher();
1566 | return dispatcher.useDebugValue(value, formatterFn);
1567 | }
1568 | }
1569 |
1570 | // Helpers to patch console.logs to avoid logging during side-effect free
1571 | // replaying on render function. This currently only patches the object
1572 | // lazily which won't cover if the log function was extracted eagerly.
1573 | // We could also eagerly patch the method.
1574 | var disabledDepth = 0;
1575 | var prevLog;
1576 | var prevInfo;
1577 | var prevWarn;
1578 | var prevError;
1579 | var prevGroup;
1580 | var prevGroupCollapsed;
1581 | var prevGroupEnd;
1582 |
1583 | function disabledLog() {}
1584 |
1585 | disabledLog.__reactDisabledLog = true;
1586 | function disableLogs() {
1587 | {
1588 | if (disabledDepth === 0) {
1589 | /* eslint-disable react-internal/no-production-logging */
1590 | prevLog = console.log;
1591 | prevInfo = console.info;
1592 | prevWarn = console.warn;
1593 | prevError = console.error;
1594 | prevGroup = console.group;
1595 | prevGroupCollapsed = console.groupCollapsed;
1596 | prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
1597 |
1598 | var props = {
1599 | configurable: true,
1600 | enumerable: true,
1601 | value: disabledLog,
1602 | writable: true
1603 | }; // $FlowFixMe Flow thinks console is immutable.
1604 |
1605 | Object.defineProperties(console, {
1606 | info: props,
1607 | log: props,
1608 | warn: props,
1609 | error: props,
1610 | group: props,
1611 | groupCollapsed: props,
1612 | groupEnd: props
1613 | });
1614 | /* eslint-enable react-internal/no-production-logging */
1615 | }
1616 |
1617 | disabledDepth++;
1618 | }
1619 | }
1620 | function reenableLogs() {
1621 | {
1622 | disabledDepth--;
1623 |
1624 | if (disabledDepth === 0) {
1625 | /* eslint-disable react-internal/no-production-logging */
1626 | var props = {
1627 | configurable: true,
1628 | enumerable: true,
1629 | writable: true
1630 | }; // $FlowFixMe Flow thinks console is immutable.
1631 |
1632 | Object.defineProperties(console, {
1633 | log: assign({}, props, {
1634 | value: prevLog
1635 | }),
1636 | info: assign({}, props, {
1637 | value: prevInfo
1638 | }),
1639 | warn: assign({}, props, {
1640 | value: prevWarn
1641 | }),
1642 | error: assign({}, props, {
1643 | value: prevError
1644 | }),
1645 | group: assign({}, props, {
1646 | value: prevGroup
1647 | }),
1648 | groupCollapsed: assign({}, props, {
1649 | value: prevGroupCollapsed
1650 | }),
1651 | groupEnd: assign({}, props, {
1652 | value: prevGroupEnd
1653 | })
1654 | });
1655 | /* eslint-enable react-internal/no-production-logging */
1656 | }
1657 |
1658 | if (disabledDepth < 0) {
1659 | error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
1660 | }
1661 | }
1662 | }
1663 |
1664 | var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
1665 | var prefix;
1666 | function describeBuiltInComponentFrame(name, source, ownerFn) {
1667 | {
1668 | if (prefix === undefined) {
1669 | // Extract the VM specific prefix used by each line.
1670 | try {
1671 | throw Error();
1672 | } catch (x) {
1673 | var match = x.stack.trim().match(/\n( *(at )?)/);
1674 | prefix = match && match[1] || '';
1675 | }
1676 | } // We use the prefix to ensure our stacks line up with native stack frames.
1677 |
1678 |
1679 | return '\n' + prefix + name;
1680 | }
1681 | }
1682 | var reentry = false;
1683 | var componentFrameCache;
1684 |
1685 | {
1686 | var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
1687 | componentFrameCache = new PossiblyWeakMap();
1688 | }
1689 |
1690 | function describeNativeComponentFrame(fn, construct) {
1691 | // If something asked for a stack inside a fake render, it should get ignored.
1692 | if (!fn || reentry) {
1693 | return '';
1694 | }
1695 |
1696 | {
1697 | var frame = componentFrameCache.get(fn);
1698 |
1699 | if (frame !== undefined) {
1700 | return frame;
1701 | }
1702 | }
1703 |
1704 | var control;
1705 | reentry = true;
1706 | var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
1707 |
1708 | Error.prepareStackTrace = undefined;
1709 | var previousDispatcher;
1710 |
1711 | {
1712 | previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
1713 | // for warnings.
1714 |
1715 | ReactCurrentDispatcher$1.current = null;
1716 | disableLogs();
1717 | }
1718 |
1719 | try {
1720 | // This should throw.
1721 | if (construct) {
1722 | // Something should be setting the props in the constructor.
1723 | var Fake = function () {
1724 | throw Error();
1725 | }; // $FlowFixMe
1726 |
1727 |
1728 | Object.defineProperty(Fake.prototype, 'props', {
1729 | set: function () {
1730 | // We use a throwing setter instead of frozen or non-writable props
1731 | // because that won't throw in a non-strict mode function.
1732 | throw Error();
1733 | }
1734 | });
1735 |
1736 | if (typeof Reflect === 'object' && Reflect.construct) {
1737 | // We construct a different control for this case to include any extra
1738 | // frames added by the construct call.
1739 | try {
1740 | Reflect.construct(Fake, []);
1741 | } catch (x) {
1742 | control = x;
1743 | }
1744 |
1745 | Reflect.construct(fn, [], Fake);
1746 | } else {
1747 | try {
1748 | Fake.call();
1749 | } catch (x) {
1750 | control = x;
1751 | }
1752 |
1753 | fn.call(Fake.prototype);
1754 | }
1755 | } else {
1756 | try {
1757 | throw Error();
1758 | } catch (x) {
1759 | control = x;
1760 | }
1761 |
1762 | fn();
1763 | }
1764 | } catch (sample) {
1765 | // This is inlined manually because closure doesn't do it for us.
1766 | if (sample && control && typeof sample.stack === 'string') {
1767 | // This extracts the first frame from the sample that isn't also in the control.
1768 | // Skipping one frame that we assume is the frame that calls the two.
1769 | var sampleLines = sample.stack.split('\n');
1770 | var controlLines = control.stack.split('\n');
1771 | var s = sampleLines.length - 1;
1772 | var c = controlLines.length - 1;
1773 |
1774 | while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
1775 | // We expect at least one stack frame to be shared.
1776 | // Typically this will be the root most one. However, stack frames may be
1777 | // cut off due to maximum stack limits. In this case, one maybe cut off
1778 | // earlier than the other. We assume that the sample is longer or the same
1779 | // and there for cut off earlier. So we should find the root most frame in
1780 | // the sample somewhere in the control.
1781 | c--;
1782 | }
1783 |
1784 | for (; s >= 1 && c >= 0; s--, c--) {
1785 | // Next we find the first one that isn't the same which should be the
1786 | // frame that called our sample function and the control.
1787 | if (sampleLines[s] !== controlLines[c]) {
1788 | // In V8, the first line is describing the message but other VMs don't.
1789 | // If we're about to return the first line, and the control is also on the same
1790 | // line, that's a pretty good indicator that our sample threw at same line as
1791 | // the control. I.e. before we entered the sample frame. So we ignore this result.
1792 | // This can happen if you passed a class to function component, or non-function.
1793 | if (s !== 1 || c !== 1) {
1794 | do {
1795 | s--;
1796 | c--; // We may still have similar intermediate frames from the construct call.
1797 | // The next one that isn't the same should be our match though.
1798 |
1799 | if (c < 0 || sampleLines[s] !== controlLines[c]) {
1800 | // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
1801 | var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
1802 |
1803 | {
1804 | if (typeof fn === 'function') {
1805 | componentFrameCache.set(fn, _frame);
1806 | }
1807 | } // Return the line we found.
1808 |
1809 |
1810 | return _frame;
1811 | }
1812 | } while (s >= 1 && c >= 0);
1813 | }
1814 |
1815 | break;
1816 | }
1817 | }
1818 | }
1819 | } finally {
1820 | reentry = false;
1821 |
1822 | {
1823 | ReactCurrentDispatcher$1.current = previousDispatcher;
1824 | reenableLogs();
1825 | }
1826 |
1827 | Error.prepareStackTrace = previousPrepareStackTrace;
1828 | } // Fallback to just using the name if we couldn't make it throw.
1829 |
1830 |
1831 | var name = fn ? fn.displayName || fn.name : '';
1832 | var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
1833 |
1834 | {
1835 | if (typeof fn === 'function') {
1836 | componentFrameCache.set(fn, syntheticFrame);
1837 | }
1838 | }
1839 |
1840 | return syntheticFrame;
1841 | }
1842 | function describeFunctionComponentFrame(fn, source, ownerFn) {
1843 | {
1844 | return describeNativeComponentFrame(fn, false);
1845 | }
1846 | }
1847 |
1848 | function shouldConstruct(Component) {
1849 | var prototype = Component.prototype;
1850 | return !!(prototype && prototype.isReactComponent);
1851 | }
1852 |
1853 | function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
1854 |
1855 | if (type == null) {
1856 | return '';
1857 | }
1858 |
1859 | if (typeof type === 'function') {
1860 | {
1861 | return describeNativeComponentFrame(type, shouldConstruct(type));
1862 | }
1863 | }
1864 |
1865 | if (typeof type === 'string') {
1866 | return describeBuiltInComponentFrame(type);
1867 | }
1868 |
1869 | switch (type) {
1870 | case exports.Suspense:
1871 | return describeBuiltInComponentFrame('Suspense');
1872 |
1873 | case REACT_SUSPENSE_LIST_TYPE:
1874 | return describeBuiltInComponentFrame('SuspenseList');
1875 | }
1876 |
1877 | if (typeof type === 'object') {
1878 | switch (type.$$typeof) {
1879 | case REACT_FORWARD_REF_TYPE:
1880 | return describeFunctionComponentFrame(type.render);
1881 |
1882 | case REACT_MEMO_TYPE:
1883 | // Memo may contain any component type so we recursively resolve it.
1884 | return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
1885 |
1886 | case REACT_BLOCK_TYPE:
1887 | return describeFunctionComponentFrame(type._render);
1888 |
1889 | case REACT_LAZY_TYPE:
1890 | {
1891 | var lazyComponent = type;
1892 | var payload = lazyComponent._payload;
1893 | var init = lazyComponent._init;
1894 |
1895 | try {
1896 | // Lazy may contain any component type so we recursively resolve it.
1897 | return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
1898 | } catch (x) {}
1899 | }
1900 | }
1901 | }
1902 |
1903 | return '';
1904 | }
1905 |
1906 | var loggedTypeFailures = {};
1907 | var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1908 |
1909 | function setCurrentlyValidatingElement(element) {
1910 | {
1911 | if (element) {
1912 | var owner = element._owner;
1913 | var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1914 | ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1915 | } else {
1916 | ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1917 | }
1918 | }
1919 | }
1920 |
1921 | function checkPropTypes(typeSpecs, values, location, componentName, element) {
1922 | {
1923 | // $FlowFixMe This is okay but Flow doesn't know it.
1924 | var has = Function.call.bind(Object.prototype.hasOwnProperty);
1925 |
1926 | for (var typeSpecName in typeSpecs) {
1927 | if (has(typeSpecs, typeSpecName)) {
1928 | var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
1929 | // fail the render phase where it didn't fail before. So we log it.
1930 | // After these have been cleaned up, we'll let them throw.
1931 |
1932 | try {
1933 | // This is intentionally an invariant that gets caught. It's the same
1934 | // behavior as without this statement except with a better message.
1935 | if (typeof typeSpecs[typeSpecName] !== 'function') {
1936 | var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
1937 | err.name = 'Invariant Violation';
1938 | throw err;
1939 | }
1940 |
1941 | error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
1942 | } catch (ex) {
1943 | error$1 = ex;
1944 | }
1945 |
1946 | if (error$1 && !(error$1 instanceof Error)) {
1947 | setCurrentlyValidatingElement(element);
1948 |
1949 | error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
1950 |
1951 | setCurrentlyValidatingElement(null);
1952 | }
1953 |
1954 | if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
1955 | // Only monitor this failure once because there tends to be a lot of the
1956 | // same error.
1957 | loggedTypeFailures[error$1.message] = true;
1958 | setCurrentlyValidatingElement(element);
1959 |
1960 | error('Failed %s type: %s', location, error$1.message);
1961 |
1962 | setCurrentlyValidatingElement(null);
1963 | }
1964 | }
1965 | }
1966 | }
1967 | }
1968 |
1969 | function setCurrentlyValidatingElement$1(element) {
1970 | {
1971 | if (element) {
1972 | var owner = element._owner;
1973 | var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1974 | setExtraStackFrame(stack);
1975 | } else {
1976 | setExtraStackFrame(null);
1977 | }
1978 | }
1979 | }
1980 |
1981 | var propTypesMisspellWarningShown;
1982 |
1983 | {
1984 | propTypesMisspellWarningShown = false;
1985 | }
1986 |
1987 | function getDeclarationErrorAddendum() {
1988 | if (ReactCurrentOwner.current) {
1989 | var name = getComponentName(ReactCurrentOwner.current.type);
1990 |
1991 | if (name) {
1992 | return '\n\nCheck the render method of `' + name + '`.';
1993 | }
1994 | }
1995 |
1996 | return '';
1997 | }
1998 |
1999 | function getSourceInfoErrorAddendum(source) {
2000 | if (source !== undefined) {
2001 | var fileName = source.fileName.replace(/^.*[\\\/]/, '');
2002 | var lineNumber = source.lineNumber;
2003 | return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
2004 | }
2005 |
2006 | return '';
2007 | }
2008 |
2009 | function getSourceInfoErrorAddendumForProps(elementProps) {
2010 | if (elementProps !== null && elementProps !== undefined) {
2011 | return getSourceInfoErrorAddendum(elementProps.__source);
2012 | }
2013 |
2014 | return '';
2015 | }
2016 | /**
2017 | * Warn if there's no key explicitly set on dynamic arrays of children or
2018 | * object keys are not valid. This allows us to keep track of children between
2019 | * updates.
2020 | */
2021 |
2022 |
2023 | var ownerHasKeyUseWarning = {};
2024 |
2025 | function getCurrentComponentErrorInfo(parentType) {
2026 | var info = getDeclarationErrorAddendum();
2027 |
2028 | if (!info) {
2029 | var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
2030 |
2031 | if (parentName) {
2032 | info = "\n\nCheck the top-level render call using <" + parentName + ">.";
2033 | }
2034 | }
2035 |
2036 | return info;
2037 | }
2038 | /**
2039 | * Warn if the element doesn't have an explicit key assigned to it.
2040 | * This element is in an array. The array could grow and shrink or be
2041 | * reordered. All children that haven't already been validated are required to
2042 | * have a "key" property assigned to it. Error statuses are cached so a warning
2043 | * will only be shown once.
2044 | *
2045 | * @internal
2046 | * @param {ReactElement} element Element that requires a key.
2047 | * @param {*} parentType element's parent's type.
2048 | */
2049 |
2050 |
2051 | function validateExplicitKey(element, parentType) {
2052 | if (!element._store || element._store.validated || element.key != null) {
2053 | return;
2054 | }
2055 |
2056 | element._store.validated = true;
2057 | var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
2058 |
2059 | if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
2060 | return;
2061 | }
2062 |
2063 | ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
2064 | // property, it may be the creator of the child that's responsible for
2065 | // assigning it a key.
2066 |
2067 | var childOwner = '';
2068 |
2069 | if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
2070 | // Give the component that originally created this child.
2071 | childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
2072 | }
2073 |
2074 | {
2075 | setCurrentlyValidatingElement$1(element);
2076 |
2077 | error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
2078 |
2079 | setCurrentlyValidatingElement$1(null);
2080 | }
2081 | }
2082 | /**
2083 | * Ensure that every element either is passed in a static location, in an
2084 | * array with an explicit keys property defined, or in an object literal
2085 | * with valid key property.
2086 | *
2087 | * @internal
2088 | * @param {ReactNode} node Statically passed child of any type.
2089 | * @param {*} parentType node's parent's type.
2090 | */
2091 |
2092 |
2093 | function validateChildKeys(node, parentType) {
2094 | if (typeof node !== 'object') {
2095 | return;
2096 | }
2097 |
2098 | if (Array.isArray(node)) {
2099 | for (var i = 0; i < node.length; i++) {
2100 | var child = node[i];
2101 |
2102 | if (isValidElement(child)) {
2103 | validateExplicitKey(child, parentType);
2104 | }
2105 | }
2106 | } else if (isValidElement(node)) {
2107 | // This element was passed in a valid location.
2108 | if (node._store) {
2109 | node._store.validated = true;
2110 | }
2111 | } else if (node) {
2112 | var iteratorFn = getIteratorFn(node);
2113 |
2114 | if (typeof iteratorFn === 'function') {
2115 | // Entry iterators used to provide implicit keys,
2116 | // but now we print a separate warning for them later.
2117 | if (iteratorFn !== node.entries) {
2118 | var iterator = iteratorFn.call(node);
2119 | var step;
2120 |
2121 | while (!(step = iterator.next()).done) {
2122 | if (isValidElement(step.value)) {
2123 | validateExplicitKey(step.value, parentType);
2124 | }
2125 | }
2126 | }
2127 | }
2128 | }
2129 | }
2130 | /**
2131 | * Given an element, validate that its props follow the propTypes definition,
2132 | * provided by the type.
2133 | *
2134 | * @param {ReactElement} element
2135 | */
2136 |
2137 |
2138 | function validatePropTypes(element) {
2139 | {
2140 | var type = element.type;
2141 |
2142 | if (type === null || type === undefined || typeof type === 'string') {
2143 | return;
2144 | }
2145 |
2146 | var propTypes;
2147 |
2148 | if (typeof type === 'function') {
2149 | propTypes = type.propTypes;
2150 | } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
2151 | // Inner props are checked in the reconciler.
2152 | type.$$typeof === REACT_MEMO_TYPE)) {
2153 | propTypes = type.propTypes;
2154 | } else {
2155 | return;
2156 | }
2157 |
2158 | if (propTypes) {
2159 | // Intentionally inside to avoid triggering lazy initializers:
2160 | var name = getComponentName(type);
2161 | checkPropTypes(propTypes, element.props, 'prop', name, element);
2162 | } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
2163 | propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
2164 |
2165 | var _name = getComponentName(type);
2166 |
2167 | error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
2168 | }
2169 |
2170 | if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
2171 | error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
2172 | }
2173 | }
2174 | }
2175 | /**
2176 | * Given a fragment, validate that it can only be provided with fragment props
2177 | * @param {ReactElement} fragment
2178 | */
2179 |
2180 |
2181 | function validateFragmentProps(fragment) {
2182 | {
2183 | var keys = Object.keys(fragment.props);
2184 |
2185 | for (var i = 0; i < keys.length; i++) {
2186 | var key = keys[i];
2187 |
2188 | if (key !== 'children' && key !== 'key') {
2189 | setCurrentlyValidatingElement$1(fragment);
2190 |
2191 | error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
2192 |
2193 | setCurrentlyValidatingElement$1(null);
2194 | break;
2195 | }
2196 | }
2197 |
2198 | if (fragment.ref !== null) {
2199 | setCurrentlyValidatingElement$1(fragment);
2200 |
2201 | error('Invalid attribute `ref` supplied to `React.Fragment`.');
2202 |
2203 | setCurrentlyValidatingElement$1(null);
2204 | }
2205 | }
2206 | }
2207 | function createElementWithValidation(type, props, children) {
2208 | var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
2209 | // succeed and there will likely be errors in render.
2210 |
2211 | if (!validType) {
2212 | var info = '';
2213 |
2214 | if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2215 | info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
2216 | }
2217 |
2218 | var sourceInfo = getSourceInfoErrorAddendumForProps(props);
2219 |
2220 | if (sourceInfo) {
2221 | info += sourceInfo;
2222 | } else {
2223 | info += getDeclarationErrorAddendum();
2224 | }
2225 |
2226 | var typeString;
2227 |
2228 | if (type === null) {
2229 | typeString = 'null';
2230 | } else if (Array.isArray(type)) {
2231 | typeString = 'array';
2232 | } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
2233 | typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />";
2234 | info = ' Did you accidentally export a JSX literal instead of a component?';
2235 | } else {
2236 | typeString = typeof type;
2237 | }
2238 |
2239 | {
2240 | error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
2241 | }
2242 | }
2243 |
2244 | var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
2245 | // TODO: Drop this when these are no longer allowed as the type argument.
2246 |
2247 | if (element == null) {
2248 | return element;
2249 | } // Skip key warning if the type isn't valid since our key validation logic
2250 | // doesn't expect a non-string/function type and can throw confusing errors.
2251 | // We don't want exception behavior to differ between dev and prod.
2252 | // (Rendering will throw with a helpful message and as soon as the type is
2253 | // fixed, the key warnings will appear.)
2254 |
2255 |
2256 | if (validType) {
2257 | for (var i = 2; i < arguments.length; i++) {
2258 | validateChildKeys(arguments[i], type);
2259 | }
2260 | }
2261 |
2262 | if (type === exports.Fragment) {
2263 | validateFragmentProps(element);
2264 | } else {
2265 | validatePropTypes(element);
2266 | }
2267 |
2268 | return element;
2269 | }
2270 | var didWarnAboutDeprecatedCreateFactory = false;
2271 | function createFactoryWithValidation(type) {
2272 | var validatedFactory = createElementWithValidation.bind(null, type);
2273 | validatedFactory.type = type;
2274 |
2275 | {
2276 | if (!didWarnAboutDeprecatedCreateFactory) {
2277 | didWarnAboutDeprecatedCreateFactory = true;
2278 |
2279 | warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
2280 | } // Legacy hook: remove it
2281 |
2282 |
2283 | Object.defineProperty(validatedFactory, 'type', {
2284 | enumerable: false,
2285 | get: function () {
2286 | warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
2287 |
2288 | Object.defineProperty(this, 'type', {
2289 | value: type
2290 | });
2291 | return type;
2292 | }
2293 | });
2294 | }
2295 |
2296 | return validatedFactory;
2297 | }
2298 | function cloneElementWithValidation(element, props, children) {
2299 | var newElement = cloneElement.apply(this, arguments);
2300 |
2301 | for (var i = 2; i < arguments.length; i++) {
2302 | validateChildKeys(arguments[i], newElement.type);
2303 | }
2304 |
2305 | validatePropTypes(newElement);
2306 | return newElement;
2307 | }
2308 |
2309 | var enableSchedulerDebugging = false;
2310 | var enableProfiling = true;
2311 |
2312 | var requestHostCallback;
2313 | var requestHostTimeout;
2314 | var cancelHostTimeout;
2315 | var shouldYieldToHost;
2316 | var requestPaint;
2317 | var getCurrentTime;
2318 | var forceFrameRate;
2319 | var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
2320 |
2321 | if (hasPerformanceNow) {
2322 | var localPerformance = performance;
2323 |
2324 | getCurrentTime = function () {
2325 | return localPerformance.now();
2326 | };
2327 | } else {
2328 | var localDate = Date;
2329 | var initialTime = localDate.now();
2330 |
2331 | getCurrentTime = function () {
2332 | return localDate.now() - initialTime;
2333 | };
2334 | }
2335 |
2336 | if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive
2337 | // implementation using setTimeout.
2338 | typeof window === 'undefined' || // Check if MessageChannel is supported, too.
2339 | typeof MessageChannel !== 'function') {
2340 | // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,
2341 | // fallback to a naive implementation.
2342 | var _callback = null;
2343 | var _timeoutID = null;
2344 |
2345 | var _flushCallback = function () {
2346 | if (_callback !== null) {
2347 | try {
2348 | var currentTime = getCurrentTime();
2349 | var hasRemainingTime = true;
2350 |
2351 | _callback(hasRemainingTime, currentTime);
2352 |
2353 | _callback = null;
2354 | } catch (e) {
2355 | setTimeout(_flushCallback, 0);
2356 | throw e;
2357 | }
2358 | }
2359 | };
2360 |
2361 | requestHostCallback = function (cb) {
2362 | if (_callback !== null) {
2363 | // Protect against re-entrancy.
2364 | setTimeout(requestHostCallback, 0, cb);
2365 | } else {
2366 | _callback = cb;
2367 | setTimeout(_flushCallback, 0);
2368 | }
2369 | };
2370 |
2371 | requestHostTimeout = function (cb, ms) {
2372 | _timeoutID = setTimeout(cb, ms);
2373 | };
2374 |
2375 | cancelHostTimeout = function () {
2376 | clearTimeout(_timeoutID);
2377 | };
2378 |
2379 | shouldYieldToHost = function () {
2380 | return false;
2381 | };
2382 |
2383 | requestPaint = forceFrameRate = function () {};
2384 | } else {
2385 | // Capture local references to native APIs, in case a polyfill overrides them.
2386 | var _setTimeout = window.setTimeout;
2387 | var _clearTimeout = window.clearTimeout;
2388 |
2389 | if (typeof console !== 'undefined') {
2390 | // TODO: Scheduler no longer requires these methods to be polyfilled. But
2391 | // maybe we want to continue warning if they don't exist, to preserve the
2392 | // option to rely on it in the future?
2393 | var requestAnimationFrame = window.requestAnimationFrame;
2394 | var cancelAnimationFrame = window.cancelAnimationFrame;
2395 |
2396 | if (typeof requestAnimationFrame !== 'function') {
2397 | // Using console['error'] to evade Babel and ESLint
2398 | console['error']("This browser doesn't support requestAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
2399 | }
2400 |
2401 | if (typeof cancelAnimationFrame !== 'function') {
2402 | // Using console['error'] to evade Babel and ESLint
2403 | console['error']("This browser doesn't support cancelAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
2404 | }
2405 | }
2406 |
2407 | var isMessageLoopRunning = false;
2408 | var scheduledHostCallback = null;
2409 | var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
2410 | // thread, like user events. By default, it yields multiple times per frame.
2411 | // It does not attempt to align with frame boundaries, since most tasks don't
2412 | // need to be frame aligned; for those that do, use requestAnimationFrame.
2413 |
2414 | var yieldInterval = 5;
2415 | var deadline = 0; // TODO: Make this configurable
2416 |
2417 | {
2418 | // `isInputPending` is not available. Since we have no way of knowing if
2419 | // there's pending input, always yield at the end of the frame.
2420 | shouldYieldToHost = function () {
2421 | return getCurrentTime() >= deadline;
2422 | }; // Since we yield every frame regardless, `requestPaint` has no effect.
2423 |
2424 |
2425 | requestPaint = function () {};
2426 | }
2427 |
2428 | forceFrameRate = function (fps) {
2429 | if (fps < 0 || fps > 125) {
2430 | // Using console['error'] to evade Babel and ESLint
2431 | console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
2432 | return;
2433 | }
2434 |
2435 | if (fps > 0) {
2436 | yieldInterval = Math.floor(1000 / fps);
2437 | } else {
2438 | // reset the framerate
2439 | yieldInterval = 5;
2440 | }
2441 | };
2442 |
2443 | var performWorkUntilDeadline = function () {
2444 | if (scheduledHostCallback !== null) {
2445 | var currentTime = getCurrentTime(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync
2446 | // cycle. This means there's always time remaining at the beginning of
2447 | // the message event.
2448 |
2449 | deadline = currentTime + yieldInterval;
2450 | var hasTimeRemaining = true;
2451 |
2452 | try {
2453 | var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
2454 |
2455 | if (!hasMoreWork) {
2456 | isMessageLoopRunning = false;
2457 | scheduledHostCallback = null;
2458 | } else {
2459 | // If there's more work, schedule the next message event at the end
2460 | // of the preceding one.
2461 | port.postMessage(null);
2462 | }
2463 | } catch (error) {
2464 | // If a scheduler task throws, exit the current browser task so the
2465 | // error can be observed.
2466 | port.postMessage(null);
2467 | throw error;
2468 | }
2469 | } else {
2470 | isMessageLoopRunning = false;
2471 | } // Yielding to the browser will give it a chance to paint, so we can
2472 | };
2473 |
2474 | var channel = new MessageChannel();
2475 | var port = channel.port2;
2476 | channel.port1.onmessage = performWorkUntilDeadline;
2477 |
2478 | requestHostCallback = function (callback) {
2479 | scheduledHostCallback = callback;
2480 |
2481 | if (!isMessageLoopRunning) {
2482 | isMessageLoopRunning = true;
2483 | port.postMessage(null);
2484 | }
2485 | };
2486 |
2487 | requestHostTimeout = function (callback, ms) {
2488 | taskTimeoutID = _setTimeout(function () {
2489 | callback(getCurrentTime());
2490 | }, ms);
2491 | };
2492 |
2493 | cancelHostTimeout = function () {
2494 | _clearTimeout(taskTimeoutID);
2495 |
2496 | taskTimeoutID = -1;
2497 | };
2498 | }
2499 |
2500 | function push(heap, node) {
2501 | var index = heap.length;
2502 | heap.push(node);
2503 | siftUp(heap, node, index);
2504 | }
2505 | function peek(heap) {
2506 | var first = heap[0];
2507 | return first === undefined ? null : first;
2508 | }
2509 | function pop(heap) {
2510 | var first = heap[0];
2511 |
2512 | if (first !== undefined) {
2513 | var last = heap.pop();
2514 |
2515 | if (last !== first) {
2516 | heap[0] = last;
2517 | siftDown(heap, last, 0);
2518 | }
2519 |
2520 | return first;
2521 | } else {
2522 | return null;
2523 | }
2524 | }
2525 |
2526 | function siftUp(heap, node, i) {
2527 | var index = i;
2528 |
2529 | while (true) {
2530 | var parentIndex = index - 1 >>> 1;
2531 | var parent = heap[parentIndex];
2532 |
2533 | if (parent !== undefined && compare(parent, node) > 0) {
2534 | // The parent is larger. Swap positions.
2535 | heap[parentIndex] = node;
2536 | heap[index] = parent;
2537 | index = parentIndex;
2538 | } else {
2539 | // The parent is smaller. Exit.
2540 | return;
2541 | }
2542 | }
2543 | }
2544 |
2545 | function siftDown(heap, node, i) {
2546 | var index = i;
2547 | var length = heap.length;
2548 |
2549 | while (index < length) {
2550 | var leftIndex = (index + 1) * 2 - 1;
2551 | var left = heap[leftIndex];
2552 | var rightIndex = leftIndex + 1;
2553 | var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
2554 |
2555 | if (left !== undefined && compare(left, node) < 0) {
2556 | if (right !== undefined && compare(right, left) < 0) {
2557 | heap[index] = right;
2558 | heap[rightIndex] = node;
2559 | index = rightIndex;
2560 | } else {
2561 | heap[index] = left;
2562 | heap[leftIndex] = node;
2563 | index = leftIndex;
2564 | }
2565 | } else if (right !== undefined && compare(right, node) < 0) {
2566 | heap[index] = right;
2567 | heap[rightIndex] = node;
2568 | index = rightIndex;
2569 | } else {
2570 | // Neither child is smaller. Exit.
2571 | return;
2572 | }
2573 | }
2574 | }
2575 |
2576 | function compare(a, b) {
2577 | // Compare sort index first, then task id.
2578 | var diff = a.sortIndex - b.sortIndex;
2579 | return diff !== 0 ? diff : a.id - b.id;
2580 | }
2581 |
2582 | // TODO: Use symbols?
2583 | var NoPriority = 0;
2584 | var ImmediatePriority = 1;
2585 | var UserBlockingPriority = 2;
2586 | var NormalPriority = 3;
2587 | var LowPriority = 4;
2588 | var IdlePriority = 5;
2589 |
2590 | var runIdCounter = 0;
2591 | var mainThreadIdCounter = 0;
2592 | var profilingStateSize = 4;
2593 | var sharedProfilingBuffer = // $FlowFixMe Flow doesn't know about SharedArrayBuffer
2594 | typeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : // $FlowFixMe Flow doesn't know about ArrayBuffer
2595 | typeof ArrayBuffer === 'function' ? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : null // Don't crash the init path on IE9
2596 | ;
2597 | var profilingState = sharedProfilingBuffer !== null ? new Int32Array(sharedProfilingBuffer) : []; // We can't read this but it helps save bytes for null checks
2598 |
2599 | var PRIORITY = 0;
2600 | var CURRENT_TASK_ID = 1;
2601 | var CURRENT_RUN_ID = 2;
2602 | var QUEUE_SIZE = 3;
2603 |
2604 | {
2605 | profilingState[PRIORITY] = NoPriority; // This is maintained with a counter, because the size of the priority queue
2606 | // array might include canceled tasks.
2607 |
2608 | profilingState[QUEUE_SIZE] = 0;
2609 | profilingState[CURRENT_TASK_ID] = 0;
2610 | } // Bytes per element is 4
2611 |
2612 |
2613 | var INITIAL_EVENT_LOG_SIZE = 131072;
2614 | var MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes
2615 |
2616 | var eventLogSize = 0;
2617 | var eventLogBuffer = null;
2618 | var eventLog = null;
2619 | var eventLogIndex = 0;
2620 | var TaskStartEvent = 1;
2621 | var TaskCompleteEvent = 2;
2622 | var TaskErrorEvent = 3;
2623 | var TaskCancelEvent = 4;
2624 | var TaskRunEvent = 5;
2625 | var TaskYieldEvent = 6;
2626 | var SchedulerSuspendEvent = 7;
2627 | var SchedulerResumeEvent = 8;
2628 |
2629 | function logEvent(entries) {
2630 | if (eventLog !== null) {
2631 | var offset = eventLogIndex;
2632 | eventLogIndex += entries.length;
2633 |
2634 | if (eventLogIndex + 1 > eventLogSize) {
2635 | eventLogSize *= 2;
2636 |
2637 | if (eventLogSize > MAX_EVENT_LOG_SIZE) {
2638 | // Using console['error'] to evade Babel and ESLint
2639 | console['error']("Scheduler Profiling: Event log exceeded maximum size. Don't " + 'forget to call `stopLoggingProfilingEvents()`.');
2640 | stopLoggingProfilingEvents();
2641 | return;
2642 | }
2643 |
2644 | var newEventLog = new Int32Array(eventLogSize * 4);
2645 | newEventLog.set(eventLog);
2646 | eventLogBuffer = newEventLog.buffer;
2647 | eventLog = newEventLog;
2648 | }
2649 |
2650 | eventLog.set(entries, offset);
2651 | }
2652 | }
2653 |
2654 | function startLoggingProfilingEvents() {
2655 | eventLogSize = INITIAL_EVENT_LOG_SIZE;
2656 | eventLogBuffer = new ArrayBuffer(eventLogSize * 4);
2657 | eventLog = new Int32Array(eventLogBuffer);
2658 | eventLogIndex = 0;
2659 | }
2660 | function stopLoggingProfilingEvents() {
2661 | var buffer = eventLogBuffer;
2662 | eventLogSize = 0;
2663 | eventLogBuffer = null;
2664 | eventLog = null;
2665 | eventLogIndex = 0;
2666 | return buffer;
2667 | }
2668 | function markTaskStart(task, ms) {
2669 | {
2670 | profilingState[QUEUE_SIZE]++;
2671 |
2672 | if (eventLog !== null) {
2673 | // performance.now returns a float, representing milliseconds. When the
2674 | // event is logged, it's coerced to an int. Convert to microseconds to
2675 | // maintain extra degrees of precision.
2676 | logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);
2677 | }
2678 | }
2679 | }
2680 | function markTaskCompleted(task, ms) {
2681 | {
2682 | profilingState[PRIORITY] = NoPriority;
2683 | profilingState[CURRENT_TASK_ID] = 0;
2684 | profilingState[QUEUE_SIZE]--;
2685 |
2686 | if (eventLog !== null) {
2687 | logEvent([TaskCompleteEvent, ms * 1000, task.id]);
2688 | }
2689 | }
2690 | }
2691 | function markTaskCanceled(task, ms) {
2692 | {
2693 | profilingState[QUEUE_SIZE]--;
2694 |
2695 | if (eventLog !== null) {
2696 | logEvent([TaskCancelEvent, ms * 1000, task.id]);
2697 | }
2698 | }
2699 | }
2700 | function markTaskErrored(task, ms) {
2701 | {
2702 | profilingState[PRIORITY] = NoPriority;
2703 | profilingState[CURRENT_TASK_ID] = 0;
2704 | profilingState[QUEUE_SIZE]--;
2705 |
2706 | if (eventLog !== null) {
2707 | logEvent([TaskErrorEvent, ms * 1000, task.id]);
2708 | }
2709 | }
2710 | }
2711 | function markTaskRun(task, ms) {
2712 | {
2713 | runIdCounter++;
2714 | profilingState[PRIORITY] = task.priorityLevel;
2715 | profilingState[CURRENT_TASK_ID] = task.id;
2716 | profilingState[CURRENT_RUN_ID] = runIdCounter;
2717 |
2718 | if (eventLog !== null) {
2719 | logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);
2720 | }
2721 | }
2722 | }
2723 | function markTaskYield(task, ms) {
2724 | {
2725 | profilingState[PRIORITY] = NoPriority;
2726 | profilingState[CURRENT_TASK_ID] = 0;
2727 | profilingState[CURRENT_RUN_ID] = 0;
2728 |
2729 | if (eventLog !== null) {
2730 | logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);
2731 | }
2732 | }
2733 | }
2734 | function markSchedulerSuspended(ms) {
2735 | {
2736 | mainThreadIdCounter++;
2737 |
2738 | if (eventLog !== null) {
2739 | logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);
2740 | }
2741 | }
2742 | }
2743 | function markSchedulerUnsuspended(ms) {
2744 | {
2745 | if (eventLog !== null) {
2746 | logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);
2747 | }
2748 | }
2749 | }
2750 |
2751 | /* eslint-disable no-var */
2752 | // Math.pow(2, 30) - 1
2753 | // 0b111111111111111111111111111111
2754 |
2755 | var maxSigned31BitInt = 1073741823; // Times out immediately
2756 |
2757 | var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
2758 |
2759 | var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
2760 | var NORMAL_PRIORITY_TIMEOUT = 5000;
2761 | var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
2762 |
2763 | var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
2764 |
2765 | var taskQueue = [];
2766 | var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
2767 |
2768 | var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
2769 | var currentTask = null;
2770 | var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.
2771 |
2772 | var isPerformingWork = false;
2773 | var isHostCallbackScheduled = false;
2774 | var isHostTimeoutScheduled = false;
2775 |
2776 | function advanceTimers(currentTime) {
2777 | // Check for tasks that are no longer delayed and add them to the queue.
2778 | var timer = peek(timerQueue);
2779 |
2780 | while (timer !== null) {
2781 | if (timer.callback === null) {
2782 | // Timer was cancelled.
2783 | pop(timerQueue);
2784 | } else if (timer.startTime <= currentTime) {
2785 | // Timer fired. Transfer to the task queue.
2786 | pop(timerQueue);
2787 | timer.sortIndex = timer.expirationTime;
2788 | push(taskQueue, timer);
2789 |
2790 | {
2791 | markTaskStart(timer, currentTime);
2792 | timer.isQueued = true;
2793 | }
2794 | } else {
2795 | // Remaining timers are pending.
2796 | return;
2797 | }
2798 |
2799 | timer = peek(timerQueue);
2800 | }
2801 | }
2802 |
2803 | function handleTimeout(currentTime) {
2804 | isHostTimeoutScheduled = false;
2805 | advanceTimers(currentTime);
2806 |
2807 | if (!isHostCallbackScheduled) {
2808 | if (peek(taskQueue) !== null) {
2809 | isHostCallbackScheduled = true;
2810 | requestHostCallback(flushWork);
2811 | } else {
2812 | var firstTimer = peek(timerQueue);
2813 |
2814 | if (firstTimer !== null) {
2815 | requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
2816 | }
2817 | }
2818 | }
2819 | }
2820 |
2821 | function flushWork(hasTimeRemaining, initialTime) {
2822 | {
2823 | markSchedulerUnsuspended(initialTime);
2824 | } // We'll need a host callback the next time work is scheduled.
2825 |
2826 |
2827 | isHostCallbackScheduled = false;
2828 |
2829 | if (isHostTimeoutScheduled) {
2830 | // We scheduled a timeout but it's no longer needed. Cancel it.
2831 | isHostTimeoutScheduled = false;
2832 | cancelHostTimeout();
2833 | }
2834 |
2835 | isPerformingWork = true;
2836 | var previousPriorityLevel = currentPriorityLevel;
2837 |
2838 | try {
2839 | if (enableProfiling) {
2840 | try {
2841 | return workLoop(hasTimeRemaining, initialTime);
2842 | } catch (error) {
2843 | if (currentTask !== null) {
2844 | var currentTime = getCurrentTime();
2845 | markTaskErrored(currentTask, currentTime);
2846 | currentTask.isQueued = false;
2847 | }
2848 |
2849 | throw error;
2850 | }
2851 | } else {
2852 | // No catch in prod code path.
2853 | return workLoop(hasTimeRemaining, initialTime);
2854 | }
2855 | } finally {
2856 | currentTask = null;
2857 | currentPriorityLevel = previousPriorityLevel;
2858 | isPerformingWork = false;
2859 |
2860 | {
2861 | var _currentTime = getCurrentTime();
2862 |
2863 | markSchedulerSuspended(_currentTime);
2864 | }
2865 | }
2866 | }
2867 |
2868 | function workLoop(hasTimeRemaining, initialTime) {
2869 | var currentTime = initialTime;
2870 | advanceTimers(currentTime);
2871 | currentTask = peek(taskQueue);
2872 |
2873 | while (currentTask !== null && !(enableSchedulerDebugging )) {
2874 | if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
2875 | // This currentTask hasn't expired, and we've reached the deadline.
2876 | break;
2877 | }
2878 |
2879 | var callback = currentTask.callback;
2880 |
2881 | if (typeof callback === 'function') {
2882 | currentTask.callback = null;
2883 | currentPriorityLevel = currentTask.priorityLevel;
2884 | var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
2885 | markTaskRun(currentTask, currentTime);
2886 | var continuationCallback = callback(didUserCallbackTimeout);
2887 | currentTime = getCurrentTime();
2888 |
2889 | if (typeof continuationCallback === 'function') {
2890 | currentTask.callback = continuationCallback;
2891 | markTaskYield(currentTask, currentTime);
2892 | } else {
2893 | {
2894 | markTaskCompleted(currentTask, currentTime);
2895 | currentTask.isQueued = false;
2896 | }
2897 |
2898 | if (currentTask === peek(taskQueue)) {
2899 | pop(taskQueue);
2900 | }
2901 | }
2902 |
2903 | advanceTimers(currentTime);
2904 | } else {
2905 | pop(taskQueue);
2906 | }
2907 |
2908 | currentTask = peek(taskQueue);
2909 | } // Return whether there's additional work
2910 |
2911 |
2912 | if (currentTask !== null) {
2913 | return true;
2914 | } else {
2915 | var firstTimer = peek(timerQueue);
2916 |
2917 | if (firstTimer !== null) {
2918 | requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
2919 | }
2920 |
2921 | return false;
2922 | }
2923 | }
2924 |
2925 | function unstable_runWithPriority(priorityLevel, eventHandler) {
2926 | switch (priorityLevel) {
2927 | case ImmediatePriority:
2928 | case UserBlockingPriority:
2929 | case NormalPriority:
2930 | case LowPriority:
2931 | case IdlePriority:
2932 | break;
2933 |
2934 | default:
2935 | priorityLevel = NormalPriority;
2936 | }
2937 |
2938 | var previousPriorityLevel = currentPriorityLevel;
2939 | currentPriorityLevel = priorityLevel;
2940 |
2941 | try {
2942 | return eventHandler();
2943 | } finally {
2944 | currentPriorityLevel = previousPriorityLevel;
2945 | }
2946 | }
2947 |
2948 | function unstable_next(eventHandler) {
2949 | var priorityLevel;
2950 |
2951 | switch (currentPriorityLevel) {
2952 | case ImmediatePriority:
2953 | case UserBlockingPriority:
2954 | case NormalPriority:
2955 | // Shift down to normal priority
2956 | priorityLevel = NormalPriority;
2957 | break;
2958 |
2959 | default:
2960 | // Anything lower than normal priority should remain at the current level.
2961 | priorityLevel = currentPriorityLevel;
2962 | break;
2963 | }
2964 |
2965 | var previousPriorityLevel = currentPriorityLevel;
2966 | currentPriorityLevel = priorityLevel;
2967 |
2968 | try {
2969 | return eventHandler();
2970 | } finally {
2971 | currentPriorityLevel = previousPriorityLevel;
2972 | }
2973 | }
2974 |
2975 | function unstable_wrapCallback(callback) {
2976 | var parentPriorityLevel = currentPriorityLevel;
2977 | return function () {
2978 | // This is a fork of runWithPriority, inlined for performance.
2979 | var previousPriorityLevel = currentPriorityLevel;
2980 | currentPriorityLevel = parentPriorityLevel;
2981 |
2982 | try {
2983 | return callback.apply(this, arguments);
2984 | } finally {
2985 | currentPriorityLevel = previousPriorityLevel;
2986 | }
2987 | };
2988 | }
2989 |
2990 | function unstable_scheduleCallback(priorityLevel, callback, options) {
2991 | var currentTime = getCurrentTime();
2992 | var startTime;
2993 |
2994 | if (typeof options === 'object' && options !== null) {
2995 | var delay = options.delay;
2996 |
2997 | if (typeof delay === 'number' && delay > 0) {
2998 | startTime = currentTime + delay;
2999 | } else {
3000 | startTime = currentTime;
3001 | }
3002 | } else {
3003 | startTime = currentTime;
3004 | }
3005 |
3006 | var timeout;
3007 |
3008 | switch (priorityLevel) {
3009 | case ImmediatePriority:
3010 | timeout = IMMEDIATE_PRIORITY_TIMEOUT;
3011 | break;
3012 |
3013 | case UserBlockingPriority:
3014 | timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
3015 | break;
3016 |
3017 | case IdlePriority:
3018 | timeout = IDLE_PRIORITY_TIMEOUT;
3019 | break;
3020 |
3021 | case LowPriority:
3022 | timeout = LOW_PRIORITY_TIMEOUT;
3023 | break;
3024 |
3025 | case NormalPriority:
3026 | default:
3027 | timeout = NORMAL_PRIORITY_TIMEOUT;
3028 | break;
3029 | }
3030 |
3031 | var expirationTime = startTime + timeout;
3032 | var newTask = {
3033 | id: taskIdCounter++,
3034 | callback: callback,
3035 | priorityLevel: priorityLevel,
3036 | startTime: startTime,
3037 | expirationTime: expirationTime,
3038 | sortIndex: -1
3039 | };
3040 |
3041 | {
3042 | newTask.isQueued = false;
3043 | }
3044 |
3045 | if (startTime > currentTime) {
3046 | // This is a delayed task.
3047 | newTask.sortIndex = startTime;
3048 | push(timerQueue, newTask);
3049 |
3050 | if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
3051 | // All tasks are delayed, and this is the task with the earliest delay.
3052 | if (isHostTimeoutScheduled) {
3053 | // Cancel an existing timeout.
3054 | cancelHostTimeout();
3055 | } else {
3056 | isHostTimeoutScheduled = true;
3057 | } // Schedule a timeout.
3058 |
3059 |
3060 | requestHostTimeout(handleTimeout, startTime - currentTime);
3061 | }
3062 | } else {
3063 | newTask.sortIndex = expirationTime;
3064 | push(taskQueue, newTask);
3065 |
3066 | {
3067 | markTaskStart(newTask, currentTime);
3068 | newTask.isQueued = true;
3069 | } // Schedule a host callback, if needed. If we're already performing work,
3070 | // wait until the next time we yield.
3071 |
3072 |
3073 | if (!isHostCallbackScheduled && !isPerformingWork) {
3074 | isHostCallbackScheduled = true;
3075 | requestHostCallback(flushWork);
3076 | }
3077 | }
3078 |
3079 | return newTask;
3080 | }
3081 |
3082 | function unstable_pauseExecution() {
3083 | }
3084 |
3085 | function unstable_continueExecution() {
3086 |
3087 | if (!isHostCallbackScheduled && !isPerformingWork) {
3088 | isHostCallbackScheduled = true;
3089 | requestHostCallback(flushWork);
3090 | }
3091 | }
3092 |
3093 | function unstable_getFirstCallbackNode() {
3094 | return peek(taskQueue);
3095 | }
3096 |
3097 | function unstable_cancelCallback(task) {
3098 | {
3099 | if (task.isQueued) {
3100 | var currentTime = getCurrentTime();
3101 | markTaskCanceled(task, currentTime);
3102 | task.isQueued = false;
3103 | }
3104 | } // Null out the callback to indicate the task has been canceled. (Can't
3105 | // remove from the queue because you can't remove arbitrary nodes from an
3106 | // array based heap, only the first one.)
3107 |
3108 |
3109 | task.callback = null;
3110 | }
3111 |
3112 | function unstable_getCurrentPriorityLevel() {
3113 | return currentPriorityLevel;
3114 | }
3115 |
3116 | var unstable_requestPaint = requestPaint;
3117 | var unstable_Profiling = {
3118 | startLoggingProfilingEvents: startLoggingProfilingEvents,
3119 | stopLoggingProfilingEvents: stopLoggingProfilingEvents,
3120 | sharedProfilingBuffer: sharedProfilingBuffer
3121 | } ;
3122 |
3123 |
3124 |
3125 | var Scheduler = /*#__PURE__*/Object.freeze({
3126 | __proto__: null,
3127 | unstable_ImmediatePriority: ImmediatePriority,
3128 | unstable_UserBlockingPriority: UserBlockingPriority,
3129 | unstable_NormalPriority: NormalPriority,
3130 | unstable_IdlePriority: IdlePriority,
3131 | unstable_LowPriority: LowPriority,
3132 | unstable_runWithPriority: unstable_runWithPriority,
3133 | unstable_next: unstable_next,
3134 | unstable_scheduleCallback: unstable_scheduleCallback,
3135 | unstable_cancelCallback: unstable_cancelCallback,
3136 | unstable_wrapCallback: unstable_wrapCallback,
3137 | unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
3138 | get unstable_shouldYield () { return shouldYieldToHost; },
3139 | unstable_requestPaint: unstable_requestPaint,
3140 | unstable_continueExecution: unstable_continueExecution,
3141 | unstable_pauseExecution: unstable_pauseExecution,
3142 | unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
3143 | get unstable_now () { return getCurrentTime; },
3144 | get unstable_forceFrameRate () { return forceFrameRate; },
3145 | unstable_Profiling: unstable_Profiling
3146 | });
3147 |
3148 | var DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs.
3149 |
3150 | var interactionIDCounter = 0;
3151 | var threadIDCounter = 0; // Set of currently traced interactions.
3152 | // Interactions "stack"–
3153 | // Meaning that newly traced interactions are appended to the previously active set.
3154 | // When an interaction goes out of scope, the previous set (if any) is restored.
3155 |
3156 | var interactionsRef = null; // Listener(s) to notify when interactions begin and end.
3157 |
3158 | var subscriberRef = null;
3159 |
3160 | {
3161 | interactionsRef = {
3162 | current: new Set()
3163 | };
3164 | subscriberRef = {
3165 | current: null
3166 | };
3167 | }
3168 | function unstable_clear(callback) {
3169 |
3170 | var prevInteractions = interactionsRef.current;
3171 | interactionsRef.current = new Set();
3172 |
3173 | try {
3174 | return callback();
3175 | } finally {
3176 | interactionsRef.current = prevInteractions;
3177 | }
3178 | }
3179 | function unstable_getCurrent() {
3180 | {
3181 | return interactionsRef.current;
3182 | }
3183 | }
3184 | function unstable_getThreadID() {
3185 | return ++threadIDCounter;
3186 | }
3187 | function unstable_trace(name, timestamp, callback) {
3188 | var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID;
3189 |
3190 | var interaction = {
3191 | __count: 1,
3192 | id: interactionIDCounter++,
3193 | name: name,
3194 | timestamp: timestamp
3195 | };
3196 | var prevInteractions = interactionsRef.current; // Traced interactions should stack/accumulate.
3197 | // To do that, clone the current interactions.
3198 | // The previous set will be restored upon completion.
3199 |
3200 | var interactions = new Set(prevInteractions);
3201 | interactions.add(interaction);
3202 | interactionsRef.current = interactions;
3203 | var subscriber = subscriberRef.current;
3204 | var returnValue;
3205 |
3206 | try {
3207 | if (subscriber !== null) {
3208 | subscriber.onInteractionTraced(interaction);
3209 | }
3210 | } finally {
3211 | try {
3212 | if (subscriber !== null) {
3213 | subscriber.onWorkStarted(interactions, threadID);
3214 | }
3215 | } finally {
3216 | try {
3217 | returnValue = callback();
3218 | } finally {
3219 | interactionsRef.current = prevInteractions;
3220 |
3221 | try {
3222 | if (subscriber !== null) {
3223 | subscriber.onWorkStopped(interactions, threadID);
3224 | }
3225 | } finally {
3226 | interaction.__count--; // If no async work was scheduled for this interaction,
3227 | // Notify subscribers that it's completed.
3228 |
3229 | if (subscriber !== null && interaction.__count === 0) {
3230 | subscriber.onInteractionScheduledWorkCompleted(interaction);
3231 | }
3232 | }
3233 | }
3234 | }
3235 | }
3236 |
3237 | return returnValue;
3238 | }
3239 | function unstable_wrap(callback) {
3240 | var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID;
3241 |
3242 | var wrappedInteractions = interactionsRef.current;
3243 | var subscriber = subscriberRef.current;
3244 |
3245 | if (subscriber !== null) {
3246 | subscriber.onWorkScheduled(wrappedInteractions, threadID);
3247 | } // Update the pending async work count for the current interactions.
3248 | // Update after calling subscribers in case of error.
3249 |
3250 |
3251 | wrappedInteractions.forEach(function (interaction) {
3252 | interaction.__count++;
3253 | });
3254 | var hasRun = false;
3255 |
3256 | function wrapped() {
3257 | var prevInteractions = interactionsRef.current;
3258 | interactionsRef.current = wrappedInteractions;
3259 | subscriber = subscriberRef.current;
3260 |
3261 | try {
3262 | var returnValue;
3263 |
3264 | try {
3265 | if (subscriber !== null) {
3266 | subscriber.onWorkStarted(wrappedInteractions, threadID);
3267 | }
3268 | } finally {
3269 | try {
3270 | returnValue = callback.apply(undefined, arguments);
3271 | } finally {
3272 | interactionsRef.current = prevInteractions;
3273 |
3274 | if (subscriber !== null) {
3275 | subscriber.onWorkStopped(wrappedInteractions, threadID);
3276 | }
3277 | }
3278 | }
3279 |
3280 | return returnValue;
3281 | } finally {
3282 | if (!hasRun) {
3283 | // We only expect a wrapped function to be executed once,
3284 | // But in the event that it's executed more than once–
3285 | // Only decrement the outstanding interaction counts once.
3286 | hasRun = true; // Update pending async counts for all wrapped interactions.
3287 | // If this was the last scheduled async work for any of them,
3288 | // Mark them as completed.
3289 |
3290 | wrappedInteractions.forEach(function (interaction) {
3291 | interaction.__count--;
3292 |
3293 | if (subscriber !== null && interaction.__count === 0) {
3294 | subscriber.onInteractionScheduledWorkCompleted(interaction);
3295 | }
3296 | });
3297 | }
3298 | }
3299 | }
3300 |
3301 | wrapped.cancel = function cancel() {
3302 | subscriber = subscriberRef.current;
3303 |
3304 | try {
3305 | if (subscriber !== null) {
3306 | subscriber.onWorkCanceled(wrappedInteractions, threadID);
3307 | }
3308 | } finally {
3309 | // Update pending async counts for all wrapped interactions.
3310 | // If this was the last scheduled async work for any of them,
3311 | // Mark them as completed.
3312 | wrappedInteractions.forEach(function (interaction) {
3313 | interaction.__count--;
3314 |
3315 | if (subscriber && interaction.__count === 0) {
3316 | subscriber.onInteractionScheduledWorkCompleted(interaction);
3317 | }
3318 | });
3319 | }
3320 | };
3321 |
3322 | return wrapped;
3323 | }
3324 |
3325 | var subscribers = null;
3326 |
3327 | {
3328 | subscribers = new Set();
3329 | }
3330 |
3331 | function unstable_subscribe(subscriber) {
3332 | {
3333 | subscribers.add(subscriber);
3334 |
3335 | if (subscribers.size === 1) {
3336 | subscriberRef.current = {
3337 | onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted,
3338 | onInteractionTraced: onInteractionTraced,
3339 | onWorkCanceled: onWorkCanceled,
3340 | onWorkScheduled: onWorkScheduled,
3341 | onWorkStarted: onWorkStarted,
3342 | onWorkStopped: onWorkStopped
3343 | };
3344 | }
3345 | }
3346 | }
3347 | function unstable_unsubscribe(subscriber) {
3348 | {
3349 | subscribers.delete(subscriber);
3350 |
3351 | if (subscribers.size === 0) {
3352 | subscriberRef.current = null;
3353 | }
3354 | }
3355 | }
3356 |
3357 | function onInteractionTraced(interaction) {
3358 | var didCatchError = false;
3359 | var caughtError = null;
3360 | subscribers.forEach(function (subscriber) {
3361 | try {
3362 | subscriber.onInteractionTraced(interaction);
3363 | } catch (error) {
3364 | if (!didCatchError) {
3365 | didCatchError = true;
3366 | caughtError = error;
3367 | }
3368 | }
3369 | });
3370 |
3371 | if (didCatchError) {
3372 | throw caughtError;
3373 | }
3374 | }
3375 |
3376 | function onInteractionScheduledWorkCompleted(interaction) {
3377 | var didCatchError = false;
3378 | var caughtError = null;
3379 | subscribers.forEach(function (subscriber) {
3380 | try {
3381 | subscriber.onInteractionScheduledWorkCompleted(interaction);
3382 | } catch (error) {
3383 | if (!didCatchError) {
3384 | didCatchError = true;
3385 | caughtError = error;
3386 | }
3387 | }
3388 | });
3389 |
3390 | if (didCatchError) {
3391 | throw caughtError;
3392 | }
3393 | }
3394 |
3395 | function onWorkScheduled(interactions, threadID) {
3396 | var didCatchError = false;
3397 | var caughtError = null;
3398 | subscribers.forEach(function (subscriber) {
3399 | try {
3400 | subscriber.onWorkScheduled(interactions, threadID);
3401 | } catch (error) {
3402 | if (!didCatchError) {
3403 | didCatchError = true;
3404 | caughtError = error;
3405 | }
3406 | }
3407 | });
3408 |
3409 | if (didCatchError) {
3410 | throw caughtError;
3411 | }
3412 | }
3413 |
3414 | function onWorkStarted(interactions, threadID) {
3415 | var didCatchError = false;
3416 | var caughtError = null;
3417 | subscribers.forEach(function (subscriber) {
3418 | try {
3419 | subscriber.onWorkStarted(interactions, threadID);
3420 | } catch (error) {
3421 | if (!didCatchError) {
3422 | didCatchError = true;
3423 | caughtError = error;
3424 | }
3425 | }
3426 | });
3427 |
3428 | if (didCatchError) {
3429 | throw caughtError;
3430 | }
3431 | }
3432 |
3433 | function onWorkStopped(interactions, threadID) {
3434 | var didCatchError = false;
3435 | var caughtError = null;
3436 | subscribers.forEach(function (subscriber) {
3437 | try {
3438 | subscriber.onWorkStopped(interactions, threadID);
3439 | } catch (error) {
3440 | if (!didCatchError) {
3441 | didCatchError = true;
3442 | caughtError = error;
3443 | }
3444 | }
3445 | });
3446 |
3447 | if (didCatchError) {
3448 | throw caughtError;
3449 | }
3450 | }
3451 |
3452 | function onWorkCanceled(interactions, threadID) {
3453 | var didCatchError = false;
3454 | var caughtError = null;
3455 | subscribers.forEach(function (subscriber) {
3456 | try {
3457 | subscriber.onWorkCanceled(interactions, threadID);
3458 | } catch (error) {
3459 | if (!didCatchError) {
3460 | didCatchError = true;
3461 | caughtError = error;
3462 | }
3463 | }
3464 | });
3465 |
3466 | if (didCatchError) {
3467 | throw caughtError;
3468 | }
3469 | }
3470 |
3471 |
3472 |
3473 | var SchedulerTracing = /*#__PURE__*/Object.freeze({
3474 | __proto__: null,
3475 | get __interactionsRef () { return interactionsRef; },
3476 | get __subscriberRef () { return subscriberRef; },
3477 | unstable_clear: unstable_clear,
3478 | unstable_getCurrent: unstable_getCurrent,
3479 | unstable_getThreadID: unstable_getThreadID,
3480 | unstable_trace: unstable_trace,
3481 | unstable_wrap: unstable_wrap,
3482 | unstable_subscribe: unstable_subscribe,
3483 | unstable_unsubscribe: unstable_unsubscribe
3484 | });
3485 |
3486 | var ReactSharedInternals$1 = {
3487 | ReactCurrentDispatcher: ReactCurrentDispatcher,
3488 | ReactCurrentOwner: ReactCurrentOwner,
3489 | IsSomeRendererActing: IsSomeRendererActing,
3490 | ReactCurrentBatchConfig: ReactCurrentBatchConfig,
3491 | // Used by renderers to avoid bundling object-assign twice in UMD bundles:
3492 | assign: assign,
3493 | // Re-export the schedule API(s) for UMD bundles.
3494 | // This avoids introducing a dependency on a new UMD global in a minor update,
3495 | // Since that would be a breaking change (e.g. for all existing CodeSandboxes).
3496 | // This re-export is only required for UMD bundles;
3497 | // CJS bundles use the shared NPM package.
3498 | Scheduler: Scheduler,
3499 | SchedulerTracing: SchedulerTracing
3500 | };
3501 |
3502 | {
3503 | ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
3504 | }
3505 |
3506 | {
3507 |
3508 | try {
3509 | var frozenObject = Object.freeze({});
3510 | /* eslint-disable no-new */
3511 |
3512 | new Map([[frozenObject, null]]);
3513 | new Set([frozenObject]);
3514 | /* eslint-enable no-new */
3515 | } catch (e) {
3516 | }
3517 | }
3518 |
3519 | var createElement$1 = createElementWithValidation ;
3520 | var cloneElement$1 = cloneElementWithValidation ;
3521 | var createFactory = createFactoryWithValidation ;
3522 | var Children = {
3523 | map: mapChildren,
3524 | forEach: forEachChildren,
3525 | count: countChildren,
3526 | toArray: toArray,
3527 | only: onlyChild
3528 | };
3529 |
3530 | exports.Children = Children;
3531 | exports.Component = Component;
3532 | exports.PureComponent = PureComponent;
3533 | exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
3534 | exports.cloneElement = cloneElement$1;
3535 | exports.createContext = createContext;
3536 | exports.createElement = createElement$1;
3537 | exports.createFactory = createFactory;
3538 | exports.createRef = createRef;
3539 | exports.forwardRef = forwardRef;
3540 | exports.isValidElement = isValidElement;
3541 | exports.lazy = lazy;
3542 | exports.memo = memo;
3543 | exports.useCallback = useCallback;
3544 | exports.useContext = useContext;
3545 | exports.useDebugValue = useDebugValue;
3546 | exports.useEffect = useEffect;
3547 | exports.useImperativeHandle = useImperativeHandle;
3548 | exports.useLayoutEffect = useLayoutEffect;
3549 | exports.useMemo = useMemo;
3550 | exports.useReducer = useReducer;
3551 | exports.useRef = useRef;
3552 | exports.useState = useState;
3553 | exports.version = ReactVersion;
3554 |
3555 | })));
3556 |
--------------------------------------------------------------------------------
/examples/bad_button/js_package/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | dist/
3 |
--------------------------------------------------------------------------------
/examples/bad_button/js_package/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "bad_button_lib",
3 | "amdName": "BadButtonLib",
4 | "source": "src/index.tsx",
5 | "main": "dist/bad_button_lib.js",
6 | "module": "dist/bad_button_lib.module.js",
7 | "unpkg": "dist/bad_button_lib.umd.js",
8 | "version": "1.0.0",
9 | "description": "",
10 | "scripts": {
11 | "build": "microbundle --jsx React.createElement --globals react=React",
12 | "dev": "microbundle watch --jsx React.createElement --globals react=React",
13 | "test": "echo \"Error: no test specified\" && exit 1"
14 | },
15 | "keywords": [],
16 | "author": "",
17 | "license": "ISC",
18 | "peerDependencies": {
19 | "react": "^17.0.1",
20 | "react-dom": "^17.0.1"
21 | },
22 | "devDependencies": {
23 | "@types/react": "^16.9.56",
24 | "react": "^17.0.1",
25 | "react-dom": "^17.0.1",
26 | "microbundle": "^0.12.4",
27 | "typescript": "^4.0.5"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/examples/bad_button/js_package/src/index.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | interface BadButtonProps {
4 | color?: string,
5 | text: string,
6 | foo: any,
7 | }
8 |
9 | const BadButton = (props: BadButtonProps): JSX.Element => {
10 | return (
11 | window.alert("Click!")}
14 | >
15 | {props.text}
16 |
17 | );
18 |
19 | };
20 |
21 | export { BadButton };
22 |
--------------------------------------------------------------------------------
/examples/material_ui/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "material_ui",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "@babel/runtime": {
8 | "version": "7.12.5",
9 | "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.12.5.tgz",
10 | "integrity": "sha512-plcc+hbExy3McchJCEQG3knOsuh3HH+Prx1P6cLIkET/0dLuQDEnrT+s27Axgc9bqfsmNUNHfscgMUdBpC9xfg==",
11 | "requires": {
12 | "regenerator-runtime": "^0.13.4"
13 | }
14 | },
15 | "@emotion/hash": {
16 | "version": "0.8.0",
17 | "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",
18 | "integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow=="
19 | },
20 | "@material-ui/core": {
21 | "version": "4.11.0",
22 | "resolved": "https://registry.npmjs.org/@material-ui/core/-/core-4.11.0.tgz",
23 | "integrity": "sha512-bYo9uIub8wGhZySHqLQ833zi4ZML+XCBE1XwJ8EuUVSpTWWG57Pm+YugQToJNFsEyiKFhPh8DPD0bgupz8n01g==",
24 | "requires": {
25 | "@babel/runtime": "^7.4.4",
26 | "@material-ui/styles": "^4.10.0",
27 | "@material-ui/system": "^4.9.14",
28 | "@material-ui/types": "^5.1.0",
29 | "@material-ui/utils": "^4.10.2",
30 | "@types/react-transition-group": "^4.2.0",
31 | "clsx": "^1.0.4",
32 | "hoist-non-react-statics": "^3.3.2",
33 | "popper.js": "1.16.1-lts",
34 | "prop-types": "^15.7.2",
35 | "react-is": "^16.8.0",
36 | "react-transition-group": "^4.4.0"
37 | }
38 | },
39 | "@material-ui/styles": {
40 | "version": "4.10.0",
41 | "resolved": "https://registry.npmjs.org/@material-ui/styles/-/styles-4.10.0.tgz",
42 | "integrity": "sha512-XPwiVTpd3rlnbfrgtEJ1eJJdFCXZkHxy8TrdieaTvwxNYj42VnnCyFzxYeNW9Lhj4V1oD8YtQ6S5Gie7bZDf7Q==",
43 | "requires": {
44 | "@babel/runtime": "^7.4.4",
45 | "@emotion/hash": "^0.8.0",
46 | "@material-ui/types": "^5.1.0",
47 | "@material-ui/utils": "^4.9.6",
48 | "clsx": "^1.0.4",
49 | "csstype": "^2.5.2",
50 | "hoist-non-react-statics": "^3.3.2",
51 | "jss": "^10.0.3",
52 | "jss-plugin-camel-case": "^10.0.3",
53 | "jss-plugin-default-unit": "^10.0.3",
54 | "jss-plugin-global": "^10.0.3",
55 | "jss-plugin-nested": "^10.0.3",
56 | "jss-plugin-props-sort": "^10.0.3",
57 | "jss-plugin-rule-value-function": "^10.0.3",
58 | "jss-plugin-vendor-prefixer": "^10.0.3",
59 | "prop-types": "^15.7.2"
60 | }
61 | },
62 | "@material-ui/system": {
63 | "version": "4.9.14",
64 | "resolved": "https://registry.npmjs.org/@material-ui/system/-/system-4.9.14.tgz",
65 | "integrity": "sha512-oQbaqfSnNlEkXEziDcJDDIy8pbvwUmZXWNqlmIwDqr/ZdCK8FuV3f4nxikUh7hvClKV2gnQ9djh5CZFTHkZj3w==",
66 | "requires": {
67 | "@babel/runtime": "^7.4.4",
68 | "@material-ui/utils": "^4.9.6",
69 | "csstype": "^2.5.2",
70 | "prop-types": "^15.7.2"
71 | }
72 | },
73 | "@material-ui/types": {
74 | "version": "5.1.0",
75 | "resolved": "https://registry.npmjs.org/@material-ui/types/-/types-5.1.0.tgz",
76 | "integrity": "sha512-7cqRjrY50b8QzRSYyhSpx4WRw2YuO0KKIGQEVk5J8uoz2BanawykgZGoWEqKm7pVIbzFDN0SpPcVV4IhOFkl8A=="
77 | },
78 | "@material-ui/utils": {
79 | "version": "4.10.2",
80 | "resolved": "https://registry.npmjs.org/@material-ui/utils/-/utils-4.10.2.tgz",
81 | "integrity": "sha512-eg29v74P7W5r6a4tWWDAAfZldXIzfyO1am2fIsC39hdUUHm/33k6pGOKPbgDjg/U/4ifmgAePy/1OjkKN6rFRw==",
82 | "requires": {
83 | "@babel/runtime": "^7.4.4",
84 | "prop-types": "^15.7.2",
85 | "react-is": "^16.8.0"
86 | }
87 | },
88 | "@types/prop-types": {
89 | "version": "15.7.3",
90 | "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.3.tgz",
91 | "integrity": "sha512-KfRL3PuHmqQLOG+2tGpRO26Ctg+Cq1E01D2DMriKEATHgWLfeNDmq9e29Q9WIky0dQ3NPkd1mzYH8Lm936Z9qw=="
92 | },
93 | "@types/react": {
94 | "version": "16.9.56",
95 | "resolved": "https://registry.npmjs.org/@types/react/-/react-16.9.56.tgz",
96 | "integrity": "sha512-gIkl4J44G/qxbuC6r2Xh+D3CGZpJ+NdWTItAPmZbR5mUS+JQ8Zvzpl0ea5qT/ZT3ZNTUcDKUVqV3xBE8wv/DyQ==",
97 | "requires": {
98 | "@types/prop-types": "*",
99 | "csstype": "^3.0.2"
100 | },
101 | "dependencies": {
102 | "csstype": {
103 | "version": "3.0.4",
104 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.4.tgz",
105 | "integrity": "sha512-xc8DUsCLmjvCfoD7LTGE0ou2MIWLx0K9RCZwSHMOdynqRsP4MtUcLeqh1HcQ2dInwDTqn+3CE0/FZh1et+p4jA=="
106 | }
107 | }
108 | },
109 | "@types/react-transition-group": {
110 | "version": "4.4.0",
111 | "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.0.tgz",
112 | "integrity": "sha512-/QfLHGpu+2fQOqQaXh8MG9q03bFENooTb/it4jr5kKaZlDQfWvjqWZg48AwzPVMBHlRuTRAY7hRHCEOXz5kV6w==",
113 | "requires": {
114 | "@types/react": "*"
115 | }
116 | },
117 | "clsx": {
118 | "version": "1.1.1",
119 | "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.1.1.tgz",
120 | "integrity": "sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA=="
121 | },
122 | "css-vendor": {
123 | "version": "2.0.8",
124 | "resolved": "https://registry.npmjs.org/css-vendor/-/css-vendor-2.0.8.tgz",
125 | "integrity": "sha512-x9Aq0XTInxrkuFeHKbYC7zWY8ai7qJ04Kxd9MnvbC1uO5DagxoHQjm4JvG+vCdXOoFtCjbL2XSZfxmoYa9uQVQ==",
126 | "requires": {
127 | "@babel/runtime": "^7.8.3",
128 | "is-in-browser": "^1.0.2"
129 | }
130 | },
131 | "csstype": {
132 | "version": "2.6.13",
133 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-2.6.13.tgz",
134 | "integrity": "sha512-ul26pfSQTZW8dcOnD2iiJssfXw0gdNVX9IJDH/X3K5DGPfj+fUYe3kB+swUY6BF3oZDxaID3AJt+9/ojSAE05A=="
135 | },
136 | "dom-helpers": {
137 | "version": "5.2.0",
138 | "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.0.tgz",
139 | "integrity": "sha512-Ru5o9+V8CpunKnz5LGgWXkmrH/20cGKwcHwS4m73zIvs54CN9epEmT/HLqFJW3kXpakAFkEdzgy1hzlJe3E4OQ==",
140 | "requires": {
141 | "@babel/runtime": "^7.8.7",
142 | "csstype": "^3.0.2"
143 | },
144 | "dependencies": {
145 | "csstype": {
146 | "version": "3.0.4",
147 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.4.tgz",
148 | "integrity": "sha512-xc8DUsCLmjvCfoD7LTGE0ou2MIWLx0K9RCZwSHMOdynqRsP4MtUcLeqh1HcQ2dInwDTqn+3CE0/FZh1et+p4jA=="
149 | }
150 | }
151 | },
152 | "hoist-non-react-statics": {
153 | "version": "3.3.2",
154 | "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
155 | "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
156 | "requires": {
157 | "react-is": "^16.7.0"
158 | }
159 | },
160 | "hyphenate-style-name": {
161 | "version": "1.0.4",
162 | "resolved": "https://registry.npmjs.org/hyphenate-style-name/-/hyphenate-style-name-1.0.4.tgz",
163 | "integrity": "sha512-ygGZLjmXfPHj+ZWh6LwbC37l43MhfztxetbFCoYTM2VjkIUpeHgSNn7QIyVFj7YQ1Wl9Cbw5sholVJPzWvC2MQ=="
164 | },
165 | "is-in-browser": {
166 | "version": "1.1.3",
167 | "resolved": "https://registry.npmjs.org/is-in-browser/-/is-in-browser-1.1.3.tgz",
168 | "integrity": "sha1-Vv9NtoOgeMYILrldrX3GLh0E+DU="
169 | },
170 | "js-tokens": {
171 | "version": "4.0.0",
172 | "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
173 | "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
174 | },
175 | "jss": {
176 | "version": "10.4.0",
177 | "resolved": "https://registry.npmjs.org/jss/-/jss-10.4.0.tgz",
178 | "integrity": "sha512-l7EwdwhsDishXzqTc3lbsbyZ83tlUl5L/Hb16pHCvZliA9lRDdNBZmHzeJHP0sxqD0t1mrMmMR8XroR12JBYzw==",
179 | "requires": {
180 | "@babel/runtime": "^7.3.1",
181 | "csstype": "^3.0.2",
182 | "is-in-browser": "^1.1.3",
183 | "tiny-warning": "^1.0.2"
184 | },
185 | "dependencies": {
186 | "csstype": {
187 | "version": "3.0.4",
188 | "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.4.tgz",
189 | "integrity": "sha512-xc8DUsCLmjvCfoD7LTGE0ou2MIWLx0K9RCZwSHMOdynqRsP4MtUcLeqh1HcQ2dInwDTqn+3CE0/FZh1et+p4jA=="
190 | }
191 | }
192 | },
193 | "jss-plugin-camel-case": {
194 | "version": "10.4.0",
195 | "resolved": "https://registry.npmjs.org/jss-plugin-camel-case/-/jss-plugin-camel-case-10.4.0.tgz",
196 | "integrity": "sha512-9oDjsQ/AgdBbMyRjc06Kl3P8lDCSEts2vYZiPZfGAxbGCegqE4RnMob3mDaBby5H9vL9gWmyyImhLRWqIkRUCw==",
197 | "requires": {
198 | "@babel/runtime": "^7.3.1",
199 | "hyphenate-style-name": "^1.0.3",
200 | "jss": "10.4.0"
201 | }
202 | },
203 | "jss-plugin-default-unit": {
204 | "version": "10.4.0",
205 | "resolved": "https://registry.npmjs.org/jss-plugin-default-unit/-/jss-plugin-default-unit-10.4.0.tgz",
206 | "integrity": "sha512-BYJ+Y3RUYiMEgmlcYMLqwbA49DcSWsGgHpVmEEllTC8MK5iJ7++pT9TnKkKBnNZZxTV75ycyFCR5xeLSOzVm4A==",
207 | "requires": {
208 | "@babel/runtime": "^7.3.1",
209 | "jss": "10.4.0"
210 | }
211 | },
212 | "jss-plugin-global": {
213 | "version": "10.4.0",
214 | "resolved": "https://registry.npmjs.org/jss-plugin-global/-/jss-plugin-global-10.4.0.tgz",
215 | "integrity": "sha512-b8IHMJUmv29cidt3nI4bUI1+Mo5RZE37kqthaFpmxf5K7r2aAegGliAw4hXvA70ca6ckAoXMUl4SN/zxiRcRag==",
216 | "requires": {
217 | "@babel/runtime": "^7.3.1",
218 | "jss": "10.4.0"
219 | }
220 | },
221 | "jss-plugin-nested": {
222 | "version": "10.4.0",
223 | "resolved": "https://registry.npmjs.org/jss-plugin-nested/-/jss-plugin-nested-10.4.0.tgz",
224 | "integrity": "sha512-cKgpeHIxAP0ygeWh+drpLbrxFiak6zzJ2toVRi/NmHbpkNaLjTLgePmOz5+67ln3qzJiPdXXJB1tbOyYKAP4Pw==",
225 | "requires": {
226 | "@babel/runtime": "^7.3.1",
227 | "jss": "10.4.0",
228 | "tiny-warning": "^1.0.2"
229 | }
230 | },
231 | "jss-plugin-props-sort": {
232 | "version": "10.4.0",
233 | "resolved": "https://registry.npmjs.org/jss-plugin-props-sort/-/jss-plugin-props-sort-10.4.0.tgz",
234 | "integrity": "sha512-j/t0R40/2fp+Nzt6GgHeUFnHVY2kPGF5drUVlgkcwYoHCgtBDOhTTsOfdaQFW6sHWfoQYgnGV4CXdjlPiRrzwA==",
235 | "requires": {
236 | "@babel/runtime": "^7.3.1",
237 | "jss": "10.4.0"
238 | }
239 | },
240 | "jss-plugin-rule-value-function": {
241 | "version": "10.4.0",
242 | "resolved": "https://registry.npmjs.org/jss-plugin-rule-value-function/-/jss-plugin-rule-value-function-10.4.0.tgz",
243 | "integrity": "sha512-w8504Cdfu66+0SJoLkr6GUQlEb8keHg8ymtJXdVHWh0YvFxDG2l/nS93SI5Gfx0fV29dO6yUugXnKzDFJxrdFQ==",
244 | "requires": {
245 | "@babel/runtime": "^7.3.1",
246 | "jss": "10.4.0",
247 | "tiny-warning": "^1.0.2"
248 | }
249 | },
250 | "jss-plugin-vendor-prefixer": {
251 | "version": "10.4.0",
252 | "resolved": "https://registry.npmjs.org/jss-plugin-vendor-prefixer/-/jss-plugin-vendor-prefixer-10.4.0.tgz",
253 | "integrity": "sha512-DpF+/a+GU8hMh/948sBGnKSNfKkoHg2p9aRFUmyoyxgKjOeH9n74Ht3Yt8lOgdZsuWNJbPrvaa3U4PXKwxVpTQ==",
254 | "requires": {
255 | "@babel/runtime": "^7.3.1",
256 | "css-vendor": "^2.0.8",
257 | "jss": "10.4.0"
258 | }
259 | },
260 | "loose-envify": {
261 | "version": "1.4.0",
262 | "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
263 | "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
264 | "requires": {
265 | "js-tokens": "^3.0.0 || ^4.0.0"
266 | }
267 | },
268 | "object-assign": {
269 | "version": "4.1.1",
270 | "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
271 | "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
272 | },
273 | "popper.js": {
274 | "version": "1.16.1-lts",
275 | "resolved": "https://registry.npmjs.org/popper.js/-/popper.js-1.16.1-lts.tgz",
276 | "integrity": "sha512-Kjw8nKRl1m+VrSFCoVGPph93W/qrSO7ZkqPpTf7F4bk/sqcfWK019dWBUpE/fBOsOQY1dks/Bmcbfn1heM/IsA=="
277 | },
278 | "prop-types": {
279 | "version": "15.7.2",
280 | "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",
281 | "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",
282 | "requires": {
283 | "loose-envify": "^1.4.0",
284 | "object-assign": "^4.1.1",
285 | "react-is": "^16.8.1"
286 | }
287 | },
288 | "react": {
289 | "version": "16.14.0",
290 | "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz",
291 | "integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",
292 | "requires": {
293 | "loose-envify": "^1.1.0",
294 | "object-assign": "^4.1.1",
295 | "prop-types": "^15.6.2"
296 | }
297 | },
298 | "react-dom": {
299 | "version": "16.14.0",
300 | "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz",
301 | "integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",
302 | "requires": {
303 | "loose-envify": "^1.1.0",
304 | "object-assign": "^4.1.1",
305 | "prop-types": "^15.6.2",
306 | "scheduler": "^0.19.1"
307 | }
308 | },
309 | "react-is": {
310 | "version": "16.13.1",
311 | "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
312 | "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
313 | },
314 | "react-transition-group": {
315 | "version": "4.4.1",
316 | "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.1.tgz",
317 | "integrity": "sha512-Djqr7OQ2aPUiYurhPalTrVy9ddmFCCzwhqQmtN+J3+3DzLO209Fdr70QrN8Z3DsglWql6iY1lDWAfpFiBtuKGw==",
318 | "requires": {
319 | "@babel/runtime": "^7.5.5",
320 | "dom-helpers": "^5.0.1",
321 | "loose-envify": "^1.4.0",
322 | "prop-types": "^15.6.2"
323 | }
324 | },
325 | "regenerator-runtime": {
326 | "version": "0.13.7",
327 | "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.7.tgz",
328 | "integrity": "sha512-a54FxoJDIr27pgf7IgeQGxmqUNYrcV338lf/6gH456HZ/PhX+5BcwHXG9ajESmwe6WRO0tAzRUrRmNONWgkrew=="
329 | },
330 | "scheduler": {
331 | "version": "0.19.1",
332 | "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
333 | "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
334 | "requires": {
335 | "loose-envify": "^1.1.0",
336 | "object-assign": "^4.1.1"
337 | }
338 | },
339 | "tiny-warning": {
340 | "version": "1.0.3",
341 | "resolved": "https://registry.npmjs.org/tiny-warning/-/tiny-warning-1.0.3.tgz",
342 | "integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="
343 | }
344 | }
345 | }
346 |
--------------------------------------------------------------------------------
/examples/material_ui/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "material_ui",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "@material-ui/core": "^4.11.0",
14 | "@material-ui/types": "^5.1.0",
15 | "react": "^16.8.0",
16 | "react-dom": "^16.8.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/reacty_yew/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 |
--------------------------------------------------------------------------------
/reacty_yew/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | [[package]]
4 | name = "itoa"
5 | version = "0.4.6"
6 | source = "registry+https://github.com/rust-lang/crates.io-index"
7 | checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
8 |
9 | [[package]]
10 | name = "proc-macro-error"
11 | version = "1.0.4"
12 | source = "registry+https://github.com/rust-lang/crates.io-index"
13 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
14 | dependencies = [
15 | "proc-macro-error-attr",
16 | "proc-macro2",
17 | "quote",
18 | "syn",
19 | "version_check",
20 | ]
21 |
22 | [[package]]
23 | name = "proc-macro-error-attr"
24 | version = "1.0.4"
25 | source = "registry+https://github.com/rust-lang/crates.io-index"
26 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
27 | dependencies = [
28 | "proc-macro2",
29 | "quote",
30 | "version_check",
31 | ]
32 |
33 | [[package]]
34 | name = "proc-macro2"
35 | version = "1.0.24"
36 | source = "registry+https://github.com/rust-lang/crates.io-index"
37 | checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
38 | dependencies = [
39 | "unicode-xid",
40 | ]
41 |
42 | [[package]]
43 | name = "quote"
44 | version = "1.0.7"
45 | source = "registry+https://github.com/rust-lang/crates.io-index"
46 | checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
47 | dependencies = [
48 | "proc-macro2",
49 | ]
50 |
51 | [[package]]
52 | name = "reacty_yew"
53 | version = "0.1.0"
54 | dependencies = [
55 | "proc-macro-error",
56 | "proc-macro2",
57 | "quote",
58 | "serde",
59 | "serde_json",
60 | "syn",
61 | ]
62 |
63 | [[package]]
64 | name = "ryu"
65 | version = "1.0.5"
66 | source = "registry+https://github.com/rust-lang/crates.io-index"
67 | checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
68 |
69 | [[package]]
70 | name = "serde"
71 | version = "1.0.117"
72 | source = "registry+https://github.com/rust-lang/crates.io-index"
73 | checksum = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a"
74 | dependencies = [
75 | "serde_derive",
76 | ]
77 |
78 | [[package]]
79 | name = "serde_derive"
80 | version = "1.0.117"
81 | source = "registry+https://github.com/rust-lang/crates.io-index"
82 | checksum = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e"
83 | dependencies = [
84 | "proc-macro2",
85 | "quote",
86 | "syn",
87 | ]
88 |
89 | [[package]]
90 | name = "serde_json"
91 | version = "1.0.59"
92 | source = "registry+https://github.com/rust-lang/crates.io-index"
93 | checksum = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95"
94 | dependencies = [
95 | "itoa",
96 | "ryu",
97 | "serde",
98 | ]
99 |
100 | [[package]]
101 | name = "syn"
102 | version = "1.0.48"
103 | source = "registry+https://github.com/rust-lang/crates.io-index"
104 | checksum = "cc371affeffc477f42a221a1e4297aedcea33d47d19b61455588bd9d8f6b19ac"
105 | dependencies = [
106 | "proc-macro2",
107 | "quote",
108 | "unicode-xid",
109 | ]
110 |
111 | [[package]]
112 | name = "unicode-xid"
113 | version = "0.2.1"
114 | source = "registry+https://github.com/rust-lang/crates.io-index"
115 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
116 |
117 | [[package]]
118 | name = "version_check"
119 | version = "0.9.2"
120 | source = "registry+https://github.com/rust-lang/crates.io-index"
121 | checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
122 |
--------------------------------------------------------------------------------
/reacty_yew/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "reacty_yew"
3 | version = "0.1.0"
4 | authors = ["Maximilian Goisser "]
5 | edition = "2018"
6 | description = "Generate Yew components from React component via Typescript type definitions"
7 | license = "MIT OR Apache-2.0"
8 | repository = "https://github.com/hobofan/reacty_yew"
9 | keywords = ["yew", "react"]
10 | readme = "../README.md"
11 |
12 | [lib]
13 | proc-macro = true
14 |
15 | [dependencies]
16 | serde = { version = "1.0", features = ["derive"] }
17 | serde_json = { version = "1.0" }
18 | syn = { version = "1.0.8", features = ["full", "extra-traits"] }
19 | quote = "1.0.2"
20 | proc-macro2 = "1.0.6"
21 | proc-macro-error = "1.0"
22 |
--------------------------------------------------------------------------------
/reacty_yew/src/analyzer.rs:
--------------------------------------------------------------------------------
1 | use proc_macro_error::{diagnostic, emit_error, Level};
2 | use quote::quote;
3 | use serde::{Deserialize, Serialize};
4 | use std::fs;
5 | use std::path::PathBuf;
6 | use std::process::Command;
7 |
8 | const ANALYZER_SCRIPT_FILE: &'static str = include_str!("./js/index.js");
9 | const TYPESCRIPT_SCRIPT_FILE: &'static str = include_str!("./js/typescript.js");
10 |
11 | #[derive(Serialize, Deserialize, Debug, Clone)]
12 | pub struct AnalyzerOutput {
13 | pub types: Vec,
14 | pub components: Vec,
15 | }
16 |
17 | #[derive(Serialize, Deserialize, Debug, Clone)]
18 | pub struct Type {
19 | pub name: String,
20 | pub properties: Vec,
21 | }
22 |
23 | #[derive(Serialize, Deserialize, Debug, Clone)]
24 | pub struct TypeProperty {
25 | #[serde(rename = "intrinsicType")]
26 | pub intrinsic_type: Option,
27 | pub name: String,
28 | pub optional: bool,
29 | }
30 |
31 | #[derive(Serialize, Deserialize, Debug, Clone)]
32 | pub struct Component {
33 | pub name: String,
34 | #[serde(rename = "propsName")]
35 | pub props_name: String,
36 | }
37 |
38 | impl AnalyzerOutput {
39 | pub fn types(&self) -> Vec {
40 | let mut types = self.types.clone();
41 | types.dedup_by_key(|n| n.name.clone());
42 | types
43 | }
44 | }
45 |
46 | impl TypeProperty {
47 | pub fn name_ident(&self) -> syn::Ident {
48 | syn::Ident::new(&self.name, proc_macro2::Span::call_site())
49 | }
50 |
51 | pub fn rust_type_for_intrinsic_type(&self) -> Option {
52 | self.intrinsic_type
53 | .as_ref()
54 | .map(|intrinsic_type| match intrinsic_type.as_ref() {
55 | "string" => quote! { String },
56 | "number" => quote! { f64 },
57 | "boolean" => quote! { bool },
58 | "any" => quote! { JsValue },
59 | other => {
60 | emit_error!(diagnostic!(
61 | proc_macro::Span::call_site(),
62 | Level::Error,
63 | format!(
64 | "reacty_yew: Unable to convert intrinsic type \"{}\" to Rust type",
65 | other
66 | ),
67 | ));
68 | quote! {}
69 | }
70 | })
71 | }
72 |
73 | pub fn conversion_to_js_type(&self, prop_name: syn::Ident) -> proc_macro2::TokenStream {
74 | self.intrinsic_type
75 | .as_ref()
76 | .map(|intrinsic_type| match intrinsic_type.as_ref() {
77 | "string" | "number" | "boolean" => {
78 | quote! { JsValue::from_serde(#prop_name).unwrap() }
79 | }
80 | "any" => {
81 | quote! { #prop_name.to_owned() }
82 | }
83 | _ => unimplemented!(),
84 | })
85 | .unwrap()
86 | }
87 | }
88 |
89 | pub fn init_js_scripts() {
90 | let analyzer_script_path =
91 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("./target/index.js");
92 | let typescript_script_path =
93 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("./target/typescript.js");
94 |
95 | fs::write(&analyzer_script_path, ANALYZER_SCRIPT_FILE)
96 | .expect("Unable to write analyzer script");
97 | fs::write(&typescript_script_path, TYPESCRIPT_SCRIPT_FILE)
98 | .expect("Unable to write typscript dependency script");
99 | }
100 |
101 | pub fn run_analyzer(path: &str) -> AnalyzerOutput {
102 | let analyzer_script_path =
103 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("./target/index.js");
104 | let input_path = PathBuf::from(path).canonicalize().unwrap();
105 |
106 | let output = Command::new("node")
107 | .args(&[
108 | analyzer_script_path.to_string_lossy().as_ref(),
109 | input_path.to_string_lossy().as_ref(),
110 | ])
111 | .output()
112 | .expect("failed to execute process");
113 |
114 | serde_json::from_slice(&output.stdout).unwrap()
115 | }
116 |
--------------------------------------------------------------------------------
/reacty_yew/src/js/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | exports.__esModule = true;
3 | exports.generateDocumentation = void 0;
4 | var ts = require("./typescript.js");
5 | var util = require('util');
6 | var log = util.debuglog('fortest');
7 | /** Generate documentation for all classes in a set of .ts files */
8 | function generateDocumentation(fileNames, options) {
9 | // Build a program using the set of root file names in fileNames
10 | var program = ts.createProgram(fileNames, options);
11 | // Get the checker, we will use it to find more about classes
12 | var checker = program.getTypeChecker();
13 | var output = [];
14 | var types = [];
15 | var components = [];
16 | // Visit every sourceFile in the program
17 | for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
18 | var sourceFile = _a[_i];
19 | // if (sourceFile.isDeclarationFile) {
20 | // Walk the tree to search for classes
21 | ts.forEachChild(sourceFile, visit);
22 | // }
23 | }
24 | return [components, types];
25 | /** visit nodes finding exported classes */
26 | function visit(node) {
27 | // Only consider exported nodes
28 | if (!isNodeExported(node)) {
29 | return;
30 | }
31 | if (ts.isClassDeclaration(node) && node.name) {
32 | // This is a top level class, get its symbol
33 | var symbol = checker.getSymbolAtLocation(node.name);
34 | if (symbol) {
35 | output.push(serializeClass(symbol));
36 | }
37 | // No need to walk any further, class expressions/inner declarations
38 | // cannot be exported
39 | }
40 | else if (ts.isModuleDeclaration(node)) {
41 | // This is a namespace, visit its children
42 | ts.forEachChild(node, visit);
43 | }
44 | if (ts.isVariableStatement(node)) {
45 | node.declarationList.declarations.forEach(function (subnode) {
46 | var initializer = subnode.initializer || subnode.type;
47 | if (initializer && initializer.parameters && isFunctionalComponent(initializer)) {
48 | var propsName_1;
49 | initializer.parameters.forEach(function (param) {
50 | var typeNode = param.type;
51 | var typ = checker.getTypeFromTypeNode(typeNode);
52 | var simpleType = typeToSimpleType(typ);
53 | types.push(simpleType);
54 | propsName_1 = simpleType.name;
55 | });
56 | var componentExportedName = exportedNameForSymbol(subnode, node);
57 | var component = {
58 | name: componentExportedName,
59 | propsName: propsName_1
60 | };
61 | components.push(component);
62 | }
63 | });
64 | }
65 | if (ts.isFunctionDeclaration(node)) {
66 | if (isFunctionalComponent(node)) {
67 | var propsName_2;
68 | node.parameters.forEach(function (param) {
69 | var typeNode = param.type;
70 | var typ = checker.getTypeFromTypeNode(typeNode);
71 | var simpleType = typeToSimpleType(typ);
72 | types.push(simpleType);
73 | propsName_2 = simpleType.name;
74 | });
75 | var component = {
76 | name: node.name.escapedText,
77 | propsName: propsName_2
78 | };
79 | components.push(component);
80 | }
81 | }
82 | }
83 | function isFunctionalComponent(node) {
84 | var signatureDeclaration = node;
85 | var isElementSymbolWithJsxParent = function (returnType) {
86 | if (returnType.symbol &&
87 | returnType.symbol.parent &&
88 | returnType.symbol.escapedText === 'Element' &&
89 | returnType.symbol.parent.escapedText === 'JSX') {
90 | return true;
91 | }
92 | if (returnType.symbol &&
93 | returnType.symbol.parent &&
94 | returnType.symbol.escapedName === 'Element' &&
95 | returnType.symbol.parent.escapedName === 'JSX') {
96 | return true;
97 | }
98 | return false;
99 | };
100 | if (ts.isFunctionLike(node)) {
101 | var returnType = checker.getSignatureFromDeclaration(signatureDeclaration).getReturnType();
102 | if (isElementSymbolWithJsxParent(returnType)) {
103 | return true;
104 | }
105 | }
106 | var typeName = node.type.typeName;
107 | if (typeName && ts.isQualifiedName(typeName)) {
108 | if (ts.isIdentifier(typeName.left) &&
109 | typeName.left.escapedText === 'JSX' &&
110 | typeName.right.escapedText === 'Element') {
111 | return true;
112 | }
113 | }
114 | return false;
115 | }
116 | function typeToSimpleType(type) {
117 | var typeName;
118 | if (type.aliasSymbol) {
119 | typeName = type.aliasSymbol.escapedName;
120 | }
121 | if (!typeName) {
122 | typeName = type.symbol.escapedName;
123 | }
124 | var simpleType = {
125 | name: typeName,
126 | properties: []
127 | };
128 | type.symbol.members.forEach(function (symbol, key) {
129 | var checkedType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
130 | var intrinsicName = checkedType.intrinsicName;
131 | var optional = checker.isOptionalParameter(symbol.declarations[0]);
132 | var complexType;
133 | if (checkedType.aliasSymbol) {
134 | complexType = checkedType.aliasSymbol.escapedName;
135 | var simpleType_1 = typeToSimpleType(checkedType);
136 | types.push(simpleType_1);
137 | }
138 | var property = {
139 | name: key,
140 | intrinsicType: intrinsicName,
141 | complexType: complexType,
142 | optional: optional
143 | };
144 | simpleType.properties.push(property);
145 | });
146 | return simpleType;
147 | }
148 | function exportedNameForSymbol(symbol, fileNode) {
149 | var localName = symbol.name.escapedText;
150 | var exportedName;
151 | fileNode.parent.symbol.exports.forEach(function (value, key) {
152 | // Follow exported symbol to original symbol
153 | try {
154 | var aliasedSymbol = checker.getAliasedSymbol(value);
155 | if (aliasedSymbol.escapedName === localName) {
156 | exportedName = value.escapedName;
157 | }
158 | }
159 | catch (_a) { }
160 | });
161 | return exportedName || localName;
162 | }
163 | /** Serialize a symbol into a json object */
164 | function serializeSymbol(symbol) {
165 | return {
166 | name: symbol.getName(),
167 | documentation: ts.displayPartsToString(symbol.getDocumentationComment(checker)),
168 | type: checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))
169 | };
170 | }
171 | /** Serialize a class symbol information */
172 | function serializeClass(symbol) {
173 | var details = serializeSymbol(symbol);
174 | // Get the construct signatures
175 | var constructorType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
176 | details.constructors = constructorType
177 | .getConstructSignatures()
178 | .map(serializeSignature);
179 | return details;
180 | }
181 | /** Serialize a signature (call or construct) */
182 | function serializeSignature(signature) {
183 | return {
184 | parameters: signature.parameters.map(serializeSymbol),
185 | returnType: checker.typeToString(signature.getReturnType()),
186 | documentation: ts.displayPartsToString(signature.getDocumentationComment(checker))
187 | };
188 | }
189 | /** True if this is visible outside this file, false otherwise */
190 | function isNodeExported(node) {
191 | return ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0 ||
192 | (!!node.parent && node.parent.kind === ts.SyntaxKind.SourceFile));
193 | }
194 | }
195 | exports.generateDocumentation = generateDocumentation;
196 | if (require.main === module) {
197 | var _a = generateDocumentation(process.argv.slice(2), {
198 | target: ts.ScriptTarget.ES5,
199 | module: ts.ModuleKind.CommonJS
200 | }), components = _a[0], types = _a[1];
201 | // print out the doc
202 | var nullPrinter = function (key, value) { return typeof value === 'undefined' ? null : value; };
203 | console.log(JSON.stringify({
204 | "types": types,
205 | "components": components
206 | }, nullPrinter, 4));
207 | // fs.writeFileSync(
208 | // "types.json",
209 | // JSON.stringify(types, nullPrinter, 4)
210 | // );
211 | // fs.writeFileSync(
212 | // "components.json",
213 | // JSON.stringify(components, nullPrinter, 4)
214 | // );
215 | }
216 |
--------------------------------------------------------------------------------
/reacty_yew/src/js/update_source.sh:
--------------------------------------------------------------------------------
1 | #! /bin/bash
2 | set -euxo pipefail
3 |
4 | cp ../../../analyzer/src/index.js .
5 | cp ../../../analyzer/src/typescript.js .
6 |
7 | echo 'You need to manually edit the require("typescript") -> require("./typescript.js")'
8 |
--------------------------------------------------------------------------------
/reacty_yew/src/lib.rs:
--------------------------------------------------------------------------------
1 | extern crate proc_macro;
2 |
3 | mod analyzer;
4 |
5 | use proc_macro::TokenStream;
6 | use proc_macro_error::proc_macro_error;
7 | use quote::quote;
8 | use syn::parse::{Parse, ParseStream};
9 | use syn::Result;
10 |
11 | use analyzer::*;
12 |
13 | struct MacroInput {
14 | mod_ident: syn::Ident,
15 | types_path: String,
16 | global_name: String,
17 | }
18 |
19 | impl Parse for MacroInput {
20 | fn parse(input: ParseStream) -> Result {
21 | let initial_mod_part = input.call(syn::Meta::parse)?;
22 | input.parse::()?;
23 | let parts = input
24 | .call(syn::punctuated::Punctuated::::parse_terminated)?;
25 |
26 | let mod_ident = initial_mod_part.path().get_ident().unwrap().to_owned();
27 |
28 | let mut parts = parts.into_iter();
29 | let path_part = parts.next().unwrap();
30 | let global_part = parts.next().unwrap();
31 |
32 | let (types_path, global_name) = match (path_part, global_part) {
33 | (syn::Meta::NameValue(path), syn::Meta::NameValue(global)) => {
34 | match (path.lit, global.lit) {
35 | (syn::Lit::Str(raw_path), syn::Lit::Str(raw_global)) => {
36 | (raw_path.value(), raw_global.value())
37 | }
38 | _ => unimplemented!(),
39 | }
40 | }
41 | _ => unimplemented!(),
42 | };
43 |
44 | Ok(MacroInput {
45 | mod_ident,
46 | types_path,
47 | global_name,
48 | })
49 | }
50 | }
51 |
52 | #[proc_macro_error]
53 | #[proc_macro]
54 | pub fn react_component_mod(item: TokenStream) -> TokenStream {
55 | let input = syn::parse_macro_input!(item as MacroInput);
56 | init_js_scripts();
57 | let analyzer_output = run_analyzer(&input.types_path);
58 |
59 | let mod_name = input.mod_ident;
60 |
61 | let mut props_structs = quote! {};
62 | for props_type in analyzer_output.types() {
63 | let props_struct = component_props_struct(&props_type);
64 |
65 | props_structs = quote! {
66 | #props_structs
67 | #props_struct
68 | };
69 | }
70 |
71 | let mut component_and_render_fns = quote! {};
72 | for component in analyzer_output.components {
73 | let props = analyzer_output
74 | .types
75 | .iter()
76 | .find(|n| n.name == component.props_name)
77 | .unwrap();
78 |
79 | let (render_fn_name, render_fn) =
80 | component_render_function(&input.global_name, &component.name, &props);
81 | let struct_and_impl = component_struct_and_impl(&component.name, &props, &render_fn_name);
82 |
83 | component_and_render_fns = quote! {
84 | #component_and_render_fns
85 |
86 | #struct_and_impl
87 |
88 | #render_fn
89 | };
90 | }
91 |
92 | let expanded = quote! {
93 | mod #mod_name {
94 | use wasm_bindgen::prelude::*;
95 | use yew::prelude::*;
96 | use yew::web_sys::{self, Node};
97 | use yew::virtual_dom::VNode;
98 | use serde::{Serialize, Deserialize};
99 |
100 | #props_structs
101 |
102 | #component_and_render_fns
103 | }
104 | };
105 | TokenStream::from(expanded)
106 | }
107 |
108 | fn component_props_struct(props_type: &Type) -> proc_macro2::TokenStream {
109 | let props_name = syn::Ident::new(&props_type.name, proc_macro2::Span::call_site());
110 |
111 | let mut struct_fields = quote! {};
112 | for property in &props_type.properties {
113 | let field_name = property.name_ident();
114 | let rust_type = property
115 | .rust_type_for_intrinsic_type()
116 | .expect("Unsupported TS intrinsic type");
117 |
118 | let new_struct_field = match property.optional {
119 | false => {
120 | quote! {
121 | pub #field_name : #rust_type,
122 | }
123 | }
124 | true => {
125 | quote! {
126 | #[prop_or_default]
127 | pub #field_name : Option<#rust_type>,
128 | }
129 | }
130 | };
131 |
132 | struct_fields = quote! {
133 | #struct_fields
134 | #new_struct_field
135 | }
136 | }
137 |
138 | quote! {
139 | #[derive(Clone, Properties)]
140 | pub struct #props_name {
141 | #struct_fields
142 | }
143 | }
144 | }
145 |
146 | fn component_render_function(
147 | js_lib_name: &str,
148 | component_name: &str,
149 | props: &Type,
150 | ) -> (String, proc_macro2::TokenStream) {
151 | let render_fn_name = format!("render_{}", component_name);
152 | let render_fn_js_name = format!("render_{}_js", component_name);
153 |
154 | let component_name = syn::Ident::new(&component_name, proc_macro2::Span::call_site());
155 |
156 | let render_fn_name_ident = syn::Ident::new(&render_fn_name, proc_macro2::Span::call_site());
157 | let render_fn_js_name_ident =
158 | syn::Ident::new(&render_fn_js_name, proc_macro2::Span::call_site());
159 |
160 | let props_names: String = props
161 | .properties
162 | .iter()
163 | .map(|n| n.name.to_owned())
164 | .collect::>()
165 | .join(", ");
166 | let inline_js_script = format!(
167 | r#"
168 | export function {render_fn_js_name}(node, {props_names}) {{
169 | let element = React.createElement(
170 | {js_lib_name}.{component_name},
171 | {{ {props_names} }}
172 | );
173 | return ReactDOM.render(element, node);
174 | }}
175 | "#,
176 | js_lib_name = js_lib_name,
177 | component_name = component_name,
178 | render_fn_js_name = render_fn_js_name,
179 | props_names = props_names,
180 | );
181 |
182 | let mut original_type_props = quote! {};
183 | for property in &props.properties {
184 | let prop_name = property.name_ident();
185 | let prop_type = property.rust_type_for_intrinsic_type().unwrap();
186 |
187 | let maybe_type = match property.optional {
188 | false => {
189 | quote! { #prop_type }
190 | }
191 | true => {
192 | quote! { Option<#prop_type> }
193 | }
194 | };
195 |
196 | let original_type_prop = quote! { #prop_name: maybe_type, };
197 | original_type_props = quote! { #original_type_props #original_type_prop };
198 | }
199 | let mut type_conversions = quote! {};
200 | for property in &props.properties {
201 | let prop_name = property.name_ident();
202 | let type_conversion = property.conversion_to_js_type(prop_name);
203 | type_conversions = quote! {
204 | #type_conversions
205 | #type_conversion,
206 | };
207 | }
208 |
209 | let mut js_type_props = quote! {};
210 | for property in &props.properties {
211 | let prop_name = property.name_ident();
212 | let js_type_prop = quote! { #prop_name: JsValue, };
213 | js_type_props = quote! { #js_type_props #js_type_prop };
214 | }
215 |
216 | let render_fn = quote! {
217 | fn #render_fn_name_ident(node: &Node, #original_type_props) {
218 | #render_fn_js_name_ident(
219 | node,
220 | #type_conversions
221 | );
222 | }
223 |
224 | #[wasm_bindgen(inline_js = #inline_js_script)]
225 | extern "C" {
226 | fn #render_fn_js_name_ident(node: &Node, #js_type_props);
227 | }
228 | };
229 |
230 | (render_fn_name, render_fn)
231 | }
232 |
233 | fn component_struct_and_impl(
234 | component_name: &str,
235 | props: &Type,
236 | render_fn_name: &str,
237 | ) -> proc_macro2::TokenStream {
238 | let component_name = syn::Ident::new(&component_name, proc_macro2::Span::call_site());
239 | let props_name = syn::Ident::new(&props.name, proc_macro2::Span::call_site());
240 | let render_fn_name = syn::Ident::new(&render_fn_name, proc_macro2::Span::call_site());
241 |
242 | let mut original_type_props = quote! {};
243 | for property in &props.properties {
244 | let prop_name = property.name_ident();
245 | // let prop_type = property.rust_type_for_intrinsic_type().unwrap();
246 |
247 | let original_type_prop = quote! { &self.props.#prop_name, };
248 | original_type_props = quote! { #original_type_props #original_type_prop };
249 | }
250 |
251 | quote! {
252 | pub struct #component_name {
253 | node: Node,
254 | props: #props_name,
255 | }
256 |
257 | impl Component for #component_name {
258 | type Message = ();
259 | type Properties = #props_name;
260 |
261 |
262 | fn create(props: Self::Properties, _link: ComponentLink) -> Self {
263 | Self {
264 | node: Node::from(
265 | web_sys::window()
266 | .unwrap()
267 | .document()
268 | .unwrap()
269 | .create_element("div")
270 | .unwrap(),
271 | ),
272 | props,
273 | }
274 | }
275 |
276 | fn change(&mut self, _new_props: Self::Properties) -> ShouldRender {
277 | true
278 | }
279 |
280 | fn update(&mut self, msg: Self::Message) -> ShouldRender {
281 | true
282 | }
283 |
284 | fn view(&self) -> Html {
285 | #render_fn_name(&self.node, #original_type_props);
286 |
287 | VNode::VRef(self.node.clone())
288 | }
289 | }
290 | }
291 | }
292 |
--------------------------------------------------------------------------------