├── .babelrc.json ├── .editorconfig ├── .eslintrc.js ├── .gitignore ├── .storybook ├── main.ts └── preview.js ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── assets │ ├── client_error.png │ ├── release_gif.gif │ ├── server_error.png │ ├── storybook_control_params.png │ ├── success_status.png │ └── unknown_status.png ├── components │ ├── Header │ │ ├── index.css │ │ └── index.tsx │ ├── Toast │ │ ├── index.css │ │ └── index.tsx │ ├── ToastMessage │ │ ├── index.css │ │ └── index.tsx │ └── index.ts ├── index.ts ├── stories │ └── toast.stories.tsx ├── types │ ├── index.ts │ ├── statusCode.type.ts │ └── theme.type.ts └── utils │ ├── getMessagesByTheme.util.ts │ ├── getThemIcon.util.tsx │ ├── getThemeByStatusCode.util.ts │ ├── getToastTitleByTheme.util.ts │ ├── index.css │ └── index.ts ├── test └── example │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── reportWebVitals.js │ └── setupTests.js ├── tsconfig.json └── tsup.config.js /.babelrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "sourceType": "unambiguous", 3 | "presets": [ 4 | [ 5 | "@babel/preset-env", 6 | { 7 | "targets": { 8 | "chrome": 100 9 | } 10 | } 11 | ], 12 | "@babel/preset-react", 13 | "@babel/preset-typescript" 14 | ], 15 | "plugins": ["@babel/plugin-syntax-jsx"] 16 | } 17 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = crlf 5 | 6 | [*.{js,json,yml}] 7 | charset = utf-8 -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | }, 6 | extends: [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:react/recommended", 10 | ], 11 | overrides: [ 12 | { 13 | env: { 14 | node: true, 15 | }, 16 | files: [".eslintrc.{js,cjs, ts, tsx}"], 17 | parserOptions: { 18 | sourceType: "script", 19 | }, 20 | }, 21 | ], 22 | parser: "@typescript-eslint/parser", 23 | parserOptions: { 24 | ecmaVersion: "latest", 25 | sourceType: "module", 26 | }, 27 | plugins: ["@typescript-eslint", "react"], 28 | rules: { 29 | "object-curly-spacing": ["error", "always"], 30 | "eol-last": ["error", "always"], 31 | indent: ["error", 2], 32 | "linebreak-style": ["error", "windows"], 33 | quotes: ["error", "single"], 34 | semi: ["error", "always"], 35 | }, 36 | }; 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | .vscode 125 | 126 | # yarn v2 127 | .yarn/cache 128 | .yarn/unplugged 129 | .yarn/build-state.yml 130 | .yarn/install-state.gz 131 | .pnp.* 132 | -------------------------------------------------------------------------------- /.storybook/main.ts: -------------------------------------------------------------------------------- 1 | // .storybook/main.ts 2 | 3 | // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) 4 | import type { StorybookConfig } from '@storybook/react-webpack5'; 5 | 6 | const config: StorybookConfig = { 7 | // Required 8 | framework: '@storybook/react-webpack5', 9 | stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], 10 | // Optional 11 | addons: ['@storybook/addon-essentials'], 12 | docs: { 13 | autodocs: 'tag', 14 | }, 15 | staticDirs: ['../src'], 16 | }; 17 | 18 | export default config; -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | /** @type { import('@storybook/react').Preview } */ 2 | const preview = { 3 | parameters: { 4 | actions: { argTypesRegex: "^on[A-Z].*" }, 5 | controls: { 6 | matchers: { 7 | color: /(background|color)$/i, 8 | date: /Date$/, 9 | }, 10 | }, 11 | }, 12 | }; 13 | 14 | export default preview; 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Marina Marques 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # HTTP STATUS TOAST 3 | 4 | Introducing a straightforward and practical library designed to assist developers in effectively notifying users about the status of their requests. 😁 5 | 6 | ### ✨ Release 🚀 Check on [releases on source repository!](https://github.com/ninamarq/http-status-toast/releases) ✨ 7 | 8 | 9 | 10 | ## Description 11 | 12 | This library offers a simple, concise, and versatile solution, making it easier than ever for developers to communicate essential information to users. With its user-friendly approach, it simplifies the process of conveying the current state of requests, ensuring a seamless user experience. Whether you need to provide updates, alerts, or general notifications, this library has got you covered, enabling you to streamline your development process while delivering clear and informative messages to your users. 13 | 14 | 15 | ## License 16 | 17 | [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/) 18 | 19 | 20 | ## Suggestions and Issues 21 | 22 | Suggestions are always welcome! 23 | 24 | Please, if you have a suggestion or issue to do, create an issue at this repo. 25 | Follow this example: 26 | 27 | `[ToastHeader] Alignments with alignment error` 28 | 29 | And inside of it, your description of the suggestion/issue. 30 | 31 | Thank you 🚀✨ 32 | ## Installation 33 | 34 | Install `http-status-toast` using npm 35 | 36 | ```bash 37 | npm install http-status-toast 38 | ``` 39 | 40 | ## Demonstration 41 | 42 | For use in the simplest way: 43 | 44 | ```bash 45 | fetch(URL) 46 | .then((response) => setData(response.data)) 47 | .catch((error) => httpStatusToast(response.status, 'en')) 48 | ``` 49 | 50 | Above we have a simple call of the lib function, that will call a notification with a simple message and a simple toast with its theme according to the status passed by params. 51 | 52 | ### **Default examples by status** 53 | 54 | Here we will have some examples of the simplest use of this function, passing just the status and the english lang to the function. 55 | 56 | - When the status passed it fits successfull request: 57 | 58 | 59 | 60 | - When the status passed it fits client error request: 61 | 62 | 63 | 64 | - When the status passed it fits server error request: 65 | 66 | 67 | 68 | - When the status passed it fits unknown type of request: 69 | 70 | 71 | 72 | But if you want to customize more and more, we have some optionals uses for this function. 73 | 74 | You can costume: 75 | - Style by `customStyle` params, JSON format 76 | - Horizontal position by `position` params, passing "right" or "left" values 77 | - Language by `lang` params, for now we have just for portuguese ("pt"), spanish ("es") and english ("en") 78 | - Toast duration by `duration` params, passing milisseconds value 79 | - Custom message by `message` params, passing a string or a React Node 80 | - Custom header by `customHeader` params, passing a string or a React Node 81 | 82 | ## Storybook controls visualization 83 | 84 | 85 | 86 | Examples of uses: 87 | 88 | - Style 89 | 90 | ```bash 91 | fetch(URL) 92 | .then((response) => httpStatusToast({ 93 | status: response.status, 94 | lang: 'en', 95 | customStyle: { "font-family": "Times new Roman", "color": "red" } 96 | })) 97 | .catch((error) => console.error(error)) 98 | ``` 99 | 100 | - Position 101 | 102 | ```bash 103 | fetch(URL) 104 | .then((response) => httpStatusToast({ 105 | status: response.status, 106 | lang: 'en', 107 | position: "left" 108 | })) 109 | .catch((error) => console.error(error)) 110 | ``` 111 | 112 | - Language 113 | 114 | ```bash 115 | fetch(URL) 116 | .then((response) => httpStatusToast({ 117 | status: response.status, 118 | lang: 'pt' 119 | })) 120 | .catch((error) => console.error(error)) 121 | ``` 122 | 123 | - Duration 124 | 125 | ```bash 126 | fetch(URL) 127 | .then((response) => httpStatusToast({ 128 | status: response.status, 129 | lang: 'pt', 130 | duration: 6000, // 6 seconds 131 | })) 132 | .catch((error) => console.error(error)) 133 | ``` 134 | 135 | - Message 136 | 137 | ```bash 138 | fetch(URL) 139 | .then((response) => httpStatusToast({ 140 | status: response.status, 141 | lang: 'en', 142 | message: response.data.message ||
Lorem ipsum
, 143 | })) 144 | .catch((error) => console.error(error)) 145 | ``` 146 | 147 | - Custom header 148 | 149 | ```bash 150 | fetch(URL) 151 | .then((response) => httpStatusToast({ 152 | status: response.status, 153 | lang: 'en', 154 | customHeader: "Lorem ipsum" ||
Lorem ipsum
, 155 | })) 156 | .catch((error) => console.error(error)) 157 | ``` 158 | 159 | And that's it! ❤️ 160 |
161 | 162 | ### Thank you for using my first lib, and thank you for reading till here! 163 | 164 | ## Created by me [@ninamarq](https://www.github.com/ninamarq) 🚀✨ 165 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "http-status-toast", 3 | "version": "1.5.0", 4 | "description": "A simple toast notification according to your http req response!", 5 | "source": "src/index.d.cts", 6 | "main": "dist/index.cjs", 7 | "module": "dist/index.js", 8 | "typings": "dist/index.d.ts", 9 | "type": "module", 10 | "files": [ 11 | "dist" 12 | ], 13 | "moduleFileExtensions": [ 14 | "ts", 15 | "tsx", 16 | "js", 17 | "jsx", 18 | "json", 19 | "node" 20 | ], 21 | "scripts": { 22 | "test": "echo \"Error: no test specified\" && exit 1", 23 | "storybook": "storybook dev -p 6006", 24 | "build-storybook": "storybook build", 25 | "build": "tsup", 26 | "build2": "rollup -c" 27 | }, 28 | "repository": { 29 | "type": "git", 30 | "url": "git+https://github.com/ninamarq/http-status-toast.git" 31 | }, 32 | "keywords": [ 33 | "status-toast", 34 | "http", 35 | "status", 36 | "toast", 37 | "alert", 38 | "general", 39 | "notification" 40 | ], 41 | "author": "Marina Marques - ninamarq", 42 | "license": "MIT", 43 | "bugs": { 44 | "url": "https://github.com/ninamarq/http-status-toast/issues" 45 | }, 46 | "homepage": "https://github.com/ninamarq/http-status-toast#readme", 47 | "devDependencies": { 48 | "@babel/preset-env": "^7.22.5", 49 | "@babel/preset-react": "^7.22.5", 50 | "@storybook/addon-essentials": "^7.0.23", 51 | "@storybook/addon-interactions": "^7.0.23", 52 | "@storybook/addon-links": "^7.0.23", 53 | "@storybook/addons": "^7.0.23", 54 | "@storybook/blocks": "^7.0.23", 55 | "@storybook/react": "^7.0.23", 56 | "@storybook/react-webpack5": "^7.0.23", 57 | "@storybook/testing-library": "^0.0.14-next.2", 58 | "@swc/core": "^1.3.68", 59 | "@types/aria-query": "^5.0.1", 60 | "@types/react": "^18.2.14", 61 | "@types/react-dom": "^18.2.6", 62 | "@types/storybook__react": "^5.2.1", 63 | "@typescript-eslint/eslint-plugin": "^5.60.0", 64 | "@typescript-eslint/parser": "^5.60.0", 65 | "eslint": "^8.43.0", 66 | "eslint-plugin-react": "^7.32.2", 67 | "postcss-preset-env": "^9.0.0", 68 | "prop-types": "^15.8.1", 69 | "react": "^18.2.0", 70 | "react-dom": "^18.2.0", 71 | "react-icons": "^4.10.1", 72 | "storybook": "^7.0.23", 73 | "tsup": "^7.1.0", 74 | "typescript": "^5.1.6", 75 | "typescript-eslint": "^0.0.1-alpha.0", 76 | "webpack": "^5.88.1" 77 | }, 78 | "peerDependencies": { 79 | "react": "^18.2.0", 80 | "react-dom": "^18.2.0" 81 | }, 82 | "dependencies": { 83 | "postcss": "^8.4.25", 84 | "react-icons": "^4.10.1" 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/assets/client_error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/client_error.png -------------------------------------------------------------------------------- /src/assets/release_gif.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/release_gif.gif -------------------------------------------------------------------------------- /src/assets/server_error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/server_error.png -------------------------------------------------------------------------------- /src/assets/storybook_control_params.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/storybook_control_params.png -------------------------------------------------------------------------------- /src/assets/success_status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/success_status.png -------------------------------------------------------------------------------- /src/assets/unknown_status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/src/assets/unknown_status.png -------------------------------------------------------------------------------- /src/components/Header/index.css: -------------------------------------------------------------------------------- 1 | .header { 2 | display: flex; 3 | flex-direction: row-reverse; 4 | flex-wrap: nowrap; 5 | align-items: flex-start; 6 | justify-content: space-between; 7 | box-sizing: border-box; 8 | width: 100%; 9 | height: 100%; 10 | cursor: default; 11 | word-break: break-word; 12 | } 13 | 14 | .header svg { 15 | font-size: 20px; 16 | } 17 | 18 | .close-button { 19 | transition: .75s; 20 | cursor: pointer; 21 | } 22 | 23 | .close-button:hover { 24 | transition: .75s; 25 | opacity: 70%; 26 | } 27 | 28 | .close-button svg { 29 | width: 14px; 30 | } 31 | -------------------------------------------------------------------------------- /src/components/Header/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback } from 'react'; 2 | import { getThemeIcon } from '../../utils'; 3 | import { EStatusTheme, TLang } from '../../types'; 4 | import { AiOutlineClose } from 'react-icons/ai'; 5 | import './index.css' 6 | 7 | interface IHeaderProps { 8 | currentTheme: EStatusTheme 9 | currentLang: TLang 10 | handleDisplayToast: (value: string) => void 11 | currentHeader?: string | React.ReactNode 12 | } 13 | 14 | export const Header = (props: IHeaderProps) => { 15 | const handleHeader = useCallback(() => { 16 | if (props.currentHeader) { 17 | return props.currentHeader 18 | } 19 | 20 | return getThemeIcon(props.currentTheme, props.currentLang) 21 | }, [props.currentHeader, props.currentLang, props.currentTheme]) 22 | 23 | return ( 24 |
25 |
26 | props.handleDisplayToast("false")}/> 27 |
28 | {handleHeader()} 29 |
30 | ); 31 | }; 32 | -------------------------------------------------------------------------------- /src/components/Toast/index.css: -------------------------------------------------------------------------------- 1 | .toast_container { 2 | display: flex; 3 | box-sizing: border-box; 4 | border-radius: 6px; 5 | flex-direction: column; 6 | font-family: Fira code; 7 | font-size: 14px; 8 | color: #F0EFFB; 9 | padding: 8px; 10 | z-index: 3; 11 | -webkit-transform: translate3d(0, 0, 3); 12 | position: fixed; 13 | top: 5%; 14 | width: 30%; 15 | min-width: 150px; 16 | max-width: 500px; 17 | box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px; 18 | transition: .5s; 19 | overflow: hidden; 20 | } 21 | 22 | .hide_toast { 23 | display: none; 24 | } 25 | 26 | #right { 27 | right: 4%; 28 | animation: toasting-right 2s normal; 29 | } 30 | 31 | #left { 32 | left: 4%; 33 | animation: toasting-left 2s normal; 34 | } 35 | 36 | .bg_success { 37 | background-color: #7FB069; 38 | } 39 | 40 | .bg_client_error { 41 | background-color: #FF3C38; 42 | } 43 | 44 | .bg_server_error { 45 | background-color: #FF8C42; 46 | } 47 | 48 | .bg_unknown { 49 | background-color: #76949F; 50 | } 51 | 52 | .timer{ 53 | position: absolute; 54 | bottom: 0; 55 | left: 0; 56 | height: 2px; 57 | width: 100%; 58 | } 59 | 60 | .timer::before{ 61 | content: ""; 62 | position: absolute; 63 | bottom: 0; 64 | right: 0; 65 | height: 100%; 66 | width: 100%; 67 | background-color: #ddd; 68 | } 69 | 70 | @keyframes timer { 71 | from { 72 | transform: translate3d(0, 0, 0); 73 | } 74 | to { 75 | transform: translate3d(100%, 0, 0); 76 | } 77 | } 78 | 79 | @keyframes toasting-right { 80 | from { 81 | transform: translate3d(110%, 0, 0); 82 | visibility: visible; 83 | } 84 | to { 85 | transform: translate3d(0, 0, 0); 86 | } 87 | } 88 | 89 | @keyframes toasting-left { 90 | from { 91 | transform: translate3d(-110%, 0, 0); 92 | visibility: visible; 93 | } 94 | to { 95 | transform: translate3d(0, 0, 0); 96 | } 97 | } -------------------------------------------------------------------------------- /src/components/Toast/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useMemo, useState } from 'react'; 2 | import './index.css'; 3 | import { getThemeByStatusCode } from '../../utils'; 4 | import { EStatusTheme, TLang } from '../../types'; 5 | import { Header } from '../Header'; 6 | import { ToastMessage } from '../ToastMessage'; 7 | import { createRoot } from 'react-dom/client'; 8 | import ReactDOM from 'react-dom' 9 | 10 | export interface IToastProps { 11 | status: string | number 12 | lang: TLang 13 | position?: 'right' | 'left' 14 | duration?: string | number 15 | message?: string | React.ReactNode 16 | customHeader?: string | React.ReactNode 17 | customStyle?: React.CSSProperties 18 | } 19 | 20 | export const Toast = (props: IToastProps) => { 21 | const ToastComponent = (props: IToastProps) => { 22 | const [toastTheme, setToastTheme] = useState(EStatusTheme.SUCCESS); 23 | const [displayToast, setDisplayToast] = useState("true"); 24 | 25 | useMemo(() => { 26 | setToastTheme(getThemeByStatusCode(props.status)); 27 | }, [props.status]); 28 | 29 | setTimeout(() => { 30 | setDisplayToast("false"); 31 | }, Number(props.duration) || 7000); 32 | 33 | const handleClassName = () => { 34 | const styleArr = ["toast_container"] 35 | styleArr.push(`bg_${toastTheme}`) 36 | 37 | if (displayToast === "false") styleArr.push("hide_toast") 38 | 39 | return styleArr.join(" ") 40 | } 41 | 42 | return ( 43 |
44 |
50 | 55 |
61 |
62 | ) 63 | } 64 | 65 | let domNode; 66 | const toastNotify = document.getElementById('@ninamarq/http-status-toast'); 67 | 68 | const handleRoot = (node: Element | DocumentFragment) => { 69 | const internalRoot = (ReactDOM as any)._internalRoot; 70 | 71 | if (internalRoot && internalRoot.current) { 72 | internalRoot.current.render(); 73 | } else { 74 | const root = createRoot(node); 75 | root.render(); 76 | } 77 | }; 78 | 79 | if (toastNotify) { 80 | domNode = document.querySelector('body')?.appendChild(toastNotify); 81 | } else { 82 | const divInjet = document.createElement('div'); 83 | divInjet.setAttribute('id', '@ninamarq/http-status-toast'); 84 | 85 | domNode = document.querySelector('body')?.appendChild(divInjet); 86 | } 87 | 88 | if (domNode) { 89 | handleRoot(domNode); 90 | return; 91 | } 92 | 93 | console.warn("Error in http-status-toast render, please notify Marina at this link: https://github.com/ninamarq/http-status-toast/issues"); 94 | }; -------------------------------------------------------------------------------- /src/components/ToastMessage/index.css: -------------------------------------------------------------------------------- 1 | .message_container { 2 | display: flex; 3 | flex-wrap: nowrap; 4 | word-break: break-word; 5 | text-align: justify; 6 | width: 100%; 7 | box-sizing: border-box; 8 | padding: 8px 4px; 9 | } 10 | -------------------------------------------------------------------------------- /src/components/ToastMessage/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback } from 'react'; 2 | import './index.css'; 3 | import { getMessagesByTheme } from '../../utils'; 4 | import { EStatusTheme, TLang } from '../../types'; 5 | 6 | interface IToastMessageProps { 7 | currentMessage?: string | React.ReactNode 8 | currentTheme: EStatusTheme 9 | currentLang: TLang 10 | } 11 | 12 | export const ToastMessage = (props: IToastMessageProps) => { 13 | const messageToRender = useCallback(() => { 14 | if(props.currentMessage) { 15 | return props.currentMessage; 16 | } 17 | 18 | return getMessagesByTheme(props.currentTheme, props.currentLang); 19 | }, [props.currentTheme, props.currentMessage, props.currentLang]); 20 | 21 | return ( 22 |
23 | {messageToRender()} 24 |
25 | ); 26 | }; 27 | -------------------------------------------------------------------------------- /src/components/index.ts: -------------------------------------------------------------------------------- 1 | export { Toast } from './Toast' 2 | export { ToastMessage } from './ToastMessage' 3 | export { Header } from './Header' -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { Toast as httpStatusToast } from './components' 2 | export * from './types' 3 | export * from './utils' 4 | -------------------------------------------------------------------------------- /src/stories/toast.stories.tsx: -------------------------------------------------------------------------------- 1 | import { Meta, StoryObj } from '@storybook/react'; 2 | import App from '../../test/example/src/App.js' 3 | // import { App } from '../../src'; 4 | 5 | const meta: Meta = { 6 | component: App, 7 | }; 8 | 9 | export default meta; 10 | type Story = StoryObj; 11 | 12 | //👇 Throws a type error it the args don't match the component props 13 | export const Primary: Story = { 14 | args: { 15 | status: '204', 16 | position: 'right', 17 | duration: '5000', 18 | message: {}, 19 | lang: 'pt', 20 | customStyle: {}, 21 | customHeader: {} 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./statusCode.type"; 2 | export * from "./theme.type"; 3 | 4 | export type TLang = "pt" | "es" | "en"; 5 | -------------------------------------------------------------------------------- /src/types/statusCode.type.ts: -------------------------------------------------------------------------------- 1 | import { TLang } from "."; 2 | 3 | export interface IStatusCode { 4 | statusCode: string | number; 5 | name: string; 6 | description: string; 7 | } 8 | 9 | export type TStatusCode = 10 | | "success" 11 | | "client_error" 12 | | "server_error" 13 | | "unknown"; 14 | 15 | export enum EStatusTheme { 16 | SUCCESS = "success", 17 | CLIENT_ERROR = "client_error", 18 | SERVER_ERROR = "server_error", 19 | UNKNOWN = "unknown", 20 | } 21 | 22 | export type SuccessStatusCode = 200 | 204; 23 | 24 | export type ClientErrorStatusCode = 25 | | 400 26 | | 401 27 | | 403 28 | | 404 29 | | 409 30 | | 422 31 | | 429 32 | | 499; 33 | 34 | export type ServerErrorStatusCode = 500 | 502 | 504; 35 | 36 | export type StatusCodes = SuccessStatusCode & 37 | ClientErrorStatusCode & 38 | ServerErrorStatusCode; 39 | 40 | export type StatusTranslations = { 41 | [status in TStatusCode]: { 42 | [lang in TLang]: string; 43 | }; 44 | }; 45 | -------------------------------------------------------------------------------- /src/types/theme.type.ts: -------------------------------------------------------------------------------- 1 | export interface IThemeProps { 2 | theme: { [key: string]: string } | TTheme; 3 | } 4 | 5 | export type TTheme = "success" | "client_error" | "server_error"; 6 | -------------------------------------------------------------------------------- /src/utils/getMessagesByTheme.util.ts: -------------------------------------------------------------------------------- 1 | import { EStatusTheme, StatusTranslations, TLang } from "../types"; 2 | 3 | const getMessagesByTheme = (theme: EStatusTheme, lang?: TLang) => { 4 | const message: StatusTranslations = { 5 | [EStatusTheme.SUCCESS]: { 6 | en: "Your request was submitted successfully!", 7 | es: "¡Su solicitud se envió correctamente!", 8 | pt: "Sua solicitação foi enviada com sucesso!", 9 | }, 10 | [EStatusTheme.CLIENT_ERROR]: { 11 | en: "An error occurred with your client!", 12 | es: "¡Se produjo un error con su cliente!", 13 | pt: "Ocorreu um erro com o seu cliente!", 14 | }, 15 | [EStatusTheme.SERVER_ERROR]: { 16 | en: "Resource not found, an error occurred with the system server", 17 | es: "Recurso no encontrado, se produjo un error con el servidor del sistema", 18 | pt: "Recurso não encontrado, ocorreu um erro com o servidor do sistema", 19 | }, 20 | [EStatusTheme.UNKNOWN]: { 21 | pt: "Retorno desconhecido para darmos alguma especificação!", 22 | es: "¡Respuesta desconocida para especificaciones!", 23 | en: "Unknown response for specifications!", 24 | }, 25 | }; 26 | 27 | if (lang) { 28 | return message[theme][lang]; 29 | } 30 | 31 | return message[theme]["en"] || ""; 32 | }; 33 | 34 | export default getMessagesByTheme; 35 | -------------------------------------------------------------------------------- /src/utils/getThemIcon.util.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { AiFillCheckCircle, AiOutlineDisconnect } from "react-icons/ai"; 3 | import { BiSolidErrorAlt } from "react-icons/bi"; 4 | import { MdSmsFailed } from "react-icons/md"; 5 | import { EStatusTheme, TLang } from "../types"; 6 | import getToastTitleByTheme from "./getToastTitleByTheme.util"; 7 | import "./index.css"; 8 | 9 | const getThemeIcon = (theme: EStatusTheme, lang?: TLang) => { 10 | const themeIcons = { 11 | success: , 12 | client_error: , 13 | server_error: , 14 | unknown: , 15 | }; 16 | 17 | return ( 18 |
19 | {themeIcons[theme]} 20 | {getToastTitleByTheme(theme, lang)} 21 |
22 | ); 23 | }; 24 | 25 | export default getThemeIcon; 26 | -------------------------------------------------------------------------------- /src/utils/getThemeByStatusCode.util.ts: -------------------------------------------------------------------------------- 1 | import { EStatusTheme, StatusCodes } from "../types"; 2 | 3 | const getThemeByStatusCode = (status: string | number): EStatusTheme => { 4 | const statusType = new Map([ 5 | [200, EStatusTheme.SUCCESS], 6 | [204, EStatusTheme.SUCCESS], 7 | [400, EStatusTheme.CLIENT_ERROR], 8 | [401, EStatusTheme.CLIENT_ERROR], 9 | [403, EStatusTheme.CLIENT_ERROR], 10 | [404, EStatusTheme.CLIENT_ERROR], 11 | [409, EStatusTheme.CLIENT_ERROR], 12 | [422, EStatusTheme.CLIENT_ERROR], 13 | [429, EStatusTheme.CLIENT_ERROR], 14 | [499, EStatusTheme.CLIENT_ERROR], 15 | [500, EStatusTheme.SERVER_ERROR], 16 | [502, EStatusTheme.SERVER_ERROR], 17 | [504, EStatusTheme.SERVER_ERROR], 18 | ] as Array<[StatusCodes, EStatusTheme]>); 19 | 20 | const statusString = String(status); 21 | 22 | for (const [statusCode, theme] of statusType.entries()) { 23 | if (statusString === String(statusCode)) { 24 | return theme; 25 | } 26 | } 27 | 28 | return EStatusTheme.UNKNOWN; 29 | }; 30 | 31 | export default getThemeByStatusCode; 32 | -------------------------------------------------------------------------------- /src/utils/getToastTitleByTheme.util.ts: -------------------------------------------------------------------------------- 1 | import { EStatusTheme, StatusTranslations, TLang } from "../types"; 2 | 3 | const getToastTitleByTheme = (theme: EStatusTheme, lang?: TLang) => { 4 | const title: StatusTranslations = { 5 | [EStatusTheme.SUCCESS]: { 6 | en: "Success", 7 | es: "Éxito", 8 | pt: "Sucesso", 9 | }, 10 | [EStatusTheme.CLIENT_ERROR]: { 11 | en: "Client error", 12 | es: "Error de cliente", 13 | pt: "Erro de cliente", 14 | }, 15 | [EStatusTheme.SERVER_ERROR]: { 16 | en: "Server error", 17 | es: "Error con el servidor", 18 | pt: "Erro de servidor", 19 | }, 20 | [EStatusTheme.UNKNOWN]: { 21 | pt: "Status desconhecido", 22 | es: "Status desconocido", 23 | en: "Unknown status", 24 | }, 25 | }; 26 | 27 | if (lang) { 28 | return title[theme][lang]; 29 | } 30 | 31 | return title[theme]["en"] || ""; 32 | }; 33 | 34 | export default getToastTitleByTheme; 35 | -------------------------------------------------------------------------------- /src/utils/index.css: -------------------------------------------------------------------------------- 1 | .theme_icon { 2 | display: flex; 3 | gap: 10px; 4 | justify-content: flex-start; 5 | align-items: center; 6 | } -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | import getThemeByStatusCode from './getThemeByStatusCode.util'; 2 | import getThemeIcon from './getThemIcon.util'; 3 | import getMessagesByTheme from './getMessagesByTheme.util'; 4 | import getToastTitleByTheme from './getToastTitleByTheme.util'; 5 | 6 | export { getThemeByStatusCode, getThemeIcon, getMessagesByTheme, getToastTitleByTheme }; 7 | -------------------------------------------------------------------------------- /test/example/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /test/example/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /test/example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.5", 7 | "@testing-library/react": "^13.4.0", 8 | "@testing-library/user-event": "^13.5.0", 9 | "react": "^18.2.0", 10 | "react-dom": "^18.2.0", 11 | "react-scripts": "5.0.1", 12 | "http-status-toast": "1.3.6", 13 | "web-vitals": "^2.1.4" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": [ 23 | "react-app", 24 | "react-app/jest" 25 | ] 26 | }, 27 | "browserslist": { 28 | "production": [ 29 | ">0.2%", 30 | "not dead", 31 | "not op_mini all" 32 | ], 33 | "development": [ 34 | "last 1 chrome version", 35 | "last 1 firefox version", 36 | "last 1 safari version" 37 | ] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /test/example/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/test/example/public/favicon.ico -------------------------------------------------------------------------------- /test/example/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /test/example/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/test/example/public/logo192.png -------------------------------------------------------------------------------- /test/example/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninamarq/http-status-toast/a2870aefb54bc461c959d114b0c8b0f789cf0c0f/test/example/public/logo512.png -------------------------------------------------------------------------------- /test/example/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /test/example/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /test/example/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/example/src/App.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | import { Toast as httpStatusToast } from "../../../src/components/Toast"; 3 | import { AiFillAlert } from "react-icons/ai"; 4 | 5 | function App() { 6 | const [data, setData] = useState([]); 7 | const makeRequest = () => { 8 | fetch("https://jsonplaceholder.typicode.com/todos") 9 | .then(async (response) => { 10 | const todos = await response.json(); 11 | setData(todos); 12 | httpStatusToast({ 13 | status: 500, 14 | lang: "en", 15 | duration: 5000, 16 | // position: "left" 17 | }); 18 | }) 19 | .catch((error) => 20 | httpStatusToast({ 21 | status: error.status, 22 | lang: "pt", 23 | duration: 5000, 24 | // customHeader: ( 25 | //

26 | // ss 27 | //

28 | // ), 29 | // position: "left" 30 | }) 31 | ); 32 | }; 33 | 34 | useEffect(() => { 35 | makeRequest(); 36 | }, []); 37 | 38 | return ( 39 |
40 |
41 |
    42 | {data.map((todo) => ( 43 |
  • {todo.title}
  • 44 | ))} 45 |
46 | 47 |
48 |
49 |
50 | ); 51 | } 52 | 53 | export default App; 54 | -------------------------------------------------------------------------------- /test/example/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /test/example/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /test/example/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | const root = ReactDOM.createRoot(document.getElementById('root')); 8 | root.render( 9 | 10 | 11 | 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /test/example/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/example/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /test/example/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "ESNext", 5 | "jsx": "react", 6 | "rootDir": "src", 7 | "sourceMap": true, 8 | "outDir": "dist", 9 | "strict": true, 10 | "moduleResolution": "node", 11 | "allowSyntheticDefaultImports": true, 12 | "esModuleInterop": true, 13 | "skipLibCheck": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "downlevelIteration": true, 16 | "declaration": true, 17 | "emitDeclarationOnly": true 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tsup.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "tsup"; 2 | import pkg from "./package.json"; 3 | 4 | const dependencies = Object.keys(pkg.dependencies); 5 | const peerDependencies = Object.keys(pkg.peerDependencies); 6 | 7 | export default defineConfig({ 8 | clean: true, 9 | entry: ["src/index.ts"], 10 | format: ["cjs", "esm"], 11 | treeshake: true, 12 | minify: true, 13 | bundle: true, 14 | dts: true, 15 | tsconfig: "tsconfig.json", 16 | splitting: !true, 17 | sourcemap: !true, 18 | noExternal: dependencies, 19 | external: peerDependencies, 20 | injectStyle: true, 21 | esbuildOptions(options) { 22 | options.define = { 23 | "process.env.NODE_ENV": JSON.stringify("production"), 24 | }; 25 | options.banner = { 26 | js: '"use client"', 27 | }; 28 | }, 29 | async onSuccess() { 30 | console.log("Build success"); 31 | }, 32 | esbuildPlugins: [ 33 | { 34 | name: "css-module", 35 | setup(build) { 36 | build.onResolve( 37 | { filter: /\.module\.css$/, namespace: "file" }, 38 | (args) => ({ 39 | path: `${args.path}#css-module`, 40 | namespace: "css-module", 41 | pluginData: { 42 | pathDir: path.join(args.resolveDir, args.path), 43 | }, 44 | }) 45 | ); 46 | build.onLoad( 47 | { filter: /#css-module$/, namespace: "css-module" }, 48 | async (args) => { 49 | const { pluginData } = args; 50 | const source = await fsPromises.readFile( 51 | pluginData.pathDir, 52 | "utf8" 53 | ); 54 | 55 | let cssModule = {}; 56 | const result = await postcss([ 57 | postcssModules({ 58 | getJSON(_, json) { 59 | cssModule = json; 60 | }, 61 | }), 62 | ]).process(source, { from: pluginData.pathDir }); 63 | 64 | return { 65 | pluginData: { css: result.css }, 66 | contents: `import "${ 67 | pluginData.pathDir 68 | }"; export default ${JSON.stringify(cssModule)}`, 69 | }; 70 | } 71 | ); 72 | build.onResolve( 73 | { filter: /\.module\.css$/, namespace: "css-module" }, 74 | (args) => ({ 75 | path: path.join(args.resolveDir, args.path, "#css-module-data"), 76 | namespace: "css-module", 77 | pluginData: args.pluginData, 78 | }) 79 | ); 80 | build.onLoad( 81 | { filter: /#css-module-data$/, namespace: "css-module" }, 82 | (args) => ({ 83 | contents: args.pluginData.css, 84 | loader: "css", 85 | }) 86 | ); 87 | }, 88 | }, 89 | ], 90 | target: ["es6", "esnext", "node14"], 91 | }); 92 | --------------------------------------------------------------------------------