├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github └── workflows │ ├── ci.yml │ └── copyright-update.yml ├── .gitignore ├── .npmignore ├── .prettierrc ├── LICENSE.txt ├── NOTICE ├── README.md ├── package-lock.json ├── package.json ├── src ├── component │ ├── index.ts │ ├── metrics │ │ ├── cacheMetrics.tsx │ │ ├── datasourceMetrics.tsx │ │ ├── endpointsRequestsMetrics.tsx │ │ ├── garbageCollectorMetrics.tsx │ │ ├── httpRequestMetrics.tsx │ │ ├── index.ts │ │ ├── jvmMemory.tsx │ │ ├── jvmThreads.tsx │ │ ├── systemMetrics.tsx │ │ ├── thread-item.tsx │ │ └── threads-modal.tsx │ └── pagination │ │ ├── item-count.spec.tsx │ │ ├── item-count.tsx │ │ ├── pagination-utils.spec.ts │ │ ├── pagination-utils.ts │ │ └── pagination.tsx ├── form │ ├── index.ts │ ├── validated-form.spec.tsx │ └── validated-form.tsx ├── formatter │ ├── index.ts │ ├── text-format.spec.tsx │ └── text-format.tsx ├── index.ts ├── language │ ├── index.ts │ ├── translate.spec.tsx │ ├── translate.tsx │ ├── translator-context.spec.tsx │ └── translator-context.ts ├── type │ ├── index.ts │ └── redux-action.type.ts └── util │ ├── data-utils.spec.ts │ ├── data-utils.ts │ ├── dom-utils.ts │ ├── index.ts │ ├── log-util.ts │ ├── number-utils.spec.ts │ ├── number-utils.ts │ ├── promise-utils.spec.ts │ ├── promise-utils.ts │ ├── storage-util.spec.ts │ ├── storage-util.ts │ ├── url-utils.spec.ts │ └── url-utils.ts ├── tests └── setup.ts ├── tsconfig.json ├── tsconfig.test.json └── vitest.config.ts /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | # Change these settings to your own preference 10 | indent_style = space 11 | indent_size = 2 12 | 13 | # We recommend you to keep these unchanged 14 | end_of_line = lf 15 | charset = utf-8 16 | trim_trailing_whitespace = true 17 | insert_final_newline = true 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | webpack.config.js 2 | target/ 3 | build/ 4 | bundles/ 5 | lib/ 6 | coverage/ 7 | node_modules/ 8 | jest.conf.js 9 | node/ 10 | postcss.config.js 11 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "plugins": ["@typescript-eslint"], 4 | "extends": [ 5 | "plugin:react/recommended", 6 | "eslint:recommended", 7 | "plugin:@typescript-eslint/eslint-recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:@typescript-eslint/recommended-requiring-type-checking", 10 | "prettier", 11 | "eslint-config-prettier" 12 | ], 13 | "parserOptions": { 14 | "ecmaVersion": 2018, 15 | "sourceType": "module", 16 | "ecmaFeatures": { 17 | "jsx": true 18 | }, 19 | "project": "./tsconfig.test.json" 20 | }, 21 | "settings": { 22 | "react": { 23 | "version": "detect" 24 | } 25 | }, 26 | "rules": { 27 | "@typescript-eslint/member-ordering": [ 28 | "error", 29 | { 30 | "default": ["static-field", "instance-field", "constructor", "static-method", "instance-method"] 31 | } 32 | ], 33 | "@typescript-eslint/no-misused-promises": "off", 34 | "@typescript-eslint/no-unnecessary-type-assertion": "off", 35 | "@typescript-eslint/no-unused-vars": "off", 36 | "@typescript-eslint/no-unsafe-argument": "off", 37 | "@typescript-eslint/explicit-member-accessibility": "off", 38 | "@typescript-eslint/explicit-function-return-type": "off", 39 | "@typescript-eslint/no-explicit-any": "off", 40 | "@typescript-eslint/no-unsafe-return": "off", 41 | "@typescript-eslint/no-unsafe-member-access": "off", 42 | "@typescript-eslint/no-unsafe-call": "off", 43 | "@typescript-eslint/no-unsafe-assignment": "off", 44 | "@typescript-eslint/explicit-module-boundary-types": "off", 45 | "@typescript-eslint/restrict-template-expressions": "off", 46 | "@typescript-eslint/restrict-plus-operands": "off", 47 | "@typescript-eslint/no-floating-promises": "off", 48 | "@typescript-eslint/ban-types": [ 49 | "error", 50 | { 51 | "types": { 52 | "Object": "Use {} instead." 53 | } 54 | } 55 | ], 56 | "@typescript-eslint/interface-name-prefix": "off", 57 | "@typescript-eslint/no-empty-function": "off", 58 | "@typescript-eslint/unbound-method": "off", 59 | "@typescript-eslint/array-type": "off", 60 | "@typescript-eslint/no-shadow": "error", 61 | "spaced-comment": ["warn", "always"], 62 | "guard-for-in": "error", 63 | "no-labels": "error", 64 | "no-caller": "error", 65 | "no-bitwise": "error", 66 | "no-console": ["error", { "allow": ["warn", "error"] }], 67 | "no-new-wrappers": "error", 68 | "no-eval": "error", 69 | "no-new": "error", 70 | "no-var": "error", 71 | "radix": "error", 72 | "eqeqeq": ["error", "always", { "null": "ignore" }], 73 | "prefer-const": "error", 74 | "object-shorthand": ["error", "always", { "avoidExplicitReturnArrows": true }], 75 | "default-case": "error", 76 | "complexity": ["error", 40], 77 | "no-invalid-this": "off", 78 | "react/prop-types": "off", 79 | "react/display-name": "off" 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Test & Build 5 | 6 | on: 7 | push: 8 | branches: [main] 9 | pull_request: 10 | branches: [main] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | strategy: 17 | matrix: 18 | node-version: [18.x] 19 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v2 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | cache: 'npm' 28 | - run: npm ci 29 | - run: npm run build --if-present 30 | - run: npm test 31 | -------------------------------------------------------------------------------- /.github/workflows/copyright-update.yml: -------------------------------------------------------------------------------- 1 | name: Copyright Update 2 | on: 3 | schedule: 4 | - cron: '0 0 31 12 *' # Repeats December 31st every year 5 | 6 | permissions: 7 | contents: read 8 | 9 | jobs: 10 | build: 11 | permissions: 12 | contents: write # for peter-evans/create-pull-request to create branch 13 | pull-requests: write # for peter-evans/create-pull-request to create a PR 14 | name: copyright update 15 | if: github.repository == 'jhipster/react-jhipster' 16 | runs-on: ubuntu-latest 17 | timeout-minutes: 40 18 | steps: 19 | # Checkout 20 | - uses: actions/checkout@v3 21 | with: 22 | ref: main 23 | fetch-depth: 0 24 | # Update the copyright headers 25 | - name: Find and Replace 26 | run: | 27 | CURRENT_YEAR=$(date +'%Y') 28 | NEW_YEAR=$(($CURRENT_YEAR + 1)) 29 | grep -rlZE "Copyright ([0-9]+)-$CURRENT_YEAR" . | xargs -0 sed -i -E "s/Copyright ([0-9]+)-$CURRENT_YEAR/Copyright \1-$NEW_YEAR/g" 30 | # Create PR 31 | - name: Create Pull Request 32 | uses: peter-evans/create-pull-request@v4 33 | with: 34 | token: ${{ secrets.GITHUB_TOKEN }} 35 | commit-message: 'Update copyright headers' 36 | title: 'Update Copyright Headers' 37 | body: 'This is an automated pull request to update the copyright headers' 38 | branch: 'copyright-date-update' 39 | author: 'jhipster-bot ' 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Misc 3 | ################# 4 | nbproject 5 | manifest.mf 6 | build.xml 7 | node_modules 8 | node_modules/* 9 | npm-debug.log 10 | yarn-error.log 11 | src/**/*.{js,jsx} 12 | tests/**/*.{js,jsx} 13 | /index.js 14 | /react-jhipster.{js,jsx} 15 | config/testing-utils.js 16 | !make.js 17 | !examples/**/*.{js,jsx} 18 | coverage 19 | **/*.metadata.json 20 | *.metadata.json 21 | /bundles 22 | build/ 23 | react-jhipster.iml 24 | lib 25 | 26 | ################# 27 | ## IDE 28 | ################# 29 | .idea 30 | .project 31 | .settings 32 | .vscode 33 | 34 | ############ 35 | ## Windows 36 | ############ 37 | 38 | # Windows image file caches 39 | Thumbs.db 40 | 41 | # Folder config file 42 | Desktop.ini 43 | 44 | ############ 45 | ## Mac 46 | ############ 47 | 48 | # Mac crap 49 | .DS_Store 50 | **/.DS_Store 51 | 52 | build/test-results/karma/ 53 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Misc 3 | ################# 4 | nbproject 5 | manifest.mf 6 | build.xml 7 | node_modules 8 | node_modules/* 9 | npm-debug.log 10 | *.ts 11 | !*.d.ts 12 | /tests 13 | /lib/tests 14 | /config 15 | examples 16 | .github 17 | coverage 18 | !*.metadata.json 19 | !bundles/*.{js,jsx} 20 | /sample/ 21 | 22 | ################# 23 | ## IDE 24 | ################# 25 | .idea 26 | .project 27 | .settings 28 | .vscode 29 | 30 | ############ 31 | ## Windows 32 | ############ 33 | 34 | # Windows image file caches 35 | Thumbs.db 36 | 37 | # Folder config file 38 | Desktop.ini 39 | 40 | ############ 41 | ## Mac 42 | ############ 43 | 44 | # Mac crap 45 | .DS_Store 46 | **/.DS_Store 47 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | # Prettier configuration 2 | printWidth: 140 3 | singleQuote: true 4 | 5 | # js and ts rules: 6 | arrowParens: avoid 7 | 8 | # jsx and tsx rules: 9 | bracketSameLine: false 10 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Copyright 2017-2025 the original author or authors from the JHipster project 3 | 4 | Apache License 5 | Version 2.0, January 2004 6 | http://www.apache.org/licenses/ 7 | 8 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 9 | 10 | 1. Definitions. 11 | 12 | "License" shall mean the terms and conditions for use, reproduction, 13 | and distribution as defined by Sections 1 through 9 of this document. 14 | 15 | "Licensor" shall mean the copyright owner or entity authorized by 16 | the copyright owner that is granting the License. 17 | 18 | "Legal Entity" shall mean the union of the acting entity and all 19 | other entities that control, are controlled by, or are under common 20 | control with that entity. For the purposes of this definition, 21 | "control" means (i) the power, direct or indirect, to cause the 22 | direction or management of such entity, whether by contract or 23 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 24 | outstanding shares, or (iii) beneficial ownership of such entity. 25 | 26 | "You" (or "Your") shall mean an individual or Legal Entity 27 | exercising permissions granted by this License. 28 | 29 | "Source" form shall mean the preferred form for making modifications, 30 | including but not limited to software source code, documentation 31 | source, and configuration files. 32 | 33 | "Object" form shall mean any form resulting from mechanical 34 | transformation or translation of a Source form, including but 35 | not limited to compiled object code, generated documentation, 36 | and conversions to other media types. 37 | 38 | "Work" shall mean the work of authorship, whether in Source or 39 | Object form, made available under the License, as indicated by a 40 | copyright notice that is included in or attached to the work 41 | (an example is provided in the Appendix below). 42 | 43 | "Derivative Works" shall mean any work, whether in Source or Object 44 | form, that is based on (or derived from) the Work and for which the 45 | editorial revisions, annotations, elaborations, or other modifications 46 | represent, as a whole, an original work of authorship. For the purposes 47 | of this License, Derivative Works shall not include works that remain 48 | separable from, or merely link (or bind by name) to the interfaces of, 49 | the Work and Derivative Works thereof. 50 | 51 | "Contribution" shall mean any work of authorship, including 52 | the original version of the Work and any modifications or additions 53 | to that Work or Derivative Works thereof, that is intentionally 54 | submitted to Licensor for inclusion in the Work by the copyright owner 55 | or by an individual or Legal Entity authorized to submit on behalf of 56 | the copyright owner. For the purposes of this definition, "submitted" 57 | means any form of electronic, verbal, or written communication sent 58 | to the Licensor or its representatives, including but not limited to 59 | communication on electronic mailing lists, source code control systems, 60 | and issue tracking systems that are managed by, or on behalf of, the 61 | Licensor for the purpose of discussing and improving the Work, but 62 | excluding communication that is conspicuously marked or otherwise 63 | designated in writing by the copyright owner as "Not a Contribution." 64 | 65 | "Contributor" shall mean Licensor and any individual or Legal Entity 66 | on behalf of whom a Contribution has been received by Licensor and 67 | subsequently incorporated within the Work. 68 | 69 | 2. Grant of Copyright License. Subject to the terms and conditions of 70 | this License, each Contributor hereby grants to You a perpetual, 71 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 72 | copyright license to reproduce, prepare Derivative Works of, 73 | publicly display, publicly perform, sublicense, and distribute the 74 | Work and such Derivative Works in Source or Object form. 75 | 76 | 3. Grant of Patent License. Subject to the terms and conditions of 77 | this License, each Contributor hereby grants to You a perpetual, 78 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 79 | (except as stated in this section) patent license to make, have made, 80 | use, offer to sell, sell, import, and otherwise transfer the Work, 81 | where such license applies only to those patent claims licensable 82 | by such Contributor that are necessarily infringed by their 83 | Contribution(s) alone or by combination of their Contribution(s) 84 | with the Work to which such Contribution(s) was submitted. If You 85 | institute patent litigation against any entity (including a 86 | cross-claim or counterclaim in a lawsuit) alleging that the Work 87 | or a Contribution incorporated within the Work constitutes direct 88 | or contributory patent infringement, then any patent licenses 89 | granted to You under this License for that Work shall terminate 90 | as of the date such litigation is filed. 91 | 92 | 4. Redistribution. You may reproduce and distribute copies of the 93 | Work or Derivative Works thereof in any medium, with or without 94 | modifications, and in Source or Object form, provided that You 95 | meet the following conditions: 96 | 97 | (a) You must give any other recipients of the Work or 98 | Derivative Works a copy of this License; and 99 | 100 | (b) You must cause any modified files to carry prominent notices 101 | stating that You changed the files; and 102 | 103 | (c) You must retain, in the Source form of any Derivative Works 104 | that You distribute, all copyright, patent, trademark, and 105 | attribution notices from the Source form of the Work, 106 | excluding those notices that do not pertain to any part of 107 | the Derivative Works; and 108 | 109 | (d) If the Work includes a "NOTICE" text file as part of its 110 | distribution, then any Derivative Works that You distribute must 111 | include a readable copy of the attribution notices contained 112 | within such NOTICE file, excluding those notices that do not 113 | pertain to any part of the Derivative Works, in at least one 114 | of the following places: within a NOTICE text file distributed 115 | as part of the Derivative Works; within the Source form or 116 | documentation, if provided along with the Derivative Works; or, 117 | within a display generated by the Derivative Works, if and 118 | wherever such third-party notices normally appear. The contents 119 | of the NOTICE file are for informational purposes only and 120 | do not modify the License. You may add Your own attribution 121 | notices within Derivative Works that You distribute, alongside 122 | or as an addendum to the NOTICE text from the Work, provided 123 | that such additional attribution notices cannot be construed 124 | as modifying the License. 125 | 126 | You may add Your own copyright statement to Your modifications and 127 | may provide additional or different license terms and conditions 128 | for use, reproduction, or distribution of Your modifications, or 129 | for any such Derivative Works as a whole, provided Your use, 130 | reproduction, and distribution of the Work otherwise complies with 131 | the conditions stated in this License. 132 | 133 | 5. Submission of Contributions. Unless You explicitly state otherwise, 134 | any Contribution intentionally submitted for inclusion in the Work 135 | by You to the Licensor shall be under the terms and conditions of 136 | this License, without any additional terms or conditions. 137 | Notwithstanding the above, nothing herein shall supersede or modify 138 | the terms of any separate license agreement you may have executed 139 | with Licensor regarding such Contributions. 140 | 141 | 6. Trademarks. This License does not grant permission to use the trade 142 | names, trademarks, service marks, or product names of the Licensor, 143 | except as required for reasonable and customary use in describing the 144 | origin of the Work and reproducing the content of the NOTICE file. 145 | 146 | 7. Disclaimer of Warranty. Unless required by applicable law or 147 | agreed to in writing, Licensor provides the Work (and each 148 | Contributor provides its Contributions) on an "AS IS" BASIS, 149 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 150 | implied, including, without limitation, any warranties or conditions 151 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 152 | PARTICULAR PURPOSE. You are solely responsible for determining the 153 | appropriateness of using or redistributing the Work and assume any 154 | risks associated with Your exercise of permissions under this License. 155 | 156 | 8. Limitation of Liability. In no event and under no legal theory, 157 | whether in tort (including negligence), contract, or otherwise, 158 | unless required by applicable law (such as deliberate and grossly 159 | negligent acts) or agreed to in writing, shall any Contributor be 160 | liable to You for damages, including any direct, indirect, special, 161 | incidental, or consequential damages of any character arising as a 162 | result of this License or out of the use or inability to use the 163 | Work (including but not limited to damages for loss of goodwill, 164 | work stoppage, computer failure or malfunction, or any and all 165 | other commercial damages or losses), even if such Contributor 166 | has been advised of the possibility of such damages. 167 | 168 | 9. Accepting Warranty or Additional Liability. While redistributing 169 | the Work or Derivative Works thereof, You may choose to offer, 170 | and charge a fee for, acceptance of support, warranty, indemnity, 171 | or other liability obligations and/or rights consistent with this 172 | License. However, in accepting such obligations, You may act only 173 | on Your own behalf and on Your sole responsibility, not on behalf 174 | of any other Contributor, and only if You agree to indemnify, 175 | defend, and hold each Contributor harmless for any liability 176 | incurred by, or claims asserted against, such Contributor by reason 177 | of your accepting any such warranty or additional liability. 178 | 179 | END OF TERMS AND CONDITIONS 180 | 181 | APPENDIX: How to apply the Apache License to your work. 182 | 183 | To apply the Apache License to your work, attach the following 184 | boilerplate notice, with the fields enclosed by brackets "[]" 185 | replaced with your own identifying information. (Don't include 186 | the brackets!) The text should be enclosed in the appropriate 187 | comment syntax for the file format. We also recommend that a 188 | file or class name and description of purpose be included on the 189 | same "printed page" as the copyright notice for easier 190 | identification within third-party archives. 191 | 192 | Copyright [yyyy] [name of copyright owner] 193 | 194 | Licensed under the Apache License, Version 2.0 (the "License"); 195 | you may not use this file except in compliance with the License. 196 | You may obtain a copy of the License at 197 | 198 | http://www.apache.org/licenses/LICENSE-2.0 199 | 200 | Unless required by applicable law or agreed to in writing, software 201 | distributed under the License is distributed on an "AS IS" BASIS, 202 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 203 | See the License for the specific language governing permissions and 204 | limitations under the License. 205 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | JHipster React library 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | For more information on the JHipster project, see https://www.jhipster.tech/ 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Logo][jhipster-image]][jhipster-url] 2 | 3 | Greetings, Java Hipster! 4 | 5 | This is the JHipster React utilities library 6 | 7 | [![NPM version][npm-image]][npm-url] 8 | [![Build Status][github-actions-image]][github-actions-url] 9 | 10 | Full documentation and information is available on our website at [http://www.jhipster.tech/][jhipster-url] 11 | 12 | Please read our [guidelines](https://github.com/jhipster/generator-jhipster/CONTRIBUTING.md#submitting-an-issue) before submitting an issue. If your issue is a bug, please use the bug template pre populated [here](https://github.com/jhipster/generator-jhipster/issues/new). For feature requests and queries you can use [this template][feature-template]. 13 | 14 | [github-actions-image]: https://github.com/jhipster/react-jhipster/actions/workflows/ci.yml/badge.svg 15 | [github-actions-url]: https://github.com/jhipster/react-jhipster/actions/workflows/ci.yml 16 | [jhipster-image]: https://raw.githubusercontent.com/jhipster/jhipster.github.io/main/images/logo/logo-jhipster2x.png 17 | [jhipster-url]: http://www.jhipster.tech/ 18 | [npm-image]: https://badge.fury.io/js/react-jhipster.svg 19 | [npm-url]: https://npmjs.org/package/react-jhipster 20 | [feature-template]: https://github.com/jhipster/generator-jhipster/issues/new?body=*%20**Overview%20of%20the%20request**%0A%0A%3C!--%20what%20is%20the%20query%20or%20request%20--%3E%0A%0A*%20**Motivation%20for%20or%20Use%20Case**%20%0A%0A%3C!--%20explain%20why%20this%20is%20a%20required%20for%20you%20--%3E%0A%0A%0A*%20**Browsers%20and%20Operating%20System**%20%0A%0A%3C!--%20is%20this%20a%20problem%20with%20all%20browsers%20or%20only%20IE8%3F%20--%3E%0A%0A%0A*%20**Related%20issues**%20%0A%0A%3C!--%20has%20a%20similar%20issue%20been%20reported%20before%3F%20--%3E%0A%0A*%20**Suggest%20a%20Fix**%20%0A%0A%3C!--%20if%20you%20can%27t%20fix%20this%20yourself%2C%20perhaps%20you%20can%20point%20to%20what%20might%20be%0A%20%20causing%20the%20problem%20(line%20of%20code%20or%20commit)%20--%3E 21 | 22 | ## Development setup 23 | 24 | You need NodeJS and NPM. 25 | 26 | ### Fork the react-jhipster project 27 | 28 | Go to the [react-jhipster project](https://github.com/jhipster/react-jhipster) and click on the "fork" button. You can then clone your own fork of the project, and start working on it. 29 | 30 | [Please read the Github forking documentation for more information](https://help.github.com/articles/fork-a-repo) 31 | 32 | ### Build 33 | 34 | Run `npm install` to install all dependencies. 35 | 36 | Make some changes, run `npm run test` to run both eslint and karma tests. 37 | 38 | Package the library with `npm run build`. 39 | 40 | ### Set NPM to use the cloned project 41 | 42 | In your cloned `react-jhipster` project, type `npm link`. 43 | 44 | This will do a symbolic link from the global `node_modules` version to point to this folder. 45 | 46 | For testing, you will want to integrate your version of `react-jhipster` into an application generated by JHipster. 47 | 48 | Go to your application folder, run `npm link react-jhipster` so that the local version has a symbolic link to the development version of `react-jhipster`. 49 | 50 | You should see your changes reflected in the application. 51 | 52 | Another way is to run `npm pack` on react-jhipster and then do `npm install path-to/react-jhipster/react-jhipster-0.15.0.tgz` on the generated application. this is the most fool proof way to test if `npm link` doesn't work 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-jhipster", 3 | "version": "0.25.3", 4 | "description": "A Jhipster util library for React", 5 | "keywords": [ 6 | "jhipster", 7 | "react" 8 | ], 9 | "homepage": "https://www.jhipster.tech", 10 | "bugs": { 11 | "url": "https://github.com/jhipster/generator-jhipster/issues" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/jhipster/react-jhipster.git" 16 | }, 17 | "license": "Apache-2.0", 18 | "author": "Deepu KS", 19 | "exports": "./lib/index.js", 20 | "main": "lib/index.js", 21 | "types": "lib/index.d.ts", 22 | "typings": "lib/index.d.ts", 23 | "files": [ 24 | "src", 25 | "lib", 26 | "LICENCE.txt", 27 | "NOTICE", 28 | "README.md", 29 | "index.ts", 30 | "react-jhipster.ts" 31 | ], 32 | "scripts": { 33 | "build": "npm run cleanup && npm run tsc", 34 | "cleanup": "rimraf lib/* src/*.d.ts src/**/*.d.ts src/*.{js,jsx} src/**/*.{js,jsx} tests/**/*.d.ts tests/*.d.ts", 35 | "lint": "eslint . --ext .js,.ts,.jsx,.tsx", 36 | "lint:fix": "npm run lint -- --fix", 37 | "precommit": "lint-staged", 38 | "prepare": "npm run build", 39 | "prettier:check": "prettier --check \"*.ts\" package.json \"{src,test}/**/*.{ts,tsx}\"", 40 | "prettier:format": "prettier --write \"*.ts\" package.json \"{src,test}/**/*.{ts,tsx}\"", 41 | "release": "npm test && git push && git push --tags && npm publish", 42 | "release:major": "npm run build && npm run commit-lib && npm version major -a -m \"Update to %s\" && npm run release", 43 | "release:minor": "npm run build && npm run commit-lib && npm version minor -a -m \"Update to %s\" && npm run release", 44 | "release:patch": "npm run build && npm run commit-lib && npm version patch -a -m \"Update to %s\" && npm run release", 45 | "pretest": "npm run lint && npm run prettier:check", 46 | "test": "npm run vitest", 47 | "test:watch": "npm run vitest", 48 | "tsc": "tsc", 49 | "vitest": "vitest run --coverage" 50 | }, 51 | "lint-staged": { 52 | "*.{ts,tsx}": [ 53 | "prettier --write", 54 | "npm run lint:fix", 55 | "git add" 56 | ] 57 | }, 58 | "dependencies": { 59 | "lodash": "^4.17.21", 60 | "numeral": "^2.0.6", 61 | "react-popper": "^2.3.0", 62 | "sanitize-html": "^2.13.1", 63 | "tslib": "^2.8.1" 64 | }, 65 | "devDependencies": { 66 | "@testing-library/react": "^16.1.0", 67 | "@types/react": "^18.3.14", 68 | "@types/react-dom": "^18.3.2", 69 | "@types/sanitize-html": "^2.13.0", 70 | "@types/webpack-env": "^1.18.5", 71 | "@typescript-eslint/eslint-plugin": "^7.18.0", 72 | "@typescript-eslint/parser": "^7.18.0", 73 | "@vitejs/plugin-react": "^4.3.4", 74 | "@vitest/coverage-v8": "^2.1.8", 75 | "axios": "^1.7.9", 76 | "dayjs": "^1.11.13", 77 | "eslint": "^8.57.0", 78 | "eslint-config-prettier": "^9.1.0", 79 | "eslint-plugin-react": "^7.37.2", 80 | "husky": "^6.0.0", 81 | "jsdom": "^25.0.1", 82 | "lint-staged": "^11.0.0", 83 | "prettier": "^3.4.2", 84 | "prettier-plugin-packagejson": "^2.5.6", 85 | "react": "^18.3.1", 86 | "react-dom": "^18.3.1", 87 | "react-hook-form": "^7.54.0", 88 | "reactstrap": "^9.2.3", 89 | "rimraf": "^3.0.2", 90 | "typescript": "5.7.2", 91 | "vitest": "^2.1.8" 92 | }, 93 | "peerDependencies": { 94 | "axios": "*", 95 | "dayjs": "^1.10.4", 96 | "react": "^18 || ^19", 97 | "react-dom": "^18 || ^19", 98 | "react-hook-form": "^7.30.0", 99 | "reactstrap": "^9.2.3" 100 | }, 101 | "peerDependenciesMeta": { 102 | "reactstrap": { 103 | "optional": true 104 | } 105 | }, 106 | "engines": { 107 | "node": ">=18.13.0" 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/component/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | export * from './pagination/pagination'; 20 | export * from './pagination/item-count'; 21 | export * from './pagination/pagination-utils'; 22 | export * from './metrics'; 23 | -------------------------------------------------------------------------------- /src/component/metrics/cacheMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Table } from 'reactstrap'; 4 | import { nanToZero } from '../../util/number-utils'; 5 | 6 | export interface ICacheMetricsProps { 7 | cacheMetrics: any; 8 | twoDigitAfterPointFormat: string; 9 | } 10 | 11 | export class CacheMetrics extends React.Component { 12 | render() { 13 | const { cacheMetrics, twoDigitAfterPointFormat } = this.props; 14 | return ( 15 |
16 |

