feat: feature detection and disable resize when necessary

This commit is contained in:
EnixCoda 2019-08-20 21:09:46 +08:00
parent 9ce4fb4264
commit 9622cfc86e
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD
3 changed files with 38 additions and 20 deletions

View file

@ -4,6 +4,7 @@ import cx from 'utils/cx'
import { useWindowSize, useMediaStyleSheet } from 'utils/hooks'
import { bodySpacingClassName } from 'utils/DOMHelper'
import configHelper, { configKeys } from 'utils/configHelper'
import * as features from 'utils/features'
export type Size = number
type Props = {
@ -53,12 +54,14 @@ export default function Resizable({
return (
<div className={cx('gitako-position-wrapper', className)}>
<div className={'gitako-position-content'}>{children}</div>
<HorizontalResizeHandler
onResize={size => {
if (size < window.innerWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH) setSize(size)
}}
size={size}
/>
{features.resize && (
<HorizontalResizeHandler
onResize={size => {
if (size < window.innerWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH) setSize(size)
}}
size={size}
/>
)}
</div>
)
}

View file

@ -1,4 +1,5 @@
import * as React from 'react'
import * as features from 'utils/features'
type Size = {
width: number
@ -23,24 +24,37 @@ export default function SizeObserver({
})
React.useEffect(() => {
const observer = new window.ResizeObserver(entries => {
const entry = entries[0]
if (!entry) return
const rect = entry.contentRect
// requestAnimationFrame fixes "ResizeObserver loop limit exceeded" error
requestAnimationFrame(() =>
setSize({
width: rect.width,
height: rect.height,
}),
)
})
if (features.resize) {
const observer = new window.ResizeObserver(entries => {
const entry = entries[0]
if (!entry) return
const rect = entry.contentRect
safeSetSize(rect)
})
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
} else {
if (ref.current) {
if ('getBoundingClientRect' in ref.current) {
const rect = ref.current.getBoundingClientRect()
setSize(rect)
}
}
}
}, [])
const props: any = { ...rest, ref } // :)
return React.createElement(type, props, children(size))
function safeSetSize(rect: DOMRectReadOnly) {
// requestAnimationFrame fixes "ResizeObserver loop limit exceeded" error
requestAnimationFrame(() =>
setSize({
width: rect.width,
height: rect.height,
}),
)
}
}

1
src/utils/features.ts Normal file
View file

@ -0,0 +1 @@
export const resize = Boolean(window.ResizeObserver)