All files / src getDataFromTree.ts

97.17% Statements 103/106
86.9% Branches 73/84
100% Functions 22/22
96.97% Lines 96/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 25427x                                                 133x       305x       133x           105x           27x                   313x 6x 2x     311x 6x       305x 261x 133x 133x 133x 133x     133x 105x       105x     105x     105x           105x 3x       1x   3x     105x 1x 1x 1x   104x 1x 103x 2x     105x 19x     105x 27x     78x     28x       28x     104x 100x 10x   95x     128x   8x       8x 8x   2x 2x     6x     8x 8x 4x   6x         120x       120x 72x 124x 122x         44x   44x           95x       30x       46x 92x   46x   46x 201x 30x 30x 27x 27x         44x         46x     46x   44x 24x     27x 27x 26x 3x     20x       20x   18x   1x   1x     1x 1x       27x   40x   20x 20x   20x 20x      
import * as React from 'react';
 
export interface Context {
  [key: string]: any;
}
 
interface PromiseTreeArgument {
  rootElement: React.ReactNode;
  rootContext?: Context;
}
interface FetchComponent extends React.Component<any> {
  fetchData(): Promise<void>;
}
 
interface PromiseTreeResult {
  promise: Promise<any>;
  context: Context;
  instance: FetchComponent;
}
 
interface PreactElement<P> {
  attributes: P;
}
 
function getProps<P>(element: React.ReactElement<P> | PreactElement<P>): P {
  return (element as React.ReactElement<P>).props || (element as PreactElement<P>).attributes;
}
 
function isReactElement(element: React.ReactNode): element is React.ReactElement<any> {
  return !!(element as any).type;
}
 
function isComponentClass(Comp: React.ComponentType<any>): Comp is React.ComponentClass<any> {
  return Comp.prototype && (Comp.prototype.render || Comp.prototype.isReactComponent);
}
 
function providesChildContext(
  instance: React.Component<any>,
): instance is React.Component<any> & React.ChildContextProvider<any> {
  return !!(instance as any).getChildContext;
}
 
