|
| 1 | +import MainContent from '@/components/MainContent'; |
| 2 | +import TextFieldWithClean from '@/components/TextFieldWithClean'; |
| 3 | +import TextFieldWithCopy from '@/components/TextFieldWithCopy'; |
| 4 | +import SendIcon from '@mui/icons-material/Send'; |
| 5 | +import TranslateIcon from '@mui/icons-material/Translate'; |
| 6 | +import { Box, Button, Stack } from '@mui/material'; |
| 7 | +import { useState } from 'react'; |
| 8 | + |
| 9 | +function UnicodeConverter() { |
| 10 | + const [input, setInput] = useState(''); // 输入的普通文本或unicode码 |
| 11 | + const [output, setOutput] = useState(''); // 输出的unicode码或普通文本 |
| 12 | + |
| 13 | + // Unicode编码函数 |
| 14 | + const encodeToUnicode = (str: string) => { |
| 15 | + let unicode_str = ''; |
| 16 | + for (let i = 0; i < str.length; i++) { |
| 17 | + let unicode_code = str.charCodeAt(i).toString(16).toUpperCase(); |
| 18 | + unicode_str += '\\u' + ('0000' + unicode_code).slice(-4); |
| 19 | + } |
| 20 | + setOutput(unicode_str); |
| 21 | + }; |
| 22 | + |
| 23 | + // Unicode解码函数 |
| 24 | + const decodeFromUnicode = (unicode_str: string) => { |
| 25 | + let str = ''; |
| 26 | + unicode_str.replace( |
| 27 | + /\\u([\da-f]{4})/gi, |
| 28 | + (match, key) => (str += String.fromCharCode(parseInt(key, 16))) |
| 29 | + ); |
| 30 | + setOutput(str); |
| 31 | + }; |
| 32 | + |
| 33 | + // 渲染组件 |
| 34 | + return ( |
| 35 | + <MainContent> |
| 36 | + <Stack spacing={2} direction='row' alignItems='center'> |
| 37 | + <TextFieldWithClean |
| 38 | + multiline |
| 39 | + rows={8} |
| 40 | + value={input} |
| 41 | + variant='outlined' |
| 42 | + onClean={() => setInput('')} |
| 43 | + onChange={(e) => setInput(e.target.value)} |
| 44 | + /> |
| 45 | + <Box sx={{ minWidth: '88px' }}> |
| 46 | + <Button |
| 47 | + variant='contained' |
| 48 | + startIcon={<SendIcon />} |
| 49 | + sx={{ mb: 2 }} |
| 50 | + onClick={() => encodeToUnicode(input)} |
| 51 | + > |
| 52 | + 转码 |
| 53 | + </Button> |
| 54 | + <Button |
| 55 | + variant='contained' |
| 56 | + startIcon={<TranslateIcon />} |
| 57 | + onClick={() => decodeFromUnicode(input)} |
| 58 | + > |
| 59 | + 解码 |
| 60 | + </Button> |
| 61 | + </Box> |
| 62 | + <TextFieldWithCopy |
| 63 | + multiline |
| 64 | + rows={8} |
| 65 | + value={output} |
| 66 | + onChange={(e) => setOutput(e.target.value)} |
| 67 | + variant={'outlined'} |
| 68 | + /> |
| 69 | + </Stack> |
| 70 | + </MainContent> |
| 71 | + ); |
| 72 | +} |
| 73 | + |
| 74 | +export default UnicodeConverter; |
0 commit comments