Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* eslint-disable max-classes-per-file */
- import React from 'react';
- import PropTypes from 'prop-types';
- function ColbertMountNode(props) {
- return <div>{props.children}</div>;
- }
- function ColbertPreloader(props) {
- return <div>{props.children}</div>;
- }
- class ColbertQuestionnaireError extends Error {}
- class ColbertQuestionnaire extends React.Component {
- static propTypes = {
- questionId: PropTypes.string.isRequired,
- };
- constructor(props) {
- super(props);
- this.references = {};
- }
- state = {
- loading: true,
- mounted: false,
- };
- componentDidMount() {
- if (!window.colbert) {
- this.hide();
- return;
- }
- if (!this.references.mountNode) {
- throw new ColbertQuestionnaireError('"ColbertMountNode" is not found in child components');
- }
- const options = {
- id: this.props.questionId,
- onSuccess: this.onSuccess,
- onFailure: this.onFailure,
- };
- window.colbert('mountQuestionnaire', this.references.mountNode, options);
- }
- onSuccess = () => {
- if (this.isStillMounted()) {
- this.setState({ loading: false, mounted: true });
- }
- };
- onFailure = () => {
- if (this.isStillMounted()) {
- this.hide();
- }
- };
- getOptsForComponent = (component) => {
- switch (component.type) {
- case ColbertPreloader:
- return { hidden: !this.state.loading };
- case ColbertMountNode:
- return {
- ref: (ref) => { this.references.mountNode = ref; },
- hidden: !this.state.mounted,
- };
- default:
- return null;
- }
- };
- isStillMounted = () => {
- // This component has methods that's used as callbacks in external library
- // so we should check that's this component is still mounted
- return this.references.mountNode;
- };
- hide = () => {
- this.setState({ loading: false, mounted: false });
- };
- childrenWithRefs = () => {
- return React.Children.map(this.props.children, (child) => {
- const opts = this.getOptsForComponent(child);
- if (!opts) {
- return child;
- }
- return (
- <div className={child.props.className} {...opts}>
- {child}
- </div>
- );
- });
- };
- render() {
- const hidden = !(this.state.loading || this.state.mounted);
- return (
- <div className={this.props.className} hidden={hidden}>
- {this.childrenWithRefs()}
- </div>
- );
- }
- }
- export {
- ColbertQuestionnaire,
- ColbertMountNode,
- ColbertPreloader,
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement