├── .babelrc ├── .gitignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── rollup.config.js ├── site ├── .gitignore ├── .prettierrc ├── gatsby-config.js ├── package.json ├── src │ ├── app.css │ └── pages │ │ └── index.js └── yarn.lock ├── src ├── Measure.js ├── __tests__ │ ├── Measure.test.js │ └── __snapshots__ │ │ └── Measure.test.js.snap ├── get-content-rect.js ├── get-types.js ├── get-window-of.js ├── index.js └── with-content-rect.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { "loose": true, "modules": false }], 4 | ["@babel/preset-react", { "useBuiltIns": true }] 5 | ], 6 | "plugins": [["@babel/plugin-proposal-class-properties", { "loose": true }]], 7 | "env": { 8 | "test": { 9 | "plugins": ["@babel/transform-modules-commonjs"] 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log 4 | dist -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "es5", 4 | "semi": false 5 | } 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## CHANGELOG 2 | 3 | ### 2.5.2 4 | 5 | Default to global (possibly polyfilled) ResizeObserver if the local window does not have ResizeObserver #148 6 | 7 | ### 2.5.1 8 | 9 | Use `ResizeObserver` of local `window` object #147 10 | 11 | ### 2.5.0 12 | 13 | Set `innerRef` before observing [#140](https://github.com/souporserious/react-measure/pull/140) 14 | 15 | ### 2.4.0 16 | 17 | Use the local `window` object of the observed node [#146](https://github.com/souporserious/react-measure/pull/146) 18 | 19 | ### 2.3.0 20 | 21 | Fix regression with `contentRect.bounds` not getting called properly 22 | 23 | Note that `onResize` will get called twice when first mounting now 24 | 25 | ### 2.2.6 26 | 27 | Fix initial `onResize` delay caused by `requestAnimationFrame` [#135](https://github.com/souporserious/react-measure/pull/135) 28 | 29 | ### 2.2.5 30 | 31 | Fix sporadic `ResizeObserver` loop limit exceeded error when using `onResize` [#133](https://github.com/souporserious/react-measure/pull/133) 32 | 33 | ### 2.2.4 34 | 35 | Only observe one element, add tests [#130](https://github.com/souporserious/react-measure/pull/130) 36 | 37 | ### 2.2.3 38 | 39 | Fix not passing `ResizeObserver` `entries` to `measure` method [#125](https://github.com/souporserious/react-measure/pull/125) 40 | 41 | Add support for `createRef` [#126](https://github.com/souporserious/react-measure/pull/126) 42 | 43 | ### 2.2.2 44 | 45 | Add `@babel/runtime` as a dependency 46 | 47 | ### 2.2.1 48 | 49 | Fix `ResizeObserver` callback error 50 | 51 | Fix `eslint` warnings 52 | 53 | ### 2.2.0 54 | 55 | Remove `componentWillMount` for React >16 StrictMode compliance 56 | [#121](https://github.com/souporserious/react-measure/pull/121) 57 | 58 | Upgrade `get-node-dimensions` package to `1.2.1` 59 | 60 | Upgrade `prop-types` package to `15.6.2` 61 | 62 | Fixes `disconnect` being used instead of `unobserve` for `ResizeObserver` 63 | 64 | ### 2.1.3 65 | 66 | Update `resize-observer-polyfill` 67 | [#88](https://github.com/souporserious/react-measure/pull/88) 68 | 69 | Added handling when `getComputedStyle` returns `null` 70 | [#89](https://github.com/souporserious/react-measure/pull/89) 71 | 72 | Call `setState` within `requestAnimationFrame` to prevent infinite loop 73 | [#118](https://github.com/souporserious/react-measure/pull/118) 74 | 75 | ### 2.1.2 76 | 77 | Move children propType from with-content-rect to Measure 78 | [#117](https://github.com/souporserious/react-measure/pull/117) 79 | 80 | ### 2.1.1 81 | 82 | Allow children to be any element 83 | [#78](https://github.com/souporserious/react-measure/pull/78) 84 | 85 | ### 2.1.0 86 | 87 | Disconnect and de-initialize resize observer on unmount 88 | [#112](https://github.com/souporserious/react-measure/pull/112) 89 | 90 | Remove `babel-plugin-add-module-exports` 91 | 92 | ### 2.0.2 93 | 94 | Disconnect correct node within `handleRef` 95 | [#51](https://github.com/souporserious/react-measure/pull/51) 96 | 97 | ### 2.0.1 98 | 99 | Observe and disconnect ResizeObserver in ref callback 100 | 101 | ### 2.0.0 102 | 103 | Complete rewrite. Check README for new docs. 104 | 105 | Most transitions from the old API should be easy. You just need to pass a ref 106 | callback down now. If you have any issues please feel free to file an issue. 107 | 108 | ### 1.4.7 109 | 110 | Update to use separate prop-types package as per React 15.5 deprecation 111 | [#43](https://github.com/souporserious/react-measure/pull/43#pullrequestreview-32216767) 112 | 113 | ### 1.4.6 114 | 115 | Update to `resize-observer-polyfill` 1.4.1 116 | 117 | ### 1.4.5 118 | 119 | Update to `resize-observer-polyfill` 1.3.1 to fix Webpack 2 issues 120 | [#29](https://github.com/souporserious/react-measure/issues/29) 121 | 122 | Remove monkey patch for importing `resize-observer-polyfill` 123 | 124 | ### 1.4.4 125 | 126 | Use ResizeObserver.default if available. This fixes older browsers in the local 127 | dev environment. 128 | 129 | ### 1.4.3 130 | 131 | Requiring default export of `resize-observer-polyfill` 132 | [#28](https://github.com/souporserious/react-measure/pull/28) 133 | 134 | ### 1.4.2 135 | 136 | Only require ResizeObserver polyfill when window is available 137 | 138 | ### 1.4.1 139 | 140 | Cleanup old element-resize-detector code 141 | [#23](https://github.com/souporserious/react-measure/pull/23) 142 | 143 | ### 1.4.0 144 | 145 | Moved away from element-resize-detector in favor of 146 | [resize-observer-polyfill](https://github.com/que-etc/resize-observer-polyfill) 147 | 🎉 148 | 149 | ### 1.3.1 150 | 151 | Fixes exception when changing key of rendered child 152 | [#19](https://github.com/souporserious/react-measure/issues/19) 153 | 154 | ### 1.3.0 155 | 156 | Update get-node-dimensions to 1.2.0 157 | 158 | Use `includeMargin` to account for margins when calculating dimensions now 159 | 160 | ### 1.2.2 161 | 162 | Fix dist build 163 | 164 | ### 1.2.1 165 | 166 | Ensure `setState` is not called after unmounting 167 | [#18](https://github.com/souporserious/react-measure/pull/18) 168 | 169 | ### 1.2.0 170 | 171 | Provide dimension defaults 172 | 173 | ### 1.1.0 174 | 175 | Update get-node-dimensions to 1.1.0 176 | 177 | ### 1.0.0 178 | 179 | Update get-node-dimensions to 1.0.0 180 | 181 | `accurate` renamed to `useClone` 182 | 183 | Added `cloneOptions` prop that gets passed to `getNodeDimensions` 184 | 185 | Fixed build to not include `get-node-dimensions` library 186 | 187 | Removed bower support 188 | 189 | ### 0.5.1 190 | 191 | Use properties instead of constructor 192 | 193 | When unmounting, call uninstall in addition to removeAllListeners 194 | [#15](https://github.com/souporserious/react-measure/pull/15) 195 | 196 | ### 0.5.0 197 | 198 | Moved dimension calculations to its own library 199 | 200 | Cleaned up build files for NPMCDN 201 | 202 | ### 0.4.2 203 | 204 | Removed old code from `lib` folder 205 | 206 | Make sure `package.json` cleans `lib` folder on each build 207 | 208 | ### 0.4.1 209 | 210 | Fixed dist build 211 | 212 | Updated to latest element-resize-detector 213 | 214 | ### 0.4.0 215 | 216 | Moved away from MutationObserver's in favor of 217 | [element-resize-detector](https://github.com/wnr/element-resize-detector) 218 | 219 | Added a more convenient API by allowing child functions 220 | [#11](https://github.com/souporserious/react-measure/issues/11) 221 | 222 | `measure` is now a public method available on the Measure component 223 | 224 | `accurate` prop now returns both cloned element width and height 225 | 226 | `shouldMeasure` now accepts only a boolean 227 | 228 | Removed `lodash.debounce` dependency 229 | 230 | ### 0.3.5 231 | 232 | Fixed bug in IE with accurate height calculation when checking for children 233 | nodes. 234 | 235 | Fixed 236 | [deprecation notice](https://www.chromestatus.com/features/5724912467574784) 237 | when calculating SVG dimensions. 238 | 239 | Removed `react-addons-shallow-compare` dependency. 240 | 241 | Moved `react` and `react-dom` packages into peer dependencies. 242 | 243 | ### 0.3.4 244 | 245 | Fix server-side rendering 246 | 247 | ### 0.3.3 248 | 249 | Added public method `getDimensions` 250 | 251 | Clone nodes without any children 252 | 253 | Fixed calculating measurements on resize 254 | 255 | ### 0.3.2 256 | 257 | Patch to fix `shallowCompare` so bower works. 258 | 259 | Added a resize handler to measure component changes on window resize. 260 | 261 | ### 0.3.1 262 | 263 | Renamed `onChange` prop to `onMeasure` 264 | 265 | Added `shouldMeasure` prop, similar to componentShouldUpdate. It determines 266 | whether or not the `onMeasure` callback will fire, useful for perf and not 267 | performing measurements if you don't need to. 268 | 269 | Fixed updating of `config` prop to disconnect and reconnect a new 270 | MutationObserver with the new configuration 271 | 272 | Fixed updaing of `whitelist` & `blacklist` props to use new values 273 | 274 | ### 0.3.0 275 | 276 | Rebuilt from the ground up 277 | 278 | No more cloning of elements! 279 | 280 | Optimized to touch the DOM as least as possible 281 | 282 | `clone`, `forceAutoHeight`, `collection` props removed 283 | 284 | `config` prop added, accepts a 285 | [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) 286 | configuration 287 | 288 | `accurate` prop added, use to get an accurate measurement, only height supported 289 | right now 290 | 291 | ### 0.2.0 292 | 293 | Upgraded to React 0.14.0 294 | 295 | ### 0.1.3 296 | 297 | Added `forceAutoHeight` prop to help with proper height calculation when 298 | children heights are animating 299 | 300 | ### 0.1.2 301 | 302 | Clone prop now exposed to allow optional cloning of component 303 | 304 | Defaults to false which could potentially break components relying on cloned 305 | calculations 306 | 307 | ### 0.1.1 308 | 309 | Set width/height to auto on clone no matter what to get a true dimension 310 | 311 | Append clone directly after original instead of the end of its parent 312 | 313 | Portal now gets destroyed after measurements have been calculated 314 | 315 | ### 0.1.0 316 | 317 | Rewritten to be more React friendly 318 | 319 | Measure component no longer accepts a child function, instead get dimensions by 320 | setting state in onChange callback 321 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 React Measure authors 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 | ## 📏 React Measure 2 | 3 | [![npm version](https://badge.fury.io/js/react-measure.svg)](https://badge.fury.io/js/react-measure) 4 | [![Dependency Status](https://david-dm.org/souporserious/react-measure.svg)](https://david-dm.org/souporserious/react-measure) 5 | 6 | Compute measurements of React components. Uses a 7 | [`ResizeObserver`](https://developers.google.com/web/updates/2016/10/resizeobserver) 8 | to detect when an element's dimensions have changed. 9 | 10 | Includes a 11 | [polyfill for `ResizeObserver`](https://github.com/que-etc/resize-observer-polyfill) 12 | in unsupported browsers. 13 | 14 | ## Install 15 | 16 | `yarn add react-measure` 17 | 18 | `npm install react-measure --save` 19 | 20 | ```html 21 | 22 | (UMD library exposed as `ReactMeasure`) 23 | ``` 24 | 25 | ## Measure Component 26 | 27 | Wrap any child component and calculate its client rect. 28 | 29 | ### Props 30 | 31 | #### `client`: PropTypes.bool 32 | 33 | Adds the following to `contentRect.client` returned in the child function. 34 | 35 | [clientTop](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop), 36 | [clientLeft](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientLeft), 37 | [clientWidth](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth), 38 | and 39 | [clientHeight](https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight). 40 | 41 | #### `offset`: PropTypes.bool 42 | 43 | Adds the following to `contentRect.offset` returned in the child function. 44 | 45 | [offsetTop](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop), 46 | [offsetLeft](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft), 47 | [offsetWidth](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth), 48 | and 49 | [offsetHeight](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight). 50 | 51 | #### `scroll`: PropTypes.bool 52 | 53 | Adds the following to `contentRect.scroll` returned in the child function. 54 | 55 | [scrollTop](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop), 56 | [scrollLeft](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft), 57 | [scrollWidth](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth), 58 | and 59 | [scrollHeight](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight). 60 | 61 | #### `bounds`: PropTypes.bool 62 | 63 | Uses 64 | [getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) 65 | to calculate the element rect and add it to `contentRect.bounds` returned in the 66 | child function. 67 | 68 | #### `margin`: PropTypes.bool 69 | 70 | Uses 71 | [getComputedStyle](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) 72 | to calculate margins and add it to `contentRect.margin` returned in the child 73 | function. 74 | 75 | #### `innerRef`: PropTypes.func 76 | 77 | Use this to access the internal component `ref`. 78 | 79 | #### `onResize`: PropTypes.func 80 | 81 | Callback invoked when either element width or height have changed. Note that this will be called twice on mount to get the initial values. The first call will come from `componentDidMount` while the second call will come from the `ResizeObserver`. 82 | 83 | #### `children`: PropTypes.func 84 | 85 | Children must be a function. Will receive the following object shape: 86 | 87 | - `measureRef`: must be passed down to your component's ref in order to obtain a 88 | proper node to measure 89 | 90 | - `measure`: use to programmatically measure your component, calls the internal 91 | `measure` method in `withContentRect` 92 | 93 | - `contentRect`: this will contain any of the following allowed rects from 94 | above: `client`, `offset`, `scroll`, `bounds`, or `margin`. It will also 95 | include `entry` from the `ResizeObserver` when available. 96 | 97 | ### Example 98 | 99 | ```javascript 100 | import Measure from 'react-measure' 101 | import classNames from 'classnames' 102 | 103 | class ItemToMeasure extends Component { 104 | state = { 105 | dimensions: { 106 | width: -1, 107 | height: -1, 108 | }, 109 | } 110 | 111 | render() { 112 | const { width, height } = this.state.dimensions 113 | const className = classNames(width < 400 && 'small-width-modifier') 114 | 115 | return ( 116 | { 119 | this.setState({ dimensions: contentRect.bounds }) 120 | }} 121 | > 122 | {({ measureRef }) => ( 123 |
124 | I can do cool things with my dimensions now :D 125 | {height > 250 && ( 126 |
Render responsive content based on the component size!
127 | )} 128 |
129 | )} 130 |
131 | ) 132 | } 133 | } 134 | ``` 135 | 136 | ## withContentRect(types) HoC 137 | 138 | A higher-order component that provides dimensions to the wrapped component. 139 | Accepts `types`, which determines what measurements are returned, similar to 140 | above. Then returns a function to pass the component you want measured. 141 | 142 | Pass an array or single value of either `client`, `offset`, `scroll`, `bounds`, 143 | or `margin` to calculate and receive those measurements as the prop 144 | `contentRect` in your wrapped component. You can also use the `measure` function 145 | passed down to programmatically measure your component if you need to. And 146 | finally, remember to pass down the `measureRef` to the component you want 147 | measured. 148 | 149 | Passes down the same props as the `Measure` child function above, `measureRef`, 150 | `measure`, and `contentRect`. 151 | 152 | Fun fact, the `Measure` component is a thin wrapper around `withContentRect`. 153 | Just check 154 | [the source](https://github.com/souporserious/react-measure/blob/master/src/Measure.js). 155 | This means your wrapped component will accept the same props as `Measure` does 156 | 😊 157 | 158 | ### Example 159 | 160 | ```javascript 161 | import { withContentRect } from 'react-measure' 162 | 163 | const ItemToMeasure = withContentRect('bounds')( 164 | ({ measureRef, measure, contentRect }) => ( 165 |
166 | Some content here 167 |
{JSON.stringify(contentRect, null, 2)}
168 |
169 | ) 170 | ) 171 | ``` 172 | 173 | ## Run Example 174 | 175 | clone repo 176 | 177 | `git clone git@github.com:souporserious/react-measure.git` 178 | 179 | move into folder 180 | 181 | `cd ~/react-measure` 182 | 183 | install package dependencies 184 | 185 | `yarn` 186 | 187 | move into site folder and install local site dependencies 188 | 189 | `cd ~/site && yarn` 190 | 191 | run development mode 192 | 193 | `yarn gatsby develop` 194 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-measure", 3 | "version": "2.5.2", 4 | "description": "Compute measurements of React components.", 5 | "main": "dist/index.cjs.js", 6 | "module": "dist/index.esm.js", 7 | "files": [ 8 | "dist", 9 | "src" 10 | ], 11 | "scripts": { 12 | "build": "rollup -c", 13 | "test": "jest --env=jsdom", 14 | "test:ci": "cross-env CI=1 jest --env=jsdom", 15 | "prettier": "prettier --write 'src/**/*.{js,json,css}'", 16 | "prepublishOnly": "npm run build" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/souporserious/react-measure" 21 | }, 22 | "keywords": [ 23 | "react", 24 | "component", 25 | "measure", 26 | "measurements", 27 | "dimensions", 28 | "element-queries", 29 | "container-queries", 30 | "size" 31 | ], 32 | "author": "Travis Arnold (http://souporserious.com)", 33 | "license": "MIT", 34 | "bugs": { 35 | "url": "https://github.com/souporserious/react-measure/issues" 36 | }, 37 | "homepage": "https://github.com/souporserious/react-measure", 38 | "jest": { 39 | "roots": [ 40 | "/src" 41 | ] 42 | }, 43 | "peerDependencies": { 44 | "react": ">0.13.0", 45 | "react-dom": ">0.13.0" 46 | }, 47 | "dependencies": { 48 | "@babel/runtime": "^7.2.0", 49 | "get-node-dimensions": "^1.2.1", 50 | "prop-types": "^15.6.2", 51 | "resize-observer-polyfill": "^1.5.0" 52 | }, 53 | "devDependencies": { 54 | "@babel/cli": "^7.2.0", 55 | "@babel/core": "^7.2.0", 56 | "@babel/plugin-proposal-class-properties": "^7.2.1", 57 | "@babel/plugin-transform-runtime": "^7.2.0", 58 | "@babel/preset-env": "^7.2.0", 59 | "@babel/preset-react": "^7.0.0", 60 | "cross-env": "^5.2.0", 61 | "jest": "^24.0.0", 62 | "prettier": "^1.16.4", 63 | "react": "^16.7.0", 64 | "react-dom": "^16.7.0", 65 | "rollup": "^0.67.4", 66 | "rollup-plugin-babel": "^4.1.0", 67 | "rollup-plugin-node-resolve": "^4.0.0" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel' 2 | import resolve from 'rollup-plugin-node-resolve' 3 | import pkg from './package.json' 4 | 5 | const getBabelOptions = ({ useESModules }) => ({ 6 | exclude: 'node_modules/**', 7 | runtimeHelpers: true, 8 | plugins: [['@babel/plugin-transform-runtime', { useESModules }]], 9 | }) 10 | 11 | const isExternal = id => !id.startsWith('.') && !id.startsWith('/') 12 | 13 | const input = './src/index.js' 14 | 15 | const umd = { 16 | input, 17 | output: { 18 | file: 'dist/index.umd.js', 19 | format: 'umd', 20 | name: 'ReactMeasure', 21 | globals: { 22 | react: 'React', 23 | }, 24 | }, 25 | external: ['react', 'prop-types'], 26 | plugins: [resolve(), babel(getBabelOptions({ useESModules: true }))], 27 | } 28 | 29 | const es = { 30 | input, 31 | output: { file: pkg.module, format: 'es' }, 32 | external: isExternal, 33 | plugins: [babel(getBabelOptions({ useESModules: true }))], 34 | } 35 | 36 | const cjs = { 37 | input, 38 | output: { file: pkg.main, format: 'cjs' }, 39 | external: isExternal, 40 | plugins: [babel(getBabelOptions({ useESModules: false }))], 41 | } 42 | 43 | export default [umd, es, cjs] 44 | -------------------------------------------------------------------------------- /site/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # dotenv environment variables file 55 | .env 56 | 57 | # gatsby files 58 | .cache/ 59 | public 60 | 61 | # Mac files 62 | .DS_Store 63 | 64 | # Yarn 65 | yarn-error.log 66 | .pnp/ 67 | .pnp.js 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | -------------------------------------------------------------------------------- /site/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /site/gatsby-config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | pathPrefix: '/react-measure', 3 | siteMetadata: { 4 | title: '📏 React Measure', 5 | }, 6 | plugins: [ 7 | 'gatsby-plugin-react-helmet', 8 | { 9 | resolve: `gatsby-plugin-manifest`, 10 | options: { 11 | name: 'gatsby-starter-default', 12 | short_name: 'starter', 13 | start_url: '/', 14 | background_color: '#663399', 15 | theme_color: '#663399', 16 | display: 'minimal-ui', 17 | }, 18 | }, 19 | ], 20 | } 21 | -------------------------------------------------------------------------------- /site/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gatsby-starter-default", 3 | "description": "Gatsby default starter", 4 | "version": "1.0.0", 5 | "author": "Kyle Mathews ", 6 | "dependencies": { 7 | "gatsby": "^2.0.53", 8 | "gatsby-image": "^2.0.20", 9 | "gatsby-plugin-manifest": "^2.0.9", 10 | "gatsby-plugin-offline": "^2.0.16", 11 | "gatsby-plugin-react-helmet": "^3.0.2", 12 | "gatsby-plugin-sharp": "^2.0.14", 13 | "gatsby-source-filesystem": "^2.0.8", 14 | "gatsby-transformer-sharp": "^2.1.8", 15 | "react": "^16.6.3", 16 | "react-dom": "^16.6.3", 17 | "react-helmet": "^5.2.0" 18 | }, 19 | "keywords": [ 20 | "gatsby" 21 | ], 22 | "license": "MIT", 23 | "scripts": { 24 | "build": "gatsby build", 25 | "develop": "gatsby develop", 26 | "deploy": "gatsby build --prefix-paths && gh-pages -d public", 27 | "format": "prettier --write \"src/**/*.js\"" 28 | }, 29 | "devDependencies": { 30 | "gh-pages": "^2.0.1", 31 | "prettier": "^1.15.2" 32 | }, 33 | "repository": { 34 | "type": "git", 35 | "url": "https://github.com/gatsbyjs/gatsby-starter-default" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /site/src/app.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | body { 6 | padding: 24px; 7 | } 8 | 9 | button { 10 | outline: 0; 11 | cursor: pointer; 12 | } 13 | 14 | #app { 15 | max-width: 800px; 16 | margin: 0 auto; 17 | } 18 | 19 | .measure-example header, 20 | .measure-example main { 21 | display: flex; 22 | } 23 | 24 | .paragraphs { 25 | flex: 1; 26 | } 27 | .paragraphs-measurements { 28 | flex: 1; 29 | } 30 | 31 | .square { 32 | width: 50%; 33 | height: 300px; 34 | background: orange; 35 | } 36 | 37 | .animate { 38 | animation: animateInOut 1000ms infinite; 39 | } 40 | 41 | @keyframes animateInOut { 42 | 0%, 43 | 100% { 44 | width: 50%; 45 | height: 300px; 46 | } 47 | 50% { 48 | width: 100%; 49 | height: 600px; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /site/src/pages/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import Measure from '../../../src' 3 | 4 | import '../app.css' 5 | 6 | function Paragraph() { 7 | return ( 8 |
9 |

10 | The path of the righteous man is beset on all sides by the iniquities of 11 | the selfish and the tyranny of evil men. Blessed is he who, in the name 12 | of charity and good will, shepherds the weak through the valley of 13 | darkness, for he is truly his brother's keeper and the finder of lost 14 | children. And I will strike down upon thee with great vengeance and 15 | furious anger those who would attempt to poison and destroy My brothers. 16 | And you will know My name is the Lord when I lay My vengeance upon thee.{' '} 17 |

18 |
19 | ) 20 | } 21 | 22 | class Paragraphs extends Component { 23 | constructor(props) { 24 | super(props) 25 | this.state = { 26 | count: 0, 27 | display: true, 28 | contentRect: {}, 29 | } 30 | } 31 | 32 | _renderParagraphs() { 33 | let paragraphs = [] 34 | for (let i = 0; i < this.state.count; i++) { 35 | paragraphs.push() 36 | } 37 | return paragraphs 38 | } 39 | 40 | render() { 41 | const { count, display } = this.state 42 | return ( 43 | 44 | {({ measure, measureRef, contentRect }) => ( 45 |
46 |
47 | 50 | 53 | 54 |
55 |
{JSON.stringify(contentRect.scroll, null, 2)}
56 |
63 |
70 | {this._renderParagraphs()} 71 |
72 |
73 |
74 | )} 75 |
76 | ) 77 | } 78 | } 79 | 80 | const AnimatingChild = ({ animate }) => ( 81 | 82 | {({ measureRef, contentRect }) => ( 83 |
84 | 85 | {animate ? 'Click to stop animating' : 'Click to animate'} 86 | 87 |
{JSON.stringify(contentRect.offset, null, 2)}
88 |
89 | )} 90 |
91 | ) 92 | 93 | class App extends Component { 94 | state = { 95 | animate: false, 96 | } 97 | 98 | render() { 99 | const { animate } = this.state 100 | return ( 101 |
102 | 103 | {({ measureRef, contentRect }) => ( 104 |
105 | 106 |
107 | )} 108 |
109 |
this.setState({ animate: !animate })}> 110 | 111 |
112 |
113 | ) 114 | } 115 | } 116 | 117 | export default App 118 | -------------------------------------------------------------------------------- /src/Measure.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import withContentRect from './with-content-rect' 3 | 4 | const Measure = withContentRect()( 5 | ({ measure, measureRef, contentRect, children }) => 6 | children({ measure, measureRef, contentRect }) 7 | ) 8 | 9 | Measure.displayName = 'Measure' 10 | Measure.propTypes.children = PropTypes.func 11 | 12 | export default Measure 13 | -------------------------------------------------------------------------------- /src/__tests__/Measure.test.js: -------------------------------------------------------------------------------- 1 | import React, { createRef } from 'react' 2 | import { render } from 'react-dom' 3 | 4 | describe('Measure', () => { 5 | let container, resizeObserver, defaultChildrenFn, MeasureWith 6 | 7 | beforeEach(() => { 8 | jest.useFakeTimers() 9 | jest.resetModules() 10 | 11 | global.ResizeObserver = jest.fn( 12 | callback => 13 | (resizeObserver = { 14 | observe: jest.fn(), 15 | unobserve: jest.fn(), 16 | disconnect: jest.fn(), 17 | callback, 18 | }) 19 | ) 20 | 21 | global.requestAnimationFrame = cb => setTimeout(cb, 0) 22 | 23 | defaultChildrenFn = jest.fn(({ measureRef, ...rest }) => ( 24 |
{JSON.stringify(rest, null, 2)}
25 | )) 26 | const setupMeasure = Measure => ({ 27 | children = defaultChildrenFn, 28 | ...rest 29 | }) => {children} 30 | 31 | MeasureWith = setupMeasure(require('../Measure').default) 32 | container = document.createElement('div') 33 | }) 34 | 35 | it('should handle entry', () => { 36 | const ref = createRef() 37 | render(, container) 38 | expect(container.firstChild).toMatchSnapshot() 39 | 40 | resizeObserver.callback([ 41 | { contentRect: { width: 0, height: 0 }, target: ref.current }, 42 | ]) 43 | jest.runAllTimers() 44 | 45 | expect(defaultChildrenFn).toHaveBeenCalledTimes(2) 46 | expect(container.firstChild).toMatchSnapshot() 47 | }) 48 | 49 | it('should handle bounds', () => { 50 | render(, container) 51 | expect(container.firstChild).toMatchSnapshot() 52 | 53 | resizeObserver.callback() 54 | jest.runAllTimers() 55 | 56 | expect(defaultChildrenFn).toHaveBeenCalledTimes(2) 57 | expect(container.firstChild).toMatchSnapshot() 58 | }) 59 | 60 | describe('resizeObserver', () => { 61 | it('should trigger observe when measureRef is attached', () => { 62 | render(, container) 63 | expect(resizeObserver.observe).toHaveBeenCalledTimes(1) 64 | }) 65 | it('should always unobserve before observing next one', () => { 66 | const ref = createRef() 67 | 68 | render( null} />, container) 69 | expect(ref.current).toBe(null) 70 | 71 | render( 72 | ( 75 | <> 76 |
77 |
78 | 79 | )} 80 | />, 81 | container 82 | ) 83 | expect(resizeObserver.observe).toHaveBeenCalledTimes(2) 84 | expect(resizeObserver.unobserve).toHaveBeenCalledTimes(1) 85 | 86 | expect(resizeObserver.observe.mock.calls[0][0].id).toBe('child1') 87 | expect(resizeObserver.unobserve.mock.calls[0][0].id).toBe('child1') 88 | expect(resizeObserver.observe.mock.calls[1][0].id).toBe('child2') 89 | 90 | expect(ref.current.id).toBe('child2') 91 | }) 92 | it('should trigger onResize after setting innerRef', () => { 93 | const ref = createRef() 94 | 95 | let refOnResize = undefined; 96 | const onResize = () => refOnResize = ref.current 97 | render( 98 |
} 102 | />, 103 | container 104 | ) 105 | expect(refOnResize).not.toBe(null) 106 | expect(refOnResize.id).toBe('child') 107 | }) 108 | it('should trigger onResize when componentDidMount is called', () => { 109 | const onResize = jest.fn() 110 | render(, container) 111 | expect(onResize).toHaveBeenCalledTimes(1) 112 | }) 113 | it('should trigger onResize when resizeObserver callback is called', () => { 114 | const onResize = jest.fn() 115 | 116 | render(, container) 117 | resizeObserver.callback() 118 | jest.runAllTimers() 119 | 120 | expect(onResize).toHaveBeenCalledTimes(2) 121 | }) 122 | }) 123 | }) 124 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/Measure.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Measure should handle bounds 1`] = ` 4 |
5 | { 6 | "contentRect": { 7 | "entry": {}, 8 | "client": {}, 9 | "offset": {}, 10 | "scroll": {}, 11 | "bounds": {}, 12 | "margin": {} 13 | } 14 | } 15 |
16 | `; 17 | 18 | exports[`Measure should handle bounds 2`] = ` 19 |
20 | { 21 | "contentRect": { 22 | "bounds": { 23 | "top": 0, 24 | "right": 0, 25 | "bottom": 0, 26 | "left": 0, 27 | "width": 0, 28 | "height": 0 29 | } 30 | } 31 | } 32 |
33 | `; 34 | 35 | exports[`Measure should handle entry 1`] = ` 36 |
37 | { 38 | "contentRect": { 39 | "entry": {}, 40 | "client": {}, 41 | "offset": {}, 42 | "scroll": {}, 43 | "bounds": {}, 44 | "margin": {} 45 | } 46 | } 47 |
48 | `; 49 | 50 | exports[`Measure should handle entry 2`] = ` 51 |
52 | { 53 | "contentRect": { 54 | "entry": { 55 | "width": 0, 56 | "height": 0 57 | } 58 | } 59 | } 60 |
61 | `; 62 | -------------------------------------------------------------------------------- /src/get-content-rect.js: -------------------------------------------------------------------------------- 1 | function getContentRect(node, types) { 2 | const calculations = {} 3 | 4 | if (types.indexOf('client') > -1) { 5 | calculations.client = { 6 | top: node.clientTop, 7 | left: node.clientLeft, 8 | width: node.clientWidth, 9 | height: node.clientHeight, 10 | } 11 | } 12 | 13 | if (types.indexOf('offset') > -1) { 14 | calculations.offset = { 15 | top: node.offsetTop, 16 | left: node.offsetLeft, 17 | width: node.offsetWidth, 18 | height: node.offsetHeight, 19 | } 20 | } 21 | 22 | if (types.indexOf('scroll') > -1) { 23 | calculations.scroll = { 24 | top: node.scrollTop, 25 | left: node.scrollLeft, 26 | width: node.scrollWidth, 27 | height: node.scrollHeight, 28 | } 29 | } 30 | 31 | if (types.indexOf('bounds') > -1) { 32 | const rect = node.getBoundingClientRect() 33 | calculations.bounds = { 34 | top: rect.top, 35 | right: rect.right, 36 | bottom: rect.bottom, 37 | left: rect.left, 38 | width: rect.width, 39 | height: rect.height, 40 | } 41 | } 42 | 43 | if (types.indexOf('margin') > -1) { 44 | const styles = getComputedStyle(node) 45 | calculations.margin = { 46 | top: styles ? parseInt(styles.marginTop) : 0, 47 | right: styles ? parseInt(styles.marginRight) : 0, 48 | bottom: styles ? parseInt(styles.marginBottom) : 0, 49 | left: styles ? parseInt(styles.marginLeft) : 0, 50 | } 51 | } 52 | 53 | return calculations 54 | } 55 | 56 | export default getContentRect 57 | -------------------------------------------------------------------------------- /src/get-types.js: -------------------------------------------------------------------------------- 1 | const types = ['client', 'offset', 'scroll', 'bounds', 'margin'] 2 | 3 | export default function getTypes(props) { 4 | const allowedTypes = [] 5 | types.forEach(type => { 6 | if (props[type]) { 7 | allowedTypes.push(type) 8 | } 9 | }) 10 | return allowedTypes 11 | } 12 | -------------------------------------------------------------------------------- /src/get-window-of.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns the global window object associated with provided element. 3 | */ 4 | function getWindowOf(target) { 5 | // Assume that the element is an instance of Node, which means that it 6 | // has the "ownerDocument" property from which we can retrieve a 7 | // corresponding global object. 8 | const ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView 9 | 10 | // Return the local window object if it's not possible extract one from 11 | // provided element. 12 | return ownerGlobal || window 13 | }; 14 | 15 | export default getWindowOf 16 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import Measure from './Measure' 2 | import withContentRect from './with-content-rect' 3 | 4 | export { Measure as default, withContentRect } 5 | -------------------------------------------------------------------------------- /src/with-content-rect.js: -------------------------------------------------------------------------------- 1 | import { Component, createElement } from 'react' 2 | import PropTypes from 'prop-types' 3 | import ResizeObserver from 'resize-observer-polyfill' 4 | 5 | import getTypes from './get-types' 6 | import getContentRect from './get-content-rect' 7 | import getWindowOf from './get-window-of' 8 | 9 | function withContentRect(types) { 10 | return WrappedComponent => 11 | class WithContentRect extends Component { 12 | static propTypes = { 13 | client: PropTypes.bool, 14 | offset: PropTypes.bool, 15 | scroll: PropTypes.bool, 16 | bounds: PropTypes.bool, 17 | margin: PropTypes.bool, 18 | innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), 19 | onResize: PropTypes.func, 20 | } 21 | 22 | state = { 23 | contentRect: { 24 | entry: {}, 25 | client: {}, 26 | offset: {}, 27 | scroll: {}, 28 | bounds: {}, 29 | margin: {}, 30 | }, 31 | } 32 | 33 | _animationFrameID = null 34 | 35 | _resizeObserver = null 36 | 37 | _node = null 38 | 39 | _window = null 40 | 41 | componentDidMount() { 42 | this._resizeObserver = (this._window !== null && this._window.ResizeObserver) 43 | ? new this._window.ResizeObserver(this.measure) 44 | : new ResizeObserver(this.measure); 45 | if (this._node !== null) { 46 | this._resizeObserver.observe(this._node) 47 | 48 | if (typeof this.props.onResize === 'function') { 49 | this.props.onResize( 50 | getContentRect(this._node, types || getTypes(this.props)) 51 | ) 52 | } 53 | } 54 | } 55 | 56 | componentWillUnmount() { 57 | if (this._window !== null) { 58 | this._window.cancelAnimationFrame(this._animationFrameID) 59 | } 60 | 61 | if (this._resizeObserver !== null) { 62 | this._resizeObserver.disconnect() 63 | this._resizeObserver = null 64 | } 65 | } 66 | 67 | measure = entries => { 68 | const contentRect = getContentRect( 69 | this._node, 70 | types || getTypes(this.props) 71 | ) 72 | 73 | if (entries) { 74 | contentRect.entry = entries[0].contentRect 75 | } 76 | 77 | this._animationFrameID = this._window.requestAnimationFrame(() => { 78 | if (this._resizeObserver !== null) { 79 | this.setState({ contentRect }) 80 | if (typeof this.props.onResize === 'function') { 81 | this.props.onResize(contentRect) 82 | } 83 | } 84 | }) 85 | } 86 | 87 | _handleRef = node => { 88 | if (this._resizeObserver !== null && this._node !== null) { 89 | this._resizeObserver.unobserve(this._node) 90 | } 91 | 92 | this._node = node 93 | this._window = getWindowOf(this._node) 94 | 95 | const { innerRef } = this.props 96 | if (innerRef) { 97 | if (typeof innerRef === 'function') { 98 | innerRef(this._node) 99 | } else { 100 | innerRef.current = this._node 101 | } 102 | } 103 | 104 | if (this._resizeObserver !== null && this._node !== null) { 105 | this._resizeObserver.observe(this._node) 106 | } 107 | } 108 | 109 | render() { 110 | const { innerRef, onResize, ...props } = this.props 111 | return createElement(WrappedComponent, { 112 | ...props, 113 | measureRef: this._handleRef, 114 | measure: this.measure, 115 | contentRect: this.state.contentRect, 116 | }) 117 | } 118 | } 119 | } 120 | 121 | export default withContentRect 122 | --------------------------------------------------------------------------------