// Recurse a React Element tree, running visitor on each element.
// If visitor returns `false`, don't call the element's render function
// or recurse into its child elements.
export function walkTree(
  element: React.ReactNode,
  context: Context,
  visitor: (
    element: React.ReactNode,
    instance: React.Component<any> | null,
    context: Context,
    childContext?: Context,
  ) => boolean | void,
) {
  if (Array.isArray(element)) {
    element.forEach(item => walkTree(item, context, visitor));
    return;
  }
 
  if (!element) {
    return;
  }
 
  // A stateless functional component or a class
  if (isReactElement(element)) {
    if (typeof element.type === 'function') {
      const Comp = element.type;
      const props = Object.assign({}, Comp.defaultProps, getProps(element));
      let childContext = context;
      let child;
 
      // Are we are a react class?
      if (isComponentClass(Comp)) {
        const instance = new Comp(props, context);
        // In case the user doesn't pass these to super in the constructor.
        // Note: `Component.props` are now readonly in `@types/react`, so
        // we're using `defineProperty` as a workaround (for now).
        Object.defineProperty(instance, 'props', {
          value: instance.props || props,
        });
        instance.context = instance.context || context;
 
        // Set the instance state to null (not undefined) if not set, to match React behaviour
        instance.state = instance.state || null;
 
        // Override setState to just change the state, not queue up an update
        // (we can't do the default React thing as we aren't mounted
        // "properly", however we don't need to re-render as we only support
        // setState in componentWillMount, which happens *before* render).
        instance.setState = newState => {
          if (typeof newState === 'function') {
            // React's TS type definitions don't contain context as a third parameter for
            // setState's updater function.
            // Remove this cast to `any` when that is fixed.
            newState = (newState as any)(instance.state, instance.props, instance.context);
          }
          instance.state = Object.assign({}, instance.state, newState);
        };
 
        if (Comp.getDerivedStateFromProps) {
          const result = Comp.getDerivedStateFromProps(instance.props, instance.state);
          Eif (result !== null) {
            instance.state = Object.assign({}, instance.state, result);
          }
        } else if (instance.UNSAFE_componentWillMount) {
          instance.UNSAFE_componentWillMount();
        } else if (instance.componentWillMount) {
          instance.componentWillMount();
        }
 
        if (providesChildContext(instance)) {
          childContext = Object.assign({}, context, instance.getChildContext());
        }
 
        if (visitor(element, instance, context, childContext) === false) {
          return;
        }
 
        child = instance.render();
      } else {
        // Just a stateless functional
        Iif (visitor(element, null, context) === false) {
          return;
        }
 
        child = Comp(props, context);
      }
 
      if (child) {
        if (Array.isArray(child)) {
          child.forEach(item => walkTree(item, childContext, visitor));
        } else {
          walkTree(child, childContext, visitor);
        }
      }
    } else if ((element.type as any)._context || (element.type as any).Consumer) {
      // A React context provider or consumer
      Iif (visitor(element, null, context) === false) {
        return;
      }
 
      let child;
      if ((element.type as any)._context) {
        // A provider - sets the context value before rendering children
        ((element.type as any)._context as any)._currentValue = element.props.value;
        child = element.props.children;
      } else {
        // A consumer
        child = element.props.children((element.type as any)._currentValue);
      }
 
      Eif (child) {
        if (Array.isArray(child)) {
          child.forEach(item => walkTree(item, context, visitor));
        } else {
          walkTree(child, context, visitor);
        }
      }
    } else {
      // A basic string or dom element, just get children
      Iif (visitor(element, null, context) === false) {
        return;
      }
 
      if (element.props && element.props.children) {
        React.Children.forEach(element.props.children, (child: any) => {
          if (child) {
            walkTree(child, context, visitor);
          }
        });
      }
    }
  } else Eif (typeof element === 'string' || typeof element === 'number') {
    // Just visit these, they are leaves so we don't keep traversing.
    visitor(element, null, context);
  }
  // TODO: Portals?
}
 
function hasFetchDataFunction(instance: React.Component<any>): instance is FetchComponent {
  return typeof (instance as any).fetchData === 'function';
}
 
function isPromise<T>(promise: Object): promise is Promise<T> {
  return typeof (promise as any).then === 'function';
}
 
function getPromisesFromTree({
  rootElement,
  rootContext = {},
}: PromiseTreeArgument): PromiseTreeResult[] {
  const promises: PromiseTreeResult[] = [];
 
  walkTree(rootElement, rootContext, (_, instance, context, childContext) => {
    if (instance && hasFetchDataFunction(instance)) {
      const promise = instance.fetchData();
      if (isPromise<Object>(promise)) {
        promises.push({ promise, context: childContext || context, instance });
        return false;
      }
    }
  });
 
  return promises;
}
 
function getDataAndErrorsFromTree(
  rootElement: React.ReactNode,
  IrootContext: any = {},
  storeError: Function,
): Promise<any> {
  const promises = getPromisesFromTree({ rootElement, rootContext });
 
  if (!promises.length) {
    return Promise.resolve();
  }
 
  const mappedPromises = promises.map(({ promise, context, instance }) => {
    return promise
      .then(_ => getDataAndErrorsFromTree(instance.render(), context, storeError))
      .catch(e => storeError(e));
  });
 
  return Promise.all(mappedPromises);
}
 
function processErrors(errors: any[]) {
  switch (errors.length) {
    case 0:
      break;
    case 1:
      throw errors.pop();
    default:
      const wrapperError: any = new Error(
        `${errors.length} errors were thrown when executing your fetchData functions.`,
      );
      wrapperError.queryErrors = errors;
      throw wrapperError;
  }
}
 
export default function getDataFromTree(
  rootElement: React.ReactNode,
  ErootContext: any = {},
): Promise<any> {
  const errors: any[] = [];
  const storeError = (error: any) => errors.push(error);
 
  return getDataAndErrorsFromTree(rootElement, rootContext, storeError).then(_ =>
    processErrors(errors),
  );
}