redoc/src/common-elements/perfect-scrollbar.tsx

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-01-23 15:58:30 +03:00
import * as React from 'react';
import PerfectScrollbarType, * as PerfectScrollbarNamespace from 'perfect-scrollbar';
2018-01-23 15:58:30 +03:00
import psStyles from 'perfect-scrollbar/css/perfect-scrollbar.css';
import styled, { injectGlobal } from '../styled-components';
/*
* perfect scrollbar umd bundle uses exports assignment while module uses default export
* so when bundled with webpack default export works but with jest it crashes
* That's why the following ugly fix is required
*/
const PerfectScrollbarConstructor =
PerfectScrollbarNamespace.default || ((PerfectScrollbarNamespace as any) as PerfectScrollbarType);
2018-01-23 20:09:23 +03:00
injectGlobal`${psStyles && psStyles.toString()}`;
2018-01-23 15:58:30 +03:00
const StyledScrollWrapper = styled.div`
position: relative;
`;
export class PerfectScrollbar extends React.Component<{
options?: PerfectScrollbarType.Options;
2018-01-23 15:58:30 +03:00
className?: string;
updateFn: (fn) => void;
}> {
private _container: HTMLElement;
private inst: PerfectScrollbarType;
2018-01-23 15:58:30 +03:00
componentDidMount() {
const offset = (this._container.parentElement && this._container.parentElement.scrollTop) || 0;
2018-01-23 15:58:30 +03:00
this.inst = new PerfectScrollbarConstructor(this._container, this.props.options || {});
2018-07-31 16:58:44 +03:00
if (this._container.scrollTo) {
this._container.scrollTo(0, offset);
}
2018-01-23 15:58:30 +03:00
}
componentDidUpdate() {
this.inst.update();
}
componentWillUnmount() {
this.inst.destroy();
}
handleRef = ref => {
this._container = ref;
};
render() {
const { children, className, updateFn } = this.props;
updateFn(this.componentDidUpdate.bind(this));
return (
<StyledScrollWrapper className={`scrollbar-container ${className}`} innerRef={this.handleRef}>
{children}
</StyledScrollWrapper>
);
}
}