Document Typescript React components with TSDoc and export Storybook-friendly JSON 🤖

Overview

Document React components with @prop

react-tsdoc 🤖

react-tsdoc is an tool to extract information from React Typescript component files with TSDoc for documentation generation that elaborates on the TSDoc standard. Just use @prop!

Similar to react-docgen, react-tsdoc is a low level tool to extract information about React components. Use react-tsdoc-loader to inject the docs into Storybook.

Wouldn't it be nice if instead of doing this...

/**
 * Nice button
 */
const Button = ({
	disabled,
	label,
	onClick
}: {
	/**
	 * Disables the button
	 */
	disabled: boolean
	/**
	 * Label for the button
	 */
	label: string
	/**
	 * Fired when button clicked
	 */
	onClick: (...) => {}
}) => ();

You could do this 👇 and still have Storybook pick up the prop descriptions?

/**
 * Nice button
 *
 * @prop disabled - Disables the button
 * @prop label - Label for the button
 * @prop onClick - Fired when button clicked
 */
const Button = ({
	disabled,
	label,
	onClick
}: {
	disabled: boolean
	label: string
	onClick: (...) => {}
}) => ();

That's where react-tsdoc comes in! It automatically generates documentation from the TSDoc comment's @props while also still passing through all the other goodies you also want to see, such as if a prop is required, types, default values, and more!

Install

To install react-tsdoc just run:

npm i -g react-tsdoc

And you can run the parser like:

react-tsdoc ./src/components --output ./docs/output.json

How do I use this with Storybook?

This tool just create JSON blobs with the documentation information. To use this with Storybook you'll need to use the Webpack loader to inject this information into your story's components.

Use react-tsdoc-loader to inject the docs into Storybook.

Why @prop?

Because it looks nicer! I personally perfer seeing the descriptions for all of my component's props right at the top so I can get all of the information I need right at a glance.

Why TSDoc instead of JSDoc?

Great question! Part of the beauty of Typescript is that you explicitely set types, so why would you want to duplicate those in your docs? TSDoc does away with that so you only need to call out your prop name and add a description. Easy!

Output

Here's an example component with the associated parser output...

Input:

/**
 * Button
 *
 * @prop disabled - Sets if field is disabled
 * @prop label - Sets the button text
 */
const Button = ({
	disabled = false,
	label
}: {
	disabled?: boolean
	label: string
}) => {
	return (
		<button disabled={disabled}>
			{label}
		</button>
	)
};

Output:

{
  "description": "Button",
  "props": {
    "disabled": {
      "description": "Sets if field is disabled",
      "required": false,
      "tsType": {
        "name": "boolean"
      },
      "defaultValue": {
        "value": "false",
        "computed": false
      }
    },
    "label": {
      "description": "Sets the button text",
      "required": true,
      "tsType": {
        "name": "string"
      }
    }
  }
}

Adding to tsdoc.json

Adding support for the @prop tag to your TSDoc config is easy! This allows your eslint-plugin-tsdoc to properly parse @prop. Create a tsdoc.json if you don't already have one and add this to it:

{
  "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
  "tagDefinitions": [
    {
      "tagName": "@prop",
      "syntaxKind": "block"
    }
  ]
}

Why another docgen?

Though react-docgen, typedoc, and react-docgen-typescript are all wonderful tools, defining props can be a challenge, especially if you are destructuring props.

As Shilman of Storybook noted in this Gist, Storybook plans to adopt react-docgen for SB7, however react-docgen is based on an outdated Doc parser (doctrine) and does not support the TSDoc standard.

I have found that interface documentation can be rather cumbersome and being able to see what each respective prop is used for at a glance is extremely handy.

Ultimately, this is just an excuse for me to play around with ASTs, but I hope others find some use in this project.

Supported Types

  • Simple (foo: string, bar: boolean)
  • Literals (foo: 'bar')
  • Tuples (foo: [string, number])
  • Unions (foo: string | boolean)
  • Typed arrays (foo: string[])
  • Object signatures ({ foo: string})
  • Index signatures ([foo: string]: string)
  • Function signatures (foo: (x: string) => void)
  • Intersect (foo: string & number)
  • Nullable modifier (foo: ?number)
  • Typed classes (foo: Class<bar>)

Extended support coming soon.

Development

I've heavily commented a lot of the functions as this has been an AST learning experience for me, and I hope others find it easy to understand and contribute.

To build, just run:

npm install && npm run build

This will build the ./lib folder and then you can execute the CLI from the /bin directory, like this:

bin/react-tsdoc.js ./src/components ./output.json && cat ./output.json

To run the tests:

