All files / Bandstand/src/components ChartEditor.tsx

80.49% Statements 227/282
69.69% Branches 23/33
27.27% Functions 3/11
80.49% Lines 227/282

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347    1x 1x 1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                     5x 5x 5x 5x 5x 5x 5x             5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x   5x     5x                                 5x           5x 1x 1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x       1x   5x 5x         5x 5x 5x 5x 5x 5x   5x 5x 5x 5x   5x 5x 5x 5x 5x   5x 5x 5x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 5x 5x 5x 5x   5x 5x 5x 5x 5x 10x 10x 10x 10x 10x 10x   10x 10x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x   5x 5x 5x 5x   5x 10x 10x 10x 10x 10x 10x 10x   10x 10x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x                 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x         5x 5x     5x 5x 5x 5x 5x 5x   5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x   5x 5x 5x         5x 5x   5x  
'use client'
 
import Link from 'next/link'
import {useRouter} from 'next/navigation'
import {useMemo, useRef, useState} from 'react'
import {detectKey, importChordsOverWords, parseChordPro} from '@/lib/chordpro'
import {abcPresets} from '@/lib/abc'
import {parseLength} from '@/lib/gig'
import ChartBody from '@/components/chart/ChartBody'
 
export type SongFormValues = {
  title: string
  writer: string
  leadSinger: string
  guitars: string
  /** "3:12" */
  length: string
  keys: string
  percussion: string
  youtubeUrl: string
  lyricsUrl: string
  status: 'READY' | 'LEARNING'
  notes: string
}
 
const FIELDS: [keyof SongFormValues, string, string?][] = [
  ['title', 'Title'],
  ['writer', 'Written by'],
  ['leadSinger', 'Lead singer'],
  ['guitars', 'Guitars', 'number'],
  ['length', 'Length (m:ss)'],
  ['keys', 'Keys'],
  ['percussion', 'Percussion'],
  ['youtubeUrl', 'Recording link', 'url'],
  ['lyricsUrl', 'Lyrics link', 'url'],
]
 
export function toPayload({length, ...v}: SongFormValues) {
  const seconds = parseLength(length)
  return {
    ...v,
    // Unreadable ("3.12"): leave the saved length alone rather than erase it
    ...(seconds === undefined ? {} : {seconds}),
    guitars: v.guitars.trim() === '' ? null : Number(v.guitars),
    notes: v.notes.trim() || null,
  }
}
 
