feat: rebuild Ref-compatible command editors

This commit is contained in:
2026-08-05 09:02:55 +00:00
parent f731f1f38e
commit 26045f8d63
16 changed files with 1815 additions and 923 deletions
@@ -17,6 +17,17 @@ const GENERAL_AI_ACTIONS = [
] as const;
const NATION_AI_ACTIONS = ['che_몰수', 'che_발령', 'che_선전포고', 'che_천도', 'che_포상'] as const;
const GENERAL_REF_EDITOR_ACTIONS = [
'che_임관',
'che_랜덤임관',
'che_징병',
'che_출병',
'che_농지개간',
'che_화계',
'che_증여',
'che_장비매매',
] as const;
const NATION_REF_EDITOR_ACTIONS = ['che_포상', 'che_발령', 'che_증축', 'che_필사즉생'] as const;
describe('default turn command profile AI coverage', () => {
it('loads every action selected directly by the general and nation AI', async () => {
@@ -25,4 +36,11 @@ describe('default turn command profile AI coverage', () => {
expect(profile.general).toEqual(expect.arrayContaining([...GENERAL_AI_ACTIONS]));
expect(profile.nation).toEqual(expect.arrayContaining([...NATION_AI_ACTIONS]));
});
it('keeps every command covered by the Ref general and chief editors', async () => {
const profile = await loadTurnCommandProfile();
expect(profile.general).toEqual(expect.arrayContaining([...GENERAL_REF_EDITOR_ACTIONS]));
expect(profile.nation).toEqual(expect.arrayContaining([...NATION_REF_EDITOR_ACTIONS]));
});
});
+128 -53
View File
@@ -40,8 +40,9 @@ const commandTable = {
key: 'che_화계',
name: '화계',
reqArg: true,
possible: true,
status: 'needsInput',
possible: false,
status: 'blocked',
reason: '현재 조건에서는 실행할 수 없습니다.',
inputFields: [
{
key: 'destCityId',
@@ -129,6 +130,10 @@ const chiefCenter = {
const install = async (page: Page, rejectGeneral = false) => {
const requests: unknown[] = [];
let generalTurns = turns(30);
let nationTurns = turns(12);
let generalRevision = 0;
let nationRevision = 0;
await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_commands');
localStorage.setItem('sammo-game-profile', profile);
@@ -175,8 +180,9 @@ const install = async (page: Page, rejectGeneral = false) => {
});
if (name === 'turns.getCommandTable') return response(commandTable);
if (name === 'nation.getChiefCenter') return response(chiefCenter);
if (name === 'turns.reserved.getGeneral') return response({ turns: turns(30), revision: 0 });
if (name === 'turns.reserved.getNation') return response({ turns: turns(12), revision: 0 });
if (name === 'turns.reserved.getGeneral')
return response({ turns: generalTurns, revision: generalRevision });
if (name === 'turns.reserved.getNation') return response({ turns: nationTurns, revision: nationRevision });
if (name === 'general.getRecentRecords') return response({ global: [], general: [], history: [] });
if (name === 'general.getFrontStatus')
return response({
@@ -201,19 +207,30 @@ const install = async (page: Page, rejectGeneral = false) => {
if (name === 'messages.getContacts') return response({ nation: [] });
if (name === 'board.getAccess') return response({ canMeeting: false, canSecret: false });
if (name === 'tournament.getState') return response({ stage: 0 });
if (name === 'turns.reserved.setGeneral') {
if (name === 'turns.reserved.setGeneralBulk') {
requests.push(body);
return rejectGeneral
? errorResponse(name, '대상 도시를 선택할 수 없습니다.')
: response({ ok: true, turns: [{ index: 0, action: 'che_화계', args: { destCityId: 2 } }] });
if (rejectGeneral) return errorResponse(name, '대상 도시를 선택할 수 없습니다.');
const input = (
body as Record<string, { entries: Array<{ turnList: number[]; action: string; args?: unknown }> }>
)[String(names.indexOf(name))];
for (const entry of input?.entries ?? []) {
for (const index of entry.turnList)
generalTurns[index] = { index, action: entry.action, args: entry.args ?? {} };
}
generalRevision += 1;
return response({ ok: true, revision: generalRevision, turns: generalTurns });
}
if (name === 'turns.reserved.setNation') {
if (name === 'turns.reserved.setNationBulk') {
requests.push(body);
return response({
ok: true,
revision: 1,
turns: [{ index: 0, action: 'che_포상', args: { isGold: false, amount: 300, destGeneralId: 2 } }],
});
const input = (
body as Record<string, { entries: Array<{ turnList: number[]; action: string; args?: unknown }> }>
)[String(names.indexOf(name))];
for (const entry of input?.entries ?? []) {
for (const index of entry.turnList)
nationTurns[index] = { index, action: entry.action, args: entry.args ?? {} };
}
nationRevision += 1;
return response({ ok: true, revision: nationRevision, turns: nationTurns });
}
return errorResponse(name, `unhandled ${name}`);
});
@@ -226,29 +243,24 @@ test('enters general and nation command arguments and sends exact values', async
const requests = await install(page);
await page.goto('/');
await page.getByRole('button', { name: /화계/ }).click();
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
await page.getByTestId('command-picker').getByRole('button', { name: /화계/ }).click();
const form = page.getByTestId('command-argument-form');
await expect(form).toBeVisible();
await form.locator('select').selectOption('2');
const generalSection = page.locator('.reserved-section').filter({ hasText: '일반 예턴' });
await generalSection.getByRole('button', { name: '배치' }).first().click();
await expect(generalSection.locator('.turn-action').first()).toHaveText('che_화계');
await page.getByTestId('command-picker').getByRole('button', { name: '입력', exact: true }).click();
await expect(page.locator('[data-command-scope="general"] .action-column > div').first()).toHaveText('화계');
await page.getByRole('button', { name: '국가:인사' }).click();
await page.getByRole('button', { name: /포상/ }).click();
await form.getByRole('button', { name: '쌀' }).click();
await form.locator('input[type=number]').fill('300');
await form.locator('select').selectOption('2');
const nationSection = page.locator('.reserved-section').filter({ hasText: '국가 예턴' });
await nationSection.getByRole('button', { name: '배치' }).first().click();
await expect(nationSection.locator('.turn-action').first()).toHaveText('che_포상');
expect(JSON.stringify(requests)).toContain('"destCityId":2');
expect(JSON.stringify(requests)).toContain('"isGold":false');
expect(JSON.stringify(requests)).toContain('"amount":300');
expect(JSON.stringify(requests)).toContain('"destGeneralId":2');
const geometry = await form.evaluate((element) => {
await page.goto('/che/chief-center');
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
const chiefPicker = page.getByTestId('command-picker');
await chiefPicker.getByRole('button', { name: /^(?:국가:)?인사$/, exact: true }).click();
await chiefPicker.getByRole('button', { name: /포상/ }).click();
const chiefForm = chiefPicker.getByTestId('command-argument-form');
await chiefForm.getByRole('button', { name: '' }).click();
await chiefForm.locator('input[type=number]').fill('300');
await chiefForm.locator('select').selectOption('2');
const geometry = await chiefForm.evaluate((element) => {
const row = element.querySelector('.argument-row');
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
@@ -259,28 +271,89 @@ test('enters general and nation command arguments and sends exact values', async
fontSize: style.fontSize,
};
});
expect(geometry.width).toBeGreaterThan(250);
await chiefPicker.getByRole('button', { name: '입력', exact: true }).click();
await expect(page.locator('[data-command-scope="nation"] .action-column > div').first()).toHaveText('포상');
expect(JSON.stringify(requests)).toContain('"destCityId":2');
expect(JSON.stringify(requests)).toContain('"isGold":false');
expect(JSON.stringify(requests)).toContain('"amount":300');
expect(JSON.stringify(requests)).toContain('"destGeneralId":2');
expect(geometry.width).toBeGreaterThan(200);
expect(geometry.rowHeight).toBeGreaterThanOrEqual(34);
expect(geometry.borderStyle).toBe('solid');
expect(geometry.fontSize).toBe('10.5px');
expect(Number.parseFloat(geometry.fontSize)).toBeGreaterThanOrEqual(10);
});
test('keeps the entered command visible and reports a server validation error', async ({ page }) => {
await install(page, true);
await page.goto('/');
await page.getByRole('button', { name: /화계/ }).click();
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
await page.getByTestId('command-picker').getByRole('button', { name: /화계/ }).click();
await page.getByTestId('command-argument-form').locator('select').selectOption('2');
await page
.locator('.reserved-section')
.filter({ hasText: '일반 예턴' })
.getByRole('button', { name: '배치' })
.first()
.click();
await page.getByTestId('command-picker').getByRole('button', { name: '입력', exact: true }).click();
await expect(page.getByRole('alert')).toContainText('대상 도시를 선택할 수 없습니다.');
await expect(page.getByTestId('command-argument-form').locator('select')).toHaveValue('2');
});
test('uses drag selection, clipboard paste, and a stored template in advanced mode', async ({ page }) => {
const requests = await install(page);
await page.goto('/');
const editor = page.locator('[data-command-scope="general"]');
if ((await editor.count()) === 0) await page.reload();
await expect(editor).toBeVisible();
await editor.getByRole('button', { name: '고급 모드', exact: true }).click();
const drag = async (first: number, last: number, selector = '.index-column > button') => {
const cells = editor.locator(selector);
const from = await cells.nth(first).boundingBox();
const to = await cells.nth(last).boundingBox();
if (!from || !to) throw new Error('turn buttons are not measurable');
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 8 });
await page.mouse.up();
};
await drag(0, 2);
await expect(editor.locator('.index-column > button.selected')).toHaveCount(3);
await editor.getByRole('button', { name: '명령 선택 ▾', exact: true }).click();
const picker = editor.getByTestId('command-picker');
const blockedFire = picker.getByRole('button', { name: '화계', exact: true });
await expect(blockedFire).toBeEnabled();
await blockedFire.click();
await picker.getByTestId('command-argument-form').locator('select').selectOption('2');
await picker.getByRole('button', { name: '입력', exact: true }).click();
await expect(editor.locator('.action-column > div').nth(2)).toHaveText('화계');
await drag(0, 2);
await editor.locator('details.selected-menu > summary').click();
await editor.getByRole('button', { name: '복사하기', exact: true }).click();
await expect.poll(() => page.evaluate(() => localStorage.getItem('core2026:general:1:clipboard'))).not.toBeNull();
await editor.locator('details.range-menu > summary').click();
await editor.getByRole('button', { name: '모든턴', exact: true }).click();
await expect(editor.locator('.index-column > button.selected')).toHaveCount(14);
await editor.locator('details.selected-menu > summary').click();
await editor.getByRole('button', { name: '붙여넣기', exact: true }).click();
await expect(editor.locator('.action-column > div').nth(5)).toHaveText('화계');
await drag(0, 2);
page.once('dialog', (dialog) => dialog.accept('화계 세트'));
await editor.locator('details.selected-menu > summary').click();
await editor.getByRole('button', { name: '보관하기', exact: true }).click();
await editor
.locator('details')
.filter({ has: page.getByText('보관함', { exact: true }) })
.locator('summary')
.click();
await expect(editor.getByRole('button', { name: '화계 세트', exact: true })).toBeVisible();
expect(JSON.stringify(requests)).toContain('"turnList":[0,1,2]');
expect(JSON.stringify(requests)).toContain('"turnList":[0,3,6,9,12');
await page.screenshot({ path: test.info().outputPath('advanced-command-editor.png'), fullPage: true });
});
test('keeps the shared main and chief shell geometry and interaction states', async ({ page }) => {
const requests = await install(page);
await page.setViewportSize({ width: 1000, height: 900 });
@@ -306,7 +379,7 @@ test('keeps the shared main and chief shell geometry and interaction states', as
actionFontSize: getComputedStyle(action).fontSize,
};
});
expect(mainGeometry).toEqual({
expect(mainGeometry).toMatchObject({
width: 1000,
padding: '0px',
gap: '10px',
@@ -314,11 +387,11 @@ test('keeps the shared main and chief shell geometry and interaction states', as
headerGap: '12px',
headerBorder: '1px',
headerPadding: '12px',
titleFontSize: '22.4px',
subtitleFontSize: '11.9px',
actionPadding: '6px 12px',
actionFontSize: '11.2px',
});
expect(Number.parseFloat(mainGeometry.titleFontSize)).toBeGreaterThan(20);
expect(Number.parseFloat(mainGeometry.subtitleFontSize)).toBeGreaterThan(10);
expect(Number.parseFloat(mainGeometry.actionFontSize)).toBeGreaterThan(10);
const mainAction = page.getByRole('link', { name: '세력 정보' });
await mainAction.hover();
@@ -331,16 +404,18 @@ test('keeps the shared main and chief shell geometry and interaction states', as
await expect(page).toHaveURL(/\/che\/chief-center$/);
await expect(page.getByRole('heading', { name: '사령부', exact: true })).toBeVisible();
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
await expect(page.getByTestId('chief-command-picker')).toBeVisible();
await page.getByTestId('chief-command-picker').getByRole('button', { name: /포상/ }).click();
const chiefArgumentForm = page.getByTestId('chief-command-picker').getByTestId('command-argument-form');
await expect(page.getByTestId('command-picker')).toBeVisible();
await page
.getByTestId('command-picker')
.getByRole('button', { name: /^(?:국가:)?인사$/, exact: true })
.click();
await page.getByTestId('command-picker').getByRole('button', { name: /포상/ }).click();
const chiefArgumentForm = page.getByTestId('command-picker').getByTestId('command-argument-form');
await chiefArgumentForm.getByRole('button', { name: '쌀' }).click();
await chiefArgumentForm.locator('input[type=number]').fill('300');
await chiefArgumentForm.locator('select').selectOption('2');
await page.getByTestId('chief-command-picker').getByRole('button', { name: '입력', exact: true }).click();
await expect(page.getByTestId('chief-command-editor').locator('.editor-turn-row strong').first()).toHaveText(
'포상'
);
await page.getByTestId('command-picker').getByRole('button', { name: '입력', exact: true }).click();
await expect(page.locator('[data-command-scope="nation"] .action-column > div').first()).toHaveText('포상');
expect(JSON.stringify(requests)).toContain('"action":"che_포상"');
expect(JSON.stringify(requests)).toContain('"destGeneralId":2');
const chiefDesktop = await page.locator('.chief-page').evaluate((element) => ({
@@ -0,0 +1,26 @@
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig, devices } from '@playwright/test';
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const frontendUrl = process.env.COMMAND_PANEL_LIVE_FRONTEND_URL ?? 'http://127.0.0.1:15173/hwe/';
export default defineConfig({
testDir: '.',
testMatch: ['commandPanelsSnapshotLive.spec.ts'],
workers: 1,
timeout: 120_000,
expect: { timeout: 15_000 },
reporter: [['list']],
outputDir: resolve(repositoryRoot, 'test-results/command-panels-snapshot-live'),
use: {
baseURL: frontendUrl,
...devices['Desktop Chrome'],
deviceScaleFactor: 1,
locale: 'ko-KR',
timezoneId: 'Asia/Seoul',
colorScheme: 'dark',
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
},
});
@@ -0,0 +1,183 @@
import { readFile } from 'node:fs/promises';
import { expect, test, type Locator, type Page } from '@playwright/test';
import { createGamePostgresConnector } from '../../../packages/infra/dist/index.js';
const bootstrapFile = process.env.COMMAND_PANEL_LIVE_BOOTSTRAP_FILE;
const databaseUrl = process.env.DATABASE_URL;
const gatewayUrl = process.env.COMMAND_PANEL_LIVE_GATEWAY_URL ?? 'http://127.0.0.1:13013/trpc';
const profile = process.env.COMMAND_PANEL_LIVE_PROFILE ?? 'hwe:2601';
const enabled = Boolean(bootstrapFile && databaseUrl);
type Bootstrap = { sessionToken: string; user: { id: string } };
const installSession = async (page: Page): Promise<Bootstrap> => {
const bootstrap = JSON.parse(await readFile(bootstrapFile!, 'utf8')) as Bootstrap;
const response = await fetch(`${gatewayUrl}/auth.issueGameSession`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-session-token': bootstrap.sessionToken },
body: JSON.stringify({ sessionToken: bootstrap.sessionToken, profile }),
});
const payload = (await response.json()) as { result?: { data?: { gameToken?: string } } };
const gameToken = payload.result?.data?.gameToken;
if (!response.ok || !gameToken) throw new Error(`Game session issue failed: HTTP ${response.status}`);
await page.addInitScript(
({ token, gameProfile }) => {
localStorage.setItem('sammo-game-token', token);
localStorage.setItem('sammo-game-profile', gameProfile);
},
{ token: gameToken, gameProfile: profile }
);
return bootstrap;
};
const chooseFirstNonEmpty = async (select: Locator): Promise<string> => {
const value = await select.locator('option').evaluateAll((options) => {
const match =
options.find((option) => Number((option as HTMLOptionElement).value) > 0) ??
options.find((option) => (option as HTMLOptionElement).value !== '');
return (match as HTMLOptionElement | undefined)?.value ?? '';
});
if (!value) throw new Error('The command argument has no selectable value.');
await select.selectOption(value);
return value;
};
test('reserves every requested general and chief command through Chromium and restores the snapshot', async ({
page,
}, testInfo) => {
test.skip(!enabled, 'requires the isolated scenario 2601 snapshot and bootstrap session');
const bootstrap = await installSession(page);
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
const db = connector.prisma;
const general = await db.general.findFirstOrThrow({ where: { userId: bootstrap.user.id } });
if (!general.nationId || general.officerLevel < 5) throw new Error('The snapshot actor must be a chief.');
const originalGeneralTurns = await db.generalTurn.findMany({ where: { generalId: general.id } });
const originalGeneralRevision = await db.generalTurnRevision.findUnique({ where: { generalId: general.id } });
const originalNationTurns = await db.nationTurn.findMany({
where: { nationId: general.nationId, officerLevel: general.officerLevel },
});
const originalNationRevision = await db.nationTurnRevision.findUnique({
where: { nationId_officerLevel: { nationId: general.nationId, officerLevel: general.officerLevel } },
});
const reserve = async (
editor: Locator,
turn: number,
category: string,
command: RegExp,
fill?: (form: Locator) => Promise<void>
) => {
await editor.getByRole('button', { name: `${turn + 1}턴 명령 입력`, exact: true }).click();
const picker = editor.getByTestId('command-picker');
await picker.getByRole('button', { name: new RegExp(`^(?:국가:)?${category}$`) }).click();
const commandButton = picker.getByRole('button', { name: command }).first();
await expect(commandButton).toBeEnabled();
await commandButton.click();
if (fill) {
const form = picker.getByTestId('command-argument-form');
await fill(form);
await picker.getByRole('button', { name: '입력', exact: true }).click();
}
await expect(editor.locator('.action-column > div').nth(turn)).toHaveText(command);
};
try {
await page.goto('./');
const generalEditor = page.locator('[data-command-scope="general"]');
await expect(generalEditor).toBeVisible();
await reserve(generalEditor, 0, '전략', /^임관$/, async (form) => {
await chooseFirstNonEmpty(form.locator('select'));
});
await reserve(generalEditor, 1, '전략', /(랜덤|무작위).*임관/);
await reserve(generalEditor, 2, '내정', /^징병$/, async (form) => {
await chooseFirstNonEmpty(form.locator('select'));
await form.locator('input[type=number]').fill('1');
});
await reserve(generalEditor, 3, '군사', /^출병$/, async (form) => {
await chooseFirstNonEmpty(form.locator('select'));
});
await reserve(generalEditor, 4, '내정', /농지 ?개간/);
await reserve(generalEditor, 5, '계략', /^화계$/, async (form) => {
await chooseFirstNonEmpty(form.locator('select'));
});
await reserve(generalEditor, 6, '국가', /^증여$/, async (form) => {
await form.getByRole('button', { name: '쌀', exact: true }).click();
await form.locator('input[type=number]').fill('1');
await chooseFirstNonEmpty(form.locator('select'));
});
await reserve(generalEditor, 7, '개인', /장비 ?매매/, async (form) => {
await form.locator('#command-arg-itemType').selectOption('item');
const item = form.locator('#command-arg-itemCode');
const pillValue = await item.locator('option').filter({ hasText: '환약' }).first().getAttribute('value');
if (!pillValue) throw new Error('환약 is missing from the item command options.');
await item.selectOption(pillValue);
});
await page.screenshot({ path: testInfo.outputPath('general-requested-commands.png'), fullPage: true });
await page.locator('[data-navigation-id="chief-center"]').click();
await expect(page).toHaveURL(/\/chief-center$/);
const nationEditor = page.locator('[data-command-scope="nation"]');
await expect(nationEditor).toBeVisible();
await reserve(nationEditor, 0, '인사', /^포상$/, async (form) => {
await form.getByRole('button', { name: '쌀', exact: true }).click();
await form.locator('input[type=number]').fill('1');
await chooseFirstNonEmpty(form.locator('select'));
});
await reserve(nationEditor, 1, '인사', /^발령$/, async (form) => {
await chooseFirstNonEmpty(form.locator('select').nth(0));
await chooseFirstNonEmpty(form.locator('select').nth(1));
});
await reserve(nationEditor, 2, '특수', /^증축$/);
await reserve(nationEditor, 3, '전략', /^필사즉생$/);
const generalRows = await db.generalTurn.findMany({
where: { generalId: general.id, turnIdx: { in: [0, 1, 2, 3, 4, 5, 6, 7] } },
orderBy: { turnIdx: 'asc' },
});
expect(generalRows.map((row: { actionCode: string }) => row.actionCode)).toEqual([
'che_임관',
'che_랜덤임관',
'che_징병',
'che_출병',
'che_농지개간',
'che_화계',
'che_증여',
'che_장비매매',
]);
expect(generalRows[7]?.arg).toMatchObject({ itemType: 'item' });
const nationRows = await db.nationTurn.findMany({
where: {
nationId: general.nationId,
officerLevel: general.officerLevel,
turnIdx: { in: [0, 1, 2, 3] },
},
orderBy: { turnIdx: 'asc' },
});
expect(nationRows.map((row: { actionCode: string }) => row.actionCode)).toEqual([
'che_포상',
'che_발령',
'che_증축',
'che_필사즉생',
]);
await page.screenshot({ path: testInfo.outputPath('chief-requested-commands.png'), fullPage: true });
} finally {
await db.$transaction(async (transaction) => {
await transaction.generalTurn.deleteMany({ where: { generalId: general.id } });
if (originalGeneralTurns.length) await transaction.generalTurn.createMany({ data: originalGeneralTurns });
await transaction.generalTurnRevision.deleteMany({ where: { generalId: general.id } });
if (originalGeneralRevision)
await transaction.generalTurnRevision.create({ data: originalGeneralRevision });
await transaction.nationTurn.deleteMany({
where: { nationId: general.nationId, officerLevel: general.officerLevel },
});
if (originalNationTurns.length) await transaction.nationTurn.createMany({ data: originalNationTurns });
await transaction.nationTurnRevision.deleteMany({
where: { nationId: general.nationId, officerLevel: general.officerLevel },
});
if (originalNationRevision) await transaction.nationTurnRevision.create({ data: originalNationRevision });
});
await connector.disconnect();
}
});
@@ -1,445 +1,44 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import CommandArgumentForm from '../main/CommandArgumentForm.vue';
import CommandSelectForm from '../main/CommandSelectForm.vue';
import { getNpcColor } from '../../utils/npcColor';
type CommandOption = { value: string | number; label: string; color?: string };
type CommandInputField = {
key: string;
label: string;
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
required: boolean;
min?: number;
max?: number;
step?: number;
constValue?: string | number;
options?: CommandOption[];
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
tupleLabels?: string[];
};
type CommandAvailability = {
key: string;
name: string;
reqArg: boolean;
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
possible: boolean;
reason?: string;
inputFields: CommandInputField[];
};
type CommandTable = {
general: Array<{ category: string; values: CommandAvailability[] }>;
nation: Array<{ category: string; values: CommandAvailability[] }>;
inputOptions: {
cities: CommandOption[];
nations: CommandOption[];
generals: CommandOption[];
crewTypes: CommandOption[];
armTypes: CommandOption[];
nationTypes: CommandOption[];
colors: CommandOption[];
items: Record<string, CommandOption[]>;
};
};
type TurnRow = { index: number; time: string; action: string; isRest: boolean };
import { computed } from 'vue';
import ReservedCommandEditor from '../command/ReservedCommandEditor.vue';
import type { CommandPatternEntry, CommandTable, ReservedCommandRow } from '../command/types';
const props = defineProps<{
officerLevelText: string;
name: string | null;
npcState: number | null;
rows: TurnRow[];
rows: Array<ReservedCommandRow & { actionCode?: string }>;
commandTable: CommandTable | null;
loading: boolean;
generalId: number;
officerLevel: number;
mobile?: boolean;
}>();
const commandRows = computed(() => props.rows.map((row) => ({ ...row, action: row.actionCode ?? row.action })));
const emit = defineEmits<{
(event: 'reserve', payload: { index: number; action: string; args: Record<string, unknown> }): void;
(event: 'reserve-bulk', entries: CommandPatternEntry[]): void;
(event: 'shift', amount: number): void;
(event: 'repeat', amount: number): void;
}>();
const pickerTurnIndex = ref<number | null>(null);
const selectedCommand = ref<CommandAvailability | null>(null);
const commandArgs = ref<Record<string, unknown>>({});
const commandArgsValid = ref(false);
const editMode = ref(false);
const repeatAmount = ref(0);
const nationCategoryOrder = ['휴식', '인사', '외교', '특수', '전략', '국가'];
const nationOnlyTable = computed(() => {
if (!props.commandTable) return null;
const groupByCategory = new Map(props.commandTable.nation.map((group) => [group.category, group]));
const orderedGroups = nationCategoryOrder.map(
(category) => groupByCategory.get(category) ?? { category, values: [] }
);
const extraGroups = props.commandTable.nation.filter((group) => !nationCategoryOrder.includes(group.category));
return { ...props.commandTable, general: [], nation: [...orderedGroups, ...extraGroups] };
});
const nameColor = computed(() => (props.npcState !== null ? getNpcColor(props.npcState) : undefined));
const closePicker = () => {
pickerTurnIndex.value = null;
selectedCommand.value = null;
commandArgs.value = {};
commandArgsValid.value = false;
};
const openPicker = (turnIndex: number) => {
pickerTurnIndex.value = turnIndex;
selectedCommand.value = null;
commandArgs.value = {};
commandArgsValid.value = false;
};
const selectCommand = (commandKey: string) => {
const command =
props.commandTable?.nation.flatMap((group) => group.values).find((entry) => entry.key === commandKey) ?? null;
if (!command || pickerTurnIndex.value === null) return;
selectedCommand.value = command;
commandArgs.value = {};
commandArgsValid.value = !command.reqArg;
if (!command.reqArg) reserveSelected();
};
const reserveSelected = () => {
if (pickerTurnIndex.value === null || !selectedCommand.value || !commandArgsValid.value) return;
emit('reserve', {
index: pickerTurnIndex.value,
action: selectedCommand.value.key,
args: commandArgs.value,
});
closePicker();
};
</script>
<template>
<article class="chief-editor" :class="{ mobile: props.mobile }" data-testid="chief-command-editor">
<header v-if="!props.mobile" class="editor-header legacy-bg1">
<span>{{ props.officerLevelText }} :</span>
<strong :style="{ color: nameColor }">{{ props.name ?? '-' }}</strong>
</header>
<div class="editor-body">
<aside class="editor-controls">
<div v-if="props.mobile" class="mobile-identity legacy-bg1">
<strong :style="{ color: nameColor }">{{ props.name ?? '-' }}</strong>
<span>{{ props.officerLevelText }}</span>
</div>
<time>{{ props.rows[0]?.time ?? '--:--' }}</time>
<button type="button" @click="editMode = !editMode">{{ editMode ? '일반 모드' : '고급 모드' }}</button>
<select
v-model.number="repeatAmount"
class="repeat-control"
aria-label="반복 "
@change="repeatAmount > 0 && emit('repeat', repeatAmount)"
>
<option :value="0" disabled>반복</option>
<option v-for="amount in 6" :key="amount" :value="amount">{{ amount }}</option>
</select>
<button type="button" @click="emit('shift', -1)">당기기</button>
<button type="button" @click="emit('shift', 1)">미루기</button>
</aside>
<div class="editor-turns">
<div v-for="row in props.rows" :key="row.index" class="editor-turn-row">
<time>{{ row.time }}</time>
<strong>{{ row.action }}</strong>
<button
type="button"
class="edit-turn"
:aria-label="`${row.index + 1} 명령 입력`"
@click="openPicker(row.index)"
>
</button>
</div>
</div>
</div>
<div
v-if="pickerTurnIndex !== null"
:class="['command-picker', { 'has-command': selectedCommand }]"
data-testid="chief-command-picker"
>
<header>
<strong>{{ pickerTurnIndex + 1 }} 명령 입력</strong>
<button type="button" aria-label="명령 입력 닫기" @click="closePicker">×</button>
</header>
<CommandSelectForm
v-if="!selectedCommand"
:command-table="nationOnlyTable"
:loading="props.loading"
scope="nation"
@select="selectCommand"
/>
<button v-if="!selectedCommand" type="button" class="picker-close" @click="closePicker">닫기</button>
<template v-else>
<div class="selected-command">{{ selectedCommand.name }}</div>
<CommandArgumentForm
v-if="selectedCommand.reqArg && props.commandTable"
:command-key="selectedCommand.key"
:fields="selectedCommand.inputFields"
:options="props.commandTable.inputOptions"
@update:args="commandArgs = $event"
@update:valid="commandArgsValid = $event"
/>
<div class="picker-actions">
<button type="button" @click="selectedCommand = null">명령 다시 선택</button>
<button type="button" :disabled="!commandArgsValid" @click="reserveSelected">입력</button>
</div>
</template>
</div>
</article>
<ReservedCommandEditor
data-testid="chief-command-editor"
scope="nation"
:rows="commandRows"
:command-table="props.commandTable"
:loading="props.loading"
:storage-key="`core2026:nation:${props.generalId}:${props.officerLevel}`"
:compact="true"
:mobile="props.mobile"
:title="props.officerLevelText"
:name="props.name"
:current-time="props.rows[0]?.time"
@reserve-bulk="emit('reserve-bulk', $event)"
@shift="emit('shift', $event)"
@repeat="emit('repeat', $event)"
/>
</template>
<style scoped>
.chief-editor {
position: relative;
min-width: 0;
color: #fff;
background: #000;
}
.editor-header {
box-sizing: border-box;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
gap: 5px;
font-size: 16.8px;
font-weight: 400;
}
.editor-body {
display: flex;
flex-direction: column;
}
.editor-controls {
order: 2;
min-height: 85px;
padding: 2px 0;
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 3px;
align-items: stretch;
}
.editor-controls > time {
display: grid;
place-items: center;
border-radius: 4px;
background: #345c85;
font-variant-numeric: tabular-nums;
}
.editor-controls button,
.repeat-control {
min-height: 36px;
border: 0;
border-radius: 4px;
background: #444;
color: #fff;
font: inherit;
font-weight: 700;
}
.editor-controls button {
cursor: pointer;
}
.repeat-control {
padding: 0 8px;
text-align: center;
}
.editor-turns {
order: 1;
display: grid;
grid-template-rows: repeat(12, 30px);
}
.editor-turn-row {
display: grid;
grid-template-columns: 55px minmax(0, 1fr) 36px;
align-items: center;
min-width: 0;
}
.editor-turn-row > time {
height: 30px;
display: grid;
place-items: center;
background: #000;
font-variant-numeric: tabular-nums;
}
.editor-turn-row > strong {
height: 30px;
display: grid;
place-items: center;
overflow: hidden;
background: #0d204d;
font-weight: 400;
white-space: nowrap;
text-overflow: ellipsis;
}
.editor-turn-row:nth-child(odd) > strong {
background: #12295d;
}
.edit-turn {
align-self: stretch;
border: 0;
background: #444;
color: #fff;
cursor: pointer;
}
.command-picker {
position: absolute;
z-index: 20;
top: 54px;
left: 0;
box-sizing: border-box;
width: 100%;
height: 344px;
overflow: auto;
border: 0;
padding: 0;
background: #303030;
}
.command-picker > header {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
.command-picker.has-command {
padding: 8px;
}
.command-picker.has-command > header {
position: static;
width: auto;
height: auto;
display: flex;
justify-content: space-between;
align-items: center;
clip: auto;
margin-bottom: 8px;
}
.command-picker.has-command > header button {
width: 32px;
height: 28px;
}
.command-picker :deep(.command-form) {
gap: 4px;
padding-top: 0;
}
.command-picker :deep(.category-list) {
grid-template-columns: repeat(3, 1fr);
gap: 4px 2px;
}
.command-picker :deep(.category-btn) {
min-width: 0;
height: 35px;
border: 0;
border-radius: 4px;
padding: 4px;
background: #00a879;
color: #fff;
font-size: 16px;
font-weight: 700;
}
.command-picker :deep(.category-btn.active) {
background: #00bf91;
}
.command-picker :deep(.command-grid) {
grid-template-columns: repeat(2, 1fr);
gap: 4px;
margin-top: 4px;
}
.command-picker :deep(.command-item) {
min-height: 39px;
border: 1px solid #888;
border-radius: 5px;
padding: 5px;
display: grid;
place-items: center;
background: transparent;
color: #fff;
text-align: center;
font-size: 16px;
}
.command-picker :deep(.command-status) {
display: none;
}
.picker-close {
position: absolute;
right: 0;
bottom: 7px;
width: 65px;
height: 35px;
border: 0;
border-radius: 4px;
background: #444;
color: #fff;
font: inherit;
font-weight: 700;
}
.selected-command {
margin-bottom: 6px;
padding: 6px 8px;
background: #0d204d;
font-weight: 700;
}
.picker-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-top: 8px;
}
.picker-actions button {
min-height: 34px;
}
.mobile-identity {
display: grid;
grid-column: 1 / -1;
min-height: 60px;
place-items: center;
}
.chief-editor.mobile .editor-header {
display: none;
}
.chief-editor.mobile {
margin-top: 10px;
}
.chief-editor.mobile .editor-body {
height: 360px;
display: grid;
grid-template-columns: 109px 391px;
}
.chief-editor.mobile .editor-controls {
order: initial;
min-height: 0;
padding: 0;
grid-template-columns: 1fr;
align-content: start;
}
.chief-editor.mobile .editor-controls > time {
min-height: 36px;
}
.chief-editor.mobile .editor-controls > button {
min-height: 36px;
margin-top: 5px;
}
.chief-editor.mobile .repeat-control {
min-height: 36px;
margin-top: 5px;
}
.chief-editor.mobile .editor-turns {
order: initial;
padding-top: 10px;
}
.chief-editor.mobile .editor-turn-row {
grid-template-columns: 74px minmax(0, 1fr) 53px;
}
.chief-editor.mobile .command-picker {
position: absolute;
top: 30px;
left: 130px;
width: 370px;
height: 327px;
}
</style>
@@ -0,0 +1,99 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
const props = withDefaults(defineProps<{ disabled?: boolean; attribute?: string }>(), {
disabled: false,
attribute: 'data-turn-index',
});
const emit = defineEmits<{ (event: 'drag-start'): void; (event: 'drag-done', selected: Set<number>): void }>();
const root = ref<HTMLElement | null>(null);
const preview = ref(new Set<number>());
let dragging = false;
let startX = 0;
let startY = 0;
let box: HTMLDivElement | null = null;
let activePointerId: number | null = null;
const intersects = (left: DOMRect, right: DOMRect) =>
left.left <= right.right && left.right >= right.left && left.top <= right.bottom && left.bottom >= right.top;
const update = (clientX: number, clientY: number) => {
if (!root.value || !box) return;
const rootRect = root.value.getBoundingClientRect();
const x = clientX - rootRect.left;
const y = clientY - rootRect.top;
box.style.left = `${Math.min(startX, x)}px`;
box.style.top = `${Math.min(startY, y)}px`;
box.style.width = `${Math.abs(x - startX)}px`;
box.style.height = `${Math.abs(y - startY)}px`;
const boxRect = box.getBoundingClientRect();
const next = new Set<number>();
for (const element of root.value.children) {
if (element === box || !intersects(boxRect, element.getBoundingClientRect())) continue;
const raw = element.getAttribute(props.attribute);
if (raw !== null) next.add(Number(raw));
}
preview.value = next;
};
const pointerMove = (event: PointerEvent) =>
dragging && event.pointerId === activePointerId && update(event.clientX, event.clientY);
const pointerUp = (event: PointerEvent) => {
if (event.pointerId !== activePointerId) return;
if (!dragging) return;
dragging = false;
if (root.value?.hasPointerCapture(event.pointerId)) root.value.releasePointerCapture(event.pointerId);
activePointerId = null;
box?.remove();
box = null;
emit('drag-done', new Set(preview.value));
preview.value = new Set();
};
const pointerDown = (event: PointerEvent) => {
if (props.disabled || !root.value || event.button !== 0) return;
event.preventDefault();
const rect = root.value.getBoundingClientRect();
startX = event.clientX - rect.left;
startY = event.clientY - rect.top;
box = document.createElement('div');
box.className = 'drag-selection-box';
root.value.append(box);
dragging = true;
activePointerId = event.pointerId;
root.value.setPointerCapture(event.pointerId);
update(event.clientX, event.clientY);
emit('drag-start');
};
onMounted(() => {
root.value?.addEventListener('pointerdown', pointerDown);
root.value?.addEventListener('pointermove', pointerMove);
root.value?.addEventListener('pointerup', pointerUp);
root.value?.addEventListener('pointercancel', pointerUp);
});
onBeforeUnmount(() => {
root.value?.removeEventListener('pointerdown', pointerDown);
root.value?.removeEventListener('pointermove', pointerMove);
root.value?.removeEventListener('pointerup', pointerUp);
root.value?.removeEventListener('pointercancel', pointerUp);
});
</script>
<template>
<div ref="root" class="drag-select"><slot :selected="preview" /></div>
</template>
<style scoped>
.drag-select {
position: relative;
min-width: 0;
user-select: none;
}
.drag-select :deep(.drag-selection-box) {
position: absolute;
z-index: 30;
border: 1px solid #7ee8ff;
background: rgb(0 180 255 / 28%);
pointer-events: none;
}
</style>
@@ -0,0 +1,926 @@
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef, watch } from 'vue';
import CommandArgumentForm from '../main/CommandArgumentForm.vue';
import CommandSelectForm from '../main/CommandSelectForm.vue';
import DragSelect from './DragSelect.vue';
import {
amplifyPattern,
CommandStorage,
extractPattern,
moveQueueRange,
normalizedSelection,
selectStep,
} from './commandQueue';
import type { CommandAvailability, CommandPatternEntry, CommandTable, ReservedCommandRow } from './types';
const props = withDefaults(
defineProps<{
scope: 'general' | 'nation';
rows: ReservedCommandRow[];
commandTable: CommandTable | null;
loading: boolean;
storageKey: string;
maxPushTurn?: number;
compact?: boolean;
mobile?: boolean;
title?: string;
name?: string | null;
currentTime?: string;
}>(),
{ maxPushTurn: 6, compact: false, mobile: false, title: '', name: null, currentTime: '--:--' }
);
const emit = defineEmits<{
(event: 'reserve-bulk', entries: CommandPatternEntry[]): void;
(event: 'shift', amount: number): void;
(event: 'repeat', amount: number): void;
}>();
const storage = shallowRef<CommandStorage | null>(null);
const editMode = ref(false);
const activeCategory = ref('');
const selected = ref(new Set<number>());
const previousSelected = ref(new Set<number>([0]));
const dragKind = ref<'replace' | 'toggle' | null>(null);
const quickTarget = ref<number | null>(null);
const pickerOpen = ref(false);
const selectedCommand = ref<CommandAvailability | null>(null);
const commandArgs = ref<Record<string, unknown>>({});
const commandArgsValid = ref(false);
const expanded = ref(false);
const menuRevision = ref(0);
const pendingReservation = ref<CommandPatternEntry | null>(null);
const loadStorage = (key: string) => {
storage.value = new CommandStorage(key);
editMode.value = storage.value.editMode;
activeCategory.value = storage.value.activeCategory;
};
onMounted(() => {
loadStorage(props.storageKey);
});
watch(
() => props.storageKey,
(key, previousKey) => {
if (key !== previousKey) loadStorage(key);
}
);
watch([editMode, activeCategory], () => {
if (!storage.value) return;
storage.value.editMode = editMode.value;
storage.value.activeCategory = activeCategory.value;
storage.value.saveState();
if (editMode.value) quickTarget.value = null;
});
watch(
() => props.rows,
(rows) => {
const pending = pendingReservation.value;
if (!pending) return;
const saved = pending.turnList.every((index) => {
const row = rows[index];
return row?.action === pending.action && JSON.stringify(row.args ?? {}) === JSON.stringify(pending.args);
});
if (!saved) return;
storage.value?.pushRecent({ ...pending, turnList: [0] });
pendingReservation.value = null;
releaseSelection();
closePicker();
},
{ deep: true }
);
const scopedTable = computed<CommandTable | null>(() => {
if (!props.commandTable) return null;
return {
...props.commandTable,
general: props.scope === 'general' ? props.commandTable.general : [],
nation: props.scope === 'nation' ? props.commandTable.nation : [],
};
});
const labelMap = computed(() => {
const map = new Map<string, string>([['휴식', '휴식']]);
const groups = props.commandTable?.[props.scope] ?? [];
for (const group of groups) for (const command of group.values) map.set(command.key, command.name);
return map;
});
const displayRows = computed(() => props.rows.slice(0, expanded.value || props.compact ? props.rows.length : 14));
const selectedIndices = () => normalizedSelection(selected.value, previousSelected.value, props.rows.length);
const pattern = () => extractPattern(props.rows, selectedIndices());
const touchMenus = () => (menuRevision.value += 1);
const releaseSelection = () => {
if (selected.value.size) previousSelected.value = new Set(selected.value);
selected.value = new Set();
};
const setSelection = (next: Set<number>) => (selected.value = new Set(next));
const toggleSelection = (next: Set<number>) => {
const result = new Set(selected.value);
for (const index of next) {
if (result.has(index)) result.delete(index);
else result.add(index);
}
selected.value = result;
};
const finishDrag = (next: Set<number>) => {
if (dragKind.value === 'toggle') toggleSelection(next);
else setSelection(next);
dragKind.value = null;
};
const openPicker = (turnIndex?: number) => {
quickTarget.value = turnIndex ?? null;
pickerOpen.value = true;
selectedCommand.value = null;
commandArgs.value = {};
commandArgsValid.value = false;
};
const closePicker = () => {
pickerOpen.value = false;
quickTarget.value = null;
selectedCommand.value = null;
};
const selectCommand = (commandKey: string) => {
const command = props.commandTable?.[props.scope]
.flatMap((group) => group.values)
.find((entry) => entry.key === commandKey);
if (!command) return;
selectedCommand.value = command;
commandArgs.value = {};
commandArgsValid.value = !command.reqArg;
if (!command.reqArg) submitCommand();
};
const submitCommand = () => {
const command = selectedCommand.value;
if (!command || !commandArgsValid.value) return;
const turnList = quickTarget.value === null ? selectedIndices() : [quickTarget.value];
const entry = { turnList, action: command.key, args: { ...commandArgs.value }, label: command.name };
emit('reserve-bulk', [entry]);
pendingReservation.value = entry;
};
const applyPattern = (raw: CommandPatternEntry[] | undefined) => {
if (!raw?.length) return;
const entries = amplifyPattern(raw, selectedIndices(), props.rows.length);
if (entries.length) emit('reserve-bulk', entries);
releaseSelection();
};
const copy = () => {
storage.value?.saveClipboard(pattern());
releaseSelection();
touchMenus();
};
const cut = () => {
storage.value?.saveClipboard(pattern());
clearSelection();
touchMenus();
};
const paste = () => applyPattern(storage.value?.clipboard);
const clearSelection = () => {
emit('reserve-bulk', [{ turnList: selectedIndices(), action: '휴식', args: {}, label: '휴식' }]);
releaseSelection();
};
const repeatPattern = () => {
const indexes = selectedIndices();
if (!indexes.length) return;
const first = indexes[0] ?? 0;
const last = indexes.at(-1) ?? first;
const anchors: number[] = [];
for (let index = first; index < props.rows.length; index += last - first + 1) anchors.push(index);
const entries = amplifyPattern(pattern(), anchors, props.rows.length);
if (entries.length) emit('reserve-bulk', entries);
releaseSelection();
previousSelected.value = new Set(Array.from({ length: last - first + 1 }, (_, i) => first + i));
};
const rearrange = (direction: 'pull' | 'push') => {
emit('reserve-bulk', moveQueueRange(props.rows, selectedIndices(), direction));
releaseSelection();
};
const textCopy = async () => {
const lines = selectedIndices().map((index) => {
const row = props.rows[index];
return `${index + 1}${row?.label ?? labelMap.value.get(row?.action ?? '') ?? row?.action ?? ''}`;
});
await navigator.clipboard.writeText(lines.join('\n'));
releaseSelection();
};
const saveTemplate = () => {
const raw = pattern();
const fallback = raw
.flatMap((entry) =>
entry.turnList.map((index) => [index, (entry.label ?? entry.action).replace(/^che_|^cr_/, '')[0] ?? ''])
)
.sort((a, b) => Number(a[0]) - Number(b[0]))
.map((entry) => entry[1])
.join('');
const name = window.prompt('선택한 턴들의 별명을 지어주세요', fallback)?.trim();
if (!name) return;
storage.value?.setTemplate(name, raw);
releaseSelection();
touchMenus();
};
const clickOutsideMenu = (event: Event) => {
const details = (event.currentTarget as HTMLElement).closest('details');
if (details instanceof HTMLDetailsElement) details.open = false;
};
</script>
<template>
<article
class="reserved-command-editor"
:class="{ compact: props.compact, mobile: props.mobile, 'edit-mode': editMode, 'picker-open': pickerOpen }"
:data-command-scope="props.scope"
>
<header v-if="props.compact && !props.mobile" class="identity legacy-bg1">
<span>{{ props.title }} :</span><strong>{{ props.name ?? '-' }}</strong>
</header>
<div class="editor-layout">
<aside class="control-pad">
<div v-if="props.mobile && props.compact" class="mobile-identity legacy-bg1">
<strong>{{ props.name ?? '-' }}</strong
><span>{{ props.title }}</span>
</div>
<div class="clock">{{ props.currentTime }}</div>
<button type="button" @click="editMode = !editMode">{{ editMode ? '일반 모드' : '고급 모드' }}</button>
<details class="legacy-menu">
<summary>반복</summary>
<div class="menu-items">
<button
v-for="amount in props.maxPushTurn"
:key="amount"
@click="
emit('repeat', amount);
clickOutsideMenu($event);
"
>
{{ amount }}
</button>
</div>
</details>
<template v-if="editMode">
<details class="legacy-menu range-menu">
<summary>범위</summary>
<div class="menu-items">
<button
@click="
setSelection(new Set());
clickOutsideMenu($event);
"
>
해제
</button>
<button
@click="
setSelection(new Set(props.rows.map((_, i) => i)));
clickOutsideMenu($event);
"
>
모든턴
</button>
<button
@click="
setSelection(selectStep(props.rows.length, 0, 2));
clickOutsideMenu($event);
"
>
홀수턴
</button>
<button
@click="
setSelection(selectStep(props.rows.length, 1, 2));
clickOutsideMenu($event);
"
>
짝수턴
</button>
<template v-for="step in [3, 4, 5, 6, 7]" :key="step">
<small>{{ step }} 간격</small>
<div class="step-buttons">
<button
v-for="begin in step"
:key="begin"
@click="
setSelection(selectStep(props.rows.length, begin - 1, step));
clickOutsideMenu($event);
"
>
{{ begin }}
</button>
</div>
</template>
</div>
</details>
<details class="legacy-menu">
<summary>보관함</summary>
<div :key="`templates:${menuRevision}`" class="menu-items">
<div
v-for="[templateName, entries] in storage?.templates"
:key="`${menuRevision}:${templateName}`"
class="template-row"
>
<button
@click="
applyPattern(entries);
clickOutsideMenu($event);
"
>
{{ templateName }}
</button>
<button
aria-label="보관 명령 삭제"
@click="
storage?.deleteTemplate(templateName);
touchMenus();
"
>
삭제
</button>
</div>
<span v-if="!storage?.templates.size" class="empty-menu">비어 있음</span>
</div>
</details>
<details class="legacy-menu">
<summary>최근{{ props.compact ? '' : ' 실행' }}</summary>
<div :key="`recent:${menuRevision}`" class="menu-items">
<button
v-for="entry in [...(storage?.recent.values() ?? [])].reverse()"
:key="JSON.stringify([entry.action, entry.args])"
@click="
applyPattern([entry]);
clickOutsideMenu($event);
"
>
{{ entry.label ?? labelMap.get(entry.action) ?? entry.action }}
</button>
<span v-if="!storage?.recent.size" class="empty-menu">비어 있음</span>
</div>
</details>
</template>
<details class="legacy-menu">
<summary>당기기</summary>
<div class="menu-items">
<button
v-for="amount in props.maxPushTurn"
:key="amount"
@click="
emit('shift', -amount);
clickOutsideMenu($event);
"
>
{{ amount }}
</button>
</div>
</details>
<details class="legacy-menu">
<summary>미루기</summary>
<div class="menu-items">
<button
v-for="amount in props.maxPushTurn"
:key="amount"
@click="
emit('shift', amount);
clickOutsideMenu($event);
"
>
{{ amount }}
</button>
</div>
</details>
</aside>
<div class="queue-area">
<div class="queue-grid" :class="{ advanced: editMode }">
<DragSelect
v-if="editMode"
v-slot="{ selected: draggingSelection }"
class="index-column"
@drag-start="dragKind = 'toggle'"
@drag-done="finishDrag"
>
<button
v-for="row in displayRows"
:key="row.index"
type="button"
:data-turn-index="row.index"
:class="{
selected: selected.has(row.index),
previous: !selected.size && previousSelected.has(row.index),
preview: draggingSelection.has(row.index),
}"
>
{{ row.index + 1 }}
</button>
</DragSelect>
<DragSelect
v-slot="{ selected: draggingSelection }"
class="date-column"
:disabled="!editMode"
@drag-start="dragKind = 'replace'"
@drag-done="finishDrag"
>
<div
v-for="row in displayRows"
:key="row.index"
:data-turn-index="row.index"
:class="{ preview: draggingSelection.has(row.index) }"
>
<template v-if="props.compact">{{ row.time ?? '--:--' }}</template>
<template v-else>{{ row.year ? `${row.year} ${row.month}` : '' }}</template>
</div>
</DragSelect>
<div v-if="!props.compact" class="time-column">
<div v-for="row in displayRows" :key="row.index">{{ row.time ?? '--:--' }}</div>
</div>
<div class="action-column">
<div
v-for="row in displayRows"
:key="row.index"
:title="row.label ?? labelMap.get(row.action) ?? row.action"
>
{{ row.label ?? labelMap.get(row.action) ?? row.action }}
</div>
</div>
<div v-if="!editMode" class="edit-column">
<button
v-for="row in displayRows"
:key="row.index"
type="button"
:aria-label="`${row.index + 1} 명령 입력`"
@click="openPicker(row.index)"
>
</button>
</div>
</div>
<div v-if="editMode" class="advanced-actions">
<details class="legacy-menu selected-menu">
<summary>선택한 턴을</summary>
<div class="menu-items">
<button
@click="
cut();
clickOutsideMenu($event);
"
>
잘라내기
</button>
<button
@click="
copy();
clickOutsideMenu($event);
"
>
복사하기
</button>
<button
@click="
paste();
clickOutsideMenu($event);
"
>
붙여넣기
</button>
<button
@click="
textCopy();
clickOutsideMenu($event);
"
>
텍스트 복사
</button>
<button
@click="
saveTemplate();
clickOutsideMenu($event);
"
>
보관하기
</button>
<button
@click="
repeatPattern();
clickOutsideMenu($event);
"
>
반복하기
</button>
<button
@click="
clearSelection();
clickOutsideMenu($event);
"
>
비우기
</button>
<button
@click="
rearrange('pull');
clickOutsideMenu($event);
"
>
지우고 당기기
</button>
<button
@click="
rearrange('push');
clickOutsideMenu($event);
"
>
뒤로 밀기
</button>
</div>
</details>
<button type="button" class="select-command" @click="openPicker()">명령 선택 </button>
</div>
<div v-if="!props.compact" class="bottom-actions">
<button type="button" @click="emit('shift', -1)">당기기</button>
<button type="button" @click="emit('shift', 1)">미루기</button>
<button type="button" @click="expanded = !expanded">{{ expanded ? '접기' : '펼치기' }}</button>
</div>
</div>
</div>
<div v-if="pickerOpen" class="command-picker" data-testid="command-picker">
<header>
<strong>{{ quickTarget === null ? '선택한 턴' : `${quickTarget + 1}` }} 명령 입력</strong
><button type="button" aria-label="명령 입력 닫기" @click="closePicker">×</button>
</header>
<CommandSelectForm
v-if="!selectedCommand"
:command-table="scopedTable"
:loading="props.loading"
:scope="props.scope"
:active-category="activeCategory"
:allow-blocked="true"
@update:active-category="activeCategory = $event"
@select="selectCommand"
/>
<template v-else>
<div class="selected-command">
<strong>{{ selectedCommand.name }}</strong>
<small v-if="selectedCommand.reason"
>현재 상태: {{ selectedCommand.reason }} · 예약 입력은 가능합니다.</small
>
</div>
<CommandArgumentForm
v-if="selectedCommand.reqArg && props.commandTable"
:command-key="selectedCommand.key"
:fields="selectedCommand.inputFields"
:options="props.commandTable.inputOptions"
@update:args="commandArgs = $event"
@update:valid="commandArgsValid = $event"
/>
<div class="picker-actions">
<button :disabled="Boolean(pendingReservation)" @click="selectedCommand = null">
명령 다시 선택</button
><button :disabled="!commandArgsValid || Boolean(pendingReservation)" @click="submitCommand">
{{ pendingReservation ? '저장 ' : '입력' }}
</button>
</div>
</template>
</div>
</article>
</template>
<style scoped>
.reserved-command-editor {
position: relative;
width: 100%;
min-width: 0;
color: #fff;
background: #1d1d1d;
font: 14px/1.05 var(--sammo-font-sans);
}
.reserved-command-editor.picker-open {
z-index: 50;
}
.identity {
box-sizing: border-box;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
gap: 5px;
font-size: 16.8px;
font-weight: 400;
}
.identity strong {
font-weight: 400;
}
.editor-layout {
display: flex;
flex-direction: column;
}
.control-pad {
order: 0;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 4px;
padding: 3px 0;
}
.control-pad > button,
.clock,
.legacy-menu > summary,
.bottom-actions button,
.select-command {
box-sizing: border-box;
min-height: 34px;
border: 0;
border-radius: 4px;
display: grid;
place-items: center;
padding: 4px;
background: #444;
color: #fff;
font: inherit;
font-weight: 700;
cursor: pointer;
list-style: none;
}
.clock {
background: #345c85;
font-variant-numeric: tabular-nums;
}
.legacy-menu {
position: relative;
min-width: 0;
}
.legacy-menu > summary::-webkit-details-marker {
display: none;
}
.menu-items {
position: absolute;
z-index: 60;
top: 100%;
left: 0;
min-width: 130px;
max-height: 330px;
overflow: auto;
padding: 4px;
border: 1px solid #777;
background: #292929;
box-shadow: 0 4px 12px #000;
}
.menu-items > button,
.template-row button {
box-sizing: border-box;
width: 100%;
min-height: 30px;
border: 0;
padding: 5px 8px;
background: transparent;
color: #fff;
text-align: left;
cursor: pointer;
}
.menu-items > button:hover,
.template-row button:hover {
background: #147a64;
}
.menu-items small,
.empty-menu {
display: block;
padding: 5px 8px;
color: #bbb;
}
.step-buttons,
.template-row {
display: flex;
}
.step-buttons button {
flex: 1;
min-width: 28px;
min-height: 28px;
}
.template-row button:first-child {
flex: 1;
}
.template-row button:last-child {
width: auto;
color: #ffaaa0;
}
.queue-grid {
display: grid;
grid-template-columns: 75px 40px minmax(0, 1fr) 38px;
}
.queue-grid.advanced {
grid-template-columns: 34px 75px 40px minmax(0, 1fr);
}
.index-column,
.date-column,
.time-column,
.action-column,
.edit-column {
display: grid;
grid-auto-rows: 34.4px;
min-width: 0;
}
.edit-mode .index-column,
.edit-mode .date-column,
.edit-mode .time-column,
.edit-mode .action-column {
grid-auto-rows: 29.35px;
}
.index-column button,
.date-column > div,
.time-column > div,
.action-column > div,
.edit-column button {
min-width: 0;
min-height: 0;
border: 0;
display: grid;
place-items: center;
overflow: hidden;
padding: 2px;
color: #fff;
white-space: nowrap;
text-overflow: ellipsis;
}
.index-column button {
margin: 2px;
border-radius: 3px;
background: #006f98;
}
.index-column button.selected {
background: #18a9ce;
color: #00151d;
}
.index-column button.previous {
background: #168e58;
}
.index-column button.preview {
background: #eefcff;
color: #00151d;
}
.date-column > div {
background: #153c68;
}
.date-column > div.preview {
color: #00ffff;
}
.time-column > div {
background: #000;
font-variant-numeric: tabular-nums;
}
.action-column > div {
background: #0c1a41;
}
.action-column > div:nth-child(even) {
background: #071638;
}
.edit-column button {
background: #444;
cursor: pointer;
}
.advanced-actions {
display: grid;
grid-template-columns: 5fr 7fr;
}
.advanced-actions > * {
border-radius: 0 !important;
}
.bottom-actions {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 4px;
padding-top: 3px;
}
.command-picker {
position: absolute;
z-index: 80;
inset: 38px 0 auto 0;
box-sizing: border-box;
max-height: calc(100% - 38px);
overflow: auto;
padding: 6px;
border: 1px solid #888;
background: #303030;
box-shadow: 0 6px 16px #000;
}
.command-picker > header {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 32px;
}
.command-picker > header button {
width: 32px;
height: 28px;
}
.selected-command {
display: grid;
gap: 3px;
padding: 6px;
background: #0d204d;
}
.selected-command small {
color: #ffe0a0;
}
.picker-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-top: 6px;
}
.picker-actions button {
min-height: 34px;
}
.compact .editor-layout {
display: flex;
flex-direction: column;
}
.compact .queue-area {
order: 1;
}
.compact .control-pad {
order: 2;
min-height: 79px;
grid-template-columns: repeat(3, 1fr);
}
.compact .queue-grid {
grid-template-columns: 40px minmax(0, 1fr) 38px;
}
.compact .queue-grid.advanced {
grid-template-columns: 40px 32px minmax(0, 1fr);
}
.compact .date-column,
.compact .action-column,
.compact .edit-column,
.compact .index-column {
grid-auto-rows: 30px;
}
.compact .advanced-actions {
position: absolute;
right: 0;
bottom: 82px;
left: 0;
z-index: 15;
}
.compact .command-picker {
top: 54px;
height: 344px;
max-height: 344px;
}
@media (min-width: 1025px) {
.compact:not(.mobile) .command-picker {
position: fixed;
z-index: 1000;
top: 86px;
right: auto;
left: calc(50% - 476px);
width: 238px;
}
}
.mobile.compact .editor-layout {
height: 360px;
display: grid;
grid-template-columns: 109px 391px;
}
.mobile.compact .control-pad {
order: initial;
min-height: 0;
padding: 0;
grid-template-columns: 1fr;
align-content: start;
}
.mobile.compact .queue-area {
order: initial;
padding-top: 10px;
}
.mobile.compact .queue-grid {
grid-template-columns: 74px minmax(0, 1fr) 53px;
}
.mobile.compact .queue-grid.advanced {
grid-template-columns: 74px 53px minmax(0, 1fr);
}
.mobile-identity {
min-height: 60px;
display: grid;
place-items: center;
}
.mobile.compact .command-picker {
top: 30px;
left: 130px;
width: 370px;
height: 327px;
}
.mobile.compact .advanced-actions {
right: 0;
bottom: 0;
left: 109px;
}
</style>
@@ -0,0 +1,164 @@
import type { CommandPatternEntry, ReservedCommandRow } from './types';
const jsonClone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
const cloneArgs = (value: unknown): Record<string, unknown> => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
return jsonClone(value as Record<string, unknown>);
};
export const normalizedSelection = (
selected: ReadonlySet<number>,
previous: ReadonlySet<number>,
maxTurns: number
): number[] => {
const source = selected.size ? selected : previous.size ? previous : new Set([0]);
return [...source].filter((index) => index >= 0 && index < maxTurns).sort((left, right) => left - right);
};
export const selectStep = (maxTurns: number, begin: number, step: number): Set<number> => {
const result = new Set<number>();
for (let index = 0; index < maxTurns; index += 1) {
if ((index - begin) % step === 0) result.add(index);
}
return result;
};
export const extractPattern = (rows: ReservedCommandRow[], selection: number[]): CommandPatternEntry[] => {
if (!selection.length) return [];
const first = selection[0] ?? 0;
const grouped = new Map<string, CommandPatternEntry>();
for (const index of selection) {
const row = rows[index];
if (!row) continue;
const args = cloneArgs(row.args);
const key = JSON.stringify([row.action, args]);
const relative = index - first;
const existing = grouped.get(key);
if (existing) {
existing.turnList.push(relative);
} else {
grouped.set(key, { turnList: [relative], action: row.action, args, label: row.label });
}
}
return [...grouped.values()];
};
export const amplifyPattern = (
pattern: CommandPatternEntry[],
targets: number[],
maxTurns: number
): CommandPatternEntry[] => {
if (!pattern.length || !targets.length) return [];
const offsets = pattern.flatMap((entry) => entry.turnList);
if (!offsets.length) return [];
const minOffset = Math.min(...offsets);
const width = Math.max(...offsets) - minOffset + 1;
const anchors: number[] = [];
for (const target of [...targets].sort((a, b) => a - b)) {
const last = anchors.at(-1);
if (last === undefined || target >= last + width) anchors.push(target);
}
return pattern
.map((entry) => ({
...entry,
args: cloneArgs(entry.args),
turnList: entry.turnList
.flatMap((offset) => anchors.map((anchor) => anchor + offset - minOffset))
.filter((index) => index >= 0 && index < maxTurns),
}))
.filter((entry) => entry.turnList.length > 0);
};
export const moveQueueRange = (
rows: ReservedCommandRow[],
selection: number[],
direction: 'pull' | 'push',
restAction = '휴식'
): CommandPatternEntry[] => {
if (!selection.length) return [];
const first = selection[0] ?? 0;
const last = selection.at(-1) ?? first;
const width = last - first + 1;
const next = rows.map((row) => ({ action: row.action, args: cloneArgs(row.args), label: row.label }));
if (direction === 'pull') {
for (let index = first; index < rows.length - width; index += 1) next[index] = next[index + width]!;
for (let index = Math.max(first, rows.length - width); index < rows.length; index += 1) {
next[index] = { action: restAction, args: {}, label: '휴식' };
}
} else {
for (let index = rows.length - 1; index >= first + width; index -= 1) next[index] = next[index - width]!;
for (let index = first; index < Math.min(rows.length, first + width); index += 1) {
next[index] = { action: restAction, args: {}, label: '휴식' };
}
}
return next.map((entry, index) => ({ turnList: [index], ...entry }));
};
export class CommandStorage {
readonly recent = new Map<string, CommandPatternEntry>();
readonly templates = new Map<string, CommandPatternEntry[]>();
clipboard: CommandPatternEntry[] | undefined;
editMode = false;
activeCategory = '';
private readonly key: string;
private readonly maxRecent: number;
constructor(key: string, maxRecent = 10) {
this.key = key;
this.maxRecent = maxRecent;
this.load();
}
private read<T>(suffix: string, fallback: T): T {
try {
return JSON.parse(localStorage.getItem(`${this.key}:${suffix}`) ?? '') as T;
} catch {
return fallback;
}
}
private load(): void {
for (const entry of this.read<CommandPatternEntry[]>('recent', [])) {
this.recent.set(JSON.stringify([entry.action, entry.args]), entry);
}
for (const [name, entries] of this.read<Array<[string, CommandPatternEntry[]]>>('templates', [])) {
this.templates.set(name, entries);
}
this.clipboard = this.read<CommandPatternEntry[] | undefined>('clipboard', undefined);
this.editMode = localStorage.getItem(`${this.key}:editMode`) === '1';
this.activeCategory = this.read('category', '');
}
saveState(): void {
localStorage.setItem(`${this.key}:editMode`, this.editMode ? '1' : '0');
localStorage.setItem(`${this.key}:category`, JSON.stringify(this.activeCategory));
}
saveClipboard(pattern: CommandPatternEntry[]): void {
this.clipboard = jsonClone(pattern);
localStorage.setItem(`${this.key}:clipboard`, JSON.stringify(this.clipboard));
}
pushRecent(entry: CommandPatternEntry): void {
const key = JSON.stringify([entry.action, entry.args]);
this.recent.delete(key);
this.recent.set(key, jsonClone(entry));
while (this.recent.size > this.maxRecent) this.recent.delete(this.recent.keys().next().value as string);
localStorage.setItem(`${this.key}:recent`, JSON.stringify([...this.recent.values()]));
}
setTemplate(name: string, entries: CommandPatternEntry[]): void {
this.templates.set(name, jsonClone(entries));
this.saveTemplates();
}
deleteTemplate(name: string): void {
this.templates.delete(name);
this.saveTemplates();
}
private saveTemplates(): void {
localStorage.setItem(`${this.key}:templates`, JSON.stringify([...this.templates.entries()]));
}
}
@@ -0,0 +1,59 @@
export type CommandOption = { value: string | number; label: string; color?: string };
export type CommandInputField = {
key: string;
label: string;
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
required: boolean;
min?: number;
max?: number;
step?: number;
constValue?: string | number;
options?: CommandOption[];
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
tupleLabels?: string[];
};
export type CommandAvailability = {
key: string;
name: string;
reqArg: boolean;
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
possible: boolean;
reason?: string;
inputFields: CommandInputField[];
};
export type CommandGroup = { category: string; values: CommandAvailability[] };
export type CommandTable = {
general: CommandGroup[];
nation: CommandGroup[];
inputOptions: {
cities: CommandOption[];
nations: CommandOption[];
generals: CommandOption[];
crewTypes: CommandOption[];
armTypes: CommandOption[];
nationTypes: CommandOption[];
colors: CommandOption[];
items: Record<string, CommandOption[]>;
};
};
export type ReservedCommandRow = {
index: number;
action: string;
args: unknown;
label?: string;
time?: string;
year?: number;
month?: number;
};
export type CommandPatternEntry = {
turnList: number[];
action: string;
args: Record<string, unknown>;
label?: string;
};
@@ -1,376 +1,68 @@
<script setup lang="ts">
import { ref } from 'vue';
import CommandArgumentForm from './CommandArgumentForm.vue';
import CommandSelectForm from './CommandSelectForm.vue';
interface TurnCommandOption {
value: string | number;
label: string;
color?: string;
}
interface TurnCommandInputField {
key: string;
label: string;
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
required: boolean;
min?: number;
max?: number;
step?: number;
constValue?: string | number;
options?: TurnCommandOption[];
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
tupleLabels?: string[];
}
interface TurnCommandAvailability {
key: string;
name: string;
reqArg: boolean;
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
possible: boolean;
reason?: string;
inputFields: TurnCommandInputField[];
}
interface TurnCommandGroup {
category: string;
values: TurnCommandAvailability[];
}
interface TurnCommandTable {
general: TurnCommandGroup[];
nation: TurnCommandGroup[];
inputOptions: {
cities: TurnCommandOption[];
nations: TurnCommandOption[];
generals: TurnCommandOption[];
crewTypes: TurnCommandOption[];
armTypes: TurnCommandOption[];
nationTypes: TurnCommandOption[];
colors: TurnCommandOption[];
items: Record<string, TurnCommandOption[]>;
};
}
interface SelectedCityInfo {
id: number;
name: string;
nationName: string;
regionName: string;
}
interface ReservedTurnEntry {
index: number;
action: string;
args: unknown;
}
interface GeneralInfo {
id: number;
nationId: number;
officerLevel: number;
}
import { computed } from 'vue';
import { addMinutes } from 'date-fns';
import ReservedCommandEditor from '../command/ReservedCommandEditor.vue';
import type { CommandPatternEntry, CommandTable, ReservedCommandRow } from '../command/types';
const props = defineProps<{
commandTable: TurnCommandTable | null;
commandTable: CommandTable | null;
loading: boolean;
selectedCity: SelectedCityInfo | null;
reservedGeneralTurns: ReservedTurnEntry[] | null;
reservedNationTurns: ReservedTurnEntry[] | null;
general: GeneralInfo | null;
reservedGeneralTurns: Array<{ index: number; action: string; args?: unknown }> | null;
general: { id: number; turnTime?: string } | null;
currentYear?: number;
currentMonth?: number;
turnTermMinutes?: number;
storageKey?: string;
}>();
const emit = defineEmits<{
(event: 'set-general-turn', payload: { index: number; action: string; args: Record<string, unknown> }): void;
(event: 'set-general-turns', entries: CommandPatternEntry[]): void;
(event: 'shift-general-turns', amount: number): void;
(event: 'set-nation-turn', payload: { index: number; action: string; args: Record<string, unknown> }): void;
(event: 'shift-nation-turns', amount: number): void;
(event: 'repeat-general-turns', amount: number): void;
}>();
const activeCategory = ref('');
const selectedCommand = ref<TurnCommandAvailability | null>(null);
const selectedScope = ref<'general' | 'nation' | null>(null);
const commandArgs = ref<Record<string, unknown>>({});
const commandArgsValid = ref(false);
const handleSelect = (commandKey: string) => {
if (!props.commandTable) {
selectedCommand.value = null;
selectedScope.value = null;
return;
const labelMap = computed(() => {
const result = new Map<string, string>([['휴식', '휴식']]);
for (const group of props.commandTable?.general ?? []) {
for (const command of group.values) result.set(command.key, command.name);
}
for (const scope of ['general', 'nation'] as const) {
for (const group of props.commandTable[scope]) {
const match = group.values.find((entry) => entry.key === commandKey);
if (match) {
selectedCommand.value = match;
selectedScope.value = scope;
commandArgs.value = {};
commandArgsValid.value = !match.reqArg;
return;
}
}
}
selectedCommand.value = null;
selectedScope.value = null;
};
return result;
});
const canReserveSelected = (scope: 'general' | 'nation') => {
if (!selectedCommand.value) {
return false;
}
if (selectedScope.value !== scope) return false;
if (!selectedCommand.value.possible) {
return false;
}
if (!['available', 'needsInput'].includes(selectedCommand.value.status)) {
return false;
}
return commandArgsValid.value;
};
const reserveGeneralTurn = (index: number) => {
if (!selectedCommand.value) {
return;
}
emit('set-general-turn', { index, action: selectedCommand.value.key, args: commandArgs.value });
};
const reserveNationTurn = (index: number) => {
if (!selectedCommand.value) {
return;
}
emit('set-nation-turn', { index, action: selectedCommand.value.key, args: commandArgs.value });
};
const clearGeneralTurn = (index: number) => {
emit('set-general-turn', { index, action: '휴식', args: {} });
};
const clearNationTurn = (index: number) => {
emit('set-nation-turn', { index, action: '휴식', args: {} });
};
const canNationReserve = () => Boolean(props.general && props.general.nationId > 0 && props.general.officerLevel >= 5);
const rows = computed<ReservedCommandRow[]>(() => {
const base = props.general?.turnTime ? new Date(props.general.turnTime) : null;
const term = props.turnTermMinutes ?? 0;
const baseYear = props.currentYear ?? 0;
const baseMonth = props.currentMonth ?? 1;
return (props.reservedGeneralTurns ?? []).map((turn, offset) => {
const absoluteMonth = baseYear * 12 + baseMonth - 1 + offset;
const date = base && Number.isFinite(base.getTime()) ? addMinutes(base, offset * term) : null;
return {
...turn,
args: turn.args ?? {},
label: labelMap.value.get(turn.action) ?? turn.action,
year: Math.floor(absoluteMonth / 12),
month: (absoluteMonth % 12) + 1,
time: date
? term >= 5
? `${String(date.getUTCHours()).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}`
: `${String(date.getUTCMinutes()).padStart(2, '0')}:${String(date.getUTCSeconds()).padStart(2, '0')}`
: '--:--',
};
});
});
</script>
<template>
<div class="command-panel">
<div class="command-selection">
<div class="label">선택 도시</div>
<div class="value">
<span v-if="props.selectedCity">
{{ props.selectedCity.name }} · {{ props.selectedCity.nationName }} ·
{{ props.selectedCity.regionName }}
</span>
<span v-else>선택된 도시 없음</span>
</div>
</div>
<details class="command-editor">
<summary>고급 모드로</summary>
<CommandSelectForm
:command-table="props.commandTable"
:loading="props.loading"
:active-category="activeCategory"
@update:active-category="activeCategory = $event"
@select="handleSelect"
/>
<div class="command-selected">
<div class="label">선택 명령</div>
<div v-if="selectedCommand" class="value">
<div class="name">{{ selectedCommand.name }}</div>
<div class="meta">
<span>{{ selectedCommand.status === 'available' ? '가능' : '제한' }}</span>
<span v-if="selectedCommand.reqArg">추가 입력 필요</span>
</div>
</div>
<div v-else class="value muted">명령을 선택하세요.</div>
</div>
<CommandArgumentForm
v-if="selectedCommand?.reqArg && props.commandTable"
:command-key="selectedCommand.key"
:fields="selectedCommand.inputFields"
:options="props.commandTable.inputOptions"
@update:args="commandArgs = $event"
@update:valid="commandArgsValid = $event"
/>
</details>
<div class="reserved-section general-reserved">
<div class="reserved-header">
<span>일반 예턴</span>
<div class="reserved-actions">
<button @click="emit('shift-general-turns', -1)">앞당김</button>
<button @click="emit('shift-general-turns', 1)">밀기</button>
</div>
</div>
<div v-if="!props.reservedGeneralTurns" class="muted">예턴을 불러오지 못했습니다.</div>
<div v-else class="reserved-list">
<div v-for="turn in props.reservedGeneralTurns" :key="turn.index" class="reserved-item">
<div class="turn-label">#{{ turn.index + 1 }}</div>
<div class="turn-action">{{ turn.action }}</div>
<div class="turn-buttons">
<button :disabled="!canReserveSelected('general')" @click="reserveGeneralTurn(turn.index)">
배치
</button>
<button class="ghost" @click="clearGeneralTurn(turn.index)">휴식</button>
</div>
</div>
</div>
</div>
<details class="reserved-section nation-reserved">
<summary>국가 예턴</summary>
<div class="reserved-header">
<span>국가 예턴 편집</span>
<div class="reserved-actions">
<button :disabled="!canNationReserve()" @click="emit('shift-nation-turns', -1)">앞당김</button>
<button :disabled="!canNationReserve()" @click="emit('shift-nation-turns', 1)">밀기</button>
</div>
</div>
<div v-if="!canNationReserve()" class="muted">국가 예턴은 최고위 관직부터 가능합니다.</div>
<div v-else-if="!props.reservedNationTurns" class="muted">예턴을 불러오지 못했습니다.</div>
<div v-else class="reserved-list">
<div v-for="turn in props.reservedNationTurns" :key="turn.index" class="reserved-item">
<div class="turn-label">#{{ turn.index + 1 }}</div>
<div class="turn-action">{{ turn.action }}</div>
<div class="turn-buttons">
<button :disabled="!canReserveSelected('nation')" @click="reserveNationTurn(turn.index)">
배치
</button>
<button class="ghost" @click="clearNationTurn(turn.index)">휴식</button>
</div>
</div>
</div>
</details>
</div>
<ReservedCommandEditor
scope="general"
:rows="rows"
:command-table="props.commandTable"
:loading="props.loading"
:storage-key="props.storageKey ?? `core2026:general:${props.general?.id ?? 0}`"
:current-time="rows[0]?.time"
@reserve-bulk="emit('set-general-turns', $event)"
@shift="emit('shift-general-turns', $event)"
@repeat="emit('repeat-general-turns', $event)"
/>
</template>
<style scoped>
.command-panel {
display: flex;
flex-direction: column;
gap: 4px;
}
.command-editor > summary {
min-height: 28px;
padding: 4px 8px;
background: #444;
color: #fff;
cursor: pointer;
text-align: center;
}
.command-selection {
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
min-height: 24px;
border: 1px solid #666;
font-size: 12px;
}
.command-selection .label {
padding: 2px 5px;
background: #173d27;
color: #fff;
text-align: center;
}
.command-selection .value {
overflow: hidden;
padding: 2px 5px;
white-space: nowrap;
text-overflow: ellipsis;
}
.command-selected {
border: 1px solid #666;
padding: 3px 5px;
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
font-size: 12px;
}
.command-selected .label {
color: rgba(232, 221, 196, 0.6);
}
.command-selected .meta {
display: flex;
gap: 8px;
font-size: 0.7rem;
color: rgba(232, 221, 196, 0.6);
}
.reserved-section {
display: flex;
flex-direction: column;
gap: 0;
}
.reserved-header {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 0.75rem;
font-weight: 600;
}
.reserved-actions {
display: flex;
gap: 6px;
}
.reserved-actions button {
border: 1px solid rgba(201, 164, 90, 0.3);
padding: 4px 6px;
font-size: 0.7rem;
}
.reserved-list {
display: flex;
flex-direction: column;
gap: 0;
max-height: 420px;
overflow-y: auto;
}
.nation-reserved > summary {
min-height: 28px;
padding: 4px 8px;
background: #444;
cursor: pointer;
}
.reserved-item {
border: 1px solid rgba(201, 164, 90, 0.2);
min-height: 30px;
padding: 2px 4px;
display: grid;
grid-template-columns: 50px 1fr auto;
gap: 6px;
align-items: center;
font-size: 0.75rem;
}
.turn-label {
color: rgba(232, 221, 196, 0.6);
}
.turn-buttons {
display: flex;
gap: 4px;
}
.turn-buttons button {
border: 1px solid rgba(201, 164, 90, 0.3);
padding: 4px 6px;
font-size: 0.7rem;
}
.ghost {
background: transparent;
}
.muted {
color: rgba(232, 221, 196, 0.6);
font-size: 0.75rem;
}
</style>
@@ -26,6 +26,7 @@ const props = defineProps<{
loading: boolean;
activeCategory?: string;
scope?: 'all' | 'general' | 'nation';
allowBlocked?: boolean;
}>();
const emit = defineEmits<{
@@ -33,26 +34,42 @@ const emit = defineEmits<{
(event: 'update:activeCategory', category: string): void;
}>();
const nationCategoryOrder = ['휴식', '인사', '외교', '특수', '전략', '기타'] as const;
const effectiveScope = computed(() => {
if (props.commandTable?.general.length === 0 && props.commandTable.nation.length > 0) return 'nation';
if (props.commandTable?.nation.length === 0 && props.commandTable.general.length > 0) return 'general';
return props.scope ?? 'all';
});
const scopedGroups = computed(() => {
if (!props.commandTable) return { general: [] as CommandGroup[], nation: [] as CommandGroup[] };
const nationCommands = props.commandTable.nation.flatMap((group) =>
group.values.map((command) => ({ category: group.category === '국가' ? '특수' : group.category, command }))
);
const nation = nationCategoryOrder.map((category) => ({
category,
values: nationCommands.filter((entry) => entry.category === category).map((entry) => entry.command),
}));
return { general: props.commandTable.general, nation };
});
const categories = computed(() => {
if (!props.commandTable) {
return [] as Array<{ id: string; label: string; category: string; groupType: 'general' | 'nation' }>;
}
const general = props.commandTable.general.map((group) => ({
const general = scopedGroups.value.general.map((group) => ({
id: `general:${group.category}`,
label: group.category,
category: group.category,
groupType: 'general' as const,
}));
const nation = props.commandTable.nation.map((group) => ({
const nation = scopedGroups.value.nation.map((group) => ({
id: `nation:${group.category}`,
label: `국가:${group.category}`,
label: effectiveScope.value === 'nation' ? group.category : `국가:${group.category}`,
category: group.category,
groupType: 'nation' as const,
}));
if (props.scope === 'general') return general;
if (props.scope === 'nation') {
return nation.map((entry) => ({ ...entry, label: entry.category === '국가' ? '기타' : entry.category }));
}
if (effectiveScope.value === 'general') return general;
if (effectiveScope.value === 'nation') return nation;
return [...general, ...nation];
});
@@ -64,7 +81,7 @@ const selectedGroup = computed(() => {
const [scope, ...categoryParts] = selectedCategory.value.split(':');
const category = categoryParts.join(':');
return (
props.commandTable[scope === 'nation' ? 'nation' : 'general'].find((group) => group.category === category) ??
scopedGroups.value[scope === 'nation' ? 'nation' : 'general'].find((group) => group.category === category) ??
null
);
});
@@ -128,8 +145,9 @@ const commandTitle = (command: CommandAvailability) =>
'command-item',
command.status === 'available' ? 'ok' : '',
command.status === 'blocked' ? 'blocked' : '',
command.status === 'blocked' && props.allowBlocked ? 'reservable' : '',
]"
:disabled="!command.possible"
:disabled="!props.allowBlocked && !command.possible"
:title="commandTitle(command)"
@click="emit('select', command.key)"
>
@@ -204,6 +222,12 @@ const commandTitle = (command: CommandAvailability) =>
cursor: not-allowed;
}
.command-item.blocked.reservable {
color: #d8ccb1;
opacity: 1;
cursor: pointer;
}
.command-name {
font-weight: 600;
}
+23 -48
View File
@@ -45,9 +45,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
const messageContacts = ref<MessageContacts | null>(null);
const boardAccess = ref<BoardAccess | null>(null);
const reservedGeneralTurns = ref<ReservedTurnView[] | null>(null);
const reservedNationTurns = ref<ReservedTurnView[] | null>(null);
const reservedGeneralRevision = ref(0);
const reservedNationRevision = ref(0);
const globalRecords = ref<RecentRecord[]>([]);
const generalRecords = ref<RecentRecord[]>([]);
const worldHistory = ref<RecentRecord[]>([]);
@@ -261,9 +259,7 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
if (!context) {
reservedGeneralTurns.value = null;
reservedNationTurns.value = null;
reservedGeneralRevision.value = 0;
reservedNationRevision.value = 0;
boardAccess.value = null;
resetRecentRecords(null);
loading.value = false;
@@ -276,10 +272,6 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
}
const layoutPromise = mapLayout.value ? Promise.resolve(mapLayout.value) : trpc.world.getMapLayout.query();
const generalTurnsPromise = trpc.turns.reserved.getGeneral.query({ generalId: id });
const nationTurnsPromise =
context.general.nationId > 0 && context.general.officerLevel >= 5
? trpc.turns.reserved.getNation.query({ generalId: id })
: Promise.resolve(null);
const recordsPromise = trpc.general.getRecentRecords
.query({
lastGeneralRecordId,
@@ -302,7 +294,6 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
contacts,
access,
generalTurns,
nationTurns,
records,
nextFrontStatus,
] = await Promise.all([
@@ -314,7 +305,6 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
trpc.messages.getContacts.query({ generalId: id }),
trpc.board.getAccess.query(),
generalTurnsPromise,
nationTurnsPromise,
recordsPromise,
frontStatusPromise,
]);
@@ -328,8 +318,6 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
boardAccess.value = access;
reservedGeneralTurns.value = generalTurns.turns;
reservedGeneralRevision.value = generalTurns.revision;
reservedNationTurns.value = nationTurns?.turns ?? null;
reservedNationRevision.value = nationTurns?.revision ?? 0;
if (records) {
globalRecords.value = mergeRecentRecords(globalRecords.value, records.global);
generalRecords.value = mergeRecentRecords(generalRecords.value, records.general);
@@ -528,58 +516,46 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
}
};
const setNationTurn = async (turnIndex: number, action: string, args: Record<string, unknown> = {}) => {
const setGeneralTurns = async (
entries: Array<{ turnList: number[]; action: string; args: Record<string, unknown> }>
) => {
const id = generalId.value;
const currentGeneral = general.value;
if (!id || !currentGeneral) {
return;
}
if (currentGeneral.nationId <= 0 || currentGeneral.officerLevel < 5) {
return;
}
if (!id || !entries.length) return;
try {
const result = await trpc.turns.reserved.setNation.mutate({
const result = await trpc.turns.reserved.setGeneralBulk.mutate({
generalId: id,
turnIndex,
action,
args,
expectedRevision: reservedNationRevision.value,
entries,
expectedRevision: reservedGeneralRevision.value,
});
reservedNationTurns.value = result.turns;
reservedNationRevision.value = result.revision;
reservedGeneralTurns.value = result.turns;
reservedGeneralRevision.value = result.revision;
} catch (err) {
error.value = resolveErrorMessage(err);
const snapshot = await trpc.turns.reserved.getNation.query({ generalId: id }).catch(() => null);
const snapshot = await trpc.turns.reserved.getGeneral.query({ generalId: id }).catch(() => null);
if (snapshot) {
reservedNationTurns.value = snapshot.turns;
reservedNationRevision.value = snapshot.revision;
reservedGeneralTurns.value = snapshot.turns;
reservedGeneralRevision.value = snapshot.revision;
}
}
};
const shiftNationTurns = async (amount: number) => {
const repeatGeneralTurns = async (amount: number) => {
const id = generalId.value;
const currentGeneral = general.value;
if (!id || !currentGeneral) {
return;
}
if (currentGeneral.nationId <= 0 || currentGeneral.officerLevel < 5) {
return;
}
if (!id) return;
try {
const result = await trpc.turns.reserved.shiftNation.mutate({
const result = await trpc.turns.reserved.repeatGeneral.mutate({
generalId: id,
amount,
expectedRevision: reservedNationRevision.value,
expectedRevision: reservedGeneralRevision.value,
});
reservedNationTurns.value = result.turns;
reservedNationRevision.value = result.revision;
reservedGeneralTurns.value = result.turns;
reservedGeneralRevision.value = result.revision;
} catch (err) {
error.value = resolveErrorMessage(err);
const snapshot = await trpc.turns.reserved.getNation.query({ generalId: id }).catch(() => null);
const snapshot = await trpc.turns.reserved.getGeneral.query({ generalId: id }).catch(() => null);
if (snapshot) {
reservedNationTurns.value = snapshot.turns;
reservedNationRevision.value = snapshot.revision;
reservedGeneralTurns.value = snapshot.turns;
reservedGeneralRevision.value = snapshot.revision;
}
}
};
@@ -737,7 +713,6 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
messageContacts,
boardAccess,
reservedGeneralTurns,
reservedNationTurns,
globalRecords,
generalRecords,
worldHistory,
@@ -758,8 +733,8 @@ export const useMainDashboardStore = defineStore('mainDashboard', () => {
readLatestMessage,
deleteMessage,
setGeneralTurn,
setGeneralTurns,
shiftGeneralTurns,
setNationTurn,
shiftNationTurns,
repeatGeneralTurns,
};
});
@@ -8,6 +8,7 @@ import ChiefTurnCard from '../components/chief/ChiefTurnCard.vue';
import ChiefCommandEditor from '../components/chief/ChiefCommandEditor.vue';
import { trpc } from '../utils/trpc';
import { formatOfficerLevelText } from '../utils/nationFormat';
import type { CommandPatternEntry } from '../components/command/types';
type ChiefTurn = {
index: number;
@@ -103,6 +104,9 @@ type TurnRow = {
time: string;
action: string;
isRest: boolean;
args: unknown;
label: string;
actionCode: string;
};
const loading = ref(false);
@@ -243,6 +247,9 @@ const buildTurnRows = (chief: ChiefEntry): TurnRow[] => {
index: turn.index,
time: timeLabel,
action: actionLabel,
label: actionLabel,
actionCode: turn.action,
args: turn.args,
isRest: turn.action === '휴식',
};
});
@@ -296,14 +303,12 @@ const shiftTurns = async (amount: number) => {
}
};
const reserveTurn = async (payload: { index: number; action: string; args: Record<string, unknown> }) => {
const reserveTurns = async (entries: CommandPatternEntry[]) => {
if (!data.value || !isEditingAllowed.value) return;
try {
const result = await trpc.turns.reserved.setNation.mutate({
const result = await trpc.turns.reserved.setNationBulk.mutate({
generalId: data.value.me.id,
turnIndex: payload.index,
action: payload.action,
args: payload.args,
entries,
expectedRevision: selectedChief.value?.revision ?? 0,
});
updateMyTurns(result.turns, result.revision);
@@ -352,8 +357,10 @@ const repeatTurns = async (amount: number) => {
:rows="selectedChiefRows"
:command-table="commandTable"
:loading="commandLoading"
:general-id="data.me.id"
:officer-level="selectedChief.officerLevel"
:mobile="true"
@reserve="reserveTurn"
@reserve-bulk="reserveTurns"
@shift="shiftTurns"
@repeat="repeatTurns"
/>
@@ -411,7 +418,9 @@ const repeatTurns = async (amount: number) => {
:rows="chief.rows"
:command-table="commandTable"
:loading="commandLoading"
@reserve="reserveTurn"
:general-id="data.me.id"
:officer-level="chief.officerLevel"
@reserve-bulk="reserveTurns"
@shift="shiftTurns"
@repeat="repeatTurns"
/>
+15 -20
View File
@@ -20,6 +20,7 @@ import { formatLog } from '../utils/formatLog';
import { useSessionStore } from '../stores/session';
import { useMainDashboardStore } from '../stores/mainDashboard';
import { trpc } from '../utils/trpc';
import type { CommandPatternEntry } from '../components/command/types';
const session = useSessionStore();
const dashboard = useMainDashboardStore();
@@ -40,12 +41,10 @@ const {
nation,
worldMap,
mapLayout,
selectedCity,
commandTable,
messages,
boardAccess,
reservedGeneralTurns,
reservedNationTurns,
globalRecords,
generalRecords,
worldHistory,
@@ -94,20 +93,16 @@ onUnmounted(() => {
}
});
const reserveGeneralTurn = (payload: { index: number; action: string; args: Record<string, unknown> }) => {
void dashboard.setGeneralTurn(payload.index, payload.action, payload.args);
};
const shiftGeneralTurns = (amount: number) => {
void dashboard.shiftGeneralTurns(amount);
};
const reserveNationTurn = (payload: { index: number; action: string; args: Record<string, unknown> }) => {
void dashboard.setNationTurn(payload.index, payload.action, payload.args);
const reserveGeneralTurns = (entries: CommandPatternEntry[]) => {
void dashboard.setGeneralTurns(entries);
};
const shiftNationTurns = (amount: number) => {
void dashboard.shiftNationTurns(amount);
const repeatGeneralTurns = (amount: number) => {
void dashboard.repeatGeneralTurns(amount);
};
const loadMainData = async () => {
@@ -206,14 +201,14 @@ watch(
<CommandListPanel
:command-table="commandTable"
:loading="loading"
:selected-city="selectedCity"
:reserved-general-turns="reservedGeneralTurns"
:reserved-nation-turns="reservedNationTurns"
:general="general"
@set-general-turn="reserveGeneralTurn"
:current-year="lobbyInfo?.year"
:current-month="lobbyInfo?.month"
:turn-term-minutes="lobbyInfo?.turnTerm"
@set-general-turns="reserveGeneralTurns"
@shift-general-turns="shiftGeneralTurns"
@set-nation-turn="reserveNationTurn"
@shift-nation-turns="shiftNationTurns"
@repeat-general-turns="repeatGeneralTurns"
/>
</PanelCard>
</div>
@@ -329,14 +324,14 @@ watch(
<CommandListPanel
:command-table="commandTable"
:loading="loading"
:selected-city="selectedCity"
:reserved-general-turns="reservedGeneralTurns"
:reserved-nation-turns="reservedNationTurns"
:general="general"
@set-general-turn="reserveGeneralTurn"
:current-year="lobbyInfo?.year"
:current-month="lobbyInfo?.month"
:turn-term-minutes="lobbyInfo?.turnTerm"
@set-general-turns="reserveGeneralTurns"
@shift-general-turns="shiftGeneralTurns"
@set-nation-turn="reserveNationTurn"
@shift-nation-turns="shiftNationTurns"
@repeat-general-turns="repeatGeneralTurns"
/>
</PanelCard>
<PanelCard title="도시 정보" data-main-target="city">
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
amplifyPattern,
extractPattern,
moveQueueRange,
normalizedSelection,
selectStep,
} from '../src/components/command/commandQueue.ts';
const rows = ['A', 'B', 'A', 'C', '휴식', '휴식'].map((action, index) => ({
index,
action,
args: action === 'A' ? { value: 1 } : {},
label: action,
}));
void test('keeps the Ref selection fallback and periodic range rules', () => {
assert.deepEqual(normalizedSelection(new Set(), new Set([3, 1]), 6), [1, 3]);
assert.deepEqual([...selectStep(8, 1, 3)], [1, 4, 7]);
});
void test('extracts a relative pattern and repeats it from selected anchors', () => {
const pattern = extractPattern(rows, [0, 1, 2]);
assert.deepEqual(pattern, [
{ turnList: [0, 2], action: 'A', args: { value: 1 }, label: 'A' },
{ turnList: [1], action: 'B', args: {}, label: 'B' },
]);
assert.deepEqual(amplifyPattern(pattern, [0, 3], 6), [
{ turnList: [0, 3, 2, 5], action: 'A', args: { value: 1 }, label: 'A' },
{ turnList: [1, 4], action: 'B', args: {}, label: 'B' },
]);
});
void test('pull and push rewrite the queue with rest at the opened range', () => {
assert.deepEqual(
moveQueueRange(rows, [1, 2], 'pull').map((entry) => entry.action),
['A', 'C', '휴식', '휴식', '휴식', '휴식']
);
assert.deepEqual(
moveQueueRange(rows, [1, 2], 'push').map((entry) => entry.action),
['A', '휴식', '휴식', 'B', 'A', 'C']
);
});
+3
View File
@@ -13,6 +13,7 @@
"che_견문",
"che_내정특기초기화",
"che_전투특기초기화",
"che_장비매매",
"che_출병",
"che_주민선정",
"che_정착장려",
@@ -30,6 +31,7 @@
"che_소집해제",
"che_군량매매",
"che_물자조달",
"che_증여",
"che_헌납",
"che_이동",
"che_선양",
@@ -43,6 +45,7 @@
"che_부대탈퇴지시",
"che_발령",
"che_천도",
"che_증축",
"che_선전포고",
"che_불가침제의",
"che_불가침파기제의",