feat(saves): localize battle and preset names, merge overview form and guard cache writes
This commit is contained in:
1 parent
e6e75d92c6
commit
7cb1011f0d
11 files changed
+276
-59
No files matched your search
@@ -108,6 +108,9 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
|
||||
return Number.isNaN(parsed) ? iso : new Date(parsed).toLocaleString(i18n.language);
|
||||
};
|
||||
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const vehicleSeparator = language === 'zh' ? '、' : ', ';
|
||||
const vehicleLabel = (id: string): string => preview?.vehicleNames[id]?.[language] ?? id;
|
||||
const canImportSelection = options.importSettings || options.unlockVehicles;
|
||||
|
||||
return (
|
||||
@@ -190,8 +193,10 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
|
||||
{preview && (
|
||||
<div className="maintenance-confirm">
|
||||
<p>{t('saves.official.summary', { files: preview.files.length, presets: preview.presets.length, vehicles: preview.vehicles.length })}</p>
|
||||
{preview.presets.map((preset, index) => <p key={index}>{preset.title} · {preset.vehicles.join(', ')}</p>)}
|
||||
{preview.omitted.length > 0 && <p>{t('saves.official.omitted', { names: preview.omitted.join(', ') })}</p>}
|
||||
{preview.presets.map((preset, index) => (
|
||||
<p key={index}>{preset.title} · {preset.vehicles.map(vehicleLabel).join(vehicleSeparator)}</p>
|
||||
))}
|
||||
{preview.omitted.length > 0 && <p>{t('saves.official.omitted', { names: preview.omitted.map(vehicleLabel).join(vehicleSeparator) })}</p>}
|
||||
</div>
|
||||
)}
|
||||
{imported && <p className="small" role="status">{t('saves.official.done')}</p>}
|
||||
|
||||
@@ -18,6 +18,10 @@ export function SaveAvatarField({ copyId, avatar, disabled, onError }: SaveAvata
|
||||
const [preview, setPreview] = useState<{ id: string; data: string } | null>(null);
|
||||
const canPreview = choices?.some(({ id }) => id === selected) ?? false;
|
||||
|
||||
useEffect(() => {
|
||||
setSelected(avatar);
|
||||
}, [avatar]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
ipcInvoke('saves:avatars', { copyId })
|
||||
|
||||
@@ -90,45 +90,46 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
const submitEdits = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
if (!userId) return;
|
||||
const data = new FormData(event.currentTarget);
|
||||
const values: CurrencyEdits = {};
|
||||
for (const name of CURRENCIES) {
|
||||
const value = String(data.get(name) ?? '').trim();
|
||||
if (value) values[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value);
|
||||
}
|
||||
if (Object.keys(values).length === 0) return;
|
||||
setSaving(true);
|
||||
setMessage('');
|
||||
ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values })
|
||||
.then((updated) => {
|
||||
updateDetails(updated);
|
||||
setMessage(t('saves.saved'));
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
|
||||
const submitAccount = (event: FormEvent<HTMLFormElement>): void => {
|
||||
const submitOverview = (event: FormEvent<HTMLFormElement>): void => {
|
||||
event.preventDefault();
|
||||
if (!details || !userId) return;
|
||||
const data = new FormData(event.currentTarget);
|
||||
|
||||
const nick = String(data.get('nick') ?? '').trim();
|
||||
const days = String(data.get('premiumDays') ?? '').trim();
|
||||
const avatar = String(data.get('avatar') ?? '');
|
||||
const level = String(data.get('level') ?? '').trim();
|
||||
const edits: AccountEdits = {};
|
||||
if (nick !== details.save.nick) edits.nick = nick;
|
||||
if (avatar && avatar !== details.save.avatar) edits.avatar = avatar;
|
||||
if (level !== '' && Number(level) !== details.save.level) edits.level = Number(level);
|
||||
if (days !== '' && Number(days) !== details.save.premiumDays) edits.premiumDays = Number(days);
|
||||
if (Object.keys(edits).length === 0) return;
|
||||
const accountEdits: AccountEdits = {};
|
||||
if (nick && nick !== details.save.nick) accountEdits.nick = nick;
|
||||
if (avatar && avatar !== details.save.avatar) accountEdits.avatar = avatar;
|
||||
if (level !== '' && Number(level) !== details.save.level) accountEdits.level = Number(level);
|
||||
if (days !== '' && Number(days) !== details.save.premiumDays) accountEdits.premiumDays = Number(days);
|
||||
|
||||
const currencyValues: CurrencyEdits = {};
|
||||
for (const name of CURRENCIES) {
|
||||
const value = String(data.get(name) ?? '').trim();
|
||||
if (value) currencyValues[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value);
|
||||
}
|
||||
|
||||
const hasAccount = Object.keys(accountEdits).length > 0;
|
||||
const hasCurrencies = Object.keys(currencyValues).length > 0;
|
||||
if (!hasAccount && !hasCurrencies) return;
|
||||
|
||||
setSaving(true);
|
||||
setMessage('');
|
||||
ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits })
|
||||
.then((updated) => { updateDetails(updated); setMessage(t('saves.saved')); })
|
||||
(async () => {
|
||||
let updated: SaveDetails | null = null;
|
||||
if (hasAccount) {
|
||||
updated = await ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits: accountEdits });
|
||||
}
|
||||
if (hasCurrencies) {
|
||||
updated = await ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values: currencyValues });
|
||||
}
|
||||
if (updated) {
|
||||
updateDetails(updated);
|
||||
setMessage(t('saves.saved'));
|
||||
}
|
||||
})()
|
||||
.catch(onError)
|
||||
.finally(() => setSaving(false));
|
||||
};
|
||||
@@ -238,13 +239,29 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
|
||||
if (!details) return <Sheet title={title} aside={copy.name}><p className="lead">{t(userId ? 'saves.loading' : 'saves.empty')}</p></Sheet>;
|
||||
const { save } = details;
|
||||
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||
const vehicleSeparator = language === 'zh' ? '、' : ', ';
|
||||
const overviewKey = JSON.stringify([
|
||||
copy.id,
|
||||
save.userId,
|
||||
save.nick,
|
||||
save.avatar,
|
||||
save.level,
|
||||
save.premiumDays,
|
||||
save.currencies?.silverLions,
|
||||
save.currencies?.goldenEagles,
|
||||
save.currencies?.gjnCents,
|
||||
save.currencies?.freeRp,
|
||||
]);
|
||||
return (
|
||||
<Sheet title={title} aside={save.nick}>
|
||||
{section === 'overview' && (
|
||||
<>
|
||||
{readOnly && <p className="small">{t('saves.readOnly')}</p>}
|
||||
<Row label={t('saves.login')}>{save.login}</Row>
|
||||
<form key={JSON.stringify([copy.id, save.userId, save.nick, save.avatar, save.level, save.premiumDays])} onSubmit={submitAccount}>
|
||||
<Row label={t('saves.vehicles')}>{format.format(save.vehicleCount)}</Row>
|
||||
<Row label={t('saves.battles')}>{format.format(save.battleCount)}</Row>
|
||||
<form key={overviewKey} onSubmit={submitOverview}>
|
||||
<Row label={t('saves.nick')}>
|
||||
<input className="input" aria-label={t('saves.nick')} name="nick" defaultValue={save.nick} disabled={readOnly || saving} required />
|
||||
</Row>
|
||||
@@ -259,11 +276,6 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
<input className="input" aria-label={t('saves.premiumDays')} type="number" min="0" step="1"
|
||||
name="premiumDays" defaultValue={save.premiumDays} disabled={readOnly || saving} />
|
||||
</Row>
|
||||
<button type="submit" className="button" disabled={readOnly || saving}>{t('saves.saveAccount')}</button>
|
||||
</form>
|
||||
<Row label={t('saves.vehicles')}>{format.format(save.vehicleCount)}</Row>
|
||||
<Row label={t('saves.battles')}>{format.format(save.battleCount)}</Row>
|
||||
<form key={save.userId} onSubmit={submitEdits}>
|
||||
{CURRENCIES.map((name) => (
|
||||
<Row key={name} label={t(`saves.${name}`)}>
|
||||
<span>{save.currencies ? format.format(name === 'gjnCents' ? save.currencies[name] / 100 : save.currencies[name]) : '—'}</span>
|
||||
@@ -271,19 +283,31 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
|
||||
aria-label={t(`saves.${name}`)} disabled={readOnly || saving} />
|
||||
</Row>
|
||||
))}
|
||||
<button type="submit" className="button button-primary" disabled={readOnly || saving}>{t('saves.apply')}</button>
|
||||
{message && <p className="small" role="status">{message}</p>}
|
||||
<div className="save-overview-actions">
|
||||
<button type="submit" className="button button-primary" disabled={readOnly || saving}>{t('saves.apply')}</button>
|
||||
{message && <p className="small" role="status">{message}</p>}
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{section === 'battles' && (
|
||||
details.battles.length === 0 ? <p className="lead">{t('saves.noBattles')}</p> : details.battles.map((battle) => (
|
||||
<Row key={battle.id} label={battle.mission || battle.mode} hint={date(battle.time)}>
|
||||
<span>{battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')}</span>
|
||||
<span>{t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })}</span>
|
||||
<span>{battle.vehicles.join(', ')}</span>
|
||||
</Row>
|
||||
))
|
||||
details.battles.length === 0 ? <p className="lead">{t('saves.noBattles')}</p> : details.battles.map((battle) => {
|
||||
const missionText = battle.missionName[language] || battle.mission || battle.mode;
|
||||
const vehiclesText = battle.vehicleNames.map((entry) => entry[language]).join(vehicleSeparator);
|
||||
return (
|
||||
<Row key={battle.id} label={missionText} hint={date(battle.time)}>
|
||||
<div className="battle-row">
|
||||
<div className="battle-summary">
|
||||
<span className={battle.won === true ? 'ok' : battle.won === false ? 'warn' : undefined}>
|
||||
{battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')}
|
||||
</span>
|
||||
<span>{t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })}</span>
|
||||
</div>
|
||||
{vehiclesText && <div className="battle-vehicles">{vehiclesText}</div>}
|
||||
</div>
|
||||
</Row>
|
||||
);
|
||||
})
|
||||
)}
|
||||
{section === 'official' && (
|
||||
<OfficialSaveImport key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onImported={refreshSave} />
|
||||
|
||||
@@ -162,6 +162,11 @@
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.row-label {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.row-label small {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
|
||||
@@ -311,6 +311,38 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.save-overview-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.save-overview-actions .small {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.battle-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.battle-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.battle-vehicles {
|
||||
font-size: 12.5px;
|
||||
color: var(--text-dim);
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* ===== About ===== */
|
||||
.update-notes {
|
||||
white-space: pre-line;
|
||||
|
||||
@@ -4,10 +4,11 @@ import { CopyIdSchema } from './install.ts';
|
||||
export const LocalUserIdSchema = z.string().regex(/^\d+$/);
|
||||
|
||||
export const SaveKeysSchema = z.object({ copyId: CopyIdSchema, userId: LocalUserIdSchema });
|
||||
export const LocalizedNameSchema = z.object({ en: z.string(), zh: z.string() });
|
||||
export const SaveAvatarIdSchema = z.string().regex(/^cardicon_[a-z0-9_]+$/);
|
||||
export const SaveAvatarChoicesSchema = z.array(z.object({
|
||||
id: SaveAvatarIdSchema,
|
||||
name: z.object({ en: z.string(), zh: z.string() }),
|
||||
name: LocalizedNameSchema,
|
||||
}));
|
||||
export type SaveAvatarChoices = z.output<typeof SaveAvatarChoicesSchema>;
|
||||
|
||||
@@ -48,8 +49,10 @@ export const SaveDetailsSchema = z.object({
|
||||
save: SaveSummarySchema,
|
||||
maxLevel: z.number().int().positive().nullable(),
|
||||
battles: z.array(z.object({
|
||||
id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(), mode: z.string(),
|
||||
vehicles: z.array(z.string()), silverLions: z.number(), researchPoints: z.number(),
|
||||
id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(),
|
||||
missionName: LocalizedNameSchema, mode: z.string(),
|
||||
vehicles: z.array(z.string()), vehicleNames: z.array(LocalizedNameSchema),
|
||||
silverLions: z.number(), researchPoints: z.number(),
|
||||
})),
|
||||
owned: z.array(z.string()),
|
||||
research: z.array(z.object({ name: z.string(), points: z.number() })),
|
||||
@@ -87,6 +90,7 @@ export const OfficialPreviewSchema = z.object({
|
||||
files: z.array(z.object({ name: z.string(), version: z.number().int() })),
|
||||
presets: z.array(z.object({ country: z.string(), title: z.string(), vehicles: z.array(z.string()) })),
|
||||
vehicles: z.array(z.string()),
|
||||
vehicleNames: z.record(z.string(), LocalizedNameSchema),
|
||||
omitted: z.array(z.string()),
|
||||
});
|
||||
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
|
||||
|
||||
@@ -162,5 +162,12 @@ function readEntry(path: string): CacheEntry | undefined {
|
||||
}
|
||||
|
||||
function writeEntry(path: string, entry: CacheEntry): void {
|
||||
writeFileAtomic(path, JSON.stringify(entry));
|
||||
try {
|
||||
writeFileAtomic(path, JSON.stringify(entry));
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
// Another worker updating the same cache file on Windows can hold a brief lock; reading stays valid.
|
||||
if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.t
|
||||
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
|
||||
import { loadTuning } from '../../tuning/tuning.ts';
|
||||
import type { SaveLocation } from '../save-editor.ts';
|
||||
import { loadSaveLabels, localizeVehicleName } from '../save-labels.ts';
|
||||
import { readBackupBlk } from './backup-blk.ts';
|
||||
|
||||
const TYPES = {
|
||||
@@ -152,12 +153,17 @@ function prepare(location: SaveLocation, paths: readonly string[]) {
|
||||
|
||||
const presetVehicles = [...presetReferenced].filter((name) => known.has(name)).sort();
|
||||
const omitted = [...presetReferenced].filter((name) => !known.has(name)).sort();
|
||||
const labels = loadSaveLabels(location.dataFolder, location.gameFolder);
|
||||
const vehicleNames = Object.fromEntries(
|
||||
[...presetReferenced].map((name) => [name, localizeVehicleName(name, labels)]),
|
||||
);
|
||||
return {
|
||||
files, presets, presetVehicles, known, gameFiles, datasets,
|
||||
preview: {
|
||||
files: files.map(({ name, version }) => ({ name, version })),
|
||||
presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })),
|
||||
vehicles: presetVehicles,
|
||||
vehicleNames,
|
||||
omitted,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@ import { serverTimeNow } from '../profile/server-time.ts';
|
||||
import { setUpProfiles } from '../profiles-setup.ts';
|
||||
import { loadTuning } from '../tuning/tuning.ts';
|
||||
import { readSaveAvatar } from './save-avatars.ts';
|
||||
import { loadSaveLabels, localizeMissionName, localizeVehicleName, type SaveLabels } from './save-labels.ts';
|
||||
|
||||
export interface SaveLocation {
|
||||
readonly gameFolder: string;
|
||||
@@ -57,19 +58,24 @@ export function readSaveSnapshot(dataFolder: string, userId: string): BlkBlock |
|
||||
}
|
||||
}
|
||||
|
||||
function battleEntries(profile: BlkBlock) {
|
||||
function battleEntries(profile: BlkBlock, labels?: SaveLabels) {
|
||||
return (findBlock(profile, 'userlogs')?.blocks ?? [])
|
||||
.filter((entry) => intField(entry, 'type') === EULT_SESSION_RESULT)
|
||||
.map((entry) => {
|
||||
const body = findBlock(entry, 'body');
|
||||
const win = body && findParam(body, 'win')?.value;
|
||||
const mission = stringField(body, 'locName') || stringField(body, 'mission');
|
||||
const mode = stringField(body, 'eventId');
|
||||
const vehicles = (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [];
|
||||
return {
|
||||
id: entry.name,
|
||||
time: intField(entry, 'time'),
|
||||
won: win?.type === 'bool' ? win.value : null,
|
||||
mission: stringField(body, 'locName') || stringField(body, 'mission'),
|
||||
mode: stringField(body, 'eventId'),
|
||||
vehicles: (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [],
|
||||
mission,
|
||||
missionName: labels ? localizeMissionName(mission || mode, labels) : { en: mission || mode, zh: mission || mode },
|
||||
mode,
|
||||
vehicles,
|
||||
vehicleNames: vehicles.map((unitId) => (labels ? localizeVehicleName(unitId, labels) : { en: unitId, zh: unitId })),
|
||||
silverLions: intField(body, 'wpEarned'),
|
||||
researchPoints: intField(body, 'xpEarned'),
|
||||
};
|
||||
@@ -104,9 +110,10 @@ export function readSaveDetails(dataFolder: string, userId: string, gameFolder?:
|
||||
.filter(({ points }) => points > 0)
|
||||
: [];
|
||||
const thresholds = rankThresholds(dataFolder, gameFolder);
|
||||
const labels = loadSaveLabels(dataFolder, gameFolder);
|
||||
return {
|
||||
save: summary(account, profile, thresholds),
|
||||
battles: profile ? battleEntries(profile) : [],
|
||||
battles: profile ? battleEntries(profile, labels) : [],
|
||||
owned,
|
||||
research,
|
||||
maxLevel: thresholds.length || null,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
|
||||
import type { Dataset } from '../game-data/datasets/dataset.ts';
|
||||
import { parseLocalizedCsvMap, type LocalizedCsvText } from '../game-data/datasets/lang-csv.ts';
|
||||
import { GameFiles } from '../game-data/game-files.ts';
|
||||
|
||||
const LANGUAGE_PACK = 'lang.vromfs.bin';
|
||||
const UNIT_FILE = 'lang/units.csv';
|
||||
const MISSION_FILES = ['lang/missions_versus.csv', 'lang/missions_locations.csv', 'lang/missions_single.csv'] as const;
|
||||
const UNIT_SHOP_SUFFIX = '_shop';
|
||||
/** Gaijin uses control-picture and private-use code points for in-game nation flag glyphs. */
|
||||
const GAME_FONT_GLYPHS = /[\u2400-\u243f\ue000-\uf8ff]/g;
|
||||
|
||||
export interface SaveLabels {
|
||||
readonly units: Readonly<Record<string, LocalizedCsvText>>;
|
||||
readonly missions: Readonly<Record<string, LocalizedCsvText>>;
|
||||
}
|
||||
|
||||
const EMPTY_LABELS: SaveLabels = { units: {}, missions: {} };
|
||||
|
||||
const saveLabelsDataset: Dataset<SaveLabels> = {
|
||||
id: 'save-labels',
|
||||
version: 1,
|
||||
extract: (source) => {
|
||||
const available = new Set(source.listFiles(LANGUAGE_PACK));
|
||||
const units: Record<string, LocalizedCsvText> = {};
|
||||
if (available.has(UNIT_FILE)) {
|
||||
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, UNIT_FILE))) {
|
||||
if (!key.endsWith(UNIT_SHOP_SUFFIX)) continue;
|
||||
const unitId = key.slice(0, -UNIT_SHOP_SUFFIX.length);
|
||||
if (!unitId) continue;
|
||||
units[unitId] = stripGlyphs(text, unitId);
|
||||
}
|
||||
}
|
||||
|
||||
const missions: Record<string, LocalizedCsvText> = {};
|
||||
for (const file of MISSION_FILES) {
|
||||
if (!available.has(file)) continue;
|
||||
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, file))) {
|
||||
if (!(key in missions)) missions[key] = stripGlyphs(text, key);
|
||||
}
|
||||
}
|
||||
|
||||
return { units, missions };
|
||||
},
|
||||
};
|
||||
|
||||
export function loadSaveLabels(dataFolder: string, gameFolder: string | undefined): SaveLabels {
|
||||
if (!gameFolder) return EMPTY_LABELS;
|
||||
try {
|
||||
return new DatasetCache(dataFolder, new GameFiles(gameFolder), () => {}).load(saveLabelsDataset);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return EMPTY_LABELS;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function localizeVehicleName(unitId: string, labels: SaveLabels): LocalizedCsvText {
|
||||
return labels.units[unitId] ?? { en: unitId, zh: unitId };
|
||||
}
|
||||
|
||||
export function localizeMissionName(raw: string, labels: SaveLabels): LocalizedCsvText {
|
||||
if (!raw) return { en: '', zh: '' };
|
||||
const exact = lookupMission(raw, labels);
|
||||
if (exact) return exact;
|
||||
|
||||
const parts = raw.split(';').map((part) => part.trim()).filter(Boolean);
|
||||
if (parts.length <= 1) return { en: raw, zh: raw };
|
||||
|
||||
const resolved = parts.map((part) => lookupMission(part, labels) ?? { en: part, zh: part });
|
||||
return {
|
||||
en: joinMissionParts(resolved.map(({ en }) => en), false),
|
||||
zh: joinMissionParts(resolved.map(({ zh }) => zh), true),
|
||||
};
|
||||
}
|
||||
|
||||
function lookupMission(key: string, labels: SaveLabels): LocalizedCsvText | undefined {
|
||||
return labels.missions[key]
|
||||
?? (key.startsWith('missions/') ? labels.missions[key.slice('missions/'.length)] : labels.missions[`missions/${key}`]);
|
||||
}
|
||||
|
||||
function joinMissionParts(parts: readonly string[], cjk: boolean): string {
|
||||
let result = '';
|
||||
for (const part of parts) {
|
||||
if (!part) continue;
|
||||
if (!result) {
|
||||
result = part;
|
||||
} else if (cjk && (result.endsWith('】') || result.endsWith(']') || part.startsWith('【'))) {
|
||||
result += part;
|
||||
} else {
|
||||
result += ` ${part}`;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function stripGlyphs(text: LocalizedCsvText, fallback: string): LocalizedCsvText {
|
||||
const en = text.en.replace(GAME_FONT_GLYPHS, '').trim() || fallback;
|
||||
const zh = text.zh.replace(GAME_FONT_GLYPHS, '').trim() || en;
|
||||
return { en, zh };
|
||||
}
|
||||
@@ -2,12 +2,17 @@
|
||||
* Write a file so that a crash leaves either the old or the new content, never a mix:
|
||||
* write a temporary file next to it, flush it to disk, then rename it over the target.
|
||||
*/
|
||||
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
const TRANSIENT_RENAME_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
||||
const MAX_RENAME_ATTEMPTS = 6;
|
||||
const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
export function writeFileAtomic(path: string, content: Uint8Array | string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const temporary = `${path}.${process.pid}.tmp`;
|
||||
const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
||||
const fd = openSync(temporary, 'w');
|
||||
try {
|
||||
writeSync(fd, typeof content === 'string' ? Buffer.from(content, 'utf8') : content);
|
||||
@@ -15,5 +20,23 @@ export function writeFileAtomic(path: string, content: Uint8Array | string): voi
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
renameSync(temporary, path);
|
||||
try {
|
||||
renameWithRetry(temporary, path);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* ignore cleanup errors */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function renameWithRetry(source: string, target: string): void {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
renameSync(source, target);
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (attempt >= MAX_RENAME_ATTEMPTS || !code || !TRANSIENT_RENAME_ERRORS.has(code)) throw error;
|
||||
Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 25);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user