index.js 9 KB
Newer Older
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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = require('react');
var loadable = _interopDefault(require('@loadable/component'));
var _get = _interopDefault(require('lodash/fp/get'));
var tslib_1 = require('tslib');
var __chunk_1 = require('./chunk.js');
var _omit = _interopDefault(require('lodash/fp/omit'));
var router = require('@reach/router');
var _first = _interopDefault(require('lodash/fp/first'));
var capitalize = _interopDefault(require('capitalize'));
require('fast-deep-equal');
require('lodash/fp/merge');
require('array-sort');
require('lodash/fp/unionBy');
require('lodash/fp/flattenDepth');
require('lodash/fp/pipe');
require('ulid');
require('match-sorter');
require('lodash/fp/throttle');
var react = require('@mdx-js/react');
var createHashSource = require('hash-source');
let source = createHashSource.default();;

const BasePlayground = loadable(() => Promise.resolve(require('./Playground.js')));
const Playground = props => typeof window !== 'undefined' ? React.createElement(React.Suspense, {
  fallback: null
}, React.createElement(BasePlayground, Object.assign({}, props))) : null;

const AsyncComponent = defaultProps => {
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [data, setData] = React.useState({});
  React.useEffect(() => {
    const {
      getInitialProps
    } = defaultProps;

    if (getInitialProps && __chunk_1.isFn(getInitialProps)) {
      setLoading(true);
      getInitialProps(defaultProps).then(data => {
        setLoading(false);
        setError(null);
        setData(data);
      }).catch(err => {
        setLoading(false);
        setError(err);
        setData({});
      });
    }
  }, []);

  const {
    as: Comp,
    getInitialProps
  } = defaultProps,
        props = tslib_1.__rest(defaultProps, ["as", "getInitialProps"]);

  return React.createElement(Comp, Object.assign({}, props, {
    data: Object.assign({}, data, {
      loading,
      error
    })
  }));
};

const loadRoute = (path, imports, components) => {
  const Loading = components.loading;

  const fn = async () => {
    const importFn = _get(path, imports);

    const {
      default: Component,
      getInitialProps
    } = await importFn();

    const ExportedComponent = props => React.createElement(AsyncComponent, Object.assign({}, props, {
      as: Component || 'div',
      getInitialProps: getInitialProps
    }));

    return ExportedComponent;
  };

  return loadable(fn, {
    fallback: React.createElement(Loading, null)
  });
};
const AsyncRoute = defaultProps => {
  const {
    asyncComponent,
    path,
    entry
  } = defaultProps,
        routeProps = tslib_1.__rest(defaultProps, ["asyncComponent", "path", "entry"]);

  const components = __chunk_1.useComponents();
  const Page = components.page;
  const Component = asyncComponent;
  const props = Object.assign({}, routeProps, {
    doc: entry
  });
  return Page ? React.createElement(Page, Object.assign({}, props), React.createElement(Component, Object.assign({}, props))) : React.createElement(Component, Object.assign({}, props));
};

const Link = React.forwardRef((defaultProps, ref) => {
  const props = _omit(['activeClassName', 'partiallyActive'], defaultProps);

  const isActive = React.useCallback(({
    isCurrent
  }) => {
    return isCurrent ? {
      className: `${props.className} active`
    } : {};
  }, [props.className]);
  return React.createElement(router.Link, Object.assign({}, props, {
    getProps: isActive,
    ref: ref
  }));
});
Link.displayName = 'Link';

const RE_OBJECTOF = /(?:React\.)?(?:PropTypes\.)?objectOf\((?:React\.)?(?:PropTypes\.)?(\w+)\)/;

const getTypeStr = type => {
  switch (type.name.toLowerCase()) {
    case 'instanceof':
      return `Class(${type.value})`;

    case 'enum':
      if (type.computed) return type.value;
      return type.value ? type.value.map(v => `${v.value}`).join(' │ ') : type.raw;

    case 'union':
      return type.value ? type.value.map(t => `${getTypeStr(t)}`).join(' │ ') : type.raw;

    case 'array':
      return type.raw;

    case 'arrayof':
      return `Array<${getTypeStr(type.value)}>`;

    case 'custom':
      if (type.raw.indexOf('function') !== -1 || type.raw.indexOf('=>') !== -1) return 'Custom(Function)';else if (type.raw.toLowerCase().indexOf('objectof') !== -1) {
        const m = type.raw.match(RE_OBJECTOF);
        if (m && m[1]) return `ObjectOf(${capitalize(m[1])})`;
        return 'ObjectOf';
      }
      return 'Custom';

    case 'bool':
      return 'Boolean';

    case 'func':
      return 'Function';

    case 'shape':
      const shape = type.value;
      const rst = {};
      Object.keys(shape).forEach(key => {
        rst[key] = getTypeStr(shape[key]);
      });
      return JSON.stringify(rst, null, 2);

    default:
      return capitalize(type.name);
  }
};

