How to use react-docgen - 10 common examples

To help you get started, we’ve selected a few react-docgen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github auth0 / cosmos / tooling / component-metadata.js View on Github external
.map(path => {
      try {
        /* ignore secondary files */
        const directoryName = path.split('/').splice(-2, 1)[0]
        const componentFileName = directoryName.replace('_', '') + '.js'

        /* if component file does not exist, move on*/
        if (!path.includes(componentFileName)) return

        /* append display name handler to handlers list */
        const handlers = docgen.defaultHandlers
          .concat(createDisplayNameHandler(path))
          .concat(deprecationHandler)

        /* read file to get source code */
        const code = fs.readFileSync(path, 'utf8')

        /* parse the component code to get metadata */
        const data = docgen.parse(code, null, handlers)

        /* make modifications to prop types to improve documentation */
        if (data.props) {
          Object.values(data.props).forEach(prop => {
            /* remove redundant quotes from default value of type string */
            if (prop.defaultValue) {
              if (typeof prop.defaultValue.value === 'string') {
                prop.defaultValue.value = prop.defaultValue.value.replace(/^'(.*)'$/, '$1')
github mui-org / material-ui / docs / scripts / buildApi.js View on Github external
const stylesRegexp = /export const styles.*[\r\n](.*[\r\n])*};[\r\n][\r\n]/;
    const styleRegexp = /\/\* (.*) \*\/[\r\n]\s*(\w*)/g;
    // Extract the styles section from the source
    const stylesSrc = stylesRegexp.exec(styleSrc);

    if (stylesSrc) {
      // Extract individual classes and descriptions
      stylesSrc[0].replace(styleRegexp, (match, desc, key) => {
        styles.descriptions[key] = desc;
      });
    }
  }

  let reactAPI;
  try {
    reactAPI = docgenParse(src, null, defaultHandlers.concat(muiDefaultPropsHandler), {
      filename: componentObject.filename,
    });
  } catch (err) {
    console.log('Error parsing src for', componentObject.filename);
    throw err;
  }

  reactAPI.name = name;
  reactAPI.styles = styles;
  reactAPI.pagesMarkdown = pagesMarkdown;
  reactAPI.src = src;
  reactAPI.spread = spread;
  reactAPI.EOL = getLineFeed(src);

  const testInfo = await parseTest(componentObject.filename);
  // no Object.assign to visually check for collisions
github callstack / component-docs / src / parsers / component.js View on Github external
for (const line of lines) {
    if (line === '// @component-docs ignore-next-line') {
      skip = true;
      continue;
    }

    if (skip) {
      skip = false;
      continue;
    }

    content += line + '\n';
  }

  const info = parse(
    content,
    undefined,
    [...defaultHandlers, staticPropertyHandler],
    {
      cwd: root,
      filename: filepath,
    }
  );
  const name = info.displayName || getNameFromPath(filepath);

  return {
    filepath: path.relative(root, filepath),
    title: name,
    description: info.description,
    link: dashify(name),
    data: info,
github mlaursen / react-md / docs_old / scripts / docgen.js View on Github external
if (regex) {
      replace({
        regex,
        replacement: '',
        paths: [temp],
        silent: true,
      });
    }
  }

  const rawFile = fs.readFileSync(path.resolve(reactMD, sourceFolder, temp || file + '.js'));
  try {
    // For some reason there are 2 entries in the navigation drawer
    const docgenIndex = file === 'NavigationDrawer' ? 1 : 0;
    const generated = docgen.parse(rawFile, docgen.resolver.findAllComponentDefinitions)[docgenIndex];
    generated.source = `src/js/${sourceFolder}/${file}.js`;
    generated.component = component.replace(/(?=Focus)Container/, '');
    generated.methods = generated.methods.filter(method => method.name.charAt(0) !== '_');
    Object.keys(generated.props).forEach(key => {
      if (key.charAt(0) === '_' || generated.props[key].description.match(/@access private/)) {
        delete generated.props[key];
      }
    });


    docgens[folder] = docgens[folder] || {
      name: generated.component.replace(/((?!Snackbar)Container|Group)/, ''),
      docgens: [],
    };

    docgens[folder].docgens.push(generated);
github reach / reach-ui / website / gatsby-config.js View on Github external
name: `docs`,
        path: `${__dirname}/../packages`,
        ignore: ["examples/**", "es/**", "umd/**"]
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`
      }
    },
    {
      resolve: `gatsby-transformer-react-docgen`,
      options: {
        resolver: require("react-docgen").resolver.findAllComponentDefinitions,
        babelrcRoots: ["../*"]
      }
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: "reach-ui",
        short_name: "reach-ui",
        start_url: "/",
        background_color: "#1159a6",
        theme_color: "#1159a6",
        display: "minimal-ui",
        icon: "src/images/reach-icon.png" // This path is relative to the root of the site.
      }
github alfa-laboratory / library-utils / react-doc / create-resolver.js View on Github external
function resolveDefinition(definition, types) {
    if (isReactCreateClassCall(definition)) {
        // return argument
        const resolvedPath = resolveToValue(definition.get('arguments', 0));
        if (types.ObjectExpression.check(resolvedPath.node)) {
            return resolvedPath;
        }
    } else if (isReactComponentClass(definition) || isDecoratedBy(definition, 'cn')) {
        normalizeClassDefinition(definition);
        return definition;
    } else if (isStatelessComponent(definition)) {
        return definition;
    }
    return null;
}
github jamesmfriedman / rmwc / scripts / docgen-resolver.js View on Github external
function resolveDefinition(definition, types) {
  if (isReactCreateClassCall(definition)) {
    // return argument
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    if (types.ObjectExpression.check(resolvedPath.node)) {
      return resolvedPath;
    }
  } else if (isReactComponentClass(definition)) {
    normalizeClassDefinition(definition);
    return definition;
  } else if (isStatelessComponent(definition)) {
    return definition;
  } else if (isSimpleTag(definition)) {
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    return resolvedPath;
  } else if (isWithMDC(definition)) {
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    return resolvedPath;
  }
github jamesmfriedman / rmwc / scripts / docgen-resolver.js View on Github external
function resolveDefinition(definition, types) {
  if (isReactCreateClassCall(definition)) {
    // return argument
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    if (types.ObjectExpression.check(resolvedPath.node)) {
      return resolvedPath;
    }
  } else if (isReactComponentClass(definition)) {
    normalizeClassDefinition(definition);
    return definition;
  } else if (isStatelessComponent(definition)) {
    return definition;
  } else if (isSimpleTag(definition)) {
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    return resolvedPath;
  } else if (isWithMDC(definition)) {
    var resolvedPath = resolveToValue(definition.get('arguments', 0));
    return resolvedPath;
  }

  return null;
}
github alfa-laboratory / library-utils / react-doc / create-resolver.js View on Github external
visitAssignmentExpression(path) {
            // Ignore anything that is not `exports.X = ...;` or
            // `module.exports = ...;`
            if (!isExportsOrModuleAssignment(path)) {
                return false;
            }
            // Resolve the value of the right hand side. It should resolve to a call
            // expression, something like React.createClass
            path = resolveToValue(path.get('right'));
            if (!isComponentDefinition(path)) {
                path = resolveToValue(resolveHOC(path));
                if (!isComponentDefinition(path)) {
                    return false;
                }
            }
            if (definition) {
                // If a file exports multiple components, ... complain!
                throw new Error(ERROR_MULTIPLE_DEFINITIONS);
            }
            definition = resolveDefinition(path, types);
            return false;
        }
    });
github alfa-laboratory / library-utils / react-doc / create-resolver.js View on Github external
.reduce((acc, def) => {
                if (isComponentDefinition(def)) {
                    acc.push(def);
                    return acc;
                }

                const resolved = resolveToValue(resolveHOC(def));
                if (isComponentDefinition(resolved)) {
                    acc.push(resolved);
                    return acc;
                }

                if (isDecoratedBy(def, 'cn') && def.get('superClass')) {
                    const superClass = def.get('superClass');
                    if (!originalClassName) { // save original component name and use it to patch parent class
                        originalClassName = def.get('id').value.name;
                    }

                    const src = getSourceFileContent(importedModules[superClass.value.name], filePath);
                    filePath = src.filePath; // update file path, so we can correctly resolve imports
                    linkedFile = recast.parse(src.content, { esprima: babylon });
                    return acc;
                }