├── .npmrc ├── .github ├── motion.gif ├── react-value-flash.png ├── dependabot.yml └── workflows │ └── cicd.yml ├── tsconfig.eslint.json ├── .husky └── pre-commit ├── .babelrc ├── .vscode └── settings.json ├── .storybook ├── preview.js └── main.js ├── .gitignore ├── stories ├── useInterval.ts ├── components │ └── ValueSetter.tsx └── Flash.stories.tsx ├── src ├── formatters │ └── index.ts ├── Flash.test.tsx └── Flash.tsx ├── eslint.config.js ├── LICENSE ├── CODE_OF_CONDUCT.md ├── package.json ├── README.md └── tsconfig.json /.npmrc: -------------------------------------------------------------------------------- 1 | legacy-peer-deps=true 2 | -------------------------------------------------------------------------------- /.github/motion.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab49/react-value-flash/HEAD/.github/motion.gif -------------------------------------------------------------------------------- /.github/react-value-flash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lab49/react-value-flash/HEAD/.github/react-value-flash.png -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [ 4 | "src", 5 | "stories" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | export ESLINT_USE_FLAT_CONFIG=false 5 | npx lint-staged 6 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env", 4 | "@babel/preset-react", 5 | "@babel/preset-typescript" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "eslint.experimental": { 3 | "useFlatConfig": false 4 | }, 5 | "eslint.options": { 6 | "overrideConfigFile": "eslint.config.js" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | export const parameters = { 2 | actions: { argTypesRegex: "^on[A-Z].*" }, 3 | controls: { 4 | matchers: { 5 | color: /(background|color)$/i, 6 | date: /Date$/, 7 | }, 8 | }, 9 | }; 10 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | stories: ["../**/*.stories.mdx", "../**/*.stories.@(js|jsx|ts|tsx)"], 3 | addons: [ 4 | "@storybook/addon-links", 5 | "@storybook/addon-essentials", 6 | "@storybook/addon-interactions", 7 | ], 8 | features: { 9 | interactionsDebugger: true, 10 | }, 11 | framework: "@storybook/react", 12 | core: { 13 | builder: "@storybook/builder-webpack5", 14 | }, 15 | }; 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | build-storybook.log 4 | storybook-static 5 | coverage 6 | # dependencies 7 | node_modules 8 | 9 | # builds 10 | build 11 | dist 12 | .rpt2_cache 13 | 14 | # misc 15 | .DS_Store 16 | .env 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /stories/useInterval.ts: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export const useInterval = (callback: () => void, delay: number) => { 4 | const savedCallback = React.useRef<() => void>(); 5 | 6 | React.useEffect(() => { 7 | savedCallback.current = callback; 8 | }); 9 | 10 | React.useEffect(() => { 11 | const tick = () => { 12 | if (savedCallback.current) { 13 | savedCallback.current(); 14 | } 15 | }; 16 | const id = setInterval(tick, delay); 17 | 18 | return () => clearInterval(id); 19 | }, [delay]); 20 | }; 21 | -------------------------------------------------------------------------------- /src/formatters/index.ts: -------------------------------------------------------------------------------- 1 | import type { Props } from "../Flash"; 2 | 3 | export type Formatter = (value: Props["value"]) => string; 4 | 5 | type Formatters = { 6 | [K in Extract]: (value: Props["value"]) => string; 7 | } & { 8 | default: Formatter; 9 | }; 10 | 11 | const numberFormatter = (value: number) => 12 | Intl.NumberFormat("en").format(value); 13 | 14 | const currencyFormatter = (value: number) => 15 | Intl.NumberFormat("en", { style: "currency", currency: "USD" }).format(value); 16 | 17 | const percentageFormatter = (value: number) => 18 | Intl.NumberFormat("en", { 19 | style: "percent", 20 | // See: https://github.com/microsoft/TypeScript/issues/36533 21 | // @ts-ignore 22 | signDisplay: "exceptZero", 23 | }).format(value); 24 | 25 | const defaultFormatter = (value: number) => `${value}`; 26 | 27 | export const formatters: Formatters = { 28 | default: defaultFormatter, 29 | number: numberFormatter, 30 | currency: currencyFormatter, 31 | percentage: percentageFormatter, 32 | }; 33 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: "@typescript-eslint/parser", 3 | parserOptions: { 4 | project: "./tsconfig.json", 5 | }, 6 | plugins: ["@typescript-eslint", "prettier"], 7 | extends: [ 8 | "airbnb-typescript", 9 | "plugin:eslint-comments/recommended", 10 | "plugin:import/errors", 11 | "plugin:import/warnings", 12 | "plugin:import/typescript", 13 | "plugin:react/recommended", 14 | "plugin:react-hooks/recommended", 15 | "plugin:storybook/recommended", 16 | ], 17 | rules: { 18 | "prettier/prettier": "error", 19 | "import/prefer-default-export": "off", 20 | "import/no-default-export": "error", 21 | "@typescript-eslint/quotes": "off", 22 | "@typescript-eslint/comma-dangle": "off", 23 | }, 24 | overrides: [ 25 | { 26 | files: ["./stories/**/*stories*"], 27 | rules: { 28 | "import/no-default-export": 0, 29 | "import/no-extraneous-dependencies": "off", 30 | }, 31 | }, 32 | ], 33 | settings: { 34 | react: { 35 | version: "detect", 36 | }, 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Lab49 (lab49.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /stories/components/ValueSetter.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | interface Props { 4 | children: any; 5 | downLabel?: string; 6 | initialValue?: number; 7 | upLabel?: string; 8 | } 9 | 10 | const defaultProps = { 11 | downLabel: "Subtract one", 12 | initialValue: 20_000, 13 | upLabel: "Add one", 14 | }; 15 | 16 | export const ValueSetter = ({ 17 | initialValue = defaultProps.initialValue, 18 | children, 19 | upLabel, 20 | downLabel, 21 | }: Props) => { 22 | const [value, setValue] = React.useState(initialValue); 23 | 24 | return ( 25 |
26 |
27 | 34 | 35 | 42 |
43 | 44 |
45 | 46 | {children(value)} 47 |
48 | ); 49 | }; 50 | 51 | ValueSetter.defaultProps = defaultProps; 52 | -------------------------------------------------------------------------------- /.github/workflows/cicd.yml: -------------------------------------------------------------------------------- 1 | on: [push] 2 | 3 | jobs: 4 | cicd: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | with: 9 | fetch-depth: 0 # Required to retrieve git history for Chromatic 10 | 11 | - uses: actions/cache@v2 12 | env: 13 | cache-name: cache-node-modules 14 | with: 15 | path: ~/.npm 16 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} 17 | restore-keys: | 18 | ${{ runner.os }}-build-${{ env.cache-name }}- 19 | ${{ runner.os }}-build- 20 | ${{ runner.os }}- 21 | 22 | - run: npm ci 23 | - run: npm run lint 24 | - run: npm run types 25 | - run: | 26 | npm run test -- --coverage 27 | bash <(curl -s https://codecov.io/bash) -f ./coverage/coverage-final.json 28 | 29 | - uses: chromaui/action@v1 30 | with: 31 | token: ${{ secrets.GITHUB_TOKEN }} 32 | projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }} 33 | exitOnceUploaded: true 34 | 35 | - uses: JS-DevTools/npm-publish@v1 36 | with: 37 | token: ${{ secrets.NPM_TOKEN }} 38 | -------------------------------------------------------------------------------- /src/Flash.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { render, screen } from "@testing-library/react"; 3 | 4 | import { Flash } from "./Flash"; 5 | import { Formatter } from "./formatters/index"; 6 | 7 | const currencyFormatterYen = (value: number): string => 8 | Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format( 9 | value 10 | ); 11 | 12 | describe("Given component", () => { 13 | const testCases: { 14 | when: string; 15 | value: number; 16 | formatter?: "currency" | "percentage" | "number"; 17 | formatterFn?: Formatter; 18 | then: string; 19 | formattedValue: string; 20 | }[] = [ 21 | { 22 | when: "formatter is set to number", 23 | value: 20000, 24 | formatter: "number", 25 | then: "value should be displayed in number format", 26 | formattedValue: "20,000", 27 | }, 28 | { 29 | when: "formatter is set to percentage", 30 | value: 20000, 31 | formatter: "percentage", 32 | then: "value should be displayed in percentage format", 33 | formattedValue: "+2,000,000%", 34 | }, 35 | { 36 | when: "formatter is set to currency", 37 | value: 20000, 38 | formatter: "currency", 39 | then: "value should be displayed in currency format", 40 | formattedValue: "$20,000.00", 41 | }, 42 | { 43 | when: "a custom formatter function is provided", 44 | value: 20000, 45 | formatterFn: currencyFormatterYen, 46 | then: "value should be displayed in custom format", 47 | formattedValue: "¥20,000", 48 | }, 49 | { 50 | when: "no formatter is set", 51 | value: 20000, 52 | then: "value should be displayed in default number format", 53 | formattedValue: "20000", 54 | }, 55 | ]; 56 | 57 | testCases.forEach( 58 | ({ when, value, formatter, then, formattedValue, formatterFn }) => { 59 | describe(`When ${when}`, () => { 60 | beforeEach(() => { 61 | render( 62 | 67 | ); 68 | }); 69 | it(`Then ${then}`, () => { 70 | const valueEl = screen.getByText(formattedValue); 71 | expect(valueEl).not.toBeNull(); 72 | }); 73 | }); 74 | } 75 | ); 76 | }); 77 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the team at opensource@lab49.com. 59 | All complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@lab49/react-value-flash", 3 | "version": "0.1.7", 4 | "description": "Flash on value change. Perfect for financial applications.", 5 | "author": "brianmcallister", 6 | "license": "MIT", 7 | "repository": "@lab49/react-value-flash", 8 | "bugs": { 9 | "url": "https://github.com/lab49/react-value-flash/issues" 10 | }, 11 | "homepage": "https://github.com/lab49/react-value-flash", 12 | "keywords": [ 13 | "react", 14 | "finance", 15 | "fintech", 16 | "streaming", 17 | "realtime", 18 | "javascript", 19 | "typescript" 20 | ], 21 | "main": "dist/index.js", 22 | "module": "dist/index.modern.js", 23 | "source": "src/Flash.tsx", 24 | "files": [ 25 | "dist" 26 | ], 27 | "scripts": { 28 | "build-storybook": "build-storybook", 29 | "build": "tsup src/Flash.tsx --dts --sourcemap --format esm,cjs,iife", 30 | "lint:staged": "eslint", 31 | "lint": "ESLINT_USE_FLAT_CONFIG=false eslint --config=eslint.config.js --ext=ts,tsx src", 32 | "precommit": "lint-staged", 33 | "prepare": "husky install & npm run build", 34 | "start": "tsup src/Flash.tsx --watch", 35 | "storybook": "start-storybook -p 6006", 36 | "test:watch": "jest --watch", 37 | "test": "jest", 38 | "types": "tsc --noEmit", 39 | "test-storybook": "test-storybook" 40 | }, 41 | "peerDependencies": { 42 | "classnames": "^2.x", 43 | "react": ">=16.8" 44 | }, 45 | "devDependencies": { 46 | "@babel/core": "^7.20.7", 47 | "@babel/preset-env": "^7.20.2", 48 | "@babel/preset-react": "^7.18.6", 49 | "@babel/preset-typescript": "^7.18.6", 50 | "@storybook/addon-actions": "^6.5.15", 51 | "@storybook/addon-essentials": "^6.5.15", 52 | "@storybook/addon-interactions": "^6.5.15", 53 | "@storybook/addon-links": "^6.5.15", 54 | "@storybook/builder-webpack5": "^6.5.15", 55 | "@storybook/jest": "^0.0.10", 56 | "@storybook/manager-webpack5": "^6.5.15", 57 | "@storybook/react": "^6.5.15", 58 | "@storybook/test-runner": "^0.9.2", 59 | "@storybook/testing-library": "^0.0.13", 60 | "@swc/core": "^1.3.24", 61 | "@testing-library/jest-dom": "^5.16.5", 62 | "@testing-library/react": "^13.4.0", 63 | "@testing-library/user-event": "^14.4.3", 64 | "@types/classnames": "^2.3.1", 65 | "@types/jest": "^29.2.4", 66 | "@types/node": "^18.11.18", 67 | "@types/react": "^18.0.26", 68 | "@types/react-dom": "^18.0.10", 69 | "@typescript-eslint/eslint-plugin": "^5.47.1", 70 | "@typescript-eslint/parser": "^5.47.1", 71 | "babel-eslint": "^10.0.3", 72 | "babel-loader": "^9.1.0", 73 | "chromatic": "^6.14.0", 74 | "classnames": "^2.3.2", 75 | "cross-env": "^7.0.3", 76 | "eslint": "^8.30.0", 77 | "eslint-config-airbnb-typescript": "^17.0.0", 78 | "eslint-plugin-eslint-comments": "^3.2.0", 79 | "eslint-plugin-import": "^2.26.0", 80 | "eslint-plugin-jsx-a11y": "^6.6.1", 81 | "eslint-plugin-node": "^11.0.0", 82 | "eslint-plugin-prettier": "^4.2.1", 83 | "eslint-plugin-promise": "^6.1.1", 84 | "eslint-plugin-react": "^7.31.11", 85 | "eslint-plugin-react-hooks": "^4.6.0", 86 | "eslint-plugin-storybook": "^0.6.8", 87 | "html-webpack-plugin": "^5.5.0", 88 | "husky": "^8.0.2", 89 | "jest": "^29.3.1", 90 | "jest-environment-jsdom": "^29.3.1", 91 | "lint-staged": "^13.1.0", 92 | "prettier": "^2.8.1", 93 | "react": "^18.2.0", 94 | "react-dom": "^18.2.0", 95 | "ts-loader": "^9.4.2", 96 | "tsup": "^6.5.0", 97 | "typescript": "^4.9.4" 98 | }, 99 | "husky": { 100 | "hooks": { 101 | "pre-commit": "lint-staged" 102 | } 103 | }, 104 | "lint-staged": { 105 | "*.{js,jsx,ts,tsx}": [ 106 | "eslint --config=eslint.config.js --fix", 107 | "prettier --write" 108 | ] 109 | }, 110 | "jest": { 111 | "testEnvironment": "jsdom" 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/Flash.tsx: -------------------------------------------------------------------------------- 1 | import classnames from "classnames"; 2 | import React from "react"; 3 | 4 | import { formatters, Formatter } from "./formatters/index"; 5 | 6 | export enum FlashDirection { 7 | Down = "down", 8 | Up = "up", 9 | } 10 | 11 | export interface Props { 12 | /** 13 | * Color value when the component flashes 'down'. 14 | */ 15 | downColor?: string; 16 | /** 17 | * One of the built in formatters. 18 | */ 19 | formatter?: "currency" | "percentage" | "number"; 20 | /** 21 | * Pass your own formatter function. 22 | */ 23 | formatterFn?: Formatter; 24 | /** 25 | * Prefix for the CSS selectors in the DOM. 26 | */ 27 | stylePrefix?: string; 28 | /** 29 | * Amount of time the flashed state is visible for, in milliseconds. 30 | */ 31 | timeout?: number; 32 | /** 33 | * Custom CSS transition property. 34 | */ 35 | transition?: string; 36 | /** 37 | * Transition length, in milliseconds. 38 | */ 39 | transitionLength?: number; 40 | /** 41 | * Color value when the component flashes 'up'. 42 | */ 43 | upColor?: string; 44 | /** 45 | * Value to display. The only required prop. 46 | */ 47 | value: number; 48 | } 49 | 50 | /** 51 | * Flash component. 52 | * 53 | * `react-value-flash` will display a flashed value on screen based 54 | * on some value change. This pattern is extremely common in financial 55 | * applications, and at Lab49, we're focused on the finance industry. 56 | * 57 | * Incorporate this component into your application and pass along a 58 | * number. As that number changes, this component will briefly flash 59 | * a color, letting the user know the number has changed. By default, 60 | * this component will flash green when the value changes up, or red 61 | * when the value changes down. 62 | * 63 | * Not only are these colors configurable, but the properties of the 64 | * flash itself and the formatting of the value are configurable as well. 65 | * 66 | * Furthermore, this component doesn't come with any styles, but does 67 | * provide plenty of hooks to add your own styles. Even though flash 68 | * color and transition properties are configurable as props, you can 69 | * still use the generated classnames (which are also configurable) to 70 | * add your own unique styles. 71 | */ 72 | export const Flash = ({ 73 | downColor = "#d43215", 74 | formatter, 75 | formatterFn, 76 | timeout = 200, 77 | transition, 78 | transitionLength = 100, 79 | upColor = "#00d865", 80 | value, 81 | stylePrefix = "rvf_Flash", 82 | }: Props) => { 83 | const ref = React.useRef(value); 84 | const [flash, setFlash] = React.useState(null); 85 | const style = { 86 | transition: 87 | transition || `background-color ${transitionLength}ms ease-in-out`, 88 | ...(flash 89 | ? { backgroundColor: flash === FlashDirection.Up ? upColor : downColor } 90 | : null), 91 | }; 92 | const cls = classnames(stylePrefix, { 93 | [`${stylePrefix}--flashing`]: flash != null, 94 | [`${stylePrefix}--flashing-${flash}`]: flash != null, 95 | [`${stylePrefix}--even`]: value === 0, 96 | [`${stylePrefix}--negative`]: value < 0, 97 | [`${stylePrefix}--positive`]: value > 0, 98 | }); 99 | const valueFormatter = 100 | formatterFn ?? (formatter ? formatters[formatter] : formatters.default); 101 | 102 | React.useEffect(() => { 103 | // If there's no change, only reset (this prevents flash on first render). 104 | // TODO (brianmcallister) - Which, maybe, people might want? 105 | if (ref.current === value) { 106 | setFlash(null); 107 | 108 | return () => {}; 109 | } 110 | 111 | // Set the flash direction. 112 | setFlash(value > ref.current ? FlashDirection.Up : FlashDirection.Down); 113 | 114 | // Reset the flash state after `timeout`. 115 | const timeoutInterval = setTimeout(() => { 116 | setFlash(null); 117 | }, timeout); 118 | 119 | // Update the ref to reflect the new `value`. 120 | ref.current = value; 121 | 122 | return () => { 123 | clearTimeout(timeoutInterval); 124 | }; 125 | }, [value, timeout]); 126 | 127 | return ( 128 |
129 | {valueFormatter(value)} 130 |
131 | ); 132 | }; 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @lab49/react-value-flash 2 | 3 | [![codecov](https://codecov.io/gh/lab49/react-value-flash/branch/master/graph/badge.svg)](https://codecov.io/gh/lab49/react-value-flash) [![.github/workflows/cicd.yml](https://github.com/lab49/react-value-flash/actions/workflows/cicd.yml/badge.svg)](https://github.com/lab49/react-value-flash/actions/workflows/cicd.yml) [![npm version](https://img.shields.io/npm/v/@lab49/react-value-flash?label=version&color=%2354C536&logo=npm)](https://www.npmjs.com/package/@lab49/react-value-flash) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](code_of_conduct.md) 4 | 5 |

 

6 |

7 | 8 |

Flash on value change. Perfect for financial applications.

9 |

10 |

 

11 | 12 | `react-value-flash` will display a flashed value on screen based on some value change. This pattern is extremely common in financial applications, and at Lab49, we're focused on the finance industry. 13 | 14 | Incorporate this component into your application and pass along a number. As that number changes, this component will briefly flash a color, letting the user know the number has changed. By default, this component will flash green when the value changes up, or red when the value changes down. 15 | 16 | Not only are these colors configurable, but the properties of the flash itself and the formatting of the value are configurable as well. 17 | 18 | Furthermore, this component doesn't come with any styles, but does provide plenty of hooks to add your own styles. Even though flash color and transition properties are configurable as props, you can still use the generated classnames (which are also configurable) to add your own unique styles. 19 | 20 |

21 | 22 |

23 | 24 | This component is perfect for: 25 | 26 | - Trading platforms 27 | - Analytics dashboards 28 | - Monitoring dashboards 29 | 30 | ## Features 31 | 32 | - Written in TypeScript 33 | - Small, simple, configurable, performant 34 | - Maintained by a team of finance industry professionals 35 | 36 | ## Table of contents 37 | 38 | - [Demo](#demo) 39 | - [Installation](#installation) 40 | - [Usage](#usage) 41 | - [API](#api) 42 | - [`Flash`](#Flash) 43 | - [`Props`](#Props) 44 | - [`FlashDirection`](#FlashDirection) 45 | - [License](#License) 46 | - [TODO](#TODO) 47 | 48 | ## Demo 49 | 50 | Hosted demo: [https://master--5f3fca6e6b5eba0022c71e4e.chromatic.com/](https://master--5f3fca6e6b5eba0022c71e4e.chromatic.com/) 51 | 52 | You can also run the demo locally. To get started: 53 | 54 | ```sh 55 | git clone git@github.com:lab49/react-value-flash.git 56 | npm install 57 | npm run storybook 58 | ``` 59 | 60 | ###### [⇡ Top](#table-of-contents) 61 | 62 | ## Installation 63 | 64 | ```sh 65 | npm install @lab49/react-value-flash 66 | ``` 67 | 68 | ###### [⇡ Top](#table-of-contents) 69 | 70 | ## Usage 71 | 72 | ```js 73 | import { Flash } from '@lab49/react-value-flash'; 74 | 75 | 76 | ``` 77 | 78 | As discussed above, there are a number of classnames you can use to add your own styles. There is an example of doing exactly that in the include [Storybook](./stories/Flash.stories.tsx), but as an example, here's a description of the available classnames: 79 | 80 | | Class | Description | 81 | | --- | --- | 82 | | `.rvf_Flash` | Root DOM node | 83 | | `.rvf_Flash__value` | Rendered value, direct (and only) child of the root node. | 84 | | `.rvf_Flash--flashing` | Applied only when the component is in the flashing state. | 85 | | `.rvf_Flash--flashing-up` | Applied when flashing 'up'. | 86 | | `.rvf_Flash--flashing-down` | Applied when flashing 'down'. | 87 | | `.rvf_Flash--positive` | Applied when the value is positive. | 88 | | `.rvf_Flash--negative` | Applied when the value is negative. | 89 | 90 | ###### [⇡ Top](#table-of-contents) 91 | 92 | ## API 93 | 94 | ### `Flash` 95 | 96 | `` is a `(props: Props) => JSX.Element`. See `Props` below for a description of the avilable props. 97 | 98 | ```ts 99 | import { Flash } from '@lab49/react-value-flash'; 100 | 101 | const MyComponent = () => ; 102 | ``` 103 | 104 | ### `Props` 105 | 106 | ```ts 107 | interface Props { 108 | /** 109 | * Color value when the component flashes 'down'. 110 | */ 111 | downColor?: string; 112 | /** 113 | * One of the built in formatters. 114 | */ 115 | formatter?: 'currency' | 'percentage' | 'number'; 116 | /** 117 | * Pass your own formatter function. 118 | */ 119 | formatterFn?: Formatter; 120 | /** 121 | * Prefix for the CSS selectors in the DOM. 122 | */ 123 | stylePrefix?: string; 124 | /** 125 | * Amount of time the flashed state is visible for, in milliseconds. 126 | */ 127 | timeout?: number; 128 | /** 129 | * Custom CSS transition property. 130 | */ 131 | transition?: string; 132 | /** 133 | * Transition length, in milliseconds. 134 | */ 135 | transitionLength?: number; 136 | /** 137 | * Color value when the component flashes 'up'. 138 | */ 139 | upColor?: string; 140 | /** 141 | * Value to display. The only required prop. 142 | */ 143 | value: number; 144 | } 145 | ``` 146 | 147 | ### `FlashDirection` 148 | 149 | ```ts 150 | enum FlashDirection { 151 | Down = 'down', 152 | Up = 'up', 153 | } 154 | ``` 155 | 156 | ###### [⇡ Top](#table-of-contents) 157 | 158 | ## License 159 | 160 | MIT @ [Lab49](https://lab49.com) 161 | 162 | ###### [⇡ Top](#table-of-contents) 163 | 164 | ## Sponsored by Lab49 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "esnext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | "lib": ["dom", "esnext"], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./dist", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | "resolveJsonModule": true, 46 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 47 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 48 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 49 | // "typeRoots": [], /* List of folders to include type definitions from. */ 50 | // "types": [], /* Type declaration files to be included in compilation. */ 51 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 52 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 53 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 54 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 55 | 56 | /* Source Map Options */ 57 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 58 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 59 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 60 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 61 | 62 | /* Experimental Options */ 63 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 64 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 65 | 66 | /* Advanced Options */ 67 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 68 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 69 | }, 70 | "include": [ 71 | "src", 72 | "stories", 73 | "." 74 | ] 75 | } 76 | -------------------------------------------------------------------------------- /stories/Flash.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Story, ComponentMeta, ComponentStory } from "@storybook/react"; 3 | import { userEvent, within } from "@storybook/testing-library"; 4 | import { expect } from "@storybook/jest"; 5 | 6 | import { Flash, Props } from "../src/Flash"; 7 | import { useInterval } from "./useInterval"; 8 | import { ValueSetter } from "./components/ValueSetter"; 9 | import pkg from "../package.json"; 10 | 11 | export default { 12 | title: "Flash", 13 | component: Flash, 14 | parameters: { 15 | componentSubtitle: pkg.description, 16 | }, 17 | } as ComponentMeta; 18 | 19 | const numberMap: { [key: string]: string } = { 20 | 0: "zero", 21 | 1: "one", 22 | 2: "two", 23 | 3: "three", 24 | 4: "four", 25 | 5: "five", 26 | 6: "six", 27 | 7: "seven", 28 | 8: "eight", 29 | 9: "nine", 30 | }; 31 | 32 | const Template: Story = (args) => { 33 | return ( 34 | 35 | {(value: number) => } 36 | 37 | ); 38 | }; 39 | 40 | export const Default = Template.bind({}); 41 | 42 | export const StreamingData = () => { 43 | const [hasRan, setHasRan] = React.useState(false); 44 | const [val, setVal] = React.useState(1); 45 | 46 | useInterval(() => { 47 | if (Math.random() > 0.8) { 48 | setHasRan(true); 49 | setVal(Math.floor(Math.random() * 100) - 50); 50 | } 51 | }, 200); 52 | 53 | return ( 54 |
55 |

56 | Stream:  57 | {hasRan ? "Connected!" : "Loading..."} 58 |

59 | 60 | 61 |
62 | ); 63 | }; 64 | 65 | StreamingData.parameters = { 66 | chromatic: { 67 | disable: true, 68 | }, 69 | }; 70 | 71 | export const CustomColors = Template.bind({}); 72 | 73 | CustomColors.args = { 74 | upColor: "blue", 75 | downColor: "purple", 76 | }; 77 | 78 | export const NoTransition = Template.bind({}); 79 | 80 | NoTransition.args = { 81 | transition: "none", 82 | }; 83 | 84 | export const TransitionLength = Template.bind({}); 85 | 86 | TransitionLength.args = { 87 | timeout: 1200, 88 | transitionLength: 1000, 89 | }; 90 | 91 | export const NumberFormatter = Template.bind({}); 92 | 93 | NumberFormatter.args = { 94 | formatter: "number", 95 | }; 96 | 97 | export const CurrencyFormatter: ComponentStory = () => { 98 | return ( 99 | 100 | {(value: number) => } 101 | 102 | ); 103 | }; 104 | 105 | CurrencyFormatter.play = async ({ canvasElement }) => { 106 | const canvas = within(canvasElement); 107 | 108 | await expect(canvas.getByText("$20,000.00")).toBeInTheDocument(); 109 | 110 | await userEvent.click(canvas.getByTestId("first-button")); 111 | 112 | await expect(canvas.getByText("$20,001.00")).toBeInTheDocument(); 113 | }; 114 | 115 | export const PercentageFormatter = () => { 116 | return ( 117 | 118 | {(value: number) => } 119 | 120 | ); 121 | }; 122 | 123 | export const CustomFormatter = () => { 124 | return ( 125 | 126 | {(value: number) => ( 127 | { 130 | return `[${`${val}` 131 | .split("") 132 | .map((v) => numberMap[v]) 133 | .join(", ")}]`; 134 | }} 135 | /> 136 | )} 137 | 138 | ); 139 | }; 140 | 141 | export const StylingComponentClassNames = () => { 142 | return ( 143 |
144 |