├── .babelrc
├── .eslintignore
├── .eslintrc.json
├── .github
└── workflows
│ └── npm-publish-github-packages.yml
├── .gitignore
├── .npmignore
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.txt
├── README.md
├── __tests__
├── .eslintrc.json
├── components
│ ├── Case.spec.jsx
│ ├── Default.spec.jsx
│ ├── ElseIf.spec.jsx
│ ├── Switch.spec.jsx
│ └── TryCatch.spec.jsx
└── index.spec.js
├── commitlint.config.js
├── examples
├── if-condition
│ └── ReactIf.jsx
├── if-else-condition
│ ├── ReactIfElse.jsx
│ └── ReactNestedIfElse.jsx
├── switch-case
│ └── SwitchCase.jsx
└── try-catch
│ └── ReactTryCatch.jsx
├── package.json
└── src
├── components
├── Case.jsx
├── Default.jsx
├── ElseIf.jsx
├── Switch.jsx
├── TryCatch.jsx
└── TryCatchFinally.js
└── index.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["amex"]
3 | }
4 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 | build
4 | lib
5 | test/api.js
6 | test/store.js
7 | test-results
8 | examples/**/*
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "amex"
3 | }
4 |
--------------------------------------------------------------------------------
/.github/workflows/npm-publish-github-packages.yml:
--------------------------------------------------------------------------------
1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
3 |
4 | name: Node.js Package
5 |
6 | on:
7 | release:
8 | types: [created]
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v2
15 | - uses: actions/setup-node@v2
16 | with:
17 | node-version: 16
18 | - run: npm ci
19 | - run: npm test
20 |
21 | publish-gpr:
22 | needs: build
23 | runs-on: ubuntu-latest
24 | permissions:
25 | contents: read
26 | packages: write
27 | steps:
28 | - uses: actions/checkout@v2
29 | - uses: actions/setup-node@v2
30 | with:
31 | node-version: 16
32 | registry-url: https://npm.pkg.github.com/
33 | - run: npm ci
34 | - run: npm publish
35 | env:
36 | NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Other Repos
2 | #################
3 | .svn
4 | .editorconfig
5 |
6 | ## Project Specific
7 | #################
8 |
9 | .vagrant
10 | node_modules
11 | out
12 | .coverdata
13 | .coverrun
14 | dist
15 | build
16 | lib
17 | coverage
18 | env
19 | reports/*
20 | !reports/.gitkeep
21 | npm-debug.log
22 | package-lock.json
23 | .sass-cache
24 | logs/
25 | ./config/development.js
26 | test-results
27 | .gitkeep
28 | .jest-cache
29 | .webpack-stats.*
30 |
31 |
32 | ## OSX
33 | #################
34 |
35 | [Tt]humbs.db
36 | *.DS_Store
37 |
38 | ## Generic
39 | #################
40 |
41 | *.tmp
42 | *.bak
43 | *.cya
44 |
45 | ## Webstorm
46 | #################
47 |
48 | .idea
49 |
50 | ## Eclipse
51 | #################
52 |
53 | *.pydevproject
54 | .project
55 | .metadata
56 | .gradle
57 | bin/
58 | tmp/
59 | target/
60 | *.swp
61 | *~.nib
62 | local.properties
63 | .classpath
64 | .settings/
65 | .loadpath
66 |
67 | ## Atlassian
68 | #################
69 |
70 | atlassian-ide-plugin.xml
71 |
72 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | ## Other Repos
2 | #################
3 | .svn
4 |
5 | ## Project Specific
6 | #################
7 |
8 | .vagrant
9 | node_modules
10 | out
11 | .coverdata
12 | .coverrun
13 | dist
14 | env
15 | reports/*
16 | !reports/.gitkeep
17 | npm-debug.log
18 | .sass-cache
19 | logs/
20 | ./config/development.js
21 | test-results
22 |
23 |
24 | ## OSX
25 | #################
26 |
27 | [Tt]humbs.db
28 | *.DS_Store
29 |
30 | ## Generic
31 | #################
32 |
33 | *.tmp
34 | *.bak
35 | *.cya
36 |
37 | ## Webstorm
38 | #################
39 |
40 | .idea
41 |
42 | ## Eclipse
43 | #################
44 |
45 | *.iml
46 | *.pydevproject
47 | .project
48 | .metadata
49 | .gradle
50 | bin/
51 | tmp/
52 | target/
53 | *.swp
54 | *~.nib
55 | local.properties
56 | .classpath
57 | .settings/
58 | .loadpath
59 |
60 | ## Atlassian
61 | #################
62 |
63 | atlassian-ide-plugin.xml
64 |
65 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "12"
4 | - "10"
5 | - "8"
6 | deploy:
7 | on:
8 | tags: true
9 | branch: master
10 | provider: npm
11 | email: open-source-ops@aexp.com
12 | api_key:
13 | secure: aJ9xDFzjQ1chQ/A+m2rq81W5zTyoNCSTxsX//iw33fQGHvtPV5sLxxBx5AP+9XDEcvixJ/tMDVzO8RiT0DnEAH9XfAGupfnMNgXPVK4X+hmDY4eOUvT6WWcvxoECojC5SaSfqhDfRrihzZfzJCbegHUiVUu9YknZf7kcYudLuvad4//q0WGQbV3F8hErQAQ6gDDjGa3mwv9a/OS2GlRXrIEbTNED+ocwDtRaW0vIYD3CxZtkOj3Na3XaWd9LmkKvKiZhkI8AnS0Iqt9Y1SlxVrh7fUNddUyTqWxolwMWTTL2bVVODIWg9Jllm5F2XDkDhYXI7WLL9f+SzLaDYM4WFpS7VMU2HeEM6wpfBq4O0QmfZpUZSyW+KRFumvZftXMK+f9XWrrqeuBdNQLZMhjtHtf+AXF0SClKu1/y7VGcSnFzUhfWa9Zc05/oteP18QQy191ly6stC2EaBGpT9tL6TmUmb4r5BeWLhhsMXVsUCSqox0/yCG6J7WaEjHoKyjYkJGssChb2gv1PDT5tnk2f3jGXC/kpnneixi7L0vmH5aBYRYKCKXdl8cXlnwoiOH6KTZ8+khDclVYkDgJBATcUPd25Kh7I57J5Kp/iUf1nwuoAAm8atTsu05Qmh53X9w29hK1JvovsITHuOM9fhTeijuCPXJz3sarfBt+5YwoIj98=
14 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ### American Express Open Source Community Guidelines
2 |
3 | #### Last Modified: January 29, 2016
4 |
5 | Welcome to the American Express Open Source Community on GitHub! These American Express Community Guidelines outline our expectations for Github participating members within the American Express community, as well as steps for reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect our community Guidelines to be honored.
6 |
7 | **IMPORTANT REMINDER:**
8 |
9 | When you visit American Express on any third party sites such as GitHub your activity there is subject to that site’s then current terms of use., along with their privacy and data security practices and policies. The Github platform is not affiliated with us and may have practices and policies that are different than are our own.
10 | Please note, American Express is not responsible for, and does not control, the GitHub site’s terms of use, privacy and data security practices and policies. You should, therefore, always exercise caution when posting, sharing or otherwise taking any action on that site and, of course, on the Internet in general.
11 | Our open source community strives to:
12 | - **Be friendly and patient**.
13 | - **Be welcoming**: We strive to be a community that welcomes and supports people of all
14 | backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, color, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability.
15 | - **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary language.
16 | - **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a productive one.
17 | - **Be careful in the words that we choose**: We are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren't acceptable.
18 | - **Try to understand why we disagree**: Disagreements, both social and technical, happen all the time. It is important that we resolve disagreements and differing views constructively. Remember that we’re all different people. The strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping to resolve issues and learning from mistakes.
19 |
20 | ### Definitions
21 | Harassment includes, but is not limited to:
22 | - Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, neuro(a)typicality, physical appearance, body size, race, age, regional discrimination, political or religious affiliation
23 | - Unwelcome comments regarding a person’s lifestyle choices and practices, including those related to food, health, parenting, drugs, and employment
24 | - Deliberate misgendering. This includes deadnaming or persistently using a pronoun that does not correctly reflect a person's gender identity. You must address people by the name they give you when not addressing them by their username or handle
25 | - Physical contact and simulated physical contact (eg, textual descriptions like “hug” or “backrub”) without consent or after a request to stop
26 | - Threats of violence, both physical and psychological
27 | - Incitement of violence towards any individual, including encouraging a person to commit suicide
28 | or to engage in self-harm
29 | - Deliberate intimidation
30 | - Stalking or following
31 | - Harassing photography or recording, including logging online activity for harassment purposes
32 | - Sustained disruption of discussion
33 | - Unwelcome sexual attention, including gratuitous or off-topic sexual images or behaviour
34 | - Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of
35 | intimacy with others
36 | - Continued one-on-one communication after requests to cease
37 | - Deliberate “outing” of any aspect of a person’s identity without their consent except as necessary
38 | to protect others from intentional abuse
39 | - Publication of non-harassing private communication
40 |
41 | Our open source community prioritizes marginalized people’s safety over privileged people’s comfort. We will not act on complaints regarding:
42 | - ‘Reverse’ -isms, including ‘reverse racism,’ ‘reverse sexism,’ and ‘cisphobia’
43 | - Reasonable communication of boundaries, such as “leave me alone,” “go away,” or “I’m not
44 | discussing this with you”
45 | - Refusal to explain or debate social justice concepts
46 | - Communicating in a ‘tone’ you don’t find congenial
47 | - Criticizing racist, sexist, cissexist, or otherwise oppressive behavior or assumptions
48 |
49 | ### Diversity Statement
50 | We encourage everyone to participate and are committed to building a community for all. Although we will fail at times, we seek to treat everyone both as fairly and equally as possible. Whenever a participant has made a mistake, we expect them to take responsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and respectfully, and do our best to right the wrong.
51 |
52 | Although this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression, culture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation, socioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected characteristics above, including participants with disabilities.
53 |
54 | ### Reporting Issues
55 | If you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us at opensource@aexp.com. All reports will be handled with discretion. In your report please include:
56 | - Your contact information.
57 | - Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional
58 | witnesses, please include them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly available record (e.g. a mailing list archive or a public IRC logger), please include a link.
59 | - Any additional information that may be helpful.
60 |
61 | After filing a report, a representative of our community will contact you personally, review the incident, follow up with any additional questions, and make a decision as to how to respond. If the person who is harassing you is part of the response team, they will recuse themselves from handling your incident. If the complaint originates from a member of the response team, it will be handled by a different member of the response team. We will respect confidentiality requests for the purpose of protecting victims of abuse.
62 |
63 | ### Removal of Posts
64 | We will not review every comment or post, but we reserve the right to remove any that violates these Guidelines or that, in our sole discretion, we otherwise consider objectionable and we may ban offenders from our community.
65 |
66 | ### Suspension/Termination/Reporting to Authority
67 | In certain instances, we may suspend, terminate or ban certain repeat offenders and/or those committing significant violations of these Guidelines. When appropriate, we may also, on our own or as required by the GitHub terms of use, be required to refer and/or work with GitHub and/or the appropriate authorities to review and/or pursue certain violations.
68 |
69 | ### Attribution & Acknowledgements
70 | These Guidelines have been adapted from the [Code of Conduct of the TODO group](http://todogroup.org/opencodeofconduct/). They are subject to revision by American Express and may be revised from time to time.
71 |
72 | Thank you for your participation!
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | The following guidelines must be followed by all contributors to this repository. Please review them carefully and do not hesitate to ask for help.
4 |
5 | ### Code of Conduct
6 |
7 | * Review and test your code before submitting a pull request.
8 | * Be kind and professional. Avoid assumptions; oversights happen.
9 | * Be clear and concise when documenting code; focus on value.
10 | * Don't commit commented code to the main repo (stash locally, if needed).
11 |
12 | ### Git Commit Guidelines
13 |
14 | We follow precise rules for git commit message formatting. These rules make it easier to review commit logs and improve contextual understanding of code changes. This also allows us to auto-generate the CHANGELOG from commit messages.
15 |
16 | Each commit message consists of a **header**, **body** and **footer**.
17 |
18 | #### Header
19 |
20 | The header is required and must not exceed 70 characters to ensure it is well-formatted in common git tools. It has a special format that includes a *type*, *scope* and *subject*:
21 |
22 | Syntax:
23 |
24 | ```bash
25 | ():
26 | ```
27 |
28 | #### Type
29 |
30 | The *type* should always be lowercase as shown below.
31 |
32 | ##### Allowed `` values:
33 |
34 | * **feat** (new feature for the user)
35 | * **fix** (bug fix for the user, not a fix to build scripts)
36 | * **docs** (changes to documentation)
37 | * **style** (formatting, missing semi colons, etc; no functional code change)
38 | * **refactor** (refactoring production code, eg. renaming a variable)
39 | * **test** (adding missing tests, refactoring tests; no production code change)
40 | * **chore** (updating build/env/packages, etc; no production code change)
41 |
42 | #### Scope
43 |
44 | The *scope* describes the affected code. The descriptor may be a route, component, feature, utility, etc. It should be one word or camelCased, if needed:
45 |
46 | ```bash
47 | feat(transactions): added column for quantity
48 | feat(BalanceModule): initial setup
49 | ```
50 |
51 | The commit headers above work well if the commit affects many parts of a larger feature. If changes are more specific, it may be too broad. To better clarify specific scopes, you should use a `feature/scope` syntax:
52 |
53 | ```bash
54 | fix(transaction/details): missing quantity field
55 | ```
56 |
57 | The above syntax helps reduce verbosity in the _subject_. In comparison, consider the following example:
58 |
59 | ```bash
60 | fix(transaction): missing quantity field in txn details
61 | ```
62 |
63 | Another scenario for scope is using a `route/scope` (or `context/scope`) syntax. This would be useful when a commit only affects a particular instance of code that is used in multiple places.
64 |
65 | *Example*: Transactions may be shown in multiple routes/contexts, but a bug affecting transaction actions may only exist under the "home" route, possibly related to other code. In such cases, you could use the following format:
66 |
67 | ```bash
68 | fix(home/transactions): txn actions not working
69 | ```
70 |
71 | This header makes it clear that the fix is limited in scope to transactions within the home route/context.
72 |
73 | #### Subject
74 |
75 | Short summary of the commit. Avoid redundancy and simplify wording in ways that do not compromise understanding.
76 |
77 | Good:
78 |
79 | ```bash
80 | $ git commit -m "fix(nav/link): incorrect URL for Travel"
81 | ```
82 |
83 | Bad:
84 |
85 | ```bash
86 | $ git commit -m "fix(nav): incorrect URL for Travel nav item :P"
87 | ```
88 |
89 | > Note that the _Bad_ example results in a longer commit header. This is partly attributed to the scope not being more specific and personal expression tacked on the end.
90 |
91 | **Note regarding subjects for bug fixes:**
92 |
93 | Summarize _what is fixed_, rather than stating that it _is_ fixed. The _type_ ("fix") already specifies the state of the issue.
94 |
95 | For example, don't do:
96 |
97 | ```bash
98 | $ git commit -m "fix(nav): corrected Travel URL"
99 | ```
100 |
101 | Instead, do:
102 |
103 | ```bash
104 | $ git commit -m "fix(nav): broken URL for Travel"
105 | ```
106 |
107 |
108 | #### Body and Footer (optional)
109 |
110 | The body and footer should wrap at 80 characters.
111 |
112 | The **body** describes the commit in more detail and should not be more than 1 paragraph (3-5 sentences). Details are important, but too much verbosity can inhibit understanding and productivity -- keep it clear and concise.
113 |
114 | The **footer** should only reference Pull Requests or Issues associated with the commit.
115 |
116 | For bug fixes that address open issues, the footer should be formatted like so:
117 |
118 | ```bash
119 | Closes #17, #26
120 | ```
121 | and for Pull Requests, use the format:
122 |
123 | ```bash
124 | Related #37
125 | ```
126 |
127 | If a commit is associated with issues and pull requests, use the following format:
128 |
129 | ```bash
130 | Closes #17, #26
131 | Related #37
132 | ```
133 | > Issues should always be referenced before pull requests, as shown above.
134 |
135 | #### Piecing It All Together
136 |
137 | Below is an example of a full commit message that includes a header, body and footer:
138 |
139 | ```bash
140 | refactor(nav/item): added prop (isActive)
141 |
142 | NavItem now supports an "isActive" property. This property is used to control the styling of active navigation links.
143 |
144 | Closes #21
145 | ```
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 | Apache License
4 | Version 2.0, January 2004
5 | http://www.apache.org/licenses/
6 |
7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 |
9 | 1. Definitions.
10 |
11 | "License" shall mean the terms and conditions for use, reproduction,
12 | and distribution as defined by Sections 1 through 9 of this document.
13 |
14 | "Licensor" shall mean the copyright owner or entity authorized by
15 | the copyright owner that is granting the License.
16 |
17 | "Legal Entity" shall mean the union of the acting entity and all
18 | other entities that control, are controlled by, or are under common
19 | control with that entity. For the purposes of this definition,
20 | "control" means (i) the power, direct or indirect, to cause the
21 | direction or management of such entity, whether by contract or
22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
23 | outstanding shares, or (iii) beneficial ownership of such entity.
24 |
25 | "You" (or "Your") shall mean an individual or Legal Entity
26 | exercising permissions granted by this License.
27 |
28 | "Source" form shall mean the preferred form for making modifications,
29 | including but not limited to software source code, documentation
30 | source, and configuration files.
31 |
32 | "Object" form shall mean any form resulting from mechanical
33 | transformation or translation of a Source form, including but
34 | not limited to compiled object code, generated documentation,
35 | and conversions to other media types.
36 |
37 | "Work" shall mean the work of authorship, whether in Source or
38 | Object form, made available under the License, as indicated by a
39 | copyright notice that is included in or attached to the work
40 | (an example is provided in the Appendix below).
41 |
42 | "Derivative Works" shall mean any work, whether in Source or Object
43 | form, that is based on (or derived from) the Work and for which the
44 | editorial revisions, annotations, elaborations, or other modifications
45 | represent, as a whole, an original work of authorship. For the purposes
46 | of this License, Derivative Works shall not include works that remain
47 | separable from, or merely link (or bind by name) to the interfaces of,
48 | the Work and Derivative Works thereof.
49 |
50 | "Contribution" shall mean any work of authorship, including
51 | the original version of the Work and any modifications or additions
52 | to that Work or Derivative Works thereof, that is intentionally
53 | submitted to Licensor for inclusion in the Work by the copyright owner
54 | or by an individual or Legal Entity authorized to submit on behalf of
55 | the copyright owner. For the purposes of this definition, "submitted"
56 | means any form of electronic, verbal, or written communication sent
57 | to the Licensor or its representatives, including but not limited to
58 | communication on electronic mailing lists, source code control systems,
59 | and issue tracking systems that are managed by, or on behalf of, the
60 | Licensor for the purpose of discussing and improving the Work, but
61 | excluding communication that is conspicuously marked or otherwise
62 | designated in writing by the copyright owner as "Not a Contribution."
63 |
64 | "Contributor" shall mean Licensor and any individual or Legal Entity
65 | on behalf of whom a Contribution has been received by Licensor and
66 | subsequently incorporated within the Work.
67 |
68 | 2. Grant of Copyright License. Subject to the terms and conditions of
69 | this License, each Contributor hereby grants to You a perpetual,
70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71 | copyright license to reproduce, prepare Derivative Works of,
72 | publicly display, publicly perform, sublicense, and distribute the
73 | Work and such Derivative Works in Source or Object form.
74 |
75 | 3. Grant of Patent License. Subject to the terms and conditions of
76 | this License, each Contributor hereby grants to You a perpetual,
77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78 | (except as stated in this section) patent license to make, have made,
79 | use, offer to sell, sell, import, and otherwise transfer the Work,
80 | where such license applies only to those patent claims licensable
81 | by such Contributor that are necessarily infringed by their
82 | Contribution(s) alone or by combination of their Contribution(s)
83 | with the Work to which such Contribution(s) was submitted. If You
84 | institute patent litigation against any entity (including a
85 | cross-claim or counterclaim in a lawsuit) alleging that the Work
86 | or a Contribution incorporated within the Work constitutes direct
87 | or contributory patent infringement, then any patent licenses
88 | granted to You under this License for that Work shall terminate
89 | as of the date such litigation is filed.
90 |
91 | 4. Redistribution. You may reproduce and distribute copies of the
92 | Work or Derivative Works thereof in any medium, with or without
93 | modifications, and in Source or Object form, provided that You
94 | meet the following conditions:
95 |
96 | (a) You must give any other recipients of the Work or
97 | Derivative Works a copy of this License; and
98 |
99 | (b) You must cause any modified files to carry prominent notices
100 | stating that You changed the files; and
101 |
102 | (c) You must retain, in the Source form of any Derivative Works
103 | that You distribute, all copyright, patent, trademark, and
104 | attribution notices from the Source form of the Work,
105 | excluding those notices that do not pertain to any part of
106 | the Derivative Works; and
107 |
108 | (d) If the Work includes a "NOTICE" text file as part of its
109 | distribution, then any Derivative Works that You distribute must
110 | include a readable copy of the attribution notices contained
111 | within such NOTICE file, excluding those notices that do not
112 | pertain to any part of the Derivative Works, in at least one
113 | of the following places: within a NOTICE text file distributed
114 | as part of the Derivative Works; within the Source form or
115 | documentation, if provided along with the Derivative Works; or,
116 | within a display generated by the Derivative Works, if and
117 | wherever such third-party notices normally appear. The contents
118 | of the NOTICE file are for informational purposes only and
119 | do not modify the License. You may add Your own attribution
120 | notices within Derivative Works that You distribute, alongside
121 | or as an addendum to the NOTICE text from the Work, provided
122 | that such additional attribution notices cannot be construed
123 | as modifying the License.
124 |
125 | You may add Your own copyright statement to Your modifications and
126 | may provide additional or different license terms and conditions
127 | for use, reproduction, or distribution of Your modifications, or
128 | for any such Derivative Works as a whole, provided Your use,
129 | reproduction, and distribution of the Work otherwise complies with
130 | the conditions stated in this License.
131 |
132 | 5. Submission of Contributions. Unless You explicitly state otherwise,
133 | any Contribution intentionally submitted for inclusion in the Work
134 | by You to the Licensor shall be under the terms and conditions of
135 | this License, without any additional terms or conditions.
136 | Notwithstanding the above, nothing herein shall supersede or modify
137 | the terms of any separate license agreement you may have executed
138 | with Licensor regarding such Contributions.
139 |
140 | 6. Trademarks. This License does not grant permission to use the trade
141 | names, trademarks, service marks, or product names of the Licensor,
142 | except as required for reasonable and customary use in describing the
143 | origin of the Work and reproducing the content of the NOTICE file.
144 |
145 | 7. Disclaimer of Warranty. Unless required by applicable law or
146 | agreed to in writing, Licensor provides the Work (and each
147 | Contributor provides its Contributions) on an "AS IS" BASIS,
148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149 | implied, including, without limitation, any warranties or conditions
150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151 | PARTICULAR PURPOSE. You are solely responsible for determining the
152 | appropriateness of using or redistributing the Work and assume any
153 | risks associated with Your exercise of permissions under this License.
154 |
155 | 8. Limitation of Liability. In no event and under no legal theory,
156 | whether in tort (including negligence), contract, or otherwise,
157 | unless required by applicable law (such as deliberate and grossly
158 | negligent acts) or agreed to in writing, shall any Contributor be
159 | liable to You for damages, including any direct, indirect, special,
160 | incidental, or consequential damages of any character arising as a
161 | result of this License or out of the use or inability to use the
162 | Work (including but not limited to damages for loss of goodwill,
163 | work stoppage, computer failure or malfunction, or any and all
164 | other commercial damages or losses), even if such Contributor
165 | has been advised of the possibility of such damages.
166 |
167 | 9. Accepting Warranty or Additional Liability. While redistributing
168 | the Work or Derivative Works thereof, You may choose to offer,
169 | and charge a fee for, acceptance of support, warranty, indemnity,
170 | or other liability obligations and/or rights consistent with this
171 | License. However, in accepting such obligations, You may act only
172 | on Your own behalf and on Your sole responsibility, not on behalf
173 | of any other Contributor, and only if You agree to indemnify,
174 | defend, and hold each Contributor harmless for any liability
175 | incurred by, or claims asserted against, such Contributor by reason
176 | of your accepting any such warranty or additional liability.
177 |
178 | END OF TERMS AND CONDITIONS
179 |
180 | APPENDIX: How to apply the Apache License to your work.
181 |
182 | To apply the Apache License to your work, attach the following
183 | boilerplate notice, with the fields enclosed by brackets "[]"
184 | replaced with your own identifying information. (Don't include
185 | the brackets!) The text should be enclosed in the appropriate
186 | comment syntax for the file format. We also recommend that a
187 | file or class name and description of purpose be included on the
188 | same "printed page" as the copyright notice for easier
189 | identification within third-party archives.
190 |
191 | Copyright 2019 American Express Travel Related Services Company, Inc.
192 |
193 | Licensed under the Apache License, Version 2.0 (the "License");
194 | you may not use this file except in compliance with the License.
195 | You may obtain a copy of the License at
196 |
197 | http://www.apache.org/licenses/LICENSE-2.0
198 |
199 | Unless required by applicable law or agreed to in writing, software
200 | distributed under the License is distributed on an "AS IS" BASIS,
201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 | See the License for the specific language governing permissions and
203 | limitations under the License.
204 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-conditional-flow
2 |
3 | Component(s) intended to simplify react conditional rendering
4 |
5 |
6 |
7 | ## Components:
8 |
9 |
14 |
15 |
16 |
17 | ## `ElseIf`
18 |
19 | ## How to use
20 |
21 | | Prop | Type | Required/Default | Description |
22 | | ---------- | --------- | ---------------- | ------------------------------------------------------------------------------------------------------- |
23 | | if | `boolean` | `no` / `false` | determines if prop `render` should be rendered |
24 | | render | `element` | `no` / `null` | JSX element to be rendered should `if` be true |
25 | | conditions | `array` | `no` / `[]` | Array of objects: `{if: boolean, render: element}` used to determine `if/else if` conditional rendering |
26 | | else | `element` | `no` / `null` | JSX element to be rendered should no provided condition be met |
27 |
28 | There are two ways of using the `ElseIf`. Either for a single `if` with an optional `else`:
29 |
30 | Example 1
31 |
32 | ```js
33 | import { ElseIf } from 'react-conditional-flow';
34 |
35 | Blue Skys and Sunshine!
} /> // else case is null by default
36 |
37 | // or with an else
38 | Blue Skys and Sunshine!} // What to render should `if` be true
41 | else={The Sky isnt blue!?
} // what to render should `if` be false
42 | />
43 | ```
44 |
45 | Or with an array of conditions (array of objects with the shape `{ if: bool, render: element }`).
46 |
47 | The first `if` property inside the conditions array is used to determine which `render` should be used, all other renders are ignored.
48 |
49 | Example 2
50 |
51 | ```js
52 | import { ElseIf } from 'react-conditional-flow';
53 |
54 | const myConditions = [
55 | { if: false, render: {one}
}, // skipped because `if` is false
56 | { if: true, render: {two}
}, // This render is used because `if` was true
57 | { if: true, render: {three}
} // This condition it's checked because there was already an `if` that was true at an earlier index
58 | ];
59 |
60 | ;
61 |
62 | // an else can still be provided in an array of conditions
63 |
64 | const myConditions = [
65 | { if: false, render: {one}
}, // skipped because `if` is false
66 | { if: false, render: {two}
}, // skipped because `if` is false
67 | { if: false, render: {three}
} // skipped because `if` is false
68 | ];
69 |
70 | Nothing to see here!} />; // else will render as no conditions were met
71 | ```
72 |
73 | Back to Top
74 |
75 |
76 |
77 | ## `Switch, Case, Default`
78 |
79 | As an alternative to using the `ElseIf` Component, you can use a combindation of `Switch`, `Case`, and `Default` components to mimick the the
80 | JS `switch()` conditional shape except in form of JSX.
81 |
82 | The `Switch` Component compares it's `on` property with it's `Case` children's `value` prop. The first matching result is rendered, ignoring all other `Case`(s).
83 |
84 | ## How to use
85 |
86 | ## Switch
87 |
88 | | Prop | Type | Required | Description |
89 | | -------- | ---------------- | -------- | --------------------------------------------------------------------------------------------------------- |
90 | | on | `any` | `yes` | variable to be compared to render child `Case` Component |
91 | | children | `Case Component` | `yes` | Component to be rendered when a match is found between `Case`'s `value` prop and the `Switch`'s `on` prop |
92 |
93 | ---
94 |
95 | ## Case
96 |
97 | | Prop | Type | Required | Description |
98 | | -------- | ------------------------ | -------- | ---------------------------------------------------------------------------------- |
99 | | value | `any` | `yes` | determines if children should be rendered based on match with `Switch`'s `on` prop |
100 | | children | `element` or `[element]` | `yes` | elements to be rendered |
101 |
102 | ---
103 |
104 | ## Default (optional)
105 |
106 | | Prop | Type | Required | Description |
107 | | -------- | ------------------------ | -------- | ----------------------- |
108 | | children | `element` or `[element]` | `yes` | elements to be rendered |
109 |
110 | ---
111 |
112 | Example 1
113 |
114 | ```js
115 | import { Switch, Case, Default } from 'react-conditional-flow';
116 |
117 | let switcher = 'red';
118 |
119 |
120 | {/* This Case will render as the value matches the Switch's {on} prop */}
121 |
122 | Rendering the red case
123 |
124 |
125 | Rendering the blue case
126 |
127 | ;
128 |
129 | // A Default Component is optional with a Switch block, if no Default is provided and
130 | // no Case(s) match then the Switch will render null
131 |
132 | switcher = 'green';
133 |
134 |
135 |
136 | Rendering the red case
137 |
138 |
139 | Rendering the blue case
140 |
141 |
142 | {/* The Default will render as no value matches the Switch's {on} prop */}
143 | Im what renders by default!
144 |
145 | ;
146 |
147 | // Case(s) can be given an array of values as well which will all be taken into account when searching for a match in the Switch
148 |
149 | switcher = 'yellow';
150 |
151 |
152 |
153 | Rendering the red case
154 |
155 |
156 | {/* This Case will render as one of the values match the Switch's {on} prop */}
157 | Rendering the green, yellow and blue case
158 |
159 |
160 | {/* fun fact! This will never render as blue is already apart of a previous Case */}
161 | Rendering the blue case
162 |
163 |
164 | Im what renders by default!
165 |
166 | ;
167 | ```
168 |
169 | Back to Top
170 |
171 |
172 |
173 | ## `TryCatch`
174 |
175 | ## How to use
176 |
177 | | Prop | Type | Required/Default | Description |
178 | | ----- | ------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------ |
179 | | try | `func` | `yes` / no default | function that returns a Component/JSX |
180 | | catch | `func` | `no` / `throw Error` | callback which is provided `(error, info)` as arguments to either render custom error handling or return a Component/JSX |
181 |
182 | `TryCatch` is intended to reduce boiler plate with handling errors that occur with rendering.
183 |
184 | Example 1
185 |
186 | ```js
187 | import { TryCatch } from 'react-conditional-flow';
188 |
189 | const renderComponentWithAPICallFailure = () => ;
190 |
191 | (
194 |
195 | An error has occurred! {error}
196 |
197 | )}
198 | />;
199 |
200 | // or without a catch. This will result in an error being thrown by the TryCatch component.
201 | // It's best to provide a custom catch so you can do whatever specific logic you need to should something unexpected happen
202 | ;
203 | ```
204 |
205 | Back to Top
206 |
207 | ## Contributing
208 |
209 | We welcome Your interest in the American Express Open Source Community on Github. Any Contributor to
210 | any Open Source Project managed by the American Express Open Source Community must accept and sign
211 | an Agreement indicating agreement to the terms below. Except for the rights granted in this
212 | Agreement to American Express and to recipients of software distributed by American Express, You
213 | reserve all right, title, and interest, if any, in and to Your Contributions. Please
214 | [fill out the Agreement](https://cla-assistant.io/americanexpress/react-conditional-flow).
215 |
216 | ## License
217 |
218 | Any contributions made under this project will be governed by the
219 | [Apache License 2.0](./LICENSE.txt).
220 |
221 | ## Code of Conduct
222 |
223 | This project adheres to the [American Express Community Guidelines](./CODE_OF_CONDUCT.md). By
224 | participating, you are expected to honor these guidelines.
--------------------------------------------------------------------------------
/__tests__/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "amex/test"
3 | }
4 |
--------------------------------------------------------------------------------
/__tests__/components/Case.spec.jsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-undef, react/jsx-one-expression-per-line */
2 |
3 | /*
4 | * Copyright 2019 American Express Travel Related Services Company, Inc.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7 | * in compliance with the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software distributed under the License
12 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13 | * or implied. See the License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 |
17 | import React from 'react';
18 | import { shallow } from 'enzyme';
19 | import Case from '../../src/components/Case';
20 |
21 | const childText = 'Im component One!';
22 |
23 | const defaultProps = {};
24 |
25 | const renderComp = props => shallow(
26 |
27 | {childText}
28 |
29 | );
30 |
31 | describe('Case', () => {
32 | it('successfully renders when no error is thrown', () => {
33 | const component = renderComp();
34 | expect(component.text()).toEqual(childText);
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/__tests__/components/Default.spec.jsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-undef, react/jsx-one-expression-per-line */
2 |
3 | /*
4 | * Copyright 2019 American Express Travel Related Services Company, Inc.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7 | * in compliance with the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software distributed under the License
12 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13 | * or implied. See the License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 |
17 | import React from 'react';
18 | import { shallow } from 'enzyme';
19 | import Default from '../../src/components/Default';
20 |
21 | const childText = 'Im component One!';
22 |
23 | const defaultProps = {};
24 |
25 | const renderComp = props => shallow(
26 |
27 | {childText}
28 |
29 | );
30 |
31 | describe('Default', () => {
32 | it('successfully renders when no error is thrown', () => {
33 | const component = renderComp();
34 | expect(component.text()).toEqual(childText);
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/__tests__/components/ElseIf.spec.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { shallow } from 'enzyme';
17 | import EliseIf from '../../src/components/ElseIf';
18 |
19 | const one = 'Im component One!';
20 | const two = 'Hello from two';
21 | const three = 'Hello from three';
22 |
23 | const condArr = (bOne, bTwo, bThree) => [
24 | { if: bOne, render: {one}
},
25 | { if: bTwo, render: {two}
},
26 | { if: bThree, render: {three}
},
27 | ];
28 |
29 | const defaultProps = {};
30 |
31 | const renderComp = props => shallow();
32 |
33 | describe('EliseIf', () => {
34 | it('last condition should render', () => {
35 | const conditions = condArr(false, false, true);
36 | const component = renderComp({ conditions });
37 | expect(component.text()).toEqual(three);
38 | });
39 |
40 | it('second condition should render', () => {
41 | const conditions = condArr(false, true, true);
42 | const component = renderComp({ conditions });
43 | expect(component.text()).toEqual(two);
44 | });
45 |
46 | it('first condition should render', () => {
47 | const conditions = condArr(true, true, true);
48 | const component = renderComp({ conditions });
49 | expect(component.text()).toEqual(one);
50 | });
51 |
52 | it('fallback should render when all cases are false', () => {
53 | const conditions = condArr(false, false, false);
54 | const component = renderComp({ conditions });
55 | expect(component.text()).toEqual('');
56 | });
57 |
58 | it('fallback should render', () => {
59 | const component = renderComp({ conditions: [], else: Fallback rendered
});
60 | expect(component.text()).toEqual('Fallback rendered');
61 | });
62 |
63 | it('null should render', () => {
64 | const component = renderComp({ conditions: [] });
65 | expect(component.text()).toEqual('');
66 | });
67 |
68 | it('handles single if case', () => {
69 | const component = renderComp({ if: true, render: {one}
});
70 | expect(component.text()).toEqual(one);
71 | });
72 | });
73 |
--------------------------------------------------------------------------------
/__tests__/components/Switch.spec.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { shallow } from 'enzyme';
17 | import Switch from '../../src/components/Switch';
18 | import Case from '../../src/components/Case';
19 |
20 | const childTextOne = 'Im component One!';
21 | const childTextTwo = 'Im component Two!';
22 | const childTextThree = 'Im component Three!';
23 | const childTextFourFiveSix = 'Im component for Four Five and Six!';
24 |
25 | const defaultProps = {};
26 |
27 | const childOne = {childTextOne};
28 | const childTwo = {childTextTwo};
29 | const childThree = {childTextThree};
30 | const childFourFiveSix = {childTextFourFiveSix};
31 | const childEdgeCase = Im a div and Ive come to ruin your component!
;
32 |
33 | const renderChildlessComp = props => shallow();
34 |
35 | const renderCompSingleChild = props => shallow(
36 |
37 | {childOne}
38 |
39 | );
40 | const renderComp = props => shallow(
41 |
42 | {childOne}
43 | {childTwo}
44 | {childThree}
45 | {childFourFiveSix}
46 |
47 | );
48 |
49 | const renderCompWithEdgeCase = props => shallow(
50 |
51 | {childOne}
52 | {childTwo}
53 | {childThree}
54 | {childEdgeCase}
55 |
56 | );
57 |
58 | describe('Switch', () => {
59 | it('match and return only first child', () => {
60 | const component = renderComp({ on: 'one' });
61 | expect(component.children().length).toEqual(1);
62 | expect(component.children().text()).toEqual(childTextOne);
63 | });
64 | it('match and return only second child', () => {
65 | const component = renderComp({ on: 'two' });
66 | expect(component.children().length).toEqual(1);
67 | expect(component.children().text()).toEqual(childTextTwo);
68 | });
69 | it('match and return only third child', () => {
70 | const component = renderComp({ on: 'three' });
71 | expect(component.children().length).toEqual(1);
72 | expect(component.children().text()).toEqual(childTextThree);
73 | });
74 | it('matches on an array of values', () => {
75 | const componentValueFour = renderComp({ on: 'four' });
76 | expect(componentValueFour.children().length).toEqual(1);
77 | expect(componentValueFour.children().text()).toEqual(childTextFourFiveSix);
78 |
79 | const componentValueFive = renderComp({ on: 'five' });
80 | expect(componentValueFive.children().length).toEqual(1);
81 | expect(componentValueFive.children().text()).toEqual(childTextFourFiveSix);
82 |
83 | const componentValueSix = renderComp({ on: 'six' });
84 | expect(componentValueSix.children().length).toEqual(1);
85 | expect(componentValueSix.children().text()).toEqual(childTextFourFiveSix);
86 | });
87 | it('functions normally when give a single child', () => {
88 | const componentOne = renderCompSingleChild({ on: 'one' });
89 | expect(componentOne.children().length).toEqual(1);
90 | expect(componentOne.children().text()).toEqual(childTextOne);
91 |
92 | const componentTwo = renderCompSingleChild({ on: 'two' });
93 | expect(componentTwo.children().length).toEqual(0);
94 | expect(componentTwo.instance()).toBe(null);
95 | });
96 | it('return null when no matches', () => {
97 | const instance = renderComp({ on: 'five' }).instance();
98 | expect(instance).toBe(null);
99 | });
100 | });
101 |
102 | describe('Switch Exceptions', () => {
103 | it('throws error when Case is not immediate child', () => {
104 | expect(renderCompWithEdgeCase).toThrowError(
105 | ` must only contain children. Please wrap <${
106 | childEdgeCase.type
107 | }/> in a `
108 | );
109 | });
110 |
111 | it('throws error when no children proivded to Switch', () => {
112 | expect(renderChildlessComp).toThrowError(
113 | ' requires at least one child component'
114 | );
115 | });
116 | });
117 |
--------------------------------------------------------------------------------
/__tests__/components/TryCatch.spec.jsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-undef, react/jsx-one-expression-per-line */
2 |
3 | /*
4 | * Copyright 2019 American Express Travel Related Services Company, Inc.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7 | * in compliance with the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software distributed under the License
12 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13 | * or implied. See the License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 |
17 | import React from 'react';
18 | import { shallow } from 'enzyme';
19 | import TryCatch from '../../src/components/TryCatch';
20 |
21 | const one = () => 'Im component One!';
22 | const two = () => `Hello from two${bob}`;
23 | const three = lasagna => `Hello from three${lasagna()}`;
24 |
25 | const defaultProps = {};
26 |
27 | const renderComp = props => shallow();
28 |
29 | describe('TryCatch', () => {
30 | it('successfully renders when no error is thrown', () => {
31 | const component = renderComp({ try: one });
32 | expect(component.text()).toEqual(one());
33 | });
34 |
35 | it('renders default catch when error is caught', () => {
36 | try {
37 | renderComp({ try: two });
38 | } catch (e) {
39 | expect(e).toEqual(new Error('ReferenceError: bob is not defined'));
40 | }
41 | });
42 |
43 | it('renders custom catch when error is caught', () => {
44 | const catcher = e => I got the error: {e.message};
45 | const component = renderComp({ try: three, catch: catcher });
46 | expect(component.text()).toEqual('I got the error: lasagna is not a function');
47 | });
48 | });
49 |
--------------------------------------------------------------------------------
/__tests__/index.spec.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import ElseIf from '../src/components/ElseIf';
16 | import TryCatch from '../src/components/TryCatch';
17 | import Switch from '../src/components/Switch';
18 | import Case from '../src/components/Case';
19 | import Default from '../src/components/Default';
20 | import ModuleContainer from '../src';
21 |
22 | describe('index', () => {
23 | it('Should export ElseIf', () => {
24 | expect(ModuleContainer.ElseIf).toEqual(ElseIf);
25 | });
26 | it('Should export TryCatch', () => {
27 | expect(ModuleContainer.TryCatch).toEqual(TryCatch);
28 | });
29 | it('Should export Switch', () => {
30 | expect(ModuleContainer.Switch).toEqual(Switch);
31 | });
32 | it('Should export Case', () => {
33 | expect(ModuleContainer.Case).toEqual(Case);
34 | });
35 | it('Should export Default', () => {
36 | expect(ModuleContainer.Default).toEqual(Default);
37 | });
38 | });
39 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | module.exports = {
16 | extends: ['@commitlint/config-conventional'],
17 | };
18 |
--------------------------------------------------------------------------------
/examples/if-condition/ReactIf.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { ElseIf } from './../../src/components/ElseIf';
17 |
18 | const boolCheck = !0;
19 |
20 | const ReactIf = () => (
21 |
25 | Hello Conditional Flow
26 |
27 | }
28 | />
29 | );
30 |
--------------------------------------------------------------------------------
/examples/if-else-condition/ReactIfElse.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { ElseIf } from 'react-conditional-flow';
17 |
18 | const boolCheck = !0;
19 |
20 | const ReactIfElse = () => (
21 |
25 | Hello If Conditional render
26 |
27 | )}
28 | else={(
29 |
30 | Hello Else conditional render
31 |
32 | )}
33 | />
34 | );
35 |
--------------------------------------------------------------------------------
/examples/if-else-condition/ReactNestedIfElse.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { ElseIf } from 'react-conditional-flow';
17 |
18 | const boolCheck = !0;
19 |
20 | const ReactNestedIfElse = () => (
21 | Hello if check 1,
27 | },
28 | {
29 | if: !boolCheck,
30 | render: (
31 |
32 |
hello paragrapsh for if check 2
33 |
Deep if } />
34 |
35 | ),
36 | },
37 | ]
38 | }
39 | else={default flow
}
40 | />
41 | );
42 |
--------------------------------------------------------------------------------
/examples/switch-case/SwitchCase.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { Switch, Case, Default } from 'react-conditional-flow';
17 |
18 | const expressionString = 'mangoes';
19 |
20 | const SwitchCase = () => (
21 |
22 |
23 | Hello Papayas
24 |
25 |
26 | Hello Mangoes
27 |
28 |
29 | Hello Oranges
30 |
31 |
32 | Default
33 |
34 |
35 | );
36 |
--------------------------------------------------------------------------------
/examples/try-catch/ReactTryCatch.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import React from 'react';
16 | import { TryCatch } from 'react-conditional-flow';
17 |
18 | const ReactTryCatch = () => (
19 | try block
22 | }
23 | catch={
24 | () => catch block
25 | }
26 | />
27 | );
28 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-conditional-flow",
3 | "version": "1.0.3",
4 | "files": [
5 | "lib"
6 | ],
7 | "main": "lib",
8 | "description": "Dependency which provides react components on top of control flow operations like if, if-else, if-else-if, switch-case, & try-catch.",
9 | "contributors": [
10 | "Arivu Arumugam ",
11 | "Prasath Pandiyan ",
12 | "Emit Dutcher "
13 | ],
14 | "author": "Emit Dutcher ",
15 | "license": "Apache-2.0",
16 | "keywords": [
17 | "control-flow",
18 | "conditional-flow",
19 | "react",
20 | "react-control-flow",
21 | "react-conditional-flow"
22 | ],
23 | "scripts": {
24 | "build": "babel src -d lib --copy-files",
25 | "clean": "rimraf lib",
26 | "lint": "eslint --ignore-path .eslintignore --ext js,jsx,snap .",
27 | "posttest": "npm run lint",
28 | "test": "jest",
29 | "prepare": "npm run build",
30 | "githook:pre-commit": "npm run test",
31 | "githook:commit-msg": "commitlint --edit $GIT_PARAMS"
32 | },
33 | "jest": {
34 | "preset": "amex-jest-preset-react"
35 | },
36 | "dependencies": {
37 | "prop-types": "^15.5.9",
38 | "react": "^16.4.2"
39 | },
40 | "devDependencies": {
41 | "@commitlint/cli": "^7.6.1",
42 | "@commitlint/config-conventional": "^8.1.0",
43 | "amex-jest-preset-react": "^5.0.0",
44 | "babel-cli": "^6.26.0",
45 | "babel-core": "^6.26.3",
46 | "babel-preset-amex": "^1.1.0",
47 | "enzyme": "^3.3.0",
48 | "enzyme-to-json": "^3.3.0",
49 | "eslint": "^5.0.0",
50 | "eslint-config-amex": "^10.0.0",
51 | "githook-scripts": "^1.0.1",
52 | "jest": "^23.0.0",
53 | "react-dom": "^16.4.2",
54 | "react-test-renderer": "^16.2.0",
55 | "rimraf": "^3.0.0"
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/components/Case.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | const Case = ({ children }) => children;
16 |
17 | export default Case;
18 |
--------------------------------------------------------------------------------
/src/components/Default.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | const Default = ({ children }) => children;
16 |
17 | export default Default;
18 |
--------------------------------------------------------------------------------
/src/components/ElseIf.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import {
16 | arrayOf, shape, bool, element,
17 | } from 'prop-types';
18 |
19 | const ElseIf = ({
20 | if: singleCondition, render: singleRender, conditions, else: fallback,
21 | }) => {
22 | let render;
23 | if (singleCondition) {
24 | render = singleRender;
25 | }
26 | if (!singleCondition && conditions.length > 0) {
27 | ({ render } = conditions.find(o => o.if) || { render: null });
28 | }
29 |
30 | return render || fallback;
31 | };
32 |
33 | ElseIf.propTypes = {
34 | if: bool,
35 | render: element,
36 | conditions: arrayOf(shape({ if: bool.isRequired, render: element.isRequired })),
37 | else: element,
38 | };
39 |
40 | ElseIf.defaultProps = {
41 | if: false,
42 | render: null,
43 | conditions: [],
44 | else: null,
45 | };
46 |
47 | export default ElseIf;
48 |
--------------------------------------------------------------------------------
/src/components/Switch.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | const Switch = ({ on, children }) => {
16 | if (!children) {
17 | throw new Error(' requires at least one child component');
18 | }
19 |
20 | const arrChildren = Array.isArray(children) ? children : [children];
21 | const badChild = arrChildren.find(child => !['Case', 'Default'].includes(child.type.name));
22 |
23 | if (badChild) {
24 | throw new Error(
25 | ` must only contain children. Please wrap <${badChild.type}/> in a `
26 | );
27 | }
28 |
29 | const firstMatch = arrChildren.find((child) => {
30 | const { value } = child.props;
31 | if (Array.isArray(value)) return value.includes(on);
32 | return value === on;
33 | });
34 | if (firstMatch) return firstMatch;
35 |
36 | const defaultComp = arrChildren.find(child => child.type.name === 'Default');
37 | return defaultComp || null;
38 | };
39 |
40 | export default Switch;
41 |
--------------------------------------------------------------------------------
/src/components/TryCatch.jsx:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import { func } from 'prop-types';
16 |
17 | const TryCatch = ({ try: render, catch: fallBack }) => {
18 | try {
19 | return render();
20 | } catch (e) {
21 | return fallBack(e);
22 | }
23 | };
24 |
25 | TryCatch.propTypes = {
26 | try: func,
27 | catch: func,
28 | };
29 |
30 | TryCatch.defaultProps = {
31 | try: null,
32 | catch: (e) => {
33 | throw new Error(e);
34 | },
35 | };
36 |
37 | export default TryCatch;
38 |
--------------------------------------------------------------------------------
/src/components/TryCatchFinally.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import { func } from 'prop-types';
16 |
17 | const TryCatchFinally = ({ try: renderTry, catch: fallBack, finally: renderFinally }) => {
18 | try {
19 | return renderTry();
20 | } catch (e) {
21 | return fallBack(e);
22 | } finally {
23 | renderFinally();
24 | }
25 | };
26 |
27 | TryCatchFinally.propTypes = {
28 | try: func,
29 | catch: func,
30 | finally: func,
31 | };
32 |
33 | TryCatchFinally.defaultProps = {
34 | try: null,
35 | catch: (e) => {
36 | throw new Error(e);
37 | },
38 | finally: null,
39 | };
40 |
41 | export default TryCatchFinally;
42 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 American Express Travel Related Services Company, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 |
15 | import ElseIf from './components/ElseIf';
16 | import TryCatch from './components/TryCatch';
17 | import TryCatchFinally from './components/TryCatchFinally';
18 | import Switch from './components/Switch';
19 | import Case from './components/Case';
20 | import Default from './components/Default';
21 |
22 | export default {
23 | ElseIf,
24 | TryCatch,
25 | TryCatchFinally,
26 | Switch,
27 | Case,
28 | Default,
29 | };
30 |
--------------------------------------------------------------------------------