Show talk-circle partners and topic on the location panel and Now tab.

The frame and card share member ids; the client builds the sentence from the directory and locale.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Leonid Pershin
2026-08-20 10:43:16 +03:00
co-authored by Cursor
parent 1a21a64b4b
commit 2034946378
20 changed files with 356 additions and 30 deletions
+8 -8
View File
@@ -11,18 +11,18 @@
## Задачи ## Задачи
- [ ] Кадр присутствия: у человека, который в кружке, список id участников и id темы. - [x] Кадр присутствия: у человека, который в кружке, список id участников и id темы.
Имена не строкой. Клиент собирает «говорит с Машей о футболе» из справочника и локали Имена не строкой. Клиент собирает «говорит с Машей о футболе» из справочника и локали
- [ ] Версия протокола +1. `ProtocolCodec.cs`, `protocol.ts`, `docs/protocol.md` в одном коммите - [x] Версия протокола +1. `ProtocolCodec.cs`, `protocol.ts`, `docs/protocol.md` в одном коммите
- [ ] Не в кружке — пустой список, как сейчас только id/узел/состояние - [x] Не в кружке — пустой список, как сейчас только id/узел/состояние
- [ ] Вкладка «Сейчас» на карточке согласована с тем же составом - [x] Вкладка «Сейчас» на карточке согласована с тем же составом
- [ ] Старый клиент отваливается Hello, как обычно - [x] Старый клиент отваливается Hello, как обычно
## Тесты, без которых фаза не закрыта ## Тесты, без которых фаза не закрыта
- [ ] Круглый трип и байтовая раскладка человека с кружком и без — на обеих сторонах - [x] Круглый трип и байтовая раскладка человека с кружком и без — на обеих сторонах
- [ ] Имя человека не встречается в кадре присутствия - [x] Имя человека не встречается в кадре присутствия
- [ ] Клиентский тест: локация показывает тему и имя напарника из directory, не из кадра - [x] Клиентский тест: локация показывает тему и имя напарника из directory, не из кадра
## Критерий готовности ## Критерий готовности
@@ -0,0 +1,51 @@
/**
* @vitest-environment happy-dom
*/
import { afterEach, describe, expect, it } from 'vitest';
import { PresenceState, type PresencePerson } from '../net/protocol.ts';
import { getLocale, setLocale } from '../i18n/locale.ts';
import { t } from '../i18n/strings.ts';
import { locationPersonLine, talkCircleText } from './talkCircle.ts';
const initial = getLocale();
afterEach(() => setLocale(initial));
describe('location talk line', () => {
it('shows the partner name from the directory and the topic from locale, not from the frame', () => {
setLocale('ru');
const person: PresencePerson = {
id: 'f0.c0',
nodeId: 'corridor-1',
state: PresenceState.Here,
talkMemberIds: ['f0.c0', 'f0.c1'],
talkTopicId: 'TopicSport',
};
const names = new Map([
['f0.c0', 'Иванова Мария'],
['f0.c1', 'Петрова Маша'],
]);
const line = locationPersonLine(person, names);
expect(JSON.stringify(person)).not.toContain('Маша');
expect(JSON.stringify(person)).not.toContain('Иванова');
expect(line).toContain('Петрова Маша');
expect(line).toContain(t('talkTopicTopicSport'));
expect(line).toBe(`Иванова Мария — ${t('locationTalking', { partners: 'Петрова Маша', topic: t('talkTopicTopicSport') })}`);
});
it('omits talk text when the circle list is empty', () => {
const person: PresencePerson = {
id: 'f0.c0',
nodeId: 'corridor-1',
state: PresenceState.Here,
talkMemberIds: [],
talkTopicId: '',
};
const names = new Map([['f0.c0', 'Иванова Мария']]);
expect(locationPersonLine(person, names)).toBe('Иванова Мария');
expect(talkCircleText(person.id, person.talkMemberIds, person.talkTopicId, names)).toBe('');
});
});
@@ -0,0 +1,64 @@
import { PresenceState, type PresencePerson } from '../net/protocol.ts';
import { t, type MessageKey } from '../i18n/strings.ts';
const TOPIC_KEYS: Record<string, MessageKey> = {
TopicStudy: 'talkTopicTopicStudy',
TopicGames: 'talkTopicTopicGames',
TopicFood: 'talkTopicTopicFood',
TopicFamily: 'talkTopicTopicFamily',
TopicSport: 'talkTopicTopicSport',
TopicGossip: 'talkTopicTopicGossip',
TopicRude: 'talkTopicTopicRude',
TopicAppearance: 'talkTopicTopicAppearance',
};
export function talkTopicLabel(topicId: string): string {
const key = TOPIC_KEYS[topicId];
return key === undefined ? topicId : t(key);
}
export function talkPartnersLabel(
selfId: string,
memberIds: readonly string[],
names: ReadonlyMap<string, string>,
): string {
const others = memberIds
.filter((id) => id !== selfId)
.map((id) => names.get(id) ?? id);
if (others.length === 0) {
return '';
}
if (others.length === 1) {
return others[0] ?? '';
}
const last = others[others.length - 1] ?? '';
const head = others.slice(0, -1).join(', ');
return t('talkPartnersJoin', { head, last });
}
export function talkCircleText(
selfId: string,
memberIds: readonly string[],
topicId: string,
names: ReadonlyMap<string, string>,
): string {
if (memberIds.length === 0 || topicId.length === 0) {
return '';
}
const partners = talkPartnersLabel(selfId, memberIds, names);
if (partners.length === 0) {
return '';
}
return t('locationTalking', { partners, topic: talkTopicLabel(topicId) });
}
export function locationPersonLine(person: PresencePerson, names: ReadonlyMap<string, string>): string {
const name = names.get(person.id) ?? person.id;
const base = person.state === PresenceState.Walking ? t('locationWalking', { name }) : name;
const talk = talkCircleText(person.id, person.talkMemberIds, person.talkTopicId, names);
return talk.length > 0 ? `${base}${talk}` : base;
}
@@ -34,6 +34,8 @@ describe('t', () => {
expect(t('mapHeadcountActivity', { name: 'Класс 101', count: 18, activity: 'Математика · 5А' })) expect(t('mapHeadcountActivity', { name: 'Класс 101', count: 18, activity: 'Математика · 5А' }))
.toBe('Класс 101 (18 · Математика · 5А)'); .toBe('Класс 101 (18 · Математика · 5А)');
expect(t('locationWalking', { name: 'Иванов' })).toBe('Иванов (walking)'); expect(t('locationWalking', { name: 'Иванов' })).toBe('Иванов (walking)');
expect(t('locationTalking', { partners: 'Петрова Маша', topic: t('talkTopicTopicSport') }))
.toBe('talking with Петрова Маша about sport');
}); });
}); });
+20
View File
@@ -335,6 +335,16 @@ const ru = {
presenceWalking: 'в пути ({name})', presenceWalking: 'в пути ({name})',
presenceAway: 'вне школы', presenceAway: 'вне школы',
locationWalking: '{name} (в пути)', locationWalking: '{name} (в пути)',
locationTalking: 'говорит с {partners} о {topic}',
talkPartnersJoin: '{head} и {last}',
talkTopicTopicStudy: 'учёбе',
talkTopicTopicGames: 'играх',
talkTopicTopicFood: 'еде',
talkTopicTopicFamily: 'семье',
talkTopicTopicSport: 'спорте',
talkTopicTopicGossip: 'сплетнях',
talkTopicTopicRude: 'грубом',
talkTopicTopicAppearance: 'внешности',
timetableTitle: 'Расписание', timetableTitle: 'Расписание',
timetableClass: 'Класс', timetableClass: 'Класс',
timetableEmpty: 'Нет уроков.', timetableEmpty: 'Нет уроков.',
@@ -692,6 +702,16 @@ const en: Messages = {
presenceWalking: 'walking ({name})', presenceWalking: 'walking ({name})',
presenceAway: 'off campus', presenceAway: 'off campus',
locationWalking: '{name} (walking)', locationWalking: '{name} (walking)',
locationTalking: 'talking with {partners} about {topic}',
talkPartnersJoin: '{head} and {last}',
talkTopicTopicStudy: 'schoolwork',
talkTopicTopicGames: 'games',
talkTopicTopicFood: 'food',
talkTopicTopicFamily: 'family',
talkTopicTopicSport: 'sport',
talkTopicTopicGossip: 'gossip',
talkTopicTopicRude: 'rough talk',
talkTopicTopicAppearance: 'looks',
timetableTitle: 'Timetable', timetableTitle: 'Timetable',
timetableClass: 'Class', timetableClass: 'Class',
timetableEmpty: 'No lessons.', timetableEmpty: 'No lessons.',
+2
View File
@@ -324,6 +324,8 @@ export interface PersonCard {
readonly needs: readonly NeedStat[]; readonly needs: readonly NeedStat[];
readonly activity: string | null; readonly activity: string | null;
readonly activityLabel: string | null; readonly activityLabel: string | null;
readonly talkCircleMemberIds: readonly string[];
readonly talkTopicId: string | null;
readonly family: { readonly family: {
readonly parents: readonly PersonRel[]; readonly parents: readonly PersonRel[];
readonly children: readonly PersonRel[]; readonly children: readonly PersonRel[];
+81 -1
View File
@@ -1,9 +1,24 @@
/** /**
* @vitest-environment happy-dom * @vitest-environment happy-dom
*/ */
import { describe, expect, it, vi } from 'vitest'; import { afterEach, describe, expect, it, vi } from 'vitest';
import { PresenceState } from '../net/protocol.ts';
import { getLocale, setLocale } from '../i18n/locale.ts';
import { t } from '../i18n/strings.ts';
import { GameScreen } from './gameScreen.ts'; import { GameScreen } from './gameScreen.ts';
vi.mock('../net/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../net/api.ts')>();
return {
...actual,
fetchDirectory: async () => [],
};
});
const initial = getLocale();
afterEach(() => setLocale(initial));
describe('GameScreen speed buttons', () => { describe('GameScreen speed buttons', () => {
it('shows five speed buttons ×½ ×1 ×2 ×5 ×10', () => { it('shows five speed buttons ×½ ×1 ×2 ×5 ×10', () => {
const onSetSpeed = vi.fn(); const onSetSpeed = vi.fn();
@@ -47,3 +62,68 @@ describe('GameScreen speed buttons', () => {
expect((screen.element.querySelector('.clock__controls') as HTMLElement).hidden).toBe(true); expect((screen.element.querySelector('.clock__controls') as HTMLElement).hidden).toBe(true);
}); });
}); });
describe('GameScreen location talk', () => {
it('shows talk partners from the directory on the location list, not from the frame', () => {
setLocale('ru');
const screen = new GameScreen({
onLeave: () => {},
onSetRunning: () => {},
onSetSpeed: () => {},
onSkip: () => {},
});
document.body.append(screen.element);
screen.show({
id: 1,
name: 'Test',
gameTime: '2012-03-31T10:00:00.000Z',
running: true,
speedIndex: 1,
seed: 1,
mine: true,
});
screen.applyMap(1, [
{
kind: 3,
id: 'corridor-1',
parentId: '',
name: 'Коридор',
pupilSlots: 0,
items: [],
positions: [],
},
]);
const presence = {
type: 'presence' as const,
schoolId: 1,
nodes: [{ id: 'corridor-1', count: 2, activitySubject: '', activityClass: '' }],
people: [
{
id: 'f0.c0',
nodeId: 'corridor-1',
state: PresenceState.Here,
talkMemberIds: ['f0.c0', 'f0.c1'],
talkTopicId: 'TopicSport',
},
{
id: 'f0.c1',
nodeId: 'corridor-1',
state: PresenceState.Here,
talkMemberIds: ['f0.c0', 'f0.c1'],
talkTopicId: 'TopicSport',
},
],
};
expect(JSON.stringify(presence)).not.toContain('Маша');
screen.applyPresence(1, presence);
screen.applyDirectory([
{ id: 'f0.c0', fullName: 'Иванова Мария' },
{ id: 'f0.c1', fullName: 'Петрова Маша' },
]);
const items = [...screen.element.querySelectorAll('.panel__list li')].map((item) => item.textContent ?? '');
expect(items.some((text) => text.includes('Петрова Маша') && text.includes(t('talkTopicTopicSport')))).toBe(
true,
);
});
});
+20 -15
View File
@@ -15,7 +15,7 @@ import { fetchDirectory, type School } from '../net/api.ts';
import { clear, el } from './dom.ts'; import { clear, el } from './dom.ts';
import { ManagementPanel } from './managementPanel.ts'; import { ManagementPanel } from './managementPanel.ts';
import { PeoplePanel } from './peoplePanel.ts'; import { PeoplePanel } from './peoplePanel.ts';
import { formatPersonPlace } from './personCard.ts'; import { locationPersonLine } from '../format/talkCircle.ts';
interface GameScreenOptions { interface GameScreenOptions {
readonly onLeave: () => void; readonly onLeave: () => void;
@@ -204,8 +204,7 @@ export class GameScreen {
this.paintSkip(); this.paintSkip();
this.paintSeed(); this.paintSeed();
this.people.setLocate((id) => this.placeOf(id)); this.bindPeople();
this.management.setLocate((id) => this.placeOf(id));
} }
/** Called when the screen opens, before the first clock frame and snapshot arrive. */ /** Called when the screen opens, before the first clock frame and snapshot arrive. */
@@ -234,8 +233,7 @@ export class GameScreen {
this.rebuildTree(); this.rebuildTree();
this.applyClock(new Date(school.gameTime), school.running, school.speedIndex, false, null, null, null); this.applyClock(new Date(school.gameTime), school.running, school.speedIndex, false, null, null, null);
this.people.show(school.id); this.people.show(school.id);
this.people.setLocate((id) => this.placeOf(id)); this.bindPeople();
this.management.setLocate((id) => this.placeOf(id));
this.showTab('map'); this.showTab('map');
this.inspect('location'); this.inspect('location');
this.showMode('overview'); this.showMode('overview');
@@ -267,13 +265,19 @@ export class GameScreen {
this.presence = message; this.presence = message;
this.paintTreeLabels(); this.paintTreeLabels();
this.paintSelection(); this.paintSelection();
this.people.setLocate((id) => this.placeOf(id)); this.bindPeople();
this.management.setLocate((id) => this.placeOf(id));
if (message.people.some((person) => !this.directory.has(person.id))) { if (message.people.some((person) => !this.directory.has(person.id))) {
void this.loadDirectory(); void this.loadDirectory();
} }
} }
/** Names for the presence stream. The frame itself never carries display names. */
applyDirectory(people: readonly { id: string; fullName: string }[]): void {
this.directory = new Map(people.map((person) => [person.id, person.fullName]));
this.paintSelection();
this.bindPeople();
}
update(clock: ClockMessage): void { update(clock: ClockMessage): void {
this.applyClock( this.applyClock(
clock.gameTime, clock.gameTime,
@@ -458,10 +462,7 @@ export class GameScreen {
const names = this.presence.people const names = this.presence.people
.filter((person) => person.nodeId === id) .filter((person) => person.nodeId === id)
.map((person) => { .map((person) => locationPersonLine(person, this.directory));
const name = this.directory.get(person.id) ?? person.id;
return person.state === PresenceState.Walking ? t('locationWalking', { name }) : name;
});
names.sort((left, right) => left.localeCompare(right)); names.sort((left, right) => left.localeCompare(right));
return names; return names;
} }
@@ -476,6 +477,13 @@ export class GameScreen {
return formatPersonPlace(person.state === PresenceState.Walking ? 'walking' : 'here', nodeName); return formatPersonPlace(person.state === PresenceState.Walking ? 'walking' : 'here', nodeName);
} }
private bindPeople(): void {
this.people.setLocate((id) => this.placeOf(id));
this.management.setLocate((id) => this.placeOf(id));
this.people.setNames(this.directory);
this.management.setNames(this.directory);
}
private async loadDirectory(): Promise<void> { private async loadDirectory(): Promise<void> {
const schoolId = this.schoolId; const schoolId = this.schoolId;
if (schoolId === null) { if (schoolId === null) {
@@ -489,10 +497,7 @@ export class GameScreen {
return; return;
} }
this.directory = new Map(people.map((person) => [person.id, person.fullName])); this.applyDirectory(people);
this.paintSelection();
this.people.setLocate((id) => this.placeOf(id));
this.management.setLocate((id) => this.placeOf(id));
} catch { } catch {
// Names stay as ids until the next presence frame retries. // Names stay as ids until the next presence frame retries.
} }
@@ -67,6 +67,8 @@ function personCard(): PersonCard {
needs: [], needs: [],
activity: null, activity: null,
activityLabel: null, activityLabel: null,
talkCircleMemberIds: [],
talkTopicId: null,
family: { parents: [], children: [], siblings: [], partners: [] }, family: { parents: [], children: [], siblings: [], partners: [] },
worn: [], worn: [],
carried: [], carried: [],
@@ -194,6 +194,10 @@ export class ManagementPanel {
this.cardHost.relocate((id) => this.placeOf(id)); this.cardHost.relocate((id) => this.placeOf(id));
} }
setNames(names: ReadonlyMap<string, string>): void {
this.cardHost.setNames(names);
}
private async reload(): Promise<void> { private async reload(): Promise<void> {
const schoolId = this.schoolId; const schoolId = this.schoolId;
if (schoolId === null) { if (schoolId === null) {
+4
View File
@@ -184,6 +184,10 @@ export class PeoplePanel {
this.cardHost.relocate((id) => this.placeOf(id)); this.cardHost.relocate((id) => this.placeOf(id));
} }
setNames(names: ReadonlyMap<string, string>): void {
this.cardHost.setNames(names);
}
private onFilterChange(): void { private onFilterChange(): void {
this.page = 1; this.page = 1;
void this.reload(); void this.reload();
@@ -33,6 +33,8 @@ function card(overrides: Partial<PersonCard> = {}): PersonCard {
needs: [], needs: [],
activity: null, activity: null,
activityLabel: null, activityLabel: null,
talkCircleMemberIds: [],
talkTopicId: null,
family: { parents: [], children: [], siblings: [], partners: [] }, family: { parents: [], children: [], siblings: [], partners: [] },
worn: [ worn: [
{ {
@@ -322,4 +324,26 @@ describe('renderPersonCard', () => {
expect(root.querySelector('.people__now-activity')?.textContent).toBe(t('peopleAtHome')); expect(root.querySelector('.people__now-activity')?.textContent).toBe(t('peopleAtHome'));
expect(root.querySelector('.people__now-activity')?.textContent).not.toBe(''); expect(root.querySelector('.people__now-activity')?.textContent).not.toBe('');
}); });
it('shows the same talk-circle partners on Now as the location line uses', () => {
setLocale('ru');
const root = document.createElement('div');
const names = new Map([
['f0.c0', 'Иванова Мария'],
['f0.c1', 'Петрова Маша'],
]);
renderPersonCard(
root,
card({
talkCircleMemberIds: ['f0.c0', 'f0.c1'],
talkTopicId: 'TopicSport',
}),
() => {},
{ tab: 'now', personNames: names },
);
expect(root.querySelector('.people__now-activity')?.textContent).toBe(
t('locationTalking', { partners: 'Петрова Маша', topic: t('talkTopicTopicSport') }),
);
});
}); });
+19 -2
View File
@@ -10,6 +10,7 @@ import type {
} from '../net/api.ts'; } from '../net/api.ts';
import { portraitUrl, type PortraitKind, type PortraitPrompt } from '../net/api.ts'; import { portraitUrl, type PortraitKind, type PortraitPrompt } from '../net/api.ts';
import { formatGameTimeOfDay } from '../format/gameTime.ts'; import { formatGameTimeOfDay } from '../format/gameTime.ts';
import { talkCircleText } from '../format/talkCircle.ts';
import { t, type MessageKey } from '../i18n/strings.ts'; import { t, type MessageKey } from '../i18n/strings.ts';
import { clear, el } from './dom.ts'; import { clear, el } from './dom.ts';
@@ -46,6 +47,8 @@ export interface RenderPersonCardOptions {
readonly swarmConfigured?: boolean; readonly swarmConfigured?: boolean;
/** null while checking or when SwarmUI is not configured. */ /** null while checking or when SwarmUI is not configured. */
readonly swarmConnected?: boolean | null; readonly swarmConnected?: boolean | null;
/** id→fullName from the presence directory; used to label the talk circle on Now. */
readonly personNames?: ReadonlyMap<string, string>;
} }
export function roleLabels(roles: readonly string[]): string { export function roleLabels(roles: readonly string[]): string {
@@ -67,7 +70,21 @@ export function placement(person: Pick<PersonListItem, 'classYear' | 'classLette
return parts.length > 0 ? parts.join(' · ') : '—'; return parts.length > 0 ? parts.join(' · ') : '—';
} }
export function nowActivityText(card: PersonCard, away: boolean): string { export function nowActivityText(
card: PersonCard,
away: boolean,
names: ReadonlyMap<string, string> = new Map(),
): string {
const talk = talkCircleText(
card.id,
card.talkCircleMemberIds,
card.talkTopicId ?? '',
names,
);
if (talk.length > 0) {
return talk;
}
if (away && (card.activityLabel === null || card.activityLabel.length === 0)) { if (away && (card.activityLabel === null || card.activityLabel.length === 0)) {
return t('peopleAtHome'); return t('peopleAtHome');
} }
@@ -307,7 +324,7 @@ function fillNow(
log: PersonLogPage | null | undefined, log: PersonLogPage | null | undefined,
options: RenderPersonCardOptions, options: RenderPersonCardOptions,
): void { ): void {
const activity = nowActivityText(card, away); const activity = nowActivityText(card, away, options.personNames);
if (activity.length > 0) { if (activity.length > 0) {
parent.append(el('p', { class: 'people__now-activity', text: activity })); parent.append(el('p', { class: 'people__now-activity', text: activity }));
} }
+16 -1
View File
@@ -41,6 +41,7 @@ export class PersonCardHost {
private container: HTMLElement | null = null; private container: HTMLElement | null = null;
private onRelative: (id: string) => void = () => {}; private onRelative: (id: string) => void = () => {};
private placeOf: (id: string) => string = () => ''; private placeOf: (id: string) => string = () => '';
private personNames: ReadonlyMap<string, string> = new Map();
private onOverviewMounted?: (overview: HTMLElement, card: PersonCard) => void; private onOverviewMounted?: (overview: HTMLElement, card: PersonCard) => void;
private logQuery: PersonLogQuery = { page: 1, pageSize: 20, dir: 'desc' }; private logQuery: PersonLogQuery = { page: 1, pageSize: 20, dir: 'desc' };
private logPage: PersonLogPage | null = null; private logPage: PersonLogPage | null = null;
@@ -172,6 +173,7 @@ export class PersonCardHost {
onShowPortraitPrompt: (kind) => void this.togglePortraitPrompt(kind), onShowPortraitPrompt: (kind) => void this.togglePortraitPrompt(kind),
swarmConfigured: this.swarmConfigured, swarmConfigured: this.swarmConfigured,
swarmConnected: this.swarmConnected, swarmConnected: this.swarmConnected,
personNames: this.personNames,
}); });
const overview = container.querySelector('[data-card-tab="overview"]'); const overview = container.querySelector('[data-card-tab="overview"]');
if (overview instanceof HTMLElement) { if (overview instanceof HTMLElement) {
@@ -301,7 +303,20 @@ export class PersonCardHost {
line.textContent = place; line.textContent = place;
const now = this.container?.querySelector('.people__now-activity'); const now = this.container?.querySelector('.people__now-activity');
if (now instanceof HTMLElement) { if (now instanceof HTMLElement) {
now.textContent = nowActivityText(this.painted, place === formatPersonPlace('away')); now.textContent = nowActivityText(this.painted, place === formatPersonPlace('away'), this.personNames);
}
}
setNames(names: ReadonlyMap<string, string>): void {
this.personNames = names;
if (this.painted === null) {
return;
}
const now = this.container?.querySelector('.people__now-activity');
if (now instanceof HTMLElement) {
const place = this.placeOf(this.painted.id);
now.textContent = nowActivityText(this.painted, place === formatPersonPlace('away'), names);
} }
} }
} }
+3 -1
View File
@@ -82,7 +82,9 @@ internal sealed record PersonCardResponse(
bool HasCustom = false, bool HasCustom = false,
bool HasFullBody = false, bool HasFullBody = false,
string? CustomPortraitPrompt = null, string? CustomPortraitPrompt = null,
PersonConnectionsResponse? Connections = null); PersonConnectionsResponse? Connections = null,
IReadOnlyList<string>? TalkCircleMemberIds = null,
string? TalkTopicId = null);
internal sealed record WornItemResponse( internal sealed record WornItemResponse(
string DefName, string DefName,
+5 -1
View File
@@ -60,6 +60,8 @@ internal static class PersonCardReader
activityLabel = activityId; activityLabel = activityId;
} }
var circle = school.TalkCircleOf(personId);
return new PersonCardResponse( return new PersonCardResponse(
person.Id, person.Id,
person.Name.Full, person.Name.Full,
@@ -89,7 +91,9 @@ internal static class PersonCardReader
person.LockerRoomId is not null person.LockerRoomId is not null
|| person.Items.Any(item => item.Location.Equals(ItemLocations.Locker, StringComparison.Ordinal)), || person.Items.Any(item => item.Location.Equals(ItemLocations.Locker, StringComparison.Ordinal)),
person.Items.Count(item => item.Location.Equals(ItemLocations.Home, StringComparison.Ordinal)), person.Items.Count(item => item.Location.Equals(ItemLocations.Home, StringComparison.Ordinal)),
Connections: Connections(roster, person, catalog, locale)); Connections: Connections(roster, person, catalog, locale),
TalkCircleMemberIds: circle?.MemberIds ?? [],
TalkTopicId: circle?.TopicId);
} }
private static IReadOnlyDictionary<string, float>? LiveNeeds(World world, string personId) private static IReadOnlyDictionary<string, float>? LiveNeeds(World world, string personId)
+4 -1
View File
@@ -25,10 +25,13 @@ internal static class PresenceFrame
} }
var walking = row.Path.Count > 0 || row.RemainingMinutes > 0; var walking = row.Path.Count > 0 || row.RemainingMinutes > 0;
var circle = school.TalkCircleOf(row.PersonId);
people.Add(new PresencePerson( people.Add(new PresencePerson(
row.PersonId, row.PersonId,
row.NodeId, row.NodeId,
walking ? PresenceState.Walking : PresenceState.Here)); walking ? PresenceState.Walking : PresenceState.Here,
circle?.MemberIds ?? [],
circle?.TopicId ?? ""));
counts[row.NodeId] = counts.GetValueOrDefault(row.NodeId) + 1; counts[row.NodeId] = counts.GetValueOrDefault(row.NodeId) + 1;
} }
+3
View File
@@ -621,3 +621,6 @@ public sealed record PresenceSnapshot(
string? GoalId = null, string? GoalId = null,
float GoalWeight = 0f, float GoalWeight = 0f,
string? GoalAction = null); string? GoalAction = null);
/// <summary>Ids of an active talk circle. Names are resolved by the client, not here.</summary>
public sealed record TalkCirclePresence(string TopicId, IReadOnlyList<string> MemberIds);
+17
View File
@@ -218,6 +218,23 @@ public sealed class School : IDisposable
public IReadOnlyList<PresenceSnapshot> CapturePresence() => PresenceSystem.Capture(this); public IReadOnlyList<PresenceSnapshot> CapturePresence() => PresenceSystem.Capture(this);
/// <summary>
/// Live circle for the presence frame and the person card. Null when this person is not talking.
/// Member ids include self and are sorted; names stay off the wire.
/// </summary>
public TalkCirclePresence? TalkCircleOf(string personId)
{
if (!TalkCircleByPerson.TryGetValue(personId, out var circleId)
|| !TalkCirclesById.TryGetValue(circleId, out var circle))
{
return null;
}
var members = circle.Members.ToArray();
Array.Sort(members, StringComparer.Ordinal);
return new TalkCirclePresence(circle.TopicId, members);
}
public void RestorePresence(IReadOnlyList<PresenceSnapshot>? saved) => PresenceSystem.Restore(this, saved); public void RestorePresence(IReadOnlyList<PresenceSnapshot>? saved) => PresenceSystem.Restore(this, saved);
public bool IsCampusEmpty() => PresenceSystem.IsEmpty(this); public bool IsCampusEmpty() => PresenceSystem.IsEmpty(this);
@@ -26,6 +26,13 @@ public class TalkCircleTests
var rows = school.CapturePresence(); var rows = school.CapturePresence();
Assert.Equal(TalkActions.Chat, rows.Single(row => row.PersonId == first.Id).ActionId); Assert.Equal(TalkActions.Chat, rows.Single(row => row.PersonId == first.Id).ActionId);
Assert.Equal(TalkActions.Chat, rows.Single(row => row.PersonId == second.Id).ActionId); Assert.Equal(TalkActions.Chat, rows.Single(row => row.PersonId == second.Id).ActionId);
var circle = school.TalkCircleOf(first.Id);
Assert.NotNull(circle);
Assert.Contains(first.Id, circle.MemberIds);
Assert.Contains(second.Id, circle.MemberIds);
Assert.False(string.IsNullOrEmpty(circle.TopicId));
Assert.Equal(circle.MemberIds, school.TalkCircleOf(second.Id)?.MemberIds);
Assert.Null(school.TalkCircleOf("missing"));
} }
} }