export default function ChartEditor({
  songId,
  initialFields,
  initialSource,
  baseNumber,
  demo = false,
}: {
  songId: string
  initialFields: SongFormValues
  initialSource: string
  baseNumber: number
  /** The tour's sample song: everything works but Save */
  demo?: boolean
}) {
  const back = demo ? '/tour/song' : `/songs/${songId}`
  const router = useRouter()
  const [fields, setFields] = useState(initialFields)
  const [source, setSource] = useState(initialSource)
  const [note, setNote] = useState('')
  const [tab, setTab] = useState<'edit' | 'preview'>('edit')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
 
  const chart = useMemo(() => parseChordPro(source), [source])
  const chartChanged = source !== initialSource
  const fieldsChanged = JSON.stringify(fields) !== JSON.stringify(initialFields)
 
  const textarea = useRef<HTMLTextAreaElement>(null)
 
  /** Drop a notation block in at the cursor (between lines), in the song's key. */
  function insertNotation() {
    const el = textarea.current
    const at = el ? el.selectionStart : source.length
    const lineStart = source.lastIndexOf('\n', at - 1) + 1
    const pattern = abcPresets(detectKey(chart))[0].abc
    const block = `{start_of_abc: Riff}\n${pattern}\n{end_of_abc}\n`
    const next = source.slice(0, lineStart) + block + source.slice(lineStart)
    setSource(next)
    requestAnimationFrame(() => {
      if (!el) return
      el.focus()
      // Select the music so it can be typed over straight away
      const start = lineStart + block.indexOf('\n') + 1
      el.setSelectionRange(start, start + pattern.length)
    })
  }
 
  function convertPasted() {
    // Turn a chords-over-lyrics paste (e.g. from a website) into ChordPro
    const {source: converted} = importChordsOverWords(source, fields.title)
    setSource(converted)
  }
 
  async function save() {
    if (demo) return
    setSaving(true)
    setError(null)
    try {
      if (fieldsChanged) {
        const r = await fetch(`/api/songs/${songId}`, {
          method: 'PATCH',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(toPayload(fields)),
        })
        if (!r.ok)
          throw new Error(
            'Could not save the song details. Check the links are full URLs.',
          )
      }
      if (chartChanged) {
        const r = await fetch(`/api/songs/${songId}/chart`, {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({source, note: note || null, baseNumber}),
        })
        if (r.status === 409) {
          const {latest} = await r.json()
          throw new Error(
            `Someone saved version ${latest} while you were editing. Your text is still here: copy it, open the chart again, and re-apply your change.`,
          )
        }
        if (!r.ok) throw new Error('Could not save the chart.')
      }
      router.push(`/songs/${songId}`)
      router.refresh()
    } catch (e) {
      setError((e as Error).message)
      setSaving(false)
    }
  }
 
  const looksLikeChordsOverWords =
    !/\[[^\]]+\]/.test(source.replace(/^\s*\[[^\]]+\]\s*$/gm, '')) &&
    /^\s*[A-G][#b]?(m|maj|sus|dim|aug|add|\d)*(\s+[A-G][#b]?\S*)*\s*$/m.test(
      source,
    )
 
  return (
    <main className="mx-auto max-w-[1400px] px-4 pb-16 pt-4 md:px-7">
      <Link
        href={back}
        className="text-sm text-muted no-underline hover:text-text"
      >
        ‹ Back to chart
      </Link>
      <h1 className="mt-1 text-3xl font-extrabold">
        Edit {initialFields.title}
      </h1>
 
      <section aria-labelledby="details-h" className="mt-5">
        <h2
          id="details-h"
          className="mb-3 text-xs font-bold uppercase tracking-widest text-muted"
        >
          Song details
        </h2>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {FIELDS.map(([k, label, type]) => (
            <label key={k} className="flex flex-col gap-1 text-sm text-muted">
              {label}
              <input
                type={type ?? 'text'}
                inputMode={type === 'number' ? 'numeric' : undefined}
                value={fields[k]}
                onChange={(e) => setFields({...fields, [k]: e.target.value})}
                className="min-h-11 rounded-lg border border-line-2 bg-panel px-3 text-base text-text"
              />
            </label>
          ))}
          <fieldset className="flex flex-col gap-1 text-sm text-muted">
            <legend className="mb-1">Status</legend>
            <div className="flex overflow-hidden rounded-lg border border-line-2">
              {(
                [
                  ['READY', 'Gig-ready'],
                  ['LEARNING', 'Learning'],
                ] as const
              ).map(([v, label]) => (
                <button
                  key={v}
                  type="button"
                  aria-pressed={fields.status === v}
                  onClick={() => setFields({...fields, status: v})}
                  className={`min-h-11 flex-1 ${fields.status === v ? 'bg-text font-semibold text-ink' : 'text-text'}`}
                >
                  {label}
                </button>
              ))}
            </div>
          </fieldset>
          <label className="flex flex-col gap-1 text-sm text-muted sm:col-span-2 lg:col-span-3">
            Notes (shown above the chart)
            <textarea
              value={fields.notes}
              onChange={(e) => setFields({...fields, notes: e.target.value})}
              rows={2}
              className="rounded-lg border border-line-2 bg-panel px-3 py-2 text-base text-text"
            />
          </label>
        </div>
      </section>
 
      <section aria-labelledby="chart-h" className="mt-8">
        <div className="mb-3 flex flex-wrap items-center gap-3">
          <h2
            id="chart-h"
            className="text-xs font-bold uppercase tracking-widest text-muted"
          >
            Chart
          </h2>
          <div
            role="tablist"
            className="flex overflow-hidden rounded-lg border border-line-2 lg:hidden"
          >
            {(['edit', 'preview'] as const).map((t) => (
              <button
                key={t}
                role="tab"
                type="button"
                aria-selected={tab === t}
                onClick={() => setTab(t)}
                className={`min-h-10 px-4 capitalize ${tab === t ? 'bg-text font-semibold text-ink' : ''}`}
              >
                {t}
              </button>
            ))}
          </div>
          <span className="flex-1" />
          <button
            type="button"
            onClick={insertNotation}
            className="min-h-10 rounded-lg border border-line-2 px-3 text-sm font-semibold"
          >
            ♪ Insert notation
          </button>
          {looksLikeChordsOverWords && (
            <button
              type="button"
              onClick={convertPasted}
              className="min-h-10 rounded-lg border border-amber px-3 text-sm font-semibold text-amber"
            >
              Convert chords-over-lyrics
            </button>
          )}
        </div>
        <div data-tour="editor" className="grid gap-6 lg:grid-cols-2">
          <div className={tab === 'edit' ? '' : 'hidden lg:block'}>
            <label htmlFor="chart-source" className="sr-only">
              Chart (ChordPro)
            </label>
            <textarea
              ref={textarea}
              id="chart-source"
              value={source}
              onChange={(e) => setSource(e.target.value)}
              spellCheck={false}
              autoCapitalize="off"
              autoCorrect="off"
              className="h-[65vh] w-full rounded-lg border border-line-2 bg-panel-2 p-3 font-mono text-[15px] leading-relaxed text-text"
            />
            <details className="mt-2 text-sm text-muted">
              <summary className="cursor-pointer py-1">
                How to write a chart
              </summary>
              <div className="mt-2 space-y-1 font-mono text-[13px]">
                <p>Oh, I could [G]hide &apos;neath the [Am]wings</p>
                <p>
                  {'{start_of_verse: Verse 1}'} … {'{end_of_verse}'}
                </p>
                <p>
                  {'{start_of_chorus: Chorus (x2)}'} … {'{end_of_chorus}'}
                </p>
                <p>
                  {'{start_of_intro: Intro}'} [G] [D7sus4] [G]{' '}
                  {'{end_of_intro}'}
                </p>
                <p>{'{comment: Micky counts it in}'}</p>
                <p>
                  {'{start_of_abc: Horn riff}'} &quot;G&quot;B2 B2 B4 |
                  &quot;C&quot;B8 |] {'{end_of_abc}'}
                </p>
                <p className="font-sans">
                  Notation is ABC (abcnotation.com): letters are notes, numbers
                  are lengths, z is a rest, “G” is a chord, | is a bar. Write it
                  in the song’s key; it transposes with the chart. The preview
                  draws it as you type.
                </p>
                <p className="font-sans">
                  Or paste chords-above-lyrics text from anywhere and press
                  “Convert”.
                </p>
              </div>
            </details>
          </div>
          <div
            className={`rounded-lg border border-line p-4 text-[17px] ${tab === 'preview' ? '' : 'hidden lg:block'}`}
          >
            <ChartBody chart={chart} columns={false} notationOpen />
          </div>
        </div>
      </section>
 
      <div className="sticky bottom-[max(env(safe-area-inset-bottom),16px)] z-20 mt-6 flex flex-wrap items-center gap-2 rounded-xl border border-line-2 bg-panel p-2 sm:gap-3 sm:p-3">
        <label className="flex min-w-0 flex-1 basis-64 items-center gap-2 text-sm text-muted">
          <span className="hidden shrink-0 sm:inline">What changed?</span>
          <input
            value={note}
            onChange={(e) => setNote(e.target.value)}
            placeholder="What changed? e.g. added the C under “to a”"
            aria-label="What changed?"
            disabled={!chartChanged}
            className="min-h-11 min-w-0 flex-1 rounded-lg border border-line-2 bg-ink px-3 text-base text-text disabled:opacity-50"
          />
        </label>
        <Link
          href={back}
          className="inline-flex min-h-11 items-center px-3 text-muted"
        >
          Cancel
        </Link>
        <button
          type="button"
          onClick={save}
          disabled={demo || saving || (!chartChanged && !fieldsChanged)}
          title={demo ? 'The tour’s sample: nothing saves' : undefined}
          className="min-h-11 rounded-lg bg-accent px-5 font-bold text-on-accent disabled:opacity-40"
        >
          {saving ? 'Saving…' : 'Save'}
        </button>
        {error && (
          <p role="alert" className="basis-full text-sm text-bad">
            {error}
          </p>
        )}
      </div>
    </main>
  )
}