<file_sep>import useSound from 'react-guitar-sound'
import E2 from 'react-guitar-sound/resources/E2.ogg'
import D3 from 'react-guitar-sound/resources/D3.ogg'
import G3 from 'react-guitar-sound/resources/G3.ogg'
import E4 from 'react-guitar-sound/resources/E4.ogg'
import useKey from './key'

const samples = { E2, D3, G3, E4 }

export default function useClassicSound(
  strings: number[],
  tuning: number[],
  muted?: boolean
) {
  const { play, strum, ...rest } = useSound(samples, strings, tuning, muted)

  useKey(
    () => true,
    e => {
      const string = parseInt(e.key) - 1
      string >= 0 && string < tuning.length && play(string)
    },
    [tuning, play]
  )
  useKey('w', () => strum(true), [strum])
  useKey('s', () => strum(), [strum])

  return { play, strum, ...rest }
}
<file_sep>import { Styles, Theme } from 'react-select'

export const className = 'font-semibold text-gray-700 hover:shadow rounded'

export const theme = (theme: Theme) => ({
  ...theme,
  borderRadius: 4,
  colors: {
    ...theme.colors,
    neutral20: '#e2e8f0',
    neutral40: 'rgba(203, 213, 224)'
  }
})

export const styles: Partial<Styles> = {
  singleValue: provided => ({ ...provided, color: 'inherit' }),
  menu: provided => ({ ...provided, width: '18em', zIndex: 3 }),
  control: (provided, state) => ({
    ...provided,
    borderColor: state.theme.colors.neutral20,
    borderWidth: '2px',
    '&:hover': {
      borderColor: state.theme.colors.neutral40
    },
    height: '2.5rem',
    boxShadow: state.isFocused && `0 0 0 3px rgba(66, 153, 225, 0.5)`
  })
}
<file_sep>import { SamplerOptions } from 'tone'
import { useEffect, useState, useCallback } from 'react'
import makePlayer, { Player } from './util/player'

export default function useSound(
  samples: SamplerOptions['urls'],
  fretting: number[],
  tuning: number[],
  muted?: boolean
) {
  const [player, setPlayer] = useState<Player>()
  const [playing, setPlaying] = useState(tuning.map(() => false))

  useEffect(() => {
    const promise = makePlayer(samples, tuning, setPlaying)
    promise.then(setPlayer)

    return () => {
      setPlayer(undefined)
      promise.then(player => {
        player.dispose()
      })
    }
  }, [samples, tuning])

  const play = useCallback(
    (string: number, when: number = 0) => {
      if (!muted) player?.play(string, fretting[string] ?? 0, when)
    },
    [muted, player, fretting]
  )

  const strum = useCallback(
    (up?: boolean) =>
      tuning.forEach((_, i) => play(!up ? tuning.length - i - 1 : i, 0.05 * i)),
    [tuning, play]
  )

  return { play, strum, playing }
}
<file_sep>import { Frequency, Sampler, SamplerOptions, immediate } from 'tone'

export type Player = {
  play: (string: number, fret: number, when: number) => Promise<void>
  dispose: () => void
}

const toMidi = (note: string | number) => {
  if (typeof note === 'string') return Frequency(note).toMidi()
  return note
}

const closest = (midi: number, samples: SamplerOptions['urls']) => {
  let min = Object.keys(samples)[0]
  Object.keys(samples).forEach(key => {
    if (Math.abs(midi - toMidi(key)) < Math.abs(midi - toMidi(min))) {
      min = key
    }
  })
  return { [min]: samples[min] }
}

export default async (
  samples: SamplerOptions['urls'],
  tuning: number[],
  onChange: (playing: boolean[]) => void
): Promise<Player> => {
  const synths = await Promise.all(
    tuning.map(
      midi =>
        new Promise<Sampler>(resolve => {
          const synth: Sampler = new Sampler(closest(midi, samples), () =>
            resolve(synth)
          ).toDestination()
        })
    )
  )
  const resolvers: Partial<{ [K: number]: (change?: boolean) => void }> = {}
  const playing = tuning.map(() => false)
  const setPlaying = (string: number, value: boolean) => {
    if (playing[string] !== value) {
      playing[string] = value
      setTimeout(() => onChange([...playing]), 0)
    }
  }

  return {
    play: (string, fret, when = 0) =>
      new Promise(resolve => {
        resolvers[string]?.(when === 0)
        if (fret < 0) return resolve()
        const startTimeout = setTimeout(
          () => setPlaying(string, true),
          when * 1000
        )
        const endTimeout = setTimeout(
          (resolvers[string] = change => {
            delete resolvers[string]
            clearTimeout(startTimeout)
            clearTimeout(endTimeout)
            resolve()
            if (!change) setPlaying(string, false)
          }),
          3000 + when * 1000
        )
        synths[string].triggerAttackRelease(
          Frequency(tuning[string] + fret, 'midi').toFrequency(),
          4,
          immediate() + when
        )
      }),
    dispose: () => synths.map(synth => synth.dispose())
  }
}
<file_sep># React-Guitar &middot; [![npm version](https://img.shields.io/npm/v/react-guitar.svg?style=flat)](https://www.npmjs.com/package/react-guitar)

