Ajout de 2 fonctionnalitées principales : import PDF que ce soit pour les règles ou les campagnes directement.
All checks were successful
Build & Push Images / build (brain) (push) Successful in 1m28s
Build & Push Images / build (core) (push) Successful in 1m40s
Build & Push Images / build-switcher (push) Successful in 19s
Build & Push Images / build (web) (push) Successful in 1m46s

Fonctionnalité de comparaison PDF / campagne pour faire un mix et demander des conseils à l'IA
This commit is contained in:
2026-06-04 13:55:27 +02:00
parent 79a68bc27b
commit 439f43875b
78 changed files with 5250 additions and 183 deletions

View File

@@ -39,7 +39,7 @@
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Quêtes du hub (scénario)</h2>
<p class="view-section-empty" *ngIf="hubQuests.length === 0">
Aucune quête pour ce hub. Créez un chapitre pour ajouter une première quête.
Aucune quête pour ce hub. Créez-en une pour démarrer.
</p>
<div class="hub-quest-grid" *ngIf="hubQuests.length > 0">

View File

@@ -82,30 +82,9 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
// IDs préfixés par type pour éviter les collisions dans LayoutService.expanded
// (chaque entité a sa propre séquence IDENTITY en base → arc.id=1 et chapter.id=1
// peuvent coexister et se marchaient sur les pieds dans le Set<string> global).
const sortedCharacters = [...data.characters].sort(byName);
const characterItems: TreeItem[] = sortedCharacters.map(ch => ({
id: `character-${ch.id}`,
label: ch.name,
route: `/campaigns/${campaignId}/characters/${ch.id}`
}));
const charactersNode: TreeItem = {
id: 'characters-root',
label: 'PJ',
iconKey: 'users',
children: characterItems,
meta: characterItems.length ? String(characterItems.length) : undefined,
sectionHeaderBefore: 'Personnages',
// Note : le section header "Personnages" est porté par le premier nœud (PJ).
// Le filet au-dessus est masqué par CSS si c'est le tout premier item de la sidebar.
createActions: [{
id: 'new-character',
label: 'Nouveau PJ',
route: `/campaigns/${campaignId}/characters/create`,
actionIcon: 'plus'
}]
};
// Note refonte Playthrough : les PJ ne sont plus rattachés à la campagne mais
// à une Partie (Playthrough). On ne les affiche donc plus dans la sidebar de
// campagne — seuls les PNJ (donnée de scénario) restent sous "Personnages".
const sortedNpcs = [...data.npcs].sort(byName);
const npcItems: TreeItem[] = sortedNpcs.map(n => ({
id: `npc-${n.id}`,
@@ -119,7 +98,9 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
iconKey: 'c-drama',
children: npcItems,
meta: npcItems.length ? String(npcItems.length) : undefined,
// Pas de sectionHeaderBefore : on reste sous le header "Personnages" du nœud PJ.
// Porte le header de section "Personnages" (les PJ ayant migré vers la Partie).
// Le filet au-dessus est masqué par CSS si c'est le tout premier item de la sidebar.
sectionHeaderBefore: 'Personnages',
createActions: [{
id: 'new-npc',
label: 'Nouveau PNJ',
@@ -166,14 +147,15 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
createActions: [{
id: `new-chapter-${arc.id}`,
label: 'Nouveau chapitre',
// Dans un arc hub, un "chapitre" est présenté comme une "quête".
label: arc.type === 'HUB' ? 'Nouvelle quête' : 'Nouveau chapitre',
route: `/campaigns/${campaignId}/arcs/${arc.id}/chapters/create`,
actionIcon: 'plus'
}]
};
});
return [...arcNodes, charactersNode, npcsNode];
return [...arcNodes, npcsNode];
}
/**
@@ -197,6 +179,8 @@ export function buildCampaignSidebarConfig(
}));
return {
title: campaign.name,
// Titre cliquable → accueil de la campagne (raccourci depuis n'importe quelle sous-page).
titleRoute: `/campaigns/${campaignId}`,
items: buildCampaignTree(campaignId, treeData),
footerLabel: 'Toutes les campagnes',
createActions: [

View File

@@ -0,0 +1,61 @@
<div class="adapt-page">
<div class="page-header">
<button type="button" class="btn-back" (click)="back()">
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
Retour à la campagne
</button>
<h1>Adapter un PDF à cette campagne</h1>
<p class="subtitle">
L'IA connaît votre campagne (structure, PNJ, univers) et lit le PDF, puis discute avec vous
pour l'intégrer et l'adapter. Ce sont des <strong>conseils</strong> : rien n'est créé,
vous appliquez ce qui vous plaît — et vous pouvez lui répondre pour qu'elle ajuste.
</p>
</div>
<!-- Choix / changement du PDF -->
<section class="upload-bar">
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
<button type="button" class="btn-primary" [disabled]="streaming" (click)="pdfInput.click()">
<lucide-icon [img]="Upload" [size]="15"></lucide-icon>
{{ hasConversation ? 'Changer de PDF' : 'Choisir un PDF à adapter' }}
</button>
<span class="file-name" *ngIf="fileName">{{ fileName }}</span>
</section>
<p class="adapt-error" *ngIf="error">{{ error }}</p>
<!-- Conversation -->
<section class="chat" *ngIf="hasConversation">
<div class="msg" *ngFor="let m of messages; let i = index"
[class.msg--user]="m.role === 'user'" [class.msg--assistant]="m.role === 'assistant'">
<div class="msg-role">{{ m.role === 'user' ? 'Vous' : 'IA' }}</div>
<div class="msg-body" *ngIf="m.role === 'user'">{{ m.content }}</div>
<div class="msg-body markdown-body" *ngIf="m.role === 'assistant'" [innerHTML]="m.content | markdown"></div>
<div class="msg-actions" *ngIf="m.role === 'assistant' && m.content && !(streaming && i === messages.length - 1)">
<button type="button" class="btn-copy" (click)="copy(i)">
<lucide-icon [img]="copiedIndex === i ? Check : Copy" [size]="12"></lucide-icon>
{{ copiedIndex === i ? 'Copié' : 'Copier' }}
</button>
</div>
<span class="streaming-cursor" *ngIf="streaming && i === messages.length - 1 && m.role === 'assistant'"></span>
</div>
</section>
<!-- Saisie d'un feedback -->
<section class="composer" *ngIf="hasConversation">
<textarea
[(ngModel)]="input"
[disabled]="streaming"
rows="2"
placeholder="Répondez à l'IA : corrigez, demandez une alternative, un autre lieu à intégrer…"
(keydown.enter)="$event.preventDefault(); sendCurrent()"></textarea>
<button type="button" class="btn-send" [disabled]="streaming || !input.trim()" (click)="sendCurrent()">
<lucide-icon [img]="Send" [size]="16"></lucide-icon>
</button>
</section>
</div>

View File

@@ -0,0 +1,184 @@
.adapt-page {
padding: 2rem 2.5rem;
max-width: 900px;
}
.page-header {
margin-bottom: 1.25rem;
h1 { margin: 0.6rem 0 0.3rem; font-size: 1.5rem; color: #f3f4f6; }
}
.btn-back {
display: inline-flex;
align-items: center;
gap: 0.4rem;
background: transparent;
border: none;
color: #9ca3af;
cursor: pointer;
font-size: 0.85rem;
padding: 0;
&:hover { color: #c4b5fd; }
}
.subtitle { margin: 0; color: #9ca3af; font-size: 0.9rem; strong { color: #d1d5db; } }
// --- Barre PDF --------------------------------------------------------------
.upload-bar {
display: flex;
align-items: center;
gap: 0.8rem;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.btn-primary {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.6rem 1.1rem;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
border: none;
background: #6c63ff;
color: white;
&:hover:not(:disabled) { background: #5b52e0; }
&:disabled { opacity: 0.6; cursor: progress; }
}
.file-name { color: #9ca3af; font-size: 0.82rem; }
.adapt-error {
margin: 0 0 1rem;
padding: 0.55rem 0.8rem;
background: rgba(248, 113, 113, 0.1);
border: 1px solid rgba(248, 113, 113, 0.35);
border-radius: 8px;
color: #fca5a5;
font-size: 0.85rem;
}
// --- Conversation -----------------------------------------------------------
.chat {
display: flex;
flex-direction: column;
gap: 0.9rem;
margin-bottom: 1rem;
}
.msg {
border-radius: 12px;
padding: 0.7rem 0.9rem;
border: 1px solid #1f2937;
&--user {
background: rgba(108, 99, 255, 0.1);
border-color: rgba(108, 99, 255, 0.3);
align-self: flex-end;
max-width: 85%;
}
&--assistant {
background: #0b1220;
}
}
.msg-role {
font-size: 0.68rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #9ca3af;
margin-bottom: 0.35rem;
}
.msg-body {
color: #d1d5db;
font-size: 0.92rem;
line-height: 1.6;
white-space: pre-wrap;
&.markdown-body { white-space: normal; }
::ng-deep {
h1, h2, h3 { color: #f3f4f6; margin: 0.9rem 0 0.4rem; }
h2 { font-size: 1.08rem; }
h3 { font-size: 1rem; }
ul, ol { padding-left: 1.3rem; }
li { margin: 0.2rem 0; }
strong { color: #fff; }
code { background: #1f2937; padding: 0.1rem 0.3rem; border-radius: 4px; font-size: 0.85em; }
a { color: #a78bfa; }
p { margin: 0.4rem 0; }
}
}
.msg-actions { margin-top: 0.5rem; }
.btn-copy {
display: inline-flex;
align-items: center;
gap: 0.3rem;
background: transparent;
border: 1px solid #374151;
border-radius: 6px;
color: #9ca3af;
cursor: pointer;
font-size: 0.75rem;
padding: 0.2rem 0.5rem;
&:hover { color: #c4b5fd; border-color: #6c63ff; }
}
.streaming-cursor {
display: inline-block;
color: #6c63ff;
animation: blink 1s step-start infinite;
}
@keyframes blink { 50% { opacity: 0; } }
// --- Composer ---------------------------------------------------------------
.composer {
display: flex;
gap: 0.5rem;
align-items: flex-end;
position: sticky;
bottom: 0;
padding-top: 0.5rem;
background: linear-gradient(to top, var(--color-bg, #0a0f1a) 70%, transparent);
textarea {
flex: 1;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 8px;
color: #f3f4f6;
padding: 0.55rem 0.7rem;
font-size: 0.9rem;
font-family: inherit;
resize: vertical;
&:focus { outline: none; border-color: #6c63ff; }
&:disabled { opacity: 0.6; }
}
}
.btn-send {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border-radius: 8px;
border: none;
background: #6c63ff;
color: white;
cursor: pointer;
&:hover:not(:disabled) { background: #5b52e0; }
&:disabled { opacity: 0.5; cursor: default; }
}

View File

@@ -0,0 +1,130 @@
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { LucideAngularModule, ArrowLeft, Upload, Copy, Check, Send } from 'lucide-angular';
import { CampaignAdaptService, AdaptMessage } from '../../../services/campaign-adapt.service';
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
import { PageTitleService } from '../../../services/page-title.service';
import { MarkdownPipe } from '../../../shared/markdown.pipe';
const FIRST_PROMPT = 'Propose-moi comment intégrer et adapter ce PDF à ma campagne.';
/**
* Page « Adapter un PDF » — CONVERSATIONNELLE. L'IA connaît la campagne (structure,
* PNJ, univers) + lit le PDF, propose une 1re adaptation, puis l'utilisateur peut
* répondre (corriger, demander des alternatives…) et l'IA rebondit.
* Route : /campaigns/:campaignId/adapt — rien n'est créé, conseils à appliquer à la main.
*/
@Component({
selector: 'app-campaign-adapt',
standalone: true,
imports: [CommonModule, FormsModule, LucideAngularModule, MarkdownPipe],
templateUrl: './campaign-adapt.component.html',
styleUrls: ['./campaign-adapt.component.scss']
})
export class CampaignAdaptComponent implements OnInit {
readonly ArrowLeft = ArrowLeft;
readonly Upload = Upload;
readonly Copy = Copy;
readonly Check = Check;
readonly Send = Send;
campaignId = '';
/** PDF choisi, conservé pour les tours de conversation suivants. */
private file: File | null = null;
fileName = '';
/** Conversation affichée (user + assistant). */
messages: AdaptMessage[] = [];
streaming = false;
error: string | null = null;
/** Saisie du message en cours. */
input = '';
copiedIndex: number | null = null;
constructor(
private route: ActivatedRoute,
private router: Router,
private service: CampaignAdaptService,
private campaignSidebar: CampaignSidebarService,
private pageTitle: PageTitleService
) {}
ngOnInit(): void {
this.campaignId = this.route.snapshot.paramMap.get('campaignId')!;
this.pageTitle.set('Adapter un PDF');
this.campaignSidebar.show(this.campaignId);
}
get hasConversation(): boolean { return this.messages.length > 0; }
// --- Choix du PDF (démarre / réinitialise la conversation) ---------------
onPdfSelected(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
this.file = file;
this.fileName = file.name;
this.messages = [];
this.error = null;
this.send(FIRST_PROMPT);
}
// --- Envoi d'un message (1er tour ou feedback) ---------------------------
sendCurrent(): void {
const text = this.input.trim();
if (!text || this.streaming) return;
this.input = '';
this.send(text);
}
private send(text: string): void {
if (!this.file || this.streaming) return;
this.error = null;
this.messages.push({ role: 'user', content: text });
// Historique envoyé = tout jusqu'au message user inclus (sans la bulle vide).
const payload: AdaptMessage[] = this.messages.map(m => ({ role: m.role, content: m.content }));
const assistant: AdaptMessage = { role: 'assistant', content: '' };
this.messages.push(assistant);
this.streaming = true;
this.service.adviseStream(this.campaignId, this.file, payload).subscribe({
next: (ev) => {
if (ev.type === 'token') {
assistant.content += ev.value;
} else if (ev.type === 'done') {
this.streaming = false;
}
},
error: (err: Error) => {
this.streaming = false;
// Bulle assistant restée vide → on la retire pour ne pas afficher de vide.
if (!assistant.content) {
this.messages = this.messages.filter(m => m !== assistant);
}
this.error = err?.message ? `Échec : ${err.message}` : "Échec de l'adaptation.";
}
});
}
copy(index: number): void {
const msg = this.messages[index];
if (!msg) return;
navigator.clipboard?.writeText(msg.content).then(() => {
this.copiedIndex = index;
setTimeout(() => (this.copiedIndex = null), 2000);
});
}
back(): void {
this.router.navigate(['/campaigns', this.campaignId]);
}
}

View File

@@ -102,38 +102,9 @@
<h2>Personnages</h2>
</div>
<!-- Sous-section : Personnages joueurs (PJ) -->
<div class="persona-subsection">
<div class="subsection-header">
<h3>
<lucide-icon [img]="User" [size]="16"></lucide-icon>
Personnages joueurs
<span class="count-badge" *ngIf="characters.length > 0">{{ characters.length }}</span>
</h3>
<button class="btn-add" (click)="createCharacter()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
Nouveau PJ
</button>
</div>
<div class="characters-grid" *ngIf="characters.length > 0">
<div class="character-card" *ngFor="let character of characters" (click)="viewCharacter(character)">
<lucide-icon [img]="User" [size]="20" class="character-icon"></lucide-icon>
<div class="character-info">
<span class="character-name">{{ character.name }}</span>
<span class="character-snippet">{{ personaSnippet(character) }}</span>
</div>
</div>
</div>
<div class="empty-state empty-state--compact" *ngIf="characters.length === 0">
<p>Aucun personnage joueur pour le moment.</p>
<button class="btn-add-first" (click)="createCharacter()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
Créer votre premier PJ
</button>
</div>
</div>
<!-- Les PJ ne sont plus rattachés à la campagne mais à une Partie (Playthrough) :
ils se gèrent depuis la page d'une Partie. Ici on ne liste que les PNJ
(donnée de scénario, partagée par toutes les Parties). -->
<!-- Sous-section : Personnages non-joueurs (PNJ) -->
<div class="persona-subsection">
@@ -172,10 +143,20 @@
<section class="detail-section arcs-section" *ngIf="!editing">
<div class="section-header">
<h2>Arcs narratifs</h2>
<button class="btn-add" (click)="createArc()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
Nouvel arc
</button>
<div class="section-header-actions">
<button class="btn-add btn-add--secondary" (click)="adaptCampaign()" title="Conseils IA pour adapter un PDF à cette campagne">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
Adapter un PDF
</button>
<button class="btn-add btn-add--secondary" (click)="importCampaign()" title="Générer l'arborescence depuis un PDF de campagne">
<lucide-icon [img]="Upload" [size]="14"></lucide-icon>
Importer un PDF
</button>
<button class="btn-add" (click)="createArc()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
Nouvel arc
</button>
</div>
</div>
<div class="arcs-grid" *ngIf="arcs.length > 0">

View File

@@ -268,6 +268,12 @@
h2 { color: #d1d5db; font-size: 1rem; font-weight: 600; }
}
.section-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.btn-add {
display: flex;
align-items: center;
@@ -283,6 +289,14 @@
transition: background 0.2s;
&:hover { background: #5b52e0; }
// Variante secondaire (ex: "Importer un PDF") : discrète à côté de l'action primaire.
&--secondary {
background: #1f2937;
color: #e5e7eb;
border: 1px solid #374151;
&:hover { background: #273244; border-color: #6c63ff; }
}
}
.arcs-grid {

View File

@@ -2,7 +2,7 @@ import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, User, Dices, Drama, Check, Play } from 'lucide-angular';
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles } from 'lucide-angular';
import { Router, RouterLink } from '@angular/router';
import { forkJoin, of } from 'rxjs';
import { catchError, switchMap, filter, map } from 'rxjs/operators';
@@ -16,7 +16,6 @@ import { SessionService } from '../../../services/session.service';
import { PlaythroughService } from '../../../services/playthrough.service';
import { Playthrough } from '../../../services/campaign.model';
import { Session } from '../../../services/session.model';
import { Character } from '../../../services/character.model';
import { Npc } from '../../../services/npc.model';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
@@ -38,11 +37,12 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
readonly Globe = Globe;
readonly Pencil = Pencil;
readonly Trash2 = Trash2;
readonly User = User;
readonly Dices = Dices;
readonly Drama = Drama;
readonly Check = Check;
readonly Play = Play;
readonly Upload = Upload;
readonly Sparkles = Sparkles;
campaign: Campaign | null = null;
arcs: Arc[] = [];
@@ -56,8 +56,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
availableGameSystems: GameSystem[] = [];
/** GameSystem associé si `campaign.gameSystemId` est renseigné ; sinon null. */
linkedGameSystem: GameSystem | null = null;
/** Fiches de personnages (PJ) de la campagne. */
characters: Character[] = [];
/** Fiches de personnages non-joueurs (PNJ) de la campagne. */
npcs: Npc[] = [];
/** Sessions de jeu (passées et en cours) liées à cette campagne. */
@@ -73,8 +71,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
/** Parties (Playthroughs) de cette campagne. */
playthroughs: Playthrough[] = [];
/** Partie par défaut (1re) — fallback pour les actions session/PJ tant que l'UI Playthrough n'est pas finie. */
defaultPlaythroughId: string | null = null;
/** Mode édition inline. */
editing = false;
@@ -124,10 +120,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.campaign = campaign;
this.editing = false;
this.playthroughs = playthroughs;
this.defaultPlaythroughId = playthroughs.length > 0 ? playthroughs[0].id! : null;
this.loadLinkedLore(campaign);
this.loadLinkedGameSystem(campaign);
this.loadCharacters(campaign.id!);
this.loadNpcs(campaign.id!);
this.loadSessions(campaign.id!);
this.arcs = treeData.arcs;
@@ -162,10 +156,8 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.campaign = campaign;
this.editing = false;
this.playthroughs = playthroughs;
this.defaultPlaythroughId = playthroughs.length > 0 ? playthroughs[0].id! : null;
this.loadLinkedLore(campaign);
this.loadLinkedGameSystem(campaign);
this.loadCharacters(campaign.id!);
this.loadNpcs(campaign.id!);
this.loadSessions(campaign.id!);
this.arcs = treeData.arcs;
@@ -200,18 +192,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
).subscribe(gs => this.linkedGameSystem = gs);
}
/** Charge les PJ de la Partie par défaut (refonte Playthrough). */
private loadCharacters(_campaignId: string): void {
if (!this.defaultPlaythroughId) {
this.characters = [];
return;
}
this.characterService.getByPlaythrough(this.defaultPlaythroughId).pipe(
catchError(() => of([] as Character[]))
).subscribe(list => this.characters = list);
}
/** Symétrique pour les PNJ. */
/** Charge les PNJ de la campagne (les PJ vivent désormais dans une Partie). */
private loadNpcs(campaignId: string): void {
this.npcService.getByCampaign(campaignId).pipe(
catchError(() => of([] as Npc[]))
@@ -245,11 +226,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
});
}
createCharacter(): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'characters', 'create']);
}
createNpc(): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', 'create']);
@@ -260,17 +236,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', npc.id, 'edit']);
}
editCharacter(character: Character): void {
if (!this.campaign || !character.id) return;
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id, 'edit']);
}
/** Ouvre la vue lecture seule (style WorldAnvil) — clic sur la carte. */
viewCharacter(character: Character): void {
if (!this.campaign || !character.id) return;
this.router.navigate(['/campaigns', this.campaign.id, 'characters', character.id]);
}
viewNpc(npc: Npc): void {
if (!this.campaign || !npc.id) return;
this.router.navigate(['/campaigns', this.campaign.id, 'npcs', npc.id]);
@@ -281,6 +246,18 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', 'create']);
}
/** Ouvre la page d'import d'un PDF de campagne (proposition d'arbre à réviser). */
importCampaign(): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'import']);
}
/** Ouvre la page de conseils d'adaptation d'un PDF à cette campagne. */
adaptCampaign(): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'adapt']);
}
openArc(arc: Arc): void {
if (!this.campaign || !arc.id) return;
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', arc.id]);
@@ -306,11 +283,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
return '(Fiche vide)';
}
/** Alias gardé pour compatibilité avec les anciens templates. */
characterSnippet(c: Character): string {
return this.personaSnippet(c);
}
private showLayout(allCampaigns: Campaign[], data: CampaignTreeData): void {
this.layoutService.show(buildCampaignSidebarConfig(this.campaign!, allCampaigns, data, this.campaign!.id!));
}
@@ -385,9 +357,9 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
const newGameSystemId = this.editGameSystemId ? this.editGameSystemId : null;
const currentGameSystemId = this.campaign.gameSystemId ?? null;
const gameSystemChanged = newGameSystemId !== currentGameSystemId;
const hasSheets = this.characters.length > 0 || this.npcs.length > 0;
const hasSheets = this.npcs.length > 0;
if (gameSystemChanged && hasSheets) {
const count = this.characters.length + this.npcs.length;
const count = this.npcs.length;
this.confirmDialog.confirm({
title: 'Changer le systeme de jeu ?',
message:

View File

@@ -0,0 +1,183 @@
<div class="import-page">
<div class="page-header">
<button type="button" class="btn-back" (click)="cancel()">
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
Retour à la campagne
</button>
<h1>Importer un PDF de campagne</h1>
<p class="subtitle">
L'IA propose une arborescence arc → chapitre → scène. Vous la révisez et l'ajustez
avant de créer quoi que ce soit.
</p>
</div>
<!-- Étape 1 : upload (masqué une fois en revue) -->
<section class="upload-area" *ngIf="!reviewing">
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
<button type="button" class="btn-primary big" [disabled]="importing" (click)="pdfInput.click()">
<lucide-icon [img]="Upload" [size]="16"></lucide-icon>
{{ importing ? 'Import en cours…' : 'Choisir un PDF de campagne' }}
</button>
<!-- Progression live -->
<div class="import-progress" *ngIf="importing">
<p class="import-phase">{{ importPhase }}</p>
<div class="progress-bar" *ngIf="importProgress">
<div class="progress-fill"
[style.width.%]="importProgress.total ? (importProgress.current / importProgress.total) * 100 : 0">
</div>
</div>
<p class="import-counts" *ngIf="importCounts">
Trouvé jusqu'ici : {{ importCounts.arcs }} arc(s) · {{ importCounts.chapters }} chapitre(s) · {{ importCounts.scenes }} scène(s)
</p>
</div>
<p class="import-error" *ngIf="importError">{{ importError }}</p>
</section>
<!-- Étape 2 : revue de l'arbre éditable -->
<section class="review-area" *ngIf="reviewing">
<div class="review-header">
<p class="review-summary">
À créer : <strong>{{ arcCount }}</strong> nouvel(s) arc(s),
<strong>{{ chapterCount }}</strong> chapitre(s),
<strong>{{ sceneCount }}</strong> scène(s).
Les éléments <em>« déjà présent »</em> (grisés) sont affichés pour situer les ajouts ;
ils ne seront pas recréés. Modifiez les nouveaux, puis créez.
</p>
</div>
<div class="tree">
<!-- Arc -->
<div class="arc-card" *ngFor="let arc of tree; let ai = index">
<div class="node-head arc-head" [class.existing-node]="arc.existing">
<button type="button" class="btn-collapse" (click)="toggleArc(arc)">
<lucide-icon [img]="arc.collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
</button>
<lucide-icon [img]="Swords" [size]="16" class="node-icon"></lucide-icon>
<input type="text" class="node-name" [(ngModel)]="arc.name" [name]="'arc-' + ai"
[readonly]="arc.existing" placeholder="Nom de l'arc" />
<span class="badge-existing" *ngIf="arc.existing">déjà présent</span>
<button type="button" class="btn-remove" *ngIf="!arc.existing" (click)="removeArc(ai)" title="Supprimer l'arc">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
</button>
</div>
<div class="node-body" *ngIf="!arc.collapsed">
<div class="arc-type-toggle" *ngIf="!arc.existing">
<span class="toggle-label">Type :</span>
<button type="button" class="type-btn" [class.active]="arc.type === 'LINEAR'"
(click)="setArcType(arc, 'LINEAR')">Linéaire</button>
<button type="button" class="type-btn" [class.active]="arc.type === 'HUB'"
(click)="setArcType(arc, 'HUB')">Hub (quêtes)</button>
</div>
<textarea class="node-desc" *ngIf="!arc.existing" [(ngModel)]="arc.description" [name]="'arc-desc-' + ai"
rows="2" placeholder="Synopsis de l'arc (optionnel)"></textarea>
<!-- Chapitres -->
<div class="chapter-card" *ngFor="let chapter of arc.chapters; let ci = index">
<div class="node-head chapter-head" [class.existing-node]="chapter.existing">
<button type="button" class="btn-collapse" (click)="toggleChapter(chapter)">
<lucide-icon [img]="chapter.collapsed ? ChevronRight : ChevronDown" [size]="14"></lucide-icon>
</button>
<lucide-icon [img]="BookOpen" [size]="14" class="node-icon"></lucide-icon>
<input type="text" class="node-name" [(ngModel)]="chapter.name" [name]="'chap-' + ai + '-' + ci"
[readonly]="chapter.existing" placeholder="Nom du chapitre" />
<span class="badge-existing" *ngIf="chapter.existing">déjà présent</span>
<button type="button" class="btn-remove" *ngIf="!chapter.existing" (click)="removeChapter(arc, ci)" title="Supprimer le chapitre">
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
</button>
</div>
<div class="node-body" *ngIf="!chapter.collapsed">
<textarea class="node-desc" *ngIf="!chapter.existing" [(ngModel)]="chapter.description" [name]="'chap-desc-' + ai + '-' + ci"
rows="2" placeholder="Synopsis du chapitre (optionnel)"></textarea>
<!-- Scènes -->
<div class="scene-card" *ngFor="let scene of chapter.scenes; let si = index"
[class.existing-node]="scene.existing">
<div class="scene-row">
<lucide-icon [img]="MapPin" [size]="13" class="node-icon scene-icon"></lucide-icon>
<div class="scene-fields">
<input type="text" class="node-name" [(ngModel)]="scene.name"
[name]="'scene-' + ai + '-' + ci + '-' + si" [readonly]="scene.existing"
placeholder="Nom de la scène" />
<input type="text" class="node-desc-inline" *ngIf="!scene.existing" [(ngModel)]="scene.description"
[name]="'scene-desc-' + ai + '-' + ci + '-' + si" placeholder="Synopsis (optionnel)" />
</div>
<span class="badge-existing" *ngIf="scene.existing">déjà présent</span>
<button type="button" class="btn-details" *ngIf="!scene.existing" (click)="toggleDetails(scene)"
title="Narration joueurs, notes MJ, pièces">
<lucide-icon [img]="scene.detailsOpen ? ChevronDown : ChevronRight" [size]="12"></lucide-icon>
Détails<span *ngIf="scene.rooms.length"> · {{ scene.rooms.length }} pièce(s)</span>
</button>
<button type="button" class="btn-remove" *ngIf="!scene.existing" (click)="removeScene(chapter, si)" title="Supprimer la scène">
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
</button>
</div>
<div class="scene-details" *ngIf="scene.detailsOpen && !scene.existing">
<label class="field-label">À lire aux joueurs</label>
<textarea class="node-desc" [(ngModel)]="scene.playerNarration"
[name]="'scene-pn-' + ai + '-' + ci + '-' + si" rows="3"
placeholder="Texte d'encadré lu aux joueurs (optionnel)"></textarea>
<label class="field-label">Notes MJ</label>
<textarea class="node-desc" [(ngModel)]="scene.gmNotes"
[name]="'scene-gm-' + ai + '-' + ci + '-' + si" rows="3"
placeholder="Secrets, développement, conséquences (optionnel)"></textarea>
<!-- Pièces (donjon) : vide = scène narrative classique -->
<span class="field-label">Pièces (lieu explorable)</span>
<div class="rooms">
<div class="room-row" *ngFor="let room of scene.rooms; let ri = index">
<input type="text" class="room-name" [(ngModel)]="room.name"
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Pièce" />
<input type="text" class="room-field" [(ngModel)]="room.description"
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Description" />
<input type="text" class="room-field" [(ngModel)]="room.enemies"
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Ennemis" />
<input type="text" class="room-field" [(ngModel)]="room.loot"
[name]="'room-loot-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Trésor" />
<button type="button" class="btn-remove" (click)="removeRoom(scene, ri)" title="Supprimer la pièce">
<lucide-icon [img]="Trash2" [size]="12"></lucide-icon>
</button>
</div>
<button type="button" class="btn-add-inline" (click)="addRoom(scene)">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Pièce
</button>
</div>
</div>
</div>
<button type="button" class="btn-add-inline" (click)="addScene(chapter)">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Scène
</button>
</div>
</div>
<button type="button" class="btn-add-inline" (click)="addChapter(arc)">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Chapitre
</button>
</div>
</div>
<button type="button" class="btn-add" (click)="addArc()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Ajouter un arc
</button>
</div>
<p class="apply-error" *ngIf="applyError">{{ applyError }}</p>
<div class="review-actions">
<button type="button" class="btn-primary" [disabled]="applying || !hasNewContent" (click)="apply()">
<lucide-icon [img]="Check" [size]="16"></lucide-icon>
{{ applying ? 'Création…' : 'Créer dans la campagne' }}
</button>
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
</div>
</section>
</div>

View File

@@ -0,0 +1,323 @@
.import-page {
padding: 2rem 2.5rem;
max-width: 900px;
}
.page-header {
margin-bottom: 1.5rem;
h1 { margin: 0.6rem 0 0.3rem; font-size: 1.5rem; color: #f3f4f6; }
}
.btn-back {
display: inline-flex;
align-items: center;
gap: 0.4rem;
background: transparent;
border: none;
color: #9ca3af;
cursor: pointer;
font-size: 0.85rem;
padding: 0;
&:hover { color: #c4b5fd; }
}
.subtitle { margin: 0; color: #9ca3af; font-size: 0.9rem; }
// --- Upload -----------------------------------------------------------------
.upload-area {
padding: 2rem;
border: 1px dashed #374151;
border-radius: 12px;
text-align: center;
background: #0b1220;
}
.btn-primary,
.btn-secondary {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.6rem 1.1rem;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
border: none;
}
.btn-primary {
background: #6c63ff;
color: white;
&:hover:not(:disabled) { background: #5b52e0; }
&:disabled { opacity: 0.6; cursor: progress; }
&.big { padding: 0.8rem 1.4rem; font-size: 0.95rem; }
}
.btn-secondary {
background: #1f2937;
color: #e5e7eb;
border: 1px solid #374151;
&:hover { background: #273244; }
}
.import-progress {
margin: 1.25rem auto 0;
max-width: 460px;
text-align: left;
}
.import-phase { margin: 0 0 0.5rem; color: #c4b5fd; font-size: 0.85rem; font-weight: 500; }
.progress-bar {
height: 6px;
background: #1f2937;
border-radius: 999px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: #6c63ff;
border-radius: 999px;
transition: width 0.3s ease;
}
.import-counts { margin: 0.55rem 0 0; color: #9ca3af; font-size: 0.8rem; }
.import-error,
.apply-error {
margin: 1rem 0 0;
padding: 0.55rem 0.8rem;
background: rgba(248, 113, 113, 0.1);
border: 1px solid rgba(248, 113, 113, 0.35);
border-radius: 8px;
color: #fca5a5;
font-size: 0.85rem;
}
// --- Revue (arbre) ----------------------------------------------------------
.review-summary { margin: 0 0 1rem; color: #d1d5db; font-size: 0.9rem; strong { color: #fff; } em { color: #9ca3af; font-style: italic; } }
// Nœuds déjà présents dans la campagne : grisés, lecture seule.
.existing-node {
opacity: 0.6;
.node-name { background: transparent; border-color: transparent; cursor: default; }
}
.badge-existing {
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #9ca3af;
background: rgba(255, 255, 255, 0.06);
border: 1px solid #1f2937;
border-radius: 999px;
padding: 0.1rem 0.45rem;
white-space: nowrap;
}
.tree { display: flex; flex-direction: column; gap: 0.75rem; }
.arc-card {
border: 1px solid #1f2937;
border-radius: 10px;
background: #0b1220;
overflow: hidden;
}
.node-head {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.55rem 0.7rem;
}
.arc-head { background: #111827; }
.chapter-head { background: rgba(255, 255, 255, 0.02); }
.btn-collapse {
background: transparent;
border: none;
color: #9ca3af;
cursor: pointer;
padding: 0;
display: flex;
&:hover { color: #c4b5fd; }
}
.node-icon { color: #a78bfa; flex-shrink: 0; }
.scene-icon { color: #6b7280; }
.node-name {
flex: 1;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 6px;
color: #f3f4f6;
padding: 0.35rem 0.5rem;
font-size: 0.88rem;
&:focus { outline: none; border-color: #6c63ff; }
}
.btn-remove {
background: transparent;
border: none;
color: #6b7280;
cursor: pointer;
padding: 0.2rem;
display: flex;
&:hover { color: #f87171; }
}
.node-body { padding: 0.5rem 0.7rem 0.7rem 1.7rem; display: flex; flex-direction: column; gap: 0.5rem; }
.node-desc,
.node-desc-inline {
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 6px;
color: #d1d5db;
padding: 0.35rem 0.5rem;
font-size: 0.82rem;
font-family: inherit;
resize: vertical;
&:focus { outline: none; border-color: #6c63ff; }
}
.chapter-card {
border: 1px solid #1f2937;
border-radius: 8px;
overflow: hidden;
}
// Sélecteur Linéaire / Hub
.arc-type-toggle {
display: flex;
align-items: center;
gap: 0.4rem;
}
.toggle-label { color: #9ca3af; font-size: 0.8rem; }
.type-btn {
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 6px;
color: #9ca3af;
cursor: pointer;
font-size: 0.78rem;
padding: 0.3rem 0.6rem;
&:hover { border-color: #6c63ff; }
&.active { background: rgba(108, 99, 255, 0.18); border-color: #6c63ff; color: #c4b5fd; font-weight: 600; }
}
.scene-card {
border: 1px solid #161e2e;
border-radius: 6px;
padding: 0.3rem 0.4rem;
}
.scene-row {
display: flex;
align-items: center;
gap: 0.4rem;
}
.btn-details {
display: inline-flex;
align-items: center;
gap: 0.25rem;
background: transparent;
border: 1px solid #1f2937;
border-radius: 6px;
color: #9ca3af;
cursor: pointer;
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
white-space: nowrap;
&:hover { color: #c4b5fd; border-color: #6c63ff; }
}
.scene-details {
display: flex;
flex-direction: column;
gap: 0.3rem;
margin: 0.4rem 0 0.2rem 1.5rem;
padding-left: 0.6rem;
border-left: 2px solid #1f2937;
}
.field-label {
color: #9ca3af;
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.03em;
margin-top: 0.3rem;
}
.rooms {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.room-row {
display: flex;
align-items: center;
gap: 0.35rem;
}
.room-name,
.room-field {
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 5px;
color: #d1d5db;
padding: 0.25rem 0.4rem;
font-size: 0.78rem;
&:focus { outline: none; border-color: #6c63ff; }
}
.room-name { flex: 0 0 22%; }
.room-field { flex: 1; min-width: 0; }
.scene-fields {
flex: 1;
display: flex;
gap: 0.4rem;
.node-name { flex: 0 0 40%; }
.node-desc-inline { flex: 1; }
}
.btn-add,
.btn-add-inline {
display: inline-flex;
align-items: center;
gap: 0.3rem;
background: transparent;
border: 1px dashed #374151;
border-radius: 6px;
color: #9ca3af;
cursor: pointer;
font-size: 0.8rem;
padding: 0.35rem 0.6rem;
align-self: flex-start;
&:hover { color: #c4b5fd; border-color: #6c63ff; }
}
.btn-add { margin-top: 0.25rem; }
.review-actions {
display: flex;
gap: 0.6rem;
margin-top: 1.5rem;
}

View File

@@ -0,0 +1,374 @@
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import {
LucideAngularModule, ArrowLeft, Upload, Plus, Trash2,
ChevronDown, ChevronRight, Swords, BookOpen, MapPin, Check
} from 'lucide-angular';
import { CampaignImportService } from '../../../services/campaign-import.service';
import { CampaignService } from '../../../services/campaign.service';
import { CharacterService } from '../../../services/character.service';
import { NpcService } from '../../../services/npc.service';
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
import { PageTitleService } from '../../../services/page-title.service';
import { ArcKind, ArcProposal, ChapterProposal, SceneProposal } from '../../../services/campaign-import.model';
import { CampaignImportProposal } from '../../../services/campaign-import.model';
import { loadCampaignTreeData, CampaignTreeData } from '../../campaign-tree.helper';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
/**
* Nœuds éditables (= proposition + état d'UI). `existing` = déjà présent dans la
* campagne (chargé pour la revue) : lecture seule, sert de parent aux ajouts.
* `existingId` = l'ID de l'entité existante (envoyé à l'apply pour s'y rattacher).
*/
interface RoomNode { name: string; description: string; enemies: string; loot: string; }
interface SceneNode {
name: string; description: string; playerNarration: string; gmNotes: string;
rooms: RoomNode[]; detailsOpen: boolean; existing: boolean; existingId?: string;
}
interface ChapterNode {
name: string; description: string; scenes: SceneNode[]; collapsed: boolean;
existing: boolean; existingId?: string;
}
interface ArcNode {
name: string; description: string; type: ArcKind; chapters: ChapterNode[]; collapsed: boolean;
existing: boolean; existingId?: string;
}
/**
* Page d'import d'un PDF de campagne → arbre arc/chapitre/scène.
* Route : /campaigns/:campaignId/import
*
* Flux : upload → progression streamée → arbre éditable (revue) → création.
* Rien n'est créé tant que l'utilisateur n'a pas validé « Créer dans la campagne ».
*/
@Component({
selector: 'app-campaign-import',
standalone: true,
imports: [CommonModule, FormsModule, LucideAngularModule],
templateUrl: './campaign-import.component.html',
styleUrls: ['./campaign-import.component.scss']
})
export class CampaignImportComponent implements OnInit {
readonly ArrowLeft = ArrowLeft;
readonly Upload = Upload;
readonly Plus = Plus;
readonly Trash2 = Trash2;
readonly ChevronDown = ChevronDown;
readonly ChevronRight = ChevronRight;
readonly Swords = Swords;
readonly BookOpen = BookOpen;
readonly MapPin = MapPin;
readonly Check = Check;
campaignId = '';
// --- État import (streaming) ---
importing = false;
importPhase = '';
importProgress: { current: number; total: number } | null = null;
importCounts: { arcs: number; chapters: number; scenes: number } | null = null;
importError: string | null = null;
/** Vrai une fois la proposition reçue (on affiche l'arbre éditable). */
reviewing = false;
// --- Arbre éditable ---
tree: ArcNode[] = [];
/** Structure actuelle de la campagne (chargée pour la fusion à la revue). */
private existingData: CampaignTreeData | null = null;
// --- État application (création) ---
applying = false;
applyError: string | null = null;
constructor(
private route: ActivatedRoute,
private router: Router,
private service: CampaignImportService,
private campaignService: CampaignService,
private characterService: CharacterService,
private npcService: NpcService,
private campaignSidebar: CampaignSidebarService,
private pageTitle: PageTitleService
) {}
ngOnInit(): void {
this.campaignId = this.route.snapshot.paramMap.get('campaignId')!;
this.pageTitle.set('Importer une campagne');
this.campaignSidebar.show(this.campaignId);
// Pré-chargement de l'arborescence existante (pour fusionner à la revue).
// En cas d'échec on dégrade : tout sera considéré comme nouveau.
loadCampaignTreeData(this.campaignService, this.campaignId, this.characterService, this.npcService)
.pipe(catchError(() => of(null)))
.subscribe(data => this.existingData = data);
}
// --- Upload + streaming --------------------------------------------------
onPdfSelected(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (file) this.importPdf(file);
}
private importPdf(file: File): void {
this.importing = true;
this.reviewing = false;
this.importError = null;
this.applyError = null;
this.importPhase = 'Extraction du texte…';
this.importProgress = null;
this.importCounts = null;
this.tree = [];
this.service.importStructureStream(this.campaignId, file).subscribe({
next: (ev) => {
if (ev.type === 'progress') {
if (ev.total === 0) {
this.importPhase = 'Extraction du texte…';
this.importProgress = null;
} else {
this.importPhase = `Analyse de la campagne… (${ev.current}/${ev.total})`;
this.importProgress = { current: ev.current, total: ev.total };
this.importCounts = { arcs: ev.arcCount, chapters: ev.chapterCount, scenes: ev.sceneCount };
}
} else if (ev.type === 'done') {
this.importing = false;
this.importPhase = '';
this.importProgress = null;
if ((ev.arcs ?? []).length === 0) {
this.importError = "Aucune structure narrative détectée dans ce PDF.";
this.reviewing = false;
} else {
this.tree = this.buildMergedTree(ev.arcs);
this.reviewing = true;
}
}
},
error: (err: Error) => {
this.importing = false;
this.importPhase = '';
this.importProgress = null;
this.importError = err?.message ? `Échec de l'import : ${err.message}` : "Échec de l'import du PDF.";
}
});
}
// --- Construction de l'arbre fusionné (existant + proposition) -----------
/**
* Construit l'arbre de revue : d'abord l'arborescence ACTUELLE de la campagne
* (nœuds `existing`, lecture seule), puis on y fusionne la proposition par NOM
* (insensible à la casse). Ce qui matche un nœud existant est rattaché ; ce qui
* ne matche pas devient un nouveau nœud éditable.
*/
private buildMergedTree(proposalArcs: ArcProposal[]): ArcNode[] {
const byOrder = (a: { order?: number }, b: { order?: number }) => (a.order ?? 0) - (b.order ?? 0);
const arcs: ArcNode[] = [];
// 1. Arbre existant.
const data = this.existingData;
if (data) {
for (const arc of [...data.arcs].sort(byOrder)) {
const chapters: ChapterNode[] = [];
for (const ch of [...(data.chaptersByArc[arc.id!] ?? [])].sort(byOrder)) {
const scenes: SceneNode[] = [];
for (const sc of [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder)) {
scenes.push(this.existingSceneNode(sc.id!, sc.name, sc.description));
}
chapters.push({
name: ch.name, description: ch.description ?? '', scenes,
collapsed: true, existing: true, existingId: ch.id
});
}
arcs.push({
name: arc.name, description: arc.description ?? '',
type: (arc.type === 'HUB' ? 'HUB' : 'LINEAR'), chapters,
collapsed: true, existing: true, existingId: arc.id
});
}
}
// 2. Fusion de la proposition.
for (const pa of proposalArcs ?? []) {
const match = arcs.find(a => a.existing && this.sameName(a.name, pa.name));
if (match) {
this.mergeChaptersInto(match, pa.chapters ?? []);
match.collapsed = false;
} else {
arcs.push(this.newArcNode(pa));
}
}
return arcs;
}
private mergeChaptersInto(arc: ArcNode, propChapters: ChapterProposal[]): void {
for (const pc of propChapters) {
const match = arc.chapters.find(c => c.existing && this.sameName(c.name, pc.name));
if (match) {
this.mergeScenesInto(match, pc.scenes ?? []);
match.collapsed = false;
} else {
arc.chapters.push(this.newChapterNode(pc));
}
}
}
private mergeScenesInto(chapter: ChapterNode, propScenes: SceneProposal[]): void {
for (const ps of propScenes) {
// Scène de même nom déjà présente → on ne duplique pas (dédup).
if (chapter.scenes.some(s => this.sameName(s.name, ps.name))) continue;
chapter.scenes.push(this.newSceneNode(ps));
}
}
private sameName(a: string, b: string): boolean {
return (a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
}
// --- Mappers proposition → nœud NEUF -------------------------------------
private newArcNode(a: ArcProposal): ArcNode {
return {
name: a.name ?? '', description: a.description ?? '',
type: (a.type === 'HUB' ? 'HUB' : 'LINEAR'),
collapsed: false, existing: false,
chapters: (a.chapters ?? []).map(c => this.newChapterNode(c))
};
}
private newChapterNode(c: ChapterProposal): ChapterNode {
return {
name: c.name ?? '', description: c.description ?? '',
collapsed: false, existing: false,
scenes: (c.scenes ?? []).map(s => this.newSceneNode(s))
};
}
private newSceneNode(s: SceneProposal): SceneNode {
return {
name: s.name ?? '', description: s.description ?? '',
playerNarration: s.playerNarration ?? '', gmNotes: s.gmNotes ?? '',
detailsOpen: false, existing: false,
rooms: (s.rooms ?? []).map(r => ({
name: r.name ?? '', description: r.description ?? '',
enemies: r.enemies ?? '', loot: r.loot ?? ''
}))
};
}
private existingSceneNode(id: string, name: string, description?: string): SceneNode {
return {
name, description: description ?? '', playerNarration: '', gmNotes: '',
detailsOpen: false, existing: true, existingId: id, rooms: []
};
}
setArcType(arc: ArcNode, type: ArcKind): void { arc.type = type; }
toggleDetails(scene: SceneNode): void { scene.detailsOpen = !scene.detailsOpen; }
addRoom(scene: SceneNode): void {
scene.rooms.push({ name: '', description: '', enemies: '', loot: '' });
scene.detailsOpen = true;
}
removeRoom(scene: SceneNode, index: number): void { scene.rooms.splice(index, 1); }
// --- Édition de l'arbre --------------------------------------------------
toggleArc(arc: ArcNode): void { arc.collapsed = !arc.collapsed; }
toggleChapter(chapter: ChapterNode): void { chapter.collapsed = !chapter.collapsed; }
addArc(): void {
this.tree.push({ name: '', description: '', type: 'LINEAR', chapters: [], collapsed: false, existing: false });
}
removeArc(index: number): void { this.tree.splice(index, 1); }
addChapter(arc: ArcNode): void {
arc.chapters.push({ name: '', description: '', scenes: [], collapsed: false, existing: false });
}
removeChapter(arc: ArcNode, index: number): void { arc.chapters.splice(index, 1); }
addScene(chapter: ChapterNode): void {
chapter.scenes.push({
name: '', description: '', playerNarration: '', gmNotes: '', rooms: [], detailsOpen: true, existing: false
});
}
removeScene(chapter: ChapterNode, index: number): void { chapter.scenes.splice(index, 1); }
/** Compteurs des nœuds NOUVEAUX (= ce qui sera réellement créé). */
get arcCount(): number { return this.tree.filter(a => !a.existing && a.name.trim()).length; }
get chapterCount(): number {
return this.tree.reduce((n, a) => n + a.chapters.filter(c => !c.existing && c.name.trim()).length, 0);
}
get sceneCount(): number {
return this.tree.reduce((n, a) =>
n + a.chapters.reduce((m, c) => m + c.scenes.filter(s => !s.existing && s.name.trim()).length, 0), 0);
}
/** Vrai s'il y a au moins un nœud nouveau à créer (sinon « Créer » désactivé). */
get hasNewContent(): boolean {
return this.arcCount > 0 || this.chapterCount > 0 || this.sceneCount > 0;
}
// --- Application (création) ----------------------------------------------
apply(): void {
if (this.applying || !this.hasNewContent) return;
this.applying = true;
this.applyError = null;
// On envoie l'arbre fusionné COMPLET (existants + nouveaux) : les nœuds
// `existing` portent leur existingId et servent de parents — l'apply ne
// recrée que les nœuds sans existingId.
const proposal: CampaignImportProposal = {
arcs: this.tree
.filter(a => a.name.trim())
.map(a => ({
name: a.name.trim(),
description: a.description.trim(),
type: a.type,
existingId: a.existingId ?? null,
chapters: a.chapters
.filter(c => c.name.trim())
.map(c => ({
name: c.name.trim(),
description: c.description.trim(),
existingId: c.existingId ?? null,
scenes: c.scenes
.filter(s => s.name.trim())
.map(s => ({
name: s.name.trim(),
description: s.description.trim(),
playerNarration: s.playerNarration.trim(),
gmNotes: s.gmNotes.trim(),
existingId: s.existingId ?? null,
rooms: s.rooms
.filter(r => r.name.trim())
.map(r => ({
name: r.name.trim(),
description: r.description.trim(),
enemies: r.enemies.trim(),
loot: r.loot.trim()
}))
}))
}))
}))
};
this.service.applyStructure(this.campaignId, proposal).subscribe({
next: () => this.router.navigate(['/campaigns', this.campaignId]),
error: () => {
this.applying = false;
this.applyError = "Échec de la création. La campagne existe-t-elle toujours ?";
}
});
}
cancel(): void {
this.router.navigate(['/campaigns', this.campaignId]);
}
}

View File

@@ -1,19 +1,19 @@
<div class="chapter-create-page">
<div class="page-header">
<h1>Créer un nouveau chapitre</h1>
<p class="arc-ref" *ngIf="arcName">Arc : {{ arcName }}</p>
<h1>{{ isHub ? 'Créer une nouvelle quête' : 'Créer un nouveau chapitre' }}</h1>
<p class="arc-ref" *ngIf="arcName">{{ isHub ? 'Hub' : 'Arc' }} : {{ arcName }}</p>
</div>
<form [formGroup]="form" (ngSubmit)="submit()" class="chapter-form">
<div class="field">
<label for="chapter-create-name">Nom du chapitre *</label>
<label for="chapter-create-name">{{ isHub ? 'Nom de la quête *' : 'Nom du chapitre *' }}</label>
<input
id="chapter-create-name"
type="text"
formControlName="name"
placeholder="Ex: Chapitre 1: Les Disparitions"
[placeholder]="isHub ? 'Ex: Sauver le marchand disparu' : 'Ex: Chapitre 1: Les Disparitions'"
[class.invalid]="form.get('name')?.invalid && form.get('name')?.touched"
/>
</div>
@@ -23,7 +23,7 @@
<textarea
id="chapter-create-description"
formControlName="description"
placeholder="Décrivez ce chapitre..."
[placeholder]="isHub ? 'Décrivez cette quête...' : 'Décrivez ce chapitre...'"
rows="5">
</textarea>
</div>
@@ -35,7 +35,7 @@
<div class="form-actions">
<button type="submit" class="btn-primary" [disabled]="form.invalid">
Créer le chapitre
{{ isHub ? 'Créer la quête' : 'Créer le chapitre' }}
</button>
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
</div>

View File

@@ -31,6 +31,8 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
campaignId = '';
arcId = '';
arcName = '';
/** Arc parent de type hub : un "chapitre" y est présenté comme une "quête". */
isHub = false;
private existingChapterCount = 0;
constructor(
@@ -62,6 +64,7 @@ export class ChapterCreateComponent implements OnInit, OnDestroy {
}).subscribe(({ campaign, allCampaigns, treeData }) => {
const currentArc = treeData.arcs.find(a => a.id === this.arcId);
this.arcName = currentArc?.name ?? '';
this.isHub = currentArc?.type === 'HUB';
this.existingChapterCount = treeData.chaptersByArc[this.arcId]?.length ?? 0;
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId));

View File

@@ -5,7 +5,6 @@ import { FormsModule } from '@angular/forms';
import { LucideAngularModule, Save, ArrowLeft, User, Trash2, Sparkles } from 'lucide-angular';
import { CharacterService } from '../../../services/character.service';
import { CampaignService } from '../../../services/campaign.service';
import { PlaythroughService } from '../../../services/playthrough.service';
import { GameSystemService } from '../../../services/game-system.service';
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
import { TemplateField } from '../../../services/template.model';
@@ -49,7 +48,7 @@ export class CharacterEditComponent implements OnInit {
toggleChat(): void { this.chatOpen = !this.chatOpen; }
campaignId: string | null = null;
/** Partie cible — déduite du 1er Playthrough de la campagne. */
/** Partie propriétaire du PJ — lue depuis la route (les PJ sont scoping Playthrough). */
playthroughId: string | null = null;
characterId: string | null = null;
@@ -67,7 +66,6 @@ export class CharacterEditComponent implements OnInit {
private router: Router,
private service: CharacterService,
private campaignService: CampaignService,
private playthroughService: PlaythroughService,
private gameSystemService: GameSystemService,
private campaignSidebar: CampaignSidebarService,
private confirmDialog: ConfirmDialogService
@@ -76,15 +74,12 @@ export class CharacterEditComponent implements OnInit {
ngOnInit(): void {
const params = this.route.snapshot.paramMap;
this.campaignId = params.get('campaignId');
this.playthroughId = params.get('playthroughId');
this.characterId = params.get('characterId');
if (this.campaignId) {
this.loadTemplateForCampaign(this.campaignId);
this.campaignSidebar.show(this.campaignId);
// Résolution Partie par défaut (1er Playthrough) — nécessaire pour create/update.
this.playthroughService.listByCampaign(this.campaignId).subscribe({
next: list => { this.playthroughId = list.length > 0 ? list[0].id! : null; }
});
}
if (this.characterId) {
@@ -138,7 +133,7 @@ export class CharacterEditComponent implements OnInit {
req.subscribe({
next: (saved) => {
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'characters', saved.id]);
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'characters', saved.id]);
} else {
this.back();
}
@@ -165,7 +160,9 @@ export class CharacterEditComponent implements OnInit {
}
back(): void {
if (this.campaignId) {
if (this.campaignId && this.playthroughId) {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId]);
} else if (this.campaignId) {
this.router.navigate(['/campaigns', this.campaignId]);
} else {
this.router.navigate(['/campaigns']);

View File

@@ -13,7 +13,7 @@ import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-dr
/**
* Vue lecture seule "WorldAnvil" d'une fiche PJ.
* Route : /campaigns/:campaignId/characters/:characterId
* Route : /campaigns/:campaignId/playthroughs/:playthroughId/characters/:characterId
*/
@Component({
selector: 'app-character-view',
@@ -28,6 +28,7 @@ export class CharacterViewComponent implements OnInit {
readonly Sparkles = Sparkles;
campaignId: string | null = null;
playthroughId: string | null = null;
characterId: string | null = null;
character: Character | null = null;
@@ -48,6 +49,7 @@ export class CharacterViewComponent implements OnInit {
ngOnInit(): void {
const params = this.route.snapshot.paramMap;
this.campaignId = params.get('campaignId');
this.playthroughId = params.get('playthroughId');
this.characterId = params.get('characterId');
if (this.characterId) {
this.service.getById(this.characterId).subscribe({
@@ -68,13 +70,15 @@ export class CharacterViewComponent implements OnInit {
}
edit(): void {
if (this.campaignId && this.characterId) {
this.router.navigate(['/campaigns', this.campaignId, 'characters', this.characterId, 'edit']);
if (this.campaignId && this.playthroughId && this.characterId) {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'characters', this.characterId, 'edit']);
}
}
back(): void {
if (this.campaignId) {
if (this.campaignId && this.playthroughId) {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId]);
} else if (this.campaignId) {
this.router.navigate(['/campaigns', this.campaignId]);
} else {
this.router.navigate(['/campaigns']);

View File

@@ -42,11 +42,17 @@
<!-- PJ -->
<section class="block">
<h2><lucide-icon [img]="Users" [size]="18"></lucide-icon> Personnages joueurs</h2>
<div class="block-header">
<h2><lucide-icon [img]="Users" [size]="18"></lucide-icon> Personnages joueurs</h2>
<button type="button" class="btn-add" (click)="createCharacter()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
Nouveau PJ
</button>
</div>
<p class="empty" *ngIf="characters.length === 0">Aucun PJ pour cette partie.</p>
<ul class="character-list" *ngIf="characters.length > 0">
<li *ngFor="let c of characters">
<a [routerLink]="['/campaigns', campaignId, 'characters', c.id]">{{ c.name }}</a>
<a [routerLink]="['/campaigns', campaignId, 'playthroughs', playthroughId, 'characters', c.id]">{{ c.name }}</a>
</li>
</ul>
</section>

View File

@@ -46,6 +46,32 @@
}
}
.block-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.7rem;
h2 { margin: 0; }
}
.btn-add {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 1rem;
background: #6c63ff;
color: white;
border: none;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
&:hover { background: #5b52e0; }
}
.empty {
font-size: 0.88rem;
color: var(--color-text-muted, #777);

View File

@@ -3,7 +3,7 @@ import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { forkJoin, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { LucideAngularModule, ArrowLeft, Play, Flag, Users, Trash2, Pencil } from 'lucide-angular';
import { LucideAngularModule, ArrowLeft, Play, Flag, Users, Trash2, Pencil, Plus } from 'lucide-angular';
import { CampaignService } from '../../../services/campaign.service';
import { CharacterService } from '../../../services/character.service';
import { NpcService } from '../../../services/npc.service';
@@ -36,6 +36,7 @@ export class PlaythroughDetailComponent implements OnInit, OnDestroy {
readonly Users = Users;
readonly Trash2 = Trash2;
readonly Pencil = Pencil;
readonly Plus = Plus;
campaignId = '';
playthroughId = '';
@@ -105,6 +106,11 @@ export class PlaythroughDetailComponent implements OnInit, OnDestroy {
this.router.navigate(['/sessions', s.id]);
}
/** Crée un PJ rattaché à CETTE Partie (route scoping Playthrough). */
createCharacter(): void {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'characters', 'create']);
}
openFlags(): void {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'flags']);
}