# Contribute

## Setup

Make sure you have the following requirements installed: [node](https://nodejs.org/) (v16+) and [yarn](https://yarnpkg.com/en/) (v1.22.0+)

Clone the repo (or fork it first if you're not part of Red Sift organization).

```
git clone git@github.com:redsift/design-system.git
cd design-system
yarn install
```

Set up your environment variable file by copying the template file:

```bash
cp .env.template .env
```

Then edit the `.env` file with the correct values. NEVER commit the `.env` file directly or any secrets and credentials it might contain.

You can then run the storybook and browse to [http://localhost:9000](http://localhost:9000) with:

```bash
yarn start:storybook
```

## Architecture

The Design System is following a monorepo architecture, providing multiple packages based on different use cases.

- `@redsift/icons`

  This package provides icons based on [Material Design Icon](https://pictogrammers.com/library/mdi/) library.

- `@redsift/design-system`

  This package is the main package of Red Sift's Design System. It provides the majority of the components, including layout, formatting, navigation, form and interactive components.

- `@redsift/popovers`

  This package provides popover components. Popover components are based on [floating-ui](https://floating-ui.com/) and [@floating-ui/react](https://floating-ui.com/docs/react). Toasts are based on [react-toastify](https://fkhadra.github.io/react-toastify).

- `@redsift/pickers`

  This package provides selection components. The Popover part of the Pickers comes from `@redsift/popovers`.

- `@redsift/table`

  This package provides datagrid components and features based on [MUI DataGrid](https://mui.com/x/react-data-grid/). The muiv6 and muiv7 branches use MUI DataGrid Pro; muiv8 (main) uses MUI DataGrid Premium. A [Pro or Premium license](https://mui.com/x/introduction/licensing/) from MUI is required.

- `@redsift/charts`

  This package provides charts components. Charts are based on [d3.js](https://d3js.org/) for computation, [react](https://react.dev/) for rendering and events and [react-spring](https://www.react-spring.dev/) for animations and transitions.

- `@redsift/dashboard`

  This package provides dashboard-related components and decorators to make charts and datagrid filterable using [crossfilter](https://crossfilter.github.io/crossfilter/).

- `@redsift/products`

  This package provides ready-to-use implementation of components with a customize style to fit Red Sift's use cases. It is based on all other packages.

Please make sure to work inside the correct package when making contribution.

If you need something inside more than one package, do not duplicate the code. Place it inside one package, export it from this package and import it inside the others.

For instance, `@redsift/dashboard` and `@redsift/charts` both have a `PieChart` component that both share the `PieChartVariant` type interface. `PieChartVariant` has been implemented inside `@redsift/charts` and is imported inside `@redsift/dashboard`.

For more convenience, add an export of this shared code in every package using it. In this example, `@redsift/dashboard` also exports `PieChartVariant`. This will make it easier for the user later.

```ts
// Even if PieChartVariant is implemented inside the charts package, the following code is not practical
import { PieChartVariant } from '@redsift/charts';
import { PieChart } from '@redsift/dashbord';

// Reexporting it from the dashboard package makes it really easier
import { PieChart, PieChartVariant } from '@redsift/dashbord';
```

To define which package should contain the shared code, select the one that would not create any circular dependencies.

### Dependencies

We try to use as few dependencies as possible.

For instance, we don't want to use `lodash` or `underscore` in the Design System. See why [you don't need them](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) and how to work without them.

We also don't want to use `momentjs`. See why [you don't need it](https://github.com/you-dont-need/You-Dont-Need-Momentjs) and what alternatives are there.

When dependencies are required, we try not to import them entirely to optimise the tree-shaking of the Design System.

```ts
// don't
import * as d3 from 'd3';

// do
import { sum as d3sum, scaleOrdinal as d3scaleOrdinal, ScaleOrdinal as d3ScaleOrdinal } from 'd3';
```

## Component

### Scaffolding

Each component should be in its own folder. If a subcomponent can be used as a standalone component, it should be in its own folder too. For instance, `CheckboxGroup` uses `Checkbox` but `Checkbox` can be used alone. In this case, `CheckboxGroup` and `Checkbox` both have their own folder. For `PieChart` and `PieChartSlice`, a `PieChartSlice` can not be used alone. It only exists inside a `PieChart` component. Therefore, both components are inside the same folder.

The name of the folder shoud be in kebab-case, the names of the component files are in PascalCase and the names of others files are in kebab-case. The scaffolding should be the same for every component. For instance, for the `Badge` component, it looks like this:

```
badge/
  __snapshots__/
  Badge.stories.tsx
  Badge.test.tsx
  Badge.tsx
  index.ts
  styles.ts
  types.ts
```

See the Typescript section to see what to put inside the `types.ts` file.

See the Styling section to see what to put inside the `styles.ts` file.

The component should stricly follow the following structure:

```ts
import React, { forwardRef, RefObject, useRef } from 'react';
import classNames from 'classnames';
import { Comp } from '../../types';
import { StyledBadge } from './styles';
import { BadgeProps } from './types';

const COMPONENT_NAME = 'Badge';
const CLASSNAME = 'redsift-badge';

/**
 * The Badge component.
 */
export const Badge: Comp<BadgeProps, HTMLDivElement> = forwardRef((props, ref) => {
  const {
    // props
    ...forwardedProps
  } = props;

  return (
    <StyledBadge
      {...forwardedProps}
      // transient props
      className={classNames(Badge.className, `${Badge.className}-${variant}`, className)}
      ref={ref as RefObject<HTMLDivElement>}
    >
      // content of the component if needed
    </StyledBadge>
  );
});
Badge.className = CLASSNAME;
Badge.displayName = COMPONENT_NAME;
```

The main things to keep in mind here are:

- to use the custom `Comp` type,
- to forward ref and props,
- to concatenate classNames,
- to define default values and
- to use types from `types.ts` and styles from `styles.ts`.

### API

The API of the components should be consistent with other components.

For instance, `isSelected` is the dedicated name for a prop indicating whether a component is selected or not. You should not use `selected` for instance. You could even be tempted to use `checked` or `isChecked` for a Checkbox component, but even if it can feel more suitable for this particular component, it creates inconsistencies among all components.

Try to think Design System when creating the API of your component. We want to provide visual options and variants for our components, but the possibilities should be limited.

```ts
// don't
innerRadius?: number;
outerRadius?: number;
height?: number;
width?: number;

// do
size?: PieChartSize;
```

To know how to define your API, to name and document your props, take a look at the existing components.

## Linting

The code is linted with [eslint](https://eslint.org/). You can run the linter with:

```bash
yarn lint
```

Or for a specific package with:

```bash
yarn lint:charts
yarn lint:dashboard
yarn lint:design-system
yarn lint:table
```

## Typing

The code is written in [TypeScript](https://www.typescriptlang.org/). The type checker will usually run in your editor, but also runs when you run:

```bash
yarn check-types
```

Or for a specific package with:

```bash
yarn check-types:charts
yarn check-types:dashboard
yarn check-types:design-system
yarn check-types:table
```

Types and interfaces are implemented inside `types.ts` files. Every shared type and interface should be placed inside a `types.ts` file at the root of the `src` folder of a component.

The `types.ts` file of a component should at minima export an interface for the component itself, named using the name of the component followed by `Props` (i.e. `BadgeProps`) and extending the HTML element it is based on (i.e. `React.ComponentProps<'div'>`). It should also export an interface for the main styled components it uses, using the same name prefixed by `Styled` (i.e. `StyledBadgeProps`). The props of the main interface **must** be documented with [jsdoc](https://jsdoc.app/) comments because this will be automatically parsed to fill the prop table inside the documentation website.

```ts
/**
 * Component props.
 */
export interface BadgeProps extends ComponentProps<'div'> {
  /** Badge variant. */
  variant?: BadgeVariant;
}
```

The styled component interface should be based on the main interface but omit every prop you don't want to forward to the rendered component. Every non native prop you need to use inside the styled component should be use as [transient props](https://styled-components.com/docs/api#transient-props) and therefore prefixed by a `$` character.

```ts
export type StyledBadgeProps = Omit<BadgeProps, 'variant'> & {
  $variant: BadgeProps['variant'];
};
```

This file is also use to implement and export any other props you may need for your component like variant interface, color interface, etc.

```ts
/**
 * Component variant.
 */
export const BadgeVariant = {
  dot: 'dot',
  standard: 'standard',
} as const;
export type BadgeVariant = ValueOf<typeof BadgeVariant>;
```

The variants, colors and all other enum-based interfaces should be implemented exactly as above to make the property compatible with both the enum values and their string equivalent values. In this example, `BadgeVariant.standard` and `"standard"` are both valid values for the `variant` prop.

## Styling

We use [styled-components](https://styled-components.com/) and [CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) for styling. CSS variables are centralized through a [style dictionary](https://amzn.github.io/style-dictionary/#/).

The `styles.ts` of a component should contain all the styled-component codes. At least one main variable should be implemented and named using the name of the component prefixed by `Styled` (i.e. `StyledBadge`).

```ts
/**
 * Component style.
 */
export const StyledBadge = styled.div<StyledBadgeProps>`
  ${({ $color }) =>
    $color
      ? css`
          color: var(--redsift-color-neutral-white);
          background-color: var(--redsift-color-presentation-color-${$color}-standard);
        `
      : ''}
`;
```

Make sure you are using the same HTML element for the styled component (i.e. `styled.div`) and the type interface (i.e. `ComponentProps<'div'>`). Type your variable with the interface you created in the `types.ts` file.

Make sure to use only [transient props](https://styled-components.com/docs/api#transient-props) and to use the styled-component's `css` helper when conditionnaly creating a new CSS block.

## Accessibility

We are trying to make the Design System as accessible as possible by following the [Web Accessibility Initiative guidelines](https://www.w3.org/WAI/ARIA/apg/).

Before implementing a component, try to see if there is a [pattern](https://www.w3.org/WAI/ARIA/apg/patterns/) - or a composition of multiple patterns - that is suitable for this component and follow the guidelines.

However, before using any ARIA, [read this disclaimer carefully](https://www.w3.org/WAI/ARIA/apg/practices/read-me-first/).

## Tests

We use [jest](https://jestjs.io/) for unit tests and [react-testing-library](https://testing-library.com/docs/react-testing-library/intro) for rendering and writing assertions. We also use [Storyshots](https://storybook.js.org/addons/@storybook/addon-storyshots) to automatically take a code snapshot of every story.

Please make sure you include tests with your pull requests. Our CI will run the tests on each PR. A minimum of 90% code coverage is required for statements, branches, functions and lines of every package. However, in practice, we try to reach a 100% code coverage.

We split the tests into 2 groups.

_Visual tests_

- A Storybook story should be written for each visual state that a component can be in (based on props).

_Unit tests_

- (Props) Anything that should be changed by a prop should be tested via react-testing-library.
- (Events) Anything that should trigger an event should be tested via react-testing-library.

You can run the tests with:

```bash
yarn test
```

Or for a specific package with:

```bash
yarn test:charts
yarn test:design-system
yarn test:dashboard
yarn test:table
```

Do not forget to update the snapshots with the `-u` option when you modify or create stories. However, you should **always** check the generated snapshots to see if they are correct. Do **not** blindly update the snapshots.

## Storybook

We use [Storybook](https://storybooks.js.org) for local development. Run the following command to start it:

```bash
yarn start:storybook
```

Then, open [http://localhost:9000](http://localhost:9000) in your browser to play around with the components and test your changes.

You can use knobs and other storybook addons to create your stories. However, it is necessary to create stories covering all the options and variants of your component to generate snapshots.

Storybook is shared among every packages of the Design System. Follow the naming of the components that already exists in the same package to make sure it will appear in the correct section.

## Documentation

We use a [Next.js](https://nextjs.org/) app with [MDX](https://mdxjs.com/) support as a documentation and demonstration site for the Design System. This app can be run as following:

```bash
yarn dev:website
```

Then, open [http://localhost:3000](http://localhost:3000) in your browser.

To add documentation for a component, a MDX file should be created in the `apps/website/pages/` folder and more precisely inside the subfolder corresponding to the section the page belongs to (i.e. `apps/website/pages/forms/checkbox.mdx` for the `Checkbox` component inside the `Forms` section).

To appear in the website's Side Panel, the page should be listed in `apps/website/components/CustomAppSidePanel/CustomAppSidePanel.tsx`) under the corresponding section.

A component page should be structured as following:

- **Introduction**
  - **Installation**: explains which package to install and how
  - **Usage**: explains how to import the component
- **Example**: explains the simplest example of usage for the component
- **Content** (optional): explains what the component can contain, if it can (for instance, a CheckboxGroup can contain Checkboxes)
- **Labeling** (optional): explains how to label the component, with accessibility and internationalization concerns; should only be used when the label is the only accessibility concern for this component, if there is more, use the Accessbility section below instead
- **Value** (optional): explains the values and states a component can have; only used for form components
- **Data** (optional): explains how the data should be formatted to display the component; only used for charts, table and dashboard components
- **Events** (optional): explains the different events attached to the component, controlled and uncontrolled version, validation system, etc...
- **Accessibility** (optional): dedicated accessibility section when it goes beyond the labeling, for instance to give navigation advice, etc
- **Visual options**: displays all the visual options and variants of the component
- **Props**: displays a table of component props

To display a prop table, use the `PropsTable` component as following:

```ts
<PropsTable component="Button" />
```

To display a demo, first create a demo (a simple `tsx` file) in the demo folder (`apps/website/demo/`) inside a subfolder with the name of the component (i.e. `apps/website/demo/button/coloring` for a coloring demo of the `Button` component). Then use the `DemoBlock` as following:

```ts
<DemoBlock withThemeSwitcher path="button/coloring" />
```

To display simple code, use the `CodeBlock` as following:

```ts
<CodeBlock
  codeString={`
yarn add @redsift/design-system
`}
  language="sh"
/>
```

## Build

The Design System is built using [Rollup](https://rollupjs.org/guide/en/) inside the `dist` folder of each package by running the following command:

```bash
yarn build
```

Or for a specific package with:

```bash
yarn build:charts
yarn build:dashboard
yarn build:design-system
yarn build:icons
yarn build:table
yarn build:products
```

## Publishing a release

### Stable release

1. Make sure you're on the release branch (ex: `release/vX.Y.Z`) and a PR is opened on Github
2. Login to NPM with an authorized account: `npm login`
3. Make sure your packages are up to date: `yarn`
4. Make sure the CI entirely passed on Github
5. (Optional) Make sure the build doesn't crash locally: `yarn build:design-system`
6. Publish the packages to NPM: `yarn release vX.Y.Z`

### Alpha release

If you need to test your contribution in a product before releasing -and you're not using `yarn link`, you can create an alpha release using the following process:

1. Create an alpha release branch (ex: `release/vX.Y.Z-alpha.N`) based on `release/vX.Y.Z`
2. Push it to remote (`git push origin release/vX.Y.Z-alpha.N`)
3. Login to NPM with an authorized account: `npm login`
4. Make sure your packages are up to date: `yarn`
5. (Optional) Make sure the build doesn't crash: `yarn build:design-system`
6. Publish the packages to NPM: `yarn release --dist-tag alpha vX.Y.Z-alpha.N`

After that if you need to make modification to your contribution, go back to `release/vX.Y.Z` and make the necessary modifications. Then remove the alpha release branch, and redo the process from step 1, incrementing `N` by 1.
