create a frontend with a main menu
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
import { useRef, useState } from 'react'
|
||||
|
||||
const CODE_LENGTH = 5
|
||||
|
||||
export default function CodeInput({ onSubmit }) {
|
||||
const [values, setValues] = useState(Array(CODE_LENGTH).fill(''))
|
||||
const inputsRef = useRef([])
|
||||
|
||||
const code = values.join('')
|
||||
const complete = code.length === CODE_LENGTH
|
||||
|
||||
const focusInput = (i) => inputsRef.current[i]?.focus()
|
||||
|
||||
const handleChange = (i, raw) => {
|
||||
const chars = raw.toUpperCase().replace(/[^A-Z0-9]/g, '')
|
||||
if (!chars) return
|
||||
const next = [...values]
|
||||
// Поддержка вставки нескольких символов (paste в отдельное поле тоже)
|
||||
for (let k = 0; k < chars.length && i + k < CODE_LENGTH; k++) {
|
||||
next[i + k] = chars[k]
|
||||
}
|
||||
setValues(next)
|
||||
const nextIndex = Math.min(i + chars.length, CODE_LENGTH - 1)
|
||||
focusInput(nextIndex)
|
||||
}
|
||||
|
||||
const handleKeyDown = (i, e) => {
|
||||
if (e.key === 'Backspace') {
|
||||
e.preventDefault()
|
||||
const next = [...values]
|
||||
if (next[i]) {
|
||||
next[i] = ''
|
||||
setValues(next)
|
||||
} else if (i > 0) {
|
||||
next[i - 1] = ''
|
||||
setValues(next)
|
||||
focusInput(i - 1)
|
||||
}
|
||||
} else if (e.key === 'ArrowLeft' && i > 0) {
|
||||
focusInput(i - 1)
|
||||
} else if (e.key === 'ArrowRight' && i < CODE_LENGTH - 1) {
|
||||
focusInput(i + 1)
|
||||
} else if (e.key === 'Enter' && complete) {
|
||||
onSubmit?.(code)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = (e) => {
|
||||
e.preventDefault()
|
||||
const text = e.clipboardData.getData('text').toUpperCase().replace(/[^A-Z0-9]/g, '')
|
||||
if (!text) return
|
||||
const next = Array(CODE_LENGTH).fill('')
|
||||
for (let k = 0; k < Math.min(text.length, CODE_LENGTH); k++) next[k] = text[k]
|
||||
setValues(next)
|
||||
focusInput(Math.min(text.length, CODE_LENGTH - 1))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="code-input-row">
|
||||
<div className="code-inputs" onPaste={handlePaste}>
|
||||
{values.map((v, i) => (
|
||||
<input
|
||||
key={i}
|
||||
ref={(el) => (inputsRef.current[i] = el)}
|
||||
className="code-cell"
|
||||
value={v}
|
||||
maxLength={CODE_LENGTH}
|
||||
inputMode="text"
|
||||
autoComplete="off"
|
||||
onChange={(e) => handleChange(i, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(i, e)}
|
||||
onFocus={(e) => e.target.select()}
|
||||
aria-label={`Символ ${i + 1}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
className="code-submit"
|
||||
disabled={!complete}
|
||||
onClick={() => onSubmit?.(code)}
|
||||
aria-label="Присоединиться"
|
||||
title="Присоединиться"
|
||||
>
|
||||
➜
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user