refactor with const enum

This commit is contained in:
Pig Fang 2020-05-13 18:40:09 +08:00
parent 3e1a10a461
commit 3556f29a24
14 changed files with 90 additions and 57 deletions

View File

@ -7,7 +7,7 @@ type Response = fetch.ResponseBody<Texture>
export default function useTexture() { export default function useTexture() {
const [tid, setTid] = useState(0) const [tid, setTid] = useState(0)
const [url, setUrl] = useState('') const [url, setUrl] = useState('')
const [type, setType] = useState<TextureType>('steve') const [type, setType] = useState(TextureType.Steve)
useEffect(() => { useEffect(() => {
if (tid <= 0) { if (tid <= 0) {

View File

@ -39,7 +39,11 @@ export type Texture = {
likes: number likes: number
} }
export type TextureType = 'steve' | 'alex' | 'cape' export const enum TextureType {
Steve = 'steve',
Alex = 'alex',
Cape = 'cape',
}
export type ClosetItem = Texture & { export type ClosetItem = Texture & {
pivot: { user_uid: number; texture_tid: number; item_name: string } pivot: { user_uid: number; texture_tid: number; item_name: string }

View File

@ -1,5 +1,6 @@
import React, { useState } from 'react' import React, { useState } from 'react'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import { TextureType } from '@/scripts/types'
import Modal from '@/components/Modal' import Modal from '@/components/Modal'
interface Props { interface Props {
@ -58,7 +59,7 @@ const ModalUpdateTexture: React.FC<Props> = (props) => {
className="mr-1" className="mr-1"
type="radio" type="radio"
value="cape" value="cape"
checked={type === 'cape'} checked={type === TextureType.Cape}
onChange={handleTypeChange} onChange={handleTypeChange}
/> />
{t('general.cape')} {t('general.cape')}

View File

@ -93,9 +93,9 @@ const Show: React.FC = () => {
input: texture.type, input: texture.type,
inputType: 'radios', inputType: 'radios',
choices: [ choices: [
{ text: 'Steve', value: 'steve' }, { text: 'Steve', value: TextureType.Steve },
{ text: 'Alex', value: 'alex' }, { text: 'Alex', value: TextureType.Alex },
{ text: t('general.cape'), value: 'cape' }, { text: t('general.cape'), value: TextureType.Cape },
], ],
}) })
type = value as TextureType type = value as TextureType
@ -232,7 +232,10 @@ const Show: React.FC = () => {
const linkToUploader = (() => { const linkToUploader = (() => {
const search = new URLSearchParams() const search = new URLSearchParams()
search.append('filter', texture.type === 'cape' ? 'cape' : 'skin') search.append(
'filter',
texture.type === TextureType.Cape ? TextureType.Cape : 'skin',
)
search.append('uploader', texture.uploader?.toString()) search.append('uploader', texture.uploader?.toString())
return `${blessing.base_url}/skinlib?${search}` return `${blessing.base_url}/skinlib?${search}`
@ -246,8 +249,12 @@ const Show: React.FC = () => {
{createPortal( {createPortal(
<React.Suspense fallback={<ViewerSkeleton />}> <React.Suspense fallback={<ViewerSkeleton />}>
<Previewer <Previewer
{...{ [texture.type === 'cape' ? 'cape' : 'skin']: textureUrl }} {...{
isAlex={texture.type === 'alex'} [texture.type === TextureType.Cape
? TextureType.Cape
: 'skin']: textureUrl,
}}
isAlex={texture.type === TextureType.Alex}
initPositionZ={60} initPositionZ={60}
> >
{currentUid === 0 ? ( {currentUid === 0 ? (
@ -284,7 +291,7 @@ const Show: React.FC = () => {
{t('skinlib.addToCloset')} {t('skinlib.addToCloset')}
</button> </button>
)} )}
{texture.type !== 'cape' && ( {texture.type !== TextureType.Cape && (
<button <button
className="btn btn-outline-info mr-2" className="btn btn-outline-info mr-2"
onClick={handleSetAsAvatar} onClick={handleSetAsAvatar}
@ -343,7 +350,9 @@ const Show: React.FC = () => {
<div className="row my-4"> <div className="row my-4">
<div className="col-4">{t('skinlib.show.model')}</div> <div className="col-4">{t('skinlib.show.model')}</div>
<div className="col-7"> <div className="col-7">
{texture.type === 'cape' ? t('general.cape') : texture.type} {texture.type === TextureType.Cape
? t('general.cape')
: texture.type}
</div> </div>
{canEdit && ( {canEdit && (
<div className="col-1"> <div className="col-1">
@ -425,7 +434,11 @@ const Show: React.FC = () => {
<ModalApply <ModalApply
show={showModalApply} show={showModalApply}
canAdd={false} canAdd={false}
{...{ [texture.type === 'cape' ? 'cape' : 'skin']: texture.tid }} {...{
[texture.type === TextureType.Cape
? TextureType.Cape
: 'skin']: texture.tid,
}}
onClose={handleCloseModalApply} onClose={handleCloseModalApply}
/> />
</> </>

View File

@ -1,5 +1,6 @@
import React from 'react' import React from 'react'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import { TextureType } from '@/scripts/types'
import Button from './Button' import Button from './Button'
import { Filter } from './types' import { Filter } from './types'
import { humanizeType } from './utils' import { humanizeType } from './utils'
@ -13,9 +14,9 @@ const FilterSelector: React.FC<Props> = (props) => {
const { filter, onChange } = props const { filter, onChange } = props
const handleSkinClick = () => onChange('skin') const handleSkinClick = () => onChange('skin')
const handleSteveClick = () => onChange('steve') const handleSteveClick = () => onChange(TextureType.Steve)
const handleAlexClick = () => onChange('alex') const handleAlexClick = () => onChange(TextureType.Alex)
const handleCapeClick = () => onChange('cape') const handleCapeClick = () => onChange(TextureType.Cape)
return ( return (
<> <>
@ -36,21 +37,21 @@ const FilterSelector: React.FC<Props> = (props) => {
</Button> </Button>
<Button <Button
className="dropdown-item" className="dropdown-item"
active={filter === 'steve'} active={filter === TextureType.Steve}
onClick={handleSteveClick} onClick={handleSteveClick}
> >
Steve Steve
</Button> </Button>
<Button <Button
className="dropdown-item" className="dropdown-item"
active={filter === 'alex'} active={filter === TextureType.Alex}
onClick={handleAlexClick} onClick={handleAlexClick}
> >
Alex Alex
</Button> </Button>
<Button <Button
className="dropdown-item" className="dropdown-item"
active={filter === 'cape'} active={filter === TextureType.Cape}
onClick={handleCapeClick} onClick={handleCapeClick}
> >
{t('general.cape')} {t('general.cape')}

View File

@ -4,7 +4,7 @@ import useBlessingExtra from '@/scripts/hooks/useBlessingExtra'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { toast } from '@/scripts/notify' import { toast } from '@/scripts/notify'
import { Paginator } from '@/scripts/types' import { Paginator, TextureType } from '@/scripts/types'
import Loading from '@/components/Loading' import Loading from '@/components/Loading'
import Pagination from '@/components/Pagination' import Pagination from '@/components/Pagination'
import addClosetItem from '../Show/addClosetItem' import addClosetItem from '../Show/addClosetItem'
@ -33,7 +33,12 @@ const SkinLibrary: React.FC = () => {
const filter = search.get('filter') ?? '' const filter = search.get('filter') ?? ''
setFilter( setFilter(
['skin', 'steve', 'alex', 'cape'].includes(filter) [
'skin',
TextureType.Steve,
TextureType.Alex,
TextureType.Cape,
].includes(filter)
? (filter as Filter) ? (filter as Filter)
: 'skin', : 'skin',
) )

View File

@ -1,11 +1,12 @@
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import { TextureType } from '@/scripts/types'
import { Filter } from './types' import { Filter } from './types'
export function humanizeType(type: Filter): string { export function humanizeType(type: Filter): string {
switch (type) { switch (type) {
case 'steve': case TextureType.Steve:
return 'Steve' return 'Steve'
case 'alex': case TextureType.Alex:
return 'Alex' return 'Alex'
default: default:
return t(`general.${type}`) return t(`general.${type}`)

View File

@ -15,7 +15,7 @@ const Previewer = React.lazy(() => import('@/components/Viewer'))
const Upload: React.FC = () => { const Upload: React.FC = () => {
const [name, setName] = useState('') const [name, setName] = useState('')
const [type, setType] = useState<TextureType>('steve') const [type, setType] = useState(TextureType.Steve)
const [isPrivate, setIsPrivate] = useState(false) const [isPrivate, setIsPrivate] = useState(false)
const [isUploading, setIsUploading] = useState(false) const [isUploading, setIsUploading] = useState(false)
const [file, setFile] = useState<File | null>(null) const [file, setFile] = useState<File | null>(null)
@ -54,8 +54,8 @@ const Upload: React.FC = () => {
} }
const texture = URL.createObjectURL(file) const texture = URL.createObjectURL(file)
setTexture(texture) setTexture(texture)
if (type !== 'cape') { if (type !== TextureType.Cape) {
setType((await isAlex(texture)) ? 'alex' : 'steve') setType((await isAlex(texture)) ? TextureType.Alex : TextureType.Steve)
} }
} }
} }
@ -136,7 +136,7 @@ const Upload: React.FC = () => {
className="mr-1" className="mr-1"
name="type" name="type"
value="steve" value="steve"
checked={type === 'steve'} checked={type === TextureType.Steve}
onChange={handleTypeChange} onChange={handleTypeChange}
/> />
Steve Steve
@ -147,7 +147,7 @@ const Upload: React.FC = () => {
className="mr-1" className="mr-1"
name="type" name="type"
value="alex" value="alex"
checked={type === 'alex'} checked={type === TextureType.Alex}
onChange={handleTypeChange} onChange={handleTypeChange}
/> />
Alex Alex
@ -158,7 +158,7 @@ const Upload: React.FC = () => {
className="mr-1" className="mr-1"
name="type" name="type"
value="cape" value="cape"
checked={type === 'cape'} checked={type === TextureType.Cape}
onChange={handleTypeChange} onChange={handleTypeChange}
/> />
{t('general.cape')} {t('general.cape')}
@ -228,9 +228,9 @@ const Upload: React.FC = () => {
{ReactDOM.createPortal( {ReactDOM.createPortal(
<React.Suspense fallback={<ViewerSkeleton />}> <React.Suspense fallback={<ViewerSkeleton />}>
<Previewer <Previewer
skin={type !== 'cape' ? texture : undefined} skin={type !== TextureType.Cape ? texture : undefined}
cape={type === 'cape' ? texture : undefined} cape={type === TextureType.Cape ? texture : undefined}
isAlex={type === 'alex'} isAlex={type === TextureType.Alex}
/> />
</React.Suspense>, </React.Suspense>,
container, container,

View File

@ -4,7 +4,12 @@ import debounce from 'lodash.debounce'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { showModal, toast } from '@/scripts/notify' import { showModal, toast } from '@/scripts/notify'
import { ClosetItem as Item, Texture, Paginator } from '@/scripts/types' import {
ClosetItem as Item,
Texture,
Paginator,
TextureType,
} from '@/scripts/types'
import Loading from '@/components/Loading' import Loading from '@/components/Loading'
import Pagination from '@/components/Pagination' import Pagination from '@/components/Pagination'
import ClosetItem from './ClosetItem' import ClosetItem from './ClosetItem'
@ -50,7 +55,7 @@ const Closet: React.FC = () => {
}, [category, query, page]) }, [category, query, page])
const switchCategory = () => { const switchCategory = () => {
setCategory(category => (category === 'skin' ? 'cape' : 'skin')) setCategory((category) => (category === 'skin' ? 'cape' : 'skin'))
} }
const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => { const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
@ -70,7 +75,7 @@ const Closet: React.FC = () => {
} }
const handleSelect = (item: Item) => { const handleSelect = (item: Item) => {
if (item.type === 'cape') { if (item.type === TextureType.Cape) {
setCape(item) setCape(item)
} else { } else {
setSkin(item) setSkin(item)
@ -106,7 +111,7 @@ const Closet: React.FC = () => {
) )
if (code === 0) { if (code === 0) {
toast.success(message) toast.success(message)
setItems(items => { setItems((items) => {
items[index] = { ...item, pivot: { ...item.pivot, item_name: name } } items[index] = { ...item, pivot: { ...item.pivot, item_name: name } }
return items.slice() return items.slice()
}) })
@ -119,7 +124,7 @@ const Closet: React.FC = () => {
const { tid } = item const { tid } = item
const ok = await removeClosetItem(tid) const ok = await removeClosetItem(tid)
if (ok) { if (ok) {
setItems(items => items.filter(item => item.tid !== tid)) setItems((items) => items.filter((item) => item.tid !== tid))
} }
} }
@ -151,7 +156,9 @@ const Closet: React.FC = () => {
<li className="nav-item"> <li className="nav-item">
<a <a
href="#" href="#"
className={`nav-link ${category === 'cape' ? 'active' : ''}`} className={`nav-link ${
category === TextureType.Cape ? 'active' : ''
}`}
data-toggle="pill" data-toggle="pill"
role="tab" role="tab"
onClick={switchCategory} onClick={switchCategory}
@ -225,7 +232,7 @@ const Closet: React.FC = () => {
<Previewer <Previewer
skin={skin?.hash} skin={skin?.hash}
cape={cape?.hash} cape={cape?.hash}
isAlex={skin?.type === 'alex'} isAlex={skin?.type === TextureType.Alex}
> >
<div className="d-flex justify-content-between"> <div className="d-flex justify-content-between">
<button className="btn btn-primary" onClick={applyToPlayer}> <button className="btn btn-primary" onClick={applyToPlayer}>

View File

@ -4,7 +4,7 @@ import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { showModal, toast } from '@/scripts/notify' import { showModal, toast } from '@/scripts/notify'
import useTexture from '@/scripts/hooks/useTexture' import useTexture from '@/scripts/hooks/useTexture'
import { Player } from '@/scripts/types' import { Player, TextureType } from '@/scripts/types'
import Loading from '@/components/Loading' import Loading from '@/components/Loading'
import Row from './Row' import Row from './Row'
import Previewer from './Previewer' import Previewer from './Previewer'
@ -200,7 +200,7 @@ const Players: React.FC = () => {
<Previewer <Previewer
skin={skin.url} skin={skin.url}
cape={cape.url} cape={cape.url}
isAlex={skin.type === 'alex'} isAlex={skin.type === TextureType.Alex}
/> />
<ModalAddPlayer <ModalAddPlayer
show={showModalAddPlayer} show={showModalAddPlayer}

View File

@ -2,7 +2,7 @@ import React from 'react'
import { render, fireEvent, waitFor } from '@testing-library/react' import { render, fireEvent, waitFor } from '@testing-library/react'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { Texture } from '@/scripts/types' import { Texture, TextureType } from '@/scripts/types'
import Show, { Badge } from '@/views/skinlib/Show' import Show, { Badge } from '@/views/skinlib/Show'
jest.mock('@/scripts/net') jest.mock('@/scripts/net')
@ -10,7 +10,7 @@ jest.mock('@/scripts/net')
const fixtureSkin: Readonly<Texture> = Object.freeze<Texture>({ const fixtureSkin: Readonly<Texture> = Object.freeze<Texture>({
tid: 1, tid: 1,
name: 'skin', name: 'skin',
type: 'steve', type: TextureType.Steve,
hash: 'abc', hash: 'abc',
size: 2, size: 2,
uploader: 1, uploader: 1,
@ -22,7 +22,7 @@ const fixtureSkin: Readonly<Texture> = Object.freeze<Texture>({
const fixtureCape: Readonly<Texture> = Object.freeze<Texture>({ const fixtureCape: Readonly<Texture> = Object.freeze<Texture>({
tid: 2, tid: 2,
name: 'cape', name: 'cape',
type: 'cape', type: TextureType.Cape,
hash: 'def', hash: 'def',
size: 2, size: 2,
uploader: 1, uploader: 1,

View File

@ -3,6 +3,7 @@ import { render, fireEvent, waitFor } from '@testing-library/react'
import { createPaginator } from '../../utils' import { createPaginator } from '../../utils'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { TextureType } from '@/scripts/types'
import SkinLibrary from '@/views/skinlib/SkinLibrary' import SkinLibrary from '@/views/skinlib/SkinLibrary'
import { LibraryItem } from '@/views/skinlib/SkinLibrary/types' import { LibraryItem } from '@/views/skinlib/SkinLibrary/types'
@ -11,7 +12,7 @@ jest.mock('@/scripts/net')
const fixtureItem: Readonly<LibraryItem> = Object.freeze<LibraryItem>({ const fixtureItem: Readonly<LibraryItem> = Object.freeze<LibraryItem>({
tid: 1, tid: 1,
name: 'my skin', name: 'my skin',
type: 'steve', type: TextureType.Steve,
uploader: 1, uploader: 1,
nickname: 'me', nickname: 'me',
public: true, public: true,

View File

@ -4,7 +4,7 @@ import { createPaginator } from '../../utils'
import $ from 'jquery' import $ from 'jquery'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { ClosetItem, Player } from '@/scripts/types' import { ClosetItem, Player, TextureType } from '@/scripts/types'
import Closet from '@/views/user/Closet' import Closet from '@/views/user/Closet'
jest.mock('@/scripts/net') jest.mock('@/scripts/net')
@ -12,7 +12,7 @@ jest.mock('@/scripts/net')
const fixtureSkin: Readonly<ClosetItem> = Object.freeze<ClosetItem>({ const fixtureSkin: Readonly<ClosetItem> = Object.freeze<ClosetItem>({
tid: 1, tid: 1,
name: 'skin', name: 'skin',
type: 'steve', type: TextureType.Steve,
hash: 'abc', hash: 'abc',
size: 2, size: 2,
uploader: 1, uploader: 1,
@ -29,7 +29,7 @@ const fixtureSkin: Readonly<ClosetItem> = Object.freeze<ClosetItem>({
const fixtureCape: Readonly<ClosetItem> = Object.freeze<ClosetItem>({ const fixtureCape: Readonly<ClosetItem> = Object.freeze<ClosetItem>({
tid: 2, tid: 2,
name: 'cape', name: 'cape',
type: 'cape', type: TextureType.Cape,
hash: 'def', hash: 'def',
size: 2, size: 2,
uploader: 1, uploader: 1,

View File

@ -2,7 +2,7 @@ import React from 'react'
import { render, fireEvent, waitFor } from '@testing-library/react' import { render, fireEvent, waitFor } from '@testing-library/react'
import { t } from '@/scripts/i18n' import { t } from '@/scripts/i18n'
import * as fetch from '@/scripts/net' import * as fetch from '@/scripts/net'
import { Player } from '@/scripts/types' import { Player, TextureType } from '@/scripts/types'
import Players from '@/views/user/Players' import Players from '@/views/user/Players'
jest.mock('@/scripts/net') jest.mock('@/scripts/net')
@ -65,8 +65,8 @@ describe('select player automatically', () => {
it('only one player', async () => { it('only one player', async () => {
fetch.get fetch.get
.mockResolvedValueOnce([fixture]) .mockResolvedValueOnce([fixture])
.mockResolvedValueOnce({ data: { hash: '', type: 'steve' } }) .mockResolvedValueOnce({ data: { hash: '', type: TextureType.Steve } })
.mockResolvedValueOnce({ data: { hash: '', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: '', type: TextureType.Cape } })
render(<Players />) render(<Players />)
await waitFor(() => expect(fetch.get).toBeCalledTimes(1)) await waitFor(() => expect(fetch.get).toBeCalledTimes(1))
@ -96,8 +96,8 @@ describe('2d preview', () => {
it('skin and cape', async () => { it('skin and cape', async () => {
fetch.get fetch.get
.mockResolvedValueOnce([fixture]) .mockResolvedValueOnce([fixture])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'steve' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: TextureType.Steve } })
.mockResolvedValueOnce({ data: { hash: 'b', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: 'b', type: TextureType.Cape } })
const { getByAltText, getByText } = render(<Players />) const { getByAltText, getByText } = render(<Players />)
await waitFor(() => expect(fetch.get).toBeCalledTimes(1)) await waitFor(() => expect(fetch.get).toBeCalledTimes(1))
@ -117,7 +117,7 @@ describe('2d preview', () => {
it('skin only', async () => { it('skin only', async () => {
fetch.get fetch.get
.mockResolvedValueOnce([{ ...fixture, tid_cape: 0 }]) .mockResolvedValueOnce([{ ...fixture, tid_cape: 0 }])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'steve' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: TextureType.Steve } })
const { getByAltText, queryByAltText, getByText, queryByText } = render( const { getByAltText, queryByAltText, getByText, queryByText } = render(
<Players />, <Players />,
@ -137,7 +137,7 @@ describe('2d preview', () => {
it('cape only', async () => { it('cape only', async () => {
fetch.get fetch.get
.mockResolvedValueOnce([{ ...fixture, tid_skin: 0 }]) .mockResolvedValueOnce([{ ...fixture, tid_skin: 0 }])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: TextureType.Cape } })
const { getByAltText, queryByAltText, getByText, queryByText } = render( const { getByAltText, queryByAltText, getByText, queryByText } = render(
<Players />, <Players />,
@ -265,7 +265,7 @@ describe('edit player name', () => {
fetch.get fetch.get
.mockResolvedValueOnce([fixture]) .mockResolvedValueOnce([fixture])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } })
.mockResolvedValueOnce({ data: { hash: 'b', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: 'b', type: TextureType.Cape } })
}) })
it('succeeded', async () => { it('succeeded', async () => {
@ -360,7 +360,7 @@ describe('reset texture', () => {
fetch.get fetch.get
.mockResolvedValueOnce([fixture]) .mockResolvedValueOnce([fixture])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } })
.mockResolvedValueOnce({ data: { hash: 'b', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: 'b', type: TextureType.Cape } })
}) })
it('clear skin and cape', async () => { it('clear skin and cape', async () => {
@ -483,7 +483,7 @@ describe('delete player', () => {
fetch.get fetch.get
.mockResolvedValueOnce([fixture]) .mockResolvedValueOnce([fixture])
.mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } }) .mockResolvedValueOnce({ data: { hash: 'a', type: 'skin' } })
.mockResolvedValueOnce({ data: { hash: 'b', type: 'cape' } }) .mockResolvedValueOnce({ data: { hash: 'b', type: TextureType.Cape } })
}) })
it('succeeded', async () => { it('succeeded', async () => {