All files / Bandstand/src/components VoteThreshold.tsx

0% Statements 0/49
100% Branches 1/1
100% Functions 1/1
0% Lines 0/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                                                                     
'use client'
 
import {useState} from 'react'
 
export default function VoteThreshold({
  initial,
  max,
}: {
  initial: number
  max: number
}) {
  const [value, setValue] = useState(initial)
  const [saved, setSaved] = useState(initial)
  const [error, setError] = useState(false)
  async function save(n: number) {
    setValue(n)
    const r = await fetch('/api/band', {
      method: 'PATCH',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({voteThreshold: n}),
    })
    if (r.ok) setSaved(n)
    else {
      setValue(saved)
      setError(true)
    }
  }
  return (
    <div className="mt-3 rounded-xl border border-line-2 bg-panel p-4">
      <p>Votes needed for a proposal to join the book</p>
      <div
        role="radiogroup"
        aria-label="Votes needed"
        className="mt-3 flex flex-wrap gap-2"
      >
        {Array.from({length: Math.max(max, initial)}, (_, i) => i + 1).map(
          (n) => (
            <button
              key={n}
              type="button"
              role="radio"
              aria-checked={value === n}
              onClick={() => save(n)}
              className={`h-11 w-11 rounded-lg font-mono font-bold ${value === n ? 'bg-accent text-on-accent' : 'border border-line-2'}`}
            >
              {n}
            </button>
          ),
        )}
      </div>
      <p className="mt-2 text-sm text-muted">
        {error
          ? 'Couldn’t save — try again.'
          : `Saved: ${saved}. Applies to the next vote cast.`}
      </p>
    </div>
  )
}