A beautiful and accessible guitar component for React.

See https://react-guitar.com for a live demo.

![Screenshot of the rendered component with an E major chord](packages/react-guitar/screenshot.png)

[![Edit quizzical-dawn-0hzuq](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/interesting-breeze-ll7zh)

## Usage

```
npm i react-guitar
```

```jsx
import React from 'react'
import { render } from 'react-dom'
import Guitar from 'react-guitar'

render(
  <Guitar strings={[0, 1, 2, 2, 0, -1]} />,
  document.getElementById('root')
)
```

Check out [the storybook](https://react-guitar.com/storybook) for more advanced examples.

### Props

| Name           | Description                                                                                                                                                                                                                               |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`           | An optional id in case several guitars are on the screen at the same time. This is used to generate the radio button names used internally which must be unique. If not specified an autoincremented id will be generated.                |
| `className`    | A CSS class string to apply to the container element.                                                                                                                                                                                     |
| `strings`      | An array where each number represents the fret the string is pressed on (`0` means open string and `-1` muted). `[0, 1, 2, 2, 0, -1]` is an `A minor` in a standard guitar and `[3, 0, 0, 0]` is a `C major` in a ukelele.                |
| `frets`        | An object with the shape `{ from: number amount: number }` to configure the frets of the guitar (`{ from: 0, amount: 22 }` by default). It can start on any fret which is useful for displaying just a chord instead of the whole guitar. |
| `lefty`        | A boolean to configure the guitar for left handed people like me.                                                                                                                                                                         |
| `center`       | A boolean to indicate if the current fretting should be centered. If set to `true` the guitar horizontal scroll will be set so that the middle fret is centered.                                                                          |
| `renderFinger` | A function `(string: number, fret: number) => JSX.Element` that will be used to render the content of the white bubble used for the fingers. This can be used to render the note name.                                                    |
| `theme`        | A theme object to customise the guitar look and feel. See [Theming](#theming).                                                                                                                                                            |
| `playOnHover`  | A boolean to indicate if hovering with the mouse should trigger play events.                                                                                                                                                              |
| `onChange`     | A function `(strings: number[]) => void` that will be called when a string is press/unpressed. If not present the guitar will be read only.                                                                                               |
| `onPlay`       | A function `(string: number) => void` that will be called each time the user plays a string (hovering with the mouse). This can be used to play the sound of the string.                                                                  |

### Hooks

#### useSound

In order to enable sound playing `react-guitar` offers the [useSound](packages/react-guitar-sound) hook:

```
npm i react-guitar react-guitar-sound react-guitar-tunings
```

```jsx
import React, { useMemo } from 'react'
import { render } from 'react-dom'
import Guitar from 'react-guitar'
import { standard } from 'react-guitar-tunings'
import useSound from 'react-guitar-sound'
import E2 from 'react-guitar-sound/resources/E2.ogg'
import D3 from 'react-guitar-sound/resources/D3.ogg'
import G3 from 'react-guitar-sound/resources/G3.ogg'
import E4 from 'react-guitar-sound/resources/E4.ogg'

const samples = { E2, D3, G3, E4 }

function SampleGuitarWithSound() {
  const strings = useMemo(() => [0, 1, 2, 2, 0, -1], [])
  const { play, strum } = useSound(samples, strings, standard)

  return <Guitar strings={strings} onPlay={play} />
}

render(<SampleGuitarWithSound />, document.getElementById('root'))
```

It receives:
| Name | Description |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `samples` | A map from note names to audio files representing the samples. `react-guitar` offers 4 samples out of the box recorded from a Spanish guitar. |
| `strings` | The same value passed as the `strings` prop to the `<Guitar />` component with the current fretting. |
| `tuning` | An array of midi values for each string. `react-guitar` offers 4 tunings out of the box (`standard`, `ukelele`, `rondeña` and `dadgad`). |

And will return an object containing:

| Name    | Description                                                           |
| ------- | --------------------------------------------------------------------- |
| `play`  | A function that receives a string number and plays its current sound. |
| `strum` | A function that will strum all the strings of the guitar.             |

### Theming

`react-guitar` look and feel can be customised by passing the `theme` prop. A theme is an object describing the customisable properties of the guitar:

```tsx
{
  description: string // for screen readers
  color: string
  nut: { color: string }
  fret: {
    color: string
    separator: {
      color: string
      radius?: boolean
      shadow?: boolean
      width?: 'sm' | 'md'
    }
    marker?: (fret: number) => JSX.Element | null
    counter: { color: string }
  }
  string: { color: (string: number) => string }
  finger: { text: { color: string }; color: string }
}
```

See https://react-guitar.com/storybook/?path=/story/guitar--theming for an interactive example.

By default the guitar is styled as a Spanish guitar but some other themes are available:

- [react-guitar-theme-dark](packages/react-guitar-theme-dark): A dark theme.
- [react-guitar-theme-coco](packages/react-guitar-theme-coco): A theme for the guitar from the [Coco](<https://en.wikipedia.org/wiki/Coco_(2017_film)>) film.

## Developing

- `yarn build` will build the component and the site, this is mandatory the first time you clone the repo.
- `yarn start` will spin up the storybook and the site and all the packages in watch mode.
