Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new(responsive): add ignoreDimensions prop to handle rerenders #834

Merged
merged 4 commits into from
Oct 7, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 54 additions & 61 deletions packages/visx-responsive/src/components/ParentSize.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import debounce from 'lodash/debounce';
import React from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

export type ParentSizeProps = {
/** Optional `className` to add to the parent `div` wrapper used for size measurement. */
className?: string;
/** Child render updates upon resize are delayed until `debounceTime` milliseconds _after_ the last resize event is observed. */
debounceTime?: number;
/** Optional keys provided won't trigger a state change when changed */
wyze marked this conversation as resolved.
Show resolved Hide resolved
disableFor?: keyof ParentSizeState | (keyof ParentSizeState)[];
wyze marked this conversation as resolved.
Show resolved Hide resolved
/** Optional flag to toggle leading debounce calls. When set to true this will ensure that the component always renders immediately. (defaults to true) */
enableDebounceLeadingCall?: boolean;
/** Optional `style` object to apply to the parent `div` wrapper used for size measurement. */
Expand All @@ -29,74 +31,65 @@ type ParentSizeState = {

export type ParentSizeProvidedProps = ParentSizeState;

export default class ParentSize extends React.Component<
ParentSizeProps & Omit<JSX.IntrinsicElements['div'], keyof ParentSizeProps>,
ParentSizeState
> {
static defaultProps = {
debounceTime: 300,
enableDebounceLeadingCall: true,
parentSizeStyles: { width: '100%', height: '100%' },
};
animationFrameID: number = 0;
resizeObserver: ResizeObserver | undefined;
target: HTMLDivElement | null = null;
export default function ParentSize({
className,
children,
debounceTime = 300,
disableFor,
parentSizeStyles = { width: '100%', height: '100%' },
enableDebounceLeadingCall = true,
...restProps
}: ParentSizeProps & Omit<JSX.IntrinsicElements['div'], keyof ParentSizeProps>) {
const target = useRef<HTMLDivElement | null>(null);
const animationFrameID = useRef(0);

state = {
width: 0,
height: 0,
top: 0,
left: 0,
};
const [state, setState] = useState<ParentSizeState>({ width: 0, height: 0, top: 0, left: 0 });

componentDidMount() {
this.resizeObserver = new ResizeObserver((entries = [] /** , observer */) => {
const resize = useMemo(() => {
const normalized = disableFor ? (Array.isArray(disableFor) ? disableFor : [disableFor]) : [];

return debounce(
(incoming: ParentSizeState) => {
setState(existing => {
const stateKeys = Object.keys(existing) as (keyof ParentSizeState)[];
const keysWithChanges = stateKeys.reduce<(keyof ParentSizeState)[]>((diff, key) => {
return existing[key] === incoming[key] ? diff : [...diff, key];
}, []);
wyze marked this conversation as resolved.
Show resolved Hide resolved
const shouldBail = keysWithChanges.every(key => normalized.includes(key));

return shouldBail ? existing : incoming;
});
},
debounceTime,
{ leading: enableDebounceLeadingCall },
);
}, [debounceTime, disableFor, enableDebounceLeadingCall]);

useEffect(() => {
const observer = new ResizeObserver((entries = [] /** , observer */) => {
entries.forEach(entry => {
const { left, top, width, height } = entry.contentRect;
this.animationFrameID = window.requestAnimationFrame(() => {
this.resize({ width, height, top, left });
animationFrameID.current = window.requestAnimationFrame(() => {
resize({ width, height, top, left });
});
});
});
if (this.target) this.resizeObserver.observe(this.target);
}
if (target.current) observer.observe(target.current);

componentWillUnmount() {
window.cancelAnimationFrame(this.animationFrameID);
if (this.resizeObserver) this.resizeObserver.disconnect();
this.resize.cancel();
}
return () => {
window.cancelAnimationFrame(animationFrameID.current);
observer.disconnect();
resize.cancel();
};
}, [resize]);

resize = debounce(
({ width, height, top, left }: ParentSizeState) => {
this.setState(() => ({ width, height, top, left }));
},
this.props.debounceTime,
{ leading: this.props.enableDebounceLeadingCall },
return (
<div style={parentSizeStyles} ref={target} className={className} {...restProps}>
{children({
...state,
ref: target.current,
resize,
})}
</div>
);

setTarget = (ref: HTMLDivElement | null) => {
this.target = ref;
};

render() {
const {
className,
children,
debounceTime,
parentSizeStyles,
enableDebounceLeadingCall,
...restProps
} = this.props;

return (
<div style={parentSizeStyles} ref={this.setTarget} className={className} {...restProps}>
{children({
...this.state,
ref: this.target,
resize: this.resize,
})}
</div>
);
}
}