npm run test
Comments
  • Write Tests

    Write Tests

    It's imperative to write some tests for the various functions in the parser.

    ~Thinking about using Jest, but debating between a centralized tests folder or directory-specific __tests__ folders.~

    Settled on the __tests__ folder convention.

    Files to write tests for:

    • [x] utils/paramsHelper.ts
    • [x] utils/reactComponentHelper.ts
    • [x] utils/tsDocHelper.ts
    • [x] utils/tsTypesHelper.ts
    • [x] parser.js
    enhancement 
    opened by noahbuscher 1
  • Add Support for `@todo`

    Add Support for `@todo`

    Currently if you have a block like the following:

    /**
     * Some component
     *
     * @prop label - Label for the component
     * @todo Improve something...
     */
    

    It will not generate any docs.

    bug 
    opened by noahbuscher 0
  • Improve React Component Helper

    Improve React Component Helper

    Right now the tool basically just checks if a variable is the default export, has a capital first letter, and is a variable declaration or function declaration. It might be smart to see if the component returns JSX or a React function.

    enhancement 
    opened by noahbuscher 0
  • Write Webpack Loader

    Write Webpack Loader

    It'll be important to write a Webpack loader to affix the __docgenInfo to the components with the doc object so this works as expected with Storybook, considering that Storybook does not allow shoe-horning in a custom docgen.

    Perhaps worth making a more generalized loader and providing a config for react-tsdoc? Seems like a common(ish) want.

    Read more here.

    enhancement 
    opened by noahbuscher 0
  • Add Support for Types

    Add Support for Types

    Imperative to add support for rolling up types into the docs.

    Take a look at this table for how to format various types as you come across them.

    Progress:

    • [x] Simple types
    • [x] Literals
    • [ ] Typed classes
    • [x] Object signatures
    • [x] Function signatures
    • [x] Callable-object / function-object signatures
    • [x] Tuple
    • [x] Union
    • [ ] Intersect
    • [ ] Nullable modifier
    enhancement 
    opened by noahbuscher 0
Owner
Noah Buscher
Noah Buscher
Next.js + TypeScript + Material UI v5 + Sass + Storybook starter

nextjs-ts-mui5-scss-storybook-starter ?? Next.js + TypeScript + Material UI v5 + Sass + Storybook starter ?? with linting & prettier pre-configured Ma

Muhammad Ridho Anshory 13 Oct 19, 2022
JSON Hero is an open-source, beautiful JSON explorer for the web that lets you browse, search and navigate your JSON files at speed. 🚀

JSON Hero makes reading and understand JSON files easy by giving you a clean and beautiful UI packed with extra features.

JSON Hero 7.2k Jan 9, 2023
📓 The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

Build bulletproof UI components faster Storybook is a development environment for UI components. It allows you to browse a component library, view the

Storybook 75.8k Jan 4, 2023
Shows how React components and Redux to build a friendly user experience with instant visual updates and scaleable code in ecommerce applications

This simple shopping cart prototype shows how React components and Redux can be used to build a friendly user experience with instant visual updates and scaleable code in ecommerce applications.

Alan Vieyra 4 Feb 1, 2022
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list Examples available here: http://claude

Claudéric Demers 10.3k Jan 2, 2023
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and s

Victor Dantas 9 Jun 30, 2022
A React utility belt for function components and higher-order components.

A Note from the Author (acdlite, Oct 25 2018): Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today,

Andrew Clark 14.8k Jan 4, 2023
Nextjs-components: A collection of React components

nextjs-components A collection of React components, transcribed from https://vercel.com/design. 1 Motivation Blog post from 01/09/2022 Todo's Unit tes

null 94 Nov 30, 2022
A document head manager for React

React Helmet This reusable React component will manage all of your changes to the document head. Helmet takes plain HTML tags and outputs plain HTML t

National Football League 16.7k Dec 30, 2022
TryShape is an open-source platform to create shapes of your choice using a simple, easy-to-use interface. You can create banners, circles, polygonal shapes, export them as SVG, PNG, and even as CSS.

Create, Export, Share, and Use any Shapes of your choice. View Demo · Report Bug · Request Feature ?? Introducing TryShape TryShape is an opensource p

TryShape 148 Dec 26, 2022
A style export tool that live edits and exports code ready to copy / paste

Awesome Title Generator A style export tool that live edits and exports code ready to copy / paste. Features Edits text and live previews it CSS and R

Crhistian de Oliveira 19 Oct 7, 2022
React friendly API wrapper around MapboxGL JS

react-map-gl | Docs react-map-gl is a suite of React components designed to provide a React API for Mapbox GL JS-compatible libraries. More informatio

Vis.gl 6.9k Dec 31, 2022
Companion React+TypeScript code for my Intro to TypeScript EmergentWorks workshop, bootstrapped with yarn + create-react-app! ✨

Getting Started with Create React App This project was bootstrapped with Create React App. Companion repository to https://github.com/JoshuaKGoldberg/

Josh Goldberg 2 Dec 21, 2022
🔄 Basic project to start studying React and Typescript. With it you can translate text to binary or morse language. This project addresses the creation of routes and components.

max-conversion Projeto criado para iniciar nos estudos de React e Typescript Basic project to gain knowledge in react Na plataforma é possível convert

Igor Neves 3 Feb 12, 2022
React components and hooks for creating VR/AR applications with @react-three/fiber

@react-three/xr React components and hooks for creating VR/AR applications with @react-three/fiber npm install @react-three/xr These demos are real,

Poimandres 1.4k Jan 4, 2023
Providing accessible components with Web Components & Material You

tiny-material Still on developing, DO NOT use for production environment Run well on Google Chrome, Firefox, Chrome for Android, Microsoft Edge (Chrom

HugePancake 11 Dec 31, 2022
✍ It has never been so easy to document your things!

Docz makes it easy to write and publish beautiful interactive documentation for your code. Create MDX files showcasing your code and Docz turns them i

Docz 23.1k Jan 9, 2023
Mobile app development framework and SDK using HTML5 and JavaScript. Create beautiful and performant cross-platform mobile apps. Based on Web Components, and provides bindings for Angular 1, 2, React and Vue.js.

Onsen UI - Cross-Platform Hybrid App and PWA Framework Onsen UI is an open source framework that makes it easy to create native-feeling Progressive We

null 8.7k Jan 8, 2023
An easily internationalizable, mobile-friendly datepicker library for the web

react-dates An easily internationalizable, accessible, mobile-friendly datepicker library for the web. Live Playground For examples of the datepicker

Airbnb 12k Dec 30, 2022