clientRect.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import {
  21. useRef,
  22. useState,
  23. useCallback,
  24. RefObject,
  25. useLayoutEffect
  26. } from 'react'
  27. import debounce from 'lodash/debounce'
  28. export const CLIENT_RECT_DEBOUNCE_INTERVAL = 200
  29. function useClientRect<T extends HTMLElement>(
  30. debounceInterval: number = CLIENT_RECT_DEBOUNCE_INTERVAL,
  31. realtime: boolean = false
  32. ): [DOMRect, RefObject<T>] {
  33. const ref = useRef<T>(null)
  34. const [rect, setRect] = useState<DOMRect>(null)
  35. const resize = useCallback(
  36. debounce(() => {
  37. if (ref.current) {
  38. setRect(ref.current.getBoundingClientRect())
  39. }
  40. }, debounceInterval),
  41. [ref.current, realtime]
  42. )
  43. useLayoutEffect(() => {
  44. if (!ref.current) {
  45. return
  46. }
  47. resize()
  48. if (typeof ResizeObserver === 'function') {
  49. let resizeObserver = new ResizeObserver(resize)
  50. resizeObserver.observe(ref.current)
  51. return () => {
  52. resizeObserver.disconnect()
  53. resizeObserver = null
  54. }
  55. } else {
  56. window.addEventListener('resize', resize)
  57. return () => {
  58. window.removeEventListener('resize', resize)
  59. }
  60. }
  61. }, [ref.current])
  62. return [rect, ref]
  63. }
  64. export default useClientRect
  65. // refs: https://github.com/rehooks/component-size/blob/master/index.js