라이어 게임: 관리자 화면에서 주제·제시어 추가/수정/삭제, 바보 모드 라이어는 비슷한 단어(같은 묶음)
- 제시어 1,519개를 주제별 '비슷한 단어 묶음' 391개로 정리(bank/*.ts groups). 바보 모드 라이어는 제시어와 같은 묶음의 다른 단어를 받음 - 관리자 → 라이어 제시어(/admin/liar): 주제 추가·이름 변경·삭제(내장 주제는 다시 살리기/처음 값으로), 제시어·묶음·다른 표기·컴퓨터 설명 편집, 저장 시 topicProblems 검사 - 저장: liar_topics(바뀐 주제), liar_bank_versions(판본). 새 판 옵션에 bank 판본을 붙여(prepareOptions) 다시 보기·복구가 같은 은행 사용 - 판 상태에 주제 이름·단어 목록·다른 표기를 복사해 진행 중 판은 관리자 수정의 영향을 받지 않음 - 대기실 주제 목록은 GET /api/liar/topics, 관리자 API /api/admin/liar/topics, 기록 liar.topic.* - 테스트: 엔진(묶음·바보 모드·판본·검사), 서버(관리자 API·새 판·재시작), E2E(관리자 편집 → 대기실 새 주제) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils';
|
||||
import { GUEST_IDLE_MS } from './server';
|
||||
import { TOPICS, bankTopics, liarBankRef, setLiarBank, setLiarBankResolver, type LiarState } from '@bg/games/liar';
|
||||
import type { Conn, Room } from './rooms/room';
|
||||
|
||||
const [SUPER, SUPER2] = TEST_SUPERADMINS;
|
||||
type Booted = ReturnType<typeof boot>;
|
||||
@@ -11,6 +13,9 @@ const clients: Client[] = [];
|
||||
afterEach(async () => {
|
||||
for (const c of clients.splice(0)) c.close();
|
||||
for (const s of running.splice(0)) await s.stop();
|
||||
// The 라이어 word bank is process-wide (the game module holds it): back to the code's for the next test.
|
||||
setLiarBank(TOPICS, null);
|
||||
setLiarBankResolver(null);
|
||||
});
|
||||
|
||||
function start(): Booted {
|
||||
@@ -142,6 +147,109 @@ describe('game settings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('라이어 게임 제시어 (§4.1)', () => {
|
||||
const topic = {
|
||||
ko: '우리 반',
|
||||
generic: ['교실에 있어요', '매일 봐요'],
|
||||
words: [
|
||||
{ word: '칠판', hints: ['앞에 걸려 있어요', '분필로 써요'], aliases: ['흑판'], group: '앞' },
|
||||
{ word: '교탁', hints: ['선생님 자리예요'], group: '앞' },
|
||||
{ word: '사물함', hints: ['뒤에 있어요', '자물쇠를 달아요'], group: '뒤' },
|
||||
{ word: '청소함', hints: ['빗자루가 들어 있어요'], group: '뒤' },
|
||||
],
|
||||
};
|
||||
const send = (s: Booted, cookie: string, method: string, path: string, body?: unknown) =>
|
||||
api(s.base, `/api/admin/liar${path}`, { method, cookie, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
|
||||
test('추가·수정·삭제·되돌리기, 잘못된 단어는 이유와 함께 거절, 일반 사용자는 403, 모두 기록', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const plain = await discordLogin(s, '111111111111111111');
|
||||
expect((await send(s, plain.cookie, 'GET', '/topics')).res.status).toBe(403);
|
||||
expect((await send(s, plain.cookie, 'POST', '/topics', topic)).res.status).toBe(403);
|
||||
|
||||
const list = await send(s, sup.cookie, 'GET', '/topics');
|
||||
expect(list.body.topics.map((t: any) => t.id)).toEqual(TOPICS.map((t) => t.id));
|
||||
expect(list.body.topics[0]).toMatchObject({ id: 'fruit', builtin: true, modified: false, deleted: false });
|
||||
expect(list.body.topics[0].words[0].group).toBeTruthy();
|
||||
|
||||
// Problems come back in Korean: the word inside its own hint, and one word inside another.
|
||||
const bad = await send(s, sup.cookie, 'POST', '/topics', { ...topic, words: [...topic.words, { word: '큰칠판', hints: ['큰 칠판이에요'] }] });
|
||||
expect(bad.res.status).toBe(400);
|
||||
expect(bad.body.error).toContain("'큰칠판'의 설명");
|
||||
expect(bad.body.error).toContain("'칠판'가 '큰칠판' 안에");
|
||||
|
||||
const made = await send(s, sup.cookie, 'POST', '/topics', topic);
|
||||
expect(made.res.status).toBe(200);
|
||||
const id = made.body.topic.id as string;
|
||||
expect(id).toMatch(/^c_[a-z0-9]+$/);
|
||||
expect(made.body.topic).toMatchObject({ ko: '우리 반', builtin: false, deleted: false });
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.at(-1)).toEqual({ id, ko: '우리 반', words: 4 });
|
||||
|
||||
// Edit a built-in topic (drop 수박), then reset it.
|
||||
const fruit = list.body.topics[0];
|
||||
const edited = await send(s, sup.cookie, 'PUT', '/topics/fruit', { ko: fruit.ko, generic: fruit.generic, words: fruit.words.filter((w: any) => w.word !== '수박') });
|
||||
expect(edited.res.status).toBe(200);
|
||||
expect(edited.body.topic).toMatchObject({ builtin: true, modified: true });
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(false);
|
||||
expect((await send(s, sup.cookie, 'POST', '/topics/fruit/reset')).body.topic.modified).toBe(false);
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(true);
|
||||
|
||||
// Delete: a built-in topic is hidden (and can come back), an admin's own is gone.
|
||||
expect((await send(s, sup.cookie, 'DELETE', '/topics/person')).res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(false);
|
||||
expect((await send(s, sup.cookie, 'GET', '/topics')).body.topics.find((t: any) => t.id === 'person')).toMatchObject({ deleted: true });
|
||||
await send(s, sup.cookie, 'POST', '/topics/person/reset');
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(true);
|
||||
expect((await send(s, sup.cookie, 'DELETE', `/topics/${id}`)).res.status).toBe(200);
|
||||
expect((await send(s, sup.cookie, 'PUT', `/topics/${id}`, topic)).res.status).toBe(404);
|
||||
expect(liarBankRef()).toBeNull();
|
||||
|
||||
const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie });
|
||||
expect(audit.body.entries.map((e: any) => e.action)).toEqual(['liar.topic.delete', 'liar.topic.reset', 'liar.topic.delete', 'liar.topic.reset', 'liar.topic.update', 'liar.topic.create']);
|
||||
});
|
||||
|
||||
test('새 판은 고친 은행을 쓰고 그 판본을 옵션에 남겨요. 은행을 또 고쳐도 지난 판본은 남고, 서버를 다시 켜도 그대로', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const id = (await send(s, sup.cookie, 'POST', '/topics', topic)).body.topic.id as string;
|
||||
const ref = liarBankRef()!;
|
||||
expect(ref).toBeTruthy();
|
||||
const host = await guest(s.base, '방장');
|
||||
const room = s.rooms.createPractice(host.id, 'liar') as Room;
|
||||
const conn: Conn = { userId: host.id, send: () => {}, close: () => {} };
|
||||
room.join(conn, 'player');
|
||||
expect(room.configure(host.id, { options: { ...(room.config.options as object), topic: id, foolMode: true } })).toBeNull();
|
||||
expect(room.start(host.id)).toBeNull();
|
||||
for (let i = 0; i < 200 && !room.game; i++) await sleep(10);
|
||||
const st = room.game!.state as LiarState;
|
||||
expect(st.topic).toBe(id);
|
||||
expect(st.options.bank).toBe(ref);
|
||||
expect(st.words).toEqual(['칠판', '교탁', '사물함', '청소함']);
|
||||
// 바보 모드: the liar's word is from the same group.
|
||||
const group = (w: string) => topic.words.find((x) => x.word === w)!.group;
|
||||
expect(group(st.liarWord!)).toBe(group(st.word));
|
||||
const stored = s.db.query<{ options_json: string }, []>("SELECT options_json FROM games WHERE game_id = 'liar'").get()!;
|
||||
expect(JSON.parse(stored.options_json).bank).toBe(ref);
|
||||
|
||||
// Another change: a new version; the old one is still found (replays).
|
||||
await send(s, sup.cookie, 'PUT', `/topics/${id}`, { ...topic, words: topic.words.slice(0, 2) });
|
||||
expect(liarBankRef()).not.toBe(ref);
|
||||
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === id)!.words).toHaveLength(2);
|
||||
|
||||
// Restart on the same database: same bank, same version name.
|
||||
const now = liarBankRef();
|
||||
await s.stop();
|
||||
running.splice(running.indexOf(s), 1);
|
||||
setLiarBank(TOPICS, null);
|
||||
const again = boot(s.dbPath);
|
||||
running.push(again);
|
||||
expect(liarBankRef()).toBe(now);
|
||||
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin-only options (threat guides)', () => {
|
||||
test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => {
|
||||
const s = start();
|
||||
|
||||
153
apps/server/src/admin/liar-bank.ts
Normal file
153
apps/server/src/admin/liar-bank.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics.
|
||||
* The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name
|
||||
* (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay
|
||||
* (or a game restored after a restart) sets up from the bank it started with.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { z } from 'zod';
|
||||
import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
|
||||
const line = (max: number) => z.string().trim().min(1).max(max);
|
||||
export const LiarTopicInputSchema = z.object({
|
||||
ko: line(20),
|
||||
generic: z.array(line(80)).max(20),
|
||||
words: z
|
||||
.array(
|
||||
z.object({
|
||||
word: line(20),
|
||||
aliases: z.array(line(20)).max(10).optional(),
|
||||
hints: z.array(line(80)).max(10),
|
||||
group: z.string().trim().max(20).optional(),
|
||||
}),
|
||||
)
|
||||
.max(300),
|
||||
});
|
||||
export type LiarTopicInput = z.infer<typeof LiarTopicInputSchema>;
|
||||
|
||||
/** Most topics an admin may add. */
|
||||
export const CUSTOM_TOPICS_MAX = 100;
|
||||
|
||||
export interface AdminLiarTopic extends Omit<LiarTopic, 'groups'> {
|
||||
builtin: boolean;
|
||||
/** Built-in topic changed by an admin (can be reset). */
|
||||
modified: boolean;
|
||||
/** Built-in topic an admin deleted (can be restored). */
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
/** Drops empty optional fields so the stored JSON stays small and stable. */
|
||||
function clean(t: LiarTopicInput): NonNullable<TopicOverride['topic']> {
|
||||
return {
|
||||
ko: t.ko,
|
||||
generic: t.generic,
|
||||
words: t.words.map((x) => ({
|
||||
word: x.word,
|
||||
hints: x.hints,
|
||||
...(x.aliases?.length ? { aliases: x.aliases } : {}),
|
||||
...(x.group ? { group: x.group } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export class LiarBankStore {
|
||||
private rows: TopicOverride[] = [];
|
||||
private versions = new Map<string, readonly LiarTopic[]>();
|
||||
|
||||
constructor(private db: Database) {
|
||||
this.load();
|
||||
setLiarBankResolver((ref) => this.version(ref));
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
this.rows = this.db
|
||||
.query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id')
|
||||
.all()
|
||||
.map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit<TopicOverride, 'id'>) }));
|
||||
const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null;
|
||||
const topics = mergeBank(this.rows);
|
||||
if (ref) {
|
||||
this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now());
|
||||
this.versions.set(ref, topics);
|
||||
}
|
||||
setLiarBank(topics, ref);
|
||||
}
|
||||
|
||||
/** A stored bank version (null if unknown: the game falls back to the bank in the code). */
|
||||
private version(ref: string): readonly LiarTopic[] | null {
|
||||
const hit = this.versions.get(ref);
|
||||
if (hit) return hit;
|
||||
const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref);
|
||||
if (!row) return null;
|
||||
const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]);
|
||||
if (this.versions.size > 50) this.versions.clear();
|
||||
this.versions.set(ref, topics);
|
||||
return topics;
|
||||
}
|
||||
|
||||
/** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */
|
||||
list(): AdminLiarTopic[] {
|
||||
const by = new Map(this.rows.map((r) => [r.id, r]));
|
||||
const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => {
|
||||
const builtin = TOPICS.some((b) => b.id === t.id);
|
||||
return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false };
|
||||
});
|
||||
for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true });
|
||||
return out;
|
||||
}
|
||||
|
||||
get(id: string): AdminLiarTopic | null {
|
||||
return this.list().find((t) => t.id === id) ?? null;
|
||||
}
|
||||
|
||||
/** Problems (Korean) with a topic as typed, or none. */
|
||||
problems(t: LiarTopicInput): string[] {
|
||||
return topicProblems(clean(t));
|
||||
}
|
||||
|
||||
private write(id: string, value: Omit<TopicOverride, 'id'>, by: string, now: number): void {
|
||||
this.db
|
||||
.query(
|
||||
'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at',
|
||||
)
|
||||
.run(id, JSON.stringify(value), now, by, now);
|
||||
this.load();
|
||||
}
|
||||
|
||||
private remove(id: string): void {
|
||||
this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id);
|
||||
this.load();
|
||||
}
|
||||
|
||||
/** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */
|
||||
save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void {
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
}
|
||||
|
||||
/** Adds a topic of the admins' own; returns its id, or null when there are too many. */
|
||||
create(t: LiarTopicInput, by: string, now = Date.now()): string | null {
|
||||
if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null;
|
||||
let id: string;
|
||||
do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`;
|
||||
while (this.rows.some((r) => r.id === id));
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */
|
||||
delete(id: string, by: string, now = Date.now()): void {
|
||||
if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now);
|
||||
else this.remove(id);
|
||||
}
|
||||
|
||||
/** A built-in topic back to the code's words (undoes a change or a delete). */
|
||||
reset(id: string): void {
|
||||
this.remove(id);
|
||||
}
|
||||
|
||||
/** Topics new rooms can pick, for the lobby. */
|
||||
static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] {
|
||||
return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length }));
|
||||
}
|
||||
}
|
||||
5
apps/server/src/db/migrations/004_liar_bank.sql
Normal file
5
apps/server/src/db/migrations/004_liar_bank.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1).
|
||||
-- One row per changed topic: a built-in topic replaced ({"topic":…}) or deleted ({"deleted":true}), or an admin's own topic (id c_…).
|
||||
CREATE TABLE liar_topics (id TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT, updated_at INTEGER NOT NULL);
|
||||
-- Every set of changes games were started with (options.bank = ref), so replays set up from the same bank.
|
||||
CREATE TABLE liar_bank_versions (ref TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL);
|
||||
@@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { botProfile, nicknameError, normalizeNickname } from '@bg/shared';
|
||||
import type { Audit, Role, Roles } from '../admin/roles';
|
||||
import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
||||
import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank';
|
||||
import type { Sessions } from '../auth/sessions';
|
||||
import { toPublicUser, type Users } from '../auth/users';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
@@ -19,6 +20,7 @@ export interface AdminDeps {
|
||||
audit: Audit;
|
||||
settings: SettingsStore;
|
||||
games: Record<string, AnyGameDefinition>;
|
||||
liarBank: LiarBankStore;
|
||||
disconnectUser: (userId: string) => void;
|
||||
/** When an idle guest will be deleted; null for members and for guests still online or seated. */
|
||||
guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null;
|
||||
@@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) {
|
||||
return c.json({ effective: d.settings.game(id), raw: {} });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1)
|
||||
app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() }));
|
||||
|
||||
/** Parses and checks a topic as typed; the error response, or the topic. */
|
||||
const liarInput = async (c: Context<Env>) => {
|
||||
const parsed = LiarTopicInputSchema.safeParse(await body(c));
|
||||
if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) };
|
||||
const problems = d.liarBank.problems(parsed.data);
|
||||
if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) };
|
||||
return { topic: parsed.data };
|
||||
};
|
||||
|
||||
app.post('/liar/topics', async (c) => {
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
const id = d.liarBank.create(r.topic, actor(c));
|
||||
if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400);
|
||||
d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.put('/liar/topics/:id', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
d.liarBank.save(id, r.topic, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.delete('/liar/topics/:id', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400);
|
||||
d.liarBank.delete(id, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.delete', id, before, null);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post('/liar/topics/:id/reset', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400);
|
||||
d.liarBank.reset(id);
|
||||
d.audit.log(actor(c), 'liar.topic.reset', id, before, null);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ site
|
||||
app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
|
||||
app.put('/site', async (c) => {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { z } from 'zod';
|
||||
import { bankTopics, liarBankRef } from '@bg/games/liar';
|
||||
import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared';
|
||||
import type { Config } from '../config';
|
||||
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
|
||||
@@ -102,6 +103,9 @@ export function createHttpApp(d: HttpDeps) {
|
||||
});
|
||||
});
|
||||
|
||||
// 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices.
|
||||
app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) }));
|
||||
|
||||
app.post('/api/auth/guest', async (c) => {
|
||||
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));
|
||||
|
||||
@@ -904,7 +904,8 @@ export class Room {
|
||||
if (countErr) return countErr;
|
||||
const eff = this.deps.settings?.game(def.id);
|
||||
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
|
||||
return { options: parsed.data };
|
||||
// Data the server decides (e.g. the admin-edited 라이어 word-bank version) goes with the options, so replays match.
|
||||
return { options: def.prepareOptions ? def.prepareOptions(parsed.data) : parsed.data };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,6 +18,7 @@ import { Replays } from './rooms/replay';
|
||||
import { Gateway, type WsData } from './ws/gateway';
|
||||
import { Audit, Roles } from './admin/roles';
|
||||
import { SettingsStore } from './admin/settings';
|
||||
import { LiarBankStore } from './admin/liar-bank';
|
||||
|
||||
/** A guest who closed the site and stayed away this long is deleted. */
|
||||
export const GUEST_IDLE_MS = 24 * 3600_000;
|
||||
@@ -57,6 +58,8 @@ export function startServer(opts: StartOptions) {
|
||||
return u ? toPublicUser(u) : null;
|
||||
};
|
||||
const settings = new SettingsStore(db, GAMES);
|
||||
// 라이어 게임 words the admins changed: loaded before rooms are restored (their games may use an edited bank).
|
||||
const liarBank = new LiarBankStore(db);
|
||||
const roles = new Roles(db, config.superadminDiscordIds);
|
||||
const audit = new Audit(db);
|
||||
const startedAt = Date.now();
|
||||
@@ -131,6 +134,7 @@ export function startServer(opts: StartOptions) {
|
||||
admin: {
|
||||
audit,
|
||||
games: GAMES,
|
||||
liarBank,
|
||||
disconnectUser: (id) => gateway.disconnectUser(id),
|
||||
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
|
||||
stats: () => {
|
||||
|
||||
@@ -25,6 +25,32 @@ import { fxMs } from '../../lib/motion';
|
||||
|
||||
type Kind = LiarView['phase']['kind'];
|
||||
|
||||
// ---------------------------------------------------------------- topics (admins may add or delete some)
|
||||
|
||||
type TopicChoice = { id: string; ko: string };
|
||||
/** The topics new games can use; the code's list until the server answers. */
|
||||
let topicChoices: TopicChoice[] = TOPIC_IDS.map((id) => ({ id, ko: TOPIC_KO[id] }));
|
||||
let topicsLoad: Promise<TopicChoice[]> | null = null;
|
||||
function loadTopics(): Promise<TopicChoice[]> {
|
||||
topicsLoad ??= fetch('/api/liar/topics', { credentials: 'same-origin' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<{ topics: TopicChoice[] }>) : Promise.reject(new Error(String(r.status)))))
|
||||
.then((d) => (topicChoices = d.topics))
|
||||
.catch(() => ((topicsLoad = null), topicChoices));
|
||||
return topicsLoad;
|
||||
}
|
||||
const topicName = (id: string) => topicChoices.find((t) => t.id === id)?.ko ?? (TOPIC_KO as Record<string, string>)[id] ?? '관리자가 고른 주제';
|
||||
function useTopicChoices(): TopicChoice[] {
|
||||
const [list, setList] = useState(topicChoices);
|
||||
useEffect(() => {
|
||||
let on = true;
|
||||
void loadTopics().then((x) => on && setList(x));
|
||||
return () => {
|
||||
on = false;
|
||||
};
|
||||
}, []);
|
||||
return list;
|
||||
}
|
||||
|
||||
const PHASE_KO: Record<Kind, string> = {
|
||||
reveal: '제시어 확인',
|
||||
describe: '한 사람씩 설명',
|
||||
@@ -662,7 +688,7 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record<string, Publ
|
||||
<h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2>
|
||||
<span>{REASON_KO[f.reason]}.</span>
|
||||
<span>
|
||||
제시어 <span className="word">{f.word}</span> · 주제 {TOPIC_KO[f.topic]}
|
||||
제시어 <span className="word">{f.word}</span> · 주제 {f.topicKo ?? topicName(f.topic)}
|
||||
{f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''}
|
||||
{f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''}
|
||||
</span>
|
||||
@@ -954,13 +980,16 @@ const secs = <T extends number>(...v: T[]): [T | null, string][] => [...v.map((x
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
const topics = useTopicChoices();
|
||||
// A topic an admin deleted plays as 무작위 (shown as such so the host isn't left with a hidden choice).
|
||||
const topic = o.topic === 'random' || topics.some((t) => t.id === o.topic) ? o.topic : 'random';
|
||||
const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label="주제">
|
||||
<Seg<LiarOptions['topic']> label="주제" value={o.topic} options={[['random', '무작위'], ...TOPIC_IDS.map((t): [LiarOptions['topic'], string] => [t, TOPIC_KO[t]])]} onChange={(topic) => set({ topic })} />
|
||||
<Seg<string> label="주제" value={topic} options={[['random', '무작위'], ...topics.map((t): [string, string] => [t.id, t.ko])]} onChange={(next) => set({ topic: next })} />
|
||||
</Field>
|
||||
<Field label="바보 모드" help="켜면 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.">
|
||||
<Field label="바보 모드" help="켜면 라이어도 제시어와 비슷한 다른 단어(같은 묶음)를 받고, 자기가 라이어인지 몰라요.">
|
||||
<Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} />
|
||||
</Field>
|
||||
<Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
|
||||
@@ -1015,7 +1044,8 @@ function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
}
|
||||
|
||||
function optionsSummary(o: LiarOptions): string {
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`];
|
||||
void loadTopics();
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${topicName(o.topic)}`];
|
||||
if (o.foolMode) parts.push('바보 모드');
|
||||
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
|
||||
return parts.join(' · ');
|
||||
@@ -1038,7 +1068,7 @@ function Rules() {
|
||||
<li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li>
|
||||
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
|
||||
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
|
||||
<li>바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
<li>바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
<li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li>
|
||||
</ul>
|
||||
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiCall, discordLoginUrl, type Role } from '../../net/api';
|
||||
import { useSession } from '../../store/session';
|
||||
import { toast } from '../../store/toast';
|
||||
import { SchemaForm, type JsonSchema } from './SchemaForm';
|
||||
import { LiarTopicEditor, LiarTopics } from './LiarWords';
|
||||
import { gameName } from '../../components/GameNotice';
|
||||
import { RecordCell, record, recordText, resultLabel, sumStats } from '../../components/PlayerCard';
|
||||
import type { GameStat } from '../../net/api';
|
||||
@@ -53,6 +54,7 @@ export default function AdminApp() {
|
||||
const tabs: [string, string, boolean][] = [
|
||||
['', '대시보드', true],
|
||||
['games', '게임', true],
|
||||
['liar', '라이어 제시어', true],
|
||||
['rooms', '방', true],
|
||||
['site', '사이트', true],
|
||||
['users', '사용자', sup],
|
||||
@@ -81,6 +83,8 @@ export default function AdminApp() {
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="games" element={<Games />} />
|
||||
<Route path="games/:id" element={<GameEditor />} />
|
||||
<Route path="liar" element={<LiarTopics />} />
|
||||
<Route path="liar/:id" element={<LiarTopicEditor />} />
|
||||
<Route path="rooms" element={<Rooms />} />
|
||||
<Route path="site" element={<Site />} />
|
||||
{sup && <Route path="users" element={<Users />} />}
|
||||
@@ -851,6 +855,10 @@ const ACTION_KO: Record<string, string> = {
|
||||
'user.delete': '계정 삭제',
|
||||
'admin.add': '어드민 추가',
|
||||
'admin.remove': '어드민 삭제',
|
||||
'liar.topic.create': '라이어 주제 추가',
|
||||
'liar.topic.update': '라이어 주제·제시어 수정',
|
||||
'liar.topic.delete': '라이어 주제 삭제',
|
||||
'liar.topic.reset': '라이어 주제 되돌리기',
|
||||
};
|
||||
|
||||
function Audit() {
|
||||
|
||||
338
apps/web/src/pages/admin/LiarWords.tsx
Normal file
338
apps/web/src/pages/admin/LiarWords.tsx
Normal file
@@ -0,0 +1,338 @@
|
||||
/** 관리자: 라이어 게임 주제와 제시어 (docs/14-admin.md §4.1). Changes apply to games started afterwards. */
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { toast } from '../../store/toast';
|
||||
|
||||
interface Word {
|
||||
word: string;
|
||||
aliases?: string[];
|
||||
hints: string[];
|
||||
group?: string;
|
||||
}
|
||||
interface Topic {
|
||||
id: string;
|
||||
ko: string;
|
||||
generic: string[];
|
||||
words: Word[];
|
||||
builtin: boolean;
|
||||
modified: boolean;
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
const api = (m: 'GET' | 'POST' | 'PUT' | 'DELETE', p: string, b?: unknown) => apiCall<{ topics?: Topic[]; topic?: Topic }>(m, `/api/admin/liar${p}`, b);
|
||||
const lines = (s: string) =>
|
||||
s
|
||||
.split('\n')
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean);
|
||||
const commas = (s: string) =>
|
||||
s
|
||||
.split(',')
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
/** `key`: reload when it changes (the editor moves from 'new' to the created topic's id). */
|
||||
function useTopics(key = ''): [Topic[] | null, () => void] {
|
||||
const [d, setD] = useState<Topic[] | null>(null);
|
||||
const load = useCallback(() => {
|
||||
api('GET', '/topics').then(
|
||||
(r) => setD(r.topics ?? []),
|
||||
(e) => toast((e as Error).message, 'error'),
|
||||
);
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(load, [load]);
|
||||
return [d, load];
|
||||
}
|
||||
|
||||
function badge(t: Topic): string {
|
||||
if (t.deleted) return '삭제됨';
|
||||
if (!t.builtin) return '관리자가 더함';
|
||||
return t.modified ? '고침' : '기본';
|
||||
}
|
||||
|
||||
export function LiarTopics() {
|
||||
const nav = useNavigate();
|
||||
const [topics, reload] = useTopics();
|
||||
const [ask, setAsk] = useState<{ t: Topic; kind: 'delete' | 'reset' } | null>(null);
|
||||
if (!topics) return <p className="muted">불러오는 중…</p>;
|
||||
const live = topics.filter((t) => !t.deleted);
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<h1>라이어 게임 제시어</h1>
|
||||
<p className="muted small">
|
||||
주제 {live.length}개 · 제시어 {live.reduce((n, t) => n + t.words.length, 0)}개. 바꾼 내용은 새로 시작하는 판부터 쓰여요. 바보 모드의 라이어는 제시어와 같은 "묶음"의 다른 단어를 받아요(묶음이 없거나 혼자면 같은 주제의 아무
|
||||
단어).
|
||||
</p>
|
||||
<button className="btn btn-primary" style={{ alignSelf: 'flex-start' }} onClick={() => nav('/admin/liar/new')}>
|
||||
+ 새 주제
|
||||
</button>
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
{topics.map((t) => (
|
||||
<div key={t.id} className="card row" style={{ justifyContent: 'space-between', padding: 12, opacity: t.deleted ? 0.6 : 1 }}>
|
||||
<div className="stack" style={{ gap: 2 }}>
|
||||
<strong>{t.ko}</strong>
|
||||
<span className="muted small">
|
||||
{badge(t)} · 제시어 {t.words.length}개 · 묶음 {new Set(t.words.map((w) => w.group).filter(Boolean)).size}개 · ID {t.id}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
{!t.deleted && (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => nav(`/admin/liar/${t.id}`)}>
|
||||
편집
|
||||
</button>
|
||||
)}
|
||||
{t.builtin && (t.modified || t.deleted) && (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setAsk({ t, kind: 'reset' })}>
|
||||
{t.deleted ? '다시 살리기' : '처음 값으로'}
|
||||
</button>
|
||||
)}
|
||||
{!t.deleted && (
|
||||
<button className="btn btn-danger btn-sm" onClick={() => setAsk({ t, kind: 'delete' })}>
|
||||
삭제
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{ask && (
|
||||
<ConfirmSheet
|
||||
title={ask.kind === 'delete' ? `'${ask.t.ko}' 주제를 삭제할까요?` : ask.t.deleted ? `'${ask.t.ko}' 주제를 다시 살릴까요?` : `'${ask.t.ko}' 주제를 처음 값으로 되돌릴까요?`}
|
||||
body={
|
||||
ask.kind === 'delete'
|
||||
? ask.t.builtin
|
||||
? '새 판에서 이 주제가 나오지 않아요. 나중에 [다시 살리기]로 되돌릴 수 있어요.'
|
||||
: '관리자가 더한 주제라 지우면 되돌릴 수 없어요.'
|
||||
: '관리자가 고친 내용이 지워지고 처음부터 있던 제시어로 돌아가요.'
|
||||
}
|
||||
confirm={ask.kind === 'delete' ? '삭제' : '되돌리기'}
|
||||
danger={ask.kind === 'delete'}
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
if (ask.kind === 'delete') await api('DELETE', `/topics/${ask.t.id}`);
|
||||
else await api('POST', `/topics/${ask.t.id}/reset`);
|
||||
toast(ask.kind === 'delete' ? '삭제했어요.' : '되돌렸어요.');
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error', 6000);
|
||||
}
|
||||
reload();
|
||||
}}
|
||||
onClose={() => setAsk(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One word as typed in the editor. */
|
||||
interface WordForm {
|
||||
word: string;
|
||||
group: string;
|
||||
aliases: string;
|
||||
hints: string;
|
||||
}
|
||||
const toForm = (w: Word): WordForm => ({ word: w.word, group: w.group ?? '', aliases: (w.aliases ?? []).join(', '), hints: w.hints.join('\n') });
|
||||
const fromForm = (f: WordForm): Word => ({ word: f.word.trim(), group: f.group.trim() || undefined, aliases: commas(f.aliases), hints: lines(f.hints) });
|
||||
const EMPTY: WordForm = { word: '', group: '', aliases: '', hints: '' };
|
||||
|
||||
function WordEditor({ value, groups, onSave, onCancel }: { value: WordForm; groups: string[]; onSave: (f: WordForm) => void; onCancel: () => void }) {
|
||||
const [f, setF] = useState(value);
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 10, padding: 12 }}>
|
||||
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
|
||||
<label className="field" style={{ flex: '1 1 140px' }}>
|
||||
제시어(두 글자 이상)
|
||||
<input className="input" value={f.word} maxLength={20} onChange={(e) => setF({ ...f, word: e.target.value })} autoFocus />
|
||||
</label>
|
||||
<label className="field" style={{ flex: '1 1 140px' }}>
|
||||
비슷한 단어 묶음
|
||||
<input className="input" value={f.group} maxLength={20} list="liar-groups" placeholder="예: 감귤류" onChange={(e) => setF({ ...f, group: e.target.value })} />
|
||||
</label>
|
||||
</div>
|
||||
<label className="field">
|
||||
정답으로 쳐 줄 다른 표기(쉼표로 구분)
|
||||
<input className="input" value={f.aliases} placeholder="예: 핸드폰, 스마트폰" onChange={(e) => setF({ ...f, aliases: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
컴퓨터가 쓸 설명(한 줄에 하나, 덜 구체적인 것부터, 제시어는 넣지 않기)
|
||||
<textarea className="input" style={{ minHeight: 110, padding: 12 }} value={f.hints} onChange={(e) => setF({ ...f, hints: e.target.value })} />
|
||||
</label>
|
||||
<datalist id="liar-groups">
|
||||
{groups.map((g) => (
|
||||
<option key={g} value={g} />
|
||||
))}
|
||||
</datalist>
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<button className="btn btn-primary btn-sm" disabled={!f.word.trim()} onClick={() => onSave(f)}>
|
||||
확인
|
||||
</button>
|
||||
<button className="btn btn-ghost btn-sm" onClick={onCancel}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LiarTopicEditor() {
|
||||
const { id = 'new' } = useParams();
|
||||
const nav = useNavigate();
|
||||
const [topics] = useTopics(id);
|
||||
const isNew = id === 'new';
|
||||
const t = topics?.find((x) => x.id === id);
|
||||
const [ko, setKo] = useState('');
|
||||
const [generic, setGeneric] = useState('');
|
||||
const [words, setWords] = useState<Word[]>([]);
|
||||
const [editing, setEditing] = useState<number | 'new' | null>(null);
|
||||
const [q, setQ] = useState('');
|
||||
const [errors, setErrors] = useState<string[]>([]);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
useEffect(() => {
|
||||
if (t) {
|
||||
setKo(t.ko);
|
||||
setGeneric(t.generic.join('\n'));
|
||||
setWords(t.words);
|
||||
}
|
||||
}, [t]);
|
||||
const groups = useMemo(() => [...new Set(words.map((w) => w.group).filter((g): g is string => !!g))].sort((x, y) => x.localeCompare(y, 'ko')), [words]);
|
||||
if (!topics) return <p className="muted">불러오는 중…</p>;
|
||||
if (!isNew && !t) return <p>없는 주제예요.</p>;
|
||||
|
||||
const change = (next: Word[]) => {
|
||||
setWords(next);
|
||||
setDirty(true);
|
||||
};
|
||||
const putWord = (i: number | 'new', f: WordForm) => {
|
||||
const w = fromForm(f);
|
||||
const dup = words.findIndex((x, j) => j !== i && x.word.replace(/\s/g, '') === w.word.replace(/\s/g, ''));
|
||||
if (dup >= 0) return toast(`'${w.word}'는 이미 있어요.`, 'error');
|
||||
change(i === 'new' ? [w, ...words] : words.map((x, j) => (j === i ? w : x)));
|
||||
setEditing(null);
|
||||
};
|
||||
const save = async () => {
|
||||
const body = { ko: ko.trim(), generic: lines(generic), words: words.map((w) => ({ ...w, aliases: w.aliases?.length ? w.aliases : undefined })) };
|
||||
try {
|
||||
const r = isNew ? await api('POST', '/topics', body) : await api('PUT', `/topics/${id}`, body);
|
||||
setErrors([]);
|
||||
setDirty(false);
|
||||
toast('저장했어요. 새로 시작하는 판부터 쓰여요.');
|
||||
if (isNew && r.topic) nav(`/admin/liar/${r.topic.id}`, { replace: true });
|
||||
} catch (e) {
|
||||
const msg = (e as Error).message;
|
||||
setErrors(msg.split('\n'));
|
||||
toast('저장하지 못했어요. 아래 문제를 고쳐 주세요.', 'error', 6000);
|
||||
}
|
||||
};
|
||||
const norm = q.trim();
|
||||
const shown = words.map((w, i) => ({ w, i })).filter(({ w }) => !norm || w.word.includes(norm) || (w.group ?? '').includes(norm) || (w.aliases ?? []).some((a) => a.includes(norm)));
|
||||
const noGroup = words.filter((w) => !w.group).length;
|
||||
const lonely = groups.filter((g) => words.filter((w) => w.group === g).length < 2);
|
||||
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
style={{ alignSelf: 'flex-start' }}
|
||||
onClick={() => {
|
||||
if (!dirty || confirm('저장하지 않은 내용이 있어요. 나갈까요?')) nav('/admin/liar');
|
||||
}}
|
||||
>
|
||||
← 주제 목록
|
||||
</button>
|
||||
<h1>{isNew ? '새 주제' : `${t!.ko} 주제`}</h1>
|
||||
<section className="card stack">
|
||||
<label className="field">
|
||||
주제 이름(게임 화면에 보여요)
|
||||
<input
|
||||
className="input"
|
||||
value={ko}
|
||||
maxLength={20}
|
||||
onChange={(e) => {
|
||||
setKo(e.target.value);
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
무난한 말(한 줄에 하나): 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요. 어느 제시어에나 맞는 말로, 제시어는 넣지 않기
|
||||
<textarea
|
||||
className="input"
|
||||
style={{ minHeight: 100, padding: 12 }}
|
||||
value={generic}
|
||||
onChange={(e) => {
|
||||
setGeneric(e.target.value);
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
<section className="card stack">
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<h2>
|
||||
제시어 {words.length}개 · 묶음 {groups.length}개
|
||||
</h2>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditing('new')}>
|
||||
+ 제시어 더하기
|
||||
</button>
|
||||
</div>
|
||||
{(noGroup > 0 || lonely.length > 0) && (
|
||||
<p className="muted small">
|
||||
{noGroup > 0 && `묶음이 없는 제시어 ${noGroup}개. `}
|
||||
{lonely.length > 0 && `혼자인 묶음: ${lonely.join(', ')}. `}
|
||||
바보 모드에서 이런 제시어가 나오면 라이어는 같은 주제의 아무 단어나 받아요.
|
||||
</p>
|
||||
)}
|
||||
{editing === 'new' && <WordEditor value={EMPTY} groups={groups} onSave={(f) => putWord('new', f)} onCancel={() => setEditing(null)} />}
|
||||
<input className="input" placeholder="제시어·묶음·다른 표기로 찾기" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
{shown.map(({ w, i }) =>
|
||||
editing === i ? (
|
||||
<WordEditor key={i} value={toForm(w)} groups={groups} onSave={(f) => putWord(i, f)} onCancel={() => setEditing(null)} />
|
||||
) : (
|
||||
<div key={i} className="row" style={{ justifyContent: 'space-between', gap: 8, padding: '6px 4px', borderBottom: '1px solid var(--border, #ddd)' }}>
|
||||
<div className="stack" style={{ gap: 2, minWidth: 0 }}>
|
||||
<span>
|
||||
<strong>{w.word}</strong>
|
||||
{w.group && <span className="badge" style={{ marginLeft: 6 }}>{w.group}</span>}
|
||||
{!!w.aliases?.length && <span className="muted small"> · {w.aliases.join(', ')}</span>}
|
||||
</span>
|
||||
<span className="muted small" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
설명 {w.hints.length}개{w.hints[0] ? ` · ${w.hints[0]}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6, flexShrink: 0 }}>
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => setEditing(i)}>
|
||||
수정
|
||||
</button>
|
||||
<button className="btn btn-danger btn-sm" aria-label={`${w.word} 삭제`} onClick={() => change(words.filter((_, j) => j !== i))}>
|
||||
삭제
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{shown.length === 0 && <p className="muted small">{words.length ? '찾는 제시어가 없어요.' : '아직 제시어가 없어요. [+ 제시어 더하기]로 넣어 주세요(2개 이상).'}</p>}
|
||||
</div>
|
||||
</section>
|
||||
{errors.length > 0 && (
|
||||
<section className="card stack" role="alert" style={{ borderColor: 'var(--danger, #c33)' }}>
|
||||
<strong>저장하지 못했어요</strong>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>
|
||||
{errors.map((e, i) => (
|
||||
<li key={i}>{e}</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
<div className="bottom-bar sticky-save">
|
||||
<div className="bottom-bar-inner">
|
||||
<button className="btn btn-primary" onClick={save}>
|
||||
저장{dirty ? ' (바뀐 내용 있음)' : ''}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user