Cache statistics

17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | {Object.keys(cacheMetrics).map(key => ( 30 | 31 | 32 | 33 | 34 | 35 | 45 | 55 | 56 | ))} 57 | 58 |
Cache NameCache HitsCache MissesCache GetsCache Hit %Cache Miss %
{key}{cacheMetrics[key]['cache.gets.hit']}{cacheMetrics[key]['cache.gets.miss']}{cacheMetrics[key]['cache.gets.miss'] + cacheMetrics[key]['cache.gets.hit']} 36 | 44 | 46 | 54 |
59 |
60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/component/metrics/datasourceMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Table } from 'reactstrap'; 4 | 5 | export interface IDatasourceMetricsProps { 6 | datasourceMetrics: any; 7 | twoDigitAfterPointFormat: string; 8 | } 9 | 10 | export class DatasourceMetrics extends React.Component { 11 | render() { 12 | const { datasourceMetrics, twoDigitAfterPointFormat } = this.props; 13 | return ( 14 |
15 |

DataSource statistics (time in millisecond)

16 | 17 | 18 | 19 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 41 | 44 | 47 | 50 | 53 | 56 | 59 | 60 | 61 | 62 | 63 | 66 | 69 | 72 | 75 | 78 | 81 | 84 | 85 | 86 | 87 | 88 | 91 | 94 | 97 | 100 | 103 | 106 | 109 | 110 | 111 |
20 | Connection Pool Usage 21 | (active: {datasourceMetrics.active.value}, min: {datasourceMetrics.min.value}, max: {datasourceMetrics.max.value}, idle:{' '} 22 | {datasourceMetrics.idle.value}) 23 | CountMeanMinp50p75p95p99Max
Acquire{datasourceMetrics.acquire.count} 39 | 40 | 42 | 43 | 45 | 46 | 48 | 49 | 51 | 52 | 54 | 55 | 57 | 58 |
Creation{datasourceMetrics.creation.count} 64 | 65 | 67 | 68 | 70 | 71 | 73 | 74 | 76 | 77 | 79 | 80 | 82 | 83 |
Usage{datasourceMetrics.usage.count} 89 | 90 | 92 | 93 | 95 | 96 | 98 | 99 | 101 | 102 | 104 | 105 | 107 | 108 |
112 |
113 | ); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/component/metrics/endpointsRequestsMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Table } from 'reactstrap'; 4 | 5 | export interface IEndpointsRequestsMetricsProps { 6 | endpointsRequestsMetrics: any; 7 | wholeNumberFormat: string; 8 | } 9 | 10 | export class EndpointsRequestsMetrics extends React.Component { 11 | render() { 12 | const { endpointsRequestsMetrics, wholeNumberFormat } = this.props; 13 | return ( 14 |
15 |

Endpoints requests (time in millisecond)

16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | {Object.entries(endpointsRequestsMetrics).map(([key, entry]) => 27 | Object.entries(entry).map(([method, methodValue]) => ( 28 | 29 | 30 | 31 | 32 | 35 | 36 | )), 37 | )} 38 | 39 |
MethodEndpoint urlCountMean
{method}{key}{methodValue.count} 33 | 34 |
40 |
41 | ); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/component/metrics/garbageCollectorMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Col, Progress, Row, Table } from 'reactstrap'; 4 | 5 | export interface IGarbageCollectorMetricsProps { 6 | garbageCollectorMetrics: any; 7 | wholeNumberFormat: string; 8 | } 9 | 10 | export class GarbageCollectorMetrics extends React.Component { 11 | render() { 12 | const { garbageCollectorMetrics, wholeNumberFormat } = this.props; 13 | return ( 14 |
15 |

Garbage Collection

16 | 17 | 18 | 19 | GC Live Data Size/GC Max Data Size ( 20 | M 21 | / 22 | M) 23 | 24 | 29 | 34 | % 35 | 36 | 37 | 38 | 39 | GC Memory Promoted/GC Memory Allocated ( 40 | M 41 | /{' '} 42 | 43 | M) 44 | 45 | 50 | 55 | % 56 | 57 | 58 | 59 | 60 | Classes loaded 61 | {garbageCollectorMetrics.classesLoaded} 62 | 63 | 64 | Classes unloaded 65 | {garbageCollectorMetrics.classesUnloaded} 66 | 67 | 68 | 69 | 70 | 71 | 72 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 89 | 92 | 95 | 98 | 101 | 104 | 107 | 110 | 111 | 112 |
73 | CountMeanMinp50p75p95p99Max
jvm.gc.pause 87 | 88 | 90 | 91 | 93 | 94 | 96 | 97 | 99 | 100 | 102 | 103 | 105 | 106 | 108 | 109 |
113 |
114 | ); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/component/metrics/httpRequestMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Progress, Table } from 'reactstrap'; 4 | import { nanToZero } from '../../util/number-utils'; 5 | 6 | export interface IHttpRequestMetricsProps { 7 | requestMetrics: any; 8 | wholeNumberFormat: string; 9 | twoDigitAfterPointFormat: string; 10 | } 11 | 12 | export class HttpRequestMetrics extends React.Component { 13 | render() { 14 | const { requestMetrics, wholeNumberFormat, twoDigitAfterPointFormat } = this.props; 15 | return ( 16 |
17 |

HTTP requests (time in milliseconds)

18 |

19 | Total requests:{' '} 20 | 21 | 22 | 23 |

24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | {Object.keys(requestMetrics.percode).map((key, index) => ( 35 | 36 | 37 | 44 | 47 | 50 | 51 | ))} 52 | 53 |
CodeCountMeanMax
{key} 38 | 39 | 40 | 41 | 42 | 43 | 45 | 46 | 48 | 49 |
54 |
55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/component/metrics/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | export * from './jvmMemory'; 20 | export * from './jvmThreads'; 21 | export * from './systemMetrics'; 22 | export * from './httpRequestMetrics'; 23 | export * from './endpointsRequestsMetrics'; 24 | export * from './cacheMetrics'; 25 | export * from './datasourceMetrics'; 26 | export * from './garbageCollectorMetrics'; 27 | export * from './thread-item'; 28 | export * from './threads-modal'; 29 | -------------------------------------------------------------------------------- /src/component/metrics/jvmMemory.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Progress } from 'reactstrap'; 4 | 5 | export interface IJvmMemoryProps { 6 | jvmMetrics: any; 7 | wholeNumberFormat: string; 8 | } 9 | 10 | export class JvmMemory extends React.Component { 11 | render() { 12 | const { jvmMetrics, wholeNumberFormat } = this.props; 13 | return ( 14 |
15 |

Memory

16 | {Object.keys(jvmMetrics).map((key, index) => ( 17 |
18 | {jvmMetrics[key].max !== -1 ? ( 19 | 20 | {key} (M /{' '} 21 | 22 | M) 23 | 24 | ) : ( 25 | 26 | {key} M 27 | 28 | )} 29 |
30 | Committed : M 31 |
32 | {jvmMetrics[key].max !== -1 ? ( 33 | 34 | 35 | % 36 | 37 | 38 | ) : ( 39 | '' 40 | )} 41 |
42 | ))} 43 |
44 | ); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/component/metrics/jvmThreads.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Progress, Button } from 'reactstrap'; 4 | import ThreadsModal from './threads-modal'; 5 | 6 | export interface IJvmThreadsProps { 7 | jvmThreads: any; 8 | wholeNumberFormat: string; 9 | } 10 | 11 | export interface IJvmThreadsState { 12 | showModal: boolean; 13 | threadStats: { 14 | threadDumpAll: number; 15 | threadDumpRunnable: number; 16 | threadDumpTimedWaiting: number; 17 | threadDumpWaiting: number; 18 | threadDumpBlocked: number; 19 | }; 20 | } 21 | 22 | export class JvmThreads extends React.Component { 23 | state: IJvmThreadsState = { 24 | showModal: false, 25 | threadStats: { 26 | threadDumpAll: 0, 27 | threadDumpRunnable: 0, 28 | threadDumpTimedWaiting: 0, 29 | threadDumpWaiting: 0, 30 | threadDumpBlocked: 0, 31 | }, 32 | }; 33 | 34 | countThreadByState() { 35 | if (this.props.jvmThreads.threads) { 36 | const threadStats = { 37 | threadDumpAll: 0, 38 | threadDumpRunnable: 0, 39 | threadDumpTimedWaiting: 0, 40 | threadDumpWaiting: 0, 41 | threadDumpBlocked: 0, 42 | }; 43 | 44 | this.props.jvmThreads.threads.forEach(thread => { 45 | if (thread.threadState === 'RUNNABLE') { 46 | threadStats.threadDumpRunnable += 1; 47 | } else if (thread.threadState === 'WAITING') { 48 | threadStats.threadDumpWaiting += 1; 49 | } else if (thread.threadState === 'TIMED_WAITING') { 50 | threadStats.threadDumpTimedWaiting += 1; 51 | } else if (thread.threadState === 'BLOCKED') { 52 | threadStats.threadDumpBlocked += 1; 53 | } 54 | }); 55 | 56 | threadStats.threadDumpAll = 57 | threadStats.threadDumpRunnable + threadStats.threadDumpWaiting + threadStats.threadDumpTimedWaiting + threadStats.threadDumpBlocked; 58 | 59 | this.setState({ threadStats }); 60 | } 61 | } 62 | 63 | componentDidMount() { 64 | if (this.props.jvmThreads.threads) { 65 | this.countThreadByState(); 66 | } 67 | } 68 | 69 | componentDidUpdate(prevProps) { 70 | if (this.props.jvmThreads.threads && this.props.jvmThreads.threads !== prevProps.jvmThreads.threads) { 71 | this.countThreadByState(); 72 | } 73 | } 74 | 75 | openModal = () => { 76 | this.setState({ 77 | showModal: true, 78 | }); 79 | }; 80 | 81 | handleClose = e => { 82 | this.setState({ 83 | showModal: false, 84 | }); 85 | }; 86 | 87 | renderModal = () => ; 88 | 89 | render() { 90 | const { wholeNumberFormat } = this.props; 91 | const { threadStats } = this.state; 92 | return ( 93 |
94 | Threads (Total: {threadStats.threadDumpAll}){' '} 95 |

96 | Runnable {threadStats.threadDumpRunnable} 97 |

98 | 99 | 100 | 105 | 106 | 107 |

108 | Timed Waiting ({threadStats.threadDumpTimedWaiting}) 109 |

110 | 111 | 112 | 117 | 118 | 119 |

120 | Waiting ({threadStats.threadDumpWaiting}) 121 |

122 | 123 | 124 | 129 | 130 | 131 |

132 | Blocked ({threadStats.threadDumpBlocked}) 133 |

134 | 135 | 136 | 141 | 142 | 143 | {this.renderModal()} 144 | 147 |
148 | ); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/component/metrics/systemMetrics.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { TextFormat } from '../../formatter'; 3 | import { Progress, Col, Row } from 'reactstrap'; 4 | 5 | export interface ISystemMetricsProps { 6 | systemMetrics: any; 7 | wholeNumberFormat: string; 8 | timestampFormat: string; 9 | } 10 | 11 | export class SystemMetrics extends React.Component { 12 | static convertMillisecondsToDuration(ms) { 13 | const times = { 14 | year: 31557600000, 15 | month: 2629746000, 16 | day: 86400000, 17 | hour: 3600000, 18 | minute: 60000, 19 | second: 1000, 20 | }; 21 | let timeString = ''; 22 | let plural = ''; 23 | for (const key in times) { 24 | if (Math.floor(ms / times[key]) > 0) { 25 | plural = Math.floor(ms / times[key]) > 1 ? 's' : ''; 26 | timeString += Math.floor(ms / times[key]).toString() + ' ' + key.toString() + plural + ' '; 27 | ms = ms - times[key] * Math.floor(ms / times[key]); 28 | } 29 | } 30 | return timeString; 31 | } 32 | 33 | render() { 34 | const { systemMetrics, wholeNumberFormat, timestampFormat } = this.props; 35 | return ( 36 |
37 |

System

38 | 39 | Uptime 40 | 41 | {SystemMetrics.convertMillisecondsToDuration(systemMetrics['process.uptime'])} 42 | 43 | 44 | 45 | Start time 46 | 47 | 48 | 49 | 50 | 51 | Process CPU usage 52 | 53 | % 54 | 55 | 56 | 57 | 58 | % 59 | 60 | 61 | 62 | System CPU usage 63 | 64 | % 65 | 66 | 67 | 68 | 69 | % 70 | 71 | 72 | 73 | System CPU count 74 | 75 | {systemMetrics['system.cpu.count']} 76 | 77 | 78 | 79 | System 1m Load average 80 | 81 | 82 | 83 | 84 | 85 | Process files max 86 | 87 | 88 | 89 | 90 | 91 | Process files open 92 | 93 | 94 | 95 | 96 |
97 | ); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/component/metrics/thread-item.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Collapse, Card, CardBody, Row } from 'reactstrap'; 3 | 4 | export interface IThreadItemProps { 5 | threadDumpInfo: any; 6 | } 7 | 8 | export interface IThreadItemState { 9 | collapse: boolean; 10 | } 11 | 12 | export class ThreadItem extends React.Component { 13 | state: IThreadItemState = { 14 | collapse: false, 15 | }; 16 | 17 | toggleStackTrace = () => { 18 | this.setState({ 19 | collapse: !this.state.collapse, 20 | }); 21 | }; 22 | 23 | render() { 24 | const { threadDumpInfo } = this.props; 25 | 26 | return ( 27 |
28 | 29 | {this.state.collapse ? Hide StackTrace : Show StackTrace} 30 | 31 | 32 | 33 | 34 | 35 | {Object.entries(threadDumpInfo.stackTrace).map(([stK, stV]: [string, any]) => ( 36 | 37 | {stV.className}.{stV.methodName} 38 | 39 | ({stV.fileName}:{stV.lineNumber}) 40 | 41 | 42 | ))} 43 | 44 | 45 | 46 | 47 | 48 |
49 | ); 50 | } 51 | } 52 | 53 | export default ThreadItem; 54 | -------------------------------------------------------------------------------- /src/component/metrics/threads-modal.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Table, Modal, ModalHeader, ModalBody, ModalFooter, Button, Input, Badge, Row } from 'reactstrap'; 3 | 4 | import ThreadItem from './thread-item'; 5 | 6 | export interface IThreadsModalProps { 7 | showModal: boolean; 8 | handleClose: (e) => void; 9 | threadDump: any; 10 | } 11 | 12 | export interface IThreadsModalState { 13 | badgeFilter: string; 14 | searchFilter: string; 15 | } 16 | 17 | export class ThreadsModal extends React.Component { 18 | state: IThreadsModalState = { 19 | badgeFilter: '', 20 | searchFilter: '', 21 | }; 22 | 23 | computeFilteredList = () => { 24 | const { badgeFilter, searchFilter } = this.state; 25 | let filteredList = this.props.threadDump.threads; 26 | if (badgeFilter !== '') { 27 | filteredList = filteredList.filter(t => t.threadState === badgeFilter); 28 | } 29 | if (searchFilter !== '') { 30 | filteredList = filteredList.filter(t => t.lockName && t.lockName.toLowerCase().includes(searchFilter.toLowerCase())); 31 | } 32 | return filteredList; 33 | }; 34 | 35 | computeCounters = () => { 36 | let threadDumpAll = 0; 37 | let threadDumpRunnable = 0; 38 | let threadDumpWaiting = 0; 39 | let threadDumpTimedWaiting = 0; 40 | let threadDumpBlocked = 0; 41 | 42 | this.props.threadDump.threads.forEach(t => { 43 | switch (t.threadState) { 44 | case 'RUNNABLE': 45 | threadDumpRunnable++; 46 | break; 47 | case 'WAITING': 48 | threadDumpWaiting++; 49 | break; 50 | case 'TIMED_WAITING': 51 | threadDumpTimedWaiting++; 52 | break; 53 | case 'BLOCKED': 54 | threadDumpBlocked++; 55 | break; 56 | default: 57 | break; 58 | } 59 | }); 60 | 61 | threadDumpAll = threadDumpRunnable + threadDumpWaiting + threadDumpTimedWaiting + threadDumpBlocked; 62 | return { threadDumpAll, threadDumpRunnable, threadDumpWaiting, threadDumpTimedWaiting, threadDumpBlocked }; 63 | }; 64 | 65 | getBadgeClass = threadState => { 66 | if (threadState === 'RUNNABLE') { 67 | return 'badge-success'; 68 | } else if (threadState === 'WAITING') { 69 | return 'badge-info'; 70 | } else if (threadState === 'TIMED_WAITING') { 71 | return 'badge-warning'; 72 | } else if (threadState === 'BLOCKED') { 73 | return 'badge-danger'; 74 | } 75 | }; 76 | 77 | updateBadgeFilter = badge => () => this.setState({ badgeFilter: badge }); 78 | 79 | updateSearchFilter = event => this.setState({ searchFilter: event.target.value }); 80 | 81 | render() { 82 | const { showModal, handleClose, threadDump } = this.props; 83 | let counters = {} as any; 84 | let filteredList = null; 85 | if (threadDump && threadDump.threads) { 86 | counters = this.computeCounters(); 87 | filteredList = this.computeFilteredList(); 88 | } 89 | 90 | return ( 91 | 92 | Threads dump 93 | 94 | 95 | All  96 | {counters.threadDumpAll || 0} 97 | 98 |   99 | 100 | Runnable  101 | {counters.threadDumpRunnable || 0} 102 | 103 |   104 | 105 | Waiting  106 | {counters.threadDumpWaiting || 0} 107 | 108 |   109 | 110 | Timed Waiting  111 | {counters.threadDumpTimedWaiting || 0} 112 | 113 |   114 | 115 | Blocked  116 | {counters.threadDumpBlocked || 0} 117 | 118 |   119 |
 
120 | 121 |
122 | {filteredList 123 | ? filteredList.map((threadDumpInfo, i) => ( 124 |
125 |
126 | {' '} 127 | {threadDumpInfo.threadState} 128 |   129 | {threadDumpInfo.threadName} (ID {threadDumpInfo.threadId} 130 | )  131 |
132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 153 | 154 | 155 |
Blocked TimeBlocked CountWaited TimeWaited CountLock Name
{threadDumpInfo.blockedTime}{threadDumpInfo.blockedCount}{threadDumpInfo.waitedTime}{threadDumpInfo.waitedCount} 151 | {threadDumpInfo.lockName} 152 |
156 |
157 |
158 | )) 159 | : null} 160 |
161 |
162 | 163 | 166 | 167 |
168 | ); 169 | } 170 | } 171 | 172 | export default ThreadsModal; 173 | -------------------------------------------------------------------------------- /src/component/pagination/item-count.spec.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | /* 5 | Copyright 2017-2025 the original author or authors from the JHipster project. 6 | 7 | This file is part of the JHipster project, see https://www.jhipster.tech/ 8 | for more information. 9 | 10 | Licensed under the Apache License, Version 2.0 (the "License"); 11 | you may not use this file except in compliance with the License. 12 | You may obtain a copy of the License at 13 | 14 | http://www.apache.org/licenses/LICENSE-2.0 15 | 16 | Unless required by applicable law or agreed to in writing, software 17 | distributed under the License is distributed on an "AS IS" BASIS, 18 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | See the License for the specific language governing permissions and 20 | limitations under the License. 21 | */ 22 | import { describe, expect, it } from 'vitest'; 23 | import React from 'react'; 24 | import { render, screen } from '@testing-library/react'; 25 | 26 | import { JhiItemCount } from './item-count'; 27 | import { TranslatorContext } from '../../language'; 28 | describe('JhiItemCountComponent test', () => { 29 | describe('UI logic tests', () => { 30 | it('should change the content on page change', () => { 31 | const { rerender } = render(); 32 | 33 | expect(screen.getByText('Showing 1 - 10 of 100 items.')).not.toBeNull(); 34 | 35 | rerender(); 36 | 37 | expect(screen.getByText('Showing 11 - 20 of 100 items.')).not.toBeNull(); 38 | }); 39 | }); 40 | 41 | describe('Translation tests', () => { 42 | it('should change on language change', () => { 43 | TranslatorContext.registerTranslations('en', { 44 | global: { 45 | 'item-count': 'Showing {{first}} - {{second}} of {{total}} items.', 46 | }, 47 | }); 48 | 49 | TranslatorContext.registerTranslations('fr', { 50 | global: { 51 | 'item-count': 'Affichage {{first}} - {{second}} de {{total}} items.', 52 | }, 53 | }); 54 | TranslatorContext.setLocale('en'); 55 | const mountedWrapper = render(); 56 | expect(mountedWrapper.getByText('Showing 1 - 10 of 100 items.')).not.toBeNull(); 57 | 58 | TranslatorContext.setLocale('fr'); 59 | const mountedWrapperFr = render(); 60 | expect(mountedWrapperFr.getByText('Affichage 1 - 10 de 100 items.')).not.toBeNull(); 61 | 62 | // Reset TranslatorContext to default so that other tests pass 63 | TranslatorContext.context = { 64 | ...TranslatorContext.context, 65 | translations: {}, 66 | locale: null, 67 | previousLocale: null, 68 | }; 69 | }); 70 | }); 71 | }); 72 | -------------------------------------------------------------------------------- /src/component/pagination/item-count.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | import React from 'react'; 20 | import { Translate } from '../../language'; 21 | 22 | export interface IJhiItemCountProps { 23 | page: number; 24 | total: number; 25 | itemsPerPage: number; 26 | i18nEnabled?: boolean; 27 | } 28 | 29 | export class JhiItemCount extends React.Component { 30 | constructor(props) { 31 | super(props); 32 | } 33 | 34 | i18nValues() { 35 | const { page, total, itemsPerPage } = this.props; 36 | 37 | const first = (page - 1) * itemsPerPage === 0 ? 1 : (page - 1) * itemsPerPage + 1; 38 | const second = page * itemsPerPage < total ? page * itemsPerPage : total; 39 | 40 | return { 41 | first, 42 | second, 43 | total, 44 | }; 45 | } 46 | 47 | render() { 48 | const { page, total, itemsPerPage, i18nEnabled } = this.props; 49 | return ( 50 |
51 | {i18nEnabled ? ( 52 | 53 | Count 54 | 55 | ) : ( 56 | 57 | Showing {(page - 1) * itemsPerPage === 0 ? 1 : (page - 1) * itemsPerPage + 1} -{' '} 58 | {page * itemsPerPage < total ? page * itemsPerPage : total} of {total} items. 59 | 60 | )} 61 |
62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/component/pagination/pagination-utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { loadMoreDataWhenScrolled } from './pagination-utils'; 3 | import { getPaginationState } from './pagination-utils'; 4 | 5 | describe('loadMoreDataWhenScrolled', () => { 6 | const setLinks = (first, last, prev) => ({ first, last, prev }); 7 | const state = { entities: [{ 1: 'fake1' }, { 2: 'fake2' }, { 3: 'fake3' }] }; 8 | const payload = { data: [{ 1: 'fake4' }, { 2: 'fake2' }, { 3: 'fake3' }] }; 9 | 10 | describe('When sorting/deleting/editing or if there is only one page', () => { 11 | it('should replace current data with incoming data', () => { 12 | expect(loadMoreDataWhenScrolled(state.entities, payload.data, setLinks(0, 0, 0))).toEqual(payload.data); 13 | }); 14 | }); 15 | 16 | describe('When current data length is greater or equal than incoming data length', () => { 17 | it('should extend current data with incoming data', () => { 18 | expect(loadMoreDataWhenScrolled(state.entities, payload.data, setLinks(0, 3, 1))).toEqual([...state.entities, ...payload.data]); 19 | }); 20 | }); 21 | }); 22 | 23 | describe('getPaginationState', () => { 24 | const NUMBER_OF_ITEMS = 25; 25 | 26 | describe('when retrieving sort state', () => { 27 | it('should return id,asc and page number 1 by default', () => { 28 | expect(getPaginationState({ search: '' }, NUMBER_OF_ITEMS)).toEqual({ 29 | activePage: 1, 30 | itemsPerPage: NUMBER_OF_ITEMS, 31 | order: 'asc', 32 | sort: 'id', 33 | }); 34 | }); 35 | 36 | it('should return given sort field and order and page number param values from search', () => { 37 | const sortField = 'customField'; 38 | const sortDirection = 'desc'; 39 | const pageNumber = 42; 40 | expect(getPaginationState({ search: '?sort=' + sortField + ',' + sortDirection + '&page=' + pageNumber }, NUMBER_OF_ITEMS)).toEqual({ 41 | activePage: pageNumber, 42 | itemsPerPage: NUMBER_OF_ITEMS, 43 | order: sortDirection, 44 | sort: sortField, 45 | }); 46 | }); 47 | 48 | it('should fall back to 1 for page number if somehing different than a number is given', () => { 49 | expect(getPaginationState({ search: '?page=invalid' }, NUMBER_OF_ITEMS)).toEqual({ 50 | activePage: 1, 51 | itemsPerPage: NUMBER_OF_ITEMS, 52 | order: 'asc', 53 | sort: 'id', 54 | }); 55 | }); 56 | }); 57 | }); 58 | 59 | /* TODO add unit tests */ 60 | -------------------------------------------------------------------------------- /src/component/pagination/pagination-utils.ts: -------------------------------------------------------------------------------- 1 | import { getUrlParameter } from '../../util/url-utils'; 2 | 3 | export interface ISortBaseState { 4 | sort: string; 5 | order: string; 6 | } 7 | 8 | export interface IPaginationBaseState extends ISortBaseState { 9 | itemsPerPage: number; 10 | activePage: number; 11 | } 12 | 13 | export const getSortState = (location: { search: string }, sortField = 'id', sortOrder = 'asc'): ISortBaseState => { 14 | const sortParam = getUrlParameter('sort', location.search); 15 | let sort = sortField; 16 | let order = sortOrder; 17 | if (sortParam !== '') { 18 | sort = sortParam.split(',')[0]; 19 | order = sortParam.split(',')[1]; 20 | } 21 | return { sort, order }; 22 | }; 23 | 24 | export const getPaginationState = ( 25 | location: { search: string }, 26 | itemsPerPage: number, 27 | sortField = 'id', 28 | sortOrder = 'asc', 29 | ): IPaginationBaseState => { 30 | const pageParam = getUrlParameter('page', location.search); 31 | let activePage = 1; 32 | if (pageParam !== '' && !isNaN(parseInt(pageParam, 10))) { 33 | activePage = parseInt(pageParam, 10); 34 | } 35 | const { sort, order } = getSortState(location, sortField, sortOrder); 36 | return { itemsPerPage, sort, order, activePage }; 37 | }; 38 | 39 | /** 40 | * Retrieve new data when infinite scrolling 41 | * @param currentData 42 | * @param incomingData 43 | * @param links 44 | */ 45 | export const loadMoreDataWhenScrolled = (currentData: any, incomingData: any, links: any): any => { 46 | if (links.first === links.last || !currentData.length) { 47 | return incomingData; 48 | } 49 | if (currentData.length >= incomingData.length) { 50 | return [...currentData, ...incomingData]; 51 | } 52 | return null; 53 | }; 54 | -------------------------------------------------------------------------------- /src/component/pagination/pagination.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Pagination, PaginationItem, PaginationLink } from 'reactstrap'; 3 | 4 | export interface IJhiPaginationProps { 5 | activePage: number; 6 | onSelect: (page: number) => void; 7 | maxButtons: number; 8 | totalItems: number; 9 | itemsPerPage: number; 10 | } 11 | 12 | export interface IJhiPaginationState { 13 | currentPage: number; 14 | } 15 | 16 | export class JhiPagination extends React.Component { 17 | constructor(props) { 18 | super(props); 19 | this.state = { 20 | currentPage: this.props.activePage, 21 | }; 22 | } 23 | 24 | updateActivePage = currentPage => () => { 25 | this.setState({ currentPage }); 26 | this.props.onSelect(currentPage); 27 | }; 28 | 29 | previousPage = () => { 30 | this.setState({ currentPage: this.state.currentPage - 1 }); 31 | this.props.onSelect(this.state.currentPage - 1); 32 | }; 33 | 34 | nextPage = () => { 35 | this.setState({ currentPage: this.state.currentPage + 1 }); 36 | this.props.onSelect(this.state.currentPage + 1); 37 | }; 38 | 39 | itemsToDisplay = activePage => { 40 | const items = []; 41 | let item: any = {}; 42 | let previousItem: any = {}; 43 | const maxPage = this.getMaxPage(); 44 | const padSup = Math.floor((this.props.maxButtons - 1) / 2); 45 | const modulo = (this.props.maxButtons - 1) % 2; 46 | const padInf = padSup + modulo; 47 | for (let j = 0; j < maxPage; j++) { 48 | item = {}; 49 | if ( 50 | j === 0 || 51 | j === maxPage - 1 || 52 | j === activePage - 1 || 53 | j === activePage - 2 || 54 | (activePage === 1 && j === 1) || 55 | (activePage - padInf < j && j < activePage + padSup) 56 | ) { 57 | item.display = 'display'; 58 | } else if (previousItem.display === 'disabled') { 59 | item.display = 'hidden'; 60 | } else { 61 | item.display = 'disabled'; 62 | } 63 | items.push(item); 64 | previousItem = { ...item }; 65 | if (item.display === 'hidden') { 66 | previousItem.display = 'disabled'; 67 | } 68 | } 69 | return items; 70 | }; 71 | 72 | displayPaginationItem = (i, activePage) => ( 73 | 74 | {i + 1} 75 | 76 | ); 77 | 78 | cleanActivePage = () => { 79 | const { totalItems, itemsPerPage, activePage } = this.props; 80 | const cleanActivePage = totalItems === 0 ? 1 : Math.min(activePage, Math.ceil(totalItems / itemsPerPage)); 81 | 82 | if (cleanActivePage !== activePage) { 83 | this.updateActivePage(cleanActivePage)(); 84 | } 85 | }; 86 | 87 | getMaxPage = () => { 88 | const { itemsPerPage, totalItems } = this.props; 89 | const division = Math.floor(totalItems / itemsPerPage); 90 | const modulo = totalItems % itemsPerPage; 91 | return division + (modulo !== 0 ? 1 : 0); 92 | }; 93 | 94 | render() { 95 | this.cleanActivePage(); 96 | const { activePage } = this.props; 97 | const maxPage = this.getMaxPage(); 98 | 99 | return ( 100 |
101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | {this.itemsToDisplay(activePage).map((paginationItem, i) => 109 | paginationItem.display === 'display' ? ( 110 | this.displayPaginationItem(i, activePage) 111 | ) : paginationItem.display === 'disabled' ? ( 112 | 113 | ... 114 | 115 | ) : null, 116 | )} 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 |
125 | ); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/form/index.ts: -------------------------------------------------------------------------------- 1 | export * from './validated-form'; 2 | -------------------------------------------------------------------------------- /src/form/validated-form.spec.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | import { beforeEach, describe, expect, it, vitest } from 'vitest'; 5 | import React from 'react'; 6 | import { render, fireEvent, screen, waitFor } from '@testing-library/react'; 7 | import { useForm } from 'react-hook-form'; 8 | 9 | import { ValidatedForm, ValidatedField, ValidatedInput } from './index'; 10 | import { Input } from 'reactstrap'; 11 | import { isEmail, ValidatedBlobField } from './validated-form'; 12 | 13 | describe('ValidatedInput', () => { 14 | describe('with basic text input', () => { 15 | it('without default value renders an empty input', () => { 16 | const { container } = render(); 17 | const input = container.querySelector('input'); 18 | expect(input.name).toEqual('test-1'); 19 | expect(input.id).toEqual('test-1'); 20 | expect(input.type).toEqual('text'); 21 | expect(input.className).toEqual('form-control'); 22 | expect(input.value).toEqual(''); 23 | }); 24 | it('with id doesnt use name as default id in input', () => { 25 | const { container } = render(); 26 | const input = container.querySelector('input'); 27 | expect(input.name).toEqual('test-1'); 28 | expect(input.id).toEqual('my-id'); 29 | expect(input.type).toEqual('text'); 30 | expect(input.className).toEqual('form-control'); 31 | expect(input.value).toEqual(''); 32 | }); 33 | it('with custom tag value renders an custom input', () => { 34 | const { container } = render(); 35 | const input = container.querySelector('input'); 36 | expect(input.name).toEqual('test-1'); 37 | expect(input.type).toEqual('radio'); 38 | expect(input.className).toEqual('form-check-input form-check-input'); 39 | expect(input.value).toEqual('on'); 40 | }); 41 | it('with custom string tag value renders an custom input', () => { 42 | const { container } = render(); 43 | const input = container.querySelector('select'); 44 | expect(input.name).toEqual('test-1'); 45 | expect(input.type).toEqual('select-one'); 46 | expect(input.className).toEqual('form-control'); 47 | expect(input.value).toEqual(''); 48 | }); 49 | it('with default value renders an input with value', () => { 50 | const { container } = render(); 51 | const input = container.querySelector('input'); 52 | expect(input.name).toEqual('test-1'); 53 | expect(input.type).toEqual('text'); 54 | expect(input.className).toEqual('form-control'); 55 | expect(input.value).toEqual('hello'); 56 | }); 57 | }); 58 | 59 | describe('with register renders', () => { 60 | function InputApp({ name, ...rest }) { 61 | const onSubmit = data => { 62 | // do nothing 63 | }; 64 | const { 65 | register, 66 | handleSubmit, 67 | formState: { errors }, 68 | } = useForm(); 69 | return ( 70 |
71 | 72 | 73 | 74 | ); 75 | } 76 | it('without default value renders an empty input', () => { 77 | const { container } = render(); 78 | const input = container.querySelector('input'); 79 | expect(input.name).toEqual('test'); 80 | expect(input.type).toEqual('text'); 81 | expect(input.className).toEqual('form-control'); 82 | expect(input.value).toEqual(''); 83 | }); 84 | it('with default value renders an input', () => { 85 | const { container } = render(); 86 | const input = container.querySelector('input'); 87 | expect(input.name).toEqual('test'); 88 | expect(input.type).toEqual('text'); 89 | expect(input.className).toEqual(' is-touched is-valid form-control'); 90 | expect(input.value).toEqual('hello'); 91 | }); 92 | it('with default value renders an input and shows error when value is absent', async () => { 93 | const mockChange = vitest.fn(e => { 94 | // do nothing 95 | }); 96 | const { container } = render( 97 | , 98 | ); 99 | 100 | let input = container.querySelector('input'); 101 | expect(input.name).toEqual('test'); 102 | expect(input.type).toEqual('text'); 103 | expect(input.className).toEqual('form-control'); 104 | expect(input.value).toEqual('hello'); 105 | 106 | fireEvent.input(screen.getByRole('textbox'), { 107 | target: { 108 | value: '', 109 | }, 110 | }); 111 | expect(mockChange).toBeCalled(); 112 | 113 | fireEvent.submit(screen.getByRole('button')); 114 | 115 | await waitFor(() => expect(screen.getByText('this is required')).not.toBeNull()); 116 | input = container.querySelector('input'); 117 | expect(input.className).toEqual('is-invalid form-control'); 118 | expect(input.value).toEqual(''); 119 | }); 120 | }); 121 | }); 122 | 123 | describe('ValidatedField', () => { 124 | describe('with basic text input', () => { 125 | it('without default value & label renders an empty input', () => { 126 | const { container } = render(); 127 | const fg = container.querySelector('div.mb-3'); 128 | expect(fg).not.toBeNull(); 129 | const input = container.querySelector('input'); 130 | expect(input.name).toEqual('test-1'); 131 | expect(input.type).toEqual('text'); 132 | expect(input.className).toEqual('form-control'); 133 | expect(input.value).toEqual(''); 134 | }); 135 | it('with custom tags renders a custom input', () => { 136 | const { container } = render(); 137 | const fg = container.querySelector('fieldset.mb-3'); 138 | expect(fg).not.toBeNull(); 139 | const input = container.querySelector('input'); 140 | expect(input.name).toEqual('test-1'); 141 | expect(input.type).toEqual('text'); 142 | expect(input.className).toEqual('form-control form-control'); 143 | expect(input.value).toEqual(''); 144 | }); 145 | it('with label renders an input with label', () => { 146 | const { container } = render(); 147 | const col = container.querySelector('div.col'); 148 | expect(col).toBeNull(); 149 | const fg = container.querySelector('div.mb-3'); 150 | expect(fg).not.toBeNull(); 151 | const input = container.querySelector('input'); 152 | expect(input.name).toEqual('test-1'); 153 | expect(input.type).toEqual('text'); 154 | expect(input.className).toEqual('form-control'); 155 | expect(input.value).toEqual('hello'); 156 | const lb = container.querySelector('label'); 157 | expect(lb).not.toBeNull(); 158 | expect(screen.getByText('Label')).not.toBeNull(); 159 | }); 160 | it('with row renders an input in a column', () => { 161 | const { container } = render(); 162 | const col = container.querySelector('div.col'); 163 | expect(col).not.toBeNull(); 164 | const fg = container.querySelector('div.mb-3'); 165 | expect(fg).not.toBeNull(); 166 | const input = container.querySelector('input'); 167 | expect(input.name).toEqual('test-1'); 168 | expect(input.type).toEqual('text'); 169 | expect(input.className).toEqual('form-control'); 170 | expect(input.value).toEqual('hello'); 171 | const lb = container.querySelector('label'); 172 | expect(lb).not.toBeNull(); 173 | expect(screen.getByText('Label')).not.toBeNull(); 174 | }); 175 | it('with check renders an input before label', () => { 176 | const { container } = render(); 177 | const fg = container.querySelector('div.form-check'); 178 | expect(fg).not.toBeNull(); 179 | expect(fg.innerHTML).toEqual( 180 | '', 181 | ); 182 | }); 183 | }); 184 | 185 | describe('with register renders', () => { 186 | function InputApp({ name, ...rest }) { 187 | const onSubmit = data => { 188 | // do nothing 189 | }; 190 | const { 191 | register, 192 | handleSubmit, 193 | formState: { errors }, 194 | } = useForm(); 195 | return ( 196 |
197 | 198 | 199 | 200 | ); 201 | } 202 | it('without default value renders an empty input', () => { 203 | const { container } = render(); 204 | const input = container.querySelector('input'); 205 | expect(input.name).toEqual('test'); 206 | expect(input.type).toEqual('text'); 207 | expect(input.className).toEqual('form-control'); 208 | expect(input.value).toEqual(''); 209 | }); 210 | it('with default value renders an input', () => { 211 | const { container } = render(); 212 | const input = container.querySelector('input'); 213 | expect(input.name).toEqual('test'); 214 | expect(input.type).toEqual('text'); 215 | expect(input.className).toEqual(' is-touched is-valid form-control'); 216 | expect(input.value).toEqual('hello'); 217 | }); 218 | it('with default value renders an input and shows error when value is absent', async () => { 219 | const mockChange = vitest.fn(e => { 220 | // do nothing 221 | }); 222 | const { container } = render( 223 | , 224 | ); 225 | 226 | let input = container.querySelector('input'); 227 | expect(input.name).toEqual('test'); 228 | expect(input.type).toEqual('text'); 229 | expect(input.className).toEqual('form-control'); 230 | expect(input.value).toEqual('hello'); 231 | 232 | fireEvent.input(screen.getByRole('textbox'), { 233 | target: { 234 | value: '', 235 | }, 236 | }); 237 | expect(mockChange).toBeCalled(); 238 | 239 | fireEvent.submit(screen.getByRole('button')); 240 | 241 | await waitFor(() => expect(screen.getByText('this is required')).not.toBeNull()); 242 | input = container.querySelector('input'); 243 | expect(input.className).toEqual('is-invalid form-control'); 244 | expect(input.value).toEqual(''); 245 | }); 246 | }); 247 | }); 248 | 249 | describe('ValidatedBlobField', () => { 250 | describe('with basic input', () => { 251 | it('without default value, register & label renders an empty file input', () => { 252 | const { container } = render(); 253 | const fg = container.querySelector('div.mb-3'); 254 | expect(fg).not.toBeNull(); 255 | const input = container.querySelector('input'); 256 | expect(input.name).toEqual('test-1'); 257 | expect(input.id).toEqual('test-1'); 258 | expect(input.type).toEqual('file'); 259 | expect(input.className).toEqual('form-control'); 260 | expect(input.value).toEqual(''); 261 | }); 262 | it('with custom tags renders a custom input', () => { 263 | const { container } = render(); 264 | const fg = container.querySelector('fieldset.mb-3'); 265 | expect(fg).not.toBeNull(); 266 | const input = container.querySelector('input'); 267 | expect(input.name).toEqual('test-1'); 268 | expect(input.type).toEqual('file'); 269 | expect(input.className).toEqual('form-control'); 270 | expect(input.value).toEqual(''); 271 | }); 272 | it('with label renders an input with label', () => { 273 | const { container } = render(); 274 | const col = container.querySelector('div.col'); 275 | expect(col).toBeNull(); 276 | const fg = container.querySelector('div.mb-3'); 277 | expect(fg).not.toBeNull(); 278 | const input = container.querySelector('input'); 279 | expect(input.name).toEqual('test-1'); 280 | expect(input.id).toEqual('my-id'); 281 | expect(input.type).toEqual('file'); 282 | expect(input.className).toEqual('form-control'); 283 | expect(input.value).toEqual(''); 284 | const lb = container.querySelector('label'); 285 | expect(lb).not.toBeNull(); 286 | expect(screen.getByText('Label')).not.toBeNull(); 287 | }); 288 | it('with row renders an input in a column', () => { 289 | const { container } = render(); 290 | const col = container.querySelector('div.col'); 291 | expect(col).not.toBeNull(); 292 | const fg = container.querySelector('div.mb-3'); 293 | expect(fg).not.toBeNull(); 294 | const input = container.querySelector('input'); 295 | expect(input.name).toEqual('test-1'); 296 | expect(input.type).toEqual('file'); 297 | expect(input.className).toEqual('form-control'); 298 | expect(input.value).toEqual(''); 299 | const lb = container.querySelector('label'); 300 | expect(lb).not.toBeNull(); 301 | expect(screen.getByText('Label')).not.toBeNull(); 302 | }); 303 | }); 304 | 305 | describe('with register renders', () => { 306 | function InputApp({ name, ...rest }) { 307 | const onSubmit = data => { 308 | // do nothing 309 | }; 310 | const { 311 | register, 312 | handleSubmit, 313 | setValue, 314 | formState: { errors }, 315 | } = useForm({ mode: 'onChange' }); 316 | return ( 317 |
318 | 319 | 322 | 323 | ); 324 | } 325 | it('without default value renders an empty inputs with no data preview', () => { 326 | const { container } = render(); 327 | const inputContentType: HTMLInputElement = container.querySelector('input'); 328 | expect(inputContentType.id).toEqual('file_test_content_type'); 329 | expect(inputContentType.name).toEqual('testContentType'); 330 | expect(inputContentType.type).toEqual('hidden'); 331 | expect(inputContentType.value).toEqual(''); 332 | const input: HTMLInputElement = container.querySelector('input.form-control'); 333 | expect(input.name).toEqual('test'); 334 | expect(input.id).toEqual('test'); 335 | expect(input.type).toEqual('file'); 336 | expect(input.className).toEqual('form-control'); 337 | expect(input.value).toEqual(''); 338 | }); 339 | it('with default value renders an input with data preview for image', () => { 340 | const { container } = render( 341 | , 350 | ); 351 | const inputContentType: HTMLInputElement = container.querySelector('input'); 352 | expect(inputContentType.name).toEqual('testContentType'); 353 | const input: HTMLInputElement = container.querySelector('input.form-control'); 354 | expect(input.name).toEqual('test'); 355 | expect(input.id).toEqual('my-id'); 356 | expect(input.type).toEqual('file'); 357 | expect(input.className).toEqual(' is-touched is-valid form-control'); 358 | const div: HTMLDivElement = container.querySelector('div.jhi-validated-blob-field-item-container'); 359 | expect(div).not.toBeNull(); 360 | const img: HTMLImageElement = container.querySelector('img.my-image'); 361 | expect(img).not.toBeNull(); 362 | expect(img.src).toEqual('data:image/jpg;base64,hello'); 363 | expect(container.querySelector('div.jhi-validated-blob-field-item-row')).not.toBeNull(); 364 | expect(container.querySelector('div.jhi-validated-blob-field-item-row-col')).not.toBeNull(); 365 | expect(container.querySelector('div.jhi-validated-blob-field-item-clear-btn')).not.toBeNull(); 366 | }); 367 | it('with default value renders an input with data preview for blob', () => { 368 | const { container } = render( 369 | 457 |
458 | 459 | 460 | 461 |
462 | , 463 | ); 464 | const form = container.querySelector('form.myform'); 465 | expect(form).not.toBeNull(); 466 | expect(screen.getByText('a div')).not.toBeNull(); 467 | expect(screen.getByText('a button')).not.toBeNull(); 468 | expect(screen.getByText('nested button')).not.toBeNull(); 469 | }); 470 | }); 471 | describe('with validated input & field children', () => { 472 | it('should override register, error, isTouched & isDirty', async () => { 473 | const { container, findByText } = render( 474 | {}} className="myform"> 475 | 476 | , 477 | ); 478 | const form = container.querySelector('form.myform'); 479 | expect(form).not.toBeNull(); 480 | const input: HTMLInputElement = container.querySelector('input[name="test-12"]'); 481 | expect(input.name).toEqual('test-12'); 482 | expect(input.type).toEqual('text'); 483 | expect(input.className).toEqual(' is-touched is-dirty is-invalid form-control'); 484 | expect(input.value).toEqual(''); 485 | 486 | expect(await findByText('Your email is required.')).not.toBeNull(); 487 | }); 488 | describe('renders them with default values passed inline', () => { 489 | it('for text field', () => { 490 | const { container } = render( 491 | {}} className="myform"> 492 | 493 | , 494 | ); 495 | const input: HTMLInputElement = container.querySelector('input[name="test-1"]'); 496 | expect(input.name).toEqual('test-1'); 497 | expect(input.type).toEqual('text'); 498 | expect(input.className).toEqual('form-control'); 499 | expect(input.value).toEqual('hello'); 500 | }); 501 | 502 | it('for password field', () => { 503 | const { container } = render( 504 | {}} className="myform"> 505 | 506 | , 507 | ); 508 | const input2: HTMLInputElement = container.querySelector('input[name="test-2"]'); 509 | expect(input2.name).toEqual('test-2'); 510 | expect(input2.type).toEqual('password'); 511 | expect(input2.className).toEqual('form-control'); 512 | expect(input2.value).toEqual('1231'); 513 | }); 514 | 515 | it('for checkbox field', () => { 516 | const { container } = render( 517 | {}} className="myform"> 518 | 519 | , 520 | ); 521 | const input3: HTMLInputElement = container.querySelector('input[name="test-3"]'); 522 | expect(input3.name).toEqual('test-3'); 523 | expect(input3.type).toEqual('checkbox'); 524 | expect(input3.className).toEqual('form-check-input'); 525 | expect(input3.value).toEqual('true'); 526 | }); 527 | 528 | it('for radio field', () => { 529 | const { container } = render( 530 | {}} className="myform"> 531 | 532 | , 533 | ); 534 | const input4: HTMLInputElement = container.querySelector('input[name="test-4"]'); 535 | expect(input4.name).toEqual('test-4'); 536 | expect(input4.type).toEqual('radio'); 537 | expect(input4.className).toEqual('form-check-input'); 538 | expect(input4.value).toEqual('on'); 539 | }); 540 | 541 | it('for select field', () => { 542 | const { container } = render( 543 | {}} className="myform"> 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | , 554 | ); 555 | const input5: HTMLSelectElement = container.querySelector('select[name="test-5"]'); 556 | expect(input5.name).toEqual('test-5'); 557 | expect(input5.className).toEqual('form-select'); 558 | expect(input5.value).toEqual('value 1'); 559 | 560 | const input6: HTMLSelectElement = container.querySelector('select[name="test-6"]'); 561 | expect(input6.name).toEqual('test-6'); 562 | expect(input6.multiple).toEqual(true); 563 | expect(input6.className).toEqual('form-select'); 564 | expect(input6.selectedOptions[0].value).toEqual('value 1'); 565 | expect(input6.selectedOptions[1].value).toEqual('value 3'); 566 | }); 567 | }); 568 | describe('renders them with default values passed via form', () => { 569 | it('for text field', () => { 570 | const { container } = render( 571 | {}} 573 | className="myform" 574 | defaultValues={{ 575 | test1: 'test1', 576 | test2: 'test2', 577 | }} 578 | > 579 | 580 | 581 | , 582 | ); 583 | 584 | const input: HTMLInputElement = container.querySelector('input[name="test1"]'); 585 | expect(input.name).toEqual('test1'); 586 | expect(input.type).toEqual('text'); 587 | expect(input.className).toEqual('form-control'); 588 | expect(input.value).toEqual('test1'); 589 | 590 | const input2: HTMLInputElement = container.querySelector('input[name="test2"]'); 591 | expect(input2.name).toEqual('test2'); 592 | expect(input2.type).toEqual('password'); 593 | expect(input2.className).toEqual('form-control'); 594 | expect(input2.value).toEqual('test2'); 595 | }); 596 | 597 | it('for checkbox/radio field should retain value inline', () => { 598 | const { container } = render( 599 | {}} 601 | className="myform" 602 | defaultValues={{ 603 | test3: 'false', 604 | test4: 'on', 605 | }} 606 | > 607 | 608 | 609 | , 610 | ); 611 | // should retain the value 612 | const input3: HTMLInputElement = container.querySelector('input[name="test3"]'); 613 | expect(input3.name).toEqual('test3'); 614 | expect(input3.type).toEqual('checkbox'); 615 | expect(input3.className).toEqual('form-check-input'); 616 | expect(input3.value).toEqual('true'); 617 | expect(input3.checked).toEqual(true); 618 | // should retain the value 619 | const input4: HTMLInputElement = container.querySelector('input[name="test4"]'); 620 | expect(input4.name).toEqual('test4'); 621 | expect(input4.type).toEqual('radio'); 622 | expect(input4.className).toEqual('form-check-input'); 623 | expect(input4.value).toEqual('on'); 624 | expect(input4.checked).toEqual(true); 625 | }); 626 | 627 | it('for select field', () => { 628 | const { container } = render( 629 | {}} 631 | className="myform" 632 | defaultValues={{ 633 | test5: 'value 1', 634 | test6: ['value 1', 'value 3'], 635 | }} 636 | > 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | , 647 | ); 648 | const input5: HTMLSelectElement = container.querySelector('select[name="test5"]'); 649 | expect(input5.name).toEqual('test5'); 650 | expect(input5.className).toEqual('form-select'); 651 | expect(input5.selectedOptions[0].value).toEqual('value 1'); 652 | expect(input5.value).toEqual('value 1'); 653 | 654 | const input6: HTMLSelectElement = container.querySelector('select[name="test6"]'); 655 | expect(input6.name).toEqual('test6'); 656 | expect(input6.multiple).toEqual(true); 657 | expect(input6.className).toEqual('form-select'); 658 | expect(input6.selectedOptions[0].value).toEqual('value 1'); 659 | expect(input6.selectedOptions[1].value).toEqual('value 3'); 660 | }); 661 | }); 662 | describe('validate the form with no default values', () => { 663 | const mockSubmit = vitest.fn((email, password, active, select, multiselect) => { 664 | // do nothing 665 | }); 666 | 667 | const onSubmit = ({ email, password, active, select, multiselect }) => { 668 | mockSubmit(email, password, active, select, multiselect); 669 | }; 670 | 671 | beforeEach(() => { 672 | render( 673 | 674 | 686 | 699 | 700 | 709 | 710 | 711 | 712 | 723 | 724 | 725 | 726 | 727 | 728 | , 729 | ); 730 | }); 731 | it('should display required error when value is invalid', async () => { 732 | fireEvent.submit(screen.getByRole('button')); 733 | 734 | expect(await screen.findByText('Your email is required.')).not.toBeNull(); 735 | expect(await screen.findByText('Your password is required.')).not.toBeNull(); 736 | expect(mockSubmit).not.toBeCalled(); 737 | }); 738 | it('should display matching error when email is invalid', async () => { 739 | fireEvent.input(screen.getByLabelText('email'), { 740 | target: { 741 | value: 'test', 742 | }, 743 | }); 744 | 745 | fireEvent.input(screen.getByLabelText('password'), { 746 | target: { 747 | value: 'password', 748 | }, 749 | }); 750 | 751 | fireEvent.submit(screen.getByRole('button')); 752 | 753 | expect(await screen.findByText('Entered value does not match email format')).not.toBeNull(); 754 | expect(mockSubmit).not.toBeCalled(); 755 | const email = screen.getByLabelText('email') as HTMLInputElement; 756 | expect(email.value).toBe('test'); 757 | const password = screen.getByLabelText('password') as HTMLInputElement; 758 | expect(password.value).toBe('password'); 759 | }); 760 | it('should display min length error when password is invalid', async () => { 761 | fireEvent.input(screen.getByLabelText('email'), { 762 | target: { 763 | value: 'test@mail.com', 764 | }, 765 | }); 766 | 767 | fireEvent.input(screen.getByLabelText('password'), { 768 | target: { 769 | value: 'pass', 770 | }, 771 | }); 772 | 773 | fireEvent.submit(screen.getByRole('button')); 774 | 775 | expect(await screen.findByText('min length is 5')).not.toBeNull(); 776 | expect(mockSubmit).not.toBeCalled(); 777 | const email = screen.getByLabelText('email') as HTMLInputElement; 778 | expect(email.value).toBe('test@mail.com'); 779 | const password = screen.getByLabelText('password') as HTMLInputElement; 780 | expect(password.value).toBe('pass'); 781 | }); 782 | it('should not display error when value is valid', async () => { 783 | fireEvent.input(screen.getByLabelText('email'), { 784 | target: { 785 | value: 'test@mail.com', 786 | }, 787 | }); 788 | 789 | fireEvent.input(screen.getByLabelText('password'), { 790 | target: { 791 | value: 'password', 792 | }, 793 | }); 794 | 795 | fireEvent.submit(screen.getByRole('button')); 796 | 797 | // await for first one 798 | await waitFor(() => expect(screen.queryByText('Your email is required.')).toBeNull()); 799 | expect(screen.queryByText('Your email is required.')).toBeNull(); 800 | expect(screen.queryByText('Your password is required.')).toBeNull(); 801 | expect(screen.queryByText('Entered value does not match email format')).toBeNull(); 802 | expect(screen.queryByText('min length is 5')).toBeNull(); 803 | expect(screen.queryByText('Your select is required.')).toBeNull(); 804 | expect(screen.queryByText('Your multiselect is required.')).toBeNull(); 805 | 806 | await waitFor(() => expect(mockSubmit).toBeCalledWith('test@mail.com', 'password', false, 'v1', ['v2'])); 807 | }); 808 | }); 809 | describe('validate the form with default values', () => { 810 | const mockSubmit = vitest.fn((email, password, active, select, multiselect) => { 811 | // do nothing 812 | }); 813 | 814 | const onSubmit = ({ email, password, active, select, multiselect }) => { 815 | mockSubmit(email, password, active, select, multiselect); 816 | }; 817 | 818 | beforeEach(() => { 819 | render( 820 | 831 | 843 | 856 | 857 | 866 | 867 | 868 | 869 | 879 | 880 | 881 | 882 | 883 | 884 | , 885 | ); 886 | }); 887 | 888 | it('should not display error when value is valid', async () => { 889 | fireEvent.input(screen.getByLabelText('email'), { 890 | target: { 891 | value: 'test@mail.com', 892 | }, 893 | }); 894 | 895 | fireEvent.input(screen.getByLabelText('password'), { 896 | target: { 897 | value: 'password', 898 | }, 899 | }); 900 | fireEvent.input(screen.getByLabelText('select'), { 901 | target: { 902 | value: 'v2', 903 | }, 904 | }); 905 | 906 | fireEvent.submit(screen.getByRole('button')); 907 | 908 | // await for first one 909 | await waitFor(() => expect(screen.queryByText('Your email is required.')).toBeNull()); 910 | expect(screen.queryByText('Your email is required.')).toBeNull(); 911 | expect(screen.queryByText('Your password is required.')).toBeNull(); 912 | expect(screen.queryByText('Entered value does not match email format')).toBeNull(); 913 | expect(screen.queryByText('min length is 5')).toBeNull(); 914 | expect(screen.queryByText('Your select is required.')).toBeNull(); 915 | expect(screen.queryByText('Your multiselect is required.')).toBeNull(); 916 | 917 | await waitFor(() => expect(mockSubmit).toBeCalledWith('test@mail.com', 'password', true, 'v1', ['v1', 'v3'])); 918 | }); 919 | }); 920 | }); 921 | }); 922 | 923 | describe('isEmail', () => { 924 | it('should return false when passed object is not an email', () => { 925 | expect(isEmail('foo')).toEqual(false); 926 | expect(isEmail('123foo')).toEqual(false); 927 | expect(isEmail('foo123foo')).toEqual(false); 928 | expect(isEmail('foo123.fr')).toEqual(false); 929 | expect(isEmail('foo123@me')).toEqual(false); 930 | expect(isEmail({})).toEqual(false); 931 | expect(isEmail([10])).toEqual(false); 932 | expect(isEmail(true)).toEqual(false); 933 | expect(isEmail('evan.sharp@availity')).toEqual(false); 934 | expect(isEmail('evan.sharp@')).toEqual(false); 935 | expect(isEmail('@availity.com')).toEqual(false); 936 | expect(isEmail('evan.sharp@.com')).toEqual(false); 937 | expect(isEmail('evan.sharp')).toEqual(false); 938 | expect(isEmail('availity.com')).toEqual(false); 939 | expect(isEmail('Evan@Sharp@Availity.com')).toEqual(false); 940 | }); 941 | it('should return true when passed object is an email or undefined', () => { 942 | expect(isEmail(false)).toEqual(true); 943 | expect(isEmail('')).toEqual(true); 944 | expect(isEmail([])).toEqual(true); 945 | expect(isEmail(null)).toEqual(true); 946 | expect(isEmail(undefined)).toEqual(true); 947 | expect(isEmail('me@me.com')).toEqual(true); 948 | expect(isEmail('evan.sharp@availity.com')).toEqual(true); 949 | expect(isEmail('evan.sharp+more-things@availity.com')).toEqual(true); 950 | expect(isEmail('evan.sharp@availity.com.co')).toEqual(true); 951 | expect(isEmail('evan.sharp@development.availity.com')).toEqual(true); 952 | expect(isEmail('Evan.Sharp@Availity.com')).toEqual(true); 953 | }); 954 | }); 955 | -------------------------------------------------------------------------------- /src/form/validated-form.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | /* eslint-disable @typescript-eslint/no-unsafe-member-access */ 20 | /* eslint-disable @typescript-eslint/no-unsafe-assignment */ 21 | import React from 'react'; 22 | import { ReactElement, useEffect, useState } from 'react'; 23 | import { 24 | DefaultValues, 25 | FieldError, 26 | FieldValues, 27 | RegisterOptions, 28 | SubmitHandler, 29 | useForm, 30 | UseFormRegister, 31 | UseFormSetValue, 32 | ValidationMode, 33 | } from 'react-hook-form'; 34 | import { Button, Col, Form, FormFeedback, FormGroup, Input, InputProps, Label, Row } from 'reactstrap'; 35 | 36 | import { byteSize, isEmpty, openFile, setFileData } from '../util'; 37 | 38 | export interface ValidatedFormProps { 39 | children: React.ReactNode; 40 | onSubmit: SubmitHandler; 41 | defaultValues?: DefaultValues; 42 | mode?: keyof ValidationMode; 43 | [key: string]: any; 44 | } 45 | 46 | /** 47 | * A wrapper for simple validated forms using Reactstrap Form and React-hook-form. 48 | * The validated fields/inputs must be direct children of the form. 49 | * This components injects methods and values from react-hook-form's `useForm` hook into the ValidatedField/ValidatedInput components 50 | * For complex use cases or for nested children, use Reactstrap form elements 51 | * or ValidatedField or ValidatedInput and pass methods and values from react-hook-form's `useForm` hook 52 | * directly as props 53 | * 54 | * @param ValidatedFormProps 55 | * @returns React.JSX.Element 56 | */ 57 | export function ValidatedForm({ defaultValues, children, onSubmit, mode, ...rest }: ValidatedFormProps): React.JSX.Element { 58 | const { 59 | handleSubmit, 60 | register, 61 | reset, 62 | setValue, 63 | formState: { errors, touchedFields, dirtyFields }, 64 | } = useForm({ mode: mode || 'onTouched', defaultValues }); 65 | 66 | useEffect(() => { 67 | reset(defaultValues); 68 | }, [reset, defaultValues]); 69 | 70 | return ( 71 |
72 | {React.Children.map(children, (child: ReactElement) => { 73 | const props: any = child?.props; 74 | const type = child?.type as any; 75 | const isValidated = type && props?.name && ['ValidatedField', 'ValidatedInput', 'ValidatedBlobField'].includes(type.displayName); 76 | 77 | if (isValidated) { 78 | const childName = props.name; 79 | const elem = { 80 | ...props, 81 | register: props.register || register, 82 | error: props.error || errors[childName], 83 | isTouched: typeof props.isTouched === 'undefined' ? touchedFields[childName] : props.isTouched, 84 | isDirty: typeof props.isDirty === 'undefined' ? dirtyFields[childName] : props.isDirty, 85 | key: childName, 86 | }; 87 | if (type.displayName === 'ValidatedBlobField') { 88 | const defaultValue = defaultValues[childName]; 89 | const defaultContentType = defaultValues[`${childName}ContentType`]; 90 | elem.setValue = typeof props.setValue === 'undefined' ? setValue : props.setValue; 91 | elem.defaultValue = typeof props.defaultValue === 'undefined' ? defaultValue : props.defaultValue; 92 | elem.defaultContentType = typeof props.defaultContentType === 'undefined' ? defaultContentType : props.defaultContentType; 93 | } 94 | return React.createElement(type, { ...elem }); 95 | } 96 | return child; 97 | })} 98 |
99 | ); 100 | } 101 | 102 | ValidatedForm.displayName = 'ValidatedForm'; 103 | 104 | export interface ValidatedInputProps extends InputProps { 105 | // name of the component, also used for validation 106 | name: string; 107 | // register function from react-hook-form 108 | register?: UseFormRegister; 109 | // error object from react-hook-form for the field, errors[fieldsName] 110 | error?: FieldError; 111 | // isTouched from react-hook-form for the field, touchedFields[fieldsName] 112 | isTouched?: boolean; 113 | // isDirty from react-hook-form for the field, dirtyFields[fieldsName] 114 | isDirty?: boolean; 115 | // validation rules for react-hook-form register function 116 | validate?: RegisterOptions; 117 | // value for the input element 118 | value?: any; 119 | // default value for the Input component, not needed if defaultValues for ValidatedForm is set 120 | defaultValue?: string | number | string[]; 121 | } 122 | 123 | export interface ValidatedFieldProps extends ValidatedInputProps { 124 | // label for the field 125 | label?: string; 126 | // className for label 127 | labelClass?: string; 128 | // hide the label 129 | labelHidden?: boolean; 130 | // Field is a column inside a row 131 | row?: boolean; 132 | // objet holding attributes for the rendered column in row mode 133 | col?: any; 134 | // field is checkbox. The input will be rendered before the label 135 | check?: boolean; 136 | // css class for the input element 137 | inputClass?: string; 138 | // tag attribute for input 139 | inputTag?: React.ElementType; 140 | } 141 | 142 | /** 143 | * A utility wrapper over Reactstrap Input component thats uses react-hook-form data to 144 | * show error message and error/validated styles. 145 | * This component can be used with ValidatedForm 146 | * 147 | * @param ValidatedInputProps 148 | * @returns React.JSX.Element 149 | */ 150 | export function ValidatedInput({ 151 | name, 152 | id = name, 153 | register, 154 | error, 155 | isTouched, 156 | isDirty, 157 | validate, 158 | children, 159 | className, 160 | onChange, 161 | onBlur, 162 | ...attributes 163 | }: ValidatedInputProps): React.JSX.Element { 164 | if (!register) { 165 | return ( 166 | 167 | {children} 168 | 169 | ); 170 | } 171 | 172 | className = className || ''; 173 | className = isTouched ? `${className} is-touched` : className; 174 | className = isDirty ? `${className} is-dirty` : className; 175 | 176 | const { name: registeredName, onBlur: onBlurValidate, onChange: onChangeValidate, ref } = register(name, validate); 177 | return ( 178 | <> 179 | { 187 | void onChangeValidate(e); 188 | onChange && onChange(e); 189 | }} 190 | onBlur={e => { 191 | void onBlurValidate(e); 192 | onBlur && onBlur(e); 193 | }} 194 | {...attributes} 195 | > 196 | {children} 197 | 198 | {error && {error.message}} 199 | 200 | ); 201 | } 202 | 203 | ValidatedInput.displayName = 'ValidatedInput'; 204 | 205 | /** 206 | * A utility wrapper over Reactstrap FormGroup + Label + ValidatedInput 207 | * that uses react-hook-form data to show error message and error/validated styles. 208 | * This component can be used with ValidatedForm 209 | * 210 | * @param ValidatedFieldProps 211 | * @returns React.JSX.Element 212 | */ 213 | export function ValidatedField({ 214 | children, 215 | name, 216 | id, 217 | disabled, 218 | className, 219 | check, 220 | row, 221 | col, 222 | tag, 223 | label, 224 | labelClass, 225 | labelHidden, 226 | inputClass, 227 | inputTag, 228 | hidden, 229 | ...attributes 230 | }: ValidatedFieldProps): React.JSX.Element { 231 | const input = ( 232 | 235 | ); 236 | 237 | const inputRow = row ? {input} : input; 238 | return ( 239 | 248 | ); 249 | } 250 | 251 | ValidatedField.displayName = 'ValidatedField'; 252 | 253 | interface ValidatedBlobFieldProps extends ValidatedFieldProps { 254 | // set value function from react-hook-forms 255 | setValue?: UseFormSetValue<{ 256 | [x: string]: any; 257 | }>; 258 | // default value for the blob content type 259 | defaultContentType?: string; 260 | // blob is an image 261 | isImage?: boolean; 262 | // style for image element 263 | imageStyle?: Record; 264 | // css class for image 265 | imageClassName?: string; 266 | // clear button override 267 | clearBtn?: (clearBlob: () => void) => React.ReactElement; 268 | // label for open action for non image blobs 269 | openActionLabel?: string; 270 | } 271 | 272 | /** 273 | * A utility wrapper over Reactstrap FormGroup + Label + Input for blobs and images 274 | * that uses react-hook-form data to show error message and error/validated styles. 275 | * This component can be used with ValidatedForm 276 | * 277 | * @param ValidatedBlobFieldProps 278 | * @returns React.JSX.Element 279 | */ 280 | export function ValidatedBlobField({ 281 | name, 282 | register, 283 | setValue, 284 | error, 285 | isTouched, 286 | isDirty, 287 | validate, 288 | children, 289 | className, 290 | onChange, 291 | onBlur, 292 | id = name, 293 | disabled, 294 | row, 295 | col, 296 | tag, 297 | label, 298 | labelClass, 299 | labelHidden, 300 | inputClass, 301 | inputTag, 302 | hidden, 303 | defaultValue, 304 | defaultContentType, 305 | isImage, 306 | imageStyle, 307 | imageClassName, 308 | clearBtn, 309 | openActionLabel, 310 | // will be ignored as type will always be `file` 311 | type, 312 | check, 313 | ...attributes 314 | }: ValidatedBlobFieldProps): React.JSX.Element { 315 | const [blob, setBlobData] = useState(defaultValue as string); 316 | const [blobContentType, setBlobContentType] = useState(defaultContentType); 317 | 318 | const contentTypeName = `${name}ContentType`; 319 | 320 | const setBlobValue = (data, contentType) => { 321 | setBlobData(data); 322 | setBlobContentType(contentType); 323 | setValue(contentTypeName, contentType, { 324 | shouldValidate: true, 325 | shouldDirty: true, 326 | }); 327 | setValue(name, data, { 328 | shouldValidate: true, 329 | shouldDirty: true, 330 | }); 331 | }; 332 | const clearBlob = () => { 333 | setBlobValue(null, null); 334 | }; 335 | 336 | const renderFormGroup = inner => ( 337 | 345 | ); 346 | 347 | const inputRow = input => (row ? {input} : input); 348 | 349 | if (!register) { 350 | return renderFormGroup( 351 | inputRow(), 352 | ); 353 | } 354 | 355 | className = className || ''; 356 | className = isTouched ? `${className} is-touched` : className; 357 | className = isDirty ? `${className} is-dirty` : className; 358 | 359 | useEffect(() => { 360 | register(name, validate); 361 | register(contentTypeName, validate); 362 | }, [register]); 363 | 364 | const input = ( 365 | <> 366 | 367 | { 375 | setFileData( 376 | e, 377 | (contentType, data) => { 378 | setBlobValue(data, contentType); 379 | }, 380 | isImage, 381 | ); 382 | onChange && onChange(e); 383 | }} 384 | onBlur={e => { 385 | setFileData( 386 | e, 387 | (contentType, data) => { 388 | setBlobValue(data, contentType); 389 | }, 390 | isImage, 391 | ); 392 | onBlur && onBlur(e); 393 | }} 394 | {...attributes} 395 | /> 396 | {error && {error.message}} 397 | 398 | ); 399 | 400 | const defaultClearBtn = ( 401 | 404 | ); 405 | 406 | return renderFormGroup( 407 | <> 408 |
409 | {blob ? ( 410 |
411 | {blobContentType ? ( 412 | 413 | {isImage ? ( 414 | 419 | ) : ( 420 | openActionLabel || 'Open' 421 | )} 422 | 423 | ) : null} 424 |
425 | 426 | 427 | 428 | {blobContentType}, {byteSize(blob)} 429 | 430 | 431 | 432 | {clearBtn ? clearBtn(clearBlob) : defaultClearBtn} 433 | 434 | 435 |
436 | ) : null} 437 | {inputRow(input)} 438 | , 439 | ); 440 | } 441 | 442 | ValidatedBlobField.displayName = 'ValidatedBlobField'; 443 | 444 | const EMAIL_REGEXP = 445 | /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i; 446 | 447 | export function isEmail(value) { 448 | if (isEmpty(value)) return true; 449 | 450 | return EMAIL_REGEXP.test(value); 451 | } 452 | -------------------------------------------------------------------------------- /src/formatter/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | export * from './text-format'; 20 | -------------------------------------------------------------------------------- /src/formatter/text-format.spec.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | import { beforeAll, describe, expect, it } from 'vitest'; 5 | import React from 'react'; 6 | import dayjs from 'dayjs'; 7 | import { render } from '@testing-library/react'; 8 | import numeral from 'numeral'; 9 | import 'numeral/locales'; // load numeral-js locale data 10 | 11 | import { TextFormat } from './index'; 12 | describe('text-format component', () => { 13 | // All tests will go here 14 | describe('date format', () => { 15 | it('Should return Invalid Date in text when value is invalid', async () => { 16 | const { findByText } = render(); 17 | expect(await findByText('Invalid Date')).not.toBeNull(); 18 | }); 19 | it('Should return blank when value is invalid and blankOnInvalid is true', () => { 20 | const { container } = render(); 21 | expect(container.firstChild).toBeNull(); 22 | }); 23 | it('Should return default formatted date for valid date', () => { 24 | const d = new Date(); 25 | const node = render(); 26 | expect(node.findByText(dayjs(d).format())).not.toBeNull(); 27 | }); 28 | it('Should return formatted date for valid date and format', () => { 29 | const d = new Date(); 30 | const node = render(); 31 | expect(node.findByText(dayjs(d).format('DD MM YY'))).not.toBeNull(); 32 | }); 33 | describe('using locales and formats', () => { 34 | const locales = ['en', 'it', 'de', 'fr', 'sk', 'tr', 'vi']; // a sample of locales 35 | const formats = ['ddd', 'dddd', 'MMM', 'MMMM']; // short and long textual formats of days and months 36 | locales.forEach(locale => { 37 | formats.forEach(format => { 38 | it(`Should return a valid date formatted with format '${format}' in '${locale}'`, () => { 39 | const d = new Date(); 40 | const node = render(); 41 | expect(node.findByText(dayjs(d).locale(locale).format(format))).not.toBeNull(); 42 | }); 43 | }); 44 | }); 45 | }); 46 | }); 47 | describe('number format', () => { 48 | it('Should return 0 in text when value is invalid', () => { 49 | const node = render(); 50 | expect(node.findByText('0')).not.toBeNull(); 51 | }); 52 | it('Should return blank when value is invalid and blankOnInvalid is true', () => { 53 | const { container } = render(); 54 | expect(container.firstChild).toBeNull(); 55 | }); 56 | it('Should return default formatted number for valid number', () => { 57 | const n = 100000; 58 | const node = render(); 59 | expect(node.findByText('100,000')).not.toBeNull(); 60 | }); 61 | it('Should return formatted number for valid number and format', () => { 62 | const n = 100000.1234; 63 | const node = render(); 64 | expect(node.findByText('100,000.12')).not.toBeNull(); 65 | }); 66 | // a sample of locales 67 | ['en', 'it', 'de', 'fr', 'sk', 'tr', 'vi'].forEach(locale => { 68 | describe(`using locale: '${locale}'`, () => { 69 | beforeAll(() => numeral.locale(locale)); 70 | 71 | // currency and ordinal textual formats 72 | ['$0,0.00', '$ 0,0[.]00'].forEach(format => { 73 | it(`Should return a number formatted with format '${format}' in '${locale}'`, () => { 74 | const n = 100000.1234; 75 | const node = render(); 76 | expect(node.findByText(numeral(n).format(format))).not.toBeNull(); 77 | }); 78 | }); 79 | }); 80 | }); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /src/formatter/text-format.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | import React from 'react'; 20 | import numeral from 'numeral'; 21 | import dayjs from 'dayjs'; 22 | import TranslatorContext from '../language/translator-context'; 23 | import 'numeral/locales'; 24 | 25 | export type ITextFormatTypes = 'date' | 'number'; 26 | 27 | export interface ITextFormatProps { 28 | value: string | number | Date; 29 | type: ITextFormatTypes; 30 | format?: string; 31 | blankOnInvalid?: boolean; 32 | locale?: string; 33 | } 34 | 35 | /** 36 | * Formats the given value to specified type like date or number. 37 | * @param value value to be formatted 38 | * @param type type of formatting to use ${ITextFormatTypes} 39 | * @param format optional format to use. 40 | * For date type dayjs(https://day.js.org/docs/en/display/format) format is used 41 | * For number type NumeralJS (http://numeraljs.com/#format) format is used 42 | * @param blankOnInvalid optional to output error or blank on null/invalid values 43 | * @param locale optional locale in which to format value or current locale from TranslatorContext 44 | */ 45 | export const TextFormat = ({ value, type, format, blankOnInvalid, locale }: ITextFormatProps) => { 46 | if (blankOnInvalid) { 47 | if (!value || !type) return null; 48 | } 49 | 50 | if (!locale) { 51 | // TODO: find a better way to keep track of *current* locale 52 | locale = TranslatorContext.context.locale; 53 | 54 | if (!numeral.locales[locale]) { 55 | // if not include, by default as en 56 | numeral.locale('en'); 57 | } else { 58 | numeral.locale(locale); 59 | } 60 | } 61 | 62 | if (type === 'date') { 63 | return {locale ? dayjs(value).locale(locale).format(format) : dayjs(value).format(format)}; 64 | } else if (type === 'number') { 65 | return {numeral(value).format(format)}; 66 | } 67 | return {value.toString()}; 68 | }; 69 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017-2025 the original author or authors from the JHipster project. 3 | 4 | This file is part of the JHipster project, see https://www.jhipster.tech/ 5 | for more information. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | */ 19 | export * from './language'; 20 | export * from './util'; 21 | export * from './component'; 22 | export * from './form'; 23 | export * from './formatter'; 24 | export * from './type'; 25 | -------------------------------------------------------------------------------- /src/language/index.ts: -------------------------------------------------------------------------------- 1 | import Translate, { translate } from './translate'; 2 | import TranslatorContext from './translator-context'; 3 | 4 | export { translate }; 5 | export { Translate }; 6 | export { TranslatorContext }; 7 | -------------------------------------------------------------------------------- /src/language/translate.spec.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; 5 | import React from 'react'; 6 | import { render } from '@testing-library/react'; 7 | 8 | import { Translate, translate, TranslatorContext } from './index'; 9 | describe('Translate', () => { 10 | describe('without translations', () => { 11 | it('renders nothing when no translations are not loaded', () => { 12 | const { container } = render(); 13 | expect(container.querySelector('span').innerHTML).toBe(''); 14 | }); 15 | }); 16 | 17 | describe('with translation', () => { 18 | beforeAll(() => { 19 | TranslatorContext.registerTranslations('en', { 20 | foo: { 21 | bar: 'i18n text', 22 | fooz: 'text {{foo }} this {{bar}}', 23 | foofoo: 'text {{ foo}} this {{bar}} test', 24 | foodirty: 'text {{ foo }} this {{bar}}

test
link', 25 | 'baz.foo': 'dirty key', 26 | foozfooz: 'jhipster is awesome!', 27 | 'bar1.bar2': { 28 | bar3: 'bar123', 29 | }, 30 | bar4: { 31 | 'bar5.bar6': 'bar456', 32 | }, 33 | bar7: { 34 | 'bar8.bar9': { 35 | 'bar10.bar11': 'bar7891011', 36 | }, 37 | }, 38 | barfalsy: { 39 | empty: '', 40 | zero: 0, 41 | false: false, 42 | }, 43 | }, 44 | }); 45 | TranslatorContext.registerTranslations('fr', { 46 | foo: { 47 | bar: 'i18n text fr', 48 | fooz: 'text {{foo}} this {{bar}} fr', 49 | }, 50 | }); 51 | }); 52 | 53 | beforeEach(() => { 54 | TranslatorContext.setLocale('en'); 55 | }); 56 | // All tests will go here 57 | it('renders child content when key is invalid and renderInnerTextForMissingKeys is true', () => { 58 | const { container } = render(def text); 59 | const span = container.querySelector('span'); 60 | expect(span.innerHTML).toBe('def text'); 61 | }); 62 | it('renders key-missing message when child content is null & key is invalid', () => { 63 | const { container } = render(); 64 | const span = container.querySelector('span'); 65 | expect(span.innerHTML).toBe('translation-not-found[foo.baz]'); 66 | }); 67 | it('renders key-missing message when key is invalid & renderInnerTextForMissingKeys is false', () => { 68 | TranslatorContext.setRenderInnerTextForMissingKeys(false); 69 | const { container } = render(def text); 70 | const span = container.querySelector('span'); 71 | expect(span.innerHTML).toBe('translation-not-found[foo.baz]'); 72 | }); 73 | it('renders key-missing message when key is invalid & interpolate argument given', () => { 74 | const { container } = render( 75 | 76 | def text 77 | , 78 | ); 79 | const span = container.querySelector('span'); 80 | expect(span.innerHTML).toBe('translation-not-found[foo.baz]'); 81 | }); 82 | it('renders a default span with translated content', () => { 83 | const { container } = render(); 84 | const span = container.querySelector('span'); 85 | expect(span.innerHTML).toBe('i18n text'); 86 | }); 87 | it('renders a default span with translated content for dirty key 1', () => { 88 | const { container } = render(); 89 | const span = container.querySelector('span'); 90 | expect(span.innerHTML).toBe('dirty key'); 91 | }); 92 | it('renders a default span with translated content for dirty key 2', () => { 93 | const { container } = render(); 94 | const span = container.querySelector('span'); 95 | expect(span.innerHTML).toBe('bar123'); 96 | }); 97 | it('renders a default span with translated content for dirty key 3', () => { 98 | const { container } = render(); 99 | const span = container.querySelector('span'); 100 | expect(span.innerHTML).toBe('bar456'); 101 | }); 102 | it('renders a default span with translated content for dirty key 4', () => { 103 | const { container } = render(); 104 | const span = container.querySelector('span'); 105 | expect(span.innerHTML).toBe('bar7891011'); 106 | }); 107 | it('renders a provided component with translated content', () => { 108 | const { container } = render(); 109 | const span = container.querySelector('h1'); 110 | expect(span.innerHTML).toBe('i18n text'); 111 | }); 112 | it('renders a provided component with translated & interpolated content', () => { 113 | const { container } = render(); 114 | const span = container.querySelector('h1'); 115 | expect(span.innerHTML).toBe('text FOO this BAR'); 116 | }); 117 | it('renders a provided component with translated & interpolated content with html', () => { 118 | const { container } = render(); 119 | const span = container.querySelector('h1'); 120 | expect(span.innerHTML).toBe('text FOO this BAR test'); 121 | }); 122 | it('renders a provided component with translated, sanitized & interpolated content', () => { 123 | const { container } = render(); 124 | const span = container.querySelector('h1'); 125 | expect(span.innerHTML).toBe('text FOO this BAR

test link'); 126 | }); 127 | it('renders a default span with translated content with new locale', () => { 128 | TranslatorContext.setLocale('fr'); 129 | const { container } = render(); 130 | const span = container.querySelector('span'); 131 | expect(span.innerHTML).toBe('i18n text fr'); 132 | }); 133 | 134 | it('renders a default span with translated content for empty string', () => { 135 | const { container } = render(); 136 | const span = container.querySelector('span'); 137 | expect(span.innerHTML).toBe(''); 138 | }); 139 | 140 | it('renders a default span with translated content for number 0', () => { 141 | const { container } = render(); 142 | const span = container.querySelector('span'); 143 | expect(span.innerHTML).toBe('0'); 144 | }); 145 | 146 | it('renders a default span with translated content for boolean false', () => { 147 | const { container } = render(); 148 | const span = container.querySelector('span'); 149 | expect(span.innerHTML).toBe('false'); 150 | }); 151 | }); 152 | }); 153 | 154 | describe('translate service', () => { 155 | beforeEach(() => { 156 | TranslatorContext.setLocale('en'); 157 | }); 158 | 159 | it('produce translated content', () => { 160 | const out = translate('foo.bar'); 161 | expect(out).toBe('i18n text'); 162 | }); 163 | 164 | it('produce translated React component', () => { 165 | const { container } = render(translate('foo.foozfooz')); 166 | const span = container.querySelector('span'); 167 | expect(span.innerHTML).toBe('jhipster is awesome!'); 168 | }); 169 | }); 170 | -------------------------------------------------------------------------------- /src/language/translate.tsx: -------------------------------------------------------------------------------- 1 | import React, { Fragment } from 'react'; 2 | import get from 'lodash/get'; 3 | import sanitizeHtml from 'sanitize-html'; 4 | import TranslatorContext from './translator-context'; 5 | 6 | export interface ITranslateProps { 7 | contentKey: string; 8 | children?: string | React.JSX.Element | Array; 9 | interpolate?: any; 10 | component?: string; 11 | } 12 | 13 | const REACT_ELEMENT = Symbol.for('react.element'); 14 | 15 | const isFlattenable = value => { 16 | const type = typeof value; 17 | return type === 'string' || type === 'number'; 18 | }; 19 | 20 | const flatten = array => { 21 | if (array.every(isFlattenable)) { 22 | return array.join(''); 23 | } 24 | return array; 25 | }; 26 | 27 | const toTemplate = string => { 28 | const expressionRe = /{{\s?\w+\s?}}/g; 29 | const match = string.match(expressionRe) || []; 30 | return [string.split(expressionRe), ...match]; 31 | }; 32 | 33 | const normalizeValue = (value, key) => { 34 | if (value == null || ['boolean', 'string', 'number'].includes(typeof value)) { 35 | return value; 36 | } 37 | if (value.$$typeof === REACT_ELEMENT) { 38 | return React.cloneElement(value, { key }); 39 | } 40 | }; 41 | 42 | const isNullOrUndefined = (value: any) => value === null || value === undefined; 43 | 44 | /** 45 | * Adapted from https://github.com/bloodyowl/react-translate 46 | * licenced under The MIT License (MIT) Copyright (c) 2014 Matthias Le Brun 47 | */ 48 | const render = (string, values) => { 49 | if (!values || !string) return string; 50 | const [parts, ...expressions] = toTemplate(string); 51 | return flatten( 52 | parts.reduce((acc, item, index, array) => { 53 | if (index === array.length - 1) { 54 | return [...acc, item]; 55 | } 56 | const match = expressions[index] && expressions[index].match(/{{\s?(\w+)\s?}}/); 57 | const value = match != null ? values[match[1]] : null; 58 | return [...acc, item, normalizeValue(value, index)]; 59 | }, []), 60 | ); 61 | }; 62 | 63 | /** 64 | * Fill the variable allPaths with all possible paths for a given paths 65 | * @param paths: inits with the classic paths and changes value in the recursive method 66 | * ex: ['foo', 'bar1', 'bar2', 'bar3'] 67 | * @param start: helps to store paths 68 | * ex: [] 69 | * @param firstCall: uses to detect the first call to this recursive function 70 | * ex: true 71 | * @param originPaths: references the first value of the variable paths 72 | * ex: ['foo', 'bar1', 'bar2', 'bar3'] 73 | * @param allPaths: stores all the possibles paths 74 | * ex: [] => ... => [ ['foo', 'bar1', 'bar2', 'bar3'], ['foo.bar1', 'bar2', 'bar3']], ['foo.bar1.bar2', 'bar3'], ... ] 75 | */ 76 | const searchAllPaths = (paths, start, firstCall, originPaths, allPaths) => { 77 | if (firstCall || paths.length < originPaths.length) { 78 | const clonePaths: string[] = Array.from(paths); 79 | let acc = ''; 80 | for (let i = 0; i < paths.length; ++i) { 81 | acc === '' ? (acc = paths[i]) : (acc += `.${paths[i]}`); 82 | clonePaths.shift(); 83 | allPaths.push(start.concat([acc]).concat(clonePaths)); 84 | searchAllPaths(clonePaths, start.concat([acc]), false, originPaths, allPaths); 85 | } 86 | } 87 | }; 88 | 89 | /** 90 | * A dirty find to split non standard keys and find data from json 91 | * @param obj json object 92 | * @param path path to find 93 | */ 94 | const deepFindDirty = (obj, path) => { 95 | const paths = path.split('.'); 96 | let current = obj; 97 | let trad = undefined; 98 | const HASHTAG = '#'; 99 | const allPaths = []; 100 | const allPathsWithoutDuplicate = []; 101 | const originPaths = paths; 102 | // Fill allPaths possibles 103 | searchAllPaths(paths, [], true, originPaths, allPaths); 104 | const setAllPaths = new Set( 105 | allPaths.map(p => { 106 | return p.join(HASHTAG); 107 | }), 108 | ); 109 | // Delete duplicates 110 | setAllPaths.forEach((v1, v2, values) => { 111 | return allPathsWithoutDuplicate.push(v2.split(HASHTAG)); 112 | }); 113 | // Test all possibles paths while traduction is not found 114 | for (let j = 0; j < allPathsWithoutDuplicate.length; ++j) { 115 | if (trad === undefined) { 116 | // Test a path 117 | for (let i = 0; i < allPaths[j].length; ++i) { 118 | if (current[allPaths[j][i]] === undefined) { 119 | current = undefined; 120 | break; 121 | } 122 | current = current[allPaths[j][i]]; 123 | } 124 | if (current !== undefined) { 125 | // Traduction found 126 | trad = current; 127 | break; 128 | } 129 | } 130 | // Search with an other path 131 | current = obj; 132 | } 133 | return trad; 134 | }; 135 | 136 | const showMissingOrDefault = (key, children) => { 137 | const renderInnerTextForMissingKeys = TranslatorContext.context.renderInnerTextForMissingKeys; 138 | if (renderInnerTextForMissingKeys && children && ['string', 'object'].includes(typeof children)) { 139 | return children; 140 | } 141 | return `${TranslatorContext.context.missingTranslationMsg}[${key}]`; 142 | }; 143 | 144 | const doTranslate = (key, interpolate, children) => { 145 | const translationData = TranslatorContext.context.translations; 146 | const currentLocale = TranslatorContext.context.locale || TranslatorContext.context.defaultLocale; 147 | const data = translationData[currentLocale]; 148 | 149 | // If there is no translation data, it means it hasn’t loaded yet, so return no content 150 | if (!Object.keys(translationData).length) { 151 | return { 152 | content: null, 153 | }; 154 | } 155 | 156 | let preRender = data ? get(data, key) || deepFindDirty(data, key) : null; 157 | preRender = typeof preRender === 'boolean' || typeof preRender === 'number' ? preRender.toString() : preRender; 158 | const renderedValue = render(preRender, interpolate); 159 | 160 | const preSanitize = !isNullOrUndefined(renderedValue) ? renderedValue : showMissingOrDefault(key, children); 161 | 162 | if (preSanitize === false || /<[a-z][\s\S]*>/i.test(preSanitize)) { 163 | // String contains HTML tags. Allow only a super restricted set of tags and attributes 164 | const preSanitizeArray = Array.isArray(preSanitize) ? preSanitize : [preSanitize]; 165 | const content = preSanitizeArray.map(part => 166 | part.$$typeof === REACT_ELEMENT 167 | ? part 168 | : sanitizeHtml(part, { 169 | allowedTags: ['b', 'i', 'em', 'strong', 'a', 'br', 'hr'], 170 | allowedAttributes: { 171 | a: ['href', 'target'], 172 | }, 173 | }), 174 | ); 175 | 176 | return { 177 | content, 178 | html: true, 179 | }; 180 | } 181 | return { 182 | content: preSanitize, 183 | html: false, 184 | }; 185 | }; 186 | 187 | /** 188 | * Translates the given key using provided i18n values 189 | */ 190 | class Translate extends React.Component { 191 | static defaultProps = { 192 | component: 'span', 193 | }; 194 | 195 | constructor(props) { 196 | super(props); 197 | this.state = { lastChange: null }; 198 | } 199 | 200 | componentDidUpdate() { 201 | this.setState({ lastChange: TranslatorContext.context.lastChange }); 202 | } 203 | 204 | shouldComponentUpdate(nextProps, nextState) { 205 | return nextState.lastChange !== TranslatorContext.context.lastChange || nextProps.interpolate !== this.props.interpolate; 206 | } 207 | 208 | render() { 209 | const { contentKey, interpolate, component, children } = this.props; 210 | const processed = doTranslate(contentKey, interpolate, children); 211 | if (processed.html) { 212 | const contentArray = Array.isArray(processed.content) ? processed.content : [processed.content]; 213 | return contentArray.map((content, i) => 214 | content.$$typeof === REACT_ELEMENT 215 | ? { ...content, key: i } 216 | : React.createElement(component, { key: i, dangerouslySetInnerHTML: { __html: content } }), 217 | ); 218 | } 219 | return React.createElement(component, null, processed.content); 220 | } 221 | } 222 | 223 | export const translate = (contentKey: string, interpolate?: any, children?: string) => { 224 | const translation = doTranslate(contentKey, interpolate, children); 225 | 226 | if (translation.html) { 227 | const contentArray = Array.isArray(translation.content) ? translation.content : [translation.content]; 228 | const processedContent = contentArray.map((content, i) => 229 | content.$$typeof === REACT_ELEMENT 230 | ? { ...content, key: i } 231 | : React.createElement('span', { key: i, dangerouslySetInnerHTML: { __html: content } }), 232 | ); 233 | return processedContent.length === 1 ? processedContent[0] : {processedContent}; 234 | } else { 235 | return translation.content; 236 | } 237 | }; 238 | 239 | export default Translate; 240 | -------------------------------------------------------------------------------- /src/language/translator-context.spec.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | import { beforeEach, describe, expect, it } from 'vitest'; 5 | import { TranslatorContext } from './index'; 6 | 7 | const translation = { 8 | bar: 'i18n text', 9 | fooz: 'text {{foo }} this {{bar}}', 10 | foofoo: 'text {{ foo}} this {{bar}} test', 11 | }; 12 | 13 | const translationMerge = { 14 | foodirty: 'text {{ foo }} this {{bar}}

test
link', 15 | 'baz.foo': 'dirty key', 16 | foozfooz: 'jhipster is awesome!', 17 | }; 18 | 19 | describe('TranslateContext', () => { 20 | beforeEach(() => { 21 | TranslatorContext.context.translations['en'] = undefined; 22 | }); 23 | describe('without translations', () => { 24 | it('should not have translations', () => { 25 | expect(TranslatorContext.context.translations['en']).toBeUndefined(); 26 | }); 27 | }); 28 | 29 | describe('with translation', () => { 30 | beforeEach(() => { 31 | TranslatorContext.registerTranslations('en', translation); 32 | }); 33 | 34 | it('should match the translation', () => { 35 | expect(TranslatorContext.context.translations['en']).toMatchObject(expect.objectContaining(translation)); 36 | }); 37 | }); 38 | 39 | describe('with merged translation', () => { 40 | beforeEach(() => { 41 | TranslatorContext.registerTranslations('en', translation); 42 | TranslatorContext.registerTranslations('en', translationMerge); 43 | }); 44 | 45 | it('should match both translations', () => { 46 | expect(TranslatorContext.context.translations['en']).toMatchObject(expect.objectContaining(translation)); 47 | expect(TranslatorContext.context.translations['en']).toMatchObject(expect.objectContaining(translationMerge)); 48 | }); 49 | }); 50 | 51 | describe('with deeep merged translation', () => { 52 | beforeEach(() => { 53 | TranslatorContext.registerTranslations('en', { foo: { bar: { baz: 1 } } }); 54 | TranslatorContext.registerTranslations('en', { foo: { bar: { foz: 1 } } }); 55 | }); 56 | 57 | it('should match both translations', () => { 58 | expect(TranslatorContext.context.translations['en'].foo.bar.baz).toBe(1); 59 | expect(TranslatorContext.context.translations['en'].foo.bar.foz).toBe(1); 60 | }); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /src/language/translator-context.ts: -------------------------------------------------------------------------------- 1 | import merge from 'lodash/merge'; 2 | 3 | /** 4 | * Holder for translation content and locale 5 | */ 6 | 7 | class TranslatorContext { 8 | static context = { 9 | previousLocale: null, 10 | defaultLocale: null, 11 | locale: null, 12 | lastChange: new Date().getTime(), 13 | translations: {}, 14 | renderInnerTextForMissingKeys: true, 15 | missingTranslationMsg: 'translation-not-found', 16 | }; 17 | 18 | static change() { 19 | this.context.lastChange = new Date().getTime(); 20 | } 21 | 22 | static registerTranslations(locale: string, translation: any) { 23 | if (this.context.translations[locale]) { 24 | merge(this.context.translations[locale], translation); 25 | } else { 26 | this.context.translations[locale] = translation; 27 | } 28 | TranslatorContext.change(); 29 | } 30 | 31 | static setDefaultLocale(locale: string) { 32 | this.context.defaultLocale = locale; 33 | TranslatorContext.change(); 34 | } 35 | 36 | static setMissingTranslationMsg(msg: string) { 37 | this.context.missingTranslationMsg = msg; 38 | TranslatorContext.change(); 39 | } 40 | 41 | static setRenderInnerTextForMissingKeys(flag: boolean) { 42 | this.context.renderInnerTextForMissingKeys = flag; 43 | TranslatorContext.change(); 44 | } 45 | 46 | static setLocale(locale: string) { 47 | this.context.previousLocale = this.context.locale; 48 | this.context.locale = locale || this.context.defaultLocale; 49 | TranslatorContext.change(); 50 | } 51 | } 52 | 53 | export default TranslatorContext; 54 | -------------------------------------------------------------------------------- /src/type/index.ts: -------------------------------------------------------------------------------- 1 | export * from './redux-action.type'; 2 | -------------------------------------------------------------------------------- /src/type/redux-action.type.ts: -------------------------------------------------------------------------------- 1 | import { AxiosPromise } from 'axios'; 2 | 3 | export interface IPayload { 4 | type: string; 5 | payload: AxiosPromise; 6 | meta?: any; 7 | } 8 | export type IPayloadResult = (dispatch: any, getState?: any) => IPayload | Promise>; 9 | export type ICrudGetAction = (id: string | number) => IPayload | ((dispatch: any) => IPayload); 10 | export type ICrudGetAllAction = (page?: number, size?: number, sort?: string) => IPayload | ((dispatch: any) => IPayload); 11 | export type ICrudSearchAction = ( 12 | search?: string, 13 | page?: number, 14 | size?: number, 15 | sort?: string, 16 | ) => IPayload | ((dispatch: any) => IPayload); 17 | export type ICrudPutAction = (data?: T) => IPayload | IPayloadResult; 18 | export type ICrudDeleteAction = (id?: string | number) => IPayload | IPayloadResult; 19 | -------------------------------------------------------------------------------- /src/util/data-utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { size, byteSize } from './index'; 3 | 4 | describe('Data utils', () => { 5 | describe('size', () => { 6 | it('should return the correct size', () => { 7 | const data = 'Hello Jhipster'; 8 | expect(size(data)).toBe(10.5); 9 | expect(size('')).toBe(0); 10 | }); 11 | }); 12 | 13 | describe('byteSize', () => { 14 | it('should return the correct value', () => { 15 | const data = 'Hello Jhipster'; 16 | expect(byteSize(data)).toBe('10.5 bytes'); 17 | expect(byteSize('')).toBe('0 bytes'); 18 | }); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/util/data-utils.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | /* 4 | Copyright 2017-2025 the original author or authors from the JHipster project. 5 | This file is part of the JHipster project, see https://www.jhipster.tech/ 6 | for more information. 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | export const openFile = (contentType: string, data: string) => () => { 18 | const fileURL = `data:${contentType};base64,${data}`; 19 | const win = window.open(); 20 | win.document.write( 21 | '', 24 | ); 25 | }; 26 | 27 | const toBase64 = (file: File, cb: (v: string) => void) => { 28 | const fileReader: FileReader = new FileReader(); 29 | fileReader.readAsDataURL(file); 30 | fileReader.onload = e => { 31 | const { result } = e.target; 32 | // eslint-disable-next-line @typescript-eslint/no-base-to-string 33 | const resultString = typeof result === 'string' ? result : result.toString(); 34 | const base64Data = resultString.substring(resultString.indexOf('base64,') + 'base64,'.length); 35 | cb(base64Data); 36 | }; 37 | }; 38 | 39 | const paddingSize = (value: string): number => { 40 | if (value.endsWith('==')) { 41 | return 2; 42 | } 43 | if (value.endsWith('=')) { 44 | return 1; 45 | } 46 | return 0; 47 | }; 48 | 49 | const formatAsBytes = (sizeValue: number): string => sizeValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ') + ' bytes'; 50 | 51 | export const size = (value: string): number => (value.length / 4) * 3 - paddingSize(value); 52 | 53 | export const byteSize = (base64String: string) => formatAsBytes(size(base64String)); 54 | 55 | export const setFileData = ( 56 | event: React.ChangeEvent | React.FocusEvent, 57 | callback: (type: any, v: string) => void, 58 | isImage: boolean, 59 | ) => { 60 | const target = event?.target; 61 | if (target && target.files && target.files[0]) { 62 | const file = target.files[0]; 63 | if (isImage && !file.type.startsWith('image/')) { 64 | return; 65 | } 66 | 67 | toBase64(file, base64Data => { 68 | callback(file.type, base64Data); 69 | }); 70 | } else { 71 | callback('', ''); 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /src/util/dom-utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Fetch the specified element by id or return default 3 | * @param id id of element 4 | */ 5 | export const containerSize = (id = 'app-view-container') => document.getElementById(id) || { offsetHeight: 960, offsetWidth: 960 }; 6 | 7 | /** 8 | * Fetch the current window size 9 | */ 10 | export const windowSize = () => ({ width: window.innerWidth, height: window.innerHeight }); 11 | 12 | /** 13 | * Get the current browser locale 14 | */ 15 | export const browserLocale = (): string => { 16 | let lang; 17 | 18 | const nav: any = navigator; 19 | if (nav.languages && nav.languages.length) { 20 | // latest versions of Chrome and Firefox set this correctly 21 | lang = nav.languages[0]; 22 | } else if (nav.userLanguage) { 23 | // IE only 24 | lang = nav.userLanguage; 25 | } else { 26 | // latest versions of Chrome, Firefox, and Safari set this correctly 27 | lang = nav.language; 28 | } 29 | return lang; 30 | }; 31 | -------------------------------------------------------------------------------- /src/util/index.ts: -------------------------------------------------------------------------------- 1 | export * from './dom-utils'; 2 | export * from './log-util'; 3 | export * from './promise-utils'; 4 | export * from './storage-util'; 5 | export * from './url-utils'; 6 | export * from './data-utils'; 7 | export * from './number-utils'; 8 | -------------------------------------------------------------------------------- /src/util/log-util.ts: -------------------------------------------------------------------------------- 1 | export type LogLevelType = 'info' | 'error' | 'warn' | 'debug' | 'off'; 2 | 3 | const initLevels = (): LogLevelType => { 4 | if (process.env.LOG_LEVEL) return process.env.LOG_LEVEL as LogLevelType; 5 | 6 | return process.env.NODE_ENV === 'development' ? 'info' : 'error'; 7 | }; 8 | 9 | const level: LogLevelType = initLevels(); 10 | 11 | /** 12 | * Log a debug message when debug level or above is enabled 13 | * @param msg message 14 | * @param data data 15 | */ 16 | export const logDebug = (msg, ...data): void => { 17 | // eslint-disable-next-line no-console 18 | if (level === 'debug') console.debug(msg, data); 19 | }; 20 | 21 | /** 22 | * Log an info message when info level or above is enabled 23 | * @param msg message 24 | * @param data data 25 | */ 26 | export const logInfo = (msg, ...data): void => { 27 | // eslint-disable-next-line no-console 28 | if (['debug', 'info'].includes(level)) console.info(msg, data); 29 | }; 30 | 31 | /** 32 | * Log a warn message when warn level or above is enabled 33 | * @param msg message 34 | * @param data data 35 | */ 36 | export const logWarn = (msg, ...data): void => { 37 | if (['debug', 'info', 'warn'].includes(level)) console.warn(msg, data); 38 | }; 39 | 40 | /** 41 | * Log an error message when error level is enabled 42 | * @param msg message 43 | * @param data data 44 | */ 45 | export const logError = (msg, ...data): void => { 46 | if (['debug', 'info', 'warn', 'error'].includes(level)) console.error(msg, data); 47 | }; 48 | 49 | export const log = logInfo; 50 | -------------------------------------------------------------------------------- /src/util/number-utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { isNumber } from './index'; 3 | 4 | describe('Number util', () => { 5 | describe('isNumber', () => { 6 | it('should return false when passed object is not a number', () => { 7 | expect(isNumber('foo')).toEqual(false); 8 | expect(isNumber('123foo')).toEqual(false); 9 | expect(isNumber('foo123foo')).toEqual(false); 10 | expect(isNumber('foo123')).toEqual(false); 11 | expect(isNumber({})).toEqual(false); 12 | expect(isNumber([10])).toEqual(false); 13 | expect(isNumber(true)).toEqual(false); 14 | }); 15 | it('should return true when passed object is a number or undefined', () => { 16 | expect(isNumber(false)).toEqual(true); 17 | expect(isNumber('')).toEqual(true); 18 | expect(isNumber([])).toEqual(true); 19 | expect(isNumber(null)).toEqual(true); 20 | expect(isNumber(undefined)).toEqual(true); 21 | expect(isNumber(10)).toEqual(true); 22 | expect(isNumber(10.5)).toEqual(true); 23 | expect(isNumber(10_00.5_0)).toEqual(true); 24 | expect(isNumber('10')).toEqual(true); 25 | expect(isNumber('10.5')).toEqual(true); 26 | expect(isNumber('1000.50')).toEqual(true); 27 | expect(isNumber(Number.MIN_VALUE)).toEqual(true); 28 | expect(isNumber(Number.MAX_VALUE)).toEqual(true); 29 | expect(isNumber(Infinity)).toEqual(true); 30 | }); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /src/util/number-utils.ts: -------------------------------------------------------------------------------- 1 | export const nanToZero = (input: number) => (isNaN(input) ? 0 : input); 2 | 3 | export function isEmpty(value) { 4 | return ( 5 | typeof value === 'undefined' || 6 | value === null || 7 | (typeof value === 'string' && value.trim() === '') || 8 | value === false || 9 | (Array.isArray(value) && value.length === 0) 10 | ); 11 | } 12 | 13 | export function isNumber(value) { 14 | if (isEmpty(value)) return true; 15 | 16 | if ((typeof value === 'boolean' && value === true) || (Array.isArray(value) && value.length !== 0)) { 17 | return false; 18 | } 19 | 20 | value = Number(value); 21 | 22 | return typeof value === 'number' && !isNaN(value); 23 | } 24 | -------------------------------------------------------------------------------- /src/util/promise-utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { isPromise } from './index'; 3 | 4 | describe('Promise util', () => { 5 | describe('isPromise', () => { 6 | it('should return false when passed object is not promise like', () => { 7 | const inp = {}; 8 | expect(isPromise(inp)).toEqual(false); 9 | }); 10 | it('should return true when passed object is promise like', () => { 11 | const inp = Promise.resolve(true); 12 | expect(isPromise(inp)).toEqual(true); 13 | }); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/util/promise-utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Check if the passed object is a promise 3 | * @param value the object to check 4 | */ 5 | export const isPromise = (value): boolean => { 6 | if (value !== null && typeof value === 'object') { 7 | return value && typeof value.then === 'function'; 8 | } 9 | return false; 10 | }; 11 | -------------------------------------------------------------------------------- /src/util/storage-util.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @vitest-environment jsdom 3 | */ 4 | import { describe, expect, it } from 'vitest'; 5 | import { Storage, StorageType, getStorage } from './index'; 6 | 7 | describe('Storage Util', () => { 8 | describe('getStorage', () => { 9 | it('should return appropriate storage type', () => { 10 | let out = getStorage(StorageType.SESSION); 11 | expect(out).toEqual(window.sessionStorage); 12 | out = getStorage(StorageType.LOCAL); 13 | expect(out).toEqual(window.localStorage); 14 | }); 15 | }); 16 | describe('set', () => { 17 | it('should set key for correct storage type', () => { 18 | Storage.session.set('testKey', 'testVal'); 19 | let out = window.sessionStorage.getItem('testKey'); 20 | expect(JSON.parse(out)).toEqual('testVal'); 21 | Storage.local.set('testKey', 'testVal'); 22 | out = window.localStorage.getItem('testKey'); 23 | expect(JSON.parse(out)).toEqual('testVal'); 24 | }); 25 | }); 26 | describe('get', () => { 27 | it('should return key from correct storage type', () => { 28 | window.sessionStorage.setItem('testKey', 'testVal'); 29 | let out = Storage.session.get('testKey'); 30 | expect(out).toEqual('testVal'); 31 | window.localStorage.setItem('testKey', 'testVal'); 32 | out = Storage.local.get('testKey'); 33 | expect(out).toEqual('testVal'); 34 | }); 35 | }); 36 | describe('remove', () => { 37 | it('should remove key from correct storage type', () => { 38 | window.sessionStorage.setItem('testKey', 'testVal'); 39 | Storage.session.remove('testKey'); 40 | let out = window.sessionStorage.getItem('testKey'); 41 | expect(out).toEqual(null); 42 | window.localStorage.setItem('testKey', 'testVal'); 43 | Storage.local.remove('testKey'); 44 | out = window.localStorage.getItem('testKey'); 45 | expect(out).toEqual(null); 46 | }); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /src/util/storage-util.ts: -------------------------------------------------------------------------------- 1 | export const enum StorageType { 2 | SESSION, 3 | LOCAL, 4 | } 5 | 6 | /** 7 | * Get either localStorage or sessionStorage 8 | * @param type storage type 9 | */ 10 | export const getStorage = (type: StorageType): Storage => { 11 | if (type === StorageType.SESSION) { 12 | return window.sessionStorage; 13 | } 14 | return window.localStorage; 15 | }; 16 | 17 | /** 18 | * Set an item into storage 19 | * @param type storage type 20 | * @param key key to set 21 | * @param value value to set 22 | */ 23 | const setItem = (type: StorageType) => (key: string, value: any) => { 24 | getStorage(type).setItem(key, JSON.stringify(value)); 25 | }; 26 | 27 | /** 28 | * Get an item from storage 29 | * @param type storage type 30 | * @param key key to get 31 | * @param defaultVal value to return if key doesnt exist 32 | */ 33 | const getItem = (type: StorageType) => (key: string, defaultVal?: any) => { 34 | const val = getStorage(type).getItem(key); 35 | if (!val || val === 'undefined') return defaultVal; 36 | try { 37 | return JSON.parse(val); 38 | } catch (e) { 39 | return val; 40 | } 41 | }; 42 | 43 | /** 44 | * Remove item from storage 45 | * @param type storage type 46 | * @param key key to remove 47 | */ 48 | const removeItem = (type: StorageType) => (key: string) => { 49 | getStorage(type).removeItem(key); 50 | }; 51 | 52 | export type getItemType = (key: string, defaultVal?: any) => any; 53 | export type setItemType = (key: string, value: any) => void; 54 | export type removeItemType = (key: string) => void; 55 | 56 | export interface IStorageAPI { 57 | get: getItemType; 58 | set: setItemType; 59 | remove: removeItemType; 60 | } 61 | 62 | export interface IStorageService { 63 | session: IStorageAPI; 64 | local: IStorageAPI; 65 | } 66 | 67 | export const Storage: IStorageService = { 68 | session: { 69 | get: getItem(StorageType.SESSION), 70 | set: setItem(StorageType.SESSION), 71 | remove: removeItem(StorageType.SESSION), 72 | }, 73 | local: { 74 | get: getItem(StorageType.LOCAL), 75 | set: setItem(StorageType.LOCAL), 76 | remove: removeItem(StorageType.LOCAL), 77 | }, 78 | }; 79 | -------------------------------------------------------------------------------- /src/util/url-utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { parseHeaderForLinks, getUrlParameter } from './index'; 3 | 4 | describe('parseHeaderForLinks', () => { 5 | it('should throw an error when passed an empty string', () => { 6 | expect(() => parseHeaderForLinks('')).toThrowError(Error); 7 | }); 8 | 9 | it('should throw an error when passed without comma', () => { 10 | expect(() => parseHeaderForLinks('test')).toThrowError(Error); 11 | }); 12 | 13 | it('should throw an error when passed without semicolon', () => { 14 | expect(() => parseHeaderForLinks('test,test2')).toThrowError(Error); 15 | }); 16 | 17 | it('should return links when headers are passed', () => { 18 | const links = { last: 0, first: 0 }; 19 | expect(parseHeaderForLinks('; rel="last",; rel="first"')).toEqual(links); 20 | }); 21 | }); 22 | 23 | describe('getUrlParameter', () => { 24 | it('should get url params for passed names', () => { 25 | expect(getUrlParameter('test', '?test=hello')).toEqual('hello'); 26 | expect(getUrlParameter('[test]', '?[test]=hello')).toEqual('hello'); 27 | expect(getUrlParameter('key', '?key=123hghygh1225')).toEqual('123hghygh1225'); 28 | expect(getUrlParameter('key', '?test=1245&key=123hghygh1225')).toEqual('123hghygh1225'); 29 | expect(getUrlParameter('key', '?test=1245&key=123hghygh1225&test2=55558')).toEqual('123hghygh1225'); 30 | expect(getUrlParameter('key', '?test=1245&key=123hghyg+h1225&test2=55558')).toEqual('123hghyg h1225'); 31 | }); 32 | 33 | it('should return an empty string for missing name', () => { 34 | expect(getUrlParameter('test', '?')).toEqual(''); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /src/util/url-utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Get base path from current window location 3 | */ 4 | export const getBasePath = (): string => window.location.href.split('#')[0]; 5 | 6 | /** 7 | * Parse the header link element and return all links inside. 8 | * @param header header of link 9 | */ 10 | export const parseHeaderForLinks = (header: string): any => { 11 | if (header.length === 0) { 12 | throw new Error('input must not be of zero length'); 13 | } 14 | 15 | // Split parts by comma 16 | const parts: string[] = header.split(','); 17 | const links: any = {}; 18 | 19 | // Parse each part into a named link 20 | parts.forEach(p => { 21 | const section: string[] = p.split(';'); 22 | 23 | if (section.length !== 2) { 24 | throw new Error('section could not be split on ";"'); 25 | } 26 | 27 | const url: string = section[0].replace(/<(.*)>/, '$1').trim(); 28 | const queryString: any = {}; 29 | 30 | url.replace(new RegExp('([^?=&]+)(=([^&]*))?', 'g'), ($0, $1, $2, $3) => (queryString[$1] = $3)); 31 | 32 | let page: any = queryString.page; 33 | 34 | if (typeof page === 'string') { 35 | page = parseInt(page, 10); 36 | } 37 | 38 | const name: string = section[1].replace(/rel="(.*)"/, '$1').trim(); 39 | links[name] = page; 40 | }); 41 | return links; 42 | }; 43 | 44 | /** 45 | * Fetch an entry from URL params 46 | * @param name the param name to fetch 47 | * @param search the search part from react router location 48 | */ 49 | export const getUrlParameter = (name: string, search: string): string => { 50 | const url = new URL(`http://localhost${search}`); // using a dummy url for parsing 51 | return url.searchParams.get(name) || ''; 52 | }; 53 | -------------------------------------------------------------------------------- /tests/setup.ts: -------------------------------------------------------------------------------- 1 | import { afterEach } from 'vitest'; 2 | import { cleanup } from '@testing-library/react'; 3 | 4 | afterEach(() => { 5 | cleanup(); 6 | }); 7 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src"], 3 | "compilerOptions": { 4 | "jsx": "react", 5 | "module": "commonjs", 6 | "target": "es2015", 7 | "emitDecoratorMetadata": true, 8 | "experimentalDecorators": true, 9 | "declaration": true, 10 | "sourceMap": true, 11 | "moduleResolution": "node", 12 | "noUnusedLocals": true, 13 | "noImplicitAny": false, 14 | "allowSyntheticDefaultImports": true, 15 | "esModuleInterop": true, 16 | "importHelpers": true, 17 | "lib": ["es2015", "es2017", "dom"], 18 | "outDir": "./lib", 19 | "types": ["webpack-env"] 20 | }, 21 | "exclude": ["node_modules", "bundles", "coverage", "build", "**/*.spec.ts", "**/*.spec.tsx"] 22 | } 23 | -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["./"], 3 | "extends": "./tsconfig", 4 | "compilerOptions": { 5 | "types": ["webpack-env"] 6 | }, 7 | "exclude": [] 8 | } 9 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config'; 2 | import react from '@vitejs/plugin-react'; 3 | 4 | export default defineConfig({ 5 | plugins: [react()], 6 | test: { 7 | setupFiles: './tests/setup.ts', 8 | }, 9 | }); 10 | --------------------------------------------------------------------------------