Compare commits
9 Commits
1a3be5f76b
...
ae013acd2d
| Author | SHA1 | Date | |
|---|---|---|---|
| ae013acd2d | |||
| dcb2d1847d | |||
| daeaaca902 | |||
| b2fe4519f8 | |||
| 2cea340163 | |||
| eaa3319c5d | |||
| 24cbc54a96 | |||
| 42567ab6e4 | |||
| 555749b953 |
76
.github/workflows/ci.yml
vendored
Normal file
76
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
name: CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
# ── 1. 린트 + 테스트 + 빌드 ────────────────────────────────────────────────
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
env:
|
||||
VITE_API_BASE_URL: https://a301.api.tolelom.xyz
|
||||
|
||||
# ── 2. Docker 빌드 & Gitea 레지스트리 푸시 (main 머지 시만) ───────────────
|
||||
docker:
|
||||
needs: test
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.tolelom.xyz
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: git.tolelom.xyz/${{ github.repository_owner }}/a301-web:latest
|
||||
platforms: linux/arm64
|
||||
build-args: |
|
||||
VITE_API_BASE_URL=https://a301.api.tolelom.xyz
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
# ── 3. 서버 배포 ──────────────────────────────────────────────────────────
|
||||
deploy:
|
||||
needs: docker
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: appleboy/ssh-action@v1
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
script: |
|
||||
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.docker/bin
|
||||
cd ~/server
|
||||
docker compose pull web
|
||||
docker compose up -d web
|
||||
@@ -3,6 +3,9 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
|
||||
<meta property="og:title" content="One of the plans">
|
||||
<meta property="og:description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
|
||||
<title>One of the plans</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-route
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import { ToastProvider } from './components/toast/ToastProvider';
|
||||
import { ConfirmProvider } from './components/confirm/ConfirmProvider';
|
||||
import { useAuth } from './context/useAuth';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import LoginPage from './pages/LoginPage';
|
||||
@@ -67,7 +68,9 @@ export default function App() {
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<ConfirmProvider>
|
||||
<AppRoutes />
|
||||
</ConfirmProvider>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
const BASE = import.meta.env.VITE_API_BASE_URL || '';
|
||||
|
||||
/** 네트워크 에러 메시지를 한국어로 변환 */
|
||||
function localizeError(message) {
|
||||
if (typeof message !== 'string') return message;
|
||||
if (message.includes('Failed to fetch')) return '서버에 연결할 수 없습니다';
|
||||
if (message.includes('NetworkError')) return '네트워크에 연결할 수 없습니다';
|
||||
if (message.includes('AbortError') || message === 'The user aborted a request.') return '요청 시간이 초과되었습니다';
|
||||
return message;
|
||||
}
|
||||
|
||||
// 동시 401 발생 시 refresh를 한 번만 실행하기 위한 Promise 공유
|
||||
let refreshingPromise = null;
|
||||
|
||||
@@ -26,19 +35,34 @@ export async function tryRefresh() {
|
||||
}
|
||||
|
||||
async function doFetch(path, options, token) {
|
||||
const headers = { 'Content-Type': 'application/json', ...options.headers };
|
||||
const headers = { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...options.headers };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
return fetch(BASE + path, { ...options, headers, credentials: 'include' });
|
||||
}
|
||||
|
||||
/** 에러 코드별 기본 한국어 메시지 */
|
||||
const ERROR_MESSAGES = {
|
||||
bad_request: '잘못된 요청입니다',
|
||||
unauthorized: '로그인이 필요합니다',
|
||||
forbidden: '권한이 없습니다',
|
||||
not_found: '요청한 리소스를 찾을 수 없습니다',
|
||||
conflict: '이미 존재하는 항목입니다',
|
||||
tx_failed: '트랜잭션 처리에 실패했습니다',
|
||||
rate_limited: '요청이 너무 많습니다. 잠시 후 다시 시도해주세요',
|
||||
internal_error: '서버 오류가 발생했습니다',
|
||||
};
|
||||
|
||||
async function parseError(res) {
|
||||
let message = res.statusText;
|
||||
let code;
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body.error) message = body.error;
|
||||
code = body.error;
|
||||
message = body.message || ERROR_MESSAGES[code] || message;
|
||||
} catch { /* 응답 바디 파싱 실패 시 statusText 사용 */ }
|
||||
const err = new Error(message);
|
||||
err.status = res.status;
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
@@ -60,6 +84,7 @@ export async function apiFetch(path, options = {}, _retryCount = 0) {
|
||||
await delay(1000 * (_retryCount + 1));
|
||||
return apiFetch(path, options, _retryCount + 1);
|
||||
}
|
||||
e.message = localizeError(e.message);
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -115,6 +140,7 @@ export function apiUpload(path, file, onProgress) {
|
||||
xhr.withCredentials = true;
|
||||
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`);
|
||||
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable && onProgress) {
|
||||
@@ -123,7 +149,7 @@ export function apiUpload(path, file, onProgress) {
|
||||
};
|
||||
|
||||
xhr.onload = () => resolve(xhr);
|
||||
xhr.onerror = () => reject(new Error('네트워크 오류가 발생했습니다.'));
|
||||
xhr.onerror = () => reject(new Error('서버에 연결할 수 없습니다'));
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export default function DownloadSection() {
|
||||
// JWT를 URL에 직접 노출하지 않고, 일회용 티켓을 발급받아 전달
|
||||
try {
|
||||
const ticket = await createLaunchTicket();
|
||||
window.location.href = 'a301://launch?ticket=' + encodeURIComponent(ticket);
|
||||
window.location.href = 'a301://launch?token=' + encodeURIComponent(ticket);
|
||||
} catch {
|
||||
// 티켓 발급 실패 시 로그인 유도
|
||||
navigate('/login');
|
||||
|
||||
99
src/components/ErrorBoundary.css
Normal file
99
src/components/ErrorBoundary.css
Normal file
@@ -0,0 +1,99 @@
|
||||
.error-boundary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 2rem;
|
||||
background-color: #2E2C2F;
|
||||
}
|
||||
|
||||
.error-boundary-card {
|
||||
text-align: center;
|
||||
max-width: 440px;
|
||||
padding: 40px 32px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.error-boundary-icon {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
margin: 0 auto 20px;
|
||||
border-radius: 50%;
|
||||
background: rgba(229, 115, 115, 0.12);
|
||||
color: rgba(229, 115, 115, 0.9);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 56px;
|
||||
}
|
||||
|
||||
.error-boundary-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.error-boundary-desc {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
.error-boundary-detail {
|
||||
padding: 12px 16px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 24px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.error-boundary-type {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: rgba(229, 115, 115, 0.8);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.error-boundary-message {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin: 6px 0 0 0;
|
||||
word-break: break-word;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.error-boundary-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.error-boundary-btn {
|
||||
padding: 10px 24px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.error-boundary-btn:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.error-boundary-btn-primary {
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.error-boundary-btn-secondary {
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
@@ -1,29 +1,52 @@
|
||||
import { Component } from 'react';
|
||||
import './ErrorBoundary.css';
|
||||
|
||||
export default class ErrorBoundary extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
static getDerivedStateFromError(error) {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error, errorInfo) {
|
||||
console.error('Uncaught error:', error, errorInfo);
|
||||
}
|
||||
|
||||
handleRetry = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
const { error } = this.state;
|
||||
const errorType = error?.name || 'Error';
|
||||
const errorMessage = error?.message || '알 수 없는 오류가 발생했습니다.';
|
||||
|
||||
return (
|
||||
<div style={{ padding: '2rem', textAlign: 'center', color: '#ccc' }}>
|
||||
<h2>문제가 발생했습니다</h2>
|
||||
<p>페이지를 새로고침하거나 잠시 후 다시 시도해주세요.</p>
|
||||
<button onClick={() => window.location.reload()} style={{ marginTop: '1rem', padding: '0.5rem 1rem', cursor: 'pointer' }}>
|
||||
<div className="error-boundary">
|
||||
<div className="error-boundary-card">
|
||||
<div className="error-boundary-icon">!</div>
|
||||
<h2 className="error-boundary-title">문제가 발생했습니다</h2>
|
||||
<p className="error-boundary-desc">
|
||||
예기치 않은 오류로 페이지를 표시할 수 없습니다.
|
||||
</p>
|
||||
<div className="error-boundary-detail">
|
||||
<span className="error-boundary-type">{errorType}</span>
|
||||
<p className="error-boundary-message">{errorMessage}</p>
|
||||
</div>
|
||||
<div className="error-boundary-actions">
|
||||
<button className="error-boundary-btn error-boundary-btn-primary" onClick={this.handleRetry}>
|
||||
다시 시도
|
||||
</button>
|
||||
<button className="error-boundary-btn error-boundary-btn-secondary" onClick={() => window.location.reload()}>
|
||||
새로고침
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
.admin-section {
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.admin-section-title {
|
||||
.sectionTitle {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
@@ -14,7 +14,7 @@
|
||||
}
|
||||
|
||||
/* Form */
|
||||
.admin-form {
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
@@ -24,18 +24,18 @@
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.admin-field {
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.admin-label {
|
||||
.label {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.admin-input {
|
||||
.input {
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
@@ -46,11 +46,11 @@
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.admin-input:focus {
|
||||
.input:focus {
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.admin-textarea {
|
||||
.textarea {
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
@@ -63,24 +63,24 @@
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.admin-textarea:focus {
|
||||
.textarea:focus {
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.admin-error {
|
||||
.error {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(229, 115, 115, 0.9);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-form-actions {
|
||||
.formActions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn-admin-primary {
|
||||
.btnPrimary {
|
||||
padding: 10px 24px;
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
@@ -92,10 +92,10 @@
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-primary:hover { opacity: 0.9; }
|
||||
.btn-admin-primary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.btnPrimary:hover { opacity: 0.9; }
|
||||
.btnPrimary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.btn-admin-secondary {
|
||||
.btnSecondary {
|
||||
padding: 10px 20px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
@@ -106,12 +106,12 @@
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-secondary:hover {
|
||||
.btnSecondary:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
/* List */
|
||||
.admin-list {
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
@@ -120,7 +120,7 @@
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.admin-list-item {
|
||||
.listItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
@@ -130,14 +130,14 @@
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.admin-list-info {
|
||||
.listInfo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-list-title {
|
||||
.listTitle {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
white-space: nowrap;
|
||||
@@ -145,19 +145,19 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.admin-list-date {
|
||||
.listDate {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.admin-list-actions {
|
||||
.listActions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-admin-edit {
|
||||
.btnEdit {
|
||||
padding: 6px 14px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.8);
|
||||
@@ -168,11 +168,11 @@
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-edit:hover {
|
||||
.btnEdit:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.btn-admin-delete {
|
||||
.btnDelete {
|
||||
padding: 6px 14px;
|
||||
background: transparent;
|
||||
color: rgba(229, 115, 115, 0.8);
|
||||
@@ -183,25 +183,25 @@
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-delete:hover {
|
||||
.btnDelete:hover {
|
||||
background: rgba(229, 115, 115, 0.08);
|
||||
}
|
||||
|
||||
/* Deploy block */
|
||||
.admin-deploy-block {
|
||||
.deployBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-deploy-header {
|
||||
.deployHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.admin-deploy-label {
|
||||
.deployLabel {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
@@ -210,32 +210,32 @@
|
||||
}
|
||||
|
||||
/* File input */
|
||||
.admin-input-file {
|
||||
.inputFile {
|
||||
padding: 8px 0;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin-input-file:disabled {
|
||||
.inputFile:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Field hint */
|
||||
.admin-field-hint {
|
||||
.fieldHint {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
/* Upload progress */
|
||||
.admin-upload-progress {
|
||||
.uploadProgress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-upload-bar {
|
||||
.uploadBar {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
background: #BACDB0;
|
||||
@@ -243,7 +243,7 @@
|
||||
transition: width 0.2s;
|
||||
}
|
||||
|
||||
.admin-upload-pct {
|
||||
.uploadPct {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
min-width: 36px;
|
||||
@@ -251,7 +251,7 @@
|
||||
}
|
||||
|
||||
/* Current build info */
|
||||
.admin-current-build {
|
||||
.currentBuild {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
@@ -261,13 +261,13 @@
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.admin-meta-row {
|
||||
.metaRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.admin-meta-item {
|
||||
.metaItem {
|
||||
font-size: 0.78rem;
|
||||
color: rgba(186, 205, 176, 0.8);
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
@@ -276,32 +276,102 @@
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
}
|
||||
|
||||
.admin-meta-hash {
|
||||
.metaHash {
|
||||
composes: metaItem;
|
||||
font-family: monospace;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* Role badge */
|
||||
.admin-list-empty {
|
||||
.listEmpty {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
padding: 12px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-role-badge {
|
||||
.roleBadge {
|
||||
font-size: 0.7rem;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.admin-role-badge.admin {
|
||||
.roleBadgeAdmin {
|
||||
composes: roleBadge;
|
||||
background: rgba(186, 205, 176, 0.15);
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.admin-role-badge.user {
|
||||
.roleBadgeUser {
|
||||
composes: roleBadge;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
.errorBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
padding: 12px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.form {
|
||||
padding: 16px 12px;
|
||||
}
|
||||
|
||||
.input,
|
||||
.textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.listItem {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.listInfo {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.listActions {
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.formActions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.formActions button {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.btnPrimary,
|
||||
.btnSecondary,
|
||||
.btnEdit,
|
||||
.btnDelete {
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.deployHeader {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
// TODO: Add tests for CRUD operations (create, update, delete announcements)
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getAnnouncements, createAnnouncement, updateAnnouncement, deleteAnnouncement } from '../../api/announcements';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import './AdminCommon.css';
|
||||
import { useConfirm } from '../confirm/useConfirm';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function AnnouncementAdmin() {
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [list, setList] = useState([]);
|
||||
const [form, setForm] = useState({ title: '', content: '' });
|
||||
const [editingId, setEditingId] = useState(null);
|
||||
@@ -58,8 +59,7 @@ export default function AnnouncementAdmin() {
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI
|
||||
if (!confirm('삭제하시겠습니까?')) return;
|
||||
if (!(await confirm('삭제하시겠습니까?'))) return;
|
||||
try {
|
||||
await deleteAnnouncement(id);
|
||||
toast.success('공지사항이 삭제되었습니다.');
|
||||
@@ -77,30 +77,30 @@ export default function AnnouncementAdmin() {
|
||||
|
||||
if (fetchLoading) {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">공지사항 관리</h2>
|
||||
<p className="admin-loading">불러오는 중...</p>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
<p className={s.loading}>불러오는 중...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (fetchError) {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">공지사항 관리</h2>
|
||||
<p className="admin-error">{fetchError}</p>
|
||||
<button className="btn-admin-secondary" onClick={load}>다시 시도</button>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
<p className={s.error}>{fetchError}</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">공지사항 관리</h2>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
|
||||
<form className="admin-form" onSubmit={handleSubmit}>
|
||||
<form className={s.form} onSubmit={handleSubmit}>
|
||||
<input
|
||||
className="admin-input"
|
||||
className={s.input}
|
||||
placeholder="제목"
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({ ...form, title: e.target.value })}
|
||||
@@ -108,7 +108,7 @@ export default function AnnouncementAdmin() {
|
||||
aria-label="공지사항 제목"
|
||||
/>
|
||||
<textarea
|
||||
className="admin-textarea"
|
||||
className={s.textarea}
|
||||
placeholder="내용"
|
||||
rows={4}
|
||||
value={form.content}
|
||||
@@ -116,29 +116,29 @@ export default function AnnouncementAdmin() {
|
||||
maxLength={10000}
|
||||
aria-label="공지사항 내용"
|
||||
/>
|
||||
{error && <p className="admin-error">{error}</p>}
|
||||
<div className="admin-form-actions">
|
||||
<button className="btn-admin-primary" type="submit" disabled={loading}>
|
||||
{error && <p className={s.error}>{error}</p>}
|
||||
<div className={s.formActions}>
|
||||
<button className={s.btnPrimary} type="submit" disabled={loading}>
|
||||
{editingId ? '수정 완료' : '공지 등록'}
|
||||
</button>
|
||||
{editingId && (
|
||||
<button className="btn-admin-secondary" type="button" onClick={handleCancel}>
|
||||
<button className={s.btnSecondary} type="button" onClick={handleCancel}>
|
||||
취소
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<ul className="admin-list">
|
||||
<ul className={s.list}>
|
||||
{list.map((item) => (
|
||||
<li key={item.id} className="admin-list-item">
|
||||
<div className="admin-list-info">
|
||||
<span className="admin-list-title">{item.title}</span>
|
||||
<span className="admin-list-date">{item.createdAt?.slice(0, 10)}</span>
|
||||
<li key={item.id} className={s.listItem}>
|
||||
<div className={s.listInfo}>
|
||||
<span className={s.listTitle}>{item.title}</span>
|
||||
<span className={s.listDate}>{item.createdAt?.slice(0, 10)}</span>
|
||||
</div>
|
||||
<div className="admin-list-actions">
|
||||
<button className="btn-admin-edit" onClick={() => handleEdit(item)}>수정</button>
|
||||
<button className="btn-admin-delete" onClick={() => handleDelete(item.id)}>삭제</button>
|
||||
<div className={s.listActions}>
|
||||
<button className={s.btnEdit} onClick={() => handleEdit(item)}>수정</button>
|
||||
<button className={s.btnDelete} onClick={() => handleDelete(item.id)}>삭제</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
|
||||
187
src/components/admin/AnnouncementAdmin.test.jsx
Normal file
187
src/components/admin/AnnouncementAdmin.test.jsx
Normal file
@@ -0,0 +1,187 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import AnnouncementAdmin from './AnnouncementAdmin';
|
||||
|
||||
// Mock APIs
|
||||
const mockGetAnnouncements = vi.fn();
|
||||
const mockCreateAnnouncement = vi.fn();
|
||||
const mockUpdateAnnouncement = vi.fn();
|
||||
const mockDeleteAnnouncement = vi.fn();
|
||||
vi.mock('../../api/announcements', () => ({
|
||||
getAnnouncements: (...args) => mockGetAnnouncements(...args),
|
||||
createAnnouncement: (...args) => mockCreateAnnouncement(...args),
|
||||
updateAnnouncement: (...args) => mockUpdateAnnouncement(...args),
|
||||
deleteAnnouncement: (...args) => mockDeleteAnnouncement(...args),
|
||||
}));
|
||||
|
||||
// Mock toast
|
||||
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
|
||||
vi.mock('../toast/useToast', () => ({
|
||||
useToast: () => mockToast,
|
||||
}));
|
||||
|
||||
// Mock confirm — resolves true by default
|
||||
let mockConfirmResult = true;
|
||||
vi.mock('../confirm/useConfirm', () => ({
|
||||
useConfirm: () => () => Promise.resolve(mockConfirmResult),
|
||||
}));
|
||||
|
||||
const SAMPLE_LIST = [
|
||||
{ id: 1, title: '점검 안내', content: '서버 점검합니다.', createdAt: '2026-03-10T00:00:00Z' },
|
||||
{ id: 2, title: '업데이트', content: '새 버전 출시.', createdAt: '2026-03-12T00:00:00Z' },
|
||||
];
|
||||
|
||||
describe('AnnouncementAdmin', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockConfirmResult = true;
|
||||
mockGetAnnouncements.mockResolvedValue(SAMPLE_LIST);
|
||||
});
|
||||
|
||||
it('renders announcements after loading', async () => {
|
||||
render(<AnnouncementAdmin />);
|
||||
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
|
||||
expect(await screen.findByText('점검 안내')).toBeInTheDocument();
|
||||
expect(screen.getByText('업데이트')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when fetch fails', async () => {
|
||||
mockGetAnnouncements.mockRejectedValueOnce(new Error('fail'));
|
||||
render(<AnnouncementAdmin />);
|
||||
expect(await screen.findByText('공지사항을 불러오지 못했습니다.')).toBeInTheDocument();
|
||||
expect(screen.getByText('다시 시도')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('retries loading when "다시 시도" is clicked', async () => {
|
||||
mockGetAnnouncements.mockRejectedValueOnce(new Error('fail'));
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('다시 시도');
|
||||
|
||||
mockGetAnnouncements.mockResolvedValueOnce(SAMPLE_LIST);
|
||||
fireEvent.click(screen.getByText('다시 시도'));
|
||||
expect(await screen.findByText('점검 안내')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a new announcement', async () => {
|
||||
mockCreateAnnouncement.mockResolvedValueOnce({});
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '새 공지' } });
|
||||
fireEvent.change(screen.getByPlaceholderText('내용'), { target: { value: '새 내용입니다.' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockCreateAnnouncement).toHaveBeenCalledWith('새 공지', '새 내용입니다.');
|
||||
});
|
||||
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 등록되었습니다.');
|
||||
});
|
||||
|
||||
it('shows validation error when fields are empty', async () => {
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
|
||||
expect(await screen.findByText('제목과 내용을 모두 입력해주세요.')).toBeInTheDocument();
|
||||
expect(mockCreateAnnouncement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows toast on create failure', async () => {
|
||||
mockCreateAnnouncement.mockRejectedValueOnce(new Error('서버 오류'));
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '제목' } });
|
||||
fireEvent.change(screen.getByPlaceholderText('내용'), { target: { value: '내용' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith('서버 오류');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('populates form on edit and submits update', async () => {
|
||||
mockUpdateAnnouncement.mockResolvedValueOnce({});
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
// Click edit on first item
|
||||
const editButtons = screen.getAllByText('수정');
|
||||
fireEvent.click(editButtons[0]);
|
||||
|
||||
// Form should be populated
|
||||
expect(screen.getByPlaceholderText('제목')).toHaveValue('점검 안내');
|
||||
expect(screen.getByPlaceholderText('내용')).toHaveValue('서버 점검합니다.');
|
||||
expect(screen.getByRole('button', { name: '수정 완료' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '취소' })).toBeInTheDocument();
|
||||
|
||||
// Modify and submit
|
||||
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '수정된 제목' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '수정 완료' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateAnnouncement).toHaveBeenCalledWith(1, '수정된 제목', '서버 점검합니다.');
|
||||
});
|
||||
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 수정되었습니다.');
|
||||
});
|
||||
|
||||
it('cancels editing and clears form', async () => {
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
const editButtons = screen.getAllByText('수정');
|
||||
fireEvent.click(editButtons[0]);
|
||||
expect(screen.getByPlaceholderText('제목')).toHaveValue('점검 안내');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '취소' }));
|
||||
expect(screen.getByPlaceholderText('제목')).toHaveValue('');
|
||||
expect(screen.getByPlaceholderText('내용')).toHaveValue('');
|
||||
expect(screen.getByRole('button', { name: '공지 등록' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes an announcement when confirmed', async () => {
|
||||
mockDeleteAnnouncement.mockResolvedValueOnce({});
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteAnnouncement).toHaveBeenCalledWith(1);
|
||||
});
|
||||
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 삭제되었습니다.');
|
||||
});
|
||||
|
||||
it('does not delete when confirm is cancelled', async () => {
|
||||
mockConfirmResult = false;
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteAnnouncement).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast on delete failure', async () => {
|
||||
mockDeleteAnnouncement.mockRejectedValueOnce(new Error('삭제 실패'));
|
||||
render(<AnnouncementAdmin />);
|
||||
await screen.findByText('점검 안내');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith('삭제 실패');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,11 @@
|
||||
// TODO: Add tests for CRUD operations (load download info, upload launcher, upload game)
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getDownloadInfo } from '../../api/download';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import UploadForm from './UploadForm';
|
||||
import './AdminCommon.css';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function DownloadAdmin() {
|
||||
const toast = useToast();
|
||||
const [info, setInfo] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
@@ -20,6 +21,7 @@ export default function DownloadAdmin() {
|
||||
.catch((err) => {
|
||||
console.error('다운로드 정보 로드 실패:', err);
|
||||
setLoadError('배포 정보를 불러올 수 없습니다.');
|
||||
toast.error('배포 정보를 불러올 수 없습니다.');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
@@ -29,34 +31,34 @@ export default function DownloadAdmin() {
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">게임 배포 관리</h2>
|
||||
<p className="admin-loading">불러오는 중...</p>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
<p className={s.loading}>불러오는 중...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">게임 배포 관리</h2>
|
||||
<p className="admin-error">{loadError}</p>
|
||||
<button className="btn-admin-secondary" onClick={load}>다시 시도</button>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
<p className={s.error}>{loadError}</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">게임 배포 관리</h2>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
|
||||
{/* 런처 섹션 */}
|
||||
<div className="admin-deploy-block">
|
||||
<div className="admin-deploy-header">
|
||||
<span className="admin-deploy-label">런처</span>
|
||||
<div className={s.deployBlock}>
|
||||
<div className={s.deployHeader}>
|
||||
<span className={s.deployLabel}>런처</span>
|
||||
{info?.launcherUrl && (
|
||||
<div className="admin-meta-row">
|
||||
{info.launcherSize && <span className="admin-meta-item">{info.launcherSize}</span>}
|
||||
<div className={s.metaRow}>
|
||||
{info.launcherSize && <span className={s.metaItem}>{info.launcherSize}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -70,16 +72,16 @@ export default function DownloadAdmin() {
|
||||
</div>
|
||||
|
||||
{/* 게임 섹션 */}
|
||||
<div className="admin-deploy-block">
|
||||
<div className="admin-deploy-header">
|
||||
<span className="admin-deploy-label">게임</span>
|
||||
<div className={s.deployBlock}>
|
||||
<div className={s.deployHeader}>
|
||||
<span className={s.deployLabel}>게임</span>
|
||||
{info?.url && (
|
||||
<div className="admin-meta-row">
|
||||
{info.version && <span className="admin-meta-item">{info.version}</span>}
|
||||
{info.fileName && <span className="admin-meta-item">{info.fileName}</span>}
|
||||
{info.fileSize && <span className="admin-meta-item">{info.fileSize}</span>}
|
||||
<div className={s.metaRow}>
|
||||
{info.version && <span className={s.metaItem}>{info.version}</span>}
|
||||
{info.fileName && <span className={s.metaItem}>{info.fileName}</span>}
|
||||
{info.fileSize && <span className={s.metaItem}>{info.fileSize}</span>}
|
||||
{info.fileHash && (
|
||||
<span className="admin-meta-item admin-meta-hash" title={info.fileHash}>
|
||||
<span className={s.metaHash} title={info.fileHash}>
|
||||
SHA256: {info.fileHash.slice(0, 12)}...
|
||||
</span>
|
||||
)}
|
||||
|
||||
85
src/components/admin/DownloadAdmin.test.jsx
Normal file
85
src/components/admin/DownloadAdmin.test.jsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import DownloadAdmin from './DownloadAdmin';
|
||||
|
||||
// Mock APIs
|
||||
const mockGetDownloadInfo = vi.fn();
|
||||
vi.mock('../../api/download', () => ({
|
||||
getDownloadInfo: (...args) => mockGetDownloadInfo(...args),
|
||||
}));
|
||||
|
||||
// Mock apiUpload
|
||||
const mockApiUpload = vi.fn();
|
||||
vi.mock('../../api/client', () => ({
|
||||
apiUpload: (...args) => mockApiUpload(...args),
|
||||
}));
|
||||
|
||||
// Mock toast
|
||||
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
|
||||
vi.mock('../toast/useToast', () => ({
|
||||
useToast: () => mockToast,
|
||||
}));
|
||||
|
||||
const SAMPLE_INFO = {
|
||||
url: 'https://example.com/game.zip',
|
||||
launcherUrl: 'https://example.com/launcher.exe',
|
||||
version: 'v1.2.0',
|
||||
fileName: 'game.zip',
|
||||
fileSize: '512 MB',
|
||||
fileHash: 'abc123def456abc123def456abc123def456abc123def456abc123def456abcd',
|
||||
launcherSize: '8 MB',
|
||||
};
|
||||
|
||||
describe('DownloadAdmin', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockGetDownloadInfo.mockResolvedValue(SAMPLE_INFO);
|
||||
});
|
||||
|
||||
it('shows loading state then renders download info', async () => {
|
||||
render(<DownloadAdmin />);
|
||||
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
|
||||
expect(await screen.findByText('v1.2.0')).toBeInTheDocument();
|
||||
expect(screen.getByText('512 MB')).toBeInTheDocument();
|
||||
expect(screen.getByText('game.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when fetch fails', async () => {
|
||||
mockGetDownloadInfo.mockRejectedValueOnce(new Error('fail'));
|
||||
render(<DownloadAdmin />);
|
||||
expect(await screen.findByText('배포 정보를 불러올 수 없습니다.')).toBeInTheDocument();
|
||||
expect(screen.getByText('다시 시도')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('retries loading on "다시 시도" click', async () => {
|
||||
mockGetDownloadInfo.mockRejectedValueOnce(new Error('fail'));
|
||||
render(<DownloadAdmin />);
|
||||
await screen.findByText('다시 시도');
|
||||
|
||||
mockGetDownloadInfo.mockResolvedValueOnce(SAMPLE_INFO);
|
||||
fireEvent.click(screen.getByText('다시 시도'));
|
||||
expect(await screen.findByText('v1.2.0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders launcher and game upload sections', async () => {
|
||||
render(<DownloadAdmin />);
|
||||
await screen.findByText('v1.2.0');
|
||||
|
||||
expect(screen.getByText('launcher.exe')).toBeInTheDocument();
|
||||
expect(screen.getByText(/게임 파일/)).toBeInTheDocument();
|
||||
// Two upload buttons (both disabled without file selection)
|
||||
const uploadButtons = screen.getAllByRole('button', { name: '업로드' });
|
||||
expect(uploadButtons).toHaveLength(2);
|
||||
uploadButtons.forEach((btn) => expect(btn).toBeDisabled());
|
||||
});
|
||||
|
||||
it('displays launcher size', async () => {
|
||||
render(<DownloadAdmin />);
|
||||
await screen.findByText('8 MB');
|
||||
});
|
||||
|
||||
it('displays SHA256 hash prefix', async () => {
|
||||
render(<DownloadAdmin />);
|
||||
expect(await screen.findByText(/SHA256: abc123def456/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState, useRef } from 'react';
|
||||
import { apiUpload } from '../../api/client';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function UploadForm({ title, hint, accept, endpoint, onSuccess }) {
|
||||
const toast = useToast();
|
||||
const [file, setFile] = useState(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
@@ -27,15 +30,32 @@ export default function UploadForm({ title, hint, accept, endpoint, onSuccess })
|
||||
const { status, body } = await apiUpload(path, file, (p) => setProgress(p));
|
||||
if (status >= 200 && status < 300) {
|
||||
onSuccess(body);
|
||||
toast.success('업로드가 완료되었습니다.');
|
||||
setFile(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
setProgress(0);
|
||||
} else if (status === 413) {
|
||||
const msg = '파일 크기가 너무 큽니다. 더 작은 파일을 선택해주세요.';
|
||||
setError(msg);
|
||||
toast.error(msg);
|
||||
} else if (status === 409) {
|
||||
const msg = '동일한 파일이 이미 존재합니다.';
|
||||
setError(msg);
|
||||
toast.error(msg);
|
||||
} else if (status >= 500) {
|
||||
const msg = '서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
|
||||
setError(msg);
|
||||
toast.error(msg);
|
||||
} else {
|
||||
setError(body.error || '업로드에 실패했습니다.');
|
||||
const msg = body.error || '업로드에 실패했습니다.';
|
||||
setError(msg);
|
||||
toast.error(msg);
|
||||
setProgress(0);
|
||||
}
|
||||
} catch {
|
||||
setError('네트워크 오류가 발생했습니다.');
|
||||
const msg = '네트워크 오류가 발생했습니다.';
|
||||
setError(msg);
|
||||
toast.error(msg);
|
||||
setProgress(0);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
@@ -43,31 +63,31 @@ export default function UploadForm({ title, hint, accept, endpoint, onSuccess })
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="admin-form" onSubmit={handleUpload}>
|
||||
<div className="admin-field">
|
||||
<label className="admin-label">{title}</label>
|
||||
<form className={s.form} onSubmit={handleUpload}>
|
||||
<div className={s.field}>
|
||||
<label className={s.label}>{title}</label>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="admin-input-file"
|
||||
className={s.inputFile}
|
||||
onChange={handleFileChange}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<span className="admin-field-hint">{hint}</span>
|
||||
<span className={s.fieldHint}>{hint}</span>
|
||||
</div>
|
||||
|
||||
{uploading && (
|
||||
<div className="admin-upload-progress">
|
||||
<div className="admin-upload-bar" style={{ width: `${progress}%` }} />
|
||||
<span className="admin-upload-pct">{progress}%</span>
|
||||
<div className={s.uploadProgress}>
|
||||
<div className={s.uploadBar} style={{ width: `${progress}%` }} />
|
||||
<span className={s.uploadPct}>{progress}%</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="admin-error">{error}</p>}
|
||||
{error && <p className={s.error}>{error}</p>}
|
||||
|
||||
<div className="admin-form-actions">
|
||||
<button className="btn-admin-primary" type="submit" disabled={uploading || !file}>
|
||||
<div className={s.formActions}>
|
||||
<button className={s.btnPrimary} type="submit" disabled={uploading || !file}>
|
||||
{uploading ? `업로드 중... (${progress}%)` : '업로드'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// TODO: Add tests for CRUD operations (list users, update role, delete user)
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getUsers, updateUserRole, deleteUser } from '../../api/users';
|
||||
import { useAuth } from '../../context/useAuth';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import './AdminCommon.css';
|
||||
import { useConfirm } from '../confirm/useConfirm';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function UserAdmin() {
|
||||
const [users, setUsers] = useState([]);
|
||||
@@ -11,6 +11,7 @@ export default function UserAdmin() {
|
||||
const [fetchError, setFetchError] = useState(false);
|
||||
const { user: me } = useAuth();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const load = () => {
|
||||
setLoading(true);
|
||||
@@ -28,8 +29,7 @@ export default function UserAdmin() {
|
||||
|
||||
const handleRoleToggle = async (u) => {
|
||||
const newRole = u.role === 'admin' ? 'user' : 'admin';
|
||||
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI
|
||||
if (!confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`)) return;
|
||||
if (!(await confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`))) return;
|
||||
try {
|
||||
await updateUserRole(u.id, newRole);
|
||||
toast.success(`${u.username}의 권한이 ${newRole}로 변경되었습니다.`);
|
||||
@@ -40,8 +40,7 @@ export default function UserAdmin() {
|
||||
};
|
||||
|
||||
const handleDelete = async (u) => {
|
||||
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI
|
||||
if (!confirm(`${u.username} 계정을 삭제하시겠습니까?`)) return;
|
||||
if (!(await confirm(`${u.username} 계정을 삭제하시겠습니까?`))) return;
|
||||
try {
|
||||
await deleteUser(u.id);
|
||||
toast.success(`${u.username} 계정이 삭제되었습니다.`);
|
||||
@@ -52,29 +51,29 @@ export default function UserAdmin() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2 className="admin-section-title">유저 관리</h2>
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>유저 관리</h2>
|
||||
{fetchError && (
|
||||
<div className="admin-error-block">
|
||||
<p className="admin-error">유저 목록을 불러올 수 없습니다.</p>
|
||||
<button className="btn-admin-secondary" onClick={load}>다시 시도</button>
|
||||
<div className={s.errorBlock}>
|
||||
<p className={s.error}>유저 목록을 불러올 수 없습니다.</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
)}
|
||||
{loading && <p className="admin-list-empty">불러오는 중...</p>}
|
||||
{!loading && users.length === 0 && <p className="admin-list-empty">등록된 유저가 없습니다.</p>}
|
||||
<ul className="admin-list">
|
||||
{loading && <p className={s.listEmpty}>불러오는 중...</p>}
|
||||
{!loading && users.length === 0 && <p className={s.listEmpty}>등록된 유저가 없습니다.</p>}
|
||||
<ul className={s.list}>
|
||||
{users.map((u) => (
|
||||
<li key={u.id} className="admin-list-item">
|
||||
<div className="admin-list-info">
|
||||
<span className="admin-list-title">{u.username}</span>
|
||||
<span className={`admin-role-badge ${u.role}`}>{u.role}</span>
|
||||
<li key={u.id} className={s.listItem}>
|
||||
<div className={s.listInfo}>
|
||||
<span className={s.listTitle}>{u.username}</span>
|
||||
<span className={u.role === 'admin' ? s.roleBadgeAdmin : s.roleBadgeUser}>{u.role}</span>
|
||||
</div>
|
||||
{u.username !== me?.username && (
|
||||
<div className="admin-list-actions">
|
||||
<button className="btn-admin-edit" onClick={() => handleRoleToggle(u)}>
|
||||
<div className={s.listActions}>
|
||||
<button className={s.btnEdit} onClick={() => handleRoleToggle(u)}>
|
||||
{u.role === 'admin' ? '일반으로' : '관리자로'}
|
||||
</button>
|
||||
<button className="btn-admin-delete" onClick={() => handleDelete(u)}>삭제</button>
|
||||
<button className={s.btnDelete} onClick={() => handleDelete(u)}>삭제</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
|
||||
161
src/components/admin/UserAdmin.test.jsx
Normal file
161
src/components/admin/UserAdmin.test.jsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import UserAdmin from './UserAdmin';
|
||||
|
||||
// Mock APIs
|
||||
const mockGetUsers = vi.fn();
|
||||
const mockUpdateUserRole = vi.fn();
|
||||
const mockDeleteUser = vi.fn();
|
||||
vi.mock('../../api/users', () => ({
|
||||
getUsers: (...args) => mockGetUsers(...args),
|
||||
updateUserRole: (...args) => mockUpdateUserRole(...args),
|
||||
deleteUser: (...args) => mockDeleteUser(...args),
|
||||
}));
|
||||
|
||||
// Mock useAuth — current user is "admin1"
|
||||
vi.mock('../../context/useAuth', () => ({
|
||||
useAuth: () => ({ user: { username: 'admin1', role: 'admin' } }),
|
||||
}));
|
||||
|
||||
// Mock toast
|
||||
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
|
||||
vi.mock('../toast/useToast', () => ({
|
||||
useToast: () => mockToast,
|
||||
}));
|
||||
|
||||
// Mock confirm
|
||||
let mockConfirmResult = true;
|
||||
vi.mock('../confirm/useConfirm', () => ({
|
||||
useConfirm: () => () => Promise.resolve(mockConfirmResult),
|
||||
}));
|
||||
|
||||
const SAMPLE_USERS = [
|
||||
{ id: 1, username: 'admin1', role: 'admin' },
|
||||
{ id: 2, username: 'player1', role: 'user' },
|
||||
{ id: 3, username: 'player2', role: 'user' },
|
||||
];
|
||||
|
||||
describe('UserAdmin', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockConfirmResult = true;
|
||||
mockGetUsers.mockResolvedValue(SAMPLE_USERS);
|
||||
});
|
||||
|
||||
it('renders user list after loading', async () => {
|
||||
render(<UserAdmin />);
|
||||
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
|
||||
expect(await screen.findByText('admin1')).toBeInTheDocument();
|
||||
expect(screen.getByText('player1')).toBeInTheDocument();
|
||||
expect(screen.getByText('player2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when fetch fails', async () => {
|
||||
mockGetUsers.mockRejectedValueOnce(new Error('fail'));
|
||||
render(<UserAdmin />);
|
||||
expect(await screen.findByText('유저 목록을 불러올 수 없습니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show action buttons for the current user', async () => {
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('admin1');
|
||||
|
||||
// admin1 row should not have edit/delete buttons
|
||||
const listItems = screen.getAllByRole('listitem');
|
||||
const admin1Item = listItems.find((li) => li.textContent.includes('admin1'));
|
||||
expect(admin1Item.querySelector('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows role badge for each user', async () => {
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('admin1');
|
||||
|
||||
const badges = screen.getAllByText(/^(admin|user)$/);
|
||||
expect(badges.length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
describe('role toggle', () => {
|
||||
it('promotes a user to admin', async () => {
|
||||
mockUpdateUserRole.mockResolvedValueOnce({});
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
// player1 should have "관리자로" button
|
||||
const promoteButtons = screen.getAllByText('관리자로');
|
||||
fireEvent.click(promoteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateUserRole).toHaveBeenCalledWith(2, 'admin');
|
||||
});
|
||||
expect(mockToast.success).toHaveBeenCalledWith('player1의 권한이 admin로 변경되었습니다.');
|
||||
});
|
||||
|
||||
it('does not toggle role when confirm is cancelled', async () => {
|
||||
mockConfirmResult = false;
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
const promoteButtons = screen.getAllByText('관리자로');
|
||||
fireEvent.click(promoteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateUserRole).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast on role toggle failure', async () => {
|
||||
mockUpdateUserRole.mockRejectedValueOnce(new Error('권한 변경 실패'));
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
const promoteButtons = screen.getAllByText('관리자로');
|
||||
fireEvent.click(promoteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith('권한 변경 실패');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes a user when confirmed', async () => {
|
||||
mockDeleteUser.mockResolvedValueOnce({});
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteUser).toHaveBeenCalledWith(2);
|
||||
});
|
||||
expect(mockToast.success).toHaveBeenCalledWith('player1 계정이 삭제되었습니다.');
|
||||
});
|
||||
|
||||
it('does not delete when confirm is cancelled', async () => {
|
||||
mockConfirmResult = false;
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast on delete failure', async () => {
|
||||
mockDeleteUser.mockRejectedValueOnce(new Error('삭제 실패'));
|
||||
render(<UserAdmin />);
|
||||
await screen.findByText('player1');
|
||||
|
||||
const deleteButtons = screen.getAllByText('삭제');
|
||||
fireEvent.click(deleteButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast.error).toHaveBeenCalledWith('삭제 실패');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
76
src/components/confirm/Confirm.css
Normal file
76
src/components/confirm/Confirm.css
Normal file
@@ -0,0 +1,76 @@
|
||||
.confirm-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10001;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: confirm-fade-in 0.15s ease-out;
|
||||
}
|
||||
|
||||
.confirm-dialog {
|
||||
background: #3a3a3a;
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
min-width: 320px;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||
animation: confirm-scale-in 0.15s ease-out;
|
||||
}
|
||||
|
||||
.confirm-message {
|
||||
font-size: 0.95rem;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
line-height: 1.5;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
.confirm-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.confirm-btn {
|
||||
padding: 8px 20px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.confirm-btn:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.confirm-btn-cancel {
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
.confirm-btn-ok {
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@keyframes confirm-fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes confirm-scale-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
46
src/components/confirm/ConfirmProvider.jsx
Normal file
46
src/components/confirm/ConfirmProvider.jsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useState, useCallback, useMemo, useRef } from 'react';
|
||||
import { ConfirmContext } from './confirmContextValue';
|
||||
import './Confirm.css';
|
||||
|
||||
export function ConfirmProvider({ children }) {
|
||||
const [dialog, setDialog] = useState(null);
|
||||
const resolveRef = useRef(null);
|
||||
|
||||
const confirm = useCallback((message) => {
|
||||
return new Promise((resolve) => {
|
||||
resolveRef.current = resolve;
|
||||
setDialog({ message });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleConfirm = useCallback(() => {
|
||||
resolveRef.current?.(true);
|
||||
resolveRef.current = null;
|
||||
setDialog(null);
|
||||
}, []);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
resolveRef.current?.(false);
|
||||
resolveRef.current = null;
|
||||
setDialog(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => confirm, [confirm]);
|
||||
|
||||
return (
|
||||
<ConfirmContext.Provider value={value}>
|
||||
{children}
|
||||
{dialog && (
|
||||
<div className="confirm-overlay" onClick={handleCancel}>
|
||||
<div className="confirm-dialog" role="alertdialog" aria-modal="true" aria-label={dialog.message} onClick={(e) => e.stopPropagation()}>
|
||||
<p className="confirm-message">{dialog.message}</p>
|
||||
<div className="confirm-actions">
|
||||
<button className="confirm-btn confirm-btn-cancel" onClick={handleCancel}>취소</button>
|
||||
<button className="confirm-btn confirm-btn-ok" onClick={handleConfirm} autoFocus>확인</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ConfirmContext.Provider>
|
||||
);
|
||||
}
|
||||
3
src/components/confirm/confirmContextValue.js
Normal file
3
src/components/confirm/confirmContextValue.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const ConfirmContext = createContext(null);
|
||||
2
src/components/confirm/index.js
Normal file
2
src/components/confirm/index.js
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ConfirmProvider } from './ConfirmProvider';
|
||||
export { useConfirm } from './useConfirm';
|
||||
8
src/components/confirm/useConfirm.js
Normal file
8
src/components/confirm/useConfirm.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useContext } from 'react';
|
||||
import { ConfirmContext } from './confirmContextValue';
|
||||
|
||||
export function useConfirm() {
|
||||
const ctx = useContext(ConfirmContext);
|
||||
if (!ctx) throw new Error('useConfirm must be used within ConfirmProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -95,3 +95,43 @@
|
||||
margin: 0 auto;
|
||||
padding: 32px 24px 80px;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.admin-header {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.admin-header-left {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.admin-header-right {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.admin-tabs {
|
||||
padding: 12px 16px 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.admin-tabs::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-tab {
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
padding: 20px 12px 60px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,12 +165,65 @@
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
.password-strength {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(186, 205, 176, 0.7);
|
||||
margin: -12px 0 0;
|
||||
/* Validation feedback */
|
||||
.input-hint {
|
||||
font-size: 0.75rem;
|
||||
color: #888;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.password-strength.strength-weak {
|
||||
.input-hint-error {
|
||||
color: #e57373;
|
||||
}
|
||||
|
||||
.input-hint-success {
|
||||
color: #bacdb0;
|
||||
}
|
||||
|
||||
.input-group input.input-valid {
|
||||
border-color: #bacdb0 !important;
|
||||
}
|
||||
|
||||
.input-group input.input-invalid {
|
||||
border-color: #e57373 !important;
|
||||
}
|
||||
|
||||
.password-strength {
|
||||
font-size: 0.75rem;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.strength-weak {
|
||||
color: #e57373;
|
||||
}
|
||||
|
||||
.strength-medium {
|
||||
color: #ffd54f;
|
||||
}
|
||||
|
||||
.strength-strong {
|
||||
color: #bacdb0;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.login-panel {
|
||||
max-width: 100%;
|
||||
padding: 32px 20px;
|
||||
margin: 0 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.game-title {
|
||||
font-size: 2.2rem;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.btn-login,
|
||||
.btn-ssafy {
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,3 +124,43 @@
|
||||
margin: 0 auto;
|
||||
padding: 40px 24px 80px;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.home-header {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.home-user {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hero-banner {
|
||||
height: 180px;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
.hero-desc {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.home-main {
|
||||
padding: 24px 16px 60px;
|
||||
}
|
||||
|
||||
.btn-logout,
|
||||
.btn-admin-link,
|
||||
.btn-header-login {
|
||||
min-height: 44px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ export default function LoginPage() {
|
||||
placeholder="아이디를 입력하세요"
|
||||
autoComplete="username"
|
||||
maxLength={50}
|
||||
aria-describedby={error ? 'login-error' : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -64,11 +65,12 @@ export default function LoginPage() {
|
||||
placeholder="비밀번호를 입력하세요"
|
||||
autoComplete="current-password"
|
||||
maxLength={72}
|
||||
aria-describedby={error ? 'login-error' : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{justRegistered && <p className="login-success">회원가입이 완료되었습니다. 로그인해주세요.</p>}
|
||||
{error && <p className="login-error" role="alert">{error}</p>}
|
||||
{error && <p id="login-error" className="login-error" role="alert">{error}</p>}
|
||||
|
||||
<button type="submit" className="btn-login" disabled={loading}>
|
||||
{loading ? '로그인 중...' : '로그인'}
|
||||
@@ -85,6 +87,9 @@ export default function LoginPage() {
|
||||
onClick={async () => {
|
||||
try {
|
||||
const data = await getSSAFYLoginURL();
|
||||
if (!data.url || !data.url.startsWith('https://')) {
|
||||
throw new Error('유효하지 않은 로그인 URL입니다.');
|
||||
}
|
||||
window.location.href = data.url;
|
||||
} catch {
|
||||
setError('SSAFY 로그인 URL을 가져올 수 없습니다.');
|
||||
|
||||
@@ -3,29 +3,31 @@ import { useNavigate, Link } from 'react-router-dom';
|
||||
import { register } from '../api/auth';
|
||||
import './AuthPage.css';
|
||||
|
||||
const USERNAME_REGEX = /^[a-z0-9_-]{3,50}$/;
|
||||
|
||||
export default function RegisterPage() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [usernameTouched, setUsernameTouched] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const isUsernameValid = USERNAME_REGEX.test(username);
|
||||
const showUsernameError = usernameTouched && username.length > 0 && !isUsernameValid;
|
||||
const showUsernameValid = usernameTouched && username.length > 0 && isUsernameValid;
|
||||
|
||||
const getPasswordStrength = (pw) => {
|
||||
if (pw.length === 0) return '';
|
||||
if (pw.length < 6) return '비밀번호는 6자 이상이어야 합니다.';
|
||||
let strength = 0;
|
||||
if (/[a-z]/.test(pw)) strength++;
|
||||
if (/[A-Z]/.test(pw)) strength++;
|
||||
if (/[0-9]/.test(pw)) strength++;
|
||||
if (/[^a-zA-Z0-9]/.test(pw)) strength++;
|
||||
if (strength <= 1) return '약함';
|
||||
if (strength <= 2) return '보통';
|
||||
return '강함';
|
||||
if (pw.length === 0) return { label: '', level: '' };
|
||||
if (pw.length < 6) return { label: '약함', level: 'weak' };
|
||||
if (pw.length < 10) return { label: '중간', level: 'medium' };
|
||||
return { label: '강함', level: 'strong' };
|
||||
};
|
||||
|
||||
const passwordStrength = getPasswordStrength(password);
|
||||
const isPasswordWeak = password.length > 0 && password.length < 6;
|
||||
const confirmMismatch = confirm.length > 0 && password !== confirm;
|
||||
const confirmMatch = confirm.length > 0 && password === confirm;
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
@@ -80,10 +82,17 @@ export default function RegisterPage() {
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
onBlur={() => setUsernameTouched(true)}
|
||||
placeholder="아이디를 입력하세요"
|
||||
autoComplete="username"
|
||||
maxLength={50}
|
||||
className={showUsernameValid ? 'input-valid' : showUsernameError ? 'input-invalid' : ''}
|
||||
aria-describedby="username-hint"
|
||||
/>
|
||||
<span id="username-hint" className={`input-hint ${showUsernameError ? 'input-hint-error' : ''}`}>
|
||||
{showUsernameError ? '3~50자 영문 소문자, 숫자, _, -만 가능합니다' : '3~50자 영문 소문자, 숫자, _, -만 가능'}
|
||||
{showUsernameValid && ' \u2713'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
@@ -96,14 +105,14 @@ export default function RegisterPage() {
|
||||
placeholder="6자 이상 입력하세요"
|
||||
autoComplete="new-password"
|
||||
maxLength={72}
|
||||
aria-describedby="password-strength"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{passwordStrength && (
|
||||
<p className={`password-strength ${isPasswordWeak ? 'strength-weak' : ''}`}>
|
||||
강도: {passwordStrength}
|
||||
</p>
|
||||
{passwordStrength.label && (
|
||||
<span id="password-strength" className={`password-strength strength-${passwordStrength.level}`}>
|
||||
강도: {passwordStrength.label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label htmlFor="confirm">비밀번호 확인</label>
|
||||
@@ -115,7 +124,15 @@ export default function RegisterPage() {
|
||||
placeholder="비밀번호를 다시 입력하세요"
|
||||
autoComplete="new-password"
|
||||
maxLength={72}
|
||||
className={confirmMatch ? 'input-valid' : confirmMismatch ? 'input-invalid' : ''}
|
||||
aria-describedby="confirm-hint"
|
||||
/>
|
||||
{confirmMismatch && (
|
||||
<span id="confirm-hint" className="input-hint input-hint-error">비밀번호가 일치하지 않습니다</span>
|
||||
)}
|
||||
{confirmMatch && (
|
||||
<span id="confirm-hint" className="input-hint input-hint-success">비밀번호가 일치합니다 \u2713</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="login-error" role="alert">{error}</p>}
|
||||
|
||||
@@ -68,27 +68,21 @@ describe('RegisterPage', () => {
|
||||
});
|
||||
|
||||
describe('password strength', () => {
|
||||
it('shows weak indicator for short passwords', () => {
|
||||
it('shows "약함" for passwords shorter than 6 characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abc' } });
|
||||
expect(screen.getByText(/비밀번호는 6자 이상이어야 합니다/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "약함" for lowercase-only password of 6+ chars', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdef' } });
|
||||
expect(screen.getByText(/약함/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "보통" for mixed-case password', () => {
|
||||
it('shows "중간" for passwords of 6-9 characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcDEF' } });
|
||||
expect(screen.getByText(/보통/)).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdef' } });
|
||||
expect(screen.getByText(/중간/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "강함" for password with multiple character types', () => {
|
||||
it('shows "강함" for passwords of 10+ characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcD1!' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdefghij' } });
|
||||
expect(screen.getByText(/강함/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1 +1,19 @@
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
// Vitest 4.x + jsdom 28: '--localstorage-file' without a valid path
|
||||
// causes localStorage to be a stub without .clear(). Provide a full implementation.
|
||||
if (typeof localStorage === 'undefined' || typeof localStorage.clear !== 'function') {
|
||||
const store = new Map();
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: {
|
||||
getItem: (key) => store.get(String(key)) ?? null,
|
||||
setItem: (key, value) => { store.set(String(key), String(value)); },
|
||||
removeItem: (key) => { store.delete(String(key)); },
|
||||
clear: () => { store.clear(); },
|
||||
get length() { return store.size; },
|
||||
key: (index) => ([...store.keys()][index] ?? null),
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user