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:
@@ -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 < b & <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> & la <strong>magie</strong></p>';
|
||||
expect(highlightHtml(html, ['sort', 'magie'])).toBe(
|
||||
'<p><a href="/sort">Le <mark>sort</mark></a> & la <strong><mark>magie</mark></strong></p>'
|
||||
);
|
||||
});
|
||||
|
||||
it('décode les entités avant de chercher', () => {
|
||||
expect(highlightHtml('<p>l'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, '&').replace(/</g, '<').replace(/>/g, '>').replaceAll(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`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user