import { Canvas, Meta } from "@storybook/addon-docs/blocks";
import * as UseBreakpointStories from "./useBreakpoint.stories";
import { useBreakpoint } from "./useBreakpoint";

<Meta of={UseBreakpointStories} />

# useBreakpoint() hook for CSS breakpoints

The `useBreakpoint` hook is used for determining the current breakpoint based on user's viewport width. The hook returns a t-shirt size value that ranges from `xs` to `xxl`.

## Install

```bash
yarn add @simplybusiness/mobius
```

## Usage

The useBreakpoint hook can be used in any component where viewport width is required.

```js
import { useBreakpoint } from "@simplybusiness/mobius";

const MyComponent = () => {
  const { breakpoint } = useBreakpoint();

  return (
    <div>
      The current breakpoint: {breakpoint.size}, {breakpoint.value}
    </div>
  );
};
```

Breakpoints are hard-coded inside the hook, to match Simply Business design tokens as follows:

```js
const breakpoints = [
  { size: "xs", value: 320 },
  { size: "sm", value: 480 },
  { size: "md", value: 640 },
  { size: "lg", value: 960 },
  { size: "xl", value: 1200 },
  { size: "xxl", value: 1320 },
];
```

The allowed keys are `xs, sm, md, lg, xl, xxl`. Values are integers representing viewport widths in pixels. There can be as few as one breakpoint and as many as six.

You can override these defaults when instantiating the hook, as follows:

```js
import { useBreakpoint, BreakpointsType } from "@simplybusiness/mobius";

const customBreakpoints = [
  { size: "xs", value: 320 },
  { size: "sm", value: 480 },
  { size: "md", value: 600 },
  { size: "lg", value: 850 },
  { size: "xl", value: 1024 },
] as BreakpointsType;

const MyComponent = () => {
  const { breakpoint } = useBreakpoint(customBreakpoints);

  return (
    <div>
      The current breakpoint: {breakpoint.size}, {breakpoint.value}
    </div>
  );
};
```

The hook will return `xs` as its default value. If the viewport width is larger (e.g. `1500px`) than the largest breakpoint in your configuration (e.g. `lg: 960`), the hook will return the largest breakpoint from the configuration (e.g. `lg`),

### Demo

<Canvas of={UseBreakpointStories.Default} />

### `up` and `down` helpers

The hook returns two functions, `up` and `down`. The `up` function returns a
boolean value that indicates whether the current breakpoint is larger than
the breakpoint passed as an argument. The `down` function returns a boolean
value that indicates whether the current breakpoint is smaller than the
breakpoint passed as an argument.

For example, if the current breakpoint is `lg` and the breakpoint passed as
an argument is `md`, the `up` function will return `true`.

```js
const { down, up } = useBreakpoint();
const isMobile = down("sm");
const isDesktop = up("md");
```

<Canvas of={UseBreakpointStories.UpAndDown} />
