feat: synchronize account icons across game profiles

This commit is contained in:
2026-07-31 11:21:08 +00:00
parent c8adeeb47b
commit 5f20413552
87 changed files with 5755 additions and 280 deletions
+54 -13
View File
@@ -4,6 +4,8 @@ import { resolve } from 'node:path';
import { expect, test, type Page, type Route } from '@playwright/test';
const response = (data: unknown) => ({ result: { data } });
const gameBasePath = (process.env.PLAYWRIGHT_GAME_BASE_PATH ?? 'che').replace(/^\/+|\/+$/gu, '');
const gameProfile = process.env.PLAYWRIGHT_GAME_PROFILE ?? `${gameBasePath}:default`;
const operationNames = (route: Route) =>
decodeURIComponent(new URL(route.request().url()).pathname.split('/trpc/')[1] ?? '').split(',');
@@ -72,8 +74,8 @@ const generals = [
id: 10,
name: '조조',
ownerName: null,
picture: 'default.jpg',
imageServer: 0,
picture: '계정 icon.png',
imageServer: 1,
npcState: 0,
age: 35,
nationId: 1,
@@ -101,7 +103,7 @@ const generals = [
id: 20,
name: '유비',
ownerName: '통일유저',
picture: 'default.jpg',
picture: '장수/유비 1.png',
imageServer: 0,
npcState: 0,
age: 34,
@@ -145,10 +147,10 @@ const install = async (
accessPages: string[] = []
) => {
let generalDirectoryCalls = 0;
await page.addInitScript(() => {
await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_directory');
localStorage.setItem('sammo-game-profile', 'che:default');
});
localStorage.setItem('sammo-game-profile', profile);
}, gameProfile);
await page.route('**/image/general/**', (route) =>
route.fulfill({
status: 200,
@@ -156,10 +158,24 @@ const install = async (
body: '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#777"/></svg>',
})
);
await page.route('**/gateway/api/user-icons/**', (route) =>
route.fulfill({
status: 200,
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#777"/></svg>',
})
);
await page.route('**/image/icons/**', (route) =>
route.fulfill({
status: 200,
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#777"/></svg>',
})
);
await page.route('**/image/game/**', (route) =>
route.fulfill({ status: 200, contentType: 'image/jpeg', body: Buffer.from('') })
);
await page.route('**/che/api/trpc/**', async (route) => {
await page.route(`**/${gameBasePath}/api/trpc/**`, async (route) => {
const requestBody = route.request().postDataJSON() as
Record<string, { json?: { page?: unknown }; page?: unknown }> | undefined;
const results = operationNames(route).map((operation, operationIndex) => {
@@ -202,12 +218,12 @@ const install = async (
};
const installAccessBoundary = async (page: Page, accessPages: string[]) => {
await page.addInitScript(() => {
await page.addInitScript((profile) => {
localStorage.setItem('sammo-game-token', 'ga_access_boundary');
localStorage.setItem('sammo-game-profile', 'che:default');
});
localStorage.setItem('sammo-game-profile', profile);
}, gameProfile);
await page.route('**/image/**', (route) => route.abort('failed'));
await page.route('**/che/api/trpc/**', async (route) => {
await page.route(`**/${gameBasePath}/api/trpc/**`, async (route) => {
const requestBody = route.request().postDataJSON() as
Record<string, { json?: { page?: unknown }; page?: unknown }> | undefined;
const results = operationNames(route).map((operation, operationIndex) => {
@@ -315,6 +331,7 @@ test('nation and general directories preserve the fixed legacy Chromium geometry
expect(await header.evaluate((element) => getComputedStyle(element).backgroundImage)).toContain('back_green.jpg');
const icon = page.locator('.general-icon').first();
await expect(icon).toBeVisible();
await expect(icon).toHaveAttribute('src', '/gateway/api/user-icons/%EA%B3%84%EC%A0%95%20icon.png');
expect(
await icon.evaluate((element) => {
const image = element as HTMLImageElement;
@@ -328,6 +345,11 @@ test('nation and general directories preserve the fixed legacy Chromium geometry
};
})
).toEqual({ width: 64, height: 64, naturalWidth: 64, naturalHeight: 64, objectFit: 'fill' });
const nestedLegacyIcon = page.locator('.general-icon').nth(1);
await expect(nestedLegacyIcon).toHaveAttribute('src', '/image/general/%EC%9E%A5%EC%88%98/%EC%9C%A0%EB%B9%84%201.png');
await expect
.poll(() => nestedLegacyIcon.evaluate((element) => (element as HTMLImageElement).naturalWidth))
.toBe(64);
const artifactRoot = process.env.DIRECTORY_PARITY_ARTIFACT_DIR;
if (artifactRoot) {
@@ -354,6 +376,23 @@ test('general directory submits the legacy sort selector and keeps wounded/bonus
expect(await page.locator('#viewType').evaluate((element) => document.activeElement === element)).toBe(true);
});
test('a reused image element falls back for each newly broken account icon', async ({ page }) => {
await install(page);
await page.route('**/gateway/api/user-icons/**', (route) =>
route.fulfill({ status: 404, contentType: 'text/plain', body: 'missing' })
);
await page.goto('general-list');
const icon = page.locator('.general-icon').first();
await expect(icon).toHaveAttribute('src', /\/image\/icons\/default\.jpg$/);
await expect.poll(() => icon.evaluate((element) => (element as HTMLImageElement).naturalWidth)).toBe(64);
await icon.evaluate((element) => {
(element as HTMLImageElement).src = '/gateway/api/user-icons/second-missing.png';
});
await expect(icon).toHaveAttribute('src', /\/image\/icons\/default\.jpg$/);
await expect.poll(() => icon.evaluate((element) => (element as HTMLImageElement).naturalWidth)).toBe(64);
});
test('a failed resort retains the selected value and existing rows', async ({ page }) => {
await install(page, 'error-after-load');
await page.goto('general-list');
@@ -368,7 +407,7 @@ test('an authenticated account without a general is redirected away from both di
await install(page, 'no-general');
for (const path of ['nation-list', 'general-list']) {
await page.goto(path);
await expect(page).toHaveURL(/\/che\/join$/);
await expect(page).toHaveURL(new RegExp(`/${gameBasePath}/join$`, 'u'));
}
});
@@ -388,7 +427,9 @@ test('route access belongs only to the eight Ref page boundaries', async ({ page
for (const [path, pageName] of retained) {
const before = accessPages.length;
await page.goto(path);
await expect(page.locator('#app')).toHaveAttribute('data-v-app', '');
await expect.poll(() => accessPages.length).toBe(before + 1);
await page.waitForLoadState('networkidle');
expect(accessPages.at(-1)).toBe(pageName);
}
@@ -415,7 +456,7 @@ test('route access belongs only to the eight Ref page boundaries', async ({ page
for (const path of endpointOwned) {
const before = accessPages.length;
await page.goto(path);
await page.waitForTimeout(50);
await page.waitForLoadState('networkidle');
expect(accessPages).toHaveLength(before);
}
});
@@ -220,7 +220,7 @@ test.describe('scenario 903 live selection pool', () => {
).toBe(true);
expect(geometry.images.every((image) => image.objectFit === 'fill')).toBe(true);
const fallbackImages = page.locator(
'.card-holder .portrait img[data-fallback-applied="true"]'
'.card-holder .portrait img[data-general-icon-fallback-source]'
);
await expect(fallbackImages).not.toHaveCount(0);
expect(assetTracker.userIconRequests).toBe(await fallbackImages.count());
@@ -389,7 +389,7 @@ test.describe('scenario 903 live selection pool', () => {
const candidateCards = page.locator('.card-holder > .general-card');
const fallbackCard = candidateCards
.filter({ has: page.locator('img[data-fallback-applied="true"]') })
.filter({ has: page.locator('img[data-general-icon-fallback-source]') })
.first();
await expect(fallbackCard).toBeVisible();
const initialName = await fallbackCard.locator('h4').first().textContent();
@@ -397,7 +397,7 @@ test.describe('scenario 903 live selection pool', () => {
await fallbackCard.locator('.select-button').click();
await expect(page.locator('.selected-card')).toHaveCount(1);
await expect(
page.locator('.selected-card img[data-fallback-applied="true"]')
page.locator('.selected-card img[data-general-icon-fallback-source]')
).toBeVisible();
expect(assetTracker.userIconRequests).toBeGreaterThan(userIconRequestsBeforePreview);
await page.locator('.custom-form select').selectOption('che_안전');
+2 -1
View File
@@ -7,6 +7,8 @@
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test": "pnpm test:unit",
"test:unit": "node --test test/**/*.test.ts",
"test:e2e:troop": "playwright test troop.spec.ts --config e2e/playwright.config.mjs",
"test:e2e:nation-offices": "playwright test nationOffices.spec.ts --config e2e/playwright.config.mjs",
"test:e2e:npc-policy": "playwright test npcPolicy.spec.ts --config e2e/playwright.config.mjs",
@@ -20,7 +22,6 @@
"test:e2e:die-on-prestart-live": "pnpm --filter @sammo-ts/infra prisma:generate && pnpm --filter @sammo-ts/common build && pnpm --filter @sammo-ts/logic build && pnpm --filter @sammo-ts/infra build && pnpm --filter @sammo-ts/game-engine build && pnpm --filter @sammo-ts/game-api build && playwright test --config e2e/dieOnPrestart.live.playwright.config.mjs --tsconfig e2e/playwright.live.tsconfig.json",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"test": "node -e \"console.log('test not configured')\"",
"typecheck": "vue-tsc --noEmit"
},
"dependencies": {
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import type { MessageType } from '@sammo-ts/logic';
import { resolveMessageGeneralIconUrl, useDefaultGeneralIcon } from '../../utils/generalIcon';
interface MessageTarget {
generalId: number;
@@ -105,16 +106,7 @@ const isBright = (color: string): boolean => {
return red * 0.299 + green * 0.587 + blue * 0.114 > 160;
};
const iconUrl = computed(() => {
const icon = props.message.src.icon?.trim();
if (!icon) {
return '/image/icons/default.jpg';
}
if (icon.startsWith('/') || /^https?:\/\//i.test(icon)) {
return icon;
}
return `${import.meta.env.BASE_URL}${icon.replace(/^\/+/, '')}`;
});
const iconUrl = computed(() => resolveMessageGeneralIconUrl(props.message.src.icon));
const targetClass = (target: MessageTarget) => ({
'msg-target': true,
@@ -155,7 +147,14 @@ onBeforeUnmount(() => {
:data-id="message.id"
>
<div class="msg-icon">
<img class="general-icon" width="64" height="64" :src="iconUrl" :alt="message.src.generalName" />
<img
class="general-icon"
width="64"
height="64"
:src="iconUrl"
:alt="message.src.generalName"
@error="useDefaultGeneralIcon"
/>
</div>
<div class="msg-body">
<div class="msg-header">
@@ -0,0 +1,74 @@
export const DEFAULT_GENERAL_ICON_URL = '/image/icons/default.jpg';
export const DEFAULT_GATEWAY_USER_ICON_BASE_URL = '/gateway/api/user-icons';
export type GeneralIconSource = {
picture?: string | null;
imageServer?: number | null;
};
type GeneralIconOptions = {
legacyBaseUrl?: string;
userIconBaseUrl?: string;
};
const trimTrailingSlashes = (value: string): string => value.replace(/\/+$/u, '');
const encodeLegacyIconPath = (value: string): string =>
value
.split('/')
.map((segment) => {
if (segment === '.') return '%2E';
if (segment === '..') return '%2E%2E';
return encodeURIComponent(segment);
})
.join('/');
const configuredUserIconBaseUrl = (): string =>
import.meta.env?.VITE_GATEWAY_USER_ICON_BASE_URL?.trim() || DEFAULT_GATEWAY_USER_ICON_BASE_URL;
export const resolveGeneralIconUrl = (
source: GeneralIconSource,
{ legacyBaseUrl = '/image/icons', userIconBaseUrl = configuredUserIconBaseUrl() }: GeneralIconOptions = {}
): string => {
const picture = source.picture?.trim() || 'default.jpg';
const baseUrl = source.imageServer ? userIconBaseUrl : legacyBaseUrl;
const encodedPicture = source.imageServer ? encodeURIComponent(picture) : encodeLegacyIconPath(picture);
return `${trimTrailingSlashes(baseUrl)}/${encodedPicture}`;
};
export const resolveGeneralIconBackgroundImage = (source: GeneralIconSource, options?: GeneralIconOptions): string => {
const resolved = resolveGeneralIconUrl(source, options);
return `url(${JSON.stringify(resolved)}), url(${JSON.stringify(DEFAULT_GENERAL_ICON_URL)})`;
};
export const resolveMessageGeneralIconUrl = (
icon: string | null | undefined,
userIconBaseUrl = configuredUserIconBaseUrl()
): string => {
const normalized = icon?.trim();
if (!normalized) {
return DEFAULT_GENERAL_ICON_URL;
}
const userIconMatch = /^\/?d_pic\/(.+)$/u.exec(normalized);
if (userIconMatch) {
return resolveGeneralIconUrl({ picture: userIconMatch[1], imageServer: 1 }, { userIconBaseUrl });
}
if (normalized.startsWith('/') || /^https?:\/\//iu.test(normalized)) {
return normalized;
}
return `${import.meta.env.BASE_URL}${normalized.replace(/^\/+/u, '')}`;
};
export const useDefaultGeneralIcon = (event: Event): void => {
if (
typeof HTMLImageElement === 'undefined' ||
!(event.currentTarget instanceof HTMLImageElement) ||
event.currentTarget.dataset.generalIconFallbackSource === event.currentTarget.currentSrc
) {
return;
}
event.currentTarget.dataset.generalIconFallbackSource = event.currentTarget.currentSrc;
event.currentTarget.src = DEFAULT_GENERAL_ICON_URL;
};
+14 -22
View File
@@ -2,6 +2,7 @@
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type RankEntry = {
@@ -47,10 +48,7 @@ const loading = ref(false);
const errorMessage = ref('');
const data = ref<BestGeneralPayload | null>(null);
const imageUrl = (entry: { picture: string | null; imageServer: number }): string => {
const picture = entry.picture?.trim() || 'default.jpg';
return entry.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const imageUrl = (entry: { picture: string | null; imageServer: number }): string => resolveGeneralIconUrl(entry);
const closePage = async (): Promise<void> => {
if (window.opener) {
@@ -89,20 +87,10 @@ watch(viewMode, () => {
</div>
<div class="view-selector" role="group" aria-label="장수 유형">
<button
class="legacy-button"
type="button"
:aria-pressed="viewMode === 'user'"
@click="viewMode = 'user'"
>
<button class="legacy-button" type="button" :aria-pressed="viewMode === 'user'" @click="viewMode = 'user'">
유저 보기
</button>
<button
class="legacy-button"
type="button"
:aria-pressed="viewMode === 'npc'"
@click="viewMode = 'npc'"
>
<button class="legacy-button" type="button" :aria-pressed="viewMode === 'npc'" @click="viewMode = 'npc'">
NPC 보기
</button>
</div>
@@ -117,7 +105,14 @@ watch(viewMode, () => {
<li v-for="(entry, rank) in section.entries" :key="`${section.title}:${entry.id}:${rank}`">
<div class="hall-rank legacy-bg2">{{ rank + 1 }}</div>
<div class="hall-img">
<img class="generalIcon" :src="imageUrl(entry)" width="64" height="64" :alt="entry.name" />
<img
class="generalIcon"
:src="imageUrl(entry)"
width="64"
height="64"
:alt="entry.name"
@error="useDefaultGeneralIcon"
/>
</div>
<div class="hall-nation" :style="{ backgroundColor: entry.bgColor, color: entry.fgColor }">
{{ entry.nationName || '-' }}
@@ -134,11 +129,7 @@ watch(viewMode, () => {
<article v-for="section in data.uniqueItems" :key="section.slot" class="rankView legacy-bg0">
<h2 class="rankType legacy-bg1">{{ section.title }}</h2>
<ul>
<li
v-for="(entry, index) in section.entries"
:key="`${entry.itemKey}:${index}`"
class="no-value"
>
<li v-for="(entry, index) in section.entries" :key="`${entry.itemKey}:${index}`" class="no-value">
<div class="hall-rank legacy-bg2 item-name" :title="entry.itemInfo">{{ entry.itemName }}</div>
<div class="hall-img">
<img
@@ -147,6 +138,7 @@ watch(viewMode, () => {
width="64"
height="64"
:alt="entry.owner.name"
@error="useDefaultGeneralIcon"
/>
</div>
<div
+7 -4
View File
@@ -2,6 +2,7 @@
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type BoardArticle = Awaited<ReturnType<typeof trpc.board.getArticles.query>>[number];
@@ -37,10 +38,11 @@ const resizeTextArea = (element: HTMLTextAreaElement | null) => {
const formatDate = (value: string): string => value.slice(5, 16).replace('T', ' ');
const iconPath = (article: BoardArticle): string => {
const picture = article.authorPicture || 'default.jpg';
return article.authorImageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const iconPath = (article: BoardArticle): string =>
resolveGeneralIconUrl({
picture: article.authorPicture,
imageServer: article.authorImageServer,
});
const refreshArticles = async () => {
if (loading.value) {
@@ -177,6 +179,7 @@ onMounted(() => {
height="64"
:src="iconPath(article)"
:alt="`${article.authorName} 아이콘`"
@error="useDefaultGeneralIcon"
/>
</div>
<div class="article-text">{{ article.content }}</div>
@@ -3,6 +3,7 @@ import { computed, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { cityLevelMap, formatOfficerLevelText, regionMap } from '../utils/nationFormat';
import { getNpcColor } from '../utils/npcColor';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type Result = Awaited<ReturnType<typeof trpc.world.getCurrentCity.query>>;
@@ -93,10 +94,7 @@ const defenceTrainText = (value: number | null) => {
if (value >= 60) return '○';
return '△';
};
const generalImage = (general: General) => {
const picture = general.picture ?? 'default.jpg';
return general.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const generalImage = (general: General): string => resolveGeneralIconUrl(general);
</script>
<template>
@@ -270,7 +268,13 @@ const generalImage = (general: General) => {
:data-general-wounded="general.injury"
>
<td class="icon-cell">
<img class="general-icon" width="64" height="64" :src="generalImage(general)" />
<img
class="general-icon"
width="64"
height="64"
:src="generalImage(general)"
@error="useDefaultGeneralIcon"
/>
</td>
<td :style="{ color: getNpcColor(general.npcState) }">{{ general.name }}</td>
<td :class="{ wounded: general.injury !== 0 }">
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { formatOfficerLevelText } from '../utils/nationFormat';
import { getNpcColor } from '../utils/npcColor';
import { trpc } from '../utils/trpc';
@@ -45,10 +46,7 @@ const loadDirectory = async () => {
}
};
const imageUrl = (general: General): string => {
const picture = general.picture ?? 'default.jpg';
return general.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/general/${picture}`;
};
const imageUrl = (general: General): string => resolveGeneralIconUrl(general, { legacyBaseUrl: '/image/general' });
const injuredStat = (value: number, injury: number): number => Math.trunc((value * (100 - injury)) / 100);
onMounted(() => {
@@ -135,11 +133,20 @@ onMounted(() => {
:data-npc-type="general.npcState"
>
<td class="center">
<img class="general-icon" width="64" height="64" :src="imageUrl(general)" alt="" />
<img
class="general-icon"
width="64"
height="64"
:src="imageUrl(general)"
alt=""
@error="useDefaultGeneralIcon"
/>
</td>
<td class="center">
<span :style="{ color: getNpcColor(general.npcState) }">{{ general.name }}</span>
<template v-if="general.ownerName"><br /><small>({{ general.ownerName }})</small></template>
<template v-if="general.ownerName"
><br /><small>({{ general.ownerName }})</small></template
>
</td>
<td class="center">{{ general.age }}세</td>
<td class="center">
@@ -156,9 +163,7 @@ onMounted(() => {
<td class="center">{{ formatOfficerLevelText(general.officerLevel, general.nationLevel) }}</td>
<td class="center">
<span :class="{ wounded: general.injury > 0 }">{{
general.injury > 0
? injuredStat(general.leadership, general.injury)
: general.leadership
general.injury > 0 ? injuredStat(general.leadership, general.injury) : general.leadership
}}</span
><span v-if="general.leadershipBonus > 0" class="leadership-bonus"
>+{{ general.leadershipBonus }}</span
+10 -5
View File
@@ -2,6 +2,7 @@
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type HallOption = {
@@ -59,10 +60,7 @@ const selection = computed({
},
});
const imageUrl = (entry: HallEntry): string => {
const picture = entry.picture?.trim() || 'default.jpg';
return entry.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const imageUrl = (entry: HallEntry): string => resolveGeneralIconUrl(entry);
const closePage = async (): Promise<void> => {
if (window.opener) {
@@ -143,7 +141,14 @@ onMounted(loadOptions);
<li v-for="(entry, rank) in section.entries" :key="`${section.title}:${entry.generalId}:${rank}`">
<div class="hall-rank legacy-bg2">{{ rank + 1 }}</div>
<div class="hall-img">
<img class="generalIcon" :src="imageUrl(entry)" width="64" height="64" :alt="entry.name" />
<img
class="generalIcon"
:src="imageUrl(entry)"
width="64"
height="64"
:alt="entry.name"
@error="useDefaultGeneralIcon"
/>
</div>
<div
v-if="entry.serverName"
+5 -16
View File
@@ -8,6 +8,7 @@ import { useSessionStore } from '../stores/session';
import { cityLevelMap, formatOfficerLevelText, regionMap } from '../utils/nationFormat';
import { getNpcColor } from '../utils/npcColor';
import { formatSeoulDateTime } from '../utils/legacyDateTime';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
type JoinConfig = Awaited<ReturnType<typeof trpc.join.getConfig.query>>;
type JoinInput = Parameters<typeof trpc.join.createGeneral.mutate>[0];
@@ -161,20 +162,8 @@ const isTrpcBusinessError = (value: unknown): boolean => {
return Boolean(data && typeof data === 'object' && 'code' in data && typeof data.code === 'string');
};
const npcImageUrl = (candidate: { picture: string | null; imageServer: number }): string => {
const picture = candidate.picture ?? 'default.jpg';
const userIconBaseUrl = import.meta.env.VITE_GATEWAY_USER_ICON_BASE_URL ?? '/gateway/api/user-icons';
return candidate.imageServer
? `${userIconBaseUrl.replace(/\/$/, '')}/${encodeURIComponent(picture)}`
: `/image/icons/${encodeURIComponent(picture)}`;
};
const useDefaultNpcImage = (event: Event): void => {
const image = event.currentTarget;
if (image instanceof HTMLImageElement && !image.src.endsWith('/image/icons/default.jpg')) {
image.src = '/image/icons/default.jpg';
}
};
const npcImageUrl = (candidate: { picture: string | null; imageServer: number }): string =>
resolveGeneralIconUrl(candidate);
const npcReservation = ref<PossessReservation | null>(null);
const npcLoading = ref(false);
@@ -806,7 +795,7 @@ onUnmounted(() => {
:alt="`${npc.name} 얼굴`"
width="64"
height="64"
@error="useDefaultNpcImage"
@error="useDefaultGeneralIcon"
/>
</h4>
<p>
@@ -935,7 +924,7 @@ onUnmounted(() => {
:alt="`${general.name} 얼굴`"
width="64"
height="64"
@error="useDefaultNpcImage"
@error="useDefaultGeneralIcon"
/>
</td>
<td
+3 -3
View File
@@ -5,6 +5,7 @@ import { formatLog } from '../utils/formatLog';
import { formatSeoulDateTime } from '../utils/legacyDateTime';
import { isDefenceTrainPenaltyWaivedByScenarioEffect } from '@sammo-ts/logic';
import { useSessionStore } from '../stores/session';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
const SCREEN_MODE_KEY = 'sam.screenMode';
const CUSTOM_CSS_KEY = 'sam_customCSS';
@@ -307,10 +308,9 @@ onMounted(() => {
<div v-else class="general-table">
<div class="portrait-cell">
<img
:src="
data.general.picture ? `/image/game/${data.general.picture}` : '/image/game/default.jpg'
"
:src="resolveGeneralIconUrl(data.general, { legacyBaseUrl: '/image/game' })"
alt=""
@error="useDefaultGeneralIcon"
/>
<strong>{{ data.general.name }}</strong>
</div>
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { resolveGeneralIconBackgroundImage } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
import { cityLevelMap, formatOfficerLevelText, getNationChiefLevel, regionMap } from '../utils/nationFormat';
@@ -61,10 +62,7 @@ const chiefAssignments = computed(() => data.value?.chiefAssignments ?? {});
const cityNameMap = computed(() => new Map((data.value?.cityAssignments ?? []).map((city) => [city.id, city.name])));
const generalMap = computed(() => new Map((data.value?.generals ?? []).map((general) => [general.id, general])));
const imageUrl = (general: GeneralEntry | undefined): string => {
const picture = general?.picture ?? 'default.jpg';
return general?.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const imageBackground = (general: GeneralEntry | undefined): string => resolveGeneralIconBackgroundImage(general ?? {});
const officerLocked = (value: number, level: number): boolean => (value & (1 << level)) !== 0;
const chiefLocked = (level: number): boolean => officerLocked(data.value?.nation.chiefSet ?? 0, level);
const cityOfficerLocked = (city: PersonnelResponse['cityAssignments'][number], level: number): boolean =>
@@ -219,7 +217,7 @@ onMounted(() => void loadPersonnel());
<td class="green-cell role-cell">{{ formatOfficerLevelText(level, nationLevel) }}</td>
<td
class="general-icon"
:style="{ backgroundImage: `url('${imageUrl(chiefAssignments[level])}')` }"
:style="{ backgroundImage: imageBackground(chiefAssignments[level]) }"
/>
<td class="chief-name">
{{ chiefAssignments[level]?.name ?? '-' }}({{
@@ -4,6 +4,7 @@ import { useRouter } from 'vue-router';
import { useSessionStore } from '../stores/session';
import { formatSeoulDateTime } from '../utils/legacyDateTime';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type JoinConfig = Awaited<ReturnType<typeof trpc.join.getConfig.query>>;
@@ -107,12 +108,7 @@ const clearPendingAction = (action: PendingSelectionAction): void => {
const isIndeterminateTimeout = (value: unknown): boolean => {
if (!value || typeof value !== 'object' || !('data' in value)) return false;
const data = value.data;
return Boolean(
data &&
typeof data === 'object' &&
'code' in data &&
data.code === 'TIMEOUT'
);
return Boolean(data && typeof data === 'object' && 'code' in data && data.code === 'TIMEOUT');
};
const formatDateTime = (value: string | null | undefined): string => {
@@ -131,25 +127,14 @@ const shuffleNations = (source: Nation[]): Nation[] => {
return shuffled;
};
const userIconBaseUrl =
import.meta.env.VITE_GATEWAY_USER_ICON_BASE_URL ?? '/gateway/api/user-icons';
const imageUrl = (candidate: Candidate): string =>
candidate.imageServer
? `${userIconBaseUrl.replace(/\/$/, '')}/${candidate.picture}`
: `/image/icons/${candidate.picture}`;
const useFallbackImage = (event: Event): void => {
const image = event.currentTarget as HTMLImageElement;
if (image.dataset.fallbackApplied === 'true') return;
image.dataset.fallbackApplied = 'true';
image.src = '/image/icons/default.jpg';
};
const imageUrl = (candidate: Candidate): string => resolveGeneralIconUrl(candidate);
const personalityName = (key: string | null): string | null => {
if (!key) return null;
return personalities.value.find((entry) => entry.key === key)?.name ?? key;
};
const personalityInfo = (key: string | null): string =>
key ? personalities.value.find((entry) => entry.key === key)?.info ?? '' : '';
key ? (personalities.value.find((entry) => entry.key === key)?.info ?? '') : '';
const lightTextNationColors = new Set([
'',
@@ -294,8 +279,10 @@ onBeforeUnmount(() => {
<tbody>
<tr>
<td>
현재 : {{ serverInfo.currentYear }} {{ serverInfo.currentMonth }}
(<span class="cyan">{{ serverInfo.tickMinutes }} </span> 서버)<br />
현재 : {{ serverInfo.currentYear }} {{ serverInfo.currentMonth }} (<span class="cyan"
>{{ serverInfo.tickMinutes }} </span
>
서버)<br />
등록 장수 : 유저 {{ serverInfo.userGeneralCount }} / {{ serverInfo.maxGeneral }} +
<span class="cyan">NPC {{ serverInfo.npcGeneralCount }} </span>
</td>
@@ -319,7 +306,9 @@ onBeforeUnmount(() => {
}"
>
<td class="invitation-nation">{{ nation.name }}</td>
<td><div class="invitation-message">{{ nation.scoutMessage ?? '-' }}</div></td>
<td>
<div class="invitation-message">{{ nation.scoutMessage ?? '-' }}</div>
</td>
</tr>
</tbody>
</table>
@@ -337,11 +326,7 @@ onBeforeUnmount(() => {
<small v-else class="expired-text">- 만료 -</small>
<br />
<div class="card-holder">
<article
v-for="candidate in candidates"
:key="candidate.uniqueName"
class="general-card"
>
<article v-for="candidate in candidates" :key="candidate.uniqueName" class="general-card">
<h4 class="legacy-bg1 with-border">{{ candidate.generalName }}</h4>
<h4 class="portrait">
<img
@@ -349,7 +334,7 @@ onBeforeUnmount(() => {
:alt="candidate.generalName"
width="64"
height="64"
@error="useFallbackImage"
@error="useDefaultGeneralIcon"
/>
</h4>
<p>
@@ -398,7 +383,7 @@ onBeforeUnmount(() => {
:alt="selectedCandidate.generalName"
width="64"
height="64"
@error="useFallbackImage"
@error="useDefaultGeneralIcon"
/>
</h4>
<p>
@@ -486,12 +471,8 @@ onBeforeUnmount(() => {
</div>
<div class="footer-banner with-border">
<small>
삼국지 모의전투 HiDCHe core2026 / KOEI의 이미지를 사용, 응용하였습니다 / 제작 :
HideD /
<a
href="https://sam.hided.net/wiki/hidche/credit"
target="_blank"
rel="noopener noreferrer"
삼국지 모의전투 HiDCHe core2026 / KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD /
<a href="https://sam.hided.net/wiki/hidche/credit" target="_blank" rel="noopener noreferrer"
>Credit</a
>
</small>
+3 -4
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { resolveGeneralIconUrl, useDefaultGeneralIcon } from '../utils/generalIcon';
import { trpc } from '../utils/trpc';
type TroopList = Awaited<ReturnType<typeof trpc.troop.getList.query>>;
@@ -159,10 +160,7 @@ const hideMemberPopup = () => {
popupMember.value = null;
};
const iconPath = (troop: Troop): string => {
const picture = troop.leader?.picture || 'default.jpg';
return troop.leader?.imageServer ? `${import.meta.env.BASE_URL}d_pic/${picture}` : `/image/icons/${picture}`;
};
const iconPath = (troop: Troop): string => resolveGeneralIconUrl(troop.leader ?? {});
const formatTurn = (turnTime: string | null): string => {
if (!turnTime) {
@@ -212,6 +210,7 @@ onMounted(() => {
width="64"
:src="iconPath(troop)"
:alt="`${troop.leader?.name ?? '부대장'} 아이콘`"
@error="useDefaultGeneralIcon"
/>
</div>
<div class="troopLeaderName">{{ troop.leader?.name ?? '알 수 없음' }}</div>
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import {
DEFAULT_GENERAL_ICON_URL,
resolveGeneralIconBackgroundImage,
resolveGeneralIconUrl,
resolveMessageGeneralIconUrl,
} from '../src/utils/generalIcon.ts';
void describe('generalIcon', () => {
void it('routes user icons through the gateway and encodes the complete filename', () => {
assert.equal(
resolveGeneralIconUrl(
{ picture: '계정 icon/../1.jpg', imageServer: 1 },
{ userIconBaseUrl: '/gateway/api/user-icons/' }
),
'/gateway/api/user-icons/%EA%B3%84%EC%A0%95%20icon%2F..%2F1.jpg'
);
});
void it('preserves each view legacy base for non-user icons', () => {
assert.equal(
resolveGeneralIconUrl({ picture: '22.jpg', imageServer: 0 }, { legacyBaseUrl: '/image/general/' }),
'/image/general/22.jpg'
);
assert.equal(
resolveGeneralIconUrl({ picture: '22.jpg', imageServer: 0 }, { legacyBaseUrl: '/image/game' }),
'/image/game/22.jpg'
);
assert.equal(
resolveGeneralIconUrl({ picture: '장수/관우 1.png', imageServer: 0 }),
'/image/icons/%EC%9E%A5%EC%88%98/%EA%B4%80%EC%9A%B0%201.png'
);
assert.equal(
resolveGeneralIconUrl({ picture: '../secret.png', imageServer: 0 }),
'/image/icons/%2E%2E/secret.png'
);
});
void it('uses a deterministic default and safe layered fallback for CSS backgrounds', () => {
assert.equal(resolveGeneralIconUrl({ picture: null, imageServer: 0 }), '/image/icons/default.jpg');
assert.equal(
resolveGeneralIconBackgroundImage(
{ picture: 'custom.jpg', imageServer: 1 },
{ userIconBaseUrl: '/gateway/api/user-icons' }
),
'url("/gateway/api/user-icons/custom.jpg"), url("/image/icons/default.jpg")'
);
});
void it('translates legacy message d_pic references without changing absolute or external icons', () => {
assert.equal(
resolveMessageGeneralIconUrl('d_pic/user name.jpg', '/gateway/api/user-icons/'),
'/gateway/api/user-icons/user%20name.jpg'
);
assert.equal(resolveMessageGeneralIconUrl('/image/icons/22.jpg'), '/image/icons/22.jpg');
assert.equal(resolveMessageGeneralIconUrl('https://cdn.example/icon.jpg'), 'https://cdn.example/icon.jpg');
assert.equal(resolveMessageGeneralIconUrl(''), DEFAULT_GENERAL_ICON_URL);
});
});