Fusion : séances accessibles et règles sous la main en séance
# Conflicts: # web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts # web/src/assets/i18n/en.json # web/src/assets/i18n/fr.json
This commit is contained in:
@@ -23,6 +23,29 @@ describe('buildCampaignTree', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('place un nœud « Parties » en tête (avant la narration), une entrée par partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({
|
||||
arcs: [{ id: 'a1', name: 'Arc', type: 'LINEAR' }] as never,
|
||||
chaptersByArc: { a1: [{ id: 'ch1', name: 'C1' }, { id: 'ch2', name: 'C2' }] } as never,
|
||||
playthroughs: [
|
||||
{ id: 'p1', campaignId: 'c1', name: 'Table du mardi' },
|
||||
{ id: 'p2', campaignId: 'c1', name: 'Table du jeudi' },
|
||||
],
|
||||
}), t);
|
||||
expect(tree[0].id).toBe('playthroughs-root');
|
||||
expect(tree[0].sectionHeaderBefore).toBe('campaignTree.sectionPlay');
|
||||
expect(tree[0].meta).toBe('2');
|
||||
expect(tree[0].children!.map((c) => c.route)).toEqual([
|
||||
'/campaigns/c1/playthroughs/p1', '/campaigns/c1/playthroughs/p2',
|
||||
]);
|
||||
expect(tree[1].id).toBe('arc-a1');
|
||||
});
|
||||
|
||||
it('pas de nœud « Parties » sans partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({ playthroughs: [] }), t);
|
||||
expect(tree.some((n) => n.id === 'playthroughs-root')).toBe(false);
|
||||
});
|
||||
|
||||
it('trie les arcs par ordre manuel (champ order, réagencé au glisser-déposer)', () => {
|
||||
const arcs = [
|
||||
{ id: 'a', name: 'Final', order: 2 },
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RandomTableService } from '../services/random-table.service';
|
||||
import { EnemyService } from '../services/enemy.service';
|
||||
import { TreeItem, TreeCreateAction, SecondarySidebarConfig, GlobalItem, ReorderKind } from '../services/layout.service';
|
||||
import { groupByFolder, byOrder } from '../shared/folder-grouping.util';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest } from '../services/campaign.model';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest, Playthrough } from '../services/campaign.model';
|
||||
import { Npc } from '../services/npc.model';
|
||||
import { RandomTable } from '../services/random-table.model';
|
||||
import { Enemy } from '../services/enemy.model';
|
||||
@@ -34,6 +34,8 @@ export interface CampaignTreeData {
|
||||
quests?: Quest[];
|
||||
/** Bilan de readiness complet — évite un fetch séparé pour le panneau du hub. */
|
||||
readiness?: CampaignReadinessAssessment | null;
|
||||
/** Parties (Playthroughs) — nœud « Parties » en tête d'arbre (accès direct aux séances). Optionnel. */
|
||||
playthroughs?: Playthrough[];
|
||||
}
|
||||
|
||||
export function loadCampaignTreeData(
|
||||
@@ -56,13 +58,14 @@ export function loadCampaignTreeData(
|
||||
randomTables: tree.randomTables ?? [],
|
||||
enemies: tree.enemies ?? [],
|
||||
quests: tree.quests ?? [],
|
||||
playthroughs: tree.playthroughs ?? [],
|
||||
gaps: tree.readiness?.gaps ?? [],
|
||||
readiness: tree.readiness ?? null
|
||||
} as CampaignTreeData)),
|
||||
// Dégradation gracieuse : sidebar vide plutôt qu'écran cassé si le back est indisponible.
|
||||
catchError(() => of({
|
||||
arcs: [], chaptersByArc: {}, scenesByChapter: {},
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], gaps: [], readiness: null
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], playthroughs: [], gaps: [], readiness: null
|
||||
} as CampaignTreeData))
|
||||
);
|
||||
}
|
||||
@@ -459,7 +462,31 @@ export function buildCampaignTree(
|
||||
}]
|
||||
};
|
||||
|
||||
return [...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode];
|
||||
// Parties (Playthroughs) : EN TÊTE d'arbre, avant la narration — c'est par une Partie
|
||||
// qu'on lance/reprend une séance ; enfouies en bas du hub, on finissait par les manquer.
|
||||
const playthroughItems: TreeItem[] = (data.playthroughs ?? [])
|
||||
.filter(p => !!p.id)
|
||||
.map(p => ({
|
||||
id: `playthrough-${p.id}`,
|
||||
label: p.name,
|
||||
iconKey: 'c-dice',
|
||||
route: `/campaigns/${campaignId}/playthroughs/${p.id}`
|
||||
}));
|
||||
const playthroughsNode: TreeItem | null = playthroughItems.length ? {
|
||||
id: 'playthroughs-root',
|
||||
label: translate.instant('campaignTree.playthroughs'),
|
||||
iconKey: 'c-dice',
|
||||
children: playthroughItems,
|
||||
meta: String(playthroughItems.length),
|
||||
// Libellé → hub (bloc « Jouer » + liste des Parties) ; chevron → une Partie par nœud.
|
||||
route: `/campaigns/${campaignId}`,
|
||||
sectionHeaderBefore: translate.instant('campaignTree.sectionPlay')
|
||||
} : null;
|
||||
|
||||
return [
|
||||
...(playthroughsNode ? [playthroughsNode] : []),
|
||||
...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -59,6 +59,14 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<!-- ============ Jouer : reprendre / démarrer une séance (accès direct) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-campaign-play-block
|
||||
[playthroughs]="playthroughs"
|
||||
[creatingPlaythrough]="newPlaythroughInFlight"
|
||||
(createPlaythrough)="createPlaythrough()">
|
||||
</app-campaign-play-block>
|
||||
}
|
||||
<!-- ============ Guidage co-MJ : « Prochaines étapes » (Pilier B) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-readiness-panel [campaignId]="campaign.id" [assessment]="readiness"></app-readiness-panel>
|
||||
|
||||
@@ -33,11 +33,12 @@ import { FolderGroup, groupByFolder, byOrder } from '../../../shared/folder-grou
|
||||
import { CampaignReadinessAssessment } from '../../../services/readiness.model';
|
||||
import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readiness-panel.component';
|
||||
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
||||
import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component';
|
||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, FoundryExportDialogComponent],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
@@ -95,14 +96,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
editPlaythroughName = '';
|
||||
/** Sessions de jeu (passées et en cours) liées à cette campagne. */
|
||||
sessions: Session[] = [];
|
||||
/**
|
||||
* Session active globale (toutes campagnes confondues).
|
||||
* Sert à désactiver le bouton "Lancer" si une session tourne déjà ailleurs.
|
||||
* Null si aucune session active dans l'app.
|
||||
*/
|
||||
activeSessionGlobal: Session | null = null;
|
||||
/** Indicateur de lancement en cours pour éviter les double-clics. */
|
||||
startingSession = false;
|
||||
|
||||
/** Parties (Playthroughs) de cette campagne. */
|
||||
playthroughs: Playthrough[] = [];
|
||||
@@ -215,6 +208,18 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||
this.showLayout(allCampaigns, treeData);
|
||||
this.pageTitleService.set(campaign.name);
|
||||
this.openEditFromQueryParam();
|
||||
}
|
||||
|
||||
/**
|
||||
* `?edit=system` (lien « Choisir le système » de l'onglet Règles en séance) : ouvre
|
||||
* directement l'édition inline, puis retire le paramètre pour qu'un rechargement
|
||||
* ne la rouvre pas.
|
||||
*/
|
||||
private openEditFromQueryParam(): void {
|
||||
if (!this.route.snapshot.queryParamMap.has('edit')) return;
|
||||
this.startEdit();
|
||||
this.router.navigate([], { relativeTo: this.route, queryParams: { edit: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<section class="play-block" [class.play-block--live]="target.kind === 'resume'" [attr.aria-label]="'playAccess.block.title' | translate">
|
||||
<div class="play-head">
|
||||
<lucide-icon [img]="Play" [size]="16" class="play-head-icon"></lucide-icon>
|
||||
<h2 class="play-title">{{ 'playAccess.block.title' | translate }}</h2>
|
||||
</div>
|
||||
|
||||
@if (target.kind === 'resume') {
|
||||
<ul class="play-rows">
|
||||
@for (r of target.sessions; track r.session.id) {
|
||||
<li class="play-row">
|
||||
<span class="live-dot" aria-hidden="true"></span>
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-label">{{ 'playAccess.block.running' | translate }}</span>
|
||||
<span class="play-row-sub">{{ r.session.name }} · {{ r.playthrough.name }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" (click)="resume(r.session)">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.resume' | translate }}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else if (target.kind === 'start') {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
@if (target.playthroughs.length > 1) {
|
||||
<label class="play-row-label" for="play-block-playthrough">{{ 'playAccess.block.playthroughLabel' | translate }}</label>
|
||||
<select id="play-block-playthrough" class="play-select" [(ngModel)]="selectedPlaythroughId">
|
||||
@for (p of target.playthroughs; track p.id) {
|
||||
<option [value]="p.id">{{ p.name }}</option>
|
||||
}
|
||||
</select>
|
||||
} @else {
|
||||
<span class="play-row-label">{{ 'playAccess.block.nextSession' | translate }}</span>
|
||||
<span class="play-row-sub">{{ target.playthroughs[0].name }}</span>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="starting" (click)="start()">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ (starting ? 'playAccess.block.starting' : 'playAccess.block.start') | translate }}
|
||||
</button>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-sub">{{ 'playAccess.block.noPlaythrough' | translate }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="creatingPlaythrough" (click)="createPlaythrough.emit()">
|
||||
<lucide-icon [img]="Plus" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.createPlaythrough' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
:host { display: block; }
|
||||
|
||||
.play-block {
|
||||
margin: 0 0 1.25rem;
|
||||
padding: 0.8rem 0.9rem;
|
||||
background: #0d1117;
|
||||
border: 1px solid #2d2a5a;
|
||||
border-radius: 10px;
|
||||
|
||||
&--live { border-color: rgba(16, 185, 129, 0.55); background: rgba(16, 185, 129, 0.05); }
|
||||
}
|
||||
|
||||
.play-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
margin-bottom: 0.55rem;
|
||||
}
|
||||
|
||||
.play-head-icon { color: #a5a0ff; }
|
||||
.play-block--live .play-head-icon { color: #34d399; }
|
||||
|
||||
.play-title {
|
||||
margin: 0;
|
||||
font-size: 0.92rem;
|
||||
font-weight: 600;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
|
||||
.play-rows {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.play-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.play-row-texts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
flex: 1 1 12rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.play-row-label {
|
||||
font-size: 0.75rem;
|
||||
color: #9ca3af;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.play-row-sub {
|
||||
font-size: 0.9rem;
|
||||
color: #e5e7eb;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.play-select {
|
||||
width: 100%;
|
||||
max-width: 22rem;
|
||||
min-height: 44px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
background: #111827;
|
||||
color: #e5e7eb;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.play-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 44px;
|
||||
padding: 0.55rem 1.1rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.play-block--live .play-btn {
|
||||
background: #059669;
|
||||
&:hover:not(:disabled) { background: #047857; }
|
||||
}
|
||||
|
||||
.live-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #10b981;
|
||||
animation: live-pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes live-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6); }
|
||||
70% { box-shadow: 0 0 0 7px rgba(16, 185, 129, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.live-dot { animation: none; }
|
||||
}
|
||||
|
||||
// Téléphone : bouton pleine largeur sous le texte.
|
||||
@media (max-width: 480px) {
|
||||
.play-btn { flex: 1 1 100%; }
|
||||
.play-select { max-width: none; }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Component, DestroyRef, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, Play, Plus } from 'lucide-angular';
|
||||
import { ActiveSessionsService } from '../../../services/active-sessions.service';
|
||||
import { SessionService } from '../../../services/session.service';
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
import { PlayTarget, computePlayTarget } from './play-target.util';
|
||||
|
||||
/**
|
||||
* Bloc « Jouer » en tête du hub campagne : reprendre la séance en cours, ou en démarrer
|
||||
* une sur la Partie la plus récente (ou en créer une s'il n'y en a aucune). La liste
|
||||
* complète des Parties reste en bas du hub ; ce bloc n'est qu'un accès direct.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-campaign-play-block',
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './campaign-play-block.component.html',
|
||||
styleUrls: ['./campaign-play-block.component.scss']
|
||||
})
|
||||
export class CampaignPlayBlockComponent implements OnInit, OnChanges {
|
||||
readonly Play = Play;
|
||||
readonly Plus = Plus;
|
||||
|
||||
@Input() playthroughs: Playthrough[] = [];
|
||||
/** Création de Partie déléguée au hub (même nom par défaut, même navigation). */
|
||||
@Input() creatingPlaythrough = false;
|
||||
@Output() createPlaythrough = new EventEmitter<void>();
|
||||
|
||||
target: PlayTarget = { kind: 'create' };
|
||||
selectedPlaythroughId = '';
|
||||
starting = false;
|
||||
|
||||
private activeSessions: Session[] = [];
|
||||
|
||||
constructor(
|
||||
private activeSessionsService: ActiveSessionsService,
|
||||
private sessionService: SessionService,
|
||||
private router: Router,
|
||||
private destroyRef: DestroyRef
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.activeSessionsService.active$.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(list => {
|
||||
this.activeSessions = list.map(e => e.session);
|
||||
this.recompute();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnChanges(): void {
|
||||
this.recompute();
|
||||
}
|
||||
|
||||
private recompute(): void {
|
||||
this.target = computePlayTarget(this.playthroughs, this.activeSessions);
|
||||
if (this.target.kind === 'start') {
|
||||
const ids = this.target.playthroughs.map(p => p.id);
|
||||
if (!ids.includes(this.selectedPlaythroughId)) {
|
||||
this.selectedPlaythroughId = this.target.defaultPlaythroughId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resume(session: Session): void {
|
||||
this.router.navigate(['/sessions', session.id]);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.starting || !this.selectedPlaythroughId) return;
|
||||
this.starting = true;
|
||||
this.sessionService.startSession(this.selectedPlaythroughId).subscribe({
|
||||
next: s => { this.starting = false; this.router.navigate(['/sessions', s.id]); },
|
||||
error: () => { this.starting = false; }
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computePlayTarget, sortPlaythroughsRecentFirst } from './play-target.util';
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
|
||||
const pt = (id: string, createdAt?: string): Playthrough => ({ id, campaignId: 'c1', name: `P${id}`, createdAt });
|
||||
const session = (id: string, playthroughId: string, startedAt: string, active = true): Session => ({
|
||||
id, name: `S${id}`, playthroughId, startedAt, endedAt: active ? null : startedAt,
|
||||
createdAt: startedAt, updatedAt: startedAt, active
|
||||
});
|
||||
|
||||
describe('sortPlaythroughsRecentFirst', () => {
|
||||
it('trie par date de création décroissante', () => {
|
||||
const r = sortPlaythroughsRecentFirst([pt('1', '2026-01-01'), pt('2', '2026-03-01'), pt('3', '2026-02-01')]);
|
||||
expect(r.map(p => p.id)).toEqual(['2', '3', '1']);
|
||||
});
|
||||
|
||||
it('sans dates : la dernière de la liste est la plus récente', () => {
|
||||
expect(sortPlaythroughsRecentFirst([pt('1'), pt('2')]).map(p => p.id)).toEqual(['2', '1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computePlayTarget', () => {
|
||||
it('aucune partie → create', () => {
|
||||
expect(computePlayTarget([], [])).toEqual({ kind: 'create' });
|
||||
});
|
||||
|
||||
it('pas de séance en cours → start sur la partie la plus récente', () => {
|
||||
const t = computePlayTarget([pt('1', '2026-01-01'), pt('2', '2026-05-01')], []);
|
||||
expect(t.kind).toBe('start');
|
||||
if (t.kind === 'start') {
|
||||
expect(t.defaultPlaythroughId).toBe('2');
|
||||
expect(t.playthroughs.map(p => p.id)).toEqual(['2', '1']);
|
||||
}
|
||||
});
|
||||
|
||||
it('ignore les séances des autres campagnes et les séances terminées', () => {
|
||||
const t = computePlayTarget([pt('1')], [session('a', 'other', '2026-01-01'), session('b', '1', '2026-01-01', false)]);
|
||||
expect(t.kind).toBe('start');
|
||||
});
|
||||
|
||||
it('séance(s) en cours sur la campagne → resume, la plus récente d\'abord', () => {
|
||||
const t = computePlayTarget([pt('1'), pt('2')], [
|
||||
session('a', '1', '2026-01-01T10:00:00'),
|
||||
session('b', '2', '2026-01-02T10:00:00'),
|
||||
session('c', 'other', '2026-01-03T10:00:00')
|
||||
]);
|
||||
expect(t.kind).toBe('resume');
|
||||
if (t.kind === 'resume') {
|
||||
expect(t.sessions.map(s => s.session.id)).toEqual(['b', 'a']);
|
||||
expect(t.sessions[0].playthrough.id).toBe('2');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
|
||||
/**
|
||||
* Ce que propose le bloc « Jouer » du hub campagne :
|
||||
* - resume : une (ou plusieurs) séance(s) tourne(nt) sur une Partie de la campagne ;
|
||||
* - start : aucune séance en cours → démarrer sur une Partie (la plus récente par défaut) ;
|
||||
* - create : aucune Partie → en créer une d'abord.
|
||||
*/
|
||||
export type PlayTarget =
|
||||
| { kind: 'resume'; sessions: { session: Session; playthrough: Playthrough }[] }
|
||||
| { kind: 'start'; playthroughs: Playthrough[]; defaultPlaythroughId: string }
|
||||
| { kind: 'create' };
|
||||
|
||||
const timeOf = (p: Playthrough): number => {
|
||||
const t = Date.parse(p.createdAt ?? p.updatedAt ?? '');
|
||||
return Number.isNaN(t) ? 0 : t;
|
||||
};
|
||||
|
||||
/** Parties de la plus récente à la plus ancienne (création ; à défaut, ordre d'origine). */
|
||||
export function sortPlaythroughsRecentFirst(playthroughs: Playthrough[]): Playthrough[] {
|
||||
return playthroughs
|
||||
.map((p, i) => ({ p, i }))
|
||||
.sort((a, b) => (timeOf(b.p) - timeOf(a.p)) || (b.i - a.i))
|
||||
.map(x => x.p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Décide du bloc « Jouer » à partir des Parties de la campagne et des séances en cours
|
||||
* de TOUTE l'appli (filtrées ici sur les Parties de la campagne, plus récente d'abord).
|
||||
*/
|
||||
export function computePlayTarget(playthroughs: Playthrough[], activeSessions: Session[]): PlayTarget {
|
||||
const withId = playthroughs.filter((p): p is Playthrough & { id: string } => !!p.id);
|
||||
if (withId.length === 0) return { kind: 'create' };
|
||||
|
||||
const byId = new Map(withId.map(p => [p.id, p]));
|
||||
const running = activeSessions
|
||||
.filter(s => s.active && byId.has(s.playthroughId))
|
||||
.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt))
|
||||
.map(session => ({ session, playthrough: byId.get(session.playthroughId)! }));
|
||||
if (running.length > 0) return { kind: 'resume', sessions: running };
|
||||
|
||||
const sorted = sortPlaythroughsRecentFirst(withId);
|
||||
return { kind: 'start', playthroughs: sorted, defaultPlaythroughId: sorted[0].id! };
|
||||
}
|
||||
Reference in New Issue
Block a user