Merge main into phase/39-school-owners.

Keep school owners and phase 41 opinions/portraits together; ResetAsync wipes all saves so shared AppHost tests stay isolated.
This commit is contained in:
Leonid Pershin
2026-08-20 08:36:13 +03:00
44 changed files with 1388 additions and 85 deletions
+22
View File
@@ -100,6 +100,7 @@ const ru = {
errorInvalidCatalog: 'Не удалось загрузить выбранные моды.',
errorUnknownCountry: 'Выбранная страна не найдена.',
errorUnknownNativeLanguage: 'Выбранный родной язык не входит в эту страну.',
errorInvalidPortraitSettings: 'Пресеты портретов этой школы заданы неверно.',
catalogLoadFailed: 'Не удалось загрузить каталог модов.',
modsTitle: 'Моды',
@@ -112,6 +113,10 @@ const ru = {
editMap: 'Редактировать карту',
mapDefaultHint: 'Будет использована карта по умолчанию.',
mapEditedHint: 'Карта изменена.',
portraitPresets: 'Пресеты портретов',
editPortraitPresets: 'Настроить модели',
portraitPresetsHint: 'Модель и промпты сохранятся в этой школе.',
portraitPresetsEdited: 'Заданы для этой школы.',
schoolSeed: 'Сид {seed}',
schoolSeedLabel: 'Сид',
schoolSeedHint: 'Необязательно. Чужой сид даёт ту же школу; пустое поле бросает свой.',
@@ -195,7 +200,13 @@ const ru = {
peopleTabApparel: 'Одежда',
peopleTabCarry: 'Ноша',
peopleTabNow: 'Сейчас',
peopleTabConnections: 'Связи',
peopleTabPortrait: 'Портрет',
peopleConnectionsFriends: 'Друзья',
peopleConnectionsEnemies: 'Враги',
peopleConnectionsSearch: 'Поиск по связям',
peopleConnectionsEmpty: 'Нет других связей.',
peopleOpinionValue: '{label} ({value})',
peopleAtHome: 'дома',
peopleApparelFit: 'Уместность: {value}',
peopleLockerYes: 'Есть шкафчик',
@@ -446,6 +457,7 @@ const en: Messages = {
errorInvalidCatalog: 'The selected packs could not be loaded.',
errorUnknownCountry: 'The selected country is not in the catalog.',
errorUnknownNativeLanguage: 'The selected native language is not in that country.',
errorInvalidPortraitSettings: 'This school\'s portrait presets are not valid.',
catalogLoadFailed: 'Could not load the mod catalog.',
modsTitle: 'Mods',
@@ -458,6 +470,10 @@ const en: Messages = {
editMap: 'Edit map',
mapDefaultHint: 'The default map will be used.',
mapEditedHint: 'The map has been edited.',
portraitPresets: 'Portrait presets',
editPortraitPresets: 'Configure models',
portraitPresetsHint: 'The model and prompts will be stored with this school.',
portraitPresetsEdited: 'Set for this school.',
schoolSeed: 'Seed {seed}',
schoolSeedLabel: 'Seed',
schoolSeedHint: 'Optional. A shared seed recreates the same people; leave blank to roll one.',
@@ -541,7 +557,13 @@ const en: Messages = {
peopleTabApparel: 'Clothes',
peopleTabCarry: 'Carried',
peopleTabNow: 'Now',
peopleTabConnections: 'Connections',
peopleTabPortrait: 'Portrait',
peopleConnectionsFriends: 'Friends',
peopleConnectionsEnemies: 'Enemies',
peopleConnectionsSearch: 'Search connections',
peopleConnectionsEmpty: 'No other connections.',
peopleOpinionValue: '{label} ({value})',
peopleAtHome: 'home',
peopleApparelFit: 'Fit: {value}',
peopleLockerYes: 'Has a locker',
+25
View File
@@ -71,6 +71,7 @@ export interface CreateSchoolOptions {
readonly countryId?: string;
readonly nativeLanguage?: string;
readonly seed?: number;
readonly portraitSettings?: SwarmUiSettingsFile;
}
export async function createSchool(
@@ -89,6 +90,7 @@ export async function createSchool(
countryId: extras.countryId ?? null,
nativeLanguage: extras.nativeLanguage ?? null,
seed: extras.seed ?? null,
portraitSettings: extras.portraitSettings ?? null,
}),
});
}
@@ -277,6 +279,28 @@ export interface PersonRel {
readonly id: string;
readonly fullName: string;
readonly female: boolean;
readonly opinion?: number | null;
readonly opinionLabel?: string | null;
}
export interface PersonOpinionLink {
readonly id: string;
readonly fullName: string;
readonly female: boolean;
readonly opinion: number;
readonly opinionLabel: string;
}
export interface PersonConnections {
readonly family: {
readonly parents: readonly PersonRel[];
readonly children: readonly PersonRel[];
readonly siblings: readonly PersonRel[];
readonly partners: readonly PersonRel[];
};
readonly friends: readonly PersonOpinionLink[];
readonly enemies: readonly PersonOpinionLink[];
readonly others: readonly PersonOpinionLink[];
}
export interface PersonCard {
@@ -316,6 +340,7 @@ export interface PersonCard {
readonly hasCustom: boolean;
readonly hasFullBody: boolean;
readonly customPortraitPrompt: string | null;
readonly connections: PersonConnections | null;
}
export interface WornItem {
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
fetchCatalog,
fetchMods,
fetchSwarmUiSettings,
type CatalogResponse,
type MapLayout,
type School,
@@ -20,6 +21,7 @@ vi.mock('../net/api.ts', async (importOriginal) => {
...actual,
fetchCatalog: vi.fn(),
fetchMods: vi.fn(),
fetchSwarmUiSettings: vi.fn(),
};
});
@@ -108,6 +110,31 @@ describe('createSchoolDialog', () => {
{ id: 'example', required: false, label: 'Example', version: '1.0', requires: ['core'] },
]);
vi.mocked(fetchCatalog).mockResolvedValue(catalog());
vi.mocked(fetchSwarmUiSettings).mockReset();
vi.mocked(fetchSwarmUiSettings).mockResolvedValue({
activePresetId: 'default',
presets: [
{
id: 'default',
label: 'Default',
model: 'template.safetensors',
steps: 4,
cfgScale: 1,
clipSkip: 1,
sampler: 'euler',
scheduler: 'normal',
seed: -1,
positive: 'base',
negative: 'neg',
positiveLoras: [],
negativeLoras: [],
avatar: { width: 512, height: 512, positive: '' },
custom: { width: 512, height: 512, positive: '' },
fullBody: { width: 512, height: 512, positive: '' },
},
],
ageRules: [],
});
});
afterEach(() => {
@@ -291,4 +318,22 @@ describe('map reset from the create editor', () => {
await vi.waitFor(() => expect(hint?.textContent).toBe(t('mapDefaultHint')));
void opened;
});
it('shows a portrait-preset button that stores settings on the school', async () => {
const opened = createSchoolDialog({
defaultStartDate: new Date('2024-09-01T00:00:00.000Z'),
suggestName: async () => 'North',
create: async () => school(),
});
await vi.waitFor(() => expect(fetchCatalog).toHaveBeenCalled());
const dialog = document.querySelector('dialog');
if (dialog === null) {
throw new Error('create dialog is missing');
}
const presets = byText(dialog, 'button', t('editPortraitPresets'));
expect(presets.nextElementSibling?.textContent).toBe(t('portraitPresetsHint'));
await vi.waitFor(() => expect(fetchSwarmUiSettings).toHaveBeenCalled());
void opened;
});
});
@@ -2,10 +2,12 @@ import {
ApiError,
fetchCatalog,
fetchMods,
fetchSwarmUiSettings,
type CatalogResponse,
type CreateSchoolOptions as CreateExtras,
type MapLayout,
type School,
type SwarmUiSettingsFile,
} from '../net/api.ts';
import { fromDateAndTimeInputs, toDateAndTimeInputs } from '../format/gameTime.ts';
import { getLocale } from '../i18n/locale.ts';
@@ -13,6 +15,7 @@ import { t } from '../i18n/strings.ts';
import { el } from './dom.ts';
import { mapEditorDialog } from './mapEditorDialog.ts';
import { Modal } from './modal.ts';
import { swarmUiSettingsDialog } from './swarmUiSettingsDialog.ts';
interface CreateSchoolOptions {
/** Prefilled start of the school year, straight from the server config. */
@@ -34,6 +37,8 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
let currentMap: MapLayout | null = null;
let countryId: string | null = null;
let nativeLanguageId: string | null = null;
let portraitSettings: SwarmUiSettingsFile | null = null;
let portraitEdited = false;
const modsField = el('div', { class: 'field' });
const modsLabel = el('span', { class: 'field__label' });
@@ -80,6 +85,16 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
el('div', { class: 'field__row' }, editMapButton, mapHint),
);
const presetsLabel = el('span', { class: 'field__label' });
const presetsButton = el('button', { class: 'button', type: 'button' });
const presetsHint = el('p', { class: 'hint' });
const presetsField = el(
'div',
{ class: 'field' },
presetsLabel,
el('div', { class: 'field__row' }, presetsButton, presetsHint),
);
const nameInput = el('input', { class: 'input', type: 'text' });
nameInput.maxLength = 40;
nameInput.required = true;
@@ -113,6 +128,7 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
countryField,
nativeField,
mapField,
presetsField,
seedField,
error,
el('div', { class: 'dialog__actions' }, cancelButton, submitButton),
@@ -127,6 +143,7 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
randomButton.toggleAttribute('disabled', value);
nativeRandomButton.toggleAttribute('disabled', value || languagesOf(catalog, countryId).length <= 1);
editMapButton.toggleAttribute('disabled', waiting);
presetsButton.toggleAttribute('disabled', waiting);
seedInput.toggleAttribute('disabled', value);
};
@@ -135,6 +152,10 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
error.hidden = false;
};
const paintPresetsHint = (): void => {
presetsHint.textContent = portraitEdited ? t('portraitPresetsEdited') : t('portraitPresetsHint');
};
const paintMapHint = (): void => {
if (catalog === null || currentMap === null) {
mapHint.textContent = '';
@@ -253,6 +274,9 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
startLabel.textContent = t('gameStart');
mapLabel.textContent = t('mapEditorTitle');
editMapButton.textContent = t('editMap');
presetsLabel.textContent = t('portraitPresets');
presetsButton.textContent = t('editPortraitPresets');
paintPresetsHint();
nameInput.placeholder = t('schoolNamePlaceholder');
randomButton.textContent = t('randomName');
randomButton.title = t('randomNameTitle');
@@ -279,6 +303,23 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
});
});
presetsButton.addEventListener('click', () => {
if (busy) {
return;
}
void swarmUiSettingsDialog(portraitSettings ?? undefined).then((next) => {
if (next === null) {
return;
}
portraitSettings = next;
portraitEdited = true;
paintPresetsHint();
presetsButton.focus();
});
});
nativeRandomButton.addEventListener('click', () => {
if (busy || catalog === null) {
return;
@@ -335,6 +376,7 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
countryId: countryId ?? undefined,
nativeLanguage: nativeLanguageId ?? undefined,
seed: seed ?? undefined,
portraitSettings: portraitSettings ?? undefined,
})
.then((school) => modal.close(school))
.catch((reason: unknown) => {
@@ -345,6 +387,15 @@ export function createSchoolDialog(options: CreateSchoolOptions): Promise<School
modal.element.append(title, form);
void paintMods();
void fetchSwarmUiSettings()
.then((settings) => {
if (portraitSettings === null) {
portraitSettings = settings;
}
})
.catch(() => {
/* Server copies swarmui.json at create if the form sends nothing. */
});
return modal.open(nameInput);
}
@@ -405,6 +456,8 @@ function describe(reason: unknown): string {
return t('errorUnknownCountry');
case 'unknown-native-language':
return t('errorUnknownNativeLanguage');
case 'invalid-portrait-settings':
return t('errorInvalidPortraitSettings');
default:
return reason.message;
}
+1 -7
View File
@@ -46,10 +46,6 @@ export class MainMenu {
class: 'button button--primary',
type: 'button',
});
private readonly settingsButton = el('button', {
class: 'button',
type: 'button',
});
private readonly logoutButton = el('button', {
class: 'button',
type: 'button',
@@ -66,7 +62,6 @@ export class MainMenu {
constructor(private readonly options: MainMenuOptions) {
this.createButton.addEventListener('click', () => void this.openCreateDialog());
this.settingsButton.addEventListener('click', () => void swarmUiSettingsDialog());
this.logoutButton.addEventListener('click', () => this.options.onLogout());
this.status.hidden = true;
@@ -75,7 +70,7 @@ export class MainMenu {
'header',
{ class: 'screen__header' },
this.title,
el('div', { class: 'screen__actions' }, this.logoutButton, this.settingsButton, this.createButton),
el('div', { class: 'screen__actions' }, this.logoutButton, this.createButton),
),
this.limitHint,
this.status,
@@ -99,7 +94,6 @@ export class MainMenu {
this.mineHeading.textContent = t('schoolsMine');
this.othersHeading.textContent = t('schoolsOthers');
this.createButton.textContent = t('createSchool');
this.settingsButton.textContent = t('settings');
this.logoutButton.textContent = t('sessionLogout');
this.emptyHint.textContent = t('emptySchools');
@@ -78,6 +78,7 @@ function personCard(): PersonCard {
hasCustom: false,
hasFullBody: false,
customPortraitPrompt: null,
connections: null,
};
}
@@ -64,6 +64,25 @@ function card(overrides: Partial<PersonCard> = {}): PersonCard {
hasCustom: false,
hasFullBody: false,
customPortraitPrompt: null,
connections: {
family: {
parents: [
{
id: 'f0.p0',
fullName: 'Иванова Ольга',
female: true,
opinion: 75,
opinionLabel: 'близкие друзья',
},
],
children: [],
siblings: [],
partners: [],
},
friends: [],
enemies: [],
others: [],
},
...overrides,
};
}
@@ -261,6 +280,17 @@ describe('renderPersonCard', () => {
expect(root.querySelector('.people__log-tools')).toBeNull();
});
it('does not mount the log table on the connections tab', () => {
setLocale('ru');
const root = document.createElement('div');
renderPersonCard(root, card(), () => {}, { tab: 'connections', log: logPage() });
expect(root.querySelector('[data-card-tab="connections"]')?.hasAttribute('hidden')).toBe(false);
expect(root.textContent).toContain('близкие друзья');
expect(root.querySelector('.people__log')).toBeNull();
expect(root.querySelector('.people__log-tools')).toBeNull();
});
it('pages the log on the now tab', () => {
setLocale('ru');
const onLogPage = vi.fn();
+131 -4
View File
@@ -4,13 +4,14 @@ import type {
PersonLogDir,
PersonLogPage,
PersonLogQuery,
PersonOpinionLink,
PersonRel,
PersonRole,
} from '../net/api.ts';
import { portraitUrl, type PortraitKind, type PortraitPrompt } from '../net/api.ts';
import { formatGameTimeOfDay } from '../format/gameTime.ts';
import { t, type MessageKey } from '../i18n/strings.ts';
import { el } from './dom.ts';
import { clear, el } from './dom.ts';
const ROLE_KEYS: Record<PersonRole, MessageKey> = {
student: 'peopleRoleStudent',
@@ -18,7 +19,7 @@ const ROLE_KEYS: Record<PersonRole, MessageKey> = {
parent: 'peopleRoleParent',
};
export type PersonCardTab = 'overview' | 'apparel' | 'carry' | 'now' | 'portrait';
export type PersonCardTab = 'overview' | 'apparel' | 'carry' | 'now' | 'connections' | 'portrait';
export interface RenderPersonCardOptions {
readonly place?: string;
@@ -110,6 +111,7 @@ export function renderPersonCard(
apparel: el('div', { class: 'people__tab-panel', dataset: { cardTab: 'apparel' } }),
carry: el('div', { class: 'people__tab-panel', dataset: { cardTab: 'carry' } }),
now: el('div', { class: 'people__tab-panel', dataset: { cardTab: 'now' } }),
connections: el('div', { class: 'people__tab-panel', dataset: { cardTab: 'connections' } }),
portrait: el('div', { class: 'people__tab-panel people__portrait-panel', dataset: { cardTab: 'portrait' } }),
};
@@ -118,6 +120,7 @@ export function renderPersonCard(
apparel: 'peopleTabApparel',
carry: 'peopleTabCarry',
now: 'peopleTabNow',
connections: 'peopleTabConnections',
portrait: 'peopleTabPortrait',
};
@@ -142,6 +145,7 @@ export function renderPersonCard(
fillApparel(panels.apparel, card);
fillCarry(panels.carry, card);
fillNow(panels.now, card, options.away === true, tab === 'now' ? options.log : null, options);
fillConnections(panels.connections, card, onRelative);
fillPortrait(panels.portrait, card, options);
const showTab = (next: PersonCardTab): void => {
@@ -160,7 +164,7 @@ export function renderPersonCard(
showTab(tab);
parent.append(tabs, panels.overview, panels.apparel, panels.carry, panels.now, panels.portrait);
parent.append(tabs, panels.overview, panels.apparel, panels.carry, panels.now, panels.connections, panels.portrait);
}
function fillOverview(parent: HTMLElement, card: PersonCard, onRelative: (id: string) => void): void {
@@ -253,7 +257,47 @@ function fillCarry(parent: HTMLElement, card: PersonCard): void {
);
}
parent.append(grid);
parent.append(grid );
}
function fillConnections(parent: HTMLElement, card: PersonCard, onRelative: (id: string) => void): void {
const connections = card.connections;
if (connections === null) {
return;
}
const family = section(t('peopleFamily'));
appendRelativesWithOpinion(family, t('peopleParents'), connections.family.parents, onRelative);
appendRelativesWithOpinion(family, t('peopleChildren'), connections.family.children, onRelative);
appendRelativesWithOpinion(family, t('peopleSiblings'), connections.family.siblings, onRelative);
appendRelativesWithOpinion(family, t('peoplePartners'), connections.family.partners, onRelative);
if (family.childElementCount > 1) {
parent.append(family);
}
appendOpinionLinks(parent, t('peopleConnectionsFriends'), connections.friends, onRelative);
appendOpinionLinks(parent, t('peopleConnectionsEnemies'), connections.enemies, onRelative);
const search = el('input', { class: 'input people__input', type: 'search' });
search.placeholder = t('peopleConnectionsSearch');
const list = el('div', { class: 'people__connections-list' });
const renderMatches = (): void => {
clear(list);
const query = search.value.trim().toLocaleLowerCase();
const matches = connections.others.filter((row) =>
query.length === 0 ? true : row.fullName.toLocaleLowerCase().includes(query),
);
if (matches.length === 0) {
list.append(el('p', { class: 'panel__empty', text: t('peopleConnectionsEmpty') }));
return;
}
appendOpinionLinks(list, '', matches, onRelative, false);
};
search.addEventListener('input', renderMatches);
parent.append(search, list);
renderMatches();
}
function fillNow(
@@ -682,3 +726,86 @@ function appendRelatives(
),
);
}
function appendRelativesWithOpinion(
parent: HTMLElement,
title: string,
relatives: readonly PersonRel[],
open: (id: string) => void,
): void {
if (relatives.length === 0) {
return;
}
const list = el('span', { class: 'people__rel-list' });
for (const relative of relatives) {
const caption =
relative.opinion !== null &&
relative.opinion !== undefined &&
relative.opinionLabel !== null &&
relative.opinionLabel !== undefined
? t('peopleOpinionValue', { label: relative.opinionLabel, value: relative.opinion })
: relative.fullName;
list.append(
el('button', {
class: 'people__link',
type: 'button',
text: caption,
title: relative.fullName,
onClick: () => open(relative.id),
}),
);
}
parent.append(
el(
'div',
{ class: 'people__rel' },
el('span', { class: 'people__rel-title', text: title }),
list,
),
);
}
function appendOpinionLinks(
parent: HTMLElement,
title: string,
rows: readonly PersonOpinionLink[],
open: (id: string) => void,
titled = true,
): void {
if (rows.length === 0) {
return;
}
const block = el('div', { class: 'people__connections-block' });
if (titled && title.length > 0) {
block.append(el('h4', { class: 'people__section-title', text: title }));
}
const list = el('dl', { class: 'people__pairs' });
for (const row of rows) {
list.append(
el(
'div',
{ class: 'people__pair' },
el(
'dt',
{},
el('button', {
class: 'people__link',
type: 'button',
text: row.fullName,
onClick: () => open(row.id),
}),
),
el('dd', {
text: t('peopleOpinionValue', { label: row.opinionLabel, value: row.opinion }),
}),
),
);
}
block.append(list);
parent.append(block);
}
@@ -1,9 +1,7 @@
import {
ApiError,
fetchGameStatus,
fetchSwarmUiDiscovery,
fetchSwarmUiSettings,
saveSwarmUiSettings,
type SwarmUiDiscovery,
type SwarmUiLoraEntry,
type SwarmUiPresetDefinition,
@@ -13,8 +11,8 @@ import { t } from '../i18n/strings.ts';
import { el } from './dom.ts';
import { Modal } from './modal.ts';
export function swarmUiSettingsDialog(): Promise<boolean> {
const modal = new Modal<boolean>(false);
export function swarmUiSettingsDialog(initial?: SwarmUiSettingsFile): Promise<SwarmUiSettingsFile | null> {
const modal = new Modal<SwarmUiSettingsFile | null>(null);
const error = el('p', { class: 'dialog__error' });
error.hidden = true;
@@ -28,7 +26,7 @@ export function swarmUiSettingsDialog(): Promise<boolean> {
let discovery: SwarmUiDiscovery = { connected: false, models: [], loras: [], samplers: [], schedulers: [] };
let editingPresetId = '';
const cancelButton = el('button', { class: 'button', type: 'button', onClick: () => modal.close(false) });
const cancelButton = el('button', { class: 'button', type: 'button', onClick: () => modal.close(null) });
const saveButton = el('button', { class: 'button button--primary', type: 'submit' });
const addPresetButton = el('button', { class: 'button button--small', type: 'button' });
const addAgeRuleButton = el('button', { class: 'button button--small', type: 'button' });
@@ -116,7 +114,7 @@ export function swarmUiSettingsDialog(): Promise<boolean> {
localize();
try {
const [settings, gameStatus, lists] = await Promise.all([
fetchSwarmUiSettings(),
initial === undefined ? fetchSwarmUiSettings() : Promise.resolve(structuredClone(initial)),
fetchGameStatus(),
fetchSwarmUiDiscovery(),
]);
@@ -153,14 +151,7 @@ export function swarmUiSettingsDialog(): Promise<boolean> {
syncActivePresetFromForm();
saveButton.disabled = true;
error.hidden = true;
try {
await saveSwarmUiSettings(config);
modal.close(true);
} catch (err) {
showError(err instanceof ApiError ? err.message : t('settingsSaveFailed'));
} finally {
saveButton.disabled = false;
}
modal.close(structuredClone(config));
}
function showError(message: string): void {