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 | 5x 5x 131x 131x 131x 26x 26x 26x 2x 2x 24x 5x 5x 19x 19x 13x 13x 12x 1x 131x 1x 131x | import { onBeforeUnmount, ref, type Ref } from 'vue'
import api from '@/services/api'
export type NicknameStatus = 'idle' | 'checking' | 'available' | 'taken' | 'invalid'
/** Mirrors the API's validateNickname: 3-20 lowercase letters/digits/underscores, starting with a letter. */
export const NICKNAME_REGEX = /^[a-z][a-z0-9_]{2,19}$/
const CHECK_DEBOUNCE_MS = 400
/**
* Nickname input state with a debounced availability check, shared by every
* place a user picks their @nickname (sign-up, profile, missing-nickname prompt).
*
* @param currentNickname - the user's saved nickname, if any: typing it back
* resets the status to idle instead of reporting it as taken (by themself).
*/
export function useNicknameAvailability(currentNickname?: Ref<string | null>) {
const nickname = ref('')
const status = ref<NicknameStatus>('idle')
let checkTimeout: ReturnType<typeof setTimeout> | null = null
function onNicknameInput(event: Event) {
nickname.value = (event.target as HTMLInputElement).value.toLowerCase()
if (checkTimeout) clearTimeout(checkTimeout)
if (!nickname.value || nickname.value === currentNickname?.value) {
status.value = 'idle'
return
}
if (!NICKNAME_REGEX.test(nickname.value)) {
status.value = 'invalid'
return
}
status.value = 'checking'
checkTimeout = setTimeout(async () => {
try {
const response = await api.get('/v1/users/nickname-availability', {
params: { nickname: nickname.value }
})
status.value = response.data.available ? 'available' : 'taken'
} catch {
status.value = 'idle'
}
}, CHECK_DEBOUNCE_MS)
}
onBeforeUnmount(() => {
Eif (checkTimeout) clearTimeout(checkTimeout)
})
return { nickname, status, onNicknameInput }
}
|