const humanize = type => getTypeStr(type);

const getPropType = prop => {
  const propName = _get('name', prop.flowType || prop.type);

  if (!propName) return null;
  const isEnum = propName.startsWith('"') || propName === 'enum';
  const name = capitalize(isEnum ? 'enum' : propName);

  const value = _get('type.value', prop);

  if (!name) return null;

  if (isEnum && typeof value === 'string' || !prop.flowType && !isEnum && !value || prop.flowType && !prop.flowType.elements) {
    return name;
  }

  return prop.flowType ? humanize(prop.flowType) : humanize(prop.type);
};
const Props = ({
  title,
  isToggle,
  isRaw,
  of: component
}) => {
  const components = __chunk_1.useComponents();
  const {
    props: stateProps
  } = React.useContext(__chunk_1.doczState.context);
  const PropsComponent = components.props;

  const filename = _get('__filemeta.filename', component);

  const filemetaName = _get('__filemeta.name', component);

  const componentName = filemetaName || component.displayName || component.name;
  const found = stateProps && stateProps.length > 0 && stateProps.find(item => filename ? item.key === filename : item.key.includes(`${componentName}.`));
  const value = _get('value', found) || [];

  const firstDefinition = _first(value);

  const definition = value.find(i => i.displayName === componentName);

  const props = _get('props', definition || firstDefinition);

  if (!props) return null;
  if (!PropsComponent) return null;
  return React.createElement(PropsComponent, {
    title: title,
    isRaw: isRaw,
    isToggle: isToggle,
    props: props,
    getPropType: getPropType
  });
};

const goToHash = ({
  location
}) => {
  setTimeout(() => {
    if (location && location.hash) {
      const decodedHash = decodeURI(location.hash);
      const id = decodedHash.substring(1);
      const el = document.getElementById(id);
      if (el) el.scrollIntoView();
    }
  });
};

const Routes = ({
  imports
}) => {
  const components = __chunk_1.useComponents();
  const {
    entries
  } = React.useContext(__chunk_1.doczState.context);
  const NotFound = components.notFound;
  const history = React.useMemo(() => router.createHistory(source), []);
  React.useEffect(() => {
    history.listen(goToHash);
  }, []);
  return React.createElement(react.MDXProvider, {
    components: components
  }, React.createElement(router.LocationProvider, {
    history: history
  }, React.createElement(router.Router, null, React.createElement(NotFound, {
    default: true
  }), entries && entries.map(({
    key: path,
    value: entry
  }) => {
    const props = {
      path,
      entries,
      components
    };
    const component = loadRoute(path, imports, components);
    return React.createElement(AsyncRoute, Object.assign({}, props, {
      entry: entry,
      key: entry.id,
      path: entry.route,
      asyncComponent: component
    }));
  }))));
};

function theme(themeConfig, transform = c => c) {
  return WrappedComponent => {
    const Theme = React.memo(props => {
      const {
        linkComponent
      } = props;
      const {
        db,
        children,
        wrapper: Wrapper = React.Fragment
      } = props;
      const initial = Object.assign({}, db, {
        themeConfig,
        transform,
        linkComponent
      });
      return React.createElement(__chunk_1.doczState.Provider, {
        initial: initial
      }, React.createElement(Wrapper, null, React.createElement(WrappedComponent, null, children)));
    });
    Theme.displayName = WrappedComponent.displayName || 'DoczTheme';
    return Theme;
  };
}

exports.ComponentsProvider = __chunk_1.ComponentsProvider;
exports.doczState = __chunk_1.doczState;
exports.useComponents = __chunk_1.useComponents;
exports.useConfig = __chunk_1.useConfig;
exports.useDataServer = __chunk_1.useDataServer;
exports.useDocs = __chunk_1.useDocs;
exports.useMenus = __chunk_1.useMenus;
exports.usePrevious = __chunk_1.usePrevious;
exports.useWindowSize = __chunk_1.useWindowSize;
exports.AsyncRoute = AsyncRoute;
exports.Link = Link;
exports.Playground = Playground;
exports.Props = Props;
exports.Routes = Routes;
exports.loadRoute = loadRoute;
exports.theme = theme;