Compare commits

..

13 Commits

28 changed files with 1652 additions and 168 deletions

11
.dockerignore Normal file
View File

@@ -0,0 +1,11 @@
.git
.gitignore
.DS_Store
node_modules
frontend/node_modules
frontend/dist
backend/node_modules
backend/.sessions
backend/uploads
docker-compose.yml
docs

5
.env.production.example Normal file
View File

@@ -0,0 +1,5 @@
MARIADB_ROOT_PASSWORD=change-this-root-password
MARIADB_DATABASE=tier_cursor
MARIADB_USER=tier_cursor
MARIADB_PASSWORD=change-this-db-password
SESSION_SECRET=change-this-session-secret

View File

@@ -39,6 +39,18 @@ VITE_API_ORIGIN=http://localhost:5179 npm run dev
자세한 내용은 [docs/local-mariadb.md](/Users/bicute/Desktop/zenn.dev/tier-cursor/docs/local-mariadb.md)를 참고하세요.
## UGREEN NAS 운영 배포
운영용은 `MariaDB + backend + frontend` 3컨테이너 구조를 권장합니다.
```bash
cp .env.production.example .env.production
docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
- 프로덕션 컴포즈: [docker-compose.prod.yml](/Users/bicute/Desktop/zenn.dev/tier-cursor/docker-compose.prod.yml)
- 배포 가이드: [docs/ugreen-nas-deploy.md](/Users/bicute/Desktop/zenn.dev/tier-cursor/docs/ugreen-nas-deploy.md)
## 사용 흐름(현재 구현)
- **게임 선택**: `/`에서 게임 클릭

15
backend/Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:20-alpine
WORKDIR /app
COPY backend/package*.json ./
RUN npm ci --omit=dev
COPY backend/ ./
ENV NODE_ENV=production
ENV PORT=5179
EXPOSE 5179
CMD ["node", "index.js"]

View File

@@ -24,7 +24,7 @@ const allowedOrigins = (process.env.CORS_ORIGINS || '')
const FileStore = FileStoreFactory(session)
;['uploads/avatars', 'uploads/games', 'uploads/custom', '.sessions'].forEach((relativePath) => {
;['uploads/avatars', 'uploads/games', 'uploads/custom', 'uploads/tierlists', '.sessions'].forEach((relativePath) => {
fs.mkdirSync(path.join(__dirname, relativePath), { recursive: true })
})
@@ -53,6 +53,7 @@ app.use(
retries: 0,
}),
secret: SESSION_SECRET,
proxy: TRUST_PROXY > 0,
resave: false,
saveUninitialized: false,
cookie: {

View File

@@ -46,6 +46,7 @@ function mapGameRow(row) {
id: row.id,
name: row.name,
thumbnailSrc: row.thumbnail_src || '',
displayRank: row.display_rank == null ? null : Number(row.display_rank),
createdAt: Number(row.created_at),
}
}
@@ -66,8 +67,12 @@ function mapTierListRow(row) {
return {
id: row.id,
authorId: row.author_id,
authorName: getUserDisplayName(row),
authorAccountName: getUserAccountName(row),
authorAvatarSrc: row.avatar_src || '',
gameId: row.game_id,
title: row.title,
thumbnailSrc: row.thumbnail_src || '',
description: row.description || '',
isPublic: !!row.is_public,
groups: parseJson(row.groups_json, []),
@@ -86,6 +91,13 @@ function getUserDisplayName(row) {
return email.split('@')[0] || email
}
function getUserAccountName(row) {
if (!row) return ''
const email = (row.email || '').trim()
if (!email) return ''
return email.split('@')[0] || email
}
async function createPool() {
const rootConnection = await mysql.createConnection({
host: DB_HOST,
@@ -144,10 +156,16 @@ async function ensureSchema() {
id VARCHAR(120) PRIMARY KEY,
name VARCHAR(120) NOT NULL,
thumbnail_src VARCHAR(255) NOT NULL DEFAULT '',
display_rank INT NULL DEFAULT NULL,
created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
`)
const displayRankColumns = await query("SHOW COLUMNS FROM games LIKE 'display_rank'")
if (!displayRankColumns.length) {
await query('ALTER TABLE games ADD COLUMN display_rank INT NULL DEFAULT NULL AFTER thumbnail_src')
}
await query(`
CREATE TABLE IF NOT EXISTS game_items (
id VARCHAR(64) PRIMARY KEY,
@@ -178,6 +196,7 @@ async function ensureSchema() {
author_id VARCHAR(64) NOT NULL,
game_id VARCHAR(120) NOT NULL,
title VARCHAR(120) NOT NULL,
thumbnail_src VARCHAR(255) NOT NULL DEFAULT '',
description TEXT NOT NULL,
is_public TINYINT(1) NOT NULL DEFAULT 0,
groups_json LONGTEXT NOT NULL,
@@ -192,6 +211,11 @@ async function ensureSchema() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
`)
const tierListThumbnailColumns = await query("SHOW COLUMNS FROM tierlists LIKE 'thumbnail_src'")
if (!tierListThumbnailColumns.length) {
await query("ALTER TABLE tierlists ADD COLUMN thumbnail_src VARCHAR(255) NOT NULL DEFAULT '' AFTER title")
}
await query(
`
INSERT INTO games (id, name, thumbnail_src, created_at)
@@ -316,14 +340,23 @@ async function adminDeleteUser(id) {
async function listGames() {
const rows = await query(
'SELECT id, name, thumbnail_src, created_at FROM games WHERE id <> ? ORDER BY created_at ASC, name ASC',
`
SELECT id, name, thumbnail_src, display_rank, created_at
FROM games
WHERE id <> ?
ORDER BY
CASE WHEN display_rank IS NULL THEN 1 ELSE 0 END ASC,
display_rank ASC,
created_at DESC,
name ASC
`,
[FREEFORM_GAME_ID]
)
return rows.map(mapGameRow)
}
async function findGameById(id) {
const rows = await query('SELECT id, name, thumbnail_src, created_at FROM games WHERE id = ? LIMIT 1', [id])
const rows = await query('SELECT id, name, thumbnail_src, display_rank, created_at FROM games WHERE id = ? LIMIT 1', [id])
return mapGameRow(rows[0])
}
@@ -343,7 +376,13 @@ async function getGameDetail(gameId) {
}
async function createGame({ id, name }) {
await query('INSERT INTO games (id, name, thumbnail_src, created_at) VALUES (?, ?, ?, ?)', [id, name, '', now()])
await query('INSERT INTO games (id, name, thumbnail_src, display_rank, created_at) VALUES (?, ?, ?, ?, ?)', [
id,
name,
'',
null,
now(),
])
return findGameById(id)
}
@@ -365,6 +404,12 @@ async function createGameItem({ id, gameId, src, label }) {
return mapGameItemRow(rows[0])
}
async function updateGameItemLabel(itemId, label) {
await query('UPDATE game_items SET label = ? WHERE id = ?', [label, itemId])
const rows = await query('SELECT id, game_id, src, label, created_at FROM game_items WHERE id = ? LIMIT 1', [itemId])
return mapGameItemRow(rows[0])
}
async function deleteGameItem(itemId) {
const gameItemRows = await query('SELECT game_id FROM game_items WHERE id = ? LIMIT 1', [itemId])
const gameId = gameItemRows[0]?.game_id
@@ -401,6 +446,20 @@ async function deleteGame(gameId) {
await query('DELETE FROM games WHERE id = ?', [gameId])
}
async function updateGameDisplayOrder(gameIds) {
const normalizedIds = Array.from(new Set((gameIds || []).filter((id) => id && id !== FREEFORM_GAME_ID))).slice(0, 50)
await query('UPDATE games SET display_rank = NULL WHERE id <> ?', [FREEFORM_GAME_ID])
await Promise.all(
normalizedIds.map((gameId, index) =>
query('UPDATE games SET display_rank = ? WHERE id = ? AND id <> ?', [index + 1, gameId, FREEFORM_GAME_ID])
)
)
return listGames()
}
async function createCustomItem({ id, ownerId, src, label }) {
const createdAt = now()
await query('INSERT INTO custom_items (id, owner_id, src, label, created_at) VALUES (?, ?, ?, ?, ?)', [
@@ -542,6 +601,7 @@ async function listPublicTierLists(gameId) {
t.id,
t.game_id,
t.title,
t.thumbnail_src,
t.created_at,
t.updated_at,
t.author_id,
@@ -561,10 +621,12 @@ async function listPublicTierLists(gameId) {
id: row.id,
gameId: row.game_id,
title: row.title,
thumbnailSrc: row.thumbnail_src || '',
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
authorId: row.author_id,
authorName: getUserDisplayName(row),
authorAccountName: getUserAccountName(row),
authorAvatarSrc: row.avatar_src || '',
}))
}
@@ -576,6 +638,7 @@ async function listUserTierLists(userId) {
t.id,
t.game_id,
t.title,
t.thumbnail_src,
t.created_at,
t.updated_at,
t.is_public,
@@ -594,10 +657,12 @@ async function listUserTierLists(userId) {
id: row.id,
gameId: row.game_id,
title: row.title,
thumbnailSrc: row.thumbnail_src || '',
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
isPublic: !!row.is_public,
authorName: getUserDisplayName(row),
authorAccountName: getUserAccountName(row),
authorAvatarSrc: row.avatar_src || '',
}))
}
@@ -605,9 +670,24 @@ async function listUserTierLists(userId) {
async function findTierListById(id) {
const rows = await query(
`
SELECT id, author_id, game_id, title, description, is_public, groups_json, pool_json, created_at, updated_at
FROM tierlists
WHERE id = ?
SELECT
t.id,
t.author_id,
t.game_id,
t.title,
t.thumbnail_src,
t.description,
t.is_public,
t.groups_json,
t.pool_json,
t.created_at,
t.updated_at,
u.nickname,
u.email,
u.avatar_src
FROM tierlists t
INNER JOIN users u ON u.id = t.author_id
WHERE t.id = ?
LIMIT 1
`,
[id]
@@ -646,17 +726,17 @@ async function deleteCustomItems(ids) {
await query(`DELETE FROM custom_items WHERE id IN (${placeholders})`, ids)
}
async function saveTierList({ id, authorId, gameId, title, description, isPublic, groups, pool }) {
async function saveTierList({ id, authorId, gameId, title, thumbnailSrc = '', description, isPublic, groups, pool }) {
const existing = id ? await findTierListById(id) : null
if (existing) {
await query(
`
UPDATE tierlists
SET title = ?, description = ?, is_public = ?, groups_json = ?, pool_json = ?, updated_at = ?
SET title = ?, thumbnail_src = ?, description = ?, is_public = ?, groups_json = ?, pool_json = ?, updated_at = ?
WHERE id = ?
`,
[title, description || '', isPublic ? 1 : 0, serializeJson(groups), serializeJson(pool), now(), existing.id]
[title, thumbnailSrc, description || '', isPublic ? 1 : 0, serializeJson(groups), serializeJson(pool), now(), existing.id]
)
return findTierListById(existing.id)
}
@@ -665,11 +745,11 @@ async function saveTierList({ id, authorId, gameId, title, description, isPublic
await query(
`
INSERT INTO tierlists (
id, author_id, game_id, title, description, is_public, groups_json, pool_json, created_at, updated_at
id, author_id, game_id, title, thumbnail_src, description, is_public, groups_json, pool_json, created_at, updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[id, authorId, gameId, title, description || '', isPublic ? 1 : 0, serializeJson(groups), serializeJson(pool), createdAt, createdAt]
[id, authorId, gameId, title, thumbnailSrc, description || '', isPublic ? 1 : 0, serializeJson(groups), serializeJson(pool), createdAt, createdAt]
)
return findTierListById(id)
}
@@ -693,8 +773,10 @@ module.exports = {
createGame,
updateGameThumbnail,
createGameItem,
updateGameItemLabel,
deleteGameItem,
deleteGame,
updateGameDisplayOrder,
createCustomItem,
listCustomItems,
findUnusedCustomItems,

View File

@@ -9,10 +9,13 @@ const {
findUserById,
findGameById,
createGame,
listGames,
updateGameThumbnail,
createGameItem,
updateGameItemLabel,
deleteGameItem,
deleteGame,
updateGameDisplayOrder,
listCustomItems,
findUnusedCustomItems,
findCustomItemsByIds,
@@ -32,6 +35,18 @@ function buildUploadFilename(file) {
return `${Date.now()}-${nanoid()}${safeExt}`
}
function buildItemLabelFromFilename(file) {
const originalName = file?.originalname || ''
const base = path.basename(originalName, path.extname(originalName))
const normalized = base
.replace(/[_-]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 60)
return normalized || 'item'
}
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname, '..', '..', 'uploads', 'games')),
@@ -50,6 +65,20 @@ router.post('/games', requireAdmin, async (req, res) => {
res.json({ game })
})
router.patch('/games/display-order', requireAdmin, async (req, res) => {
const schema = z.object({
gameIds: z.array(z.string().min(1)).max(50),
})
const parsed = schema.safeParse(req.body)
if (!parsed.success) return res.status(400).json({ error: 'bad_request' })
const games = await listGames()
const validGameIds = new Set(games.map((game) => game.id))
const filteredIds = parsed.data.gameIds.filter((gameId) => validGameIds.has(gameId))
const updatedGames = await updateGameDisplayOrder(filteredIds)
res.json({ games: updatedGames })
})
router.post('/games/:gameId/thumbnail', requireAdmin, upload.single('thumbnail'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'file_required' })
const game = await findGameById(req.params.gameId)
@@ -58,20 +87,27 @@ router.post('/games/:gameId/thumbnail', requireAdmin, upload.single('thumbnail')
res.json({ game: updated })
})
router.post('/games/:gameId/images', requireAdmin, upload.single('image'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'file_required' })
const schema = z.object({ label: z.string().min(1).max(60) })
const parsed = schema.safeParse(req.body)
if (!parsed.success) return res.status(400).json({ error: 'bad_request' })
router.post('/games/:gameId/images', requireAdmin, upload.array('images', 50), async (req, res) => {
const files = Array.isArray(req.files) ? req.files : []
if (!files.length) return res.status(400).json({ error: 'file_required' })
const game = await findGameById(req.params.gameId)
if (!game) return res.status(404).json({ error: 'not_found' })
const item = await createGameItem({
id: nanoid(),
gameId: game.id,
src: `/uploads/games/${req.file.filename}`,
label: parsed.data.label,
})
res.json({ item })
const manualLabel = typeof req.body?.label === 'string' ? req.body.label.trim() : ''
if (manualLabel && manualLabel.length > 60) return res.status(400).json({ error: 'bad_request' })
const items = await Promise.all(
files.map((file, index) =>
createGameItem({
id: nanoid(),
gameId: game.id,
src: `/uploads/games/${file.filename}`,
label: index === 0 && manualLabel ? manualLabel : buildItemLabelFromFilename(file),
})
)
)
res.json({ item: items[0], items })
})
router.delete('/games/:gameId/items/:itemId', requireAdmin, async (req, res) => {
@@ -81,6 +117,19 @@ router.delete('/games/:gameId/items/:itemId', requireAdmin, async (req, res) =>
res.json({ ok: true })
})
router.patch('/games/:gameId/items/:itemId', requireAdmin, async (req, res) => {
const schema = z.object({ label: z.string().trim().min(1).max(60) })
const parsed = schema.safeParse(req.body)
if (!parsed.success) return res.status(400).json({ error: 'bad_request' })
const game = await findGameById(req.params.gameId)
if (!game) return res.status(404).json({ error: 'not_found' })
const updated = await updateGameItemLabel(req.params.itemId, parsed.data.label)
if (!updated || updated.gameId !== game.id) return res.status(404).json({ error: 'not_found' })
res.json({ item: updated })
})
router.delete('/games/:gameId', requireAdmin, async (req, res) => {
const game = await findGameById(req.params.gameId)
if (!game) return res.status(404).json({ error: 'not_found' })

View File

@@ -44,7 +44,11 @@ router.post('/signup', async (req, res) => {
req.session.userId = user.id
req.session.isAdmin = !!user.isAdmin
res.json(user)
// 세션을 응답 전에 명시적으로 저장해 Set-Cookie가 확실히 내려오도록 보강
req.session.save((err) => {
if (err) return res.status(500).json({ error: 'session_save_failed' })
res.json(user)
})
})
router.post('/login', async (req, res) => {
@@ -60,13 +64,16 @@ router.post('/login', async (req, res) => {
req.session.userId = user.id
req.session.isAdmin = !!user.isAdmin
res.json({
id: user.id,
email: user.email,
nickname: user.nickname || '',
isAdmin: !!user.isAdmin,
avatarSrc: user.avatarSrc || '',
createdAt: user.createdAt,
req.session.save((err) => {
if (err) return res.status(500).json({ error: 'session_save_failed' })
res.json({
id: user.id,
email: user.email,
nickname: user.nickname || '',
isAdmin: !!user.isAdmin,
avatarSrc: user.avatarSrc || '',
createdAt: user.createdAt,
})
})
})

View File

@@ -52,10 +52,19 @@ const upload = multer({
limits: { fileSize: 6 * 1024 * 1024 },
})
const thumbnailUpload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname, '..', '..', 'uploads', 'tierlists')),
filename: (req, file, cb) => cb(null, buildUploadFilename(file)),
}),
limits: { fileSize: 6 * 1024 * 1024 },
})
const tierListUpsertSchema = z.object({
id: z.string().optional(),
gameId: z.string().min(1),
title: z.string().min(1).max(120),
thumbnailSrc: z.string().max(255).optional().default(''),
description: z.string().max(1000).optional().default(''),
isPublic: z.boolean().default(false),
groups: z.array(
@@ -121,6 +130,11 @@ router.post('/custom-items', requireAuth, upload.single('image'), async (req, re
res.json({ item })
})
router.post('/thumbnail', requireAuth, thumbnailUpload.single('thumbnail'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'file_required' })
res.json({ thumbnailSrc: `/uploads/tierlists/${req.file.filename}` })
})
router.post('/', requireAuth, async (req, res) => {
const parsed = tierListUpsertSchema.safeParse(req.body)
if (!parsed.success) return res.status(400).json({ error: 'bad_request' })
@@ -137,6 +151,7 @@ router.post('/', requireAuth, async (req, res) => {
authorId: existing.authorId,
gameId: existing.gameId,
title: payload.title,
thumbnailSrc: payload.thumbnailSrc || '',
description: payload.description || '',
isPublic: !!payload.isPublic,
groups: payload.groups,
@@ -150,6 +165,7 @@ router.post('/', requireAuth, async (req, res) => {
authorId: req.session.userId,
gameId: payload.gameId,
title: payload.title,
thumbnailSrc: payload.thumbnailSrc || '',
description: payload.description || '',
isPublic: !!payload.isPublic,
groups: payload.groups,

80
docker-compose.prod.yml Normal file
View File

@@ -0,0 +1,80 @@
services:
mariadb:
image: mariadb:11.4
container_name: tmaker-mariadb
restart: unless-stopped
environment:
MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD}
MARIADB_DATABASE: ${MARIADB_DATABASE}
MARIADB_USER: ${MARIADB_USER}
MARIADB_PASSWORD: ${MARIADB_PASSWORD}
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
volumes:
- tmaker_mariadb_data:/var/lib/mysql
healthcheck:
test: ["CMD-SHELL", "mariadb-admin ping -h 127.0.0.1 -uroot -p$$MARIADB_ROOT_PASSWORD --silent"]
start_period: 150s
interval: 10s
timeout: 5s
retries: 20
backend:
build:
context: .
dockerfile: backend/Dockerfile
container_name: tmaker-backend
restart: unless-stopped
depends_on:
mariadb:
condition: service_healthy
environment:
PORT: 5179
DB_HOST: mariadb
DB_PORT: 3306
DB_USER: ${MARIADB_USER}
DB_PASSWORD: ${MARIADB_PASSWORD}
DB_NAME: ${MARIADB_DATABASE}
SESSION_SECRET: ${SESSION_SECRET}
SESSION_COOKIE_SECURE: "true"
SESSION_COOKIE_SAME_SITE: "lax"
CORS_ORIGINS: https://tmaker.sori.studio
TRUST_PROXY: 1
volumes:
- tmaker_uploads:/app/uploads
- tmaker_sessions:/app/.sessions
frontend:
build:
context: .
dockerfile: frontend/Dockerfile
args:
VITE_API_ORIGIN: https://tmaker.sori.studio
container_name: tmaker-frontend
restart: unless-stopped
depends_on:
- backend
ports:
- "18080:80"
phpmyadmin:
image: phpmyadmin:5.2-apache
container_name: tmaker-phpmyadmin
restart: unless-stopped
profiles: ["admin"]
depends_on:
mariadb:
condition: service_healthy
environment:
PMA_HOST: mariadb
PMA_PORT: 3306
PMA_USER: ${MARIADB_USER}
PMA_PASSWORD: ${MARIADB_PASSWORD}
ports:
- "18081:80"
volumes:
tmaker_mariadb_data:
tmaker_uploads:
tmaker_sessions:

View File

@@ -1,5 +1,13 @@
# 의사결정 이력
## 2026-03-26 v0.1.39
- 티어표 편집 헤더는 게임명 kicker보다 제목과 설명이 더 중요하므로, 좌측 입력 중심 구조로 재배치하고 썸네일은 우측 보조 카드로 분리하는 편이 더 자연스럽다고 판단했다.
- 썸네일 조작 버튼은 모바일에서도 카드와 함께 유지되는 편이 흐름이 덜 끊기므로, 미리보기 아래 별도 줄로 떨어뜨리기보다 카드 내부의 짧은 액션 행으로 묶기로 결정했다.
## 2026-03-26 v0.1.38
- 관리자 기본 아이템은 업로드 시점에만 이름을 정할 수 있으면 운영 중 수정이 어려우므로, 목록에서 직접 이름을 바꾸고 저장할 수 있게 하기로 결정했다.
- 게임별 티어표 목록도 식별성이 중요하므로, 사용자가 편집 시 별도 썸네일을 지정할 수 있게 하고 목록 카드에서는 게임 카드와 비슷한 상단 썸네일 구조를 사용하기로 결정했다.
## 2026-03-19
- 초기 저장소는 빠른 구현을 위해 `lowdb(JSON 파일)`를 채택했다.
- 인증은 JWT 대신 서버 세션(`express-session` + `session-file-store`)을 사용했다.
@@ -72,3 +80,68 @@
- 에디터에서 저장 관련 행동은 좌우로 역할을 나눠 `다운로드/삭제``공개/저장`으로 묶는 편이 더 빠르게 인지된다고 판단했다.
- 공개 목록과 내 목록에서 제목만으로는 식별이 어려우므로, 제목 옆에 작성자 아바타와 표시명을 함께 노출하기로 결정했다.
- 티어표 카드 메타 정보는 저장 시각과 업데이트 시각을 동시에 노출하는 대신, 최종 업데이트 시각만 남겨 단순화하기로 결정했다.
## 2026-03-26 v0.1.21
- 목록 썸네일 fallback 문자는 닉네임보다 계정 기준이 더 일관되므로, 아바타 이미지가 없을 때는 계정명 첫 글자를 사용하기로 결정했다.
- 저장 성공은 화면 이동보다 현 위치 유지가 더 중요하므로, 편집을 계속할 수 있는 확인형 모달로 피드백을 제공하기로 결정했다.
- PNG export는 가장자리 여백이 없는 결과보다 중앙 정렬된 카드형 결과물이 더 완성도 있게 보이므로, export 전용 보드에 충분한 바깥 패딩을 포함하기로 했다.
## 2026-03-26 v0.1.22
- 무제목 저장은 게임 이름 기본값보다 `이름 없음 + 날짜`가 더 명확하다고 판단해 자동 제목 규칙을 변경했다.
- 제목이 비어 있는 티어표는 품질 관리 대상이 될 수 있으므로, 작성 중 단계에서 관리자 임의 삭제 가능성을 미리 안내하기로 결정했다.
- 다운로드 이미지에는 편집용 빈 칸 안내 문구를 제외하고, 더 넓은 보드 폭과 하단 작성자/날짜 메타를 포함해 공유용 완성도를 높이기로 결정했다.
## 2026-03-26 v0.1.23
- 홈 화면 정렬은 단순 생성순 하나보다 `관리자 상단 고정 순서 + 나머지 최신 생성순` 조합이 운영과 신규 노출을 함께 만족시킨다고 판단했다.
- 상단 고정은 전체 수동 정렬보다 최대 50개만 관리하는 방식이 운영 부담이 적으므로, 관리자에게는 제한된 상단 고정 목록만 직접 편집하게 하기로 결정했다.
- `커스텀 티어표 만들기`는 일반 게임 카드와 성격이 다르므로 카드형 목록에서 분리해 우측 상단 버튼으로 노출하기로 결정했다.
## 2026-03-26 v0.1.24
- 상단 고정 게임이 50개까지 늘어날 수 있으므로, 위/아래 버튼만으로는 불편하다고 판단해 드래그 정렬을 함께 제공하기로 결정했다.
- export 결과가 지나치게 넓으면 아이콘이 한 줄에 과도하게 몰리므로, 공유용 이미지 폭을 줄이고 pixel ratio도 낮춰 균형을 맞추기로 결정했다.
- 현재 업로드는 파일 크기 제한만 있고 서버 저장 전 최적화는 없으므로, 운영 문서에 현황을 명확히 남기고 향후 리사이즈/압축 도입 여부를 검토하기로 했다.
## 2026-03-26 v0.1.25
- 저장 결과물 기준 너비가 여전히 길다고 판단해, export 보드 폭을 추가로 `960px`까지 줄여 최종 PNG 밀도를 더 낮추기로 결정했다.
## 2026-03-26 v0.1.26
- 아이콘 크기는 사용자 취향 차이가 큰 요소이므로, 고정값 하나보다 기본 `80px`에 단계형 크기 선택을 제공하는 편이 더 낫다고 판단했다.
## 2026-03-26 v0.1.27
- NAS 운영은 리버스 프록시 설정을 단순하게 유지하는 편이 좋으므로, 프런트 컨테이너 하나만 외부 공개하고 `/api`, `/uploads`는 내부 프록시로 넘기는 구조를 채택했다.
- 운영은 로컬 개발 컴포즈와 분리된 전용 `docker-compose.prod.yml`을 두고, 환경변수는 `.env.production`으로 분리해 관리하기로 결정했다.
## 2026-03-26 v0.1.28
- UGREEN NAS에서 MariaDB 초기화가 길게 걸릴 수 있으므로, healthcheck는 앱 계정보다 `root` 기준 ping과 더 긴 유예 시간으로 두는 편이 안전하다고 판단했다.
## 2026-03-26 v0.1.29
- NAS에서 HTTPS를 종료한 뒤 내부 컨테이너끼리는 HTTP로 통신하는 구조에서는, 프런트 프록시가 백엔드에 원래 프로토콜을 정확히 전달하지 않으면 `secure` 세션 쿠키가 발급되지 않는다고 판단했다.
- 따라서 운영 프런트 Nginx는 백엔드 프록시 요청에 `X-Forwarded-Proto: https`를 명시하고, Express 세션도 프록시 환경을 명시적으로 신뢰하도록 설정하기로 결정했다.
## 2026-03-26 v0.1.30
- 운영 프런트는 다른 origin 절대 URL보다 같은 origin 상대 `/api` 요청을 우선해야 세션 쿠키 저장이 안정적이라고 판단했다.
## 2026-03-26 v0.1.31
- 세션 기반 로그인 응답은 저장소 반영 타이밍 차이를 줄이기 위해 `req.session.save()`를 명시 호출하는 쪽이 운영 안정성에 유리하다고 판단했다.
## 2026-03-26 v0.1.32
- 인증 문제를 빠르게 확인하기 위해 일시적으로 세션 저장 성공/실패 로그를 남기고 원인을 좁혀가는 접근을 선택했다.
## 2026-03-26 v0.1.33
- 프록시 환경의 실제 판단 값을 보기 위해 `req.secure`, `req.protocol`, `x-forwarded-proto`를 직접 로그로 비교해 원인을 확인하기로 했다.
## 2026-03-26 v0.1.34
- 일부 NAS 환경에서 `favicon.svg` 정적 응답이 `403`으로 차단될 수 있으므로, 운영 안정성을 위해 별도 파일 요청이 필요 없는 인라인 데이터 URL 파비콘으로 전환하기로 결정했다.
- 관리자 기본 아이템 등록은 단일 파일 업로드만으로는 운영 부담이 크므로, 다중 선택과 드래그 앤 드롭을 지원하고 라벨은 파일명으로 자동 생성하는 방향을 채택했다.
## 2026-03-26 v0.1.35
- NAS 운영 경로는 수동 파일 복사보다 Git clone 기반이 로컬 개발 흐름과 더 잘 맞고, 실수로 누락되는 파일을 줄일 수 있으므로 기본 배포 방식으로 권장하기로 결정했다.
- 운영 환경 변수와 Docker 볼륨은 Git 저장소 바깥의 NAS 자산으로 유지하고, 코드는 `git pull`로만 반영하는 역할 분리를 명확히 하기로 했다.
## 2026-03-26 v0.1.36
- 브라우저 탭 제목은 개발용 기본 문자열보다 서비스 이름을 직접 보여주는 편이 맞다고 판단해 `Tier Maker`로 고정했다.
- 무제목 티어표 기본값은 날짜형 임시 제목보다 사용자가 어떤 게임으로 작성했는지 즉시 알 수 있는 게임명 기준이 더 자연스럽다고 판단했다.
## 2026-03-26 v0.1.37
- 운영 포트 충돌을 피하기 위해 프로덕션 외부 포트는 `frontend=18080`, `phpMyAdmin=18081`로 고정하고, 리버스 프록시 문서도 그 기준으로 맞추기로 했다.
- 인증 장애 원인을 찾기 위한 디버그 로그는 문제 해결 후 제거하고, 실제 운영에는 세션 저장 보강과 프록시 헤더 설정만 유지하는 편이 낫다고 판단했다.

View File

@@ -7,13 +7,13 @@
## `/games/:gameId`
- 화면 파일: `frontend/src/views/GameHubView.vue`
- 역할: 선택한 게임 정보 표시, 공개 티어표 목록 표시, 작성자 닉네임 노출, 새 티어표 작성 진입
- 역할: 선택한 게임 정보 표시, 공개 티어표 목록 표시, 티어표별 상단 썸네일/작성자 표시, 새 티어표 작성 진입
- 연동 API: `GET /api/games/:gameId`, `GET /api/tierlists/public`
## `/editor/:gameId/new`, `/editor/:gameId/:tierListId`
- 화면 파일: `frontend/src/views/TierEditorView.vue`
- 역할: 티어 그룹 편집, 티어 행 추가/삭제, 관리자 아이템/커스텀 아이템 다중 드래그 앤 드롭 업로드, 작성 권한 제어, 저장, 공개 여부 설정, PNG 다운로드
- 연동 API: `GET /api/games/:gameId`, `GET /api/tierlists/:id`, `POST /api/tierlists/custom-items`, `POST /api/tierlists`
- 역할: 티어 그룹 편집, 티어 행 추가/삭제, 관리자 아이템/커스텀 아이템 다중 드래그 앤 드롭 업로드, 티어표 썸네일 선택, 작성 권한 제어, 저장, 공개 여부 설정, PNG 다운로드
- 연동 API: `GET /api/games/:gameId`, `GET /api/tierlists/:id`, `POST /api/tierlists/thumbnail`, `POST /api/tierlists/custom-items`, `POST /api/tierlists`
## `/login`
- 화면 파일: `frontend/src/views/LoginView.vue`
@@ -22,13 +22,13 @@
## `/me`
- 화면 파일: `frontend/src/views/MyTierListsView.vue`
- 역할: 내 티어표 목록 조회, 편집 화면으로 이동, 작성자 본인 티어표 삭제
- 역할: 내 티어표 목록 조회, 상단 썸네일 카드 표시, 편집 화면으로 이동, 작성자 본인 티어표 삭제
- 연동 API: `GET /api/tierlists/me`, `DELETE /api/tierlists/:id`
## `/admin`
- 화면 파일: `frontend/src/views/AdminView.vue`
- 역할: `게임 관리 / 아이템 관리 / 회원 관리` 탭 분리, 선택된 게임의 썸네일/기본 아이템 관리, 사용자 커스텀 아이템 검색/페이지네이션/사용 횟수 확인/미사용 이미지 개별·일괄 삭제, 회원 비밀번호 초기화 포함 회원 관리, 파일 입력 초기화, 아이템 삭제, 게임 삭제
- 연동 API: `POST /api/admin/games`, `POST /api/admin/games/:gameId/thumbnail`, `POST /api/admin/games/:gameId/images`, `GET /api/admin/custom-items`, `DELETE /api/admin/custom-items/:itemId`, `DELETE /api/admin/custom-items`, `GET /api/admin/users`, `PATCH /api/admin/users/:userId`, `PATCH /api/admin/users/:userId/password`, `DELETE /api/admin/users/:userId`, `DELETE /api/admin/games/:gameId/items/:itemId`, `DELETE /api/admin/games/:gameId`
- 역할: `게임 관리 / 아이템 관리 / 회원 관리` 탭 분리, 선택된 게임의 썸네일 관리, 기본 아이템 다중 드래그 앤 드롭 업로드, 기본 아이템 이름 수정, 사용자 커스텀 아이템 검색/페이지네이션/사용 횟수 확인/미사용 이미지 개별·일괄 삭제, 회원 비밀번호 초기화 포함 회원 관리, 파일 입력 초기화, 아이템 삭제, 게임 삭제
- 연동 API: `POST /api/admin/games`, `POST /api/admin/games/:gameId/thumbnail`, `POST /api/admin/games/:gameId/images`, `PATCH /api/admin/games/:gameId/items/:itemId`, `GET /api/admin/custom-items`, `DELETE /api/admin/custom-items/:itemId`, `DELETE /api/admin/custom-items`, `GET /api/admin/users`, `PATCH /api/admin/users/:userId`, `PATCH /api/admin/users/:userId/password`, `DELETE /api/admin/users/:userId`, `DELETE /api/admin/games/:gameId/items/:itemId`, `DELETE /api/admin/games/:gameId`
## `/profile`
- 화면 파일: `frontend/src/views/ProfileView.vue`

View File

@@ -6,6 +6,9 @@
- 데이터 저장소: MariaDB(MySQL 호환)
- 세션 저장소: `session-file-store` 기반 파일 세션
- 업로드 저장소: 로컬 파일 시스템(`backend/uploads/`)
- 운영 배포: `frontend(Nginx 정적 서빙 + /api,/uploads 프록시) + backend + mariadb` Docker Compose 구조
- NAS HTTPS 리버스 프록시 운영 시 프런트 Nginx는 백엔드로 `X-Forwarded-Proto: https`를 전달하고, Express 세션은 프록시 환경에서 `secure` 쿠키를 허용하도록 설정한다.
- 프런트 파비콘은 운영 정적 파일 차단 영향을 줄이기 위해 `index.html`의 인라인 데이터 URL로 제공한다.
## 데이터 저장 구조
- 메인 데이터베이스: MariaDB `tier_cursor` (기본값)
@@ -48,6 +51,7 @@
- `authorId`: string
- `gameId`: string
- `title`: string
- `thumbnailSrc`: string
- `description`: string
- `isPublic`: boolean
- `groups`: `{ id, name, itemIds[] }[]`
@@ -75,12 +79,15 @@
- `GET /api/tierlists/me`
- `GET /api/tierlists/:id`
- `DELETE /api/tierlists/:id`
- `POST /api/tierlists/thumbnail`
- `POST /api/tierlists/custom-items`
- `POST /api/tierlists`
- 관리자
- `POST /api/admin/games`
- `POST /api/admin/games/:gameId/thumbnail`
- `POST /api/admin/games/:gameId/images`
- 여러 이미지를 한 번에 업로드할 수 있고, 별도 라벨이 없으면 파일명 기준으로 기본 아이템 이름을 만든다.
- `PATCH /api/admin/games/:gameId/items/:itemId`
- `GET /api/admin/custom-items`
- `DELETE /api/admin/custom-items/:itemId`
- `DELETE /api/admin/custom-items`
@@ -93,9 +100,11 @@
## 관리자 화면 메모
- 썸네일은 16:9 비율 미리보기 후 `썸네일 적용` 버튼으로 실제 반영한다.
- 게임 기본 아이템 추가는 이름 입력, 파일 선택, 1:1 미리보기 확인 뒤 저장하는 흐름이다.
- 게임 기본 아이템 추가는 드래그 앤 드롭 또는 다중 파일 선택으로 처리하고, 미리보기 카드에서 여러 장을 함께 확인할 수 있다.
- 현재 기본 아이템 목록에서는 등록된 아이템 이름을 직접 수정하고 저장할 수 있다.
- 아이템 미리보기는 반응형 환경에서도 최대 `192px` 크기 안에서 표시한다.
- 게임 전환 또는 업로드 성공 뒤에는 파일 입력값을 초기화해 같은 파일도 다시 선택할 수 있다.
- 게임 관리 탭에서는 홈 화면 상단에 먼저 노출할 게임을 최대 50개까지 지정하고, 드래그 또는 위/아래 버튼으로 순서를 저장할 수 있다.
- 사용자 업로드 커스텀 아이템은 관리자 화면의 아이템 관리 탭에서 검색, 페이지네이션, 다운로드할 수 있다.
- 커스텀 아이템은 사용 횟수(`usageCount`)를 표시하며, 미사용 항목만 필터링해 개별/일괄 삭제할 수 있다.
- 관리자 화면에서는 회원 이메일/닉네임/권한 수정, 비밀번호 초기화, 계정 삭제가 가능하다.
@@ -106,8 +115,22 @@
- 커스텀 이미지 추가는 다중 파일 선택과 드래그 앤 드롭을 모두 지원한다.
- 티어 행은 기본 5단으로 시작하지만, 사용자가 직접 추가하거나 제거할 수 있다.
- 신규 티어표의 공개 여부 기본값은 `ON`이며, 기존 티어표는 편집 화면과 `내 티어표` 목록에서 직접 삭제할 수 있다.
- 제목이 비어 있는 상태로 저장하면 내부 제목은 현재 게임명을 기본값으로 사용한다.
- 제목 입력이 비어 있는 동안에는 무분별한 도배 방지를 위한 관리자 임의 삭제 가능성 안내 문구를 표시한다.
- 티어표는 편집 화면에서 16:9 썸네일 이미지를 별도로 선택해 저장할 수 있고, 목록 카드에서는 그 이미지를 상단 대표 썸네일로 사용한다.
- 편집 화면 상단 헤더는 좌측 제목/설명, 우측 썸네일 카드 구조를 사용하며 모바일에서는 한 열로 접힌다.
- 티어표 편집기의 아이콘 기본 크기는 `80px`이며, 사용자가 `48 / 60 / 80 / 100 / 120` 단계로 즉시 조절할 수 있다.
- 공개 티어표 목록과 `내 티어표` 목록은 제목 옆에 작성자 아바타와 표시명을 함께 보여준다.
- 작성자 아바타 이미지가 없을 경우 목록 썸네일 fallback은 닉네임이 아니라 계정명 기준 첫 글자를 사용한다.
- 티어표 목록 메타 정보는 최종 업데이트 시각만 간략하게 표시한다.
- 저장 성공 시에는 에디터 안에서 반투명 오버레이 기반 확인 모달을 띄우고, PNG export 이미지는 약 `960px` 보드 폭과 `pixelRatio 1.5`, 외곽 여백, 작성자/날짜 하단 메타를 포함해 생성한다.
- 홈 게임 목록은 관리자 상단 고정 순서가 있으면 그 순서를 먼저 적용하고, 그 외 게임은 최근 생성순으로 뒤에 이어진다.
- `커스텀 티어표 만들기`는 카드가 아니라 홈 우측 상단 버튼으로 진입한다.
## 업로드 제한 메모
- 프로필 아바타 업로드는 파일당 최대 `3MB`다.
- 관리자 게임 썸네일/기본 아이템 업로드와 사용자 커스텀 이미지 업로드는 파일당 최대 `6MB`다.
- 현재는 업로드 전에 이미지 리사이즈/압축을 하지 않고 원본 파일을 그대로 저장한다.
## 운영 환경 변수
- 프런트엔드
@@ -125,6 +148,12 @@
- `SESSION_COOKIE_SECURE`: `true`면 HTTPS 전용 쿠키
- `SESSION_COOKIE_SAME_SITE`: 기본 `lax`
## 운영 배포 메모
- 프로덕션 컴포즈 파일은 [docker-compose.prod.yml](/Users/bicute/Desktop/zenn.dev/tier-cursor/docker-compose.prod.yml)이다.
- 외부 도메인 `tmaker.sori.studio``frontend` 컨테이너의 `18080` 포트로 리버스 프록시하고, `/api`, `/uploads`, `/health`는 프런트 Nginx가 내부 `backend:5179`로 전달한다.
- 운영 볼륨은 MariaDB 데이터, 업로드 파일, 세션 파일을 각각 분리해 유지한다.
- MariaDB healthcheck는 NAS 첫 기동 지연을 고려해 `root` 기준 ping과 긴 `start_period/retries`를 사용한다.
## NAS 배포 메모
- 현재 구조는 MariaDB/MySQL 계열이므로 NAS에 MariaDB를 올리면 phpMyAdmin 또는 Adminer로 직접 데이터 확인이 가능하다.
- 추천 구성:

View File

@@ -4,6 +4,9 @@
- 사용자 커스텀 아이템을 관리자 기본 템플릿으로 승격하는 승인/복제 흐름은 아직 없다.
- 회원 관리에서 아바타/작성 티어표 수/최근 활동 같은 보조 정보는 아직 표시하지 않는다.
- 미사용 커스텀 이미지 일괄 삭제는 현재 "참조가 없는 항목" 기준이며, 보관 기간 정책 같은 운영 규칙은 아직 없다.
- 업로드 이미지는 현재 원본 파일을 그대로 저장하므로, 운영 부담이 커지면 서버 저장 전 리사이즈/압축(예: 긴 변 제한, WebP 변환) 도입이 필요하다.
- 관리자 기본 아이템 다중 업로드는 현재 파일명 기반 자동 라벨만 지원하므로, 필요하면 업로드 후 일괄 라벨 수정/정렬 UX를 추가 검토한다.
- 티어표 썸네일은 현재 업로드/교체만 지원하므로, 필요하면 자동 썸네일 추출이나 업로드 이미지 크롭 UX를 추가 검토한다.
## 배포 전 작업
- NAS 실제 도메인 기준으로 `VITE_API_ORIGIN`, `CORS_ORIGINS`, `SESSION_SECRET`, `SESSION_COOKIE_SECURE`, `TRUST_PROXY` 값을 설정한다.
@@ -16,6 +19,5 @@
- 게임/이미지/티어표 삭제 후 복구 또는 수정 이력 관리 기능을 추가한다.
- 자동 테스트와 최소한의 배포 체크리스트를 만든다.
- 관리자용 커스텀 아이템 승인/복제, 아이템 정렬 UI를 추가한다.
- 홈 화면 게임 카드와 `직접 티어표 만들기` 카드의 노출 순서를 관리자가 직접 조정할 수 있는 정렬 기능을 추가한다.
- 회원 검색/필터, 일괄 권한 변경 같은 관리 보조 기능을 추가한다.
- 티어 행 프리셋 저장, 색상 관리, 행 복제 같은 고급 편집 기능을 추가한다.

160
docs/ugreen-nas-deploy.md Normal file
View File

@@ -0,0 +1,160 @@
# UGREEN NAS 배포 가이드
## 개요
- 운영 기본 컨테이너는 `mariadb`, `backend`, `frontend` 3개다.
- `phpmyadmin`은 필요할 때만 `admin` 프로필로 추가 실행한다.
- 외부 공개는 `frontend` 컨테이너 하나만 하고, `/api`, `/uploads`, `/health`는 내부적으로 `backend`로 프록시한다.
- 도메인은 `https://tmaker.sori.studio` 기준으로 설정한다.
## 파일
- 프로덕션 컴포즈: [docker-compose.prod.yml](/Users/bicute/Desktop/zenn.dev/tier-cursor/docker-compose.prod.yml)
- 백엔드 이미지: [backend/Dockerfile](/Users/bicute/Desktop/zenn.dev/tier-cursor/backend/Dockerfile)
- 프런트 이미지: [frontend/Dockerfile](/Users/bicute/Desktop/zenn.dev/tier-cursor/frontend/Dockerfile)
- 프런트 Nginx 프록시: [frontend/nginx.conf](/Users/bicute/Desktop/zenn.dev/tier-cursor/frontend/nginx.conf)
- 환경변수 예시: [.env.production.example](/Users/bicute/Desktop/zenn.dev/tier-cursor/.env.production.example)
## 1. 프로젝트 업로드
- NAS 작업 폴더에 현재 프로젝트를 그대로 업로드한다.
- 기존 로컬 MariaDB 내용은 무시하고 새 운영 DB로 시작해도 된다.
## 1-1. 권장 방식: Git clone 기반 운영
- 수동 복사는 처음 1회에는 가능하지만, 이후부터는 로컬과 NAS가 쉽게 어긋난다.
- 권장 방식은 NAS 작업 폴더를 Git 저장소로 두고, 로컬에서 작업 후 `push`, NAS에서는 `pull`만 하는 구조다.
- 추천 흐름:
- 로컬: 개발 → 테스트 → 커밋 → `git push`
- NAS: `git pull``docker compose up -d --build`
처음부터 Git으로 시작하려면 NAS에서:
```bash
cd /volume1/docker/projects/apps
git clone https://git.sori.studio/zenn/tier-maker.git
cd tier-maker
cp .env.production.example .env.production
```
- 이미 같은 경로에 수동 복사본이 있다면, 가장 깔끔한 방법은 기존 폴더를 다른 이름으로 잠시 옮기고 새로 `clone`하는 것이다.
- `.env.production`은 Git에 올리지 않고 NAS에만 유지한다.
예시:
```bash
cd /volume1/docker/projects/apps
mv tier-maker tier-maker-manual-backup
git clone https://git.sori.studio/zenn/tier-maker.git
cd tier-maker
cp .env.production.example .env.production
```
- 이후 기존 수동 복사본의 `.env.production` 값을 새 clone 폴더의 `.env.production`에 그대로 옮기면 된다.
## 2. 환경변수 파일 준비
- 루트에서 `.env.production.example`를 복사해 `.env.production`으로 만든다.
- 최소 변경값:
- `MARIADB_ROOT_PASSWORD`
- `MARIADB_PASSWORD`
- `SESSION_SECRET`
예시:
```env
MARIADB_ROOT_PASSWORD=very-strong-root-password
MARIADB_DATABASE=tier_cursor
MARIADB_USER=tier_cursor
MARIADB_PASSWORD=very-strong-app-password
SESSION_SECRET=very-strong-random-session-secret
```
## 3. 컨테이너 실행
```bash
docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
- phpMyAdmin까지 같이 띄우려면:
```bash
docker compose --env-file .env.production -f docker-compose.prod.yml --profile admin up -d --build
```
- MariaDB 첫 초기화는 NAS 환경에서 2분 이상 걸릴 수 있다.
- 현재 프로덕션 컴포즈는 이를 고려해 `start_period: 150s`, `retries: 20` healthcheck를 사용한다.
- 로그상 DB가 정상 기동했는데도 `unhealthy`가 뜬 적이 있다면 최신 `docker-compose.prod.yml`로 다시 올리는 것이 좋다.
## 3-1. 이후 업데이트 방식
- Git clone 기반으로 전환한 뒤에는 파일을 하나씩 NAS에 덮어쓰지 않는다.
- 로컬에서 커밋과 푸시가 끝난 뒤, NAS에서는 아래 두 줄이 기본 배포 절차다.
```bash
git pull origin main
docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
- Dockerfile, Nginx 설정, 프런트 소스, 백엔드 소스가 바뀐 경우에는 `--build`를 유지한다.
- 단순 재시작만 필요할 때도 있지만, 운영에서는 실수 방지를 위해 `up -d --build`를 기본값으로 두는 편이 안전하다.
## 3-2. 이번 v0.1.34까지 적용하는 예시
- 이미 NAS 폴더가 Git clone 상태라면:
```bash
cd /volume1/docker/projects/apps/tier-maker
git pull origin main
sudo docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
- 아직 수동 복사 폴더만 있다면:
```bash
cd /volume1/docker/projects/apps
mv tier-maker tier-maker-manual-backup
git clone https://git.sori.studio/zenn/tier-maker.git
cd tier-maker
cp .env.production.example .env.production
# 여기서 기존 .env.production 값을 새 파일에 옮긴다.
docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
## 4. NAS 리버스 프록시
- 외부 도메인: `tmaker.sori.studio`
- 내부 대상 프로토콜: `http`
- 내부 대상 호스트: NAS IP 또는 `localhost`
- 내부 대상 포트: `18080`
즉 NAS 리버스 프록시는 `frontend` 컨테이너의 `18080`만 바라보면 된다.
## 5. HTTPS / 쿠키
- 현재 프로덕션 컴포즈는 `SESSION_COOKIE_SECURE=true`를 사용한다.
- 따라서 `tmaker.sori.studio`에는 HTTPS 인증서가 연결되어 있어야 한다.
- NAS 리버스 프록시가 HTTPS 종료를 하고 내부는 `http://frontend:80` 또는 `localhost:18080`으로 전달하면 된다.
- 최신 프런트 Nginx 설정은 백엔드로 `X-Forwarded-Proto: https`를 넘기므로, 로그인 직후 세션이 바로 풀리는 경우에는 프런트 이미지를 다시 빌드해 최신 설정이 반영됐는지 먼저 확인한다.
## 6. 데이터 위치
- MariaDB 데이터: Docker volume `tmaker_mariadb_data`
- 업로드 파일: Docker volume `tmaker_uploads`
- 세션 파일: Docker volume `tmaker_sessions`
## 7. 점검 포인트
- 메인 접속: `https://tmaker.sori.studio`
- 헬스체크: `https://tmaker.sori.studio/health`
- 로그인 후 새로고침 또는 `내 티어표` 진입 시 세션이 유지되는지 확인
- 관리자 로그인 후:
- 게임 생성
- 썸네일 업로드
- 티어표 저장
- 이미지 다운로드
## 8. MariaDB가 unhealthy일 때
- 로그에 `ready for connections`가 보이면 DB 자체는 정상일 가능성이 높다.
- 이 경우는 대부분 healthcheck 시간이 짧아서 생기는 문제다.
- 최신 컴포즈 파일 반영 후 아래 순서로 다시 시작한다:
```bash
docker compose --env-file .env.production -f docker-compose.prod.yml down -v
docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build
```
## 9. 참고
- 현재 업로드 이미지는 서버 저장 전에 리사이즈/압축하지 않는다.
- 운영 중 원본 이미지가 많이 쌓이면 이후 `sharp` 기반 최적화 단계를 추가하는 것이 좋다.
- 프런트/백엔드/Nginx 설정을 바꿨다면 NAS에서 `docker compose --env-file .env.production -f docker-compose.prod.yml up -d --build`로 이미지를 다시 빌드해 반영한다.
- 운영 중 `.env.production`, 업로드 파일 볼륨, MariaDB 볼륨은 Git과 별개로 NAS 로컬 자산이므로 백업 정책을 따로 잡아야 한다.

View File

@@ -1,5 +1,82 @@
# 업데이트 로그
## 2026-03-26 v0.1.39
- **에디터 헤더 재구성**: 티어표 편집 상단에서 게임명 kicker를 제거하고, 좌측 제목/설명 입력과 우측 썸네일 카드가 나란히 보이는 구조로 재정리
- **썸네일 영역 UX 개선**: 썸네일 미리보기와 선택/제거 버튼을 하나의 카드 안에 묶고, 모바일에서도 버튼이 카드 아래로 무너지지 않도록 밀도 있게 조정
## 2026-03-26 v0.1.38
- **관리자 기본 아이템 이름 수정 추가**: 게임 관리 화면의 현재 기본 아이템 목록에서 이름을 직접 수정하고 저장할 수 있도록 API와 UI를 보강
- **티어표 썸네일 추가**: 티어표 편집 화면에서 별도 썸네일 이미지를 선택해 저장할 수 있도록 업로드 흐름을 추가하고, 게임별 공개 티어표/내 티어표 목록은 게임 카드처럼 상단 썸네일 + 하단 제목/작성자 정보 카드 구조로 변경
## 2026-03-26 v0.1.37
- **운영 포트 설정 반영**: 프로덕션 컴포즈의 `frontend/phpMyAdmin` 외부 포트를 `18080/18081` 기준으로 유지하고, NAS 배포 문서와 기술 명세의 리버스 프록시 포트 안내도 동일하게 정리
- **인증 라우트 정리**: NAS 로그인 문제를 확인하기 위해 넣었던 `auth` 디버그 로그를 제거하고, 실제 운영에 필요한 세션 저장 보강만 유지
- **이력 문서 정렬**: `docs/history.md`를 날짜/버전 흐름에 맞게 다시 정리해 추적성을 높임
## 2026-03-26 v0.1.36
- **브라우저 탭 이름 변경**: 프런트 문서 제목을 `frontend`에서 `Tier Maker`로 변경
- **무제목 티어표 기본값 조정**: 사용자가 제목을 입력하지 않으면 `이름 없음 + 날짜` 대신 현재 게임명을 기본 제목으로 사용하도록 변경하고, 관리자 임의 삭제 안내 문구는 유지
## 2026-03-26 v0.1.35
- **NAS Git 배포 절차 추가**: UGREEN NAS에서 수동 복사 대신 `git clone``git pull` 기반으로 운영 배포를 관리하는 절차를 배포 가이드에 정리
- **v0.1.34 반영 명령 정리**: 이미 수동 복사본이 있는 경우 새 clone으로 전환한 뒤 최신 이미지를 다시 빌드하는 순서를 문서화
## 2026-03-26 v0.1.34
- **파비콘 정적 요청 제거**: 운영 환경에서 `/favicon.svg``403`으로 막히는 경우를 피하기 위해, 별도 파일 대신 `index.html` 인라인 데이터 URL 파비콘으로 전환
- **관리자 기본 아이템 다중 업로드 추가**: 게임 관리 화면에서 기본 아이템을 여러 장 드래그 앤 드롭 또는 다중 파일 선택으로 한 번에 추가할 수 있도록 변경하고, 기본 라벨은 파일명 기준으로 자동 생성
## 2026-03-26 v0.1.33
- **[NAS] 요청 프로토콜 디버그**: `auth/login`/`auth/me`에서 `req.secure`, `req.protocol`, `x-forwarded-proto` 값을 로그로 출력해 프록시/HTTPS 판단 문제를 확인
## 2026-03-26 v0.1.32
- **[NAS] 인증 디버그 로그 추가**: `auth/login`에서 `req.session.save` 성공/실패와 `auth/me`에서 세션 존재 여부를 콘솔 로그로 남겨 세션 쿠키 발급 문제를 빠르게 진단
## 2026-03-26 v0.1.31
- **[NAS] 세션 쿠키 발급 강제**: 백엔드 인증 라우트에서 `req.session.save()`를 명시 호출해 응답 전에 세션을 저장하고 `Set-Cookie`가 확실히 내려오도록 보강
## 2026-03-26 v0.1.30
- **[NAS] /api 상대경로 호출**: 운영(`import.meta.env.PROD`)에서는 `http://localhost:...` 같은 다른 origin으로 API를 호출하지 않도록, `frontend/src/lib/runtime.js`에서 `/api` 호출을 상대경로로 고정해 세션 쿠키가 정상 저장되도록 수정
## 2026-03-26 v0.1.29
- **NAS 로그인 유지 수정**: 프런트 Nginx가 백엔드에 전달하는 `X-Forwarded-Proto``https`로 고정하고 Express 세션의 프록시 인지를 명시해, NAS HTTPS 리버스 프록시 뒤에서도 `secure` 세션 쿠키가 정상 발급되도록 조정
- **운영 템플릿 복구**: 실수로 빠질 수 있는 `.env.production.example`를 다시 포함하고, NAS 재배포 시 최신 프런트 이미지를 다시 빌드하도록 문서 보강
## 2026-03-26 v0.1.28
- **MariaDB healthcheck 완화**: UGREEN NAS 첫 초기화 시간이 길어도 `unhealthy`로 오판하지 않도록 프로덕션 컴포즈의 DB healthcheck를 `root` 기준과 더 긴 `start_period/retries`로 조정
- **NAS 장애 대응 문서화**: `ready for connections` 이후에도 `unhealthy`가 뜨는 경우의 재기동 절차를 배포 가이드에 추가
## 2026-03-26 v0.1.27
- **UGREEN NAS 배포 파일 추가**: `backend`, `frontend`용 Dockerfile과 프런트 Nginx 프록시 설정, 프로덕션 전용 `docker-compose.prod.yml` 추가
- **운영 환경 예시 추가**: `.env.production.example`로 MariaDB/세션 시크릿 환경변수 템플릿 제공
- **배포 문서화**: `tmaker.sori.studio` 기준 NAS 리버스 프록시, 컨테이너 실행, 볼륨 구성 가이드를 문서에 정리
## 2026-03-26 v0.1.26
- **아이콘 크기 조절 추가**: 티어표 편집기에서 `48 / 60 / 80 / 100 / 120` 단계로 아이콘 크기를 직접 바꿀 수 있도록 추가
- **기본 아이콘 크기 상향**: 기본 `.thumb` 크기를 `80px` 기준으로 조정하고, 보드와 우측 아이템 목록에 함께 반영되도록 정리
## 2026-03-26 v0.1.25
- **export 폭 추가 축소**: 티어표 PNG export 보드 폭을 `960px`로 더 줄여 최종 저장 이미지가 지나치게 길어지지 않도록 조정
## 2026-03-26 v0.1.24
- **관리자 게임 순서 드래그 정렬 추가**: 상단 고정 게임 목록을 위/아래 버튼뿐 아니라 드래그로도 순서를 바꿀 수 있도록 보강
- **export 크기 재조정**: 티어표 PNG export를 약 `1360px` 폭과 `pixelRatio 1.5` 기준으로 낮춰 아이콘이 과도하게 한 줄에 몰리지 않도록 수정
- **업로드 정책 문서화**: 현재 아바타 `3MB`, 게임/커스텀 이미지 `6MB` 제한이 있으며 서버 저장 전 리사이즈/압축은 아직 하지 않는다는 점을 문서에 명시
## 2026-03-26 v0.1.23
- **홈 게임 정렬 규칙 변경**: 일반 게임 목록은 `상단 고정 순서 → 나머지 최신 생성순`으로 정렬되도록 변경
- **관리자 게임 순서 편집 추가**: 관리자 게임 관리 탭에서 최대 50개의 게임을 상단 고정 목록으로 선택하고 위/아래 순서를 저장할 수 있도록 추가
- **커스텀 티어표 진입점 변경**: 홈 화면의 `직접 티어표 만들기` 카드를 제거하고 우측 상단 버튼형 진입점으로 변경
## 2026-03-26 v0.1.22
- **무제목 저장 규칙 변경**: 제목을 비워두고 저장하면 내부 저장 제목을 `이름 없음 + 날짜` 형식으로 생성하도록 변경
- **무제목 안내 문구 추가**: 제목 입력이 비어 있는 동안 관리자 임의 삭제 가능성을 알리는 경고 문구를 제목 입력 아래에 표시
- **export 보드 확장**: 다운로드용 티어표 이미지는 빈 칸 안내 문구를 숨기고, 약 `1600px` 폭과 더 넉넉한 여백, 하단 작성자/날짜 메타 정보를 포함하도록 조정
## 2026-03-26 v0.1.21
- **아바타 fallback 기준 통일**: 티어표 목록에서 작성자 아바타 이미지가 없을 때 닉네임이 아니라 계정명 기준 첫 글자를 표시하도록 정리
- **저장 완료 모달 추가**: 에디터에서 저장 성공 시 반투명 오버레이와 확인 버튼이 있는 피드백 모달을 표시하도록 추가
- **다운로드 이미지 여백 보강**: PNG export 전용 보드에 외곽 패딩과 배경 여백을 넣어 콘텐츠가 가장자리에 붙어 보이지 않도록 조정
## 2026-03-19 v0.1.20
- **게임 선택 카드 순서 조정**: 홈 화면에서 일반 게임 카드를 먼저 보여주고 `직접 티어표 만들기` 카드는 마지막에 배치
- **게임 카드 3열 레이아웃**: PC 기준 게임 선택 화면 카드를 3열로 재구성하고, 썸네일을 16:9 비율로 통일

22
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
FROM node:20-alpine AS build
WORKDIR /app
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
ARG VITE_API_ORIGIN=https://tmaker.sori.studio
ENV VITE_API_ORIGIN=${VITE_API_ORIGIN}
RUN npm run build
FROM nginx:1.27-alpine
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -2,9 +2,12 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link
rel="icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='16' fill='%230b1220'/%3E%3Cpath d='M18 18h28v8H36v20h-8V26H18z' fill='%23f8fafc'/%3E%3C/svg%3E"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
<title>Tier Maker</title>
</head>
<body>
<div id="app"></div>

38
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,38 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:5179/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location /uploads/ {
proxy_pass http://backend:5179/uploads/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location /health {
proxy_pass http://backend:5179/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}

View File

@@ -58,7 +58,7 @@ async function logout() {
<header class="app-header">
<div class="brand" @click="$router.push('/')">
<span class="brand__title">Tier Maker</span>
<span class="brand__sub">Vue</span>
<span class="brand__sub">by zenn</span>
</div>
<nav class="nav">
<RouterLink to="/" class="nav__link">게임</RouterLink>

View File

@@ -32,6 +32,9 @@ export const api = {
listGames: () => request('/api/games'),
getGame: (gameId) => request(`/api/games/${encodeURIComponent(gameId)}`),
updateAdminGameDisplayOrder: (payload) => request('/api/admin/games/display-order', { method: 'PATCH', body: payload }),
updateAdminGameItem: (gameId, itemId, payload) =>
request(`/api/admin/games/${encodeURIComponent(gameId)}/items/${encodeURIComponent(itemId)}`, { method: 'PATCH', body: payload }),
listAdminCustomItems: ({ q = '', page = 1, limit = 50, orphanOnly = false } = {}) =>
request(
`/api/admin/custom-items?q=${encodeURIComponent(q)}&page=${encodeURIComponent(page)}&limit=${encodeURIComponent(limit)}&orphanOnly=${encodeURIComponent(orphanOnly)}`
@@ -49,6 +52,23 @@ export const api = {
getTierList: (id) => request(`/api/tierlists/${encodeURIComponent(id)}`),
deleteTierList: (id) => request(`/api/tierlists/${encodeURIComponent(id)}`, { method: 'DELETE' }),
saveTierList: (payload) => request('/api/tierlists', { method: 'POST', body: payload }),
uploadTierListThumbnail: async (file) => {
const fd = new FormData()
fd.append('thumbnail', file)
const res = await fetch(toApiUrl('/api/tierlists/thumbnail'), {
method: 'POST',
credentials: 'include',
body: fd,
})
const data = await res.json()
if (!res.ok) {
const err = new Error('request_failed')
err.status = res.status
err.data = data
throw err
}
return data
},
deleteAdminCustomItem: (itemId) => request(`/api/admin/custom-items/${encodeURIComponent(itemId)}`, { method: 'DELETE' }),
deleteAdminUnusedCustomItems: ({ q = '' } = {}) =>
request(`/api/admin/custom-items?q=${encodeURIComponent(q)}`, { method: 'DELETE' }),

View File

@@ -3,7 +3,12 @@ const FALLBACK_API_ORIGIN = 'http://localhost:5179'
export const API_ORIGIN = (import.meta.env.VITE_API_ORIGIN || FALLBACK_API_ORIGIN).replace(/\/+$/, '')
export function toApiUrl(path = '') {
if (!path) return API_ORIGIN
const p = path.startsWith('/') ? path : `/${path}`
// 운영(Nginx 프록시)에서는 같은 도메인/프로토콜로 호출해야
// 세션 쿠키(`Set-Cookie`)가 브라우저에 정상 저장됩니다.
if (import.meta.env.PROD) return p
if (/^https?:\/\//.test(path)) return path
return `${API_ORIGIN}${path.startsWith('/') ? path : `/${path}`}`
return `${API_ORIGIN}${p}`
}

View File

@@ -172,7 +172,7 @@ code {
}
#app {
width: 1126px;
/* width: 1126px; */
max-width: 100%;
margin: 0 auto;
text-align: center;

View File

@@ -1,5 +1,6 @@
<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import Sortable from 'sortablejs'
import { api } from '../lib/api'
import { toApiUrl } from '../lib/runtime'
import { useAuthStore } from '../stores/auth'
@@ -13,6 +14,7 @@ const gameMode = ref('existing')
const games = ref([])
const selectedGameId = ref('')
const selectedGame = ref(null)
const featuredGameIds = ref([])
const customItems = ref([])
const customItemQuery = ref('')
@@ -29,27 +31,37 @@ const success = ref('')
const newGameId = ref('')
const newGameName = ref('')
const uploadLabel = ref('')
const uploadFile = ref(null)
const uploadFiles = ref([])
const thumbFile = ref(null)
const itemPreviewUrl = ref('')
const itemPreviewUrls = ref([])
const isItemDragOver = ref(false)
const thumbPreviewUrl = ref('')
const itemFileInput = ref(null)
const thumbFileInput = ref(null)
const featuredListEl = ref(null)
const featuredSortable = ref(null)
const hasSelectedGame = computed(() => !!selectedGame.value?.game?.id)
const canApplyThumbnail = computed(() => !!thumbFile.value && !!selectedGameId.value)
const canAddItem = computed(() => !!uploadFile.value && !!selectedGameId.value)
const canAddItem = computed(() => uploadFiles.value.length > 0 && !!selectedGameId.value)
const customItemPageCount = computed(() => Math.max(1, Math.ceil(customItemTotal.value / customItemLimit.value)))
const featuredGames = computed(() =>
featuredGameIds.value
.map((gameId) => games.value.find((game) => game.id === gameId))
.filter(Boolean)
)
const availableGamesForFeatured = computed(() => games.value.filter((game) => !featuredGameIds.value.includes(game.id)))
onMounted(async () => {
await auth.refresh()
await Promise.all([refreshGames(), refreshCustomItems(), refreshUsers()])
await syncFeaturedSortable()
})
onUnmounted(() => {
clearPreviewUrl('item')
clearPreviewUrl('thumb')
destroyFeaturedSortable()
})
function resetMessages() {
@@ -66,11 +78,44 @@ async function refreshGames() {
try {
const data = await api.listGames()
games.value = data.games || []
featuredGameIds.value = games.value
.filter((game) => game.displayRank != null)
.sort((a, b) => a.displayRank - b.displayRank)
.map((game) => game.id)
await syncFeaturedSortable()
} catch (e) {
error.value = '게임 목록을 불러오지 못했어요.'
}
}
function destroyFeaturedSortable() {
if (featuredSortable.value) {
featuredSortable.value.destroy()
featuredSortable.value = null
}
}
async function syncFeaturedSortable() {
await nextTick()
destroyFeaturedSortable()
if (!featuredListEl.value) return
featuredSortable.value = Sortable.create(featuredListEl.value, {
animation: 160,
draggable: '[data-featured-id]',
handle: '[data-featured-handle]',
ghostClass: 'ghost',
chosenClass: 'chosen',
onEnd: (evt) => {
if (evt.oldIndex == null || evt.newIndex == null || evt.oldIndex === evt.newIndex) return
const nextIds = [...featuredGameIds.value]
const [moved] = nextIds.splice(evt.oldIndex, 1)
nextIds.splice(evt.newIndex, 0, moved)
featuredGameIds.value = nextIds
},
})
}
async function refreshCustomItems() {
if (!auth.user?.isAdmin) return
try {
@@ -106,8 +151,7 @@ async function refreshUsers() {
}
function resetUploadState() {
uploadLabel.value = ''
uploadFile.value = null
uploadFiles.value = []
thumbFile.value = null
resetFileInput('item')
resetFileInput('thumb')
@@ -126,9 +170,9 @@ function setGameMode(mode) {
}
function clearPreviewUrl(type) {
if (type === 'item' && itemPreviewUrl.value) {
URL.revokeObjectURL(itemPreviewUrl.value)
itemPreviewUrl.value = ''
if (type === 'item' && itemPreviewUrls.value.length) {
itemPreviewUrls.value.forEach((url) => URL.revokeObjectURL(url))
itemPreviewUrls.value = []
}
if (type === 'thumb' && thumbPreviewUrl.value) {
URL.revokeObjectURL(thumbPreviewUrl.value)
@@ -152,7 +196,13 @@ async function loadGame() {
try {
const data = await api.getGame(selectedGameId.value)
selectedGame.value = data
selectedGame.value = {
...data,
items: (data.items || []).map((item) => ({
...item,
draftLabel: item.label,
})),
}
} catch (e) {
error.value = '게임 정보를 불러오지 못했어요.'
}
@@ -187,9 +237,46 @@ function onThumb(event) {
}
function onFile(event) {
uploadFile.value = event.target.files && event.target.files[0] ? event.target.files[0] : null
handleItemFiles(event.target.files)
}
function handleItemFiles(fileList) {
const files = Array.from(fileList || []).filter((file) => (file.type || '').startsWith('image/'))
uploadFiles.value = files
clearPreviewUrl('item')
if (uploadFile.value) itemPreviewUrl.value = URL.createObjectURL(uploadFile.value)
if (!files.length) return
itemPreviewUrls.value = files.map((file) => URL.createObjectURL(file))
resetFileInput('item')
}
function openItemFilePicker() {
itemFileInput.value?.click()
}
function clearItemFiles() {
uploadFiles.value = []
clearPreviewUrl('item')
resetFileInput('item')
}
function onItemDragEnter(event) {
event.preventDefault()
isItemDragOver.value = true
}
function onItemDragOver(event) {
event.preventDefault()
isItemDragOver.value = true
}
function onItemDragLeave(event) {
if (event.currentTarget === event.target) isItemDragOver.value = false
}
function onItemDrop(event) {
event.preventDefault()
isItemDragOver.value = false
handleItemFiles(event.dataTransfer?.files)
}
async function uploadThumbnail() {
@@ -222,15 +309,15 @@ async function uploadThumbnail() {
async function uploadItem() {
resetMessages()
if (!uploadFile.value || !selectedGameId.value) {
if (!uploadFiles.value.length || !selectedGameId.value) {
error.value = '아이템 파일을 선택해주세요.'
return
}
try {
const fd = new FormData()
fd.append('label', uploadLabel.value || 'item')
fd.append('image', uploadFile.value)
uploadFiles.value.forEach((file) => fd.append('images', file))
const uploadCount = uploadFiles.value.length
const res = await fetch(toApiUrl(`/api/admin/games/${encodeURIComponent(selectedGameId.value)}/images`), {
method: 'POST',
credentials: 'include',
@@ -240,7 +327,7 @@ async function uploadItem() {
resetUploadState()
await loadGame()
success.value = '게임 기본 아이템이 추가됐어요.'
success.value = `게임 기본 아이템 ${uploadCount}개 추가를 완료했어요.`
} catch (e) {
error.value = '아이템 추가 실패(관리자 권한/파일 크기 확인)'
}
@@ -265,6 +352,24 @@ async function removeGameItem(itemId) {
}
}
async function saveGameItemLabel(item) {
resetMessages()
if (!selectedGameId.value) return
const nextLabel = (item.draftLabel || '').trim()
if (!nextLabel) {
error.value = '아이템 이름을 입력해주세요.'
return
}
try {
await api.updateAdminGameItem(selectedGameId.value, item.id, { label: nextLabel })
await loadGame()
success.value = '기본 아이템 이름을 수정했어요.'
} catch (e) {
error.value = '기본 아이템 이름 수정에 실패했어요.'
}
}
async function removeGame() {
resetMessages()
if (!selectedGameId.value || !selectedGame.value?.game) return
@@ -416,13 +521,56 @@ function fmt(ts) {
minute: '2-digit',
})
}
function addFeaturedGame(gameId) {
resetMessages()
if (!gameId || featuredGameIds.value.includes(gameId)) return
if (featuredGameIds.value.length >= 50) {
error.value = '상단 고정 게임은 최대 50개까지만 설정할 수 있어요.'
return
}
featuredGameIds.value = [...featuredGameIds.value, gameId]
syncFeaturedSortable()
}
function removeFeaturedGame(gameId) {
resetMessages()
featuredGameIds.value = featuredGameIds.value.filter((id) => id !== gameId)
syncFeaturedSortable()
}
function moveFeaturedGame(gameId, direction) {
const currentIndex = featuredGameIds.value.indexOf(gameId)
const nextIndex = currentIndex + direction
if (currentIndex < 0 || nextIndex < 0 || nextIndex >= featuredGameIds.value.length) return
const nextIds = [...featuredGameIds.value]
const [moved] = nextIds.splice(currentIndex, 1)
nextIds.splice(nextIndex, 0, moved)
featuredGameIds.value = nextIds
syncFeaturedSortable()
}
async function saveFeaturedOrder() {
resetMessages()
try {
const data = await api.updateAdminGameDisplayOrder({ gameIds: featuredGameIds.value })
games.value = data.games || []
featuredGameIds.value = games.value
.filter((game) => game.displayRank != null)
.sort((a, b) => a.displayRank - b.displayRank)
.map((game) => game.id)
success.value = '홈 화면 게임 순서를 저장했어요.'
} catch (e) {
error.value = '게임 순서 저장에 실패했어요.'
}
}
</script>
<template>
<section class="wrap">
<h2 class="title">관리자</h2>
<!-- <h2 class="title">관리자</h2> -->
<div class="card">
<div class="desc">기능이 많아진 만큼 관리 영역을 게임, 아이템, 회원 관리로 나눠서 정리합니다.</div>
<!-- <div class="desc">기능이 많아진 만큼 관리 영역을 게임, 아이템, 회원 관리로 나눠서 정리합니다.</div> -->
<div v-if="!auth.user" class="warn">로그인이 필요해요.</div>
<div v-else-if="!isAdmin" class="warn"> 계정은 관리자 권한이 없어요.</div>
@@ -437,6 +585,56 @@ function fmt(ts) {
<div v-if="success" class="success">{{ success }}</div>
<template v-if="activeTab === 'games'">
<div class="panel">
<div class="sectionHeader">
<div>
<div class="panel__title"> 화면 상단 고정 순서</div>
<div class="hint hint--tight">여기에 넣은 게임은 지정한 순서대로 먼저 노출되고, 나머지 게임은 최근 생성순으로 뒤에 이어집니다. 최대 50개까지 설정할 있어요.</div>
</div>
<button class="btn btn--primary" @click="saveFeaturedOrder">순서 저장</button>
</div>
<div class="featuredOrderPanel">
<div class="featuredOrderPanel__list">
<div class="section__title">상단 고정 목록</div>
<div v-if="!featuredGames.length" class="hint">아직 상단 고정 게임이 없어요.</div>
<div v-else ref="featuredListEl" class="featuredList">
<article v-for="(game, index) in featuredGames" :key="game.id" class="featuredCard" :data-featured-id="game.id">
<div class="featuredCard__meta">
<span class="featuredCard__rank">{{ index + 1 }}</span>
<div>
<div class="featuredCard__title">{{ game.name }}</div>
<div class="featuredCard__id">{{ game.id }}</div>
</div>
</div>
<div class="featuredCard__actions">
<button class="btn btn--ghost btn--small" data-featured-handle>드래그</button>
<button class="btn btn--ghost btn--small" :disabled="index === 0" @click="moveFeaturedGame(game.id, -1)">위로</button>
<button class="btn btn--ghost btn--small" :disabled="index === featuredGames.length - 1" @click="moveFeaturedGame(game.id, 1)">아래로</button>
<button class="btn btn--danger btn--small" @click="removeFeaturedGame(game.id)">제외</button>
</div>
</article>
</div>
</div>
<div class="featuredOrderPanel__picker">
<div class="section__title">게임 추가</div>
<div class="featuredPickerList">
<button
v-for="game in availableGamesForFeatured"
:key="game.id"
class="featuredPickerItem"
:disabled="featuredGameIds.length >= 50"
@click="addFeaturedGame(game.id)"
>
<span>{{ game.name }}</span>
<span class="featuredPickerItem__id">{{ game.id }}</span>
</button>
</div>
</div>
</div>
</div>
<div class="modeTabs">
<button class="modeTab" :class="{ 'modeTab--active': gameMode === 'existing' }" @click="setGameMode('existing')">
등록된 게임 선택
@@ -448,12 +646,12 @@ function fmt(ts) {
<div class="panel panel--compact">
<template v-if="gameMode === 'existing'">
<div class="panel__title">등록된 게임 선택</div>
<!-- <div class="panel__title">등록된 게임 선택</div> -->
<select v-model="selectedGameId" class="select" @change="loadGame">
<option value="">게임을 선택해주세요</option>
<option v-for="game in games" :key="game.id" :value="game.id">{{ game.name }} ({{ game.id }})</option>
</select>
<div class="hint"> 영역은 게임 자체와 관리자 기본 아이템만 관리합니다. 여기서 아이템을 삭제해도 사용자 커스텀 이미지는 삭제되지 않아요.</div>
<!-- <div class="hint"> 영역은 게임 자체와 관리자 기본 아이템만 관리합니다. 여기서 아이템을 삭제해도 사용자 커스텀 이미지는 삭제되지 않아요.</div> -->
</template>
<template v-else>
@@ -493,16 +691,36 @@ function fmt(ts) {
<div class="section__title">기본 아이템 추가</div>
<div class="itemComposer">
<div class="itemComposer__form">
<input v-model="uploadLabel" class="input input--compact" placeholder="아이템 이름" />
<input ref="itemFileInput" type="file" accept="image/*" class="inputFile inputFile--tight" @change="onFile" />
<button class="btn" :disabled="!canAddItem" @click="uploadItem">아이템 추가</button>
<input ref="itemFileInput" type="file" accept="image/*" multiple class="srOnlyInput" @change="onFile" />
<div
class="dropZone"
:class="{ 'dropZone--active': isItemDragOver }"
@dragenter="onItemDragEnter"
@dragover="onItemDragOver"
@dragleave="onItemDragLeave"
@drop="onItemDrop"
>
<div class="dropZone__title">이미지를 드래그해서 기본 아이템으로 추가</div>
<div class="dropZone__desc">여러 파일을 번에 올릴 있고, 저장 라벨은 파일명으로 자동 생성됩니다.</div>
<div class="dropZone__actions">
<button class="btn btn--ghost btn--small" type="button" @click="openItemFilePicker">파일 선택</button>
<button class="btn btn--danger btn--small" type="button" :disabled="!uploadFiles.length" @click="clearItemFiles">선택 비우기</button>
</div>
</div>
<button class="btn" :disabled="!canAddItem" @click="uploadItem">
아이템 {{ uploadFiles.length || 0 }} 추가
</button>
</div>
<div class="itemPreviewCard">
<div class="itemPreviewFrame">
<img v-if="itemPreviewUrl" class="itemPreviewImage" :src="itemPreviewUrl" alt="item preview" />
<div v-else class="itemPreviewEmpty">이미지를 선택해주세요</div>
<div v-if="itemPreviewUrls.length" class="itemPreviewGrid">
<div v-for="(previewUrl, index) in itemPreviewUrls.slice(0, 6)" :key="previewUrl" class="itemPreviewFrame">
<img class="itemPreviewImage" :src="previewUrl" :alt="uploadFiles[index]?.name || 'item preview'" />
</div>
</div>
<div v-else class="itemPreviewEmpty">선택한 기본 아이템 미리보기가 여기에 표시됩니다.</div>
<div class="thumbLabel thumbLabel--preview">
{{ uploadFiles.length ? `선택된 파일 ${uploadFiles.length}` : '아직 선택된 파일이 없어요.' }}
</div>
<div class="thumbLabel thumbLabel--preview">{{ uploadLabel || '아이템 이름 미리보기' }}</div>
</div>
</div>
</section>
@@ -514,8 +732,11 @@ function fmt(ts) {
<div v-else class="thumbGrid">
<div v-for="item in selectedGame.items" :key="item.id" class="thumbCard">
<img class="thumb thumb--game" :src="toApiUrl(item.src)" :alt="item.label" />
<div class="thumbLabel">{{ item.label }}</div>
<button class="btn btn--danger btn--small" @click="removeGameItem(item.id)">아이템 삭제</button>
<input v-model="item.draftLabel" class="input input--labelEdit" placeholder="아이템 이름" />
<div class="thumbCard__actions">
<button class="btn btn--ghost btn--small" @click="saveGameItemLabel(item)">이름 저장</button>
<button class="btn btn--danger btn--small" @click="removeGameItem(item.id)">아이템 삭제</button>
</div>
</div>
</div>
</div>
@@ -692,7 +913,94 @@ function fmt(ts) {
padding: 14px;
}
.panel--compact {
max-width: 760px;
max-width: 480px;
}
.featuredOrderPanel {
margin-top: 14px;
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(260px, 0.95fr);
gap: 16px;
}
.featuredOrderPanel__list,
.featuredOrderPanel__picker {
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(255, 255, 255, 0.03);
border-radius: 16px;
padding: 14px;
}
.featuredList,
.featuredPickerList {
margin-top: 10px;
display: grid;
gap: 10px;
max-height: 420px;
overflow: auto;
}
.featuredCard {
display: flex;
gap: 12px;
justify-content: space-between;
align-items: center;
padding: 12px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.18);
}
.featuredCard__meta {
display: flex;
gap: 12px;
align-items: center;
min-width: 0;
}
.featuredCard__rank {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 999px;
background: rgba(96, 165, 250, 0.18);
font-weight: 900;
flex: 0 0 auto;
}
.featuredCard__title {
font-weight: 900;
}
.featuredCard__id {
margin-top: 4px;
opacity: 0.68;
font-size: 12px;
word-break: break-all;
}
.featuredCard__actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.featuredCard [data-featured-handle] {
cursor: grab;
}
.featuredPickerItem {
width: 100%;
display: flex;
gap: 10px;
justify-content: space-between;
align-items: center;
padding: 12px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.16);
color: rgba(255, 255, 255, 0.92);
cursor: pointer;
text-align: left;
}
.featuredPickerItem:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.featuredPickerItem__id {
opacity: 0.64;
font-size: 12px;
}
.panel__title,
.section__title {
@@ -761,11 +1069,14 @@ function fmt(ts) {
background: rgba(0, 0, 0, 0.18);
color: rgba(255, 255, 255, 0.92);
outline: none;
margin-top: 10px;
/* margin-top: 10px; */
}
.input--compact {
max-width: 320px;
}
.input--labelEdit {
margin-top: 10px;
}
.hint {
margin-top: 10px;
opacity: 0.78;
@@ -781,6 +1092,17 @@ function fmt(ts) {
.inputFile--tight {
margin-top: 0;
}
.srOnlyInput {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.btn {
font-size: 12px;
margin-top: 12px;
@@ -794,6 +1116,17 @@ function fmt(ts) {
text-align: center;
text-decoration: none;
}
.btn--small {
margin-top: 0;
padding: 8px 10px;
font-size: 11px;
}
.ghost {
opacity: 0.4;
}
.chosen {
outline: 2px solid rgba(96, 165, 250, 0.45);
}
.btn:disabled {
cursor: not-allowed;
opacity: 0.45;
@@ -854,20 +1187,53 @@ function fmt(ts) {
gap: 12px;
align-items: start;
}
.dropZone {
padding: 18px;
border-radius: 16px;
border: 1px dashed rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.03);
transition:
border-color 0.16s ease,
background 0.16s ease,
transform 0.16s ease;
}
.dropZone--active {
border-color: rgba(96, 165, 250, 0.56);
background: rgba(96, 165, 250, 0.08);
transform: translateY(-1px);
}
.dropZone__title {
font-weight: 900;
}
.dropZone__desc {
margin-top: 8px;
font-size: 13px;
opacity: 0.74;
line-height: 1.5;
}
.dropZone__actions {
margin-top: 12px;
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.itemPreviewCard {
padding: 10px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.04);
}
.itemPreviewGrid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.itemPreviewFrame {
width: min(100%, 192px);
aspect-ratio: 1 / 1;
border-radius: 12px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(0, 0, 0, 0.18);
margin: 0 auto;
}
.itemPreviewImage {
width: 100%;
@@ -875,12 +1241,13 @@ function fmt(ts) {
object-fit: cover;
}
.itemPreviewEmpty {
width: 100%;
height: 100%;
min-height: 192px;
display: grid;
place-items: center;
color: rgba(255, 255, 255, 0.62);
font-size: 13px;
text-align: center;
line-height: 1.5;
}
.thumbGrid {
margin-top: 12px;
@@ -914,6 +1281,11 @@ function fmt(ts) {
opacity: 0.9;
word-break: break-word;
}
.thumbCard__actions {
margin-top: 10px;
display: grid;
gap: 8px;
}
.thumbLabel--preview {
text-align: center;
}
@@ -1039,13 +1411,14 @@ function fmt(ts) {
margin-top: 0;
}
@media (max-width: 980px) {
.featuredOrderPanel,
.section--topGrid,
.toolbar,
.itemComposer {
grid-template-columns: 1fr;
}
.itemPreviewCard {
max-width: 192px;
max-width: none;
}
}
@media (max-width: 640px) {

View File

@@ -34,7 +34,11 @@ function avatarSrcOf(tierList) {
}
function avatarFallbackOf(tierList) {
return displayNameOf(tierList).trim().charAt(0).toUpperCase() || '?'
return (tierList.authorAccountName || 'u').trim().charAt(0).toUpperCase() || '?'
}
function tierListThumbnailUrl(tierList) {
return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}
onMounted(async () => {
@@ -78,6 +82,10 @@ function openTierList(id) {
<div v-if="tierLists.length === 0" class="empty">아직 공개 티어표가 없어요.</div>
<div v-else class="list">
<button v-for="t in tierLists" :key="t.id" class="row" @click="openTierList(t.id)">
<div class="row__thumbWrap">
<img v-if="tierListThumbnailUrl(t)" class="row__thumb" :src="tierListThumbnailUrl(t)" :alt="t.title" />
<div v-else class="row__thumbPlaceholder"></div>
</div>
<div class="row__head">
<div class="row__title">{{ t.title }}</div>
<div class="row__author">
@@ -153,7 +161,7 @@ function openTierList(id) {
}
.row {
text-align: left;
padding: 14px;
padding: 0;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.04);
@@ -164,10 +172,28 @@ function openTierList(id) {
gap: 10px;
align-content: start;
min-height: 168px;
overflow: hidden;
}
.row:hover {
background: rgba(255, 255, 255, 0.05);
}
.row__thumbWrap {
width: 100%;
aspect-ratio: 16 / 9;
background: rgba(255, 255, 255, 0.03);
}
.row__thumb {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.row__thumbPlaceholder {
width: 100%;
height: 100%;
background:
linear-gradient(135deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
}
.row__title {
font-weight: 800;
min-width: 0;
@@ -175,6 +201,7 @@ function openTierList(id) {
line-height: 1.35;
}
.row__head {
padding: 14px 14px 0;
display: grid;
gap: 12px;
align-content: start;
@@ -202,6 +229,7 @@ function openTierList(id) {
font-weight: 900;
}
.row__meta {
padding: 0 14px 14px;
opacity: 0.78;
font-size: 13px;
margin-top: auto;

View File

@@ -41,11 +41,12 @@ function thumbUrl(g) {
</script>
<template>
<section class="hero">
<h1 class="hero__title">티어표 메이커</h1>
<p class="hero__desc">
게임을 선택하면 티어표를 만들거나, 다른 사람들이 올린 티어표를 있어요.
</p>
<section class="topBar">
<div class="topBar__copy">
<h1 class="topBar__title">게임 선택</h1>
<p class="topBar__desc">관리자 고정 순서가 있으면 먼저 보여주고, 게임은 최근 생성순으로 정렬됩니다.</p>
</div>
<button class="customTierBtn" @click="goFreeform">{{ auth.user ? '커스텀 티어표 만들기' : '로그인 커스텀 티어표 만들기' }}</button>
</section>
<div v-if="error" class="error">{{ error }}</div>
@@ -57,30 +58,41 @@ function thumbUrl(g) {
</div>
<div class="card__title">{{ g.name }}</div>
</button>
<button class="card card--freeform" @click="goFreeform">
<div class="thumbWrap thumbWrap--freeform">
<div class="thumbFallback">+</div>
</div>
<div class="card__eyebrow">{{ auth.user ? '템플릿 없이 시작' : '로그인 후 작성 가능' }}</div>
<div class="card__title">직접 티어표 만들기</div>
</button>
</section>
</template>
<style scoped>
.hero {
padding: 18px 2px 14px;
.topBar {
display: flex;
gap: 16px;
justify-content: space-between;
align-items: flex-start;
flex-wrap: wrap;
margin-top: 4px;
}
.hero__title {
font-size: 34px;
letter-spacing: -0.03em;
margin: 0 0 8px;
.topBar__copy {
display: grid;
gap: 6px;
}
.hero__desc {
.topBar__title {
margin: 0;
opacity: 0.86;
font-size: 30px;
letter-spacing: -0.03em;
}
.topBar__desc {
margin: 0;
opacity: 0.78;
line-height: 1.5;
}
.customTierBtn {
padding: 12px 16px;
border-radius: 14px;
border: 1px solid rgba(96, 165, 250, 0.28);
background: linear-gradient(135deg, rgba(96, 165, 250, 0.2), rgba(16, 185, 129, 0.16));
color: rgba(255, 255, 255, 0.96);
font-weight: 900;
cursor: pointer;
}
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
@@ -110,9 +122,6 @@ function thumbUrl(g) {
background: rgba(255, 255, 255, 0.07);
border-color: rgba(255, 255, 255, 0.18);
}
.card--freeform {
background: linear-gradient(135deg, rgba(96, 165, 250, 0.12), rgba(16, 185, 129, 0.12));
}
.thumbWrap {
width: 100%;
aspect-ratio: 16 / 9;
@@ -123,11 +132,6 @@ function thumbUrl(g) {
display: grid;
place-items: center;
}
.thumbWrap--freeform {
background:
radial-gradient(circle at top, rgba(96, 165, 250, 0.18), transparent 50%),
rgba(0, 0, 0, 0.18);
}
.thumb {
width: 100%;
height: 100%;
@@ -142,14 +146,13 @@ function thumbUrl(g) {
font-weight: 800;
letter-spacing: -0.02em;
}
.card__eyebrow {
font-size: 12px;
font-weight: 800;
opacity: 0.7;
letter-spacing: 0.04em;
text-transform: uppercase;
}
@media (max-width: 720px) {
.topBar {
align-items: stretch;
}
.customTierBtn {
width: 100%;
}
.grid {
grid-template-columns: 1fr;
}

View File

@@ -27,7 +27,11 @@ function avatarSrcOf(tierList) {
}
function avatarFallbackOf(tierList) {
return displayNameOf(tierList).trim().charAt(0).toUpperCase() || '?'
return (tierList.authorAccountName || 'u').trim().charAt(0).toUpperCase() || '?'
}
function tierListThumbnailUrl(tierList) {
return tierList.thumbnailSrc ? toApiUrl(tierList.thumbnailSrc) : ''
}
onMounted(async () => {
@@ -68,6 +72,10 @@ async function removeList(t) {
<div v-else class="list">
<article v-for="t in myLists" :key="t.id" class="row">
<button class="row__body" @click="openList(t)">
<div class="row__thumbWrap">
<img v-if="tierListThumbnailUrl(t)" class="row__thumb" :src="tierListThumbnailUrl(t)" :alt="t.title" />
<div v-else class="row__thumbPlaceholder"></div>
</div>
<div class="row__head">
<div class="row__title">{{ t.title }}</div>
<div class="row__author">
@@ -125,18 +133,17 @@ async function removeList(t) {
}
.list {
display: grid;
gap: 10px;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.row {
display: flex;
display: grid;
gap: 10px;
justify-content: space-between;
align-items: center;
padding: 12px 14px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.10);
background: rgba(0, 0, 0, 0.16);
color: rgba(255, 255, 255, 0.92);
overflow: hidden;
}
.row__body {
flex: 1 1 auto;
@@ -147,12 +154,32 @@ async function removeList(t) {
background: transparent;
color: inherit;
padding: 0;
display: grid;
gap: 10px;
}
.row__thumbWrap {
width: 100%;
aspect-ratio: 16 / 9;
background: rgba(255, 255, 255, 0.03);
}
.row__thumb {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.row__thumbPlaceholder {
width: 100%;
height: 100%;
background:
linear-gradient(135deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
}
.row__title {
font-weight: 900;
min-width: 0;
}
.row__head {
padding: 0 14px;
display: flex;
gap: 12px;
align-items: center;
@@ -181,6 +208,7 @@ async function removeList(t) {
font-weight: 900;
}
.row__meta {
padding: 0 14px;
margin-top: 6px;
opacity: 0.76;
font-size: 13px;
@@ -188,5 +216,16 @@ async function removeList(t) {
.link--danger {
background: rgba(239, 68, 68, 0.14);
border-color: rgba(239, 68, 68, 0.28);
margin: 0 14px 14px;
}
@media (max-width: 1100px) {
.list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 720px) {
.list {
grid-template-columns: 1fr;
}
}
</style>

View File

@@ -26,13 +26,21 @@ const pool = ref([])
const itemsById = ref({})
const title = ref('')
const thumbnailSrc = ref('')
const pendingThumbnailFile = ref(null)
const thumbnailPreviewUrl = ref('')
const description = ref('')
const isPublic = ref(true)
const error = ref('')
const isSaving = ref(false)
const isExporting = ref(false)
const isSaveModalOpen = ref(false)
const ownerId = ref('')
const authorName = ref('')
const authorAccountName = ref('')
const updatedAt = ref(0)
const isDragActive = ref(false)
const iconSize = ref(80)
const boardEl = ref(null)
const exportBoardEl = ref(null)
@@ -40,12 +48,60 @@ const groupListEl = ref(null)
const poolEl = ref(null)
const groupDropEls = ref({})
const fileEl = ref(null)
const thumbnailFileEl = ref(null)
const groupSortable = ref(null)
const poolSortable = ref(null)
const dropSortables = ref([])
const isNewTierList = computed(() => tierListId.value === 'new')
const canEdit = computed(() => !!auth.user && (!ownerId.value || ownerId.value === auth.user.id))
const iconSizeOptions = [48, 64, 80, 96, 112]
const hasCustomTitle = computed(() => !!(title.value || '').trim())
const fallbackTimestamp = computed(() => (updatedAt.value ? updatedAt.value : Date.now()))
const effectiveAuthorName = computed(() => {
const currentNickname = (auth.user?.nickname || '').trim()
if (currentNickname) return currentNickname
if ((authorName.value || '').trim()) return authorName.value.trim()
const currentEmail = (auth.user?.email || '').trim()
if (currentEmail) return currentEmail.split('@')[0] || currentEmail
return (authorAccountName.value || '').trim() || 'unknown'
})
const effectiveTitle = computed(() => {
const customTitle = (title.value || '').trim()
if (customTitle) return customTitle
return (gameName.value || gameId.value || 'Tier Maker').trim()
})
const displayThumbnailUrl = computed(() => thumbnailPreviewUrl.value || (thumbnailSrc.value ? resolveItemSrc({ src: thumbnailSrc.value }) : ''))
const untitledWarning = computed(
() =>
canEdit.value &&
!hasCustomTitle.value &&
'제목 없이 저장된 티어표는 무분별한 도배 방지를 위해 관리자에 의해 임의 삭제될 수 있어요.'
)
function formatTitleDate(ts) {
const date = new Date(ts)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}`
}
function formatExportDate(ts) {
return new Date(ts).toLocaleString('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
function setIconSize(nextSize) {
iconSize.value = nextSize
}
function setGroupDropEl(groupId, el) {
if (!el) {
@@ -186,6 +242,31 @@ function openFile() {
fileEl.value?.click()
}
function openThumbnailFile() {
if (!canEdit.value) return
thumbnailFileEl.value?.click()
}
function onThumbnailChange(event) {
const file = event.target.files?.[0]
if (thumbnailPreviewUrl.value) {
URL.revokeObjectURL(thumbnailPreviewUrl.value)
thumbnailPreviewUrl.value = ''
}
pendingThumbnailFile.value = file || null
if (file) thumbnailPreviewUrl.value = URL.createObjectURL(file)
event.target.value = ''
}
function clearThumbnail() {
if (thumbnailPreviewUrl.value) {
URL.revokeObjectURL(thumbnailPreviewUrl.value)
thumbnailPreviewUrl.value = ''
}
pendingThumbnailFile.value = null
thumbnailSrc.value = ''
}
function onFileChange(e) {
const files = Array.from(e.target.files || [])
if (!files.length) return
@@ -218,13 +299,13 @@ async function downloadImage() {
try {
const targetEl = exportBoardEl.value || boardEl.value
const blob = await htmlToImage.toBlob(targetEl, { pixelRatio: 2, backgroundColor: '#0b1220' })
const blob = await htmlToImage.toBlob(targetEl, { pixelRatio: 1.5, backgroundColor: '#0b1220' })
if (!blob) throw new Error('image_export_failed')
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${(title.value || gameName.value || 'tierlist').trim()}.png`
a.download = `${effectiveTitle.value.trim()}.png`
document.body.appendChild(a)
a.click()
a.remove()
@@ -271,12 +352,25 @@ async function uploadPendingCustomItems() {
}
}
async function uploadPendingThumbnail() {
if (!pendingThumbnailFile.value) return thumbnailSrc.value || ''
const data = await api.uploadTierListThumbnail(pendingThumbnailFile.value)
if (thumbnailPreviewUrl.value) {
URL.revokeObjectURL(thumbnailPreviewUrl.value)
thumbnailPreviewUrl.value = ''
}
pendingThumbnailFile.value = null
thumbnailSrc.value = data.thumbnailSrc || ''
return thumbnailSrc.value
}
function buildPayload(existingId) {
const finalTitle = (title.value || '').trim() || `${(gameName.value || gameId.value).trim()} 티어표`
const finalTitle = effectiveTitle.value
return {
id: existingId || undefined,
gameId: gameId.value,
title: finalTitle,
thumbnailSrc: thumbnailSrc.value || '',
description: (description.value || '').trim(),
isPublic: !!isPublic.value,
groups: groups.value.map((g) => ({ id: g.id, name: g.name, itemIds: g.itemIds })),
@@ -289,9 +383,14 @@ async function save() {
isSaving.value = true
try {
await uploadPendingCustomItems()
await uploadPendingThumbnail()
const payload = buildPayload(tierListId.value && tierListId.value !== 'new' ? tierListId.value : null)
const res = await api.saveTierList(payload)
if (tierListId.value === 'new') history.replaceState({}, '', `/editor/${gameId.value}/${res.tierList.id}`)
updatedAt.value = Number(res.tierList?.updatedAt || Date.now())
authorName.value = res.tierList?.authorName || effectiveAuthorName.value
authorAccountName.value = res.tierList?.authorAccountName || authorAccountName.value
isSaveModalOpen.value = true
} catch (e) {
error.value = '저장 실패: 로그인 상태인지 확인해주세요.'
} finally {
@@ -299,6 +398,10 @@ async function save() {
}
}
function closeSaveModal() {
isSaveModalOpen.value = false
}
async function removeTierList() {
if (!canEdit.value || isNewTierList.value) return
error.value = ''
@@ -315,6 +418,8 @@ async function removeTierList() {
onMounted(() => {
;(async () => {
await auth.refresh()
authorName.value = (auth.user?.nickname || '').trim()
authorAccountName.value = ((auth.user?.email || '').trim().split('@')[0] || '').trim()
if (isNewTierList.value && !auth.user) {
router.replace(`/login?redirect=/editor/${gameId.value}/new`)
@@ -344,8 +449,12 @@ onMounted(() => {
const t = res.tierList
ownerId.value = t.authorId
title.value = t.title
thumbnailSrc.value = t.thumbnailSrc || ''
description.value = t.description || ''
isPublic.value = !!t.isPublic
authorName.value = t.authorName || ''
authorAccountName.value = t.authorAccountName || ''
updatedAt.value = Number(t.updatedAt || 0)
groups.value = t.groups
const map = {}
;(t.pool || []).forEach((it) => (map[it.id] = it))
@@ -366,28 +475,48 @@ onMounted(() => {
})
onUnmounted(() => {
if (thumbnailPreviewUrl.value) URL.revokeObjectURL(thumbnailPreviewUrl.value)
destroySortables()
})
</script>
<template>
<section class="head">
<div class="head__meta">
<div class="kicker">{{ gameName || gameId }}</div>
<input v-model="title" class="titleInput" placeholder="티어표 이름을 입력하세요" :readonly="!canEdit" />
<input
v-model="description"
class="descInput"
placeholder="설명(선택): 이 티어표의 기준/룰"
:readonly="!canEdit"
/>
<div class="hint">
<template v-if="canEdit">
그룹 이름/순서 변경과 아이템 드래그&드롭이 가능합니다. 저장하려면 <b>저장</b> 누르세요.
</template>
<template v-else>
공개된 티어표를 보는 중입니다. 로그인한 작성자만 수정할 있어요.
</template>
<div class="heroCard">
<div class="heroCard__main">
<input v-model="title" class="titleInput" placeholder="티어표 이름을 입력하세요" :readonly="!canEdit" />
<div v-if="untitledWarning" class="titleNotice">{{ untitledWarning }}</div>
<input
v-model="description"
class="descInput"
placeholder="설명(선택): 이 티어표의 기준/룰"
:readonly="!canEdit"
/>
<div class="hint">
<template v-if="canEdit">
그룹 이름/순서 변경과 아이템 드래그&드롭이 가능합니다. 저장하려면 <b>저장</b> 누르세요.
</template>
<template v-else>
공개된 티어표를 보는 중입니다. 로그인한 작성자만 수정할 있어요.
</template>
</div>
</div>
<div class="heroCard__side">
<div class="thumbComposer">
<input ref="thumbnailFileEl" type="file" accept="image/*" class="hidden" @change="onThumbnailChange" />
<div class="thumbComposer__header">
<div class="thumbComposer__eyebrow">대표 썸네일</div>
<div class="thumbComposer__caption">목록 카드 상단에 표시됩니다.</div>
</div>
<div class="thumbComposer__preview">
<img v-if="displayThumbnailUrl" class="thumbComposer__image" :src="displayThumbnailUrl" alt="썸네일 미리보기" />
<div v-else class="thumbComposer__empty">썸네일 없음</div>
</div>
<div v-if="canEdit" class="thumbComposer__actions">
<button class="btn btn--ghost thumbComposer__button" @click="openThumbnailFile">썸네일 선택</button>
<button class="btn btn--danger thumbComposer__button" :disabled="!pendingThumbnailFile && !thumbnailSrc" @click="clearThumbnail">제거</button>
</div>
</div>
</div>
</div>
<div class="actions">
@@ -407,13 +536,39 @@ onUnmounted(() => {
<div v-if="error" class="error">{{ error }}</div>
<section class="layout">
<div v-if="isSaveModalOpen" class="modalOverlay" @click.self="closeSaveModal">
<div class="modalCard" role="dialog" aria-modal="true" aria-labelledby="saveModalTitle">
<div id="saveModalTitle" class="modalCard__title">저장 완료</div>
<div class="modalCard__desc">티어표가 저장되었어요. 이어서 수정한 다시 저장할 수도 있어요.</div>
<div class="modalCard__actions">
<button class="btn btn--save" @click="closeSaveModal">확인</button>
</div>
</div>
</div>
<section class="layout" :style="{ '--thumb-size': `${iconSize}px` }">
<div ref="boardEl" class="board">
<div v-if="canEdit && !isExporting" class="boardTools">
<button class="btn btn--ghost" @click="addGroup">티어 추가</button>
<div class="boardTools__left">
<button class="btn btn--ghost" @click="addGroup">티어 추가</button>
</div>
<div class="boardTools__right">
<span class="boardTools__label">아이콘 크기</span>
<div class="sizePicker">
<button
v-for="size in iconSizeOptions"
:key="size"
class="sizePicker__button"
:class="{ 'sizePicker__button--active': iconSize === size }"
@click="setIconSize(size)"
>
{{ size }}
</button>
</div>
</div>
</div>
<div ref="exportBoardEl" class="exportBoard" :class="{ 'exportBoard--active': isExporting }">
<div v-if="isExporting" class="exportBoard__title">{{ title || gameName || gameId }}</div>
<div v-if="isExporting" class="exportBoard__title">{{ effectiveTitle }}</div>
<div v-if="isExporting && description" class="exportBoard__description">{{ description }}</div>
<div ref="groupListEl" class="rows">
<div v-for="g in groups" :key="g.id" class="row">
@@ -433,13 +588,17 @@ onUnmounted(() => {
:data-group-id="g.id"
:ref="(el) => setGroupDropEl(g.id, el)"
>
<div class="row__empty" v-show="g.itemIds.length === 0">여기로 드래그해서 배치</div>
<div v-if="!isExporting" class="row__empty" v-show="g.itemIds.length === 0">여기로 드래그해서 배치</div>
<div v-for="id in g.itemIds" :key="id" class="cell" :data-item-id="id">
<img :src="resolveItemSrc(itemsById[id])" class="thumb" :alt="itemsById[id]?.label || id" />
</div>
</div>
</div>
</div>
<div v-if="isExporting" class="exportBoard__footer">
<span>{{ effectiveAuthorName }}</span>
<span>{{ formatExportDate(fallbackTimestamp) }}</span>
</div>
</div>
</div>
@@ -478,30 +637,41 @@ onUnmounted(() => {
gap: 14px;
padding: 6px 2px 14px;
}
.head__meta {
.heroCard {
display: grid;
gap: 10px;
grid-template-columns: minmax(0, 1.5fr) minmax(280px, 360px);
gap: 18px;
align-items: stretch;
}
.kicker {
font-size: 12px;
opacity: 0.7;
.heroCard__main,
.heroCard__side {
min-width: 0;
}
.heroCard__main {
display: grid;
gap: 12px;
}
.heroCard__side {
display: flex;
}
.titleInput {
width: min(100%, 920px);
width: 100%;
font-size: 22px;
font-weight: 800;
letter-spacing: -0.02em;
padding: 10px 12px;
border-radius: 14px;
padding: 14px 16px;
border-radius: 18px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.04);
background: linear-gradient(180deg, rgba(255, 255, 255, 0.07), rgba(255, 255, 255, 0.04));
color: rgba(255, 255, 255, 0.92);
outline: none;
box-sizing: border-box;
}
.descInput {
width: min(100%, 920px);
padding: 10px 12px;
border-radius: 14px;
width: 100%;
min-height: 92px;
padding: 14px 16px;
border-radius: 18px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(0, 0, 0, 0.18);
color: rgba(255, 255, 255, 0.92);
@@ -511,6 +681,69 @@ onUnmounted(() => {
.hint {
opacity: 0.78;
font-size: 13px;
line-height: 1.6;
padding: 0 2px;
}
.titleNotice {
font-size: 13px;
line-height: 1.5;
color: rgba(251, 191, 36, 0.94);
padding: 0 2px;
}
.thumbComposer {
display: grid;
gap: 10px;
width: 100%;
padding: 16px;
border-radius: 22px;
border: 1px solid rgba(255, 255, 255, 0.12);
background:
radial-gradient(circle at top right, rgba(96, 165, 250, 0.12), transparent 46%),
rgba(255, 255, 255, 0.04);
box-sizing: border-box;
}
.thumbComposer__header {
display: grid;
gap: 4px;
}
.thumbComposer__eyebrow {
font-size: 13px;
font-weight: 900;
letter-spacing: 0.02em;
}
.thumbComposer__caption {
font-size: 12px;
opacity: 0.68;
}
.thumbComposer__preview {
width: 100%;
aspect-ratio: 16 / 9;
border-radius: 18px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(11, 18, 32, 0.78);
}
.thumbComposer__image {
width: 100%;
height: 100%;
object-fit: cover;
}
.thumbComposer__empty {
width: 100%;
height: 100%;
display: grid;
place-items: center;
color: rgba(255, 255, 255, 0.62);
font-size: 13px;
}
.thumbComposer__actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.thumbComposer__button {
width: 100%;
margin-top: 0;
}
.actions {
display: flex;
@@ -587,7 +820,7 @@ onUnmounted(() => {
}
.btn--ghost {
width: 100%;
margin-top: 10px;
margin-top: 0;
}
.layout {
display: grid;
@@ -609,14 +842,94 @@ onUnmounted(() => {
padding: 20px;
align-self: start;
}
.boardTools {
.modalOverlay {
position: fixed;
inset: 0;
z-index: 40;
display: grid;
place-items: center;
padding: 20px;
background: rgba(4, 8, 16, 0.68);
backdrop-filter: blur(4px);
}
.modalCard {
width: min(100%, 420px);
border-radius: 20px;
padding: 24px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: linear-gradient(180deg, rgba(17, 24, 39, 0.96), rgba(11, 18, 32, 0.96));
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.38);
display: grid;
gap: 10px;
}
.modalCard__title {
font-size: 22px;
font-weight: 900;
letter-spacing: -0.02em;
}
.modalCard__desc {
line-height: 1.6;
opacity: 0.82;
}
.modalCard__actions {
display: flex;
justify-content: flex-end;
margin-top: 8px;
}
.boardTools {
display: flex;
gap: 12px;
align-items: center;
justify-content: flex-end;
margin-bottom: 14px;
flex-wrap: wrap;
}
.boardTools__left,
.boardTools__right {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.boardTools__left {
margin-right: auto;
}
.boardTools__label {
font-size: 13px;
opacity: 0.76;
font-weight: 800;
}
.sizePicker {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.sizePicker__button {
margin: 0;
min-width: 48px;
padding: 8px 10px;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.92);
cursor: pointer;
font-weight: 800;
}
.sizePicker__button--active {
background: rgba(96, 165, 250, 0.24);
border-color: rgba(96, 165, 250, 0.38);
}
.exportBoard--active {
display: grid;
gap: 12px;
width: 960px;
max-width: none;
box-sizing: border-box;
padding: 44px 52px;
border-radius: 28px;
background:
radial-gradient(circle at top, rgba(96, 165, 250, 0.14), transparent 38%),
rgba(11, 18, 32, 0.98);
}
.exportBoard__title {
font-size: 28px;
@@ -631,6 +944,16 @@ onUnmounted(() => {
opacity: 0.74;
text-align: left;
}
.exportBoard__footer {
margin-top: 12px;
padding-top: 18px;
border-top: 1px solid rgba(255, 255, 255, 0.12);
display: flex;
justify-content: space-between;
gap: 16px;
font-size: 15px;
opacity: 0.8;
}
.rows {
display: grid;
gap: 10px;
@@ -701,7 +1024,7 @@ onUnmounted(() => {
border-radius: 14px;
background: rgba(0, 0, 0, 0.18);
border: 1px solid rgba(255, 255, 255, 0.10);
min-height: 74px;
min-height: calc(var(--thumb-size, 80px) + 24px);
padding: 10px;
display: flex;
flex-wrap: wrap;
@@ -724,8 +1047,8 @@ onUnmounted(() => {
flex: 0 0 auto;
}
.thumb {
width: 48px;
height: 48px;
width: var(--thumb-size, 80px);
height: var(--thumb-size, 80px);
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.06);
@@ -773,7 +1096,7 @@ onUnmounted(() => {
}
.poolItem {
display: grid;
grid-template-columns: 52px 1fr;
grid-template-columns: var(--thumb-size, 80px) 1fr;
gap: 10px;
align-items: center;
padding: 10px;
@@ -796,6 +1119,9 @@ onUnmounted(() => {
border-radius: 14px;
}
@media (max-width: 980px) {
.heroCard {
grid-template-columns: 1fr;
}
.layout {
grid-template-columns: 1fr;
}
@@ -812,5 +1138,13 @@ onUnmounted(() => {
.row {
grid-template-columns: 150px 1fr;
}
.thumbComposer {
padding: 14px;
border-radius: 18px;
}
.titleInput,
.descInput {
border-radius: 16px;
}
}
</style>