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:
2026-10-17 14:01:36 +02:00
39 changed files with 2322 additions and 32 deletions
@@ -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 },
+30 -3
View File
@@ -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>
@@ -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! };
}
@@ -0,0 +1,87 @@
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { BehaviorSubject, Observable, forkJoin, merge, of } from 'rxjs';
import { catchError, filter, map, startWith, switchMap } from 'rxjs/operators';
import { SessionService } from './session.service';
import { PlaythroughService } from './playthrough.service';
import { CampaignService } from './campaign.service';
import { Session } from './session.model';
/** Séance en cours enrichie de quoi l'identifier (Partie + Campagne). */
export interface ActiveSessionEntry {
session: Session;
playthroughName: string | null;
campaignId: string | null;
campaignName: string | null;
}
interface PlaythroughLabel {
playthroughName: string | null;
campaignId: string | null;
campaignName: string | null;
}
/**
* État partagé des séances en cours (toutes Parties confondues), la plus récente d'abord.
*
* <p>Alimente le raccourci « Séance en cours » du menu principal et le bloc « Jouer »
* du hub campagne : une séance ne doit plus se perdre au fond d'une page. Rafraîchi à
* chaque navigation et après chaque démarrage/fin/suppression ({@link SessionService.changed$}).
* Les libellés Partie/Campagne sont mis en cache (une séance active change rarement de Partie).</p>
*/
@Injectable({ providedIn: 'root' })
export class ActiveSessionsService {
private readonly subject = new BehaviorSubject<ActiveSessionEntry[]>([]);
readonly active$: Observable<ActiveSessionEntry[]> = this.subject.asObservable();
private readonly labels = new Map<string, PlaythroughLabel>();
constructor(
router: Router,
private sessionService: SessionService,
private playthroughService: PlaythroughService,
private campaignService: CampaignService
) {
merge(
router.events.pipe(filter(e => e instanceof NavigationEnd)),
this.sessionService.changed$
).pipe(
startWith(null),
// switchMap : une navigation rapide annule le fetch précédent (pas de réponse périmée).
switchMap(() => this.fetch())
).subscribe(list => this.subject.next(list));
}
/** Force un rafraîchissement (ex. après une action hors SessionService). */
refresh(): void {
this.fetch().subscribe(list => this.subject.next(list));
}
private fetch(): Observable<ActiveSessionEntry[]> {
return this.sessionService.getActiveSessions().pipe(
// Back indisponible / ancienne version : on garde l'état connu plutôt que de faire clignoter.
catchError(() => of(null)),
switchMap(sessions => {
if (!sessions) return of(this.subject.value);
if (sessions.length === 0) return of([] as ActiveSessionEntry[]);
return forkJoin(sessions.map(s => this.labelOf(s.playthroughId).pipe(
map(label => ({ session: s, ...label }))
)));
})
);
}
private labelOf(playthroughId: string): Observable<PlaythroughLabel> {
const cached = this.labels.get(playthroughId);
if (cached) return of(cached);
const unknown: PlaythroughLabel = { playthroughName: null, campaignId: null, campaignName: null };
return this.playthroughService.getById(playthroughId).pipe(
switchMap(p => this.campaignService.getCampaignById(p.campaignId).pipe(
map(c => ({ playthroughName: p.name, campaignId: p.campaignId, campaignName: c.name })),
catchError(() => of({ ...unknown, playthroughName: p.name, campaignId: p.campaignId }))
)),
map(label => { this.labels.set(playthroughId, label); return label; }),
catchError(() => of(unknown))
);
}
}
+3 -1
View File
@@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Campaign, CampaignCreate, Arc, ArcCreate, Chapter, ChapterCreate, Scene, SceneCreate, Quest } from './campaign.model';
import { Campaign, CampaignCreate, Arc, ArcCreate, Chapter, ChapterCreate, Scene, SceneCreate, Quest, Playthrough } from './campaign.model';
import { CampaignReadinessAssessment } from './readiness.model';
import { Npc } from './npc.model';
import { RandomTable } from './random-table.model';
@@ -19,6 +19,8 @@ export interface CampaignTreeResponse {
randomTables: RandomTable[];
enemies: Enemy[];
quests: Quest[];
/** Parties (Playthroughs) de la campagne — nœud « Parties » de l'arbre. */
playthroughs?: Playthrough[];
readiness: CampaignReadinessAssessment;
}
+17 -5
View File
@@ -1,6 +1,6 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Observable, Subject, tap } from 'rxjs';
import { Session } from './session.model';
/**
@@ -13,11 +13,23 @@ import { Session } from './session.model';
export class SessionService {
private apiUrl = '/api/sessions';
/**
* Émet après chaque mutation qui change l'ensemble des séances en cours
* (démarrage, fin, renommage, suppression) — écouté par {@link ActiveSessionsService}
* pour rafraîchir le raccourci « Séance en cours » sans attendre une navigation.
*/
readonly changed$ = new Subject<void>();
constructor(private http: HttpClient) {}
/** Lance une nouvelle session sur la Partie (Playthrough) donnée. */
startSession(playthroughId: string): Observable<Session> {
return this.http.post<Session>(this.apiUrl, { playthroughId });
return this.http.post<Session>(this.apiUrl, { playthroughId }).pipe(tap(() => this.changed$.next()));
}
/** Toutes les séances en cours (toutes Parties confondues), la plus récente d'abord. */
getActiveSessions(): Observable<Session[]> {
return this.http.get<Session[]>(this.apiUrl, { params: new HttpParams().set('active', 'true') });
}
/**
@@ -49,15 +61,15 @@ export class SessionService {
}
endSession(id: string): Observable<Session> {
return this.http.post<Session>(`${this.apiUrl}/${id}/end`, {});
return this.http.post<Session>(`${this.apiUrl}/${id}/end`, {}).pipe(tap(() => this.changed$.next()));
}
renameSession(id: string, name: string): Observable<Session> {
return this.http.patch<Session>(`${this.apiUrl}/${id}`, { name });
return this.http.patch<Session>(`${this.apiUrl}/${id}`, { name }).pipe(tap(() => this.changed$.next()));
}
deleteSession(id: string): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${id}`);
return this.http.delete<void>(`${this.apiUrl}/${id}`).pipe(tap(() => this.changed$.next()));
}
/** Épingle (sceneId) ou dés-épingle (null) la scène courante — mode cockpit. */
@@ -0,0 +1,41 @@
@if (entries.length > 0) {
<div class="active-shortcut">
<button type="button" class="shortcut-main"
[class.shortcut-main--current]="entries.length === 1 && isCurrent(entries[0])"
[attr.aria-expanded]="entries.length > 1 ? expanded : null"
[title]="(entries.length === 1 ? 'playAccess.shortcut.openTitle' : 'playAccess.shortcut.listTitle') | translate"
(click)="onMainClick()">
<span class="live-dot" aria-hidden="true"></span>
<span class="shortcut-texts">
<span class="shortcut-label">
@if (entries.length === 1) {
{{ 'playAccess.shortcut.one' | translate }}
} @else {
{{ 'playAccess.shortcut.many' | translate:{ n: entries.length } }}
}
</span>
@if (entries.length === 1) {
<span class="shortcut-sub">{{ entries[0].session.name }}</span>
}
</span>
@if (entries.length > 1) {
<lucide-icon class="shortcut-icon" [img]="expanded ? ChevronUp : ChevronDown" [size]="14"></lucide-icon>
}
</button>
@if (expanded && entries.length > 1) {
<ul class="shortcut-list">
@for (e of entries; track e.session.id) {
<li>
<button type="button" class="shortcut-item" [class.shortcut-item--current]="isCurrent(e)" (click)="open(e)">
<span class="shortcut-item-name">{{ e.session.name }}</span>
@if (contextOf(e)) {
<span class="shortcut-item-ctx">{{ contextOf(e) }}</span>
}
</button>
</li>
}
</ul>
}
</div>
}
@@ -0,0 +1,113 @@
:host { display: block; }
.active-shortcut {
display: flex;
flex-direction: column;
gap: 0.25rem;
margin-top: 0.75rem;
}
.shortcut-main {
display: flex;
align-items: center;
gap: 0.45rem;
width: 100%;
min-height: 44px; // cible tactile
padding: 0.45rem 0.5rem 0.45rem 0.6rem;
background: rgba(16, 185, 129, 0.1);
border: 1px solid rgba(16, 185, 129, 0.45);
border-radius: 8px;
color: #d1fae5;
cursor: pointer;
text-align: left;
transition: background 0.15s, border-color 0.15s;
&:hover { background: rgba(16, 185, 129, 0.18); border-color: #10b981; }
&:focus-visible { outline: 2px solid #10b981; outline-offset: 2px; }
&--current { background: rgba(16, 185, 129, 0.22); }
}
.live-dot {
flex: 0 0 auto;
width: 8px;
height: 8px;
border-radius: 50%;
background: #10b981;
box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6);
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 6px 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; }
}
.shortcut-texts {
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
}
.shortcut-label {
font-size: 0.8rem;
font-weight: 600;
line-height: 1.25;
overflow-wrap: anywhere; // sidebar étroite : passe à la ligne plutôt que de tronquer
}
.shortcut-sub {
font-size: 0.72rem;
color: #6ee7b7;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.shortcut-icon { flex: 0 0 auto; color: #6ee7b7; }
.shortcut-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.shortcut-item {
display: flex;
flex-direction: column;
gap: 0.1rem;
width: 100%;
min-height: 44px;
justify-content: center;
padding: 0.4rem 0.7rem;
background: #161628;
border: 1px solid #2a2a45;
border-radius: 6px;
color: #e5e7eb;
cursor: pointer;
text-align: left;
&:hover { border-color: #10b981; }
&:focus-visible { outline: 2px solid #10b981; outline-offset: 2px; }
&--current { border-color: #10b981; background: rgba(16, 185, 129, 0.12); }
}
.shortcut-item-name,
.shortcut-item-ctx {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.shortcut-item-name { font-size: 0.8rem; font-weight: 500; }
.shortcut-item-ctx { font-size: 0.7rem; color: #9ca3af; }
@@ -0,0 +1,74 @@
import { Component, DestroyRef, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, ChevronDown, ChevronUp } from 'lucide-angular';
import { ActiveSessionEntry, ActiveSessionsService } from '../../services/active-sessions.service';
/**
* Raccourci « Séance en cours » du menu principal : visible dès qu'une séance tourne,
* un clic y ramène depuis n'importe quel écran. Plusieurs séances (plusieurs tables) :
* le bouton déplie la liste, la plus récente en tête.
*
* <p>Composant autonome (styles propres) pour pouvoir le réutiliser tel quel dans la
* barre haute mobile.</p>
*/
@Component({
selector: 'app-active-session-shortcut',
imports: [LucideAngularModule, TranslatePipe],
templateUrl: './active-session-shortcut.component.html',
styleUrls: ['./active-session-shortcut.component.scss']
})
export class ActiveSessionShortcutComponent implements OnInit {
readonly ChevronDown = ChevronDown;
readonly ChevronUp = ChevronUp;
entries: ActiveSessionEntry[] = [];
expanded = false;
currentUrl = '';
constructor(
private activeSessions: ActiveSessionsService,
private router: Router,
private destroyRef: DestroyRef
) {}
ngOnInit(): void {
this.currentUrl = this.router.url;
this.router.events.pipe(
filter((e): e is NavigationEnd => e instanceof NavigationEnd),
takeUntilDestroyed(this.destroyRef)
).subscribe(e => {
this.currentUrl = e.urlAfterRedirects;
this.expanded = false;
});
this.activeSessions.active$.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(list => {
this.entries = list;
if (list.length < 2) this.expanded = false;
});
}
/** Une seule séance : on y va ; plusieurs : on déplie la liste. */
onMainClick(): void {
if (this.entries.length === 1) {
this.open(this.entries[0]);
} else {
this.expanded = !this.expanded;
}
}
open(entry: ActiveSessionEntry): void {
this.router.navigate(['/sessions', entry.session.id]);
}
isCurrent(entry: ActiveSessionEntry): boolean {
return this.currentUrl.split(/[?#]/)[0] === `/sessions/${entry.session.id}`;
}
/** « Partie · Campagne » (ce qui est connu). */
contextOf(entry: ActiveSessionEntry): string {
return [entry.playthroughName, entry.campaignName].filter(Boolean).join(' · ');
}
}
@@ -42,7 +42,7 @@
</div>
<div class="composer">
<textarea
<textarea #composerInput
class="composer-input"
[(ngModel)]="input"
name="aiChatInput"
@@ -37,11 +37,14 @@ export class SessionAiChatPanelComponent implements OnChanges, OnDestroy {
@Input() sessionId!: string;
@Input() canSaveToJournal = true;
/** Question à préremplir (ex. depuis l'onglet Règles) — le MJ la relit avant d'envoyer. */
@Input() prefill: string | null = null;
/** Émis quand le MJ clique "Ajouter au journal" sur une réponse. */
@Output() saveToJournal = new EventEmitter<string>();
@ViewChild('messagesContainer') messagesContainer?: ElementRef<HTMLDivElement>;
@ViewChild('composerInput') composerInput?: ElementRef<HTMLTextAreaElement>;
messages: ChatMessage[] = [];
currentAssistantText = '';
@@ -54,6 +57,16 @@ export class SessionAiChatPanelComponent implements OnChanges, OnDestroy {
constructor(private aiChat: AiChatService, private translate: TranslateService) {}
ngOnChanges(changes: SimpleChanges): void {
if (changes['prefill'] && this.prefill) {
this.input = this.prefill;
// Après rendu : focus + curseur en fin de texte, prêt à compléter ou envoyer.
setTimeout(() => {
const el = this.composerInput?.nativeElement;
if (!el) return;
el.focus();
el.setSelectionRange(el.value.length, el.value.length);
});
}
// Reset complet si on change de session (changement d'instance jouée).
if (changes['sessionId'] && !changes['sessionId'].firstChange) {
this.cancelStream();
@@ -8,6 +8,13 @@
<lucide-icon [img]="Timer" [size]="14"></lucide-icon>
{{ 'sessionReferencePanel.tabPlay' | translate }}
</button>
<button type="button"
class="ref-tab"
[class.ref-tab--active]="activeTab === 'rules'"
(click)="selectTab('rules')">
<lucide-icon [img]="BookOpen" [size]="14"></lucide-icon>
{{ 'sessionRules.tab' | translate }}
</button>
<button type="button"
class="ref-tab"
[class.ref-tab--active]="activeTab === 'ai'"
@@ -72,10 +79,19 @@
</div>
}
<!-- ====== Règles du système (lecture + recherche instantanée, sans IA) ====== -->
@if (activeTab === 'rules') {
<app-session-rules-panel
[campaignId]="campaignId"
(askAi)="onAskAiFromRules($event)">
</app-session-rules-panel>
}
<!-- ====== IA ====== -->
@if (activeTab === 'ai') {
<app-session-ai-chat-panel
[sessionId]="sessionId"
[prefill]="aiPrefill"
[canSaveToJournal]="canAddToJournal"
(saveToJournal)="onAiSaveToJournal($event)">
</app-session-ai-chat-panel>
@@ -12,7 +12,7 @@
// ─────────────── Tabs ───────────────
.ref-tabs {
display: flex;
flex-wrap: wrap; // 6 onglets : on passe sur 2 rangs plutôt que de rogner « Scènes ».
flex-wrap: wrap; // 8 onglets : 3 rangs plutôt que de rogner « Scènes ».
background: #111827;
border-bottom: 1px solid #1f2937;
}
@@ -37,6 +37,9 @@
&:hover { color: #e5e7eb; background: rgba(108, 99, 255, 0.06); }
// Écran tactile : cible de 44 px (le rang d'onglets reste compact à la souris).
@media (pointer: coarse) { min-height: 44px; }
&--active {
color: #c4bdff;
border-bottom-color: #6c63ff;
@@ -1,7 +1,7 @@
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, User, Drama, Swords, Dices, ExternalLink, Sparkles, Table2, Package, ChevronDown, ChevronRight, Timer, Pin } from 'lucide-angular';
import { LucideAngularModule, User, Drama, Swords, Dices, ExternalLink, Sparkles, Table2, Package, ChevronDown, ChevronRight, Timer, Pin, BookOpen } from 'lucide-angular';
import { catchError, of } from 'rxjs';
import { CampaignService } from '../../services/campaign.service';
import { CharacterService } from '../../services/character.service';
@@ -20,8 +20,9 @@ import { SessionRandomTablesPanelComponent } from '../session-random-tables-pane
import { SessionItemCatalogsPanelComponent } from '../session-item-catalogs-panel/session-item-catalogs-panel.component';
import { ClocksManagerComponent } from '../../shared/clocks-manager/clocks-manager.component';
import { PlaythroughFlagsManagerComponent } from '../../shared/playthrough-flags-manager/playthrough-flags-manager.component';
import { SessionRulesPanelComponent } from '../session-rules-panel/session-rules-panel.component';
type TabId = 'play' | 'dice' | 'tables' | 'objects' | 'characters' | 'scenes' | 'ai';
type TabId = 'play' | 'rules' | 'dice' | 'tables' | 'objects' | 'characters' | 'scenes' | 'ai';
/**
* Panneau latéral du mode jeu : référence rapide en lecture seule.
@@ -35,7 +36,7 @@ type TabId = 'play' | 'dice' | 'tables' | 'objects' | 'characters' | 'scenes' |
*/
@Component({
selector: 'app-session-reference-panel',
imports: [LucideAngularModule, TranslatePipe, SessionDicePanelComponent, SessionAiChatPanelComponent, SessionRandomTablesPanelComponent, SessionItemCatalogsPanelComponent, ClocksManagerComponent, PlaythroughFlagsManagerComponent],
imports: [LucideAngularModule, TranslatePipe, SessionDicePanelComponent, SessionAiChatPanelComponent, SessionRandomTablesPanelComponent, SessionItemCatalogsPanelComponent, ClocksManagerComponent, PlaythroughFlagsManagerComponent, SessionRulesPanelComponent],
templateUrl: './session-reference-panel.component.html',
styleUrls: ['./session-reference-panel.component.scss']
})
@@ -52,6 +53,7 @@ export class SessionReferencePanelComponent implements OnChanges {
readonly ChevronRight = ChevronRight;
readonly Timer = Timer;
readonly Pin = Pin;
readonly BookOpen = BookOpen;
@Input() campaignId!: string;
/** Partie active — nécessaire pour charger les PJ (refonte Playthrough). */
@@ -68,6 +70,8 @@ export class SessionReferencePanelComponent implements OnChanges {
// « Partie » par défaut : l'état de jeu (horloges + faits) est le réflexe à la table.
activeTab: TabId = 'play';
/** Question préremplie dans l'onglet IA (depuis l'onglet Règles) ; consommée à l'ouverture. */
aiPrefill: string | null = null;
characters: Character[] = [];
npcs: Npc[] = [];
@@ -106,6 +110,7 @@ export class SessionReferencePanelComponent implements OnChanges {
selectTab(tab: TabId): void {
this.activeTab = tab;
this.aiPrefill = null;
if (tab === 'characters') this.ensureCharactersLoaded();
if (tab === 'scenes') this.ensureTreeLoaded();
}
@@ -191,6 +196,12 @@ export class SessionReferencePanelComponent implements OnChanges {
return [...(this.treeData?.scenesByChapter[chapter.id!] ?? [])].sort(byOrder);
}
/** Onglet Règles → « Demander à l'IA » : bascule sur l'IA, question préremplie. */
onAskAiFromRules(question: string): void {
this.activeTab = 'ai';
this.aiPrefill = question || null;
}
onDiceRolled(result: DiceRollResult): void {
this.rolled.emit(result);
}
@@ -0,0 +1,195 @@
import { describe, it, expect } from 'vitest';
import {
normalizeForSearch, parseRuleSections, searchTerms, filterRuleSections, blocksToMarkdown,
highlightText, highlightHtml
} from './rules-reference.util';
const RULES = [
'Ce système se joue avec des d20.',
'',
'## Combat',
"L'initiative se lance au début du combat.",
'',
'### Attaque d\'opportunité',
'',
'Quand un ennemi quitte votre allonge, vous pouvez attaquer.',
'',
'## Magie',
'Les sorts coûtent des points de mana.',
'',
'```',
'## pas un titre (bloc de code)',
'```',
'',
'## Équipement',
'| Objet | Prix |',
'| --- | --- |',
'| Épée | 10 po |',
].join('\n');
describe('normalizeForSearch', () => {
it('ignore casse et accents', () => {
expect(normalizeForSearch('Équipement Écuyer')).toBe('equipement ecuyer');
});
it('apostrophe typographique et ligatures', () => {
expect(normalizeForSearch('L’Œil du cœur')).toBe("l'oeil du coeur");
});
});
describe('parseRuleSections', () => {
const sections = parseRuleSections(RULES, 'Généralités');
it('découpe sur les H2, garde le préambule sous le titre fourni', () => {
expect(sections.map(s => s.title)).toEqual(['Généralités', 'Combat', 'Magie', 'Équipement']);
});
it('ne coupe pas sur un « ## » dans un bloc de code', () => {
const magie = sections.find(s => s.title === 'Magie')!;
expect(magie.blocks).toHaveLength(2);
expect(magie.blocks[1].markdown).toContain('## pas un titre');
});
it('rattache un sous-titre isolé au bloc suivant', () => {
const combat = sections.find(s => s.title === 'Combat')!;
expect(combat.blocks).toHaveLength(2);
expect(combat.blocks[1].markdown.startsWith("### Attaque d'opportunité")).toBe(true);
expect(combat.blocks[1].markdown).toContain('allonge');
});
it('garde un tableau en un seul bloc', () => {
const equip = sections.find(s => s.title === 'Équipement')!;
expect(equip.blocks).toHaveLength(1);
});
it('pas de préambule vide ; markdown vide → aucune section', () => {
expect(parseRuleSections('## A\ntexte', 'Intro').map(s => s.title)).toEqual(['A']);
expect(parseRuleSections('', 'Intro')).toEqual([]);
expect(parseRuleSections(null, 'Intro')).toEqual([]);
});
it('accepte les fins de ligne Windows', () => {
expect(parseRuleSections('## A\r\nun\r\n\r\ndeux', 'I')[0].blocks).toHaveLength(2);
});
});
describe('listes', () => {
const md = [
'## Classes',
'Classes jouables :',
'- **Barbare** : d12 PV.',
'- **Magicien** : d6 PV,',
' livre de sorts.',
'- **Roublard** : d8 PV.',
].join('\n');
const [classes] = parseRuleSections(md, 'I');
it('un bloc par item de premier niveau, continuation indentée incluse', () => {
expect(classes.blocks.map(b => b.markdown)).toEqual([
'- **Barbare** : d12 PV.',
'- **Magicien** : d6 PV,\n livre de sorts.',
'- **Roublard** : d8 PV.',
]);
expect(classes.blocks.every(b => b.context === 'Classes jouables :')).toBe(true);
});
it('la recherche ne garde que l\'item, le contexte reste cherchable', () => {
const r = filterRuleSections([classes], searchTerms('magicien'));
expect(r[0].blocks.map(b => b.markdown)).toEqual(['- **Magicien** : d6 PV,\n livre de sorts.']);
expect(filterRuleSections([classes], searchTerms('jouables roublard'))[0].blocks).toHaveLength(1);
});
it('rendu : contexte une seule fois, items consécutifs en liste serrée', () => {
expect(blocksToMarkdown(classes.blocks)).toBe(
'Classes jouables :\n\n- **Barbare** : d12 PV.\n- **Magicien** : d6 PV,\n livre de sorts.\n- **Roublard** : d8 PV.'
);
expect(blocksToMarkdown([classes.blocks[2]])).toBe('Classes jouables :\n\n- **Roublard** : d8 PV.');
});
it('une liste d\'un seul item reste un bloc normal', () => {
const [s] = parseRuleSections('## A\nIntro\n- seul', 'I');
expect(s.blocks).toHaveLength(1);
expect(s.blocks[0].group).toBeUndefined();
});
});
describe('searchTerms', () => {
it('normalise, ignore les mots d\'une lettre et les doublons', () => {
expect(searchTerms(' Épée a ÉPÉE sort ')).toEqual(['epee', 'sort']);
expect(searchTerms('')).toEqual([]);
});
});
describe('filterRuleSections', () => {
const sections = parseRuleSections(RULES, 'Généralités');
it('sans terme : tout', () => {
expect(filterRuleSections(sections, [])).toHaveLength(4);
});
it('ne garde que les blocs qui correspondent', () => {
const r = filterRuleSections(sections, searchTerms('opportunite'));
expect(r).toHaveLength(1);
expect(r[0].section.title).toBe('Combat');
expect(r[0].blocks).toHaveLength(1);
expect(r[0].titleMatch).toBe(false);
});
it('le titre de section sert de contexte (ET entre les termes)', () => {
const r = filterRuleSections(sections, searchTerms('combat allonge'));
expect(r.map(m => m.section.title)).toEqual(['Combat']);
expect(r[0].blocks.map(b => b.markdown)).toEqual([expect.stringContaining('allonge')]);
expect(filterRuleSections(sections, searchTerms('magie allonge'))).toEqual([]);
});
it('titre correspondant : section entière, placée en tête', () => {
const r = filterRuleSections(sections, searchTerms('magie'));
expect(r[0].section.title).toBe('Magie');
expect(r[0].titleMatch).toBe(true);
expect(r[0].blocks).toHaveLength(2);
});
it('cherche dans les tableaux, sans accents', () => {
expect(filterRuleSections(sections, searchTerms('epee'))[0].section.title).toBe('Équipement');
});
});
describe('highlightText', () => {
it('surligne sans tenir compte des accents ni de la casse, en gardant le texte d\'origine', () => {
expect(highlightText('Une Épée et une epee', ['epee'])).toBe('Une <mark>Épée</mark> et une <mark>epee</mark>');
});
it('fusionne les correspondances qui se chevauchent', () => {
expect(highlightText('initiative', ['init', 'itia'])).toBe('<mark>initia</mark>tive');
});
it('surligne une ligature trouvée par sa forme simple', () => {
expect(highlightText('Le cœur', ['coeur'])).toBe('Le <mark>cœur</mark>');
});
it('échappe le HTML', () => {
expect(highlightText('a < b & sort', ['sort'])).toBe('a &lt; b &amp; <mark>sort</mark>');
});
it('gère une forme décomposée (NFD) dans le texte', () => {
const decomposed = 'Épée'.normalize('NFD');
expect(highlightText(decomposed, ['epee'])).toBe(`<mark>${decomposed}</mark>`);
});
});
describe('highlightHtml', () => {
it('ne touche ni aux balises ni aux attributs', () => {
const html = '<p><a href="/sort">Le sort</a> &amp; la <strong>magie</strong></p>';
expect(highlightHtml(html, ['sort', 'magie'])).toBe(
'<p><a href="/sort">Le <mark>sort</mark></a> &amp; la <strong><mark>magie</mark></strong></p>'
);
});
it('décode les entités avant de chercher', () => {
expect(highlightHtml('<p>l&#39;attaque</p>', ["l'attaque"])).toBe("<p><mark>l'attaque</mark></p>");
});
it('sans terme : HTML inchangé', () => {
expect(highlightHtml('<p>x</p>', [])).toBe('<p>x</p>');
});
});
@@ -0,0 +1,308 @@
/**
* Logique PURE de l'onglet « Règles » du mode jeu : découpage du markdown de règles
* d'un GameSystem en sections H2 puis en blocs, recherche instantanée (sans IA,
* hors ligne) insensible à la casse et aux accents, surlignage dans le HTML rendu.
*
* Le découpage H2 reste cohérent avec l'éditeur de système et le parser Java
* (`^##\s+…$`) ; à la différence de ceux-ci, le texte avant le premier H2 n'est pas
* perdu (on le présente sous un titre fourni par l'appelant) et un `## ` à
* l'intérieur d'un bloc de code ne coupe pas la section.
*/
/** Bloc lisible d'une section (paragraphe, liste, tableau… séparé par une ligne vide). */
export interface RuleBlock {
markdown: string;
/** Texte brut normalisé (minuscules, sans accents ni syntaxe markdown) pour la recherche. */
searchText: string;
/** Item de liste : ce qui précède la liste (sous-titre, phrase d'introduction). */
context?: string;
/** Item de liste : identifiant de la liste d'origine (regroupement au rendu). */
group?: number;
}
export interface RuleSection {
/** Identifiant DOM stable pour l'affichage (ancre du sommaire). */
id: string;
title: string;
/** Titre normalisé pour la recherche. */
searchTitle: string;
blocks: RuleBlock[];
}
export interface RuleMatch {
section: RuleSection;
/** Blocs à afficher : tous si le titre correspond, sinon seulement ceux qui correspondent. */
blocks: RuleBlock[];
titleMatch: boolean;
}
/** Signes combinants (accents) isolés par la décomposition NFD. */
const DIACRITICS = /\p{M}/gu;
const NBSP = String.fromCharCode(0xa0);
const H2 = /^##\s+(\S.*)$/;
const FENCE = /^\s*(```|~~~)/;
const HEADING_ONLY = /^#{3,6}\s+\S/;
/**
* Minuscules + sans accents : « Écuyer » et « ecuyer » se trouvent mutuellement.
* Apostrophes typographiques et ligatures (œ, æ) ramenées à leur forme simple :
* les règles importées d'un PDF en sont pleines, la saisie au clavier jamais.
*/
export function normalizeForSearch(text: string): string {
return text.normalize('NFD').replace(DIACRITICS, '').toLowerCase()
.replace(/[‘’ʼ]/g, "'")
.replace(/œ/g, 'oe')
.replace(/æ/g, 'ae');
}
/**
* Retire les cibles de liens/images markdown (`](url)`) — parcours linéaire plutôt
* qu'une regex à quantificateurs imbriqués (backtracking sur un gros livre de règles).
*/
function stripLinkTargets(markdown: string): string {
let out = '';
let pos = 0;
for (let open = markdown.indexOf('](', pos); open !== -1; open = markdown.indexOf('](', pos)) {
const close = markdown.indexOf(')', open + 2);
if (close === -1) break;
out += markdown.slice(pos, open);
pos = close + 1;
}
return out + markdown.slice(pos);
}
/** Retire la syntaxe markdown courante pour ne chercher que dans le texte lu. */
function plainText(markdown: string): string {
return stripLinkTargets(markdown)
.replace(/[*_`~#>|![\]<]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function toBlock(markdown: string): RuleBlock {
return { markdown, searchText: normalizeForSearch(plainText(markdown)) };
}
/** Début d'item de liste de PREMIER niveau (pas d'indentation). */
const LIST_ITEM = /^(?:[-*+]|\d{1,3}[.)])\s+\S/;
/**
* Une liste devient un bloc PAR ITEM (la recherche « magicien » ne montre que la ligne
* du Magicien, pas les onze classes). Ce qui précède la liste (sous-titre, « Exemples : »)
* devient le contexte de chaque item : cherchable, et réaffiché une fois au rendu.
*/
function splitList(block: string, group: number): RuleBlock[] {
const lines = block.split('\n');
const first = lines.findIndex(l => LIST_ITEM.test(l));
if (first === -1) return [toBlock(block)];
const items: string[] = [];
for (const line of lines.slice(first)) {
if (LIST_ITEM.test(line) || items.length === 0) items.push(line);
else items[items.length - 1] += `\n${line}`;
}
if (items.length < 2) return [toBlock(block)];
const context = lines.slice(0, first).join('\n').trim() || undefined;
return items.map(item => ({
markdown: item,
searchText: normalizeForSearch(plainText(context ? `${context} ${item}` : item)),
context,
group
}));
}
/**
* Markdown à rendre pour une suite de blocs : les items consécutifs d'une même liste
* restent une liste serrée, et le contexte d'une liste n'est affiché qu'une fois.
*/
export function blocksToMarkdown(blocks: RuleBlock[]): string {
let out = '';
let previousGroup: number | undefined;
for (const b of blocks) {
const sameList = b.group !== undefined && b.group === previousGroup;
if (!sameList && b.context) out += (out ? '\n\n' : '') + b.context;
if (out) out += sameList ? '\n' : '\n\n';
out += b.markdown;
previousGroup = b.group;
}
return out;
}
/** Découpe le contenu d'une section en blocs (lignes vides hors blocs de code). */
function splitBlocks(lines: string[]): RuleBlock[] {
const raw: string[] = [];
let current: string[] = [];
let inFence = false;
const flush = () => {
const text = current.join('\n').trim();
if (text) raw.push(text);
current = [];
};
for (const line of lines) {
if (FENCE.test(line)) inFence = !inFence;
if (!inFence && line.trim() === '') { flush(); continue; }
current.push(line);
}
flush();
// Un sous-titre seul (### …) est rattaché au bloc qui le suit : un résultat de
// recherche garde ainsi son contexte.
const merged: string[] = [];
let pendingHeading = '';
for (const block of raw) {
const text = pendingHeading ? `${pendingHeading}\n\n${block}` : block;
pendingHeading = '';
if (HEADING_ONLY.test(block) && !block.includes('\n')) pendingHeading = text;
else merged.push(text);
}
if (pendingHeading) merged.push(pendingHeading);
return merged.flatMap((block, i) => splitList(block, i));
}
/**
* Découpe le markdown de règles en sections H2.
* @param preambleTitle titre donné au texte placé avant le premier H2 (s'il y en a).
*/
export function parseRuleSections(markdown: string | null | undefined, preambleTitle: string): RuleSection[] {
if (!markdown?.trim()) return [];
const groups: { title: string; lines: string[] }[] = [];
let current: { title: string; lines: string[] } = { title: preambleTitle, lines: [] };
let inFence = false;
for (const line of markdown.replace(/\r\n?/g, '\n').split('\n')) {
if (FENCE.test(line)) inFence = !inFence;
const match = inFence ? null : H2.exec(line);
if (match) {
groups.push(current);
current = { title: match[1].trim(), lines: [] };
} else {
current.lines.push(line);
}
}
groups.push(current);
return groups
.map((g, i) => ({ g, i }))
// Le préambule n'existe que s'il a du contenu ; une vraie section vide reste (son titre informe).
.filter(({ g, i }) => i > 0 || g.lines.some(l => l.trim()))
.map(({ g, i }) => ({
id: `rules-section-${i}`,
title: g.title,
searchTitle: normalizeForSearch(g.title),
blocks: splitBlocks(g.lines)
}));
}
/** Termes de recherche normalisés (mots d'au moins 2 caractères, sans doublon). */
export function searchTerms(query: string | null | undefined): string[] {
const words = normalizeForSearch(query ?? '').split(/\s+/).filter(w => w.length >= 2);
return [...new Set(words)];
}
const containsAll = (haystack: string, terms: string[]) => terms.every(t => haystack.includes(t));
/**
* Filtre les sections : un bloc correspond si TOUS les termes figurent dans le titre
* de sa section ou dans son texte (« combat initiative » trouve le paragraphe sur
* l'initiative de la section Combat). Sections dont le titre correspond en tête.
* Sans terme : toutes les sections, tous les blocs.
*/
export function filterRuleSections(sections: RuleSection[], terms: string[]): RuleMatch[] {
if (terms.length === 0) {
return sections.map(section => ({ section, blocks: section.blocks, titleMatch: false }));
}
const matches: RuleMatch[] = [];
for (const section of sections) {
if (containsAll(section.searchTitle, terms)) {
matches.push({ section, blocks: section.blocks, titleMatch: true });
continue;
}
const blocks = section.blocks.filter(b => containsAll(`${section.searchTitle} ${b.searchText}`, terms));
if (blocks.length > 0) matches.push({ section, blocks, titleMatch: false });
}
return [...matches.filter(m => m.titleMatch), ...matches.filter(m => !m.titleMatch)];
}
// ─────────────── Surlignage ───────────────
const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: NBSP };
function decodeEntities(text: string): string {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, code: string) => {
if (code[0] === '#') {
const n = code[1].toLowerCase() === 'x' ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
return Number.isFinite(n) ? String.fromCodePoint(n) : whole;
}
return ENTITIES[code.toLowerCase()] ?? whole;
});
}
function escapeHtml(text: string): string {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replaceAll(NBSP, '&nbsp;');
}
/** Surligne les termes dans un texte brut ; renvoie du HTML échappé. */
export function highlightText(text: string, terms: string[]): string {
if (terms.length === 0 || !text) return escapeHtml(text);
// Texte normalisé + correspondance index normalisé → index d'origine
// (un caractère accentué peut se décomposer en plusieurs points de code).
let norm = '';
const origStart: number[] = [];
const origEnd: number[] = [];
let i = 0;
for (const ch of text) {
const n = normalizeForSearch(ch);
origStart.push(...new Array<number>(n.length).fill(i));
origEnd.push(...new Array<number>(n.length).fill(i + ch.length));
norm += n;
i += ch.length;
}
const ranges: [number, number][] = [];
for (const term of terms) {
let from = norm.indexOf(term);
while (from !== -1) {
ranges.push([origStart[from], origEnd[from + term.length - 1]]);
from = norm.indexOf(term, from + term.length);
}
}
if (ranges.length === 0) return escapeHtml(text);
ranges.sort((a, b) => a[0] - b[0]);
const merged: [number, number][] = [];
for (const r of ranges) {
const last = merged[merged.length - 1];
if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
else merged.push([r[0], r[1]]);
}
let out = '';
let pos = 0;
for (const [start, end] of merged) {
out += escapeHtml(text.slice(pos, start)) + '<mark>' + escapeHtml(text.slice(start, end)) + '</mark>';
pos = end;
}
return out + escapeHtml(text.slice(pos));
}
/**
* Surligne les termes dans du HTML DÉJÀ assaini (sortie DOMPurify) : seuls les nœuds
* texte sont touchés, jamais les balises ni leurs attributs. N'ajoute que des
* `<mark>` autour de texte ré-échappé : le résultat reste sûr.
*/
export function highlightHtml(html: string, terms: string[]): string {
if (terms.length === 0 || !html) return html;
// Parcours linéaire texte / balise (pas de regex à backtracking sur un gros HTML).
let out = '';
let pos = 0;
while (pos < html.length) {
const tagStart = html.indexOf('<', pos);
const textEnd = tagStart === -1 ? html.length : tagStart;
if (textEnd > pos) out += highlightText(decodeEntities(html.slice(pos, textEnd)), terms);
if (tagStart === -1) break;
const tagEnd = html.indexOf('>', tagStart);
if (tagEnd === -1) { out += html.slice(tagStart); break; }
out += html.slice(tagStart, tagEnd + 1);
pos = tagEnd + 1;
}
return out;
}
@@ -0,0 +1,136 @@
<div class="rules-panel">
@switch (state) {
@case ('loading') {
<p class="rules-hint">{{ 'common.loading' | translate }}</p>
}
@case ('noSystem') {
<div class="rules-empty">
<lucide-icon [img]="BookOpen" [size]="22" class="rules-empty-icon"></lucide-icon>
<p>{{ 'sessionRules.noSystem' | translate }}</p>
<button type="button" class="rules-btn" (click)="openInNewTab(chooseSystemUrl)">
<lucide-icon [img]="ExternalLink" [size]="14"></lucide-icon>
{{ 'sessionRules.chooseSystem' | translate }}
</button>
</div>
}
@case ('noRules') {
<div class="rules-empty">
<lucide-icon [img]="BookOpen" [size]="22" class="rules-empty-icon"></lucide-icon>
<p>{{ 'sessionRules.noRules' | translate:{ name: gameSystem?.name } }}</p>
<button type="button" class="rules-btn" (click)="openInNewTab(editRulesUrl)">
<lucide-icon [img]="ExternalLink" [size]="14"></lucide-icon>
{{ 'sessionRules.addRules' | translate }}
</button>
</div>
}
@case ('ready') {
<!-- Barre : recherche instantanée + bascule vers l'IA -->
<div class="rules-toolbar">
<div class="rules-search">
<lucide-icon [img]="Search" [size]="15" class="rules-search-icon"></lucide-icon>
<input type="search" class="rules-search-input"
[ngModel]="query" (ngModelChange)="onQueryChange($event)"
(keydown.escape)="clearQuery()"
[placeholder]="'sessionRules.searchPlaceholder' | translate"
[attr.aria-label]="'sessionRules.searchPlaceholder' | translate"
autocomplete="off" spellcheck="false" />
@if (query) {
<button type="button" class="rules-icon-btn" (click)="clearQuery()" [title]="'sessionRules.clear' | translate" [attr.aria-label]="'sessionRules.clear' | translate">
<lucide-icon [img]="X" [size]="15"></lucide-icon>
</button>
}
</div>
<button type="button" class="rules-btn rules-btn--ai" (click)="askAiAboutQuery()" [title]="'sessionRules.askAiTitle' | translate">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'sessionRules.askAi' | translate }}
</button>
</div>
<p class="rules-meta">
{{ gameSystem?.name }}
@if (searching && matches.length > 0) {
· {{ (matches.length === 1 ? 'sessionRules.resultsOne' : 'sessionRules.resultsMany') | translate:{ n: matches.length } }}
}
</p>
@if (matches.length === 0) {
<div class="rules-empty rules-empty--compact">
<p>{{ 'sessionRules.noResult' | translate:{ q: query.trim() } }}</p>
<button type="button" class="rules-btn rules-btn--ai" (click)="askAiAboutQuery()">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'sessionRules.askAiInstead' | translate }}
</button>
</div>
} @else {
<!-- Sommaire (sections H2 ; épinglées en tête hors recherche) -->
<nav class="rules-toc" [attr.aria-label]="'sessionRules.toc' | translate">
<button type="button" class="rules-toc-head" (click)="tocOpen = !tocOpen" [attr.aria-expanded]="tocOpen">
<lucide-icon [img]="tocOpen ? ChevronDown : ChevronRight" [size]="13"></lucide-icon>
{{ 'sessionRules.toc' | translate }}
<span class="rules-count">{{ matches.length }}</span>
</button>
@if (tocOpen) {
<div class="rules-toc-list">
@for (m of matches; track m.section.id) {
<button type="button" class="rules-chip" [class.rules-chip--pinned]="isPinned(m)" (click)="jumpTo(m)">
@if (isPinned(m)) {
<lucide-icon [img]="Pin" [size]="11"></lucide-icon>
}
<span class="rules-chip-label">{{ m.section.title }}</span>
@if (searching && !m.titleMatch) {
<span class="rules-chip-count">{{ m.blocks.length }}</span>
}
</button>
}
</div>
}
</nav>
<!-- Sections repliables -->
<div class="rules-sections">
@for (m of matches; track m.section.id) {
<article class="rules-section" [id]="m.section.id" [class.rules-section--open]="isOpen(m)">
<div class="rules-section-head">
<button type="button" class="rules-section-toggle" (click)="toggle(m)" [attr.aria-expanded]="isOpen(m)">
<lucide-icon [img]="isOpen(m) ? ChevronDown : ChevronRight" [size]="14" class="rules-chevron"></lucide-icon>
<span class="rules-section-title">{{ m.section.title }}</span>
@if (searching && !m.titleMatch) {
<span class="rules-count">{{ m.blocks.length }} / {{ m.section.blocks.length }}</span>
}
</button>
<button type="button" class="rules-icon-btn" [class.rules-icon-btn--on]="isPinned(m)"
[attr.aria-pressed]="isPinned(m)"
[title]="(isPinned(m) ? 'sessionRules.unpin' : 'sessionRules.pin') | translate"
[attr.aria-label]="(isPinned(m) ? 'sessionRules.unpin' : 'sessionRules.pin') | translate"
(click)="togglePin(m)">
<lucide-icon [img]="isPinned(m) ? PinOff : Pin" [size]="14"></lucide-icon>
</button>
</div>
@if (isOpen(m)) {
<div class="rules-section-body">
@if (m.blocks.length > 0) {
<div class="rules-markdown" [innerHTML]="html(m)"></div>
} @else {
<p class="rules-hint">{{ 'sessionRules.emptySection' | translate }}</p>
}
<button type="button" class="rules-link" (click)="askAiAboutSection(m)">
<lucide-icon [img]="Sparkles" [size]="12"></lucide-icon>
{{ 'sessionRules.askAiSection' | translate }}
</button>
</div>
}
</article>
}
</div>
}
<button type="button" class="rules-link rules-link--footer" (click)="openInNewTab(editRulesUrl)">
<lucide-icon [img]="ExternalLink" [size]="12"></lucide-icon>
{{ 'sessionRules.editRules' | translate }}
</button>
}
}
</div>
@@ -0,0 +1,358 @@
:host { display: block; min-width: 0; }
.rules-panel {
display: flex;
flex-direction: column;
gap: 0.75rem;
min-width: 0;
}
.rules-hint {
color: #6b7280;
font-size: 0.8rem;
font-style: italic;
text-align: center;
margin: 0.5rem 0;
}
// ─────────────── États vides ───────────────
.rules-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.6rem;
padding: 1.25rem 0.5rem;
text-align: center;
color: #9ca3af;
font-size: 0.85rem;
p { margin: 0; line-height: 1.45; }
&--compact { padding: 0.75rem 0.5rem; }
}
.rules-empty-icon { color: #6b7280; }
// ─────────────── Boutons ───────────────
.rules-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
min-height: 44px;
padding: 0.45rem 0.85rem;
background: #1f2937;
border: 1px solid #374151;
border-radius: 8px;
color: #e5e7eb;
font-size: 0.82rem;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
&:hover { background: #273244; border-color: #6c63ff; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
&--ai {
background: rgba(108, 99, 255, 0.14);
border-color: rgba(108, 99, 255, 0.5);
color: #c4bdff;
&:hover { background: rgba(108, 99, 255, 0.24); }
}
}
.rules-icon-btn {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
background: transparent;
border: none;
border-radius: 8px;
color: #6b7280;
cursor: pointer;
&:hover { color: #e5e7eb; background: rgba(255, 255, 255, 0.05); }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: -2px; }
&--on { color: #fbbf24; }
}
.rules-link {
align-self: flex-start;
display: inline-flex;
align-items: center;
gap: 0.35rem;
min-height: 44px;
padding: 0 0.25rem;
background: none;
border: none;
color: #a5b4fc;
font-size: 0.78rem;
text-align: left;
cursor: pointer;
&:hover { text-decoration: underline; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
&--footer { color: #6b7280; }
}
// ─────────────── Barre de recherche ───────────────
.rules-toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.rules-search {
flex: 1 1 12rem;
min-width: 0;
display: flex;
align-items: center;
background: #111827;
border: 1px solid #374151;
border-radius: 8px;
padding-left: 0.6rem;
&:focus-within { border-color: #6c63ff; }
}
.rules-search-icon { color: #6b7280; flex: 0 0 auto; }
.rules-search-input {
flex: 1;
min-width: 0;
min-height: 42px;
padding: 0 0.5rem;
background: transparent;
border: none;
outline: none;
color: #e5e7eb;
font-size: 1rem; // 16 px : pas de zoom automatique au focus sur tablette/iPhone
&::-webkit-search-cancel-button { display: none; } // notre propre bouton « effacer »
}
.rules-meta {
margin: -0.25rem 0 0;
font-size: 0.72rem;
color: #6b7280;
}
.rules-count {
margin-left: auto;
font-size: 0.7rem;
font-weight: 400;
color: #6b7280;
text-transform: none;
letter-spacing: 0;
white-space: nowrap;
}
// ─────────────── Sommaire ───────────────
.rules-toc {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.rules-toc-head {
display: flex;
align-items: center;
gap: 0.4rem;
width: 100%;
min-height: 44px;
padding: 0;
background: none;
border: none;
color: #9ca3af;
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.4px;
cursor: pointer;
text-align: left;
&:hover { color: #d1d5db; }
}
.rules-toc-list {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
max-height: 9.5rem; // un long sommaire ne mange pas tout le panneau
overflow-y: auto;
}
.rules-chip {
display: inline-flex;
align-items: center;
gap: 0.3rem;
max-width: 100%;
min-height: 44px;
padding: 0.3rem 0.7rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 999px;
color: #d1d5db;
font-size: 0.78rem;
cursor: pointer;
&:hover { border-color: #6c63ff; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
&--pinned { border-color: rgba(251, 191, 36, 0.5); color: #fde68a; }
}
.rules-chip-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rules-chip-count {
font-size: 0.68rem;
background: rgba(250, 204, 21, 0.18);
color: #fde68a;
border-radius: 999px;
padding: 0 0.4rem;
}
// ─────────────── Sections ───────────────
.rules-sections {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.rules-section {
background: #111827;
border: 1px solid #1f2937;
border-radius: 8px;
min-width: 0;
scroll-margin-top: 0.5rem;
&--open { border-color: #2d3748; }
}
.rules-section-head {
display: flex;
align-items: center;
}
.rules-section-toggle {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 0.45rem;
min-height: 44px;
padding: 0.4rem 0.4rem 0.4rem 0.7rem;
background: none;
border: none;
color: #e5e7eb;
font-size: 0.88rem;
font-weight: 600;
text-align: left;
cursor: pointer;
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: -2px; }
}
.rules-chevron { flex: 0 0 auto; color: #6b7280; }
.rules-section-title {
overflow-wrap: anywhere;
}
.rules-section-body {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0 0.85rem 0.35rem;
border-top: 1px solid #1f2937;
}
// Rendu markdown (HTML injecté → ::ng-deep, limité à ce conteneur).
.rules-markdown {
padding-top: 0.6rem;
color: #d1d5db;
font-size: 0.86rem;
line-height: 1.55;
overflow-wrap: anywhere;
min-width: 0;
::ng-deep {
> :first-child { margin-top: 0; }
> :last-child { margin-bottom: 0; }
p { margin: 0 0 0.6em; }
h1, h2, h3, h4, h5, h6 {
margin: 0.9em 0 0.35em;
color: #f3f4f6;
font-weight: 600;
line-height: 1.25;
}
h1, h2 { font-size: 0.98rem; }
h3 { font-size: 0.92rem; }
h4, h5, h6 { font-size: 0.86rem; }
strong { color: #f3f4f6; }
ul, ol { margin: 0.3em 0 0.6em; padding-left: 1.3em; }
li { margin: 0.15em 0; }
blockquote {
margin: 0.4em 0;
padding: 0.2em 0.8em;
border-left: 3px solid #3a3a5a;
color: #9ca3af;
}
code {
background: #0b0b15;
border: 1px solid #2a2a3d;
border-radius: 3px;
padding: 0 0.25em;
font-size: 0.82em;
}
pre {
background: #0b0b15;
border: 1px solid #2a2a3d;
border-radius: 6px;
padding: 0.6em 0.75em;
overflow-x: auto;
code { background: none; border: 0; padding: 0; }
}
// Les tableaux défilent dans leur boîte : jamais de scroll horizontal de page.
table {
display: block;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
margin: 0.4em 0 0.7em;
font-size: 0.8rem;
}
th, td {
border: 1px solid #2a2a3d;
padding: 0.3em 0.55em;
text-align: left;
vertical-align: top;
}
th { background: #161b26; color: #f3f4f6; }
a { color: #a5b4fc; }
img { max-width: 100%; height: auto; }
mark {
background: rgba(250, 204, 21, 0.3);
color: #fef9c3;
border-radius: 2px;
padding: 0 1px;
}
}
}
@@ -0,0 +1,249 @@
import { Component, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import {
LucideAngularModule, Search, X, Sparkles, ChevronDown, ChevronRight, Pin, PinOff, BookOpen, ExternalLink
} from 'lucide-angular';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { Subscription, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { CampaignService } from '../../services/campaign.service';
import { GameSystemService } from '../../services/game-system.service';
import { GameSystem } from '../../services/game-system.model';
import {
RuleMatch, RuleSection, blocksToMarkdown, filterRuleSections, highlightHtml, parseRuleSections, searchTerms
} from './rules-reference.util';
type RulesState = 'loading' | 'noSystem' | 'noRules' | 'ready';
/**
* Onglet « Règles » du mode jeu : les règles du système de la campagne sous la main,
* lisibles et cherchables INSTANTANÉMENT (sans IA, hors ligne).
*
* <p>Sommaire des sections H2, sections repliables, recherche qui filtre jusqu'au
* paragraphe et surligne, sections épinglées (par système, dans le navigateur).
* « Demander à l'IA » bascule sur l'onglet IA avec la question préremplie.</p>
*/
@Component({
selector: 'app-session-rules-panel',
imports: [FormsModule, LucideAngularModule, TranslatePipe],
templateUrl: './session-rules-panel.component.html',
styleUrls: ['./session-rules-panel.component.scss']
})
export class SessionRulesPanelComponent implements OnChanges, OnDestroy {
readonly Search = Search;
readonly X = X;
readonly Sparkles = Sparkles;
readonly ChevronDown = ChevronDown;
readonly ChevronRight = ChevronRight;
readonly Pin = Pin;
readonly PinOff = PinOff;
readonly BookOpen = BookOpen;
readonly ExternalLink = ExternalLink;
@Input() campaignId = '';
/** Question (éventuellement vide) à poser dans l'onglet IA. */
@Output() askAi = new EventEmitter<string>();
state: RulesState = 'loading';
gameSystem: GameSystem | null = null;
sections: RuleSection[] = [];
matches: RuleMatch[] = [];
query = '';
terms: string[] = [];
tocOpen = true;
/** Sections dépliées hors recherche (repliées par défaut, sauf les épinglées). */
private opened = new Set<string>();
/** Sections repliées À LA MAIN pendant une recherche (sinon tout résultat est déplié). */
private collapsedInSearch = new Set<string>();
/** Titres épinglés (le titre survit aux réimports, pas l'index). */
private pinned = new Set<string>();
private htmlCache = new Map<string, SafeHtml>();
private searchTimer: ReturnType<typeof setTimeout> | null = null;
private loadSub: Subscription | null = null;
constructor(
private campaignService: CampaignService,
private gameSystemService: GameSystemService,
private translate: TranslateService,
private sanitizer: DomSanitizer
) {}
ngOnChanges(changes: SimpleChanges): void {
if (changes['campaignId']) this.load();
}
ngOnDestroy(): void {
this.loadSub?.unsubscribe();
if (this.searchTimer) clearTimeout(this.searchTimer);
}
private load(): void {
this.loadSub?.unsubscribe();
this.state = 'loading';
this.gameSystem = null;
this.sections = [];
this.matches = [];
if (!this.campaignId) return;
this.loadSub = this.campaignService.getCampaignById(this.campaignId).pipe(
switchMap(c => c.gameSystemId
? this.gameSystemService.getById(c.gameSystemId).pipe(catchError(() => of(null)))
: of(null)),
catchError(() => of(null))
).subscribe(gs => this.applySystem(gs));
}
private applySystem(gs: GameSystem | null): void {
this.gameSystem = gs;
if (!gs) { this.state = 'noSystem'; return; }
this.sections = parseRuleSections(gs.rulesMarkdown, this.translate.instant('sessionRules.preamble'));
if (this.sections.length === 0) { this.state = 'noRules'; return; }
this.pinned = this.readPins();
this.opened = new Set(this.sections.filter(s => this.pinned.has(s.title)).map(s => s.id));
this.htmlCache.clear();
this.state = 'ready';
this.recompute();
}
// ─────────────── Recherche ───────────────
onQueryChange(value: string): void {
this.query = value;
if (this.searchTimer) clearTimeout(this.searchTimer);
// Petit délai : un gros livre de règles reste fluide pendant la frappe.
this.searchTimer = setTimeout(() => this.applyQuery(), 120);
}
clearQuery(): void {
this.query = '';
this.applyQuery();
}
private applyQuery(): void {
this.searchTimer = null;
const terms = searchTerms(this.query);
if (terms.join(' ') === this.terms.join(' ')) return;
this.terms = terms;
this.collapsedInSearch.clear();
this.htmlCache.clear();
this.recompute();
}
private recompute(): void {
const matches = filterRuleSections(this.sections, this.terms);
// Hors recherche : épinglées en tête (ordre du livre conservé dans chaque groupe).
this.matches = this.terms.length
? matches
: [...matches.filter(m => this.isPinned(m)), ...matches.filter(m => !this.isPinned(m))];
}
get searching(): boolean {
return this.terms.length > 0;
}
get pinnedCount(): number {
return this.matches.filter(m => this.isPinned(m)).length;
}
// ─────────────── Sections ───────────────
isOpen(m: RuleMatch): boolean {
return this.searching ? !this.collapsedInSearch.has(m.section.id) : this.opened.has(m.section.id);
}
toggle(m: RuleMatch): void {
const set = this.searching ? this.collapsedInSearch : this.opened;
const id = m.section.id;
if (set.has(id)) set.delete(id);
else set.add(id);
}
/** Sommaire : déplie la section et la fait défiler en haut du panneau. */
jumpTo(m: RuleMatch): void {
if (!this.isOpen(m)) this.toggle(m);
setTimeout(() => document.getElementById(m.section.id)?.scrollIntoView({ block: 'start', behavior: 'smooth' }));
}
/** HTML de la section (blocs retenus), assaini puis surligné ; mis en cache par recherche. */
html(m: RuleMatch): SafeHtml {
const key = `${m.section.id}|${m.blocks.length}`;
const cached = this.htmlCache.get(key);
if (cached) return cached;
const markdown = blocksToMarkdown(m.blocks);
const raw = marked.parse(markdown, { async: false, gfm: true, breaks: true }) as string;
const clean = DOMPurify.sanitize(raw);
// Revue sécurité : le bypass est sûr ICI — le HTML sort de DOMPurify et le surlignage
// n'ajoute que des <mark> autour de texte ré-échappé (cf. highlightHtml).
// eslint-disable-next-line sonarjs/no-angular-bypass-sanitization
const safe = this.sanitizer.bypassSecurityTrustHtml(highlightHtml(clean, this.terms));
this.htmlCache.set(key, safe);
return safe;
}
// ─────────────── Épingles (localStorage, par système) ───────────────
isPinned(m: RuleMatch): boolean {
return this.pinned.has(m.section.title);
}
togglePin(m: RuleMatch): void {
const title = m.section.title;
if (this.pinned.has(title)) this.pinned.delete(title);
else this.pinned.add(title);
this.writePins();
if (!this.searching) this.recompute();
}
private pinsKey(): string | null {
return this.gameSystem?.id ? `loremind.sessionRules.pinned.${this.gameSystem.id}` : null;
}
private readPins(): Set<string> {
const key = this.pinsKey();
if (!key) return new Set();
try {
const parsed: unknown = JSON.parse(localStorage.getItem(key) ?? '[]');
return new Set(Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : []);
} catch {
return new Set();
}
}
private writePins(): void {
const key = this.pinsKey();
if (!key) return;
try {
localStorage.setItem(key, JSON.stringify([...this.pinned]));
} catch {
// Stockage indisponible (navigation privée…) : l'épingle vaut pour cet affichage seulement.
}
}
// ─────────────── IA & liens ───────────────
askAiAboutQuery(): void {
const q = this.query.trim();
this.askAi.emit(q ? this.translate.instant('sessionRules.askTemplate', { q }) : '');
}
askAiAboutSection(m: RuleMatch): void {
this.askAi.emit(this.translate.instant('sessionRules.askSectionTemplate', { title: m.section.title }));
}
/** Nouvel onglet : on ne quitte pas l'écran de séance (même règle que les fiches). */
openInNewTab(path: string): void {
window.open(path, '_blank', 'noopener');
}
get chooseSystemUrl(): string {
return `/campaigns/${this.campaignId}?edit=system`;
}
get editRulesUrl(): string {
return `/game-systems/${this.gameSystem?.id}/edit`;
}
}
@@ -17,6 +17,9 @@
</button>
</div>
<!-- Raccourci « Séance en cours » : visible seulement si une séance tourne. -->
<app-active-session-shortcut></app-active-session-shortcut>
<!-- Mode contextuel : liste des lores ou campagnes -->
@if (layoutConfig$ | async; as config) {
<div class="context-list">
+2 -1
View File
@@ -7,13 +7,14 @@ import { LayoutService } from '../services/layout.service';
import { GlobalSearchService } from '../services/global-search.service';
import { ConfigService } from '../services/config.service';
import { UpdatesService } from '../services/updates.service';
import { ActiveSessionShortcutComponent } from '../sessions/active-session-shortcut/active-session-shortcut.component';
// Single source of truth pour la version affichée dans le footer :
// on lit directement package.json à la compilation (resolveJsonModule).
import packageJson from '../../../package.json';
@Component({
selector: 'app-sidebar',
imports: [AsyncPipe, LucideAngularModule, TranslatePipe],
imports: [AsyncPipe, LucideAngularModule, TranslatePipe, ActiveSessionShortcutComponent],
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})