Bêta 1.7.0 : catalogue de sorts, entraînement aux règles, fiches tirées des règles

Systèmes de jeu
- Édition d'un système en onglets : Présentation, Règles, Structure des fiches, Sorts ;
  recherche dans les règles, sections repliées, enregistrement toujours visible.
- Catalogue de sorts (V32) : un sort par fiche, champs propres au système, recherche et
  filtres par niveau et par école ; inclus dans l'export et l'import du contenu.
- Proposition de sorts à partir des règles : lecture morceau par morceau, un sort n'est
  proposé que si son nom et un passage cité se retrouvent dans le texte.
- Sorts connus des fiches PJ, PNJ et ennemi (V33, table à part) et onglet Sorts du mode
  séance.
- Proposition des champs d'une fiche (PJ, PNJ, ennemi) à partir des règles.

Campagnes
- Entraînement aux règles : situations tirées des scènes, corrigé qui cite les règles ;
  sections et citations dans la langue de l'interface.
- Fiches de campagne en noyau + rubriques (scène, arc, aventure, quête annexe).
- Vocabulaire : aventure, ordre libre, quête annexe.
- Méthode guidée mémorisée sur l'aventure (V30).

Livret PDF
- Thème « Parchemin », placement des illustrations (V31), renvois vers les PNJ.

Bureau et IA
- Journal du Brain (logs/brain.log) et erreurs de l'IA mieux rapportées.

Passage à la 1.7.0-beta.
This commit is contained in:
2026-11-13 01:13:44 +01:00
parent 0d56f8527b
commit 6c1d74f9a5
354 changed files with 22687 additions and 1584 deletions
+1
View File
@@ -46,6 +46,7 @@ export const routes: Routes = [
{ path: 'campaigns/:campaignId/random-tables/:tableId/edit', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
{ path: 'campaigns/:campaignId/random-tables/:tableId', loadComponent: () => import('./campaigns/random-table/random-table-view/random-table-view.component').then(m => m.RandomTableViewComponent) },
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
{ path: 'campaigns/:campaignId/rule-training', loadComponent: () => import('./campaigns/rule-training/rule-training.component').then(m => m.RuleTrainingComponent) },
{ path: 'campaigns/:campaignId/guided', loadComponent: () => import('./campaigns/guided/guided-chooser/guided-chooser.component').then(m => m.GuidedChooserComponent) },
{ path: 'campaigns/:campaignId/guided/:method', loadComponent: () => import('./campaigns/guided/guided-wizard/guided-wizard.component').then(m => m.GuidedWizardComponent) },
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
@@ -24,7 +24,7 @@
&.selected {
border-color: var(--color-primary, #2c6cd6);
background: rgba(66, 133, 244, 0.06);
background: rgba(108, 99, 255, 0.1);
}
input[type="radio"] { display: none; }
@@ -37,6 +37,9 @@
[entityType]="'arc'" [entityId]="arcId" [campaignId]="campaignId"
(applied)="onAssistApplied($event)"></app-entity-assist-panel>
<!-- ═══ NOYAU : toujours visible. Ce sont les champs que l'appli comprend (relecture,
méthodes guidées, bilan de préparation). ═══ -->
<!-- Identité -->
<div class="field">
<label for="arc-edit-name">{{ 'arcEdit.nameLabel' | translate }}</label>
@@ -78,52 +81,7 @@
</div>
</div>
<div class="field">
<label>{{ 'arcEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'arcEdit.illustrationsLabel' | translate" icon="🖼️" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event">
</app-image-gallery>
<small class="field-hint">{{ 'arcEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
<!-- Thèmes et enjeux -->
<!-- Histoire cachée et accroches : la vérité que les joueurs découvriront, et pourquoi ils s'en mêlent. -->
<app-expandable-section [title]="'arcEdit.truthHooksSectionTitle' | translate" icon="🗝️" [initiallyOpen]="focusSection === 'hooks'" [filled]="truthHooksFilled">
<div class="field">
<div class="field-label-row">
<label for="arc-edit-hidden-truth">{{ 'arcEdit.hiddenTruthLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.hiddenTruth"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-hidden-truth"
formControlName="hiddenTruth"
[placeholder]="'arcEdit.hiddenTruthPlaceholder' | translate"
rows="4">
</textarea>
</div>
<div class="field">
<div class="field-label-row">
<label for="arc-edit-hooks">{{ 'arcEdit.hooksLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.hooks"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-hooks"
formControlName="hooks"
[placeholder]="'arcEdit.hooksPlaceholder' | translate"
rows="4">
</textarea>
<small class="field-hint">{{ 'arcEdit.hooksHint' | translate }}</small>
</div>
</app-expandable-section>
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
<div class="field-row">
<div class="field">
@@ -153,51 +111,102 @@
</div>
</app-expandable-section>
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'arcEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [filled]="gmNotesFilled">
<!-- Histoire cachée et accroches : la vérité que les joueurs découvriront, et pourquoi ils s'en mêlent. -->
<app-expandable-section [title]="'arcEdit.truthHooksSectionTitle' | translate" icon="🗝️" [initiallyOpen]="focusSection === 'hooks'" [filled]="truthHooksFilled">
<div class="field">
<label for="arc-edit-gm-notes">{{ 'arcEdit.gmNotesLabel' | translate }}</label>
<div class="field-label-row">
<label for="arc-edit-hidden-truth">{{ 'arcEdit.hiddenTruthLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.hiddenTruth"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-gm-notes"
formControlName="gmNotes"
[placeholder]="'arcEdit.gmNotesPlaceholder' | translate"
rows="5">
id="arc-edit-hidden-truth"
formControlName="hiddenTruth"
[placeholder]="'arcEdit.hiddenTruthPlaceholder' | translate"
rows="4">
</textarea>
<small class="field-hint">{{ 'arcEdit.gmNotesHint' | translate }}</small>
</div>
<div class="field">
<div class="field-label-row">
<label for="arc-edit-hooks">{{ 'arcEdit.hooksLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.hooks"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-hooks"
formControlName="hooks"
[placeholder]="'arcEdit.hooksPlaceholder' | translate"
rows="4">
</textarea>
<small class="field-hint">{{ 'arcEdit.hooksHint' | translate }}</small>
</div>
</app-expandable-section>
<!-- Récompenses et dénouement -->
<app-expandable-section [title]="'arcEdit.rewardsResolutionSectionTitle' | translate" icon="🎁" [filled]="rewardsResolutionFilled">
<div class="field">
<div class="field-label-row">
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.rewards"></app-writing-coach-trigger>
<!-- ═══ RUBRIQUES : optionnelles. Affichées si elles ont déjà du contenu ou si l'auteur
les a demandées (voir campaigns/entity-blocks.ts). ═══ -->
@if (shows('gmNotes')) {
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'arcEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [initiallyOpen]="blocks.isAdded('gmNotes')" [filled]="gmNotesFilled">
<div class="field">
<label for="arc-edit-gm-notes">{{ 'arcEdit.gmNotesLabel' | translate }}</label>
<textarea
id="arc-edit-gm-notes"
formControlName="gmNotes"
[placeholder]="'arcEdit.gmNotesPlaceholder' | translate"
rows="5">
</textarea>
<small class="field-hint">{{ 'arcEdit.gmNotesHint' | translate }}</small>
</div>
<textarea
id="arc-edit-rewards"
formControlName="rewards"
[placeholder]="'arcEdit.rewardsPlaceholder' | translate"
rows="4">
</textarea>
</div>
<div class="field">
<div class="field-label-row">
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.resolution"></app-writing-coach-trigger>
</app-expandable-section>
}
@if (shows('rewardsResolution')) {
<!-- Récompenses et dénouement -->
<app-expandable-section [title]="'arcEdit.rewardsResolutionSectionTitle' | translate" icon="🎁" [initiallyOpen]="blocks.isAdded('rewardsResolution')" [filled]="rewardsResolutionFilled">
<div class="field">
<div class="field-label-row">
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.rewards"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-rewards"
formControlName="rewards"
[placeholder]="'arcEdit.rewardsPlaceholder' | translate"
rows="4">
</textarea>
</div>
<textarea
id="arc-edit-resolution"
formControlName="resolution"
[placeholder]="'arcEdit.resolutionPlaceholder' | translate"
rows="4">
</textarea>
</div>
</app-expandable-section>
<div class="field">
<div class="field-label-row">
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
<app-writing-coach-trigger topic="arc.resolution"></app-writing-coach-trigger>
</div>
<textarea
id="arc-edit-resolution"
formControlName="resolution"
[placeholder]="'arcEdit.resolutionPlaceholder' | translate"
rows="4">
</textarea>
</div>
</app-expandable-section>
}
@if (shows('illustrations')) {
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'arcEdit.illustrationsLabel' | translate" icon="🖼️" [initiallyOpen]="blocks.isAdded('illustrations')" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event"
[placements]="illustrationPlacements"
(placementsChange)="illustrationPlacements = $event">
</app-image-gallery>
<small class="field-hint">{{ 'arcEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
}
<!-- ===== Pages Lore associées (phase B2 cross-context) ===== -->
@if (loreId) {
<app-expandable-section [title]="'arcEdit.relatedPagesLabel' | translate" icon="🔗" [filled]="loreFilled">
@if (loreId && shows('lore')) {
<app-expandable-section [title]="'arcEdit.relatedPagesLabel' | translate" icon="🔗" [initiallyOpen]="blocks.isAdded('lore')" [filled]="loreFilled">
<app-lore-link-picker
[value]="relatedPageIds"
[availablePages]="availablePages"
@@ -210,6 +219,16 @@
</app-expandable-section>
}
@if (shows('icon')) {
<div class="field">
<label>{{ 'arcEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
}
<!-- Rubriques encore disponibles : on n'ajoute que ce dont la fiche a besoin. -->
<app-block-adder [choices]="addableBlocks" (add)="addBlock($event)"></app-block-adder>
@if (!loreId) {
<div class="field lore-hint">
<small class="field-hint">
@@ -217,7 +236,6 @@
</small>
</div>
}
</form>
</div>
@@ -24,7 +24,7 @@
&.selected {
border-color: var(--color-primary, #2c6cd6);
background: rgba(66, 133, 244, 0.06);
background: rgba(108, 99, 255, 0.1);
}
input[type="radio"] { display: none; }
@@ -14,14 +14,17 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Arc } from '../../../services/campaign.model';
import { Arc, ImagePlacement } from '../../../services/campaign.model';
import { Page } from '../../../services/page.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { prunePlacements } from '../../../shared/image-placements/image-placement';
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
import { ExpandableSectionComponent } from '../../../shared/expandable-section/expandable-section.component';
import { BlockAdderComponent } from '../../../shared/block-adder/block-adder.component';
import { ARC_BLOCKS, ARC_BLOCK_LABELS, ArcBlock, BlockChoice, BlockState, addableOf, choicesOf, filledOf, visibleOf } from '../../entity-blocks';
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
@@ -40,7 +43,7 @@ import { WritingReviewHintsComponent } from '../../../shared/writing-review/writ
*/
@Component({
selector: 'app-arc-edit',
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
imports: [ReactiveFormsModule, BlockAdderComponent, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
templateUrl: './arc-edit.component.html',
styleUrls: ['./arc-edit.component.scss']
})
@@ -88,6 +91,8 @@ export class ArcEditComponent implements OnInit {
/** IDs des images illustrant cet arc (bind sur app-image-gallery editable). */
illustrationImageIds: string[] = [];
/** Placement choisi pour certaines illustrations dans le livret PDF (bind sur app-image-placements). */
illustrationPlacements: Record<string, ImagePlacement> = {};
// ─────────────── État « rempli » par section (pastille de l'en-tête) ───────────────
// Seul le titre est requis ; ces getters signalent ce qui contient déjà du contenu.
@@ -107,6 +112,37 @@ export class ArcEditComponent implements OnInit {
}
get loreFilled(): boolean { return this.relatedPageIds.length > 0; }
// ─────────────── Noyau + rubriques (voir campaigns/entity-blocks.ts) ───────────────
// Le noyau est toujours affiché ; une rubrique ne l'est que si elle a du contenu ou si
// l'auteur l'a demandée. Les autres attendent dans « Ajouter une rubrique ».
readonly blocks = new BlockState<ArcBlock>();
private get filledBlocks(): ArcBlock[] {
return filledOf<ArcBlock>({
gmNotes: this.gmNotesFilled,
rewardsResolution: this.rewardsResolutionFilled,
illustrations: this.illustrationsFilled,
lore: this.loreFilled,
icon: !!this.selectedIcon
});
}
get visibleBlocks(): ArcBlock[] {
return visibleOf(ARC_BLOCKS, [], this.blocks.shownBlocks, this.filledBlocks);
}
get addableBlocks(): BlockChoice[] {
return choicesOf(addableOf<ArcBlock>(ARC_BLOCKS, this.visibleBlocks, this.loreId ? [] : ['lore']), ARC_BLOCK_LABELS);
}
shows(block: ArcBlock): boolean {
return this.visibleBlocks.includes(block);
}
addBlock(id: string): void {
this.blocks.add(id as ArcBlock);
}
constructor(
private fb: FormBuilder,
private route: ActivatedRoute,
@@ -176,6 +212,7 @@ export class ArcEditComponent implements OnInit {
this.relatedPageIds = [...(arc.relatedPageIds ?? [])];
this.selectedIcon = arc.icon ?? null;
this.illustrationImageIds = [...(arc.illustrationImageIds ?? [])];
this.illustrationPlacements = { ...(arc.illustrationPlacements ?? {}) };
this.pageTitleService.set(arc.name);
this.form.patchValue({
name: arc.name,
@@ -190,6 +227,9 @@ export class ArcEditComponent implements OnInit {
hooks: arc.hooks ?? ''
});
// Ce qui a déjà du contenu reste affiché pendant toute l'édition, même une fois vidé.
this.blocks.reset(this.filledBlocks);
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
});
}
@@ -211,6 +251,7 @@ export class ArcEditComponent implements OnInit {
hooks: this.form.value.hooks,
relatedPageIds: this.relatedPageIds,
illustrationImageIds: this.illustrationImageIds,
illustrationPlacements: prunePlacements(this.illustrationPlacements, this.illustrationImageIds),
icon: this.selectedIcon
}).subscribe({
next: () => this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId]),
@@ -13,6 +13,14 @@
</p>
</div>
<div class="view-actions">
<!-- Arc linéaire : écrire son prochain chapitre avec une méthode guidée. -->
@if ((arc.type ?? 'LINEAR') === 'LINEAR') {
<a class="btn-secondary btn-guided-entry" [routerLink]="['/campaigns', campaignId, 'guided']"
[queryParams]="{ arc: arcId }" [title]="'guided.arcEntryTitle' | translate">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'guided.entry' | translate }}
</a>
}
<button type="button" class="btn-primary" (click)="editMode()">
<lucide-icon [img]="Pencil" [size]="14"></lucide-icon>
{{ 'common.edit' | translate }}
@@ -37,15 +45,24 @@
<p class="view-section-empty">{{ 'arcView.notProvided' | translate }}</p>
}
</section>
<!-- Arc HUB : ses quêtes rattachées (entité Quête réelle, avec déblocage/progression). -->
<!-- Arc HUB (« à ordre libre ») : ses quêtes rattachées (entité Quête réelle, avec
déblocage/progression), présentées à l'auteur comme les aventures de l'arc. -->
@if (arc.type === 'HUB') {
<section class="view-section">
<div class="hub-section-header">
<h2 class="view-section-title"><span class="view-section-icon">🏳️</span> {{ 'arcView.questsTitle' | translate }}</h2>
<button type="button" class="btn-primary" (click)="createQuest()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'arcView.createQuest' | translate }}
</button>
<h2 class="view-section-title"><span class="view-section-icon">📖</span> {{ 'arcView.questsTitle' | translate }}</h2>
<div class="hub-section-actions">
<!-- Écrire la quête question par question (elle garde sa méthode). -->
<a class="btn-secondary btn-guided-entry" [routerLink]="['/campaigns', campaignId, 'guided']"
[queryParams]="{ arc: arcId }" [title]="'guided.questEntryTitle' | translate">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'guided.questEntry' | translate }}
</a>
<button type="button" class="btn-primary" (click)="createQuest()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'arcView.createQuest' | translate }}
</button>
</div>
</div>
@if (hubQuests.length > 0) {
<div class="hub-quest-grid">
@@ -17,26 +17,32 @@
gap: 0.85rem;
}
// Les variables --color-* ne sont définies nulle part : les replis sont ceux du thème
// sombre de l'appli (un repli clair donnait une carte blanche au lien bleu souligné).
.hub-quest-card {
position: relative;
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.85rem 0.9rem;
border: 1px solid var(--color-border, #e2e2e2);
border: 1px solid var(--color-border, #1f2937);
border-radius: 10px;
background: var(--color-surface, #fff);
background: var(--color-surface, #111827);
color: #e5e7eb; // la carte est un lien : pas de bleu ni de soulignement par défaut
text-decoration: none;
text-align: left;
cursor: pointer;
transition: border-color 120ms ease, transform 120ms ease, box-shadow 120ms ease;
min-height: 110px;
&:hover {
border-color: var(--color-primary, #2c6cd6);
border-color: var(--color-primary, #6c63ff);
transform: translateY(-1px);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.06);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.25);
}
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
&.locked {
opacity: 0.7;
background: rgba(128, 128, 128, 0.04);
@@ -45,7 +51,7 @@
&:hover {
// Pas d'illusion d'interactivité pour les quêtes verrouillées
transform: none;
border-color: var(--color-border, #e2e2e2);
border-color: var(--color-border, #1f2937);
box-shadow: none;
}
}
@@ -61,7 +67,7 @@
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--color-primary, #2c6cd6);
color: #a5b4fc;
}
.hub-quest-card-name {
@@ -72,7 +78,7 @@
.hub-quest-card-desc {
font-size: 0.82rem;
color: var(--color-text-muted, #666);
color: var(--color-text-muted, #9ca3af);
margin: 0;
display: -webkit-box;
-webkit-line-clamp: 3;
@@ -92,7 +98,7 @@
padding-top: 0.4rem;
border-top: 1px dashed rgba(128, 128, 128, 0.25);
font-size: 0.72rem;
color: var(--color-text-muted, #777);
color: var(--color-text-muted, #9ca3af);
> lucide-icon,
> span {
@@ -110,3 +116,19 @@
flex-direction: column;
gap: 0.1rem;
}
// Entrée « Méthode guidée » : un lien stylé en bouton, aligné sur ses voisins.
.btn-guided-entry {
display: inline-flex;
align-items: center;
gap: 0.4rem;
text-decoration: none;
lucide-icon { color: #fbbf24; }
}
.hub-section-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
@@ -5,7 +5,7 @@ import { forkJoin, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DataSyncService } from '../../../services/data-sync.service';
import { LucideAngularModule, Pencil, Trash2, Plus } from 'lucide-angular';
import { LucideAngularModule, Pencil, Trash2, Plus, Sparkles } from 'lucide-angular';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { resolveCampaignIcon } from '../../campaign-icons';
import { CampaignService } from '../../../services/campaign.service';
@@ -39,6 +39,7 @@ export class ArcViewComponent implements OnInit {
readonly Pencil = Pencil;
readonly Trash2 = Trash2;
readonly Plus = Plus;
readonly Sparkles = Sparkles;
readonly resolveCampaignIcon = resolveCampaignIcon;
campaignId = '';
@@ -15,14 +15,27 @@ function data(partial: Partial<CampaignTreeData> = {}): CampaignTreeData {
}
describe('buildCampaignTree', () => {
it('produit les nœuds fixes (quêtes, PNJ, ennemis, tables, ateliers, catalogues, import) quand vide', () => {
it('produit les nœuds fixes (PNJ, ennemis, tables, ateliers, catalogues, import) quand vide', () => {
const tree = buildCampaignTree('c1', data(), t);
expect(tree.map((n) => n.id)).toEqual([
'quests-root', 'npcs-root', 'enemies-root', 'random-tables-root',
'npcs-root', 'enemies-root', 'random-tables-root',
'notebooks-root', 'item-catalogs-root', 'import-pdf-root',
]);
});
it('quêtes annexes : le dossier reste masqué tant que la campagne ne compte aucune quête libre', () => {
const none = buildCampaignTree('c1', data({
arcs: [{ id: 'a', name: 'Hub', type: 'HUB' }] as never,
quests: [{ id: 'q1', name: 'Aventure du hub', arcId: 'a' }] as never,
}), t);
expect(none.some((n) => n.id === 'quests-root')).toBe(false); // une quête d'arc n'est pas annexe
const one = buildCampaignTree('c1', data({ quests: [{ id: 'q2', name: 'Annexe', arcId: null }] as never }), t);
const root = one.find((n) => n.id === 'quests-root')!;
expect(root.children!.map((c) => c.id)).toEqual(['quest-q2']);
expect(root.children![0].iconKey).toBe('flag');
});
it('place un nœud « Parties » en tête (avant la narration), une entrée par partie', () => {
const tree = buildCampaignTree('c1', data({
arcs: [{ id: 'a1', name: 'Arc', type: 'LINEAR' }] as never,
@@ -104,9 +117,13 @@ describe('buildCampaignTree', () => {
const hubArc = hub.find((n) => n.id === 'arc-a')!;
expect(hubArc.children!.some((c) => c.id === 'quest-q1')).toBe(true); // rattachée → enfant
expect(hubArc.children!.some((c) => c.id === 'quest-q2')).toBe(false); // transverse → pas ici
// HUB : on ne crée QUE des quêtes (pas de « nouveau chapitre »).
expect(hubArc.createActions!.map((a) => a.label)).toEqual(['campaignTree.newQuest']);
// HUB : on ne crée QUE des quêtes — présentées à l'auteur comme des aventures (même
// libellé qu'en linéaire), mais la route reste celle de la quête rattachée à l'arc.
expect(hubArc.createActions!.map((a) => a.label)).toEqual(['campaignTree.newChapter']);
expect(hubArc.createActions![0].route).toBe('/campaigns/c/quests/create');
expect(hubArc.createActions![0].queryParams).toEqual({ arcId: 'a' });
// Pas de drapeau par défaut : il est réservé aux quêtes annexes.
expect(hubArc.children!.find((c) => c.id === 'quest-q1')!.iconKey).toBeUndefined();
// LINEAR : uniquement des chapitres ; une quête même arcId=arc n'apparaît PAS sous l'arc.
const linear = buildCampaignTree('c', data({
@@ -117,7 +134,7 @@ describe('buildCampaignTree', () => {
expect(linArc.children!.some((c) => c.id === 'quest-q3')).toBe(false);
expect(linArc.createActions!.map((a) => a.label)).toEqual(['campaignTree.newChapter']);
// Le nœud « Quêtes » dédié conserve son action de création.
// Le nœud « Quêtes annexes » dédié conserve son action de création.
expect(hub.find((n) => n.id === 'quests-root')!.createActions![0].label).toBe('campaignTree.newQuest');
});
+32 -6
View File
@@ -12,7 +12,7 @@ import { Npc } from '../services/npc.model';
import { RandomTable } from '../services/random-table.model';
import { Enemy } from '../services/enemy.model';
import { CampaignReadinessAssessment, ReadinessGap, ReadinessSeverity, ReadinessEntityType } from '../services/readiness.model';
import { flatContainer } from './flat-structure';
import { flatContainer, implicitArc } from './flat-structure';
/**
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
@@ -228,7 +228,8 @@ export function buildCampaignTree(
let children: TreeItem[];
if (isHub) {
// Arc HUB = quêtes. Une quête FUSIONNE avec son chapitre jumeau (héritage V10 :
// Arc HUB (« à ordre libre ») : ses quêtes sont présentées comme des AVENTURES, que
// les joueurs abordent dans l'ordre de leur choix. Une quête FUSIONNE avec son chapitre jumeau (héritage V10 :
// même contenu, la quête référence le chapitre en nœud) : UN SEUL nœud d'arbre —
// la quête — portant les scènes du jumeau. Évite les doublons quête/chapitre qui
// rendaient l'arbre illisible sur les campagnes migrées.
@@ -244,7 +245,8 @@ export function buildCampaignTree(
return {
id: `quest-${q.id}`,
label: q.name,
iconKey: q.icon ?? 'flag',
// Même icône par défaut qu'un chapitre : le drapeau est réservé aux quêtes annexes.
iconKey: q.icon ?? undefined,
route: `/campaigns/${campaignId}/quests/${q.id}`,
...dotProps(questNodeGaps),
children: twins.flatMap(sceneItemsOf),
@@ -263,11 +265,12 @@ export function buildCampaignTree(
children = sortedChapters.map(chapterNode);
}
// HUB → on ne crée QUE des quêtes ; LINÉAIRE → que des chapitres.
// HUB → on ne crée QUE des quêtes ; LINÉAIRE → que des chapitres. Même libellé pour
// l'auteur (« Nouvelle aventure ») : seule la mécanique de déblocage diffère.
const arcCreateActions: TreeCreateAction[] = isHub
? [{
id: `new-quest-${arc.id}`,
label: translate.instant('campaignTree.newQuest'),
label: translate.instant('campaignTree.newChapter'),
route: `/campaigns/${campaignId}/quests/create`,
queryParams: { arcId: arc.id! },
actionIcon: 'plus'
@@ -405,6 +408,27 @@ export function buildCampaignTree(
}];
}
// Arc implicite (créé d'office, seul, vide, encore à son nom par défaut) : l'auteur ne
// l'a pas créé, on ne le lui montre pas comme un arc. Son nœud devient le groupe neutre
// « Aventures » — même contenu, même réordonnancement des chapitres, mais sans page d'arc.
const implicit = flat ? null : implicitArc(sortedArcs);
if (implicit) {
narrationNodes = arcNodes.map(node => node.id !== `arc-${implicit.id}` ? node : {
...node,
label: translate.instant('campaignTree.adventuresGroup'),
iconKey: 'book-open',
route: `/campaigns/${campaignId}`,
dragKind: undefined,
dragId: undefined,
createActions: [{
id: `new-chapter-${implicit.id}`,
label: translate.instant('campaignTree.newAdventure'),
route: `/campaigns/${campaignId}/arcs/${implicit.id}/chapters/create`,
actionIcon: 'plus'
}]
});
}
// Quêtes LIBRES (hors arc) : même fusion quête/conteneur que dans les hubs — le
// conteneur vit dans l'arc SYSTEM (chargé avec l'arbre), la quête s'affiche avec
// ses scènes dessous et son « + scène ». Recherche des conteneurs TOUS arcs confondus.
@@ -487,7 +511,9 @@ export function buildCampaignTree(
return [
...(playthroughsNode ? [playthroughsNode] : []),
...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode
// Quêtes annexes : le dossier n'apparaît qu'à partir de la première (on en crée une
// depuis l'accueil de la campagne) — vide, il doublait « Aventures » sans rien apporter.
...narrationNodes, ...(freeQuestNodes.length ? [questsNode] : []), npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode
];
}
@@ -209,7 +209,7 @@
@if (!editing) {
<section class="detail-section arcs-section">
<div class="section-header">
<h2>{{ 'campaignDetail.arcsTitle' | translate }}</h2>
<h2>{{ (implicitArc ? 'campaignDetail.adventuresTitle' : 'campaignDetail.arcsTitle') | translate }}</h2>
<div class="section-header-actions">
@if (showQuickAddScene) {
<button class="btn-add" (click)="quickAddScene()" [disabled]="quickSceneInFlight">
@@ -217,18 +217,44 @@
{{ 'campaignDetail.quickScene' | translate }}
</button>
}
<button class="btn-add" (click)="createArc()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'campaignDetail.newArc' | translate }}
</button>
@if (implicitArc) {
<button class="btn-add" (click)="createAdventure()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'campaignDetail.newAdventure' | translate }}
</button>
} @else {
<button class="btn-add" (click)="createArc()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'campaignDetail.newArc' | translate }}
</button>
}
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided']">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'guided.entry' | translate }}
</a>
<!-- Entraînement aux règles : trancher des situations tirées des scènes. -->
<a class="btn-add btn-add--secondary btn-training" [routerLink]="['/campaigns', campaign.id, 'rule-training']"
[title]="'ruleTraining.entryTitle' | translate">
<lucide-icon [img]="GraduationCap" [size]="14"></lucide-icon>
{{ 'ruleTraining.entry' | translate }}
</a>
</div>
</div>
@if (arcs.length > 0 && !flatMode) {
<!-- Arc créé d'office, seul et vide : on montre directement ses chapitres (les
aventures), pas une carte « Arc principal » que l'auteur n'a jamais créée. -->
@if (implicitArc) {
<div class="arcs-grid">
@for (a of adventures; track a.chapter.id) {
<button type="button" class="arc-card adventure-card" (click)="openAdventure(a.chapter)">
<lucide-icon [img]="BookOpen" [size]="24" class="arc-icon"></lucide-icon>
<span class="arc-name">{{ a.chapter.name }}</span>
<span class="arc-meta">{{ 'campaignDetail.scenesCount' | translate:{ n: a.scenes } }}</span>
</button>
}
</div>
}
@if (arcs.length > 0 && !flatMode && !implicitArc) {
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
(cdkDropListDropped)="dropArc($event)">
@for (arc of arcs; track arc.id) {
@@ -264,6 +290,21 @@
</button>
</div>
}
<!-- Portes secondaires, discrètes : la structure en arcs (tant que l'arc est implicite)
et la quête annexe — une histoire facultative, à proposer pendant un creux. Son dossier
n'apparaît dans le volet qu'à partir de la première. -->
@if (arcs.length > 0) {
<div class="section-alt-links">
@if (implicitArc) {
<button type="button" class="empty-alt-action" (click)="createArc()">
{{ 'campaignDetail.organizeInArcs' | translate }}
</button>
}
<button type="button" class="empty-alt-action" (click)="createSideQuest()">
{{ 'campaignDetail.addSideQuest' | translate }}
</button>
</div>
}
</section>
}
<!-- ============ Parties (Playthroughs) ============ -->
@@ -83,6 +83,21 @@
font-size: 0.95rem;
}
// Renommer / valider / annuler : sans style propre, ces boutons gardaient le fond gris
// clair du navigateur.
.playthrough-card .btn-icon {
flex: 0 0 auto;
padding: 0.3rem;
background: transparent;
border: none;
border-radius: 6px;
color: var(--color-text-muted, #9aa0aa);
cursor: pointer;
&:hover { background: rgba(255, 255, 255, 0.08); color: var(--color-text, #e0e0e0); }
&:focus-visible { outline: 2px solid var(--color-primary, #6c63ff); outline-offset: 2px; }
}
.playthrough-meta {
font-size: 0.78rem;
color: var(--color-text-muted, #777);
@@ -539,6 +554,13 @@
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
// Lien d'entrée de l'entraînement aux règles (un <a> habillé en bouton).
.btn-training {
text-decoration: none;
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
// Action secondaire de l'état vide (« ou créer un arc ») — bouton texte discret.
.empty-alt-action {
background: none;
@@ -630,3 +652,19 @@
&--none { color: #6b7280; }
}
// Carte d'aventure (chapitre d'un arc implicite) : même carte qu'un arc, mais c'est un bouton.
.adventure-card {
font: inherit;
text-align: left;
width: 100%;
&:focus-visible { outline: 2px solid var(--color-primary, #6c63ff); outline-offset: 2px; }
}
.section-alt-links {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 1.25rem;
margin-top: 0.85rem;
}
@@ -6,7 +6,7 @@ import { CampaignSidebarService } from '../../../services/campaign-sidebar.servi
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CdkDropList, CdkDrag, CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles, Download, FileText, ChevronDown, ChevronRight, X, Network } from 'lucide-angular';
import { LucideAngularModule, BookOpen, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles, Download, FileText, ChevronDown, ChevronRight, X, Network, GraduationCap } from 'lucide-angular';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { Router, RouterLink } from '@angular/router';
import { forkJoin, of, Observable } from 'rxjs';
@@ -25,7 +25,7 @@ import { Session } from '../../../services/session.model';
import { Npc } from '../../../services/npc.model';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Campaign, Arc } from '../../../services/campaign.model';
import { Campaign, Arc, Chapter } from '../../../services/campaign.model';
import { Lore } from '../../../services/lore.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig, CampaignTreeData } from '../../campaign-tree.helper';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
@@ -37,7 +37,7 @@ import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
import { PdfExportDialogComponent } from '../pdf-export-dialog/pdf-export-dialog.component';
import { downloadBlob, safeFileName } from '../../../shared/download.util';
import { flatContainer } from '../../flat-structure';
import { flatContainer, implicitArc } from '../../flat-structure';
@Component({
selector: 'app-campaign-detail',
@@ -46,6 +46,7 @@ import { flatContainer } from '../../flat-structure';
styleUrls: ['./campaign-detail.component.scss']
})
export class CampaignDetailComponent implements OnInit, OnDestroy {
readonly BookOpen = BookOpen;
readonly Swords = Swords;
readonly Plus = Plus;
readonly Globe = Globe;
@@ -63,6 +64,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
readonly ChevronRight = ChevronRight;
readonly X = X;
readonly Network = Network;
readonly GraduationCap = GraduationCap;
/** Export Foundry en cours (anti double-clic). */
exportingFoundry = false;
@@ -214,6 +216,10 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.arcs = [...treeData.arcs].sort(byOrder).filter(a => a.type !== 'SYSTEM');
this.chapterCountByArc = this.computeChapterCounts(treeData);
this.flatMode = !!flatContainer(this.arcs, treeData.chaptersByArc);
this.implicitArc = this.flatMode ? null : implicitArc(this.arcs);
this.adventures = [...(this.implicitArc ? treeData.chaptersByArc[this.implicitArc.id!] ?? [] : [])]
.sort(byOrder)
.map(chapter => ({ chapter, scenes: (treeData.scenesByChapter[chapter.id!] ?? []).length }));
this.showLayout(allCampaigns, treeData);
this.pageTitleService.set(campaign.name);
this.openEditFromQueryParam();
@@ -342,6 +348,12 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', 'create']);
}
/** Quête annexe : une quête libre (hors arc), créée depuis l'accueil. */
createSideQuest(): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'quests', 'create']);
}
// ─────────────── Ajout rapide d'une scène (conteneur par défaut) ───────────────
// Niveau 0 : on ne force plus à créer un arc puis un chapitre avant de poser une
// scène. Si la campagne n'a pas encore de structure, on provisionne un
@@ -356,6 +368,23 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
*/
flatMode = false;
/**
* Arc créé d'office, seul et vide (cf. `implicitArc`) : on ne montre pas sa carte, mais
* directement ses chapitres — les aventures de la campagne.
*/
implicitArc: Arc | null = null;
adventures: { chapter: Chapter; scenes: number }[] = [];
createAdventure(): void {
if (!this.campaign || !this.implicitArc) return;
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', this.implicitArc.id, 'chapters', 'create']);
}
openAdventure(chapter: Chapter): void {
if (!this.campaign) return;
this.router.navigate(['/campaigns', this.campaign.id, 'arcs', chapter.arcId, 'chapters', chapter.id]);
}
get showQuickAddScene(): boolean {
if (this.arcs.length === 0) return true;
if (this.arcs.length === 1) return (this.chapterCountByArc[this.arcs[0].id!] ?? 0) <= 1;
@@ -66,6 +66,22 @@
}
</div>
<div class="pdf-group">
<span class="pdf-group-label">{{ 'pdfDialog.themeLabel' | translate }}</span>
<div class="pdf-choice">
<label class="pdf-choice-option" [class.selected]="theme === 'classic'">
<input type="radio" name="pdf-theme" value="classic" [checked]="theme === 'classic'" (change)="theme = 'classic'" />
<strong>{{ 'pdfDialog.themeClassic' | translate }}</strong>
<small>{{ 'pdfDialog.themeClassicHint' | translate }}</small>
</label>
<label class="pdf-choice-option" [class.selected]="theme === 'parchment'">
<input type="radio" name="pdf-theme" value="parchment" [checked]="theme === 'parchment'" (change)="theme = 'parchment'" />
<strong>{{ 'pdfDialog.themeParchment' | translate }}</strong>
<small>{{ 'pdfDialog.themeParchmentHint' | translate }}</small>
</label>
</div>
</div>
<div class="pdf-group pdf-inline">
<label class="pdf-format">
<span class="pdf-group-label">{{ 'pdfDialog.formatLabel' | translate }}</span>
@@ -83,6 +99,18 @@
</span>
</label>
</div>
<div class="pdf-group">
<span class="pdf-group-label">{{ 'pdfDialog.refsLabel' | translate }}</span>
<small class="pdf-note">{{ 'pdfDialog.refsHint' | translate }}</small>
<label class="pdf-check">
<input type="checkbox" name="pdf-short-names" [checked]="shortNames" (change)="shortNames = !shortNames" />
<span>
{{ 'pdfDialog.shortNames' | translate }}
<small>{{ 'pdfDialog.shortNamesHint' | translate }}</small>
</span>
</label>
</div>
</div>
<div class="confirm-actions">
@@ -167,6 +167,12 @@
small { color: #9ca3af; font-size: 0.78rem; }
}
.pdf-note {
color: #9ca3af;
font-size: 0.78rem;
line-height: 1.35;
}
.pdf-lore {
display: flex;
flex-wrap: wrap;
@@ -1,12 +1,12 @@
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import { LucideAngularModule, FileText, X, BookOpen } from 'lucide-angular';
import { TranslatePipe } from '@ngx-translate/core';
import { PDF_SECTIONS, PdfExportOptions, PdfSection } from '../../../services/pdf-export.model';
import { PDF_SECTIONS, PdfExportOptions, PdfSection, PdfTheme } from '../../../services/pdf-export.model';
import { editionPreset, toExportOptions, toggleSection } from './pdf-export-presets';
/**
* Modale des options de l'export PDF : version MJ ou joueurs, format de page, mode
* impression, parties incluses et périmètre du lore. Passer en version joueurs
* Modale des options de l'export PDF : version MJ ou joueurs, habillage (classique ou
* parchemin), format de page, mode impression, parties incluses et périmètre du lore. Passer en version joueurs
* pré-sélectionne ce qui convient à des joueurs (sans bestiaire, quêtes ni tables,
* lore limité aux pages liées) ; tout reste modifiable. Le parent télécharge au confirm.
*/
@@ -37,6 +37,10 @@ export class PdfExportDialogComponent implements OnChanges {
print = false;
sections: ReadonlySet<PdfSection> = editionPreset('gm').sections;
lore: 'ALL' | 'LINKED' = 'ALL';
/** Habillage : conservé d'une ouverture à l'autre, comme le format et le mode impression. */
theme: PdfTheme = 'classic';
/** Renvois automatiques : reconnaître aussi le premier mot du nom des PNJ (coché par défaut). */
shortNames = true;
ngOnChanges(changes: SimpleChanges): void {
// Réouverture : on repart du livret MJ complet (pas de parties fantômes d'un export précédent).
@@ -65,6 +69,7 @@ export class PdfExportDialogComponent implements OnChanges {
if (this.exporting) return;
const options = toExportOptions({
edition: this.edition, format: this.format, print: this.print, sections: this.sections, lore: this.lore,
theme: this.theme, shortNames: this.shortNames,
});
if (options) this.confirmed.emit(options);
}
@@ -2,17 +2,35 @@ import { editionPreset, toExportOptions, toggleSection, PdfExportChoice } from '
import { safeFileName } from '../../../shared/download.util';
describe('PDF export presets', () => {
const gm = (): PdfExportChoice => ({ edition: 'gm', format: 'A4', print: false, ...editionPreset('gm') });
const gm = (): PdfExportChoice => ({
edition: 'gm', format: 'A4', print: false, theme: 'classic', shortNames: false, ...editionPreset('gm'),
});
it('GM edition = complete booklet, whole lore', () => {
expect(toExportOptions(gm())).toEqual({
edition: 'gm', format: 'A4', print: false,
sections: ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE', 'APPENDIX', 'MAPS'], lore: 'ALL',
theme: 'classic', shortNames: false,
});
});
it('passes the short-name references option through', () => {
expect(toExportOptions({ ...gm(), shortNames: true })!.shortNames).toBe(true);
});
it('carries the theme along with any format and print mode', () => {
for (const format of ['A4', 'A5', 'LETTER'] as const) {
for (const print of [false, true]) {
const o = toExportOptions({ ...gm(), format, print, theme: 'parchment' })!;
expect(o).toMatchObject({ theme: 'parchment', format, print });
}
}
});
it('player edition preselects player-safe parts and linked lore only', () => {
const o = toExportOptions({ edition: 'player', format: 'A5', print: true, ...editionPreset('player') })!;
const o = toExportOptions({
edition: 'player', format: 'A5', print: true, theme: 'classic', shortNames: false, ...editionPreset('player'),
})!;
expect(o.sections).toEqual(['NARRATIVE', 'NPCS', 'LORE', 'MAPS']);
expect(o.lore).toBe('LINKED');
expect(o.format).toBe('A5');
@@ -1,4 +1,4 @@
import { PDF_SECTIONS, PdfExportOptions, PdfSection } from '../../../services/pdf-export.model';
import { PDF_SECTIONS, PdfExportOptions, PdfSection, PdfTheme } from '../../../services/pdf-export.model';
/** Choix de la modale d'export PDF (état éditable). */
export interface PdfExportChoice {
@@ -7,6 +7,8 @@ export interface PdfExportChoice {
print: boolean;
sections: ReadonlySet<PdfSection>;
lore: 'ALL' | 'LINKED';
theme: PdfTheme;
shortNames: boolean;
}
/**
@@ -31,5 +33,8 @@ export function toggleSection(sections: ReadonlySet<PdfSection>, section: PdfSec
export function toExportOptions(choice: PdfExportChoice): PdfExportOptions | null {
const sections = PDF_SECTIONS.filter(s => choice.sections.has(s));
if (sections.length === 0) return null;
return { edition: choice.edition, format: choice.format, print: choice.print, sections, lore: choice.lore };
return {
edition: choice.edition, format: choice.format, print: choice.print, sections, lore: choice.lore, theme: choice.theme,
shortNames: choice.shortNames,
};
}
@@ -7,6 +7,19 @@
}
</div>
<!-- Page blanche ? Une méthode guidée écrit le chapitre et ses scènes question par question. -->
@if (arcIsLinear) {
<a class="guided-alt" [routerLink]="['/campaigns', campaignId, 'guided']" [queryParams]="{ arc: arcId }">
<lucide-icon [img]="Sparkles" [size]="18" class="guided-alt-icon"></lucide-icon>
<span class="guided-alt-text">
<strong>{{ 'guided.createAltTitle' | translate }}</strong>
{{ 'guided.createAltText' | translate }}
</span>
<lucide-icon [img]="ArrowRight" [size]="16"></lucide-icon>
</a>
<p class="guided-alt-or">{{ 'guided.createAltOr' | translate }}</p>
}
<form [formGroup]="form" (ngSubmit)="submit()" class="chapter-form">
<div class="field">
@@ -19,3 +19,38 @@
// Le bouton "Créer" prend toute la largeur restante.
.btn-primary { flex: 1; }
// Alternative « méthode guidée » : même importance visuelle que le formulaire vide.
.guided-alt {
display: flex;
align-items: center;
gap: 0.85rem;
padding: 0.9rem 1rem;
margin-bottom: 0.75rem;
background: rgba(251, 191, 36, 0.06);
border: 1px solid rgba(251, 191, 36, 0.3);
border-radius: 10px;
color: #d1d5db;
text-decoration: none;
transition: background 0.2s, border-color 0.2s;
&:hover { background: rgba(251, 191, 36, 0.12); border-color: #fbbf24; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
.guided-alt-icon { color: #fbbf24; flex-shrink: 0; }
.guided-alt-text {
flex: 1;
font-size: 0.86rem;
line-height: 1.45;
strong { display: block; color: #f3f4f6; font-size: 0.92rem; }
}
.guided-alt-or {
margin: 0 0 1.25rem;
color: #6b7280;
font-size: 0.8rem;
text-align: center;
}
@@ -1,9 +1,9 @@
import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { forkJoin } from 'rxjs';
import { LucideAngularModule } from 'lucide-angular';
import { LucideAngularModule, ArrowRight, Sparkles } from 'lucide-angular';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { CampaignService } from '../../../services/campaign.service';
import { NpcService } from '../../../services/npc.service';
@@ -11,6 +11,7 @@ import { RandomTableService } from '../../../services/random-table.service';
import { EnemyService } from '../../../services/enemy.service';
import { LayoutService } from '../../../services/layout.service';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { implicitArc } from '../../flat-structure';
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
@@ -20,12 +21,16 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
*/
@Component({
selector: 'app-chapter-create',
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent, TranslatePipe],
imports: [ReactiveFormsModule, RouterLink, LucideAngularModule, IconPickerComponent, TranslatePipe],
templateUrl: './chapter-create.component.html',
styleUrls: ['./chapter-create.component.scss']
})
export class ChapterCreateComponent implements OnInit {
readonly campaignIconOptions = CAMPAIGN_ICON_OPTIONS;
readonly ArrowRight = ArrowRight;
readonly Sparkles = Sparkles;
/** Les méthodes guidées rangent leur chapitre dans un arc linéaire : proposées seulement là. */
arcIsLinear = false;
selectedIcon: string | null = null;
form: FormGroup;
@@ -64,7 +69,9 @@ export class ChapterCreateComponent implements OnInit {
treeData: loadCampaignTreeData(this.campaignService, this.campaignId, this.npcService, this.randomTableService, this.enemyService)
}).subscribe(({ campaign, allCampaigns, treeData }) => {
const currentArc = treeData.arcs.find(a => a.id === this.arcId);
this.arcName = currentArc?.name ?? '';
// Arc créé d'office : on ne le cite pas, l'auteur ne l'a jamais vu.
this.arcName = implicitArc(treeData.arcs)?.id === this.arcId ? '' : currentArc?.name ?? '';
this.arcIsLinear = !!currentArc && (currentArc.type ?? 'LINEAR') === 'LINEAR';
this.existingChapterCount = treeData.chaptersByArc[this.arcId]?.length ?? 0;
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
@@ -43,6 +43,9 @@
[startOpen]="assistParam === 'draft-scenes'"
(created)="onScenesCreated($event)"></app-scene-draft-panel>
<!-- ═══ NOYAU : toujours visible. Ce sont les champs que l'appli comprend (relecture,
méthodes guidées, bilan de préparation). ═══ -->
<!-- Identité -->
<div class="field">
<label for="chapter-edit-name">{{ 'chapterEdit.nameLabel' | translate }}</label>
@@ -68,36 +71,6 @@
</textarea>
</div>
<div class="field">
<label>{{ 'chapterEdit.icon' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'chapterEdit.illustrations' | translate" icon="🖼️" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event">
</app-image-gallery>
<small class="field-hint">{{ 'chapterEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'chapterEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [filled]="gmNotesFilled">
<div class="field">
<label for="chapter-edit-gm-notes">{{ 'chapterEdit.gmNotesLabel' | translate }}</label>
<textarea
id="chapter-edit-gm-notes"
formControlName="gmNotes"
[placeholder]="'chapterEdit.gmNotesPlaceholder' | translate"
rows="6">
</textarea>
<small class="field-hint">{{ 'chapterEdit.gmNotesHint' | translate }}</small>
</div>
</app-expandable-section>
<!-- Objectifs et enjeux -->
<app-expandable-section [title]="'chapterEdit.objectivesStakesSectionTitle' | translate" icon="🎯" [initiallyOpen]="focusSection === 'stakes'" [filled]="objectivesStakesFilled">
<div class="field-row">
@@ -128,9 +101,43 @@
</div>
</app-expandable-section>
<!-- ═══ RUBRIQUES : optionnelles. Affichées si elles ont déjà du contenu ou si l'auteur
les a demandées (voir campaigns/entity-blocks.ts). ═══ -->
@if (shows('gmNotes')) {
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'chapterEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [initiallyOpen]="blocks.isAdded('gmNotes')" [filled]="gmNotesFilled">
<div class="field">
<label for="chapter-edit-gm-notes">{{ 'chapterEdit.gmNotesLabel' | translate }}</label>
<textarea
id="chapter-edit-gm-notes"
formControlName="gmNotes"
[placeholder]="'chapterEdit.gmNotesPlaceholder' | translate"
rows="6">
</textarea>
<small class="field-hint">{{ 'chapterEdit.gmNotesHint' | translate }}</small>
</div>
</app-expandable-section>
}
@if (shows('illustrations')) {
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'chapterEdit.illustrations' | translate" icon="🖼️" [initiallyOpen]="blocks.isAdded('illustrations')" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event"
[placements]="illustrationPlacements"
(placementsChange)="illustrationPlacements = $event">
</app-image-gallery>
<small class="field-hint">{{ 'chapterEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
}
<!-- ===== Pages Lore associées (B2 cross-context) ===== -->
@if (loreId) {
<app-expandable-section [title]="'chapterEdit.relatedPages' | translate" icon="🔗" [filled]="loreFilled">
@if (loreId && shows('lore')) {
<app-expandable-section [title]="'chapterEdit.relatedPages' | translate" icon="🔗" [initiallyOpen]="blocks.isAdded('lore')" [filled]="loreFilled">
<app-lore-link-picker
[value]="relatedPageIds"
[availablePages]="availablePages"
@@ -143,6 +150,16 @@
</app-expandable-section>
}
@if (shows('icon')) {
<div class="field">
<label>{{ 'chapterEdit.icon' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
}
<!-- Rubriques encore disponibles : on n'ajoute que ce dont la fiche a besoin. -->
<app-block-adder [choices]="addableBlocks" (add)="addBlock($event)"></app-block-adder>
@if (!loreId) {
<div class="field">
<small class="field-hint">
@@ -150,7 +167,6 @@
</small>
</div>
}
</form>
</div>
@@ -14,14 +14,17 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Chapter } from '../../../services/campaign.model';
import { Chapter, ImagePlacement } from '../../../services/campaign.model';
import { Page } from '../../../services/page.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { prunePlacements } from '../../../shared/image-placements/image-placement';
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
import { ExpandableSectionComponent } from '../../../shared/expandable-section/expandable-section.component';
import { BlockAdderComponent } from '../../../shared/block-adder/block-adder.component';
import { CHAPTER_BLOCKS, CHAPTER_BLOCK_LABELS, ChapterBlock, BlockChoice, BlockState, addableOf, choicesOf, filledOf, visibleOf } from '../../entity-blocks';
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
@@ -40,7 +43,7 @@ import { WritingReviewHintsComponent } from '../../../shared/writing-review/writ
@Component({
selector: 'app-chapter-edit',
imports: [
ReactiveFormsModule,
ReactiveFormsModule, BlockAdderComponent,
LucideAngularModule,
LoreLinkPickerComponent,
AiChatDrawerComponent,
@@ -98,6 +101,8 @@ export class ChapterEditComponent implements OnInit {
loreId: string | null = null;
relatedPageIds: string[] = [];
illustrationImageIds: string[] = [];
/** Placement choisi pour certaines illustrations dans le livret PDF (bind sur app-image-placements). */
illustrationPlacements: Record<string, ImagePlacement> = {};
// ─────────────── État « rempli » par section (pastille de l'en-tête) ───────────────
// Seul le titre est requis ; ces getters signalent ce qui contient déjà du contenu.
@@ -109,6 +114,36 @@ export class ChapterEditComponent implements OnInit {
}
get loreFilled(): boolean { return this.relatedPageIds.length > 0; }
// ─────────────── Noyau + rubriques (voir campaigns/entity-blocks.ts) ───────────────
// Le noyau est toujours affiché ; une rubrique ne l'est que si elle a du contenu ou si
// l'auteur l'a demandée. Les autres attendent dans « Ajouter une rubrique ».
readonly blocks = new BlockState<ChapterBlock>();
private get filledBlocks(): ChapterBlock[] {
return filledOf<ChapterBlock>({
gmNotes: this.gmNotesFilled,
illustrations: this.illustrationsFilled,
lore: this.loreFilled,
icon: !!this.selectedIcon
});
}
get visibleBlocks(): ChapterBlock[] {
return visibleOf(CHAPTER_BLOCKS, [], this.blocks.shownBlocks, this.filledBlocks);
}
get addableBlocks(): BlockChoice[] {
return choicesOf(addableOf<ChapterBlock>(CHAPTER_BLOCKS, this.visibleBlocks, this.loreId ? [] : ['lore']), CHAPTER_BLOCK_LABELS);
}
shows(block: ChapterBlock): boolean {
return this.visibleBlocks.includes(block);
}
addBlock(id: string): void {
this.blocks.add(id as ChapterBlock);
}
constructor(
private fb: FormBuilder,
private route: ActivatedRoute,
@@ -176,6 +211,7 @@ export class ChapterEditComponent implements OnInit {
this.relatedPageIds = [...(chapter.relatedPageIds ?? [])];
this.selectedIcon = chapter.icon ?? null;
this.illustrationImageIds = [...(chapter.illustrationImageIds ?? [])];
this.illustrationPlacements = { ...(chapter.illustrationPlacements ?? {}) };
this.form.patchValue({
name: chapter.name,
@@ -185,6 +221,9 @@ export class ChapterEditComponent implements OnInit {
narrativeStakes: chapter.narrativeStakes ?? ''
});
// Ce qui a déjà du contenu reste affiché pendant toute l'édition, même une fois vidé.
this.blocks.reset(this.filledBlocks);
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
});
}
@@ -201,6 +240,7 @@ export class ChapterEditComponent implements OnInit {
narrativeStakes: this.form.value.narrativeStakes,
relatedPageIds: this.relatedPageIds,
illustrationImageIds: this.illustrationImageIds,
illustrationPlacements: prunePlacements(this.illustrationPlacements, this.illustrationImageIds),
icon: this.selectedIcon
}).subscribe({
next: () => this.router.navigate(['/campaigns', this.campaignId, 'arcs', this.arcId, 'chapters', this.chapterId]),
@@ -13,6 +13,13 @@
</p>
</div>
<div class="view-actions">
@if (scenes.length > 0) {
<button type="button" class="btn-secondary" (click)="openRuleTraining()"
[title]="'ruleTraining.entryTitle' | translate">
<lucide-icon [img]="GraduationCap" [size]="14"></lucide-icon>
{{ 'ruleTraining.entry' | translate }}
</button>
}
<button type="button" class="btn-secondary" (click)="openGraph()"
[title]="'chapterView.mapTitle' | translate">
<lucide-icon [img]="Network" [size]="14"></lucide-icon>
@@ -42,6 +49,11 @@
<p class="view-section-empty">{{ 'chapterView.notProvided' | translate }}</p>
}
</section>
<!-- Méthode guidée suivie : ses temps, et la scène qui tient chacun. -->
@if (chapter.guidedMethod) {
<app-guided-structure [campaignId]="campaignId" [arcId]="arcId" [chapter]="chapter" [scenes]="scenes"
(changed)="reload()"></app-guided-structure>
}
<div class="view-row">
<section class="view-section">
<h2 class="view-section-title"><span class="view-section-icon">🎯</span> {{ 'chapterView.playerObjectives' | translate }}</h2>
@@ -82,5 +94,10 @@
</div>
</section>
}
<!-- Chapitre sans méthode : proposition discrète d'en suivre une (rien n'est réécrit). -->
@if (!chapter.guidedMethod) {
<app-guided-structure [campaignId]="campaignId" [arcId]="arcId" [chapter]="chapter" [scenes]="scenes"
[suggested]="suggestedMethod" (changed)="reload()"></app-guided-structure>
}
</div>
}
@@ -4,7 +4,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { forkJoin, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { LucideAngularModule, Pencil, Network, Trash2 } from 'lucide-angular';
import { LucideAngularModule, Pencil, Network, Trash2, GraduationCap } from 'lucide-angular';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { resolveCampaignIcon } from '../../campaign-icons';
import { CampaignService } from '../../../services/campaign.service';
@@ -14,11 +14,12 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Chapter } from '../../../services/campaign.model';
import { Chapter, Scene } from '../../../services/campaign.model';
import { Page } from '../../../services/page.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { GuidedStructureComponent } from '../../guided/guided-structure/guided-structure.component';
/**
* Écran de consultation d'un Chapitre (lecture seule).
@@ -26,7 +27,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
*/
@Component({
selector: 'app-chapter-view',
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe],
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedStructureComponent],
templateUrl: './chapter-view.component.html',
styleUrls: ['./chapter-view.component.scss']
})
@@ -34,12 +35,17 @@ export class ChapterViewComponent implements OnInit {
readonly Pencil = Pencil;
readonly Network = Network;
readonly Trash2 = Trash2;
readonly GraduationCap = GraduationCap;
readonly resolveCampaignIcon = resolveCampaignIcon;
campaignId = '';
arcId = '';
chapterId = '';
chapter: Chapter | null = null;
/** Scènes du chapitre : la structure de sa méthode guidée dit laquelle tient quel rôle. */
scenes: Scene[] = [];
/** Méthode conseillée par la relecture (`?method=`), proposée si le chapitre n'en suit aucune. */
suggestedMethod: string | null = null;
loreId: string | null = null;
availablePages: Page[] = [];
@@ -70,11 +76,17 @@ export class ChapterViewComponent implements OnInit {
this.campaignId = newCampaignId;
this.arcId = newArcId;
this.chapterId = newChapterId;
this.suggestedMethod = this.route.snapshot.queryParamMap.get('method');
this.load();
}
});
}
/** Méthode, rôle ou scène modifiés depuis la structure : on recharge le chapitre et l'arbre. */
reload(): void {
this.load();
}
private load(): void {
forkJoin({
campaign: this.campaignService.getCampaignById(this.campaignId),
@@ -89,6 +101,7 @@ export class ChapterViewComponent implements OnInit {
})
).subscribe(({ campaign, allCampaigns, chapter, treeData, pages, loreId }) => {
this.chapter = chapter;
this.scenes = treeData.scenesByChapter[this.chapterId] ?? [];
this.loreId = loreId;
this.availablePages = pages;
this.pageTitleService.set(chapter.name);
@@ -108,6 +121,11 @@ export class ChapterViewComponent implements OnInit {
]);
}
/** Entraînement aux règles, avec les scènes de cette aventure déjà cochées. */
openRuleTraining(): void {
this.router.navigate(['/campaigns', this.campaignId, 'rule-training'], { queryParams: { chapterId: this.chapterId } });
}
openGraph(): void {
this.router.navigate([
'/campaigns', this.campaignId, 'arcs', this.arcId, 'chapters', this.chapterId, 'graph'
@@ -70,6 +70,9 @@
</app-dynamic-fields-form>
</div>
<!-- Sorts connus, choisis dans le catalogue du système (rien ne s'affiche s'il n'y en a pas). -->
<app-sheet-spells mode="edit" sheet="character" [campaignId]="campaignId" [ownerId]="characterId"></app-sheet-spells>
<div class="actions">
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ViewChild } from '@angular/core';
import { map, of, switchMap } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
@@ -25,9 +26,11 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
* - Le picker d'images dedie portrait/header est hors scope MVP — pour l'instant
* saisie manuelle d'IDs d'images.
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-character-edit',
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent, SheetSpellsComponent],
templateUrl: './character-edit.component.html',
styleUrls: ['./character-edit.component.scss']
})
@@ -63,6 +66,9 @@ export class CharacterEditComponent implements OnInit {
templateFields: TemplateField[] = [];
private order = 0;
/** Sorts connus de la fiche : enregistrés après elle (cf. submit). */
@ViewChild(SheetSpellsComponent) private sheetSpells?: SheetSpellsComponent;
constructor(
private route: ActivatedRoute,
private router: Router,
@@ -133,8 +139,19 @@ export class CharacterEditComponent implements OnInit {
const req = this.characterId
? this.service.update(this.characterId, { ...payload, id: this.characterId, order: this.order })
: this.service.create(payload);
req.subscribe({
next: (saved) => {
// Les sorts connus partent une fois la fiche enregistrée : elle a alors un identifiant.
req.pipe(
switchMap(saved => (this.sheetSpells?.save(saved.id) ?? of(true))
.pipe(map(spellsSaved => ({ saved, spellsSaved }))))
).subscribe({
next: ({ saved, spellsSaved }) => {
if (!spellsSaved) {
// La fiche est enregistrée, pas ses sorts : on reste sur son édition pour réessayer.
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'characters', saved.id, 'edit']);
}
return;
}
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'playthroughs', this.playthroughId, 'characters', saved.id]);
} else {
@@ -18,6 +18,8 @@
</div>
<app-persona-view [persona]="character" [templateFields]="templateFields"></app-persona-view>
<app-sheet-spells mode="view" sheet="character" [campaignId]="campaignId" [ownerId]="characterId"></app-sheet-spells>
</div>
@if (characterId && campaignId) {
@@ -16,9 +16,11 @@ import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-dr
* Vue lecture seule "WorldAnvil" d'une fiche PJ.
* Route : /campaigns/:campaignId/playthroughs/:playthroughId/characters/:characterId
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-character-view',
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent, AiChatDrawerComponent],
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent, SheetSpellsComponent, AiChatDrawerComponent],
templateUrl: './character-view.component.html',
styleUrls: ['./character-view.component.scss']
})
@@ -88,6 +88,9 @@
</app-dynamic-fields-form>
</div>
<!-- Sorts connus, choisis dans le catalogue du système (rien ne s'affiche s'il n'y en a pas). -->
<app-sheet-spells mode="edit" sheet="enemy" [campaignId]="campaignId" [ownerId]="enemyId"></app-sheet-spells>
<div class="actions">
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ViewChild } from '@angular/core';
import { map, of, switchMap } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
@@ -18,9 +19,11 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
* NpcEditComponent : formulaire dynamique piloté par le template ENNEMI du
* GameSystem associé à la campagne, + champs universels niveau/dossier.
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-enemy-edit',
imports: [FormsModule, LucideAngularModule, TranslatePipe, DynamicFieldsFormComponent, SingleImagePickerComponent],
imports: [FormsModule, LucideAngularModule, TranslatePipe, DynamicFieldsFormComponent, SingleImagePickerComponent, SheetSpellsComponent],
templateUrl: './enemy-edit.component.html',
styleUrls: ['./enemy-edit.component.scss']
})
@@ -46,6 +49,9 @@ export class EnemyEditComponent implements OnInit {
templateFields: TemplateField[] = [];
private order = 0;
/** Sorts connus de la fiche : enregistrés après elle (cf. submit). */
@ViewChild(SheetSpellsComponent) private sheetSpells?: SheetSpellsComponent;
constructor(
private route: ActivatedRoute,
private router: Router,
@@ -130,8 +136,19 @@ export class EnemyEditComponent implements OnInit {
const req = this.enemyId
? this.service.update(this.enemyId, { ...payload, id: this.enemyId, order: this.order })
: this.service.create(payload);
req.subscribe({
next: (saved) => {
// Les sorts connus partent une fois la fiche enregistrée : elle a alors un identifiant.
req.pipe(
switchMap(saved => (this.sheetSpells?.save(saved.id) ?? of(true))
.pipe(map(spellsSaved => ({ saved, spellsSaved }))))
).subscribe({
next: ({ saved, spellsSaved }) => {
if (!spellsSaved) {
// La fiche est enregistrée, pas ses sorts : on reste sur son édition pour réessayer.
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'enemies', saved.id, 'edit']);
}
return;
}
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'enemies', saved.id]);
} else {
@@ -13,6 +13,8 @@
<app-persona-view [persona]="enemy" [templateFields]="templateFields" [subtitle]="subtitle"></app-persona-view>
<app-sheet-spells mode="view" sheet="enemy" [campaignId]="campaignId" [ownerId]="enemyId"></app-sheet-spells>
@if (hasFoundryStats) {
<section class="foundry-stats">
<h2>{{ 'enemyView.foundryStatsTitle' | translate }}</h2>
@@ -16,9 +16,11 @@ import { PersonaViewComponent } from '../../../shared/persona-view/persona-view.
* Vue lecture seule d'une fiche d'ennemi (même rendu « persona » que les PNJ).
* Route : /campaigns/:campaignId/enemies/:enemyId
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-enemy-view',
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent],
imports: [LucideAngularModule, TranslatePipe, PersonaViewComponent, SheetSpellsComponent],
templateUrl: './enemy-view.component.html',
styleUrls: ['./enemy-view.component.scss']
})
+103
View File
@@ -0,0 +1,103 @@
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import {
ARC_BLOCKS, ARC_BLOCK_LABELS, BlockState, CHAPTER_BLOCKS, CHAPTER_BLOCK_LABELS, QUEST_BLOCKS,
QUEST_BLOCK_LABELS, addableOf, choicesOf, filledOf, visibleOf
} from './entity-blocks';
import { SCENE_BLOCKS, SCENE_BLOCK_LABELS } from './scene/scene-blocks';
/**
* Fiches en « noyau + rubriques » : ce qui s'affiche, ce qui reste proposable, et la règle
* d'or pour les campagnes déjà écrites — rien de rempli n'est jamais caché.
*/
const FRAGMENTS_DIR = join(process.cwd(), 'src/assets/i18n/fragments');
function i18n(lang: 'fr' | 'en'): Record<string, Record<string, unknown>> {
const all: Record<string, Record<string, unknown>> = {};
for (const file of readdirSync(FRAGMENTS_DIR).filter(f => f.endsWith(`.${lang}.json`))) {
Object.assign(all, JSON.parse(readFileSync(join(FRAGMENTS_DIR, file), 'utf-8')));
}
return all;
}
describe('entity blocks', () => {
const all = ['a', 'b', 'c', 'd'] as const;
it('shows the default, shown and filled blocks, in display order', () => {
expect(visibleOf(all, ['c'], ['a'], ['d'])).toEqual(['a', 'c', 'd']);
expect(visibleOf(all, [], [], [])).toEqual([]);
});
it('never hides a filled block', () => {
for (const block of all) {
expect(visibleOf(all, [], [], [block])).toContain(block);
}
});
it('shows the block a link points to', () => {
expect(visibleOf(all, [], [], [], 'b')).toEqual(['b']);
expect(visibleOf(all, [], [], [], null)).toEqual([]);
});
it('offers what is neither visible nor irrelevant on this sheet', () => {
expect(addableOf(all, ['a'], ['d'])).toEqual(['b', 'c']);
expect(addableOf(all, all)).toEqual([]);
});
it('lists the filled blocks and turns blocks into labelled choices', () => {
expect(filledOf({ a: true, b: false, c: true })).toEqual(['a', 'c']);
expect(choicesOf(['a'], { a: 'x.title' })).toEqual([{ id: 'a', labelKey: 'x.title' }]);
});
});
describe('block state', () => {
it('keeps a block that had content when the sheet opened, even once emptied', () => {
const state = new BlockState<'notes' | 'icon'>();
state.reset(['notes']);
expect(visibleOf(['notes', 'icon'], [], state.shownBlocks, [])).toEqual(['notes']);
expect(state.isAdded('notes')).toBe(false);
});
it('shows and opens a block the author asked for', () => {
const state = new BlockState<'notes' | 'icon'>();
state.reset([]);
state.add('icon');
expect(state.shownBlocks).toEqual(['icon']);
expect(state.isAdded('icon')).toBe(true);
});
it('forgets everything when another sheet is opened', () => {
const state = new BlockState<'notes' | 'icon'>();
state.add('icon');
state.reset(['notes']);
expect(state.shownBlocks).toEqual(['notes']);
expect(state.isAdded('icon')).toBe(false);
});
});
describe('block labels', () => {
const sheets: [string, readonly string[], Record<string, string>][] = [
['arc', ARC_BLOCKS, ARC_BLOCK_LABELS],
['chapter', CHAPTER_BLOCKS, CHAPTER_BLOCK_LABELS],
['quest', QUEST_BLOCKS, QUEST_BLOCK_LABELS],
['scene', SCENE_BLOCKS, SCENE_BLOCK_LABELS]
];
for (const lang of ['fr', 'en'] as const) {
it.each(sheets)(`${lang}: every %s block has a title`, (_sheet, blocks, labels) => {
const texts = i18n(lang);
for (const block of blocks) {
const [ns, key] = labels[block].split('.');
const value = texts[ns]?.[key];
expect(typeof value === 'string' && value.trim().length > 0, `${labels[block]} (${lang})`).toBe(true);
}
});
it(`${lang}: the adder has its texts`, () => {
const texts = i18n(lang)['entityBlocks'];
expect(typeof texts?.['title']).toBe('string');
expect(typeof texts?.['hint']).toBe('string');
});
}
});
+117
View File
@@ -0,0 +1,117 @@
/**
* Fiches de campagne en « noyau + rubriques » (logique pure, testée sans Angular).
*
* Le NOYAU d'une fiche est toujours affiché : ce sont les champs que l'appli comprend
* (relecture, méthodes guidées, bilan de préparation). Les RUBRIQUES sont optionnelles :
* on ne montre que celles que la fiche appelle d'office, celles qui ont déjà du contenu et
* celles que l'auteur a demandées. Les autres attendent dans « Ajouter une rubrique ».
*
* Règle d'or, pour les campagnes déjà écrites : rien de rempli n'est jamais caché. Aucune
* donnée ne change — les champs restent ceux de la fiche, seul l'affichage est allégé.
*
* Les rubriques d'une scène dépendent de son type : voir `scene/scene-blocks.ts`.
*/
/** Rubrique proposée dans « Ajouter une rubrique » : son identifiant et la clé i18n de son titre. */
export interface BlockChoice {
id: string;
labelKey: string;
}
/**
* Rubriques à afficher, dans l'ordre de `all` : celles proposées d'office, celles déjà
* montrées pendant cette édition, celles qui ont du contenu, et celle visée par le lien
* d'arrivée (`?focus=`).
*/
export function visibleOf<B extends string>(all: readonly B[], defaults: Iterable<B>, shown: Iterable<B>,
filled: Iterable<B>, focused?: B | null): B[] {
const wanted = new Set<B>([...defaults, ...shown, ...filled]);
if (focused) wanted.add(focused);
return all.filter(b => wanted.has(b));
}
/** Rubriques encore proposables : ni affichées, ni sans objet sur cette fiche. */
export function addableOf<B extends string>(all: readonly B[], visible: readonly B[],
unavailable: Iterable<B> = []): B[] {
const out = new Set<B>(unavailable);
return all.filter(b => !visible.includes(b) && !out.has(b));
}
/** Les rubriques dont l'état « rempli » est vrai. */
export function filledOf<B extends string>(state: Record<B, boolean>): B[] {
return (Object.keys(state) as B[]).filter(b => state[b]);
}
export function choicesOf<B extends string>(blocks: readonly B[], labels: Record<B, string>): BlockChoice[] {
return blocks.map(id => ({ id, labelKey: labels[id] }));
}
/**
* Ce que l'auteur a vu et demandé pendant l'édition d'une fiche : une rubrique affichée au
* chargement (elle avait du contenu) ou ajoutée à la main reste là, même une fois vidée —
* elle ne disparaît pas sous le curseur.
*/
export class BlockState<B extends string> {
private readonly shown = new Set<B>();
private readonly added = new Set<B>();
/** À l'ouverture de la fiche : repart des rubriques qui ont du contenu. */
reset(filled: Iterable<B>): void {
this.shown.clear();
this.added.clear();
for (const b of filled) this.shown.add(b);
}
/** L'auteur demande une rubrique : elle s'affiche, dépliée. */
add(block: B): void {
this.shown.add(block);
this.added.add(block);
}
isAdded(block: B): boolean {
return this.added.has(block);
}
get shownBlocks(): B[] {
return [...this.shown];
}
}
// ───────────────────────────── Arc ─────────────────────────────
// Noyau : nom, synopsis, structure, thèmes et enjeux, histoire cachée et accroches
// (la relecture lit les enjeux et les accroches).
export type ArcBlock = 'gmNotes' | 'rewardsResolution' | 'illustrations' | 'lore' | 'icon';
export const ARC_BLOCKS: ArcBlock[] = ['gmNotes', 'rewardsResolution', 'illustrations', 'lore', 'icon'];
export const ARC_BLOCK_LABELS: Record<ArcBlock, string> = {
gmNotes: 'arcEdit.gmNotesSectionTitle',
rewardsResolution: 'arcEdit.rewardsResolutionSectionTitle',
illustrations: 'arcEdit.illustrationsLabel',
lore: 'arcEdit.relatedPagesLabel',
icon: 'arcEdit.iconLabel'
};
// ───────────────────────────── Chapitre ─────────────────────────────
// Noyau : nom, synopsis, objectifs et enjeux (la relecture lit les enjeux).
export type ChapterBlock = 'gmNotes' | 'illustrations' | 'lore' | 'icon';
export const CHAPTER_BLOCKS: ChapterBlock[] = ['gmNotes', 'illustrations', 'lore', 'icon'];
export const CHAPTER_BLOCK_LABELS: Record<ChapterBlock, string> = {
gmNotes: 'chapterEdit.gmNotesSectionTitle',
illustrations: 'chapterEdit.illustrations',
lore: 'chapterEdit.relatedPages',
icon: 'chapterEdit.icon'
};
// ───────────────────────────── Quête ─────────────────────────────
// Noyau : nom, synopsis, objectifs et enjeux, conditions de déblocage (le propre d'une quête).
export type QuestBlock = 'nodes' | 'gmNotes' | 'illustrations' | 'lore' | 'icon';
export const QUEST_BLOCKS: QuestBlock[] = ['nodes', 'gmNotes', 'illustrations', 'lore', 'icon'];
export const QUEST_BLOCK_LABELS: Record<QuestBlock, string> = {
nodes: 'questEdit.nodesSectionTitle',
gmNotes: 'questEdit.gmNotesSectionTitle',
illustrations: 'questEdit.illustrationsLabel',
lore: 'questEdit.relatedPagesLabel',
icon: 'questEdit.iconLabel'
};
+51 -1
View File
@@ -1,4 +1,7 @@
import { flatContainer } from './flat-structure';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { DEFAULT_ARC_NAMES, flatContainer, implicitArc } from './flat-structure';
import { Arc, Chapter } from '../services/campaign.model';
describe('flatContainer (mode plat)', () => {
@@ -27,3 +30,50 @@ describe('flatContainer (mode plat)', () => {
expect(flatContainer([arc(), arc({ id: 'sys', type: 'SYSTEM' })], { a1: [chapter()] })).not.toBeNull();
});
});
describe('implicitArc (arc créé d\'office, non montré comme un arc)', () => {
const arc = (extra: Partial<Arc> = {}): Arc => ({ id: 'a1', name: 'Arc principal', campaignId: 'c', type: 'LINEAR', ...extra } as Arc);
it('recognises the lone, empty arc that still has its default name, in either language', () => {
expect(implicitArc([arc()])?.id).toBe('a1');
expect(implicitArc([arc({ name: 'Main arc' })])?.id).toBe('a1');
expect(implicitArc([arc(), arc({ id: 'sys', type: 'SYSTEM' })])?.id).toBe('a1');
});
it('keeps an arc the author named, wrote in, or made a quest arc', () => {
expect(implicitArc([arc({ name: 'La saison des cendres' })])).toBeNull();
expect(implicitArc([arc({ stakes: 'La vallée brûle' })])).toBeNull();
expect(implicitArc([arc({ illustrationImageIds: ['img'] })])).toBeNull();
expect(implicitArc([arc({ type: 'HUB' })])).toBeNull();
});
it('never applies once the campaign has several arcs, or none', () => {
expect(implicitArc([arc(), arc({ id: 'a2' })])).toBeNull();
expect(implicitArc([])).toBeNull();
});
it('agrees with the core on the default arc names', () => {
const java = readFileSync(join(process.cwd(),
'../core/src/main/java/com/loremind/application/campaigncontext/ImplicitArc.java'), 'utf-8');
const names = /DEFAULT_NAMES = List\.of\(([^)]*)\)/.exec(java)?.[1] ?? '';
expect([...names.matchAll(/"([^"]+)"/g)].map(m => m[1])).toEqual(DEFAULT_ARC_NAMES);
});
it('has the wording that does not name the arc, for the only rule that would', () => {
const dir = join(process.cwd(), 'src/assets/i18n/fragments');
for (const lang of ['fr', 'en']) {
const rule = JSON.parse(readFileSync(join(dir, `writing-review.${lang}.json`), 'utf-8'))
.writingReview.rules['WRITE-009-SINGLE-ENDING'];
expect(rule.observationNoArc, lang).toContain('{{entity}}');
expect(rule.observationNoArc, lang).not.toContain('{{arc}}');
}
});
it('knows the default arc name of every language', () => {
const dir = join(process.cwd(), 'src/assets/i18n/fragments');
for (const lang of ['fr', 'en']) {
const name = JSON.parse(readFileSync(join(dir, `campaigns-top.${lang}.json`), 'utf-8')).campaignDetail.defaultArcName;
expect(DEFAULT_ARC_NAMES, lang).toContain(name);
}
});
});
+21
View File
@@ -19,6 +19,27 @@ export function flatContainer(arcs: Arc[], chaptersByArc: Record<string, Chapter
return isBareArc(arc) && isBareChapter(chapter) ? { arc, chapter } : null;
}
/** Noms donnés à l'arc créé d'office (`campaignDetail.defaultArcName`, dans chaque langue). */
export const DEFAULT_ARC_NAMES = ['Arc principal', 'Main arc'];
/**
* Arc « implicite » : le seul arc de la campagne, linéaire, vide de texte et encore à son nom
* d'office. L'auteur ne l'a pas créé — il vient d'une scène ajoutée rapidement ou d'une
* méthode guidée — donc on ne le lui présente pas comme un arc : la campagne montre
* directement ses aventures (ses chapitres). Il redevient un arc ordinaire dès qu'on le
* renomme, qu'on y écrit quelque chose ou qu'on crée un second arc.
*
* Plus strict que le mode plat sur le nom : un arc que l'auteur a nommé lui-même reste
* affiché sous ce nom, même s'il est seul et vide.
*/
export function implicitArc(arcs: Arc[]): Arc | null {
const visible = arcs.filter(a => a.type !== 'SYSTEM');
if (visible.length !== 1) return null;
const arc = visible[0];
if ((arc.type ?? 'LINEAR') !== 'LINEAR') return null;
return isBareArc(arc) && DEFAULT_ARC_NAMES.includes((arc.name ?? '').trim()) ? arc : null;
}
/** Aucun contenu d'écriture dans l'arc (le nom ne compte pas : « Arc principal » est créé d'office). */
export function isBareArc(arc: Arc): boolean {
return [arc.description, arc.themes, arc.stakes, arc.rewards, arc.resolution, arc.gmNotes, arc.hiddenTruth, arc.hooks]
@@ -10,15 +10,38 @@
</h1>
<p class="chooser-intro">{{ 'guided.chooserIntro' | translate }}</p>
<ul class="method-list">
<!-- Aide au choix : le genre de séance désigne la méthode. -->
<fieldset class="intents">
<legend>{{ 'guided.intents.title' | translate }}</legend>
<div class="intent-row">
@for (i of intents; track i.id) {
<button type="button" class="intent-chip" [class.selected]="intent?.id === i.id"
[attr.aria-pressed]="intent?.id === i.id" (click)="choose(i)">
{{ ('guided.intents.' + i.id + '.label') | translate }}
</button>
}
</div>
</fieldset>
<ul class="method-list" aria-live="polite">
@for (method of methods; track method.id) {
<li class="method-card">
<li class="method-card" [class.method-card--advised]="isAdvised(method)">
<div class="method-text">
<h2>{{ ('guided.' + method.i18nKey + '.name') | translate }}</h2>
<h2>
{{ ('guided.' + method.i18nKey + '.name') | translate }}
@if (isAdvised(method)) {
<span class="method-badge">{{ 'guided.intents.advised' | translate }}</span>
}
</h2>
@if (isAdvised(method) && intent) {
<p class="method-advice">{{ ('guided.intents.' + intent.id + '.why') | translate }}</p>
}
<p>{{ ('guided.' + method.i18nKey + '.tagline') | translate }}</p>
<p class="method-fits">{{ ('guided.' + method.i18nKey + '.fits') | translate }}</p>
<span class="method-meta">{{ 'guided.chooserScenes' | translate:{ count: sceneCount(method) } }}</span>
</div>
<a class="btn-primary method-start" [routerLink]="['/campaigns', campaignId, 'guided', method.id]">
<a class="btn-primary method-start" [routerLink]="['/campaigns', campaignId, 'guided', method.id]"
queryParamsHandling="preserve">
{{ 'guided.chooserStart' | translate }}
<lucide-icon [img]="ArrowRight" [size]="14"></lucide-icon>
</a>
@@ -83,3 +83,56 @@
@media (max-width: 768px) {
.chooser { padding: 1rem; }
}
// --- Aide au choix : genre de séance ---
.intents {
margin: 0 0 1.5rem;
padding: 0;
border: none;
legend {
padding: 0;
margin-bottom: 0.6rem;
color: #f3f4f6;
font-size: 0.95rem;
font-weight: 600;
}
}
.intent-row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.intent-chip {
padding: 0.5rem 0.9rem;
border-radius: 999px;
border: 1px solid #374151;
background: #111827;
color: #d1d5db;
font-size: 0.86rem;
cursor: pointer;
text-align: left;
&:hover { border-color: #6b7280; }
&.selected { border-color: #fbbf24; background: rgba(251, 191, 36, 0.12); color: #fde68a; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
.method-card--advised { border-color: #92400e; }
.method-badge {
margin-left: 0.5rem;
padding: 0.1rem 0.5rem;
border-radius: 999px;
background: rgba(251, 191, 36, 0.15);
color: #fbbf24;
font-size: 0.7rem;
font-weight: 600;
vertical-align: middle;
}
.method-text .method-advice { color: #fde68a; }
.method-text .method-fits { color: #9ca3af; font-size: 0.82rem; }
@@ -4,10 +4,13 @@ import { LucideAngularModule, ArrowLeft, ArrowRight, Sparkles } from 'lucide-ang
import { TranslatePipe } from '@ngx-translate/core';
import { GUIDED_METHODS } from '../guided-methods';
import { GuidedMethod } from '../guided-method.model';
import { GUIDED_INTENTS, GuidedIntent } from '../guided-intents';
/**
* Choix d'une méthode guidée (Mentor d'écriture) : une carte par méthode, avec son
* accroche et le nombre de scènes qu'elle crée. Route : /campaigns/:campaignId/guided
* Choix d'une méthode guidée (Mentor d'écriture). Le MJ dit d'abord quel genre de séance il
* veut écrire : la méthode qui y répond passe en tête, avec la raison de ce conseil. Chaque
* carte dit à qui la méthode convient et le nombre de scènes qu'elle crée.
* Route : /campaigns/:campaignId/guided
*/
@Component({
selector: 'app-guided-chooser',
@@ -19,9 +22,26 @@ export class GuidedChooserComponent {
readonly ArrowLeft = ArrowLeft;
readonly ArrowRight = ArrowRight;
readonly Sparkles = Sparkles;
readonly methods = GUIDED_METHODS;
readonly intents = GUIDED_INTENTS;
readonly campaignId = inject(ActivatedRoute).snapshot.paramMap.get('campaignId') ?? '';
/** Genre de séance choisi (aucun : les méthodes sont listées dans leur ordre naturel). */
intent: GuidedIntent | null = null;
/** Méthodes dans l'ordre d'affichage : la méthode conseillée d'abord. */
methods: GuidedMethod[] = GUIDED_METHODS;
choose(intent: GuidedIntent): void {
this.intent = this.intent?.id === intent.id ? null : intent;
const advised = this.intent?.method;
this.methods = advised
? [...GUIDED_METHODS].sort((a, b) => Number(b.id === advised) - Number(a.id === advised))
: GUIDED_METHODS;
}
isAdvised(method: GuidedMethod): boolean {
return method.id === this.intent?.method;
}
/** Nombre de scènes produites (brouillon vide : la structure ne dépend pas des réponses). */
sceneCount(method: GuidedMethod): number {
return method.toDraft({}).scenes.length;
@@ -0,0 +1,22 @@
/**
* Aide au choix d'une méthode guidée : le MJ débutant ne sait pas ce qu'est un « donjon en
* 5 salles », mais il sait quel genre de séance il veut. Chaque intention désigne la
* méthode qui lui répond ; ses textes sont sous `guided.intents.<id>.label|why`.
*/
export interface GuidedIntent {
id: string;
/** Identifiant de la méthode conseillée (`GuidedMethod.id`). */
method: string;
}
export const GUIDED_INTENTS: GuidedIntent[] = [
{ id: 'first', method: 'five-room' },
{ id: 'mystery', method: 'investigation' },
{ id: 'threat', method: 'villain-plan' },
// Dans le doute : la méthode la plus simple, qui marche avec n'importe quel lieu.
{ id: 'unsure', method: 'five-room' }
];
export function findGuidedIntent(id: string | null): GuidedIntent | undefined {
return GUIDED_INTENTS.find(i => i.id === id);
}
@@ -1,5 +1,5 @@
import { GuidedChapterSpec, GuidedClockSpec, GuidedSceneSpec } from '../../services/guided-skeleton.model';
import { LinkType } from '../../services/campaign.model';
import { LinkType, SceneType } from '../../services/campaign.model';
/**
* Définition d'une méthode guidée (Mentor d'écriture, phases M3/M5). L'assistant
@@ -13,6 +13,12 @@ import { LinkType } from '../../services/campaign.model';
* - `fields.<fieldKey>.label|placeholder` : chaque champ (`fieldKey` peut contenir des points) ;
* - `options.<fieldKey>.<option>` : libellés des choix ;
* - `defaults.<fieldKey>` : valeur proposée d'office (ex. nom d'une salle).
*
* Rôles : chaque scène produite porte un `role`, égal à l'identifiant de l'étape qui la
* décrit (`room3`, `conclusion`…). Le chapitre garde la méthode et les scènes leur rôle : la
* méthode reste visible après la création (vue du chapitre, écrans de scène, relecture). Le
* titre et le « pourquoi » d'un rôle sont donc ceux de son étape (`steps.<role>.*`), son nom
* par défaut `defaults.<role>.name`.
*/
/** Réponses du MJ, par clé de champ. */
@@ -35,6 +41,11 @@ export interface GuidedStep {
/** `placement` : où ranger l'aventure ; `form` : questions ; `review` : récapitulatif. */
kind: 'placement' | 'form' | 'review';
fields?: GuidedField[];
/**
* Étape de placement qui présente aussi la méthode : elle reste affichée même quand le
* placement est déjà décidé par le contexte (sinon elle est sautée).
*/
intro?: boolean;
}
/** Ce que la méthode produit à partir des réponses (le placement est ajouté par l'assistant). */
@@ -69,6 +80,21 @@ export interface GuidedMethod {
toDraft(answers: GuidedAnswers): GuidedDraft;
}
/** Un rôle de la méthode : une étape qui produit une scène. */
export interface GuidedRole {
/** Identifiant du rôle = identifiant de l'étape (`room3`, `conclusion`…). */
id: string;
/** Type de scène proposé quand le MJ n'a encore rien choisi. */
type: SceneType;
}
/** Rôles de la méthode, dans l'ordre (la structure ne dépend pas des réponses). */
export function guidedRoles(method: GuidedMethod): GuidedRole[] {
return method.toDraft({}).scenes
.filter(s => !!s.role)
.map(s => ({ id: s.role as string, type: s.type }));
}
/** Valeur nettoyée d'une réponse (chaîne vide → null). */
export function answer(answers: GuidedAnswers, key: string): string | null {
const value = answers[key]?.trim();
@@ -0,0 +1,115 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { Arc, Chapter, Scene } from '../../services/campaign.model';
import { GUIDED_INTENTS, findGuidedIntent } from './guided-intents';
import { GUIDED_METHODS, findGuidedMethod } from './guided-methods';
import { PlacementTree, placementContext } from './guided-placement';
/**
* Où ranger l'aventure quand le contexte le dit déjà (arc d'origine, campagne encore
* simple), et aide au choix de la méthode (genre de séance → méthode conseillée).
*/
const FRAGMENTS_DIR = join(process.cwd(), 'src/assets/i18n/fragments');
function arc(id: string, type: Arc['type'] = 'LINEAR', extra: Partial<Arc> = {}): Arc {
return { id, name: id, campaignId: 'camp', type, ...extra } as Arc;
}
function chapter(id: string, arcId: string, extra: Partial<Chapter> = {}): Chapter {
return { id, name: id, arcId, ...extra };
}
function tree(arcs: Arc[], chapters: Chapter[] = [], scenes: Scene[] = []): PlacementTree {
const chaptersByArc: Record<string, Chapter[]> = {};
for (const c of chapters) {
chaptersByArc[c.arcId] = [...(chaptersByArc[c.arcId] ?? []), c];
}
const scenesByChapter: Record<string, Scene[]> = {};
for (const s of scenes) {
scenesByChapter[s.chapterId] = [...(scenesByChapter[s.chapterId] ?? []), s];
}
return { arcs, chaptersByArc, scenesByChapter };
}
describe('placement decided by the context', () => {
it('puts the adventure in the linear arc the wizard was opened from', () => {
const t = tree([arc('a1'), arc('a2')], [chapter('c1', 'a1'), chapter('c2', 'a2')]);
expect(placementContext(t, 'a2')).toEqual({ mode: 'existing', arc: t.arcs[1], simple: false });
});
it('makes it a quest when opened from a quest arc', () => {
const t = tree([arc('a1'), arc('hub', 'HUB')]);
expect(placementContext(t, 'hub')).toEqual({ mode: 'quest', arc: t.arcs[1], simple: false });
});
it('creates a first arc silently in a campaign that has none (the technical arc does not count)', () => {
expect(placementContext(tree([]), null)).toEqual({ mode: 'new', simple: true });
expect(placementContext(tree([arc('sys', 'SYSTEM')]), null)).toEqual({ mode: 'new', simple: true });
});
it('fills the empty chapter of a flat campaign', () => {
const t = tree([arc('a1')], [chapter('c1', 'a1')]);
expect(placementContext(t, null)).toEqual({
mode: 'existing', arc: t.arcs[0], simple: true, emptyChapter: t.chaptersByArc['a1'][0]
});
});
it('adds a chapter next to the scenes already written in a flat campaign', () => {
const t = tree([arc('a1')], [chapter('c1', 'a1')], [{ id: 's1', name: 'Scène', chapterId: 'c1' }]);
const context = placementContext(t, null);
expect(context?.mode).toBe('existing');
expect(context?.simple).toBe(true);
expect(context?.emptyChapter).toBeUndefined();
});
it('adds to the arc created by default without asking, even when opened from it', () => {
const lone = arc('a1', 'LINEAR', { name: 'Arc principal' });
const t = tree([lone], [chapter('c1', 'a1', { narrativeStakes: 'Le village brûle' }), chapter('c2', 'a1')]);
expect(placementContext(t, null)).toEqual({ mode: 'existing', arc: lone, simple: true });
expect(placementContext(t, 'a1')).toEqual({ mode: 'existing', arc: lone, simple: true });
});
it('asks the question in a campaign that is already organised', () => {
const several = tree([arc('a1'), arc('a2')], [chapter('c1', 'a1')]);
const written = tree([arc('a1')], [chapter('c1', 'a1', { narrativeStakes: 'Le village brûle' })]);
const hubOnly = tree([arc('hub', 'HUB')]);
expect(placementContext(several, null)).toBeNull();
expect(placementContext(written, null)).toBeNull();
expect(placementContext(hubOnly, null)).toBeNull();
});
it('ignores an unknown or technical arc given as context', () => {
const t = tree([arc('a1'), arc('a2'), arc('sys', 'SYSTEM')], [chapter('c1', 'a1')]);
expect(placementContext(t, 'ailleurs')).toBeNull();
expect(placementContext(t, 'sys')).toBeNull();
});
});
describe('guided intents', () => {
it('points each kind of session to an existing method, and reaches every method', () => {
for (const intent of GUIDED_INTENTS) {
expect(findGuidedMethod(intent.method), intent.id).toBeDefined();
}
expect(new Set(GUIDED_INTENTS.map(i => i.method))).toEqual(new Set(GUIDED_METHODS.map(m => m.id)));
expect(new Set(GUIDED_INTENTS.map(i => i.id)).size).toBe(GUIDED_INTENTS.length);
expect(findGuidedIntent('mystery')?.method).toBe('investigation');
expect(findGuidedIntent(null)).toBeUndefined();
});
for (const lang of ['fr', 'en'] as const) {
it(`${lang}: every intent and every method has its chooser texts`, () => {
const guided = JSON.parse(readFileSync(join(FRAGMENTS_DIR, `guided.${lang}.json`), 'utf-8')).guided;
const filled = (value: unknown) => typeof value === 'string' && value.trim().length > 0;
expect(filled(guided.intents.title)).toBe(true);
expect(filled(guided.intents.advised)).toBe(true);
for (const intent of GUIDED_INTENTS) {
expect(filled(guided.intents[intent.id]?.label), `${intent.id}.label (${lang})`).toBe(true);
expect(filled(guided.intents[intent.id]?.why), `${intent.id}.why (${lang})`).toBe(true);
}
for (const method of GUIDED_METHODS) {
expect(filled(guided[method.i18nKey]?.fits), `${method.i18nKey}.fits (${lang})`).toBe(true);
}
});
}
});
@@ -0,0 +1,48 @@
import { Arc, Chapter, Scene } from '../../services/campaign.model';
import { flatContainer, implicitArc } from '../flat-structure';
/**
* Où ranger l'aventure d'une méthode guidée quand le contexte le dit déjà (logique pure,
* testée sans Angular). Trois cas, du plus explicite au plus implicite :
* - l'assistant est ouvert depuis un arc (`?arc=`) : arc linéaire → chapitre de cet arc ;
* arc de quêtes (HUB) → quête de cet arc ;
* - la campagne n'a aucun arc : un premier arc est créé d'office ;
* - la campagne est « à plat » (un seul arc d'un seul chapitre, tous deux vides de texte) :
* l'aventure va dans cet arc, et remplit son chapitre s'il n'a encore aucune scène ;
* - la campagne n'a que son arc créé d'office (`implicitArc`) : l'aventure s'y ajoute.
* Dans les trois derniers cas le MJ n'a jamais vu la notion d'arc : on ne la lui impose pas.
*/
export type PlacementMode = 'existing' | 'quest' | 'new';
export interface PlacementContext {
mode: PlacementMode;
/** Arc visé (`existing` / `quest`) ; absent pour `new`. */
arc?: Arc;
/** Campagne encore simple : on ne parle pas d'arc au MJ. */
simple: boolean;
/** Chapitre vide de l'arc, à remplir plutôt qu'à doubler (campagne « à plat »). */
emptyChapter?: Chapter;
}
/** Ce qu'il faut connaître de la campagne (sous-ensemble de l'arbre agrégé). */
export interface PlacementTree {
arcs: Arc[];
chaptersByArc: Record<string, Chapter[]>;
scenesByChapter: Record<string, Scene[]>;
}
export function placementContext(tree: PlacementTree, contextArcId: string | null): PlacementContext | null {
const lone = implicitArc(tree.arcs);
// Ouvert depuis l'arc créé d'office : c'est le cas « campagne simple », traité plus bas.
const arc = contextArcId && contextArcId !== lone?.id ? tree.arcs.find(a => a.id === contextArcId) : undefined;
if (arc && (arc.type ?? 'LINEAR') === 'LINEAR') return { mode: 'existing', arc, simple: false };
if (arc && arc.type === 'HUB') return { mode: 'quest', arc, simple: false };
if (tree.arcs.every(a => a.type === 'SYSTEM')) return { mode: 'new', simple: true };
const flat = flatContainer(tree.arcs, tree.chaptersByArc);
if (!flat) return lone ? { mode: 'existing', arc: lone, simple: true } : null;
const hasScenes = (tree.scenesByChapter[flat.chapter.id ?? ''] ?? []).length > 0;
return { mode: 'existing', arc: flat.arc, simple: true, emptyChapter: hasScenes ? undefined : flat.chapter };
}
@@ -0,0 +1,94 @@
import { Component, Input, OnChanges } from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, Compass } from 'lucide-angular';
import { Chapter, Scene } from '../../services/campaign.model';
import { GuidedMethod, GuidedRole } from './guided-method.model';
import { methodOf, roleOf } from './guided-roles';
/**
* Rappel, sur les écrans d'une scène, du rôle qu'elle tient dans la méthode guidée de son
* chapitre : ce que ce temps de l'aventure doit accomplir, avec un exemple. N'affiche rien
* pour une scène sans rôle (ou un chapitre sans méthode).
*/
@Component({
selector: 'app-guided-role-hint',
imports: [RouterLink, TranslatePipe, LucideAngularModule],
template: `
@if (method && role) {
<aside class="hint">
<p class="hint-head">
<lucide-icon [img]="Compass" [size]="14"></lucide-icon>
<span class="hint-method">{{ k('name') | translate }}</span>
<strong>{{ k('steps.' + role.id + '.title') | translate }}</strong>
</p>
<p class="hint-why">{{ k('steps.' + role.id + '.why') | translate }}</p>
<details>
<summary>{{ 'guided.exampleLabel' | translate }}</summary>
<p>{{ k('steps.' + role.id + '.example') | translate }}</p>
</details>
@if (chapterLink) {
<a class="hint-link" [routerLink]="chapterLink">{{ 'guided.structure.seeChapter' | translate }}</a>
}
</aside>
}
`,
styles: [`
:host { display: block; }
.hint {
margin: 0 0 1.25rem;
padding: 0.75rem 0.95rem;
border-radius: 8px;
background: rgba(251, 191, 36, 0.06);
border: 1px solid rgba(251, 191, 36, 0.25);
border-left: 3px solid #fbbf24;
}
p { margin: 0; line-height: 1.5; }
.hint-head {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.4rem;
font-size: 0.86rem;
color: #f3f4f6;
}
.hint-head lucide-icon { color: #fbbf24; }
.hint-method { color: #fbbf24; font-size: 0.74rem; text-transform: uppercase; letter-spacing: 0.06em; }
.hint-why { margin-top: 0.3rem; font-size: 0.84rem; color: #d1d5db; }
details { margin-top: 0.4rem; font-size: 0.82rem; color: #9ca3af; }
summary { cursor: pointer; color: #a5b4fc; }
summary:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
details p { margin-top: 0.3rem; font-style: italic; }
.hint-link {
display: inline-block;
margin-top: 0.45rem;
font-size: 0.78rem;
color: #a5b4fc;
text-decoration: none;
}
.hint-link:hover { color: #c7d2fe; text-decoration: underline; }
.hint-link:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
`]
})
export class GuidedRoleHintComponent implements OnChanges {
readonly Compass = Compass;
/** Chapitre de la scène (il porte la méthode). */
@Input() chapter: Chapter | null | undefined = null;
@Input() scene: Scene | null | undefined = null;
/** Lien vers la vue du chapitre, où toute la structure est visible (omis : pas de lien). */
@Input() chapterLink: string[] | null = null;
method: GuidedMethod | null = null;
role: GuidedRole | null = null;
ngOnChanges(): void {
this.method = methodOf(this.chapter);
this.role = roleOf(this.method, this.scene);
}
k(path: string): string {
return `guided.${this.method?.i18nKey}.${path}`;
}
}
@@ -0,0 +1,99 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { Scene } from '../../services/campaign.model';
import { guidedRoles } from './guided-method.model';
import { GUIDED_METHODS } from './guided-methods';
import { freeScenes, methodOf, roleOf, roleRows } from './guided-roles';
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
import { INVESTIGATION_METHOD } from './methods/investigation.method';
/**
* La méthode guidée après la création du chapitre : rôles de chaque méthode, scène qui
* tient chaque rôle, et accord avec le Core (la relecture y répète la liste des rôles).
*/
const SHAPES = join(process.cwd(), '../core/src/main/java/com/loremind/application/campaigncontext/GuidedMethodShapes.java');
const FRAGMENTS_DIR = join(process.cwd(), 'src/assets/i18n/fragments');
/** Rôles déclarés par le Core, par méthode (constantes Java résolues en identifiants). */
function coreShapes(): Record<string, string[]> {
const java = readFileSync(SHAPES, 'utf-8');
const ids = Object.fromEntries(
[...java.matchAll(/static final String (\w+) = "([\w-]+)";/g)].map(m => [m[1], m[2]]));
// Une ligne par méthode : `CONSTANTE, List.of("role1", "role2", …)`.
const shapes: Record<string, string[]> = {};
for (const line of java.split('\n')) {
const at = line.indexOf(', List.of("');
if (at < 0) continue;
const method = ids[line.slice(0, at).trim()];
if (method) shapes[method] = [...line.slice(at).matchAll(/"([\w-]+)"/g)].map(r => r[1]);
}
return shapes;
}
function scene(id: string, guidedRole?: string, order = 0): Scene {
return { id, name: id, chapterId: 'c1', order, guidedRole };
}
describe('guided roles', () => {
it('gives every scene of every method a role that is one of its steps', () => {
for (const method of GUIDED_METHODS) {
const roles = guidedRoles(method);
expect(roles.length, method.id).toBe(method.toDraft({}).scenes.length);
expect(new Set(roles.map(r => r.id)).size, method.id).toBe(roles.length);
const stepIds = method.steps.map(s => s.id);
for (const role of roles) {
expect(stepIds, `${method.id} / ${role.id}`).toContain(role.id);
}
}
});
it('names the five rooms in order', () => {
expect(guidedRoles(FIVE_ROOM_METHOD).map(r => r.id)).toEqual(['room1', 'room2', 'room3', 'room4', 'room5']);
});
it('agrees with the roles the core reviews', () => {
const front = Object.fromEntries(GUIDED_METHODS.map(m => [m.id, guidedRoles(m).map(r => r.id)]));
expect(coreShapes()).toEqual(front);
});
for (const lang of ['fr', 'en'] as const) {
it(`${lang}: every role has a default scene name`, () => {
const guided = JSON.parse(readFileSync(join(FRAGMENTS_DIR, `guided.${lang}.json`), 'utf-8')).guided;
for (const method of GUIDED_METHODS) {
for (const role of guidedRoles(method)) {
const name = guided[method.i18nKey]?.defaults?.[role.id]?.name;
expect(typeof name === 'string' && name.trim().length > 0, `${method.id} / ${role.id} (${lang})`).toBe(true);
}
}
});
}
});
describe('chapter structure', () => {
it('finds the method a chapter follows, and nothing for an unknown or missing one', () => {
expect(methodOf({ guidedMethod: 'investigation' })).toBe(INVESTIGATION_METHOD);
expect(methodOf({ guidedMethod: 'heist' })).toBeNull();
expect(methodOf({ guidedMethod: null })).toBeNull();
expect(methodOf(null)).toBeNull();
});
it('pairs each role with the scene holding it, in method order', () => {
const scenes = [scene('s-climax', 'room4'), scene('s-free'), scene('s-entry', 'room1')];
const rows = roleRows(FIVE_ROOM_METHOD, scenes);
expect(rows.map(r => r.role.id)).toEqual(['room1', 'room2', 'room3', 'room4', 'room5']);
expect(rows.map(r => r.scene?.id ?? null)).toEqual(['s-entry', null, null, 's-climax', null]);
});
it('lists the scenes outside the method, by order', () => {
const scenes = [scene('b', undefined, 2), scene('held', 'room1', 0), scene('a', undefined, 1)];
expect(freeScenes(scenes).map(s => s.id)).toEqual(['a', 'b']);
});
it('resolves the role a scene holds, ignoring a role from another method', () => {
expect(roleOf(FIVE_ROOM_METHOD, scene('s', 'room3'))?.id).toBe('room3');
expect(roleOf(FIVE_ROOM_METHOD, scene('s', 'conclusion'))).toBeNull();
expect(roleOf(FIVE_ROOM_METHOD, scene('s'))).toBeNull();
expect(roleOf(null, scene('s', 'room3'))).toBeNull();
});
});
@@ -0,0 +1,38 @@
import { Chapter, Scene } from '../../services/campaign.model';
import { GuidedMethod, GuidedRole, guidedRoles } from './guided-method.model';
import { findGuidedMethod } from './guided-methods';
/**
* La méthode guidée d'un chapitre après sa création (logique pure, testée sans Angular) :
* quelle méthode il suit, quelle scène tient quel rôle, quelles scènes restent hors méthode.
*/
/** Un temps de la méthode et la scène qui le tient (absente : rôle encore à écrire). */
export interface RoleRow {
role: GuidedRole;
scene: Scene | null;
}
/** Méthode suivie par le chapitre ; `null` sans méthode, ou si cette version ne la connaît pas. */
export function methodOf(chapter: Pick<Chapter, 'guidedMethod'> | null | undefined): GuidedMethod | null {
return findGuidedMethod(chapter?.guidedMethod ?? null) ?? null;
}
/** Les rôles de la méthode, dans l'ordre, chacun avec sa scène. */
export function roleRows(method: GuidedMethod, scenes: Scene[]): RoleRow[] {
return guidedRoles(method).map(role => ({
role,
scene: scenes.find(s => s.guidedRole === role.id) ?? null
}));
}
/** Scènes du chapitre qui ne tiennent aucun rôle (candidates pour un rôle libre), par ordre. */
export function freeScenes(scenes: Scene[]): Scene[] {
return scenes.filter(s => !s.guidedRole).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
}
/** Le rôle que tient la scène dans la méthode de son chapitre, s'il existe encore. */
export function roleOf(method: GuidedMethod | null, scene: Pick<Scene, 'guidedRole'> | null | undefined): GuidedRole | null {
if (!method || !scene?.guidedRole) return null;
return guidedRoles(method).find(r => r.id === scene.guidedRole) ?? null;
}
@@ -0,0 +1,99 @@
@if (method) {
<section class="structure" [attr.aria-busy]="busy">
<h2 class="structure-title">
<lucide-icon [img]="Compass" [size]="14"></lucide-icon>
{{ 'guided.structure.title' | translate:{ method: (k('name') | translate) } }}
<span class="structure-count">{{ 'guided.structure.progress' | translate:{ done: heldCount, total: rows.length } }}</span>
</h2>
<p class="structure-tagline">{{ k('tagline') | translate }}</p>
<ol class="role-list">
@for (row of rows; track row.role.id) {
<li class="role" [class.role--missing]="!row.scene">
<div class="role-head">
<span class="role-title">{{ k('steps.' + row.role.id + '.title') | translate }}</span>
@if (row.scene; as scene) {
<a class="role-scene" [routerLink]="sceneLink(scene)">{{ scene.name }}</a>
<button type="button" class="link-button" (click)="unassign(scene)" [disabled]="busy"
[title]="'guided.structure.unassignTitle' | translate">
{{ 'guided.structure.unassign' | translate }}
</button>
} @else {
<span class="role-missing">{{ 'guided.structure.missing' | translate }}</span>
}
</div>
<p class="role-why">{{ k('steps.' + row.role.id + '.why') | translate }}</p>
@if (!row.scene) {
<div class="role-actions">
<button type="button" class="small-button" (click)="createScene(row.role)" [disabled]="busy">
<lucide-icon [img]="Plus" [size]="13"></lucide-icon>
{{ 'guided.structure.create' | translate }}
</button>
@if (free.length > 0) {
<select #pick class="role-pick" (change)="assign(row.role, pick)" [disabled]="busy"
[attr.aria-label]="'guided.structure.assign' | translate">
<option value="">{{ 'guided.structure.assign' | translate }}</option>
@for (scene of free; track scene.id) {
<option [value]="scene.id">{{ scene.name }}</option>
}
</select>
}
</div>
}
</li>
}
</ol>
@if (error) {
<p class="structure-error" role="alert">{{ 'guided.structure.error' | translate }}</p>
}
<footer class="structure-foot">
@if (free.length > 0) {
<span>{{ 'guided.structure.others' | translate:{ n: free.length } }}</span>
}
<button type="button" class="link-button" (click)="detach()" [disabled]="busy">
{{ 'guided.structure.detach' | translate }}
</button>
</footer>
</section>
} @else if (!chapter.guidedMethod) {
<section class="structure structure--offer" [attr.aria-busy]="busy">
@if (!choosing) {
<div class="offer">
<p>{{ 'guided.structure.offer' | translate }}</p>
<button type="button" class="small-button" (click)="choosing = true">
<lucide-icon [img]="Compass" [size]="13"></lucide-icon>
{{ 'guided.structure.offerButton' | translate }}
</button>
</div>
} @else {
<h2 class="structure-title">
<lucide-icon [img]="Compass" [size]="14"></lucide-icon>
{{ 'guided.structure.applyTitle' | translate }}
</h2>
<p class="structure-tagline">{{ 'guided.structure.applyIntro' | translate }}</p>
<ul class="method-list">
@for (m of methods; track m.id) {
<li class="method" [class.method--suggested]="m.id === suggested">
<div class="method-text">
<span class="method-name">
{{ ('guided.' + m.i18nKey + '.name') | translate }}
@if (m.id === suggested) {
<span class="method-badge">{{ 'guided.structure.suggested' | translate }}</span>
}
</span>
<span class="method-tagline">{{ ('guided.' + m.i18nKey + '.tagline') | translate }}</span>
</div>
<button type="button" class="small-button" (click)="apply(m)" [disabled]="busy">
{{ 'guided.structure.apply' | translate }}
</button>
</li>
}
</ul>
@if (error) {
<p class="structure-error" role="alert">{{ 'guided.structure.error' | translate }}</p>
}
<button type="button" class="link-button" (click)="choosing = false">{{ 'common.cancel' | translate }}</button>
}
</section>
}
@@ -0,0 +1,249 @@
// Même rythme qu'une .view-section (styles/_view.scss) : le panneau vit dans une fiche.
:host { display: block; }
.structure {
padding: 1.25rem 0;
border-top: 1px solid #1e1e3a;
}
.structure-title {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
margin: 0 0 0.4rem;
font-size: 0.72rem;
font-weight: 600;
color: #fbbf24;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.structure-count {
margin-left: auto;
color: #9ca3af;
font-weight: 500;
text-transform: none;
letter-spacing: 0;
font-size: 0.78rem;
}
.structure-tagline {
margin: 0 0 0.9rem;
color: #9ca3af;
font-size: 0.86rem;
line-height: 1.5;
}
.role-list {
list-style: none;
counter-reset: role;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.role {
counter-increment: role;
position: relative;
padding: 0.7rem 0.9rem 0.7rem 2.6rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 10px;
&::before {
content: counter(role);
position: absolute;
left: 0.8rem;
top: 0.7rem;
width: 1.3rem;
height: 1.3rem;
display: grid;
place-items: center;
border-radius: 50%;
background: #1f2937;
color: #d1d5db;
font-size: 0.72rem;
font-weight: 600;
}
}
.role--missing {
border-style: dashed;
border-color: #92400e;
&::before { background: rgba(251, 191, 36, 0.15); color: #fbbf24; }
}
.role-head {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.25rem 0.75rem;
}
.role-title {
color: #f3f4f6;
font-size: 0.9rem;
font-weight: 600;
}
.role-scene {
color: #a5b4fc;
font-size: 0.88rem;
text-decoration: none;
&:hover { color: #c7d2fe; text-decoration: underline; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
}
.role-missing {
color: #fbbf24;
font-size: 0.8rem;
font-style: italic;
}
.role-why {
margin: 0.3rem 0 0;
color: #9ca3af;
font-size: 0.82rem;
line-height: 1.5;
}
.role-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
margin-top: 0.6rem;
}
.role-pick {
max-width: 100%;
padding: 0.35rem 0.6rem;
background: #0b1220;
color: #d1d5db;
border: 1px solid #374151;
border-radius: 6px;
font-size: 0.8rem;
}
.small-button {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.38rem 0.75rem;
background: #1f2937;
color: #e5e7eb;
border: 1px solid #374151;
border-radius: 6px;
font-size: 0.8rem;
cursor: pointer;
white-space: nowrap;
&:hover:not(:disabled) { background: #374151; }
&:disabled { opacity: 0.45; cursor: not-allowed; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
.link-button {
padding: 0;
background: none;
border: none;
color: #9ca3af;
font-size: 0.78rem;
text-decoration: underline;
cursor: pointer;
&:hover:not(:disabled) { color: #e5e7eb; }
&:disabled { opacity: 0.45; cursor: not-allowed; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
}
.structure-foot {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.5rem 1rem;
margin-top: 0.8rem;
color: #6b7280;
font-size: 0.78rem;
.link-button { margin-left: auto; }
}
.structure-error {
margin: 0.6rem 0 0;
color: #fca5a5;
font-size: 0.82rem;
}
// --- Chapitre sans méthode ---
.offer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.6rem 1rem;
p { margin: 0; color: #6b7280; font-size: 0.86rem; font-style: italic; }
}
.method-list {
list-style: none;
padding: 0;
margin: 0 0 0.8rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.method {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.7rem 0.9rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 10px;
@media (max-width: 600px) {
flex-direction: column;
align-items: stretch;
}
}
.method--suggested { border-color: #92400e; }
.method-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.method-name {
color: #f3f4f6;
font-size: 0.9rem;
font-weight: 600;
}
.method-badge {
margin-left: 0.5rem;
padding: 0.05rem 0.45rem;
border-radius: 999px;
background: rgba(251, 191, 36, 0.15);
color: #fbbf24;
font-size: 0.7rem;
font-weight: 600;
}
.method-tagline {
color: #9ca3af;
font-size: 0.82rem;
line-height: 1.45;
}
@@ -0,0 +1,123 @@
import { Component, EventEmitter, Input, OnChanges, Output, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { LucideAngularModule, Compass, Plus } from 'lucide-angular';
import { Observable } from 'rxjs';
import { Chapter, Scene } from '../../../services/campaign.model';
import { GuidedSkeletonService } from '../../../services/guided-skeleton.service';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { GuidedMethod, GuidedRole } from '../guided-method.model';
import { GUIDED_METHODS } from '../guided-methods';
import { RoleRow, freeScenes, methodOf, roleRows } from '../guided-roles';
/**
* La méthode guidée d'un chapitre, après sa création (vue du chapitre) : chaque temps de la
* méthode, pourquoi il compte, et la scène qui le tient. Un temps sans scène se crée d'un
* clic ou se confie à une scène existante.
*
* Chapitre sans méthode : propose d'en suivre une. Rien n'est réécrit : la méthode se pose
* par-dessus les scènes déjà écrites, et le MJ dit laquelle tient quel rôle.
*/
@Component({
selector: 'app-guided-structure',
imports: [RouterLink, TranslatePipe, LucideAngularModule],
templateUrl: './guided-structure.component.html',
styleUrls: ['./guided-structure.component.scss']
})
export class GuidedStructureComponent implements OnChanges {
readonly Compass = Compass;
readonly Plus = Plus;
readonly methods = GUIDED_METHODS;
private readonly guided = inject(GuidedSkeletonService);
private readonly confirmDialog = inject(ConfirmDialogService);
private readonly translate = inject(TranslateService);
@Input({ required: true }) campaignId = '';
@Input({ required: true }) arcId = '';
@Input({ required: true }) chapter!: Chapter;
/** Scènes du chapitre (l'ordre n'importe pas : elles sont rangées par rôle). */
@Input() scenes: Scene[] = [];
/** Méthode conseillée par la relecture (`?method=`) : la liste s'ouvre dessus. */
@Input() suggested: string | null = null;
/** Méthode, rôle ou scène modifiés : le parent recharge le chapitre et l'arbre. */
@Output() changed = new EventEmitter<void>();
method: GuidedMethod | null = null;
rows: RoleRow[] = [];
free: Scene[] = [];
/** La liste des méthodes est dépliée (chapitre sans méthode). */
choosing = false;
busy = false;
error = false;
ngOnChanges(): void {
this.method = methodOf(this.chapter);
this.rows = this.method ? roleRows(this.method, this.scenes) : [];
this.free = freeScenes(this.scenes);
if (!this.chapter.guidedMethod && this.suggested && this.methods.some(m => m.id === this.suggested)) {
this.choosing = true;
}
}
/** Clé i18n de la méthode suivie. */
k(path: string): string {
return `guided.${this.method?.i18nKey}.${path}`;
}
get heldCount(): number {
return this.rows.filter(r => !!r.scene).length;
}
sceneLink(scene: Scene): string[] {
return ['/campaigns', this.campaignId, 'arcs', this.arcId, 'chapters', this.chapter.id ?? '', 'scenes', scene.id ?? ''];
}
apply(method: GuidedMethod): void {
this.run(this.guided.setChapterMethod(this.chapter.id ?? '', method.id));
}
async detach(): Promise<void> {
const ok = await this.confirmDialog.confirm({
title: this.translate.instant('guided.structure.detachTitle'),
message: this.translate.instant('guided.structure.detachMessage'),
confirmLabel: this.translate.instant('guided.structure.detach')
});
if (ok) this.run(this.guided.setChapterMethod(this.chapter.id ?? '', null));
}
/** Crée la scène du rôle, nommée et typée comme la méthode le propose. */
createScene(role: GuidedRole): void {
const name = this.translate.instant(this.k(`defaults.${role.id}.name`)) as string;
this.run(this.guided.createRoleScene(this.chapter.id ?? '', name, role.type, role.id));
}
/** Confie le rôle à une scène existante choisie dans la liste. */
assign(role: GuidedRole, select: HTMLSelectElement): void {
const sceneId = select.value;
select.value = '';
if (sceneId) this.run(this.guided.setSceneRole(sceneId, role.id));
}
unassign(scene: Scene): void {
this.run(this.guided.setSceneRole(scene.id ?? '', null));
}
private run(request: Observable<unknown>): void {
if (this.busy) return;
this.busy = true;
this.error = false;
request.subscribe({
next: () => {
this.busy = false;
this.choosing = false;
this.changed.emit();
},
error: () => {
this.busy = false;
this.error = true;
}
});
}
}
@@ -64,7 +64,19 @@
}
<!-- Où ranger l'aventure -->
@if (step.kind === 'placement') {
@if (step.kind === 'placement' && placementDecided) {
<div class="placement-decided">
<p>
@if (placementContext?.simple) {
{{ 'guided.placementSimple' | translate }}
} @else {
{{ (asQuest ? 'guided.placementContextQuest' : 'guided.placementContext') | translate:{ name: placementLabel } }}
}
</p>
<button type="button" class="btn-link" (click)="openPlacement()">{{ 'guided.placementChange' | translate }}</button>
</div>
}
@if (step.kind === 'placement' && !placementDecided) {
<fieldset class="placement">
<legend class="sr-only">{{ k('steps.placement.title') | translate }}</legend>
@if (linearArcs.length > 0) {
@@ -85,6 +97,24 @@
</div>
}
}
@if (hubArcs.length > 0) {
<label class="option-card" [class.selected]="answers['placement.mode'] === 'quest'">
<input type="radio" name="placement-mode" value="quest"
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
<span>{{ 'guided.placementQuest' | translate }}</span>
</label>
@if (answers['placement.mode'] === 'quest') {
<div class="field nested">
<label for="guided-hub-arc">{{ 'guided.placementQuestArcLabel' | translate }}</label>
<select id="guided-hub-arc" [ngModel]="answers['placement.hubArcId']"
(ngModelChange)="setAnswer('placement.hubArcId', $event)">
@for (arc of hubArcs; track arc.id) {
<option [value]="arc.id">{{ arc.name }}</option>
}
</select>
</div>
}
}
<label class="option-card" [class.selected]="answers['placement.mode'] === 'new'">
<input type="radio" name="placement-mode" value="new"
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
@@ -149,9 +179,11 @@
@if (step.kind === 'review' && draft; as d) {
<div class="review">
<dl class="review-meta">
<dt>{{ 'guided.reviewArc' | translate }}</dt>
<dd>{{ placementLabel }}</dd>
<dt>{{ 'guided.reviewChapter' | translate }}</dt>
@if (!hidesArc) {
<dt>{{ (asQuest ? 'guided.reviewQuestArc' : 'guided.reviewArc') | translate }}</dt>
<dd>{{ placementLabel }}</dd>
}
<dt>{{ (asQuest ? 'guided.reviewQuest' : 'guided.reviewChapter') | translate }}</dt>
<dd>{{ d.chapter.name }}</dd>
</dl>
<ol class="review-scenes">
@@ -426,3 +426,17 @@
.ai-note { margin: 0; color: #c7d2fe; font-size: 0.85rem; }
.ai-error { margin: 0; color: #fca5a5; font-size: 0.85rem; }
.ai-hint { margin: 0; color: #9ca3af; font-size: 0.78rem; font-style: italic; }
// Placement décidé par le contexte : une ligne d'information, pas une question.
.placement-decided {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.4rem 1rem;
padding: 0.8rem 1rem;
border-radius: 8px;
border: 1px solid #1f2937;
background: #111827;
p { margin: 0; flex: 1; min-width: 14rem; color: #d1d5db; font-size: 0.9rem; line-height: 1.5; }
}
@@ -5,18 +5,20 @@ import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { LucideAngularModule, ArrowLeft, ArrowRight, Check, RotateCcw, Sparkles } from 'lucide-angular';
import { Arc } from '../../../services/campaign.model';
import { Arc, Chapter } from '../../../services/campaign.model';
import { CampaignService } from '../../../services/campaign.service';
import { GuidedSkeletonService } from '../../../services/guided-skeleton.service';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
import { GuidedAnswers, GuidedDraft, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
import { findGuidedMethod } from '../guided-methods';
import { PlacementContext, placementContext } from '../guided-placement';
import { IDEA_KEY, applySuggestions, buildSuggestRequest, hasIdea, markTouched } from '../guided-assist';
/** Clés de réponse réservées à l'assistant (placement + chaînage), communes à toutes les méthodes. */
const PLACEMENT_MODE = 'placement.mode';
const PLACEMENT_ARC = 'placement.arcId';
const PLACEMENT_HUB_ARC = 'placement.hubArcId';
const PLACEMENT_NEW_ARC = 'placement.newArcName';
const LINK_SCENES = 'link';
@@ -53,8 +55,19 @@ export class GuidedWizardComponent implements OnInit {
method: GuidedMethod | null = null;
answers: GuidedAnswers = {};
stepIndex = 0;
/** Arcs linéaires de la campagne : seuls candidats pour y ranger l'aventure. */
/** Arcs linéaires de la campagne : l'aventure y devient un chapitre. */
linearArcs: Arc[] = [];
/** Arcs de quêtes (HUB) : l'aventure y devient une quête. */
hubArcs: Arc[] = [];
/**
* Placement décidé par le contexte (assistant ouvert depuis un arc, campagne encore
* simple) : la question n'est plus posée, sauf si le MJ demande à ranger ailleurs.
*/
placementContext: PlacementContext | null = null;
/** Le MJ a demandé à choisir lui-même où ranger l'aventure. */
placementOpen = false;
/** Chapitre vide d'une campagne « à plat » : rempli plutôt que doublé. */
private emptyFlatChapter: Chapter | null = null;
/** Le placement par défaut dépend des arcs : on attend leur chargement pour le choisir. */
private arcsLoaded = false;
submitting = false;
@@ -67,11 +80,12 @@ export class GuidedWizardComponent implements OnInit {
if (!this.method) return;
this.restoreDraft();
this.arcsLoaded = false;
this.campaignService.getArcs(this.campaignId).subscribe(arcs => {
this.linearArcs = arcs
.filter(a => (a.type ?? 'LINEAR') === 'LINEAR')
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
this.campaignService.getTree(this.campaignId).subscribe(tree => {
const byOrder = (a: Arc, b: Arc) => (a.order ?? 0) - (b.order ?? 0);
this.linearArcs = tree.arcs.filter(a => (a.type ?? 'LINEAR') === 'LINEAR').sort(byOrder);
this.hubArcs = tree.arcs.filter(a => a.type === 'HUB').sort(byOrder);
this.arcsLoaded = true;
this.applyPlacementContext(placementContext(tree, this.route.snapshot.queryParamMap.get('arc')));
this.applyDefaults();
});
this.applyDefaults();
@@ -121,9 +135,11 @@ export class GuidedWizardComponent implements OnInit {
const step = this.step;
if (!step) return false;
if (step.kind === 'placement') {
return this.answers[PLACEMENT_MODE] === 'existing'
? !!this.answers[PLACEMENT_ARC]
: !!answer(this.answers, PLACEMENT_NEW_ARC);
switch (this.answers[PLACEMENT_MODE]) {
case 'existing': return !!this.answers[PLACEMENT_ARC];
case 'quest': return !!this.answers[PLACEMENT_HUB_ARC];
default: return !!answer(this.answers, PLACEMENT_NEW_ARC);
}
}
return (step.fields ?? []).every(f => !f.required || !!answer(this.answers, f.key));
}
@@ -234,6 +250,38 @@ export class GuidedWizardComponent implements OnInit {
this.answers = a;
}
/**
* Placement décidé par le contexte : assistant ouvert depuis un arc (« Nouveau chapitre »,
* page d'un arc ou d'un arc de quêtes), ou campagne encore simple (aucun arc, ou un seul
* arc d'un seul chapitre) dont le MJ n'a jamais vu la notion d'arc. La question n'est pas
* posée : l'étape est sautée, ou réduite à sa présentation de la méthode (`intro`).
*/
private applyPlacementContext(context: PlacementContext | null): void {
this.placementContext = context;
this.emptyFlatChapter = context?.emptyChapter ?? null;
if (!context) return;
const a: GuidedAnswers = { ...this.answers, [PLACEMENT_MODE]: context.mode };
if (context.mode === 'existing') a[PLACEMENT_ARC] = context.arc?.id ?? '';
if (context.mode === 'quest') a[PLACEMENT_HUB_ARC] = context.arc?.id ?? '';
if (context.mode === 'new' && !answer(a, PLACEMENT_NEW_ARC)) {
a[PLACEMENT_NEW_ARC] = this.translate.instant('campaignDetail.defaultArcName');
}
this.answers = a;
const first = this.method?.steps[0];
if (this.stepIndex === 0 && first?.kind === 'placement' && !first.intro && this.total > 1) this.stepIndex = 1;
this.saveDraft();
}
/** Le placement vient du contexte et le MJ ne l'a pas rouvert : la question n'est pas posée. */
get placementDecided(): boolean {
return !!this.placementContext && !this.placementOpen;
}
/** Le MJ veut choisir lui-même où ranger l'aventure. */
openPlacement(): void {
this.placementOpen = true;
}
/** Arc existant par défaut s'il y en a ; sinon (ou arc disparu) nouvel arc. */
private applyPlacementDefaults(a: GuidedAnswers): void {
a[PLACEMENT_MODE] ??= this.linearArcs.length > 0 ? 'existing' : 'new';
@@ -241,6 +289,10 @@ export class GuidedWizardComponent implements OnInit {
a[PLACEMENT_ARC] = this.linearArcs[0]?.id ?? '';
if (!a[PLACEMENT_ARC]) a[PLACEMENT_MODE] = 'new';
}
if (a[PLACEMENT_MODE] === 'quest' && !this.hubArcs.some(arc => arc.id === a[PLACEMENT_HUB_ARC])) {
a[PLACEMENT_HUB_ARC] = this.hubArcs[0]?.id ?? '';
if (!a[PLACEMENT_HUB_ARC]) a[PLACEMENT_MODE] = this.linearArcs.length > 0 ? 'existing' : 'new';
}
}
// --- Récapitulatif & création --------------------------------------------------------
@@ -250,10 +302,21 @@ export class GuidedWizardComponent implements OnInit {
}
get placementLabel(): string {
if (this.answers[PLACEMENT_MODE] === 'existing') {
return this.linearArcs.find(a => a.id === this.answers[PLACEMENT_ARC])?.name ?? '';
switch (this.answers[PLACEMENT_MODE]) {
case 'existing': return this.linearArcs.find(a => a.id === this.answers[PLACEMENT_ARC])?.name ?? '';
case 'quest': return this.hubArcs.find(a => a.id === this.answers[PLACEMENT_HUB_ARC])?.name ?? '';
default: return answer(this.answers, PLACEMENT_NEW_ARC) ?? '';
}
return answer(this.answers, PLACEMENT_NEW_ARC) ?? '';
}
/** L'aventure devient une quête (arc de quêtes) plutôt qu'un chapitre. */
get asQuest(): boolean {
return this.answers[PLACEMENT_MODE] === 'quest';
}
/** Campagne encore simple : on ne parle pas d'arc au MJ, même dans le récapitulatif. */
get hidesArc(): boolean {
return this.placementDecided && !!this.placementContext?.simple;
}
get linkScenes(): boolean {
@@ -272,12 +335,21 @@ export class GuidedWizardComponent implements OnInit {
create(): void {
const draft = this.draft;
if (!draft || this.submitting) return;
const existing = this.answers[PLACEMENT_MODE] === 'existing';
const mode = this.answers[PLACEMENT_MODE];
const existing = mode === 'existing';
const quest = mode === 'quest';
let arcId: string | null = null;
if (existing) arcId = this.answers[PLACEMENT_ARC];
else if (quest) arcId = this.answers[PLACEMENT_HUB_ARC];
// Campagne « à plat » : son chapitre vide est rempli plutôt que doublé.
const fill = existing && this.emptyFlatChapter?.arcId === arcId ? this.emptyFlatChapter : null;
this.submitting = true;
this.error = null;
this.skeletonService.create(this.campaignId, {
arcId: existing ? this.answers[PLACEMENT_ARC] : null,
newArcName: existing ? null : answer(this.answers, PLACEMENT_NEW_ARC),
arcId,
newArcName: existing || quest ? null : answer(this.answers, PLACEMENT_NEW_ARC),
asQuest: quest,
intoChapterId: fill?.id ?? null,
chapter: draft.chapter,
scenes: draft.scenes,
linkSequentially: this.offersChain(draft) && this.linkScenes,
@@ -285,11 +357,14 @@ export class GuidedWizardComponent implements OnInit {
links: (draft.links ?? []).map(l => ({
from: l.from, to: l.to, kind: l.kind, label: this.translate.instant(this.k(`links.${l.labelKey}`))
})),
clock: draft.clock ?? null
clock: draft.clock ?? null,
method: this.method?.id ?? null
}).subscribe({
next: result => {
this.clearDraft();
this.router.navigate(['/campaigns', this.campaignId, 'arcs', result.arcId, 'chapters', result.chapterId]);
this.router.navigate(result.questId
? ['/campaigns', this.campaignId, 'quests', result.questId]
: ['/campaigns', this.campaignId, 'arcs', result.arcId, 'chapters', result.chapterId]);
},
error: () => {
this.submitting = false;
@@ -36,7 +36,7 @@ export const FIVE_ROOM_METHOD: GuidedMethod = {
id: 'five-room',
i18nKey: 'fiveRoom',
steps: [
{ id: 'placement', kind: 'placement' },
{ id: 'placement', kind: 'placement', intro: true },
{
id: 'frame', kind: 'form', fields: [
{ key: 'title', kind: 'text', required: true },
@@ -74,6 +74,7 @@ export const FIVE_ROOM_METHOD: GuidedMethod = {
toDraft(answers: GuidedAnswers) {
const location = answer(answers, 'location');
const room = (n: number, type: SceneType): GuidedSceneSpec => ({
role: `room${n}`,
name: answer(answers, `room${n}.name`) ?? '',
description: answer(answers, `room${n}.description`),
type,
@@ -100,6 +100,7 @@ export const INVESTIGATION_METHOD: GuidedMethod = {
toDraft(answers: GuidedAnswers) {
const scene = (prefix: string, type: SceneType, choicesKey = 'clues', secretKey?: string): GuidedSceneSpec => ({
role: prefix,
name: answer(answers, `${prefix}.name`) ?? '',
description: answer(answers, `${prefix}.description`),
type,
@@ -82,6 +82,7 @@ export const VILLAIN_PLAN_METHOD: GuidedMethod = {
gmNotes: plan.length ? plan.join('\n') : null
},
scenes: STEPS.map(n => ({
role: `step${n}`,
name: answer(answers, `step${n}.name`) ?? '',
description: answer(answers, `step${n}.action`),
type: NATURE_TO_TYPE[answers[`step${n}.nature`]] ?? NATURE_TO_TYPE[FIRST_NATURE[n]],
@@ -36,5 +36,5 @@
white-space: nowrap; color: #e0c074; font-variant-numeric: tabular-nums;
text-align: right; width: 90px;
}
.col-desc { color: var(--color-text-muted, #cfd3da); font-size: 0.9rem; }
.col-desc { color: #cfd3da; font-size: 0.9rem; }
}
@@ -19,7 +19,7 @@
}
.nac-desc {
margin: 0.4rem 0 0; font-size: 0.85rem; color: var(--color-text-muted, #cfd3da);
margin: 0.4rem 0 0; font-size: 0.85rem; color: #cfd3da;
white-space: pre-wrap;
}
@@ -87,6 +87,9 @@
</app-dynamic-fields-form>
</div>
<!-- Sorts connus, choisis dans le catalogue du système (rien ne s'affiche s'il n'y en a pas). -->
<app-sheet-spells mode="edit" sheet="npc" [campaignId]="campaignId" [ownerId]="npcId"></app-sheet-spells>
<!-- Rôle dans l'histoire : indépendant du système de jeu (le gabarit porte les caractéristiques). -->
<fieldset class="story-block">
<legend>{{ 'npcEdit.storyTitle' | translate }}</legend>
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, ViewChild } from '@angular/core';
import { map, of, switchMap } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
@@ -25,9 +26,11 @@ import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writ
* libre remplace par un formulaire dynamique pilote par le npcTemplate du
* GameSystem associe a la campagne.
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-npc-edit',
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent, LoreLinkPickerComponent, WritingCoachTriggerComponent],
imports: [FormsModule, LucideAngularModule, TranslatePipe, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent, SheetSpellsComponent, LoreLinkPickerComponent, WritingCoachTriggerComponent],
templateUrl: './npc-edit.component.html',
styleUrls: ['./npc-edit.component.scss']
})
@@ -74,6 +77,9 @@ export class NpcEditComponent implements OnInit {
story: NpcStory = { role: null };
readonly roles = NPC_ROLES;
/** Sorts connus de la fiche : enregistrés après elle (cf. submit). */
@ViewChild(SheetSpellsComponent) private sheetSpells?: SheetSpellsComponent;
constructor(
private route: ActivatedRoute,
private router: Router,
@@ -170,8 +176,19 @@ export class NpcEditComponent implements OnInit {
const req = this.npcId
? this.service.update(this.npcId, { ...payload, id: this.npcId, order: this.order })
: this.service.create(payload);
req.subscribe({
next: (saved) => {
// Les sorts connus partent une fois la fiche enregistrée : elle a alors un identifiant.
req.pipe(
switchMap(saved => (this.sheetSpells?.save(saved.id) ?? of(true))
.pipe(map(spellsSaved => ({ saved, spellsSaved }))))
).subscribe({
next: ({ saved, spellsSaved }) => {
if (!spellsSaved) {
// La fiche est enregistrée, pas ses sorts : on reste sur son édition pour réessayer.
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'npcs', saved.id, 'edit']);
}
return;
}
if (isCreation && saved.id) {
this.router.navigate(['/campaigns', this.campaignId, 'npcs', saved.id]);
} else {
@@ -19,6 +19,8 @@
<app-persona-view [persona]="npc" [templateFields]="templateFields"></app-persona-view>
<app-sheet-spells mode="view" sheet="npc" [campaignId]="campaignId" [ownerId]="npcId"></app-sheet-spells>
@if (npc?.story; as story) {
<section class="nv-story">
<h2 class="nv-story-title">
@@ -24,9 +24,11 @@ function indexPagesById(pages: Page[]): Map<string, Page> {
* Vue lecture seule "WorldAnvil" d'une fiche PNJ.
* Route : /campaigns/:campaignId/npcs/:npcId
*/
import { SheetSpellsComponent } from '../../sheet-spells/sheet-spells.component';
@Component({
selector: 'app-npc-view',
imports: [LucideAngularModule, TranslatePipe, RouterLink, PersonaViewComponent, AiChatDrawerComponent],
imports: [LucideAngularModule, TranslatePipe, RouterLink, PersonaViewComponent, SheetSpellsComponent, AiChatDrawerComponent],
templateUrl: './npc-view.component.html',
styleUrls: ['./npc-view.component.scss']
})
@@ -2,8 +2,9 @@
<div class="page-header">
<div>
<h1>{{ quest?.name || (isCreate ? ('questEdit.newTitle' | translate) : ('questEdit.fallbackTitle' | translate)) }}</h1>
<p class="subtitle">{{ 'questEdit.subtitle' | translate }}</p>
<!-- Rattachée à un arc à ordre libre : c'est une aventure de cet arc. Sinon, une quête annexe. -->
<h1>{{ quest?.name || ((isCreate ? 'questEdit.newTitle' : 'questEdit.fallbackTitle') + (isAttached ? 'Adventure' : '') | translate) }}</h1>
<p class="subtitle">{{ (isAttached ? 'questEdit.subtitleAdventure' : 'questEdit.subtitle') | translate }}</p>
</div>
<div class="header-actions">
<button type="button" class="btn-secondary" (click)="cancel()">{{ 'common.cancel' | translate }}</button>
@@ -23,6 +24,9 @@
<p class="optional-hint">{{ 'questEdit.optionalHint' | translate }}</p>
<!-- ═══ NOYAU : toujours visible. Ce sont les champs que l'appli comprend (relecture,
méthodes guidées, bilan de préparation). ═══ -->
<div class="field">
<label for="quest-name">{{ 'questEdit.nameLabel' | translate }}</label>
<input
@@ -43,58 +47,6 @@
</textarea>
</div>
<div class="field">
<label>{{ 'questEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'questEdit.illustrationsLabel' | translate" icon="🖼️" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event">
</app-image-gallery>
<small class="field-hint">{{ 'questEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
<!-- Cœur de la quête : conditions de déblocage -->
<app-expandable-section [title]="'questEdit.unlockSectionTitle' | translate" icon="🔓" [initiallyOpen]="true" [filled]="prereqFilled">
<small class="field-hint">{{ 'questEdit.unlockHint' | translate }}</small>
<app-prerequisite-editor
[prerequisites]="prerequisites"
[availableQuests]="availableQuests"
[availableFlags]="availableFlagNames"
(prerequisitesChange)="onPrerequisitesChange($event)">
</app-prerequisite-editor>
</app-expandable-section>
<!-- Nœuds narratifs traversés — quêtes TRANSVERSES uniquement : une quête d'arc HUB
a son conteneur de scènes automatique, inutile d'exposer cette plomberie. -->
@if (!isAttached) {
<app-expandable-section [title]="'questEdit.nodesSectionTitle' | translate" icon="📍" [filled]="nodesFilled">
<small class="field-hint">{{ 'questEdit.nodesHint' | translate }}</small>
<app-node-picker
[nodes]="nodes"
[chapters]="chapters"
[scenes]="scenes"
(nodesChange)="nodes = $event">
</app-node-picker>
</app-expandable-section>
}
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'questEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [filled]="gmNotesFilled">
<div class="field">
<textarea
formControlName="gmNotes"
[placeholder]="'questEdit.gmNotesPlaceholder' | translate"
rows="5">
</textarea>
</div>
</app-expandable-section>
<!-- Objectifs et enjeux -->
<app-expandable-section [title]="'questEdit.objectivesSectionTitle' | translate" icon="🎯" [filled]="objectivesFilled">
<div class="field">
@@ -117,9 +69,65 @@
</div>
</app-expandable-section>
<!-- Cœur de la quête : conditions de déblocage -->
<app-expandable-section [title]="'questEdit.unlockSectionTitle' | translate" icon="🔓" [initiallyOpen]="true" [filled]="prereqFilled">
<small class="field-hint">{{ 'questEdit.unlockHint' | translate }}</small>
<app-prerequisite-editor
[prerequisites]="prerequisites"
[availableQuests]="availableQuests"
[availableFlags]="availableFlagNames"
(prerequisitesChange)="onPrerequisitesChange($event)">
</app-prerequisite-editor>
</app-expandable-section>
<!-- ═══ RUBRIQUES : optionnelles. Affichées si elles ont déjà du contenu ou si l'auteur
les a demandées (voir campaigns/entity-blocks.ts). ═══ -->
<!-- Nœuds narratifs traversés — quêtes TRANSVERSES uniquement : une quête d'arc HUB
a son conteneur de scènes automatique, inutile d'exposer cette plomberie. -->
@if (!isAttached && shows('nodes')) {
<app-expandable-section [title]="'questEdit.nodesSectionTitle' | translate" icon="📍" [initiallyOpen]="blocks.isAdded('nodes')" [filled]="nodesFilled">
<small class="field-hint">{{ 'questEdit.nodesHint' | translate }}</small>
<app-node-picker
[nodes]="nodes"
[chapters]="chapters"
[scenes]="scenes"
(nodesChange)="nodes = $event">
</app-node-picker>
</app-expandable-section>
}
@if (shows('gmNotes')) {
<!-- Notes du MJ (privé) -->
<app-expandable-section [title]="'questEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [initiallyOpen]="blocks.isAdded('gmNotes')" [filled]="gmNotesFilled">
<div class="field">
<textarea
formControlName="gmNotes"
[placeholder]="'questEdit.gmNotesPlaceholder' | translate"
rows="5">
</textarea>
</div>
</app-expandable-section>
}
@if (shows('illustrations')) {
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'questEdit.illustrationsLabel' | translate" icon="🖼️" [initiallyOpen]="blocks.isAdded('illustrations')" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event"
[placements]="illustrationPlacements"
(placementsChange)="illustrationPlacements = $event">
</app-image-gallery>
<small class="field-hint">{{ 'questEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
}
<!-- Pages Lore associées (cross-context) -->
@if (loreId) {
<app-expandable-section [title]="'questEdit.relatedPagesLabel' | translate" icon="🔗" [filled]="loreFilled">
@if (loreId && shows('lore')) {
<app-expandable-section [title]="'questEdit.relatedPagesLabel' | translate" icon="🔗" [initiallyOpen]="blocks.isAdded('lore')" [filled]="loreFilled">
<app-lore-link-picker
[value]="relatedPageIds"
[availablePages]="availablePages"
@@ -130,12 +138,21 @@
</app-expandable-section>
}
@if (shows('icon')) {
<div class="field">
<label>{{ 'questEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
}
<!-- Rubriques encore disponibles : on n'ajoute que ce dont la fiche a besoin. -->
<app-block-adder [choices]="addableBlocks" (add)="addBlock($event)"></app-block-adder>
@if (!loreId) {
<div class="field">
<small class="field-hint">{{ 'questEdit.noLoreHint' | translate }}</small>
</div>
}
</form>
</div>
@@ -15,15 +15,18 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Quest, QuestCreate, Prerequisite, QuestNodeRef, Chapter, Scene } from '../../../services/campaign.model';
import { Quest, QuestCreate, Prerequisite, QuestNodeRef, Chapter, Scene, ImagePlacement } from '../../../services/campaign.model';
import { Page } from '../../../services/page.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
import { ExpandableSectionComponent } from '../../../shared/expandable-section/expandable-section.component';
import { BlockAdderComponent } from '../../../shared/block-adder/block-adder.component';
import { QUEST_BLOCKS, QUEST_BLOCK_LABELS, QuestBlock, BlockChoice, BlockState, addableOf, choicesOf, filledOf, visibleOf } from '../../entity-blocks';
import { PrerequisiteEditorComponent } from '../../../shared/prerequisite-editor/prerequisite-editor.component';
import { NodePickerComponent } from '../../../shared/node-picker/node-picker.component';
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { prunePlacements } from '../../../shared/image-placements/image-placement';
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
@@ -37,7 +40,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
*/
@Component({
selector: 'app-quest-edit',
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent, ExpandableSectionComponent, PrerequisiteEditorComponent, NodePickerComponent, LoreLinkPickerComponent, ImageGalleryComponent, TranslatePipe],
imports: [ReactiveFormsModule, BlockAdderComponent, LucideAngularModule, IconPickerComponent, ExpandableSectionComponent, PrerequisiteEditorComponent, NodePickerComponent, LoreLinkPickerComponent, ImageGalleryComponent, TranslatePipe],
templateUrl: './quest-edit.component.html',
styleUrls: ['./quest-edit.component.scss']
})
@@ -70,6 +73,8 @@ export class QuestEditComponent implements OnInit {
scenes: Scene[] = [];
illustrationImageIds: string[] = [];
/** Placement choisi pour certaines illustrations dans le livret PDF (bind sur app-image-placements). */
illustrationPlacements: Record<string, ImagePlacement> = {};
relatedPageIds: string[] = [];
loreId: string | null = null;
availablePages: Page[] = [];
@@ -93,6 +98,37 @@ export class QuestEditComponent implements OnInit {
get illustrationsFilled(): boolean { return this.illustrationImageIds.length > 0; }
get loreFilled(): boolean { return this.relatedPageIds.length > 0; }
// ─────────────── Noyau + rubriques (voir campaigns/entity-blocks.ts) ───────────────
// Le noyau est toujours affiché ; une rubrique ne l'est que si elle a du contenu ou si
// l'auteur l'a demandée. Les autres attendent dans « Ajouter une rubrique ».
readonly blocks = new BlockState<QuestBlock>();
private get filledBlocks(): QuestBlock[] {
return filledOf<QuestBlock>({
nodes: this.nodesFilled,
gmNotes: this.gmNotesFilled,
illustrations: this.illustrationsFilled,
lore: this.loreFilled,
icon: !!this.selectedIcon
});
}
get visibleBlocks(): QuestBlock[] {
return visibleOf(QUEST_BLOCKS, [], this.blocks.shownBlocks, this.filledBlocks);
}
get addableBlocks(): BlockChoice[] {
return choicesOf(addableOf<QuestBlock>(QUEST_BLOCKS, this.visibleBlocks, [...(this.isAttached ? ['nodes' as const] : []), ...(this.loreId ? [] : ['lore' as const])]), QUEST_BLOCK_LABELS);
}
shows(block: QuestBlock): boolean {
return this.visibleBlocks.includes(block);
}
addBlock(id: string): void {
this.blocks.add(id as QuestBlock);
}
constructor(
private fb: FormBuilder,
private route: ActivatedRoute,
@@ -164,6 +200,7 @@ export class QuestEditComponent implements OnInit {
this.nodes = allNodes.filter(n => !this.containerNodes.includes(n));
this.relatedPageIds = [...(current.relatedPageIds ?? [])];
this.illustrationImageIds = [...(current.illustrationImageIds ?? [])];
this.illustrationPlacements = { ...(current.illustrationPlacements ?? {}) };
this.pageTitleService.set(current.name);
this.form.patchValue({
name: current.name,
@@ -178,6 +215,9 @@ export class QuestEditComponent implements OnInit {
next: names => this.availableFlagNames = names
});
// Ce qui a déjà du contenu reste affiché pendant toute l'édition, même une fois vidé.
this.blocks.reset(this.filledBlocks);
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
});
}
@@ -199,7 +239,8 @@ export class QuestEditComponent implements OnInit {
playerObjectives: this.form.value.playerObjectives,
narrativeStakes: this.form.value.narrativeStakes,
relatedPageIds: this.relatedPageIds,
illustrationImageIds: this.illustrationImageIds
illustrationImageIds: this.illustrationImageIds,
illustrationPlacements: prunePlacements(this.illustrationPlacements, this.illustrationImageIds)
};
const op$ = this.questId
@@ -8,7 +8,8 @@
}
{{ quest.name }}
</h1>
<p class="view-subtitle">{{ 'questView.subtitle' | translate }}</p>
<!-- Rattachée à un arc à ordre libre : c'est une aventure de cet arc. Sinon, une quête annexe. -->
<p class="view-subtitle">{{ (quest.arcId ? 'questView.subtitleAdventure' : 'questView.subtitle') | translate }}</p>
</div>
<div class="view-actions">
@if (containerChapter) {
@@ -65,6 +66,14 @@
</section>
</div>
<!-- Méthode guidée suivie (portée par le conteneur de scènes) : ses temps et leurs scènes. -->
@if (containerChapter; as container) {
@if (container.guidedMethod) {
<app-guided-structure [campaignId]="campaignId" [arcId]="container.arcId" [chapter]="container"
[scenes]="containerScenes" (changed)="reload()"></app-guided-structure>
}
}
<!-- Conditions de déblocage -->
@if ((quest.prerequisites?.length ?? 0) > 0) {
<section class="view-section">
@@ -113,5 +122,13 @@
</div>
</section>
}
<!-- Quête sans méthode : proposition discrète d'en suivre une (rien n'est réécrit). -->
@if (containerChapter; as container) {
@if (!container.guidedMethod) {
<app-guided-structure [campaignId]="campaignId" [arcId]="container.arcId" [chapter]="container"
[scenes]="containerScenes" (changed)="reload()"></app-guided-structure>
}
}
</div>
}
@@ -19,6 +19,7 @@ import { Page } from '../../../services/page.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
import { GuidedStructureComponent } from '../../guided/guided-structure/guided-structure.component';
/**
* Écran de consultation d'une Quête (lecture seule, Niveau 1).
@@ -29,7 +30,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
*/
@Component({
selector: 'app-quest-view',
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe],
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedStructureComponent],
templateUrl: './quest-view.component.html',
styleUrls: ['./quest-view.component.scss']
})
@@ -170,6 +171,17 @@ export class QuestViewComponent implements OnInit {
return null;
}
/** Scènes du conteneur : la structure de la méthode guidée dit laquelle tient quel rôle. */
get containerScenes(): Scene[] {
const id = this.containerChapter?.id;
return id ? this.scenes.filter(s => s.chapterId === id) : [];
}
/** Méthode, rôle ou scène modifiés depuis la structure : on recharge la quête et l'arbre. */
reload(): void {
this.load();
}
/** Ouvre la carte (graphe) des scènes de la quête — création libre de scènes incluse. */
openGraph(): void {
const ch = this.containerChapter;
@@ -0,0 +1,260 @@
<div class="training">
<a class="training-back" [routerLink]="['/campaigns', campaignId]">
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
{{ 'ruleTraining.back' | translate }}
</a>
<h1>
<lucide-icon [img]="GraduationCap" [size]="22"></lucide-icon>
{{ 'ruleTraining.title' | translate }}
</h1>
@if (options?.gameSystemName) {
<p class="training-system">{{ options?.gameSystemName }}</p>
}
@switch (phase) {
@case ('loading') {
<p class="training-status" role="status">{{ 'ruleTraining.loading' | translate }}</p>
}
@case ('loadFailed') {
<p class="training-error" role="alert">{{ 'ruleTraining.loadFailed' | translate }}</p>
}
@case ('noSystem') {
<div class="training-empty">
<p>{{ 'ruleTraining.noSystem' | translate }}</p>
<a class="btn-primary" [routerLink]="['/campaigns', campaignId]" [queryParams]="{ edit: 'system' }">
{{ 'ruleTraining.chooseSystem' | translate }}
</a>
</div>
}
@case ('noRules') {
<div class="training-empty">
<p>{{ 'ruleTraining.noRules' | translate:{ name: options?.gameSystemName } }}</p>
<a class="btn-primary" [routerLink]="['/game-systems', options?.gameSystemId, 'edit']">
{{ 'ruleTraining.addRules' | translate }}
</a>
</div>
}
@case ('setup') {
<p class="training-intro">{{ 'ruleTraining.intro' | translate }}</p>
@if (notice) {
<p class="training-error" role="alert">{{ notice | translate:noticeParams }}</p>
}
<section class="training-block">
<h2>{{ 'ruleTraining.scenesTitle' | translate }}</h2>
@if (adventures.length === 0) {
<p class="training-hint">{{ 'ruleTraining.noScene' | translate }}</p>
} @else {
<p class="training-hint">{{ 'ruleTraining.scenesHint' | translate:{ max: maxScenes } }}</p>
@for (adventure of adventures; track adventure.id) {
<fieldset class="adventure">
<legend>
<label class="check">
<input type="checkbox" [checked]="isAdventureSelected(adventure)" (change)="toggleAdventure(adventure)" />
<span>{{ adventure.name }}</span>
</label>
@if (adventure.sideQuest) {
<span class="tag">{{ 'ruleTraining.sideQuest' | translate }}</span>
}
</legend>
<ul class="check-list">
@for (scene of adventure.scenes; track scene.id) {
<li>
<label class="check" [class.check--disabled]="!canSelectScene(scene.id)">
<input type="checkbox" [checked]="isSceneSelected(scene.id)"
[disabled]="!canSelectScene(scene.id)" (change)="toggleScene(scene.id)" />
<span>{{ scene.name }}</span>
</label>
@if (scene.type !== 'GENERIC') {
<span class="tag">{{ ('sceneType.' + scene.type) | translate }}</span>
}
</li>
}
</ul>
</fieldset>
}
}
</section>
<section class="training-block">
<div class="block-head">
<h2>{{ 'ruleTraining.sectionsTitle' | translate }}</h2>
@if (sectionsWereTouched) {
<button type="button" class="link-button" (click)="resetSections()">
{{ 'ruleTraining.sectionsReset' | translate }}
</button>
}
</div>
<p class="training-hint">{{ 'ruleTraining.sectionsHint' | translate }}</p>
@if (otherLanguageCount > 0) {
<p class="training-hint other-language">
{{ otherLanguageNoteKey | translate:{ count: otherLanguageCount } }}
<button type="button" class="link-button" (click)="toggleOtherLanguage()">
{{ (showOtherLanguage ? 'ruleTraining.otherLanguageHide' : 'ruleTraining.otherLanguageShow') | translate }}
</button>
</p>
}
<ul class="check-list check-list--sections">
@for (section of visibleSections; track section.title) {
<li>
<label class="check">
<input type="checkbox" [checked]="isSectionSelected(section.title)" (change)="toggleSection(section.title)" />
<span>{{ section.title }}</span>
</label>
@if (section.otherLanguage) {
<span class="tag tag--language">{{ 'ruleTraining.otherLanguageTag' | translate }}</span>
}
@switch (stateOf(section.title)) {
@case ('review') {
<span class="tag tag--review">{{ 'ruleTraining.stateReview' | translate }}</span>
}
@case ('new') {
<span class="tag tag--new">{{ 'ruleTraining.stateNew' | translate }}</span>
}
@default {
<span class="tag">{{ 'ruleTraining.stateSeen' | translate:{ count: seenCount(section.title) } }}</span>
}
}
</li>
}
</ul>
@if (overBudget) {
<p class="training-hint training-hint--warn">{{ 'ruleTraining.sectionsOverBudget' | translate }}</p>
}
</section>
<div class="training-actions">
<button type="button" class="btn-primary" [disabled]="!canStart" (click)="start()">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'ruleTraining.start' | translate }}
</button>
@if (!canStart) {
<span class="training-hint">{{ 'ruleTraining.needsSection' | translate }}</span>
}
</div>
}
@case ('preparing') {
<div class="training-wait" role="status">
<span class="spinner" aria-hidden="true"></span>
<div>
<p class="training-wait-title">{{ 'ruleTraining.preparing' | translate }}</p>
<p class="training-hint">{{ 'ruleTraining.preparingHint' | translate }}</p>
</div>
</div>
}
@case ('drill') {
@if (current; as state) {
<div class="drill-head">
<span class="drill-progress">{{ 'ruleTraining.progress' | translate:{ n: index + 1, total: drills.length } }}</span>
<span class="tag">{{ state.drill.sceneName || ('ruleTraining.generalScene' | translate) }}</span>
<button type="button" class="link-button drill-stop" (click)="stop()">{{ 'ruleTraining.stop' | translate }}</button>
</div>
@if (index === 0 && series && series.dropped > 0) {
<p class="training-hint">
{{ (series.dropped === 1 ? 'ruleTraining.droppedOne' : 'ruleTraining.droppedMany') | translate:{ count: series.dropped } }}
</p>
}
<article class="drill" aria-live="polite">
<p class="drill-situation">{{ state.drill.situation }}</p>
<label class="drill-label" for="drill-answer">{{ 'ruleTraining.answerLabel' | translate }}</label>
<textarea id="drill-answer" rows="4" [(ngModel)]="state.answer"
[placeholder]="'ruleTraining.answerPlaceholder' | translate"></textarea>
@if (!state.revealed) {
<div class="training-actions">
<button type="button" class="btn-primary" (click)="reveal()">
<lucide-icon [img]="BookOpen" [size]="14"></lucide-icon>
{{ 'ruleTraining.reveal' | translate }}
</button>
</div>
} @else {
<section class="answer-key">
<h2>{{ 'ruleTraining.rulesSay' | translate }}</h2>
<p class="answer-source">{{ 'ruleTraining.excerptFrom' | translate:{ title: state.drill.section } }}</p>
<blockquote>{{ state.drill.excerpt }}</blockquote>
<h3>{{ 'ruleTraining.aiReading' | translate }}</h3>
<p class="answer-ruling">{{ state.drill.ruling }}</p>
<p class="training-hint">{{ 'ruleTraining.aiReadingHint' | translate }}</p>
</section>
<section class="compare">
@if (state.review; as review) {
<p [class]="'verdict verdict--' + review.verdict">
{{ ('ruleTraining.verdict.' + review.verdict) | translate }}
</p>
<p class="compare-feedback">{{ review.feedback }}</p>
} @else {
<button type="button" class="btn-secondary" [disabled]="!state.answer.trim() || state.comparing"
(click)="compare()">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ (state.comparing ? 'ruleTraining.comparing' : 'ruleTraining.compare') | translate }}
</button>
@if (!state.answer.trim()) {
<span class="training-hint">{{ 'ruleTraining.compareNeedsAnswer' | translate }}</span>
}
@if (state.compareFailed) {
<p class="training-error" role="alert">
{{ 'ruleTraining.compareFailedReason' | translate:{ reason: state.compareError } }}
</p>
}
}
</section>
<div class="rate">
<span class="rate-question">{{ 'ruleTraining.rateQuestion' | translate }}</span>
<button type="button" class="btn-rate btn-rate--known" (click)="rate('known')">
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
{{ 'ruleTraining.known' | translate }}
</button>
<button type="button" class="btn-rate btn-rate--review" (click)="rate('review')">
<lucide-icon [img]="RotateCcw" [size]="14"></lucide-icon>
{{ 'ruleTraining.review' | translate }}
</button>
</div>
}
</article>
}
}
@case ('summary') {
<section class="summary">
<h2>{{ 'ruleTraining.summaryTitle' | translate }}</h2>
<p class="summary-score">{{ 'ruleTraining.summaryScore' | translate:{ known: knownCount, total: drills.length } }}</p>
@if (sectionsToReview.length > 0) {
<h3>{{ 'ruleTraining.summaryReviewTitle' | translate }}</h3>
<ul class="summary-list">
@for (title of sectionsToReview; track title) {
<li>{{ title }}</li>
}
</ul>
<button type="button" class="btn-secondary" (click)="openRules()">
<lucide-icon [img]="ExternalLink" [size]="14"></lucide-icon>
{{ 'ruleTraining.openRules' | translate }}
</button>
} @else {
<p class="training-hint">{{ 'ruleTraining.summaryAllKnown' | translate }}</p>
}
<div class="training-actions">
<button type="button" class="btn-primary" (click)="backToSetup()">
<lucide-icon [img]="ArrowRight" [size]="14"></lucide-icon>
{{ 'ruleTraining.newSeries' | translate }}
</button>
<a class="btn-secondary" [routerLink]="['/campaigns', campaignId]">{{ 'ruleTraining.back' | translate }}</a>
</div>
</section>
}
}
</div>
@@ -0,0 +1,374 @@
.training {
max-width: 760px;
padding: 2rem;
margin: 0 auto;
color: #d1d5db;
h1 {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.5rem;
color: white;
margin: 1rem 0 0.25rem;
lucide-icon { color: #fbbf24; }
}
h2 { font-size: 1.05rem; color: white; margin: 0 0 0.35rem; }
h3 { font-size: 0.95rem; color: white; margin: 1rem 0 0.35rem; }
.btn-primary,
.btn-secondary {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 1.1rem;
font-size: 0.9rem;
text-decoration: none;
}
@media (max-width: 600px) {
padding: 1rem;
}
}
.training-back {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: #9ca3af;
font-size: 0.85rem;
text-decoration: none;
&:hover { color: white; }
}
.training-system {
color: #9ca3af;
font-size: 0.9rem;
margin: 0 0 1rem;
}
.training-intro {
line-height: 1.55;
margin: 0 0 1.25rem;
}
.training-status { color: #9ca3af; }
.training-hint {
color: #9ca3af;
font-size: 0.85rem;
line-height: 1.5;
margin: 0 0 0.6rem;
&--warn { color: #fde68a; margin-top: 0.6rem; }
}
.training-error {
color: #fecaca;
background: rgba(239, 68, 68, 0.12);
border: 1px solid rgba(239, 68, 68, 0.35);
border-radius: 8px;
padding: 0.6rem 0.8rem;
font-size: 0.88rem;
margin: 0 0 1rem;
}
.training-empty {
background: #111827;
border: 1px solid #1f2937;
border-radius: 12px;
padding: 1.25rem;
p { margin: 0 0 1rem; line-height: 1.5; }
}
.training-block {
background: #111827;
border: 1px solid #1f2937;
border-radius: 12px;
padding: 1rem 1.15rem;
margin-bottom: 1rem;
}
.block-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 1rem;
}
.link-button {
background: none;
border: none;
padding: 0;
color: #a5b4fc;
font-size: 0.85rem;
cursor: pointer;
&:hover { color: white; text-decoration: underline; }
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
}
.adventure {
border: none;
padding: 0;
margin: 0.75rem 0 0;
legend {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0;
font-weight: 600;
color: white;
}
.check-list { padding-left: 1.5rem; }
}
.check-list {
list-style: none;
padding: 0;
margin: 0.35rem 0 0;
li {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.2rem 0;
}
/* Le titre pousse les étiquettes (langue, progression) à droite. */
&--sections .check { margin-right: auto; }
}
.check {
display: inline-flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
min-width: 0;
input { accent-color: #6c63ff; flex-shrink: 0; }
&--disabled { opacity: 0.5; cursor: not-allowed; }
}
.tag {
flex-shrink: 0;
padding: 0.1rem 0.5rem;
border-radius: 999px;
background: #1f2937;
color: #9ca3af;
font-size: 0.72rem;
font-weight: 500;
white-space: nowrap;
&--review { background: rgba(251, 191, 36, 0.15); color: #fde68a; }
&--new { background: rgba(108, 99, 255, 0.18); color: #c7d2fe; }
}
.training-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.75rem;
margin-top: 1rem;
.training-hint { margin: 0; }
}
// ─────────────── Attente ───────────────
.training-wait {
display: flex;
align-items: center;
gap: 1rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 12px;
padding: 1.25rem;
.training-hint { margin: 0; }
}
.training-wait-title { color: white; font-weight: 600; margin: 0 0 0.25rem; }
.spinner {
flex-shrink: 0;
width: 22px;
height: 22px;
border: 3px solid #374151;
border-top-color: #6c63ff;
border-radius: 50%;
animation: training-spin 0.9s linear infinite;
@media (prefers-reduced-motion: reduce) { animation: none; }
}
@keyframes training-spin {
to { transform: rotate(360deg); }
}
// ─────────────── Situation ───────────────
.drill-head {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
margin: 0.5rem 0 0.75rem;
}
.drill-progress { color: white; font-weight: 600; font-size: 0.9rem; }
.drill-stop { margin-left: auto; }
.drill {
background: #111827;
border: 1px solid #1f2937;
border-radius: 12px;
padding: 1.15rem;
textarea {
width: 100%;
box-sizing: border-box;
padding: 0.65rem 0.8rem;
background: #0b1220;
color: #e5e7eb;
border: 1px solid #374151;
border-radius: 8px;
font: inherit;
line-height: 1.5;
resize: vertical;
&:focus { outline: none; border-color: #6c63ff; }
}
}
.drill-situation {
color: white;
font-size: 1.02rem;
line-height: 1.6;
white-space: pre-line;
margin: 0 0 1rem;
}
.drill-label {
display: block;
color: #9ca3af;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
margin-bottom: 0.35rem;
}
.answer-key {
margin-top: 1.25rem;
padding-top: 1rem;
border-top: 1px solid #1f2937;
blockquote {
margin: 0;
padding: 0.7rem 0.9rem;
border-left: 3px solid #fbbf24;
background: rgba(251, 191, 36, 0.07);
border-radius: 0 8px 8px 0;
color: #f3f4f6;
line-height: 1.6;
white-space: pre-line;
}
}
.answer-source { color: #fde68a; font-size: 0.82rem; margin: 0 0 0.4rem; }
.answer-ruling { line-height: 1.6; white-space: pre-line; margin: 0 0 0.5rem; }
.compare {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid #1f2937;
.training-hint,
.training-error { margin: 0; }
}
.verdict {
flex-shrink: 0;
padding: 0.2rem 0.65rem;
border-radius: 999px;
font-size: 0.8rem;
font-weight: 600;
margin: 0;
&--right { background: rgba(34, 197, 94, 0.15); color: #bbf7d0; }
&--partial { background: rgba(251, 191, 36, 0.15); color: #fde68a; }
&--off { background: rgba(239, 68, 68, 0.15); color: #fecaca; }
}
.compare-feedback { flex: 1 1 100%; line-height: 1.55; margin: 0; }
.rate {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid #1f2937;
}
.rate-question { color: white; font-weight: 600; margin-right: 0.25rem; }
.btn-rate {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.55rem 1rem;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
&--known {
background: rgba(34, 197, 94, 0.14);
color: #bbf7d0;
border: 1px solid rgba(34, 197, 94, 0.4);
&:hover { background: rgba(34, 197, 94, 0.24); }
}
&--review {
background: rgba(251, 191, 36, 0.12);
color: #fde68a;
border: 1px solid rgba(251, 191, 36, 0.4);
&:hover { background: rgba(251, 191, 36, 0.22); }
}
}
// ─────────────── Bilan ───────────────
.summary {
background: #111827;
border: 1px solid #1f2937;
border-radius: 12px;
padding: 1.25rem;
}
.summary-score { color: white; font-size: 1.05rem; margin: 0 0 0.5rem; }
.summary-list {
margin: 0 0 0.9rem;
padding-left: 1.2rem;
line-height: 1.7;
}
.other-language .link-button { margin-left: 0.35rem; }
@@ -0,0 +1,375 @@
import { Component, OnDestroy, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import {
LucideAngularModule, ArrowLeft, ArrowRight, BookOpen, Check, ExternalLink, GraduationCap, RotateCcw, Sparkles
} from 'lucide-angular';
import { Subscription } from 'rxjs';
import {
RuleDrill, RuleDrillReview, RuleDrillSeries, RuleTrainingAdventure, RuleTrainingOptions, RuleTrainingSection
} from '../../services/rule-training.model';
import { RuleTrainingService } from '../../services/rule-training.service';
import {
DrillOutcome, MAX_TRAINING_SCENES, SectionState, TrainingProgress, exceedsBudget, orderByPriority,
readProgress, recordOutcome, sectionState, suggestedTitles, writeProgress
} from './rule-training.util';
type Phase = 'loading' | 'loadFailed' | 'noSystem' | 'noRules' | 'setup' | 'preparing' | 'drill' | 'summary';
/** Une situation de la série en cours, et ce que le MJ en a fait. */
interface DrillState {
drill: RuleDrill;
answer: string;
revealed: boolean;
outcome: DrillOutcome | null;
comparing: boolean;
compareFailed: boolean;
compareError: string;
review: RuleDrillReview | null;
}
/** Nombre de situations déjà posées rappelées à l'IA pour qu'elle en propose d'autres. */
const MAX_AVOIDED = 10;
/**
* Entraînement aux règles : le MJ choisit des scènes et des sections de règles, l'IA en tire
* une série de situations (un seul appel), il tranche chacune de mémoire puis lit le passage
* de ses règles qui s'applique. La comparaison de sa réponse écrite est facultative.
*
* Rien n'est enregistré dans la campagne : la progression par section vit dans le navigateur.
* Route : /campaigns/:campaignId/rule-training (?chapterId= précoche les scènes d'une aventure).
*/
@Component({
selector: 'app-rule-training',
imports: [FormsModule, RouterLink, TranslatePipe, LucideAngularModule],
templateUrl: './rule-training.component.html',
styleUrls: ['./rule-training.component.scss']
})
export class RuleTrainingComponent implements OnInit, OnDestroy {
readonly ArrowLeft = ArrowLeft;
readonly ArrowRight = ArrowRight;
readonly BookOpen = BookOpen;
readonly Check = Check;
readonly ExternalLink = ExternalLink;
readonly GraduationCap = GraduationCap;
readonly RotateCcw = RotateCcw;
readonly Sparkles = Sparkles;
readonly maxScenes = MAX_TRAINING_SCENES;
private readonly route = inject(ActivatedRoute);
private readonly service = inject(RuleTrainingService);
readonly campaignId = this.route.snapshot.paramMap.get('campaignId') ?? '';
phase: Phase = 'loading';
options: RuleTrainingOptions | null = null;
progress: TrainingProgress = {};
selectedScenes = new Set<string>();
selectedSections = new Set<string>();
/** Le MJ a coché ou décoché une section lui-même : on ne recoche plus à sa place. */
private sectionsTouched = false;
/** Le MJ a demandé à voir aussi les sections rédigées dans l'autre langue que l'interface. */
showOtherLanguage = false;
/** Message affiché au-dessus du choix (série vide, échec). */
notice = '';
noticeParams: Record<string, unknown> = {};
series: RuleDrillSeries | null = null;
drills: DrillState[] = [];
index = 0;
/** Situations posées depuis l'ouverture de la page. */
private asked: string[] = [];
/** Sections notées « À revoir » dans la série en cours. */
private flagged = new Set<string>();
private loadSub: Subscription | null = null;
private seriesSub: Subscription | null = null;
private reviewSub: Subscription | null = null;
ngOnInit(): void {
this.loadSub = this.service.options(this.campaignId).subscribe({
next: options => this.applyOptions(options),
error: () => { this.phase = 'loadFailed'; }
});
}
ngOnDestroy(): void {
this.loadSub?.unsubscribe();
this.seriesSub?.unsubscribe();
this.reviewSub?.unsubscribe();
}
private applyOptions(options: RuleTrainingOptions): void {
this.options = options;
if (options.status === 'NO_SYSTEM') { this.phase = 'noSystem'; return; }
if (options.status === 'NO_RULES') { this.phase = 'noRules'; return; }
this.progress = readProgress(options.gameSystemId);
const chapterId = this.route.snapshot.queryParamMap.get('chapterId');
const adventure = options.adventures.find(a => a.id === chapterId);
if (adventure) {
adventure.scenes.slice(0, MAX_TRAINING_SCENES).forEach(s => this.selectedScenes.add(s.id));
}
this.applySuggestedSections();
this.phase = 'setup';
}
// ─────────────── Choix des scènes ───────────────
get adventures(): RuleTrainingAdventure[] {
return this.options?.adventures ?? [];
}
isSceneSelected(id: string): boolean {
return this.selectedScenes.has(id);
}
/** Une scène de plus peut-elle être cochée ? */
canSelectScene(id: string): boolean {
return this.selectedScenes.has(id) || this.selectedScenes.size < MAX_TRAINING_SCENES;
}
toggleScene(id: string): void {
if (this.selectedScenes.has(id)) this.selectedScenes.delete(id);
else if (this.selectedScenes.size < MAX_TRAINING_SCENES) this.selectedScenes.add(id);
this.onScenesChanged();
}
isAdventureSelected(adventure: RuleTrainingAdventure): boolean {
return adventure.scenes.every(s => this.selectedScenes.has(s.id));
}
/** Coche toutes les scènes de l'aventure (dans la limite), ou les décoche si elles le sont toutes. */
toggleAdventure(adventure: RuleTrainingAdventure): void {
if (this.isAdventureSelected(adventure)) {
adventure.scenes.forEach(s => this.selectedScenes.delete(s.id));
} else {
for (const scene of adventure.scenes) {
if (this.selectedScenes.size >= MAX_TRAINING_SCENES) break;
this.selectedScenes.add(scene.id);
}
}
this.onScenesChanged();
}
private onScenesChanged(): void {
if (!this.sectionsTouched) this.applySuggestedSections();
}
// ─────────────── Choix des sections ───────────────
get sections(): RuleTrainingSection[] {
return this.options?.sections ?? [];
}
/** Sections rédigées dans la langue de l'interface : les seules cochées d'office. */
private get sectionsInLanguage(): RuleTrainingSection[] {
return this.sections.filter(s => !s.otherLanguage);
}
/** Sections listées : celles de l'autre langue n'apparaissent que sur demande. */
get visibleSections(): RuleTrainingSection[] {
return this.showOtherLanguage ? this.sections : this.sectionsInLanguage;
}
get otherLanguageCount(): number {
return this.sections.length - this.sectionsInLanguage.length;
}
/** Phrase qui annonce ces sections : elle ne dit « pas proposées » que tant qu'elles sont masquées. */
get otherLanguageNoteKey(): string {
const shown = this.showOtherLanguage ? 'Shown' : '';
return `ruleTraining.otherLanguage${shown}${this.otherLanguageCount === 1 ? 'One' : 'Many'}`;
}
/** Affiche ou masque les sections de l'autre langue ; masquées, elles sont aussi décochées. */
toggleOtherLanguage(): void {
this.showOtherLanguage = !this.showOtherLanguage;
if (!this.showOtherLanguage) {
this.sections.filter(s => s.otherLanguage).forEach(s => this.selectedSections.delete(s.title));
}
}
private applySuggestedSections(): void {
const types = this.adventures
.flatMap(a => a.scenes)
.filter(s => this.selectedScenes.has(s.id))
.map(s => s.type);
this.selectedSections = new Set(suggestedTitles(this.sectionsInLanguage, types));
}
isSectionSelected(title: string): boolean {
return this.selectedSections.has(title);
}
toggleSection(title: string): void {
if (this.selectedSections.has(title)) this.selectedSections.delete(title);
else this.selectedSections.add(title);
this.sectionsTouched = true;
}
/** Revient aux sections conseillées pour les scènes cochées. */
resetSections(): void {
this.sectionsTouched = false;
this.applySuggestedSections();
}
get sectionsWereTouched(): boolean {
return this.sectionsTouched;
}
stateOf(title: string): SectionState {
return sectionState(this.progress, title);
}
seenCount(title: string): number {
return this.progress[title]?.seen ?? 0;
}
get overBudget(): boolean {
return exceedsBudget(this.sections, this.selectedSections);
}
// ─────────────── Série ───────────────
get canStart(): boolean {
return this.selectedSections.size > 0;
}
start(): void {
if (!this.canStart || this.phase === 'preparing') return;
this.notice = '';
this.phase = 'preparing';
const inBookOrder = this.sections.map(s => s.title).filter(t => this.selectedSections.has(t));
const sceneIds = this.adventures.flatMap(a => a.scenes).map(s => s.id).filter(id => this.selectedScenes.has(id));
this.seriesSub?.unsubscribe();
this.seriesSub = this.service.series(this.campaignId, {
sceneIds,
sectionTitles: orderByPriority(inBookOrder, this.progress),
avoid: this.asked.slice(-MAX_AVOIDED)
}).subscribe({
next: series => this.applySeries(series),
error: err => {
const reason: unknown = err?.error?.error;
this.showNotice(typeof reason === 'string' && reason ? 'ruleTraining.failedReason' : 'ruleTraining.failed',
{ reason });
}
});
}
private applySeries(series: RuleDrillSeries): void {
if (series.drills.length === 0) {
this.showNotice(series.dropped > 0 ? 'ruleTraining.allDropped' : 'ruleTraining.nothingFound');
return;
}
this.series = series;
this.drills = series.drills.map(drill => ({
drill, answer: '', revealed: false, outcome: null, comparing: false, compareFailed: false, compareError: '', review: null
}));
this.asked.push(...series.drills.map(d => d.situation));
this.flagged.clear();
this.index = 0;
this.phase = 'drill';
}
private showNotice(key: string, params: Record<string, unknown> = {}): void {
this.notice = key;
this.noticeParams = params;
this.phase = 'setup';
}
get current(): DrillState | null {
return this.drills[this.index] ?? null;
}
get isLast(): boolean {
return this.index >= this.drills.length - 1;
}
reveal(): void {
if (this.current) this.current.revealed = true;
}
/** Demande à l'IA de comparer la décision écrite au passage des règles. */
compare(): void {
const state = this.current;
if (!state?.answer.trim() || state.comparing) return;
state.comparing = true;
state.compareFailed = false;
state.compareError = '';
this.reviewSub?.unsubscribe();
this.reviewSub = this.service.review(this.campaignId, {
section: state.drill.section,
situation: state.drill.situation,
excerpt: state.drill.excerpt,
ruling: state.drill.ruling,
answer: state.answer.trim()
}).subscribe({
next: review => {
state.review = review;
state.comparing = false;
},
error: err => {
const reason: unknown = err?.error?.error;
state.compareFailed = true;
state.compareError = typeof reason === 'string' ? reason : '';
state.comparing = false;
}
});
}
/** Le MJ se note, la section s'en souvient, et la série avance. */
rate(outcome: DrillOutcome): void {
const state = this.current;
if (!state || state.outcome) return;
state.outcome = outcome;
if (outcome === 'review') this.flagged.add(state.drill.section);
this.progress = recordOutcome(this.progress, state.drill.section, outcome, this.flagged.has(state.drill.section));
writeProgress(this.options?.gameSystemId, this.progress);
this.reviewSub?.unsubscribe();
state.comparing = false;
if (this.isLast) this.phase = 'summary';
else this.index++;
}
/** Abandonne la série en cours (les situations déjà notées le restent). */
stop(): void {
this.reviewSub?.unsubscribe();
this.backToSetup();
}
backToSetup(): void {
this.series = null;
this.drills = [];
this.index = 0;
this.notice = '';
if (!this.sectionsTouched) this.applySuggestedSections();
this.phase = 'setup';
}
// ─────────────── Bilan ───────────────
get knownCount(): number {
return this.drills.filter(d => d.outcome === 'known').length;
}
/** Sections d'une situation notée « À revoir », sans doublon, dans l'ordre de la série. */
get sectionsToReview(): string[] {
return [...new Set(this.drills.filter(d => d.outcome === 'review').map(d => d.drill.section))];
}
/** Nouvel onglet : on ne quitte pas l'entraînement pour relire une règle. */
openRules(): void {
window.open(this.rulesUrl, '_blank', 'noopener');
}
get rulesUrl(): string {
return `/game-systems/${this.options?.gameSystemId}/edit`;
}
get chooseSystemUrl(): string {
return `/campaigns/${this.campaignId}`;
}
}
@@ -0,0 +1,89 @@
import { RuleTrainingSection } from '../../services/rule-training.model';
import {
exceedsBudget, orderByPriority, readProgress, recordOutcome, sectionState, suggestedTitles, writeProgress
} from './rule-training.util';
/** Stockage en mémoire : le test ne dépend pas du navigateur. */
function memoryStorage(initial: Record<string, string> = {}): Storage {
const data = new Map(Object.entries(initial));
return {
getItem: (key: string) => data.get(key) ?? null,
setItem: (key: string, value: string) => { data.set(key, value); },
removeItem: (key: string) => { data.delete(key); },
clear: () => data.clear(),
key: () => null,
get length() { return data.size; }
};
}
const section = (title: string, chars: number, ...suggestedFor: string[]): RuleTrainingSection =>
({ title, chars, suggestedFor });
describe('rule-training.util', () => {
it('note une situation sans modifier la progression reçue', () => {
const start = { Combat: { seen: 2, last: 'known' as const } };
const next = recordOutcome(recordOutcome(start, ' Combat ', 'review'), 'Repos', 'known');
expect(start).toEqual({ Combat: { seen: 2, last: 'known' } });
expect(next).toEqual({ Combat: { seen: 3, last: 'review' }, Repos: { seen: 1, last: 'known' } });
expect(recordOutcome(start, ' ', 'known')).toBe(start);
expect(sectionState(next, 'Combat')).toBe('review');
expect(sectionState(next, 'Repos')).toBe('seen');
expect(sectionState(next, 'Magie')).toBe('new');
});
it('garde une section à revoir tant que la série en cours l’a signalée', () => {
const flagged = recordOutcome({}, 'Combat', 'review');
expect(recordOutcome(flagged, 'Combat', 'known', true)).toEqual({ Combat: { seen: 2, last: 'review' } });
expect(recordOutcome(flagged, 'Combat', 'known')).toEqual({ Combat: { seen: 2, last: 'known' } });
});
it('range la progression par système et ignore un stockage abîmé', () => {
const storage = memoryStorage({
'loremind.ruleTraining.progress.g2': '{"Combat":{"seen":0,"last":"known"},"Repos":{"seen":1,"last":"review"},"X":3}',
'loremind.ruleTraining.progress.g3': 'pas du json',
'loremind.ruleTraining.progress.g4': '[1,2]'
});
writeProgress('g1', { Combat: { seen: 1, last: 'known' } }, storage);
expect(readProgress('g1', storage)).toEqual({ Combat: { seen: 1, last: 'known' } });
expect(readProgress('g2', storage)).toEqual({ Repos: { seen: 1, last: 'review' } });
expect(readProgress('g3', storage)).toEqual({});
expect(readProgress('g4', storage)).toEqual({});
expect(readProgress('inconnu', storage)).toEqual({});
expect(readProgress(null, storage)).toEqual({});
writeProgress(null, { Combat: { seen: 1, last: 'known' } }, storage);
expect(storage).toHaveLength(4);
});
it('envoie les sections à revoir en premier, puis les nouvelles, puis les moins vues', () => {
const progress = {
Combat: { seen: 5, last: 'known' as const },
Magie: { seen: 1, last: 'known' as const },
Repos: { seen: 2, last: 'review' as const }
};
expect(orderByPriority(['Combat', 'Magie', 'Voyage', 'Repos', 'Social'], progress))
.toEqual(['Repos', 'Voyage', 'Social', 'Magie', 'Combat']);
expect(orderByPriority(['B', 'A'], {})).toEqual(['B', 'A']);
});
it('conseille les sections selon les types de scène, sinon toutes', () => {
const sections = [section('Combat', 10, 'ENCOUNTER'), section('Tests', 10, 'GENERIC', 'EVENT'), section('Repos', 10)];
expect(suggestedTitles(sections, ['ENCOUNTER', 'EVENT'])).toEqual(['Combat', 'Tests']);
expect(suggestedTitles(sections, [])).toEqual(['Tests']);
expect(suggestedTitles(sections, ['NPC'])).toEqual(['Combat', 'Tests', 'Repos']);
});
it('signale des sections cochées qui dépassent ce que lit une série', () => {
const sections = [section('A', 30_000), section('B', 9_000), section('C', 6_000), section('D', 500)];
expect(exceedsBudget(sections, new Set(['A', 'B', 'C']))).toBe(false);
expect(exceedsBudget(sections, new Set(['A', 'B', 'C', 'D']))).toBe(true);
expect(exceedsBudget(sections, new Set())).toBe(false);
});
});
@@ -0,0 +1,114 @@
import { RuleTrainingSection } from '../../services/rule-training.model';
/**
* Entraînement aux règles : logique pure de l'écran (progression par section, ordre de
* priorité, sections conseillées).
*
* La progression est rangée dans le navigateur, par système de jeu, comme les épingles de
* l'onglet « Règles » : rien n'est enregistré dans la campagne ni dans le système.
*/
/** Nombre maximal de scènes par série (le Core applique la même borne). */
export const MAX_TRAINING_SCENES = 8;
/** Taille de règles lue par l'IA pour une série (le Core applique la même borne). */
export const MAX_TRAINING_RULES_CHARS = 24_000;
/** Part maximale d'une section dans une série. */
export const MAX_TRAINING_SECTION_CHARS = 9_000;
export type DrillOutcome = 'known' | 'review';
/** Ce que le MJ a fait d'une section : situations vues, et sa dernière note. */
export interface SectionProgress {
seen: number;
last: DrillOutcome;
}
/** Progression par titre de section (le titre survit aux réimports, pas le rang). */
export type TrainingProgress = Record<string, SectionProgress>;
export type SectionState = 'review' | 'new' | 'seen';
const storageKey = (gameSystemId: string) => `loremind.ruleTraining.progress.${gameSystemId}`;
function isProgress(value: unknown): value is SectionProgress {
const v = value as Partial<SectionProgress> | null;
return !!v && typeof v.seen === 'number' && v.seen > 0 && (v.last === 'known' || v.last === 'review');
}
/** Progression enregistrée pour ce système (vide si le stockage est indisponible ou abîmé). */
export function readProgress(gameSystemId: string | null | undefined, storage: Storage = localStorage): TrainingProgress {
if (!gameSystemId) return {};
try {
const parsed: unknown = JSON.parse(storage.getItem(storageKey(gameSystemId)) ?? '{}');
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
return Object.fromEntries(Object.entries(parsed).filter(([, value]) => isProgress(value))) as TrainingProgress;
} catch {
return {};
}
}
export function writeProgress(gameSystemId: string | null | undefined, progress: TrainingProgress,
storage: Storage = localStorage): void {
if (!gameSystemId) return;
try {
storage.setItem(storageKey(gameSystemId), JSON.stringify(progress));
} catch {
// Stockage indisponible (navigation privée…) : la progression vaut pour cet affichage seulement.
}
}
/**
* Note une situation de cette section (ne modifie pas l'objet reçu).
*
* @param flaggedThisSeries la section a déjà reçu un « À revoir » dans la série en cours :
* elle le garde, même si une autre de ses situations est réussie ensuite. Une série
* entièrement réussie, plus tard, lèvera l'étiquette.
*/
export function recordOutcome(progress: TrainingProgress, section: string, outcome: DrillOutcome,
flaggedThisSeries = false): TrainingProgress {
const title = section?.trim();
if (!title) return progress;
const last: DrillOutcome = flaggedThisSeries ? 'review' : outcome;
return { ...progress, [title]: { seen: (progress[title]?.seen ?? 0) + 1, last } };
}
export function sectionState(progress: TrainingProgress, title: string): SectionState {
const entry = progress[title];
if (!entry) return 'new';
return entry.last === 'review' ? 'review' : 'seen';
}
const RANK: Record<SectionState, number> = { review: 0, new: 1, seen: 2 };
/**
* Ordre d'envoi des sections : à revoir d'abord, puis jamais travaillées, puis les moins
* vues. À égalité, l'ordre du livre est conservé. Les premières sont sûres d'être lues
* quand la série ne peut pas tout prendre.
*/
export function orderByPriority(titles: string[], progress: TrainingProgress): string[] {
return titles
.map((title, index) => ({ title, index }))
.sort((a, b) =>
RANK[sectionState(progress, a.title)] - RANK[sectionState(progress, b.title)]
|| (progress[a.title]?.seen ?? 0) - (progress[b.title]?.seen ?? 0)
|| a.index - b.index)
.map(entry => entry.title);
}
/**
* Sections conseillées pour ces types de scène (aucune scène : une scène générique). Si
* aucun titre ne correspond (règles découpées avec des titres maison), toutes le sont.
*/
export function suggestedTitles(sections: RuleTrainingSection[], sceneTypes: string[]): string[] {
const types = new Set(sceneTypes.length ? sceneTypes : ['GENERIC']);
const suggested = sections.filter(s => s.suggestedFor.some(t => types.has(t))).map(s => s.title);
return suggested.length ? suggested : sections.map(s => s.title);
}
/** Les sections cochées dépassent-elles ce qu'une série peut lire ? */
export function exceedsBudget(sections: RuleTrainingSection[], selected: ReadonlySet<string>): boolean {
const total = sections
.filter(s => selected.has(s.title))
.reduce((sum, s) => sum + Math.min(s.chars, MAX_TRAINING_SECTION_CHARS), 0);
return total > MAX_TRAINING_RULES_CHARS;
}
@@ -0,0 +1,45 @@
import { SCENE_BLOCKS, addableBlocks, defaultBlocks, visibleBlocks } from './scene-blocks';
/**
* Éditeur de scène en « noyau + rubriques » : ce qui s'affiche selon le type, ce qui est
* déjà rempli, et ce que l'auteur a demandé. Règle d'or : rien de rempli n'est caché.
*/
describe('scene blocks', () => {
it('proposes the blocks the scene type calls for', () => {
expect(defaultBlocks('ENCOUNTER')).toEqual(['combat', 'battlemap']);
expect(defaultBlocks('LOCATION')).toEqual(['context', 'rooms']);
expect(defaultBlocks('EVENT')).toEqual([]);
expect(defaultBlocks(null)).toEqual(['context']);
});
it('shows a block as soon as it has content, whatever the type', () => {
expect(visibleBlocks('EVENT', [], ['combat', 'illustrations'])).toEqual(['combat', 'illustrations']);
});
it('keeps a block shown during this edit even once emptied', () => {
expect(visibleBlocks('EVENT', ['purpose'], [])).toEqual(['purpose']);
});
it('lists the blocks in display order, without duplicates', () => {
expect(visibleBlocks('LOCATION', ['icon', 'context'], ['rooms', 'combat']))
.toEqual(['context', 'combat', 'rooms', 'icon']);
});
it('opens the block a review link points to, and ignores a core section', () => {
expect(visibleBlocks('EVENT', [], [], 'combat')).toEqual(['combat']);
expect(visibleBlocks('EVENT', [], [], 'rooms')).toEqual(['rooms']);
expect(visibleBlocks('EVENT', [], [], 'narration')).toEqual([]);
});
it('drops the type blocks that stayed empty when the type changes', () => {
expect(visibleBlocks('ENCOUNTER', [], [])).toEqual(['combat', 'battlemap']);
expect(visibleBlocks('REVELATION', [], [])).toEqual([]);
});
it('offers every hidden block, the lore pages only when the campaign has a lore', () => {
const visible = visibleBlocks('ENCOUNTER', [], []);
expect(addableBlocks(visible, true)).toEqual(['context', 'rooms', 'illustrations', 'lore', 'purpose', 'icon']);
expect(addableBlocks(visible, false)).toEqual(['context', 'rooms', 'illustrations', 'purpose', 'icon']);
expect(addableBlocks(SCENE_BLOCKS, true)).toEqual([]);
});
});
@@ -0,0 +1,63 @@
import { SceneType } from '../../services/campaign.model';
import { addableOf, visibleOf } from '../entity-blocks';
/**
* Éditeur de scène en « noyau + rubriques » (logique pure, testée sans Angular ; principe
* commun à toutes les fiches dans `entity-blocks.ts`).
*
* Le NOYAU est toujours là : nom, type, ce qui se passe, narration aux joueurs, notes du MJ,
* choix et sorties. Ce sont les champs que l'appli comprend (relecture, méthodes guidées).
*
* Les RUBRIQUES sont optionnelles, et c'est le TYPE de scène qui choisit celles qu'on
* propose d'office : un combat propose ses ennemis, un lieu ses pièces.
*/
export type SceneBlock =
| 'context' | 'combat' | 'rooms' | 'battlemap' | 'illustrations' | 'lore' | 'purpose' | 'icon';
/** Toutes les rubriques, dans leur ordre d'affichage. */
export const SCENE_BLOCKS: SceneBlock[] =
['context', 'combat', 'rooms', 'battlemap', 'illustrations', 'lore', 'purpose', 'icon'];
/** Titre d'une rubrique : celui de sa section, pour ne pas la nommer de deux façons. */
export const SCENE_BLOCK_LABELS: Record<SceneBlock, string> = {
context: 'sceneEdit.contextSectionTitle',
combat: 'sceneEdit.combatSectionTitle',
rooms: 'sceneEdit.dungeonSectionTitle',
battlemap: 'sceneEdit.battlemapLabel',
illustrations: 'sceneEdit.illustrationsLabel',
lore: 'sceneEdit.loreSectionTitle',
purpose: 'sceneEdit.purposeLabel',
icon: 'sceneEdit.iconLabel'
};
/** Rubriques proposées d'office selon le type de scène. */
const BLOCKS_BY_TYPE: Record<SceneType, SceneBlock[]> = {
GENERIC: ['context'],
LOCATION: ['context', 'rooms'],
ENCOUNTER: ['combat', 'battlemap'],
NPC: ['context'],
EVENT: [],
REVELATION: []
};
/** Rubrique visée par un lien « Corriger » / « Voir » (`?focus=`), si c'en est une. */
const BLOCK_BY_FOCUS: Record<string, SceneBlock> = { combat: 'combat', rooms: 'rooms' };
export function defaultBlocks(type: SceneType | null | undefined): SceneBlock[] {
return BLOCKS_BY_TYPE[type ?? 'GENERIC'] ?? [];
}
/**
* Rubriques à afficher, dans l'ordre : celles du type, celles déjà montrées pendant cette
* édition (remplies au chargement ou ajoutées à la main : elles ne disparaissent pas si on
* les vide), celles qui ont du contenu, et celle que vise le lien d'arrivée.
*/
export function visibleBlocks(type: SceneType | null | undefined, shown: Iterable<SceneBlock>,
filled: Iterable<SceneBlock>, focus: string | null = null): SceneBlock[] {
return visibleOf(SCENE_BLOCKS, defaultBlocks(type), shown, filled, focus ? BLOCK_BY_FOCUS[focus] : null);
}
/** Rubriques encore proposables (les pages du Lore seulement si la campagne a un univers). */
export function addableBlocks(visible: SceneBlock[], hasLore: boolean): SceneBlock[] {
return addableOf(SCENE_BLOCKS, visible, hasLore ? [] : ['lore']);
}
@@ -24,6 +24,9 @@
</div>
</div>
<!-- Rôle de la scène dans la méthode guidée du chapitre : ce que ce temps doit accomplir. -->
<app-guided-role-hint [chapter]="chapter" [scene]="scene"></app-guided-role-hint>
<form [formGroup]="form" (ngSubmit)="submit()" class="edit-form">
<!-- Tout est optionnel sauf le titre : on n'affiche que l'identité, le reste
@@ -39,6 +42,9 @@
[entityType]="'scene'" [entityId]="sceneId" [campaignId]="campaignId"
(applied)="onAssistApplied($event)"></app-entity-assist-panel>
<!-- ═══ NOYAU : toujours visible. Ce sont les champs que l'appli comprend (relecture,
méthodes guidées) : nom, type, ce qui se passe, narration, notes du MJ, choix et sorties. ═══ -->
<!-- Identité -->
<div class="field">
<label for="scene-edit-name">{{ 'sceneEdit.nameLabel' | translate }}</label>
@@ -51,38 +57,6 @@
/>
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.description"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-description"
formControlName="description"
[placeholder]="'sceneEdit.descriptionPlaceholder' | translate"
rows="3">
</textarea>
</div>
<!-- Utilité : ce que l'histoire perd si on coupe la scène (aide à trier et à rythmer). -->
<div class="field">
<div class="field-label-row">
<label for="scene-edit-purpose">{{ 'sceneEdit.purposeLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.purpose"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-purpose"
formControlName="purpose"
[placeholder]="'sceneEdit.purposePlaceholder' | translate"
rows="2">
</textarea>
</div>
<div class="field">
<label>{{ 'sceneEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
<!-- Type narratif du nœud (Niveau 2 — graphe de nœuds typés) -->
<div class="field">
<div class="field-label-row">
@@ -97,137 +71,18 @@
<small class="field-hint">{{ 'sceneEdit.nodeTypeHint' | translate }}</small>
</div>
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'sceneEdit.illustrationsLabel' | translate" icon="🖼️" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event">
</app-image-gallery>
<small class="field-hint">{{ 'sceneEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
<!-- Battlemaps Foundry : LISTE de variantes (Jour/Nuit, étages…), chacune selon
sa source (Dungeon Alchemist = media + .json, DungeonDraft = .dd2vtt unique).
Non affichées dans l'appli (export only). -->
<app-expandable-section [title]="'sceneEdit.battlemapLabel' | translate" icon="🗺️" [filled]="battlemapFilled">
<small class="field-hint">{{ 'sceneEdit.battlemapHint' | translate }}</small>
@for (bm of battlemaps; track $index; let i = $index) {
<div class="battlemap-card">
<div class="battlemap-card-head">
<input class="battlemap-label-input" type="text" [value]="bm.label"
(input)="updateBattlemapLabel(i, $any($event.target).value)"
[placeholder]="'sceneEdit.battlemapLabelPlaceholder' | translate" />
<button type="button" class="battlemap-remove" (click)="removeBattlemap(i)">
{{ 'sceneEdit.battlemapRemoveMap' | translate }}
</button>
</div>
<div class="battlemap-source" role="group" [attr.aria-label]="'sceneEdit.battlemapSourceLabel' | translate">
<button type="button" [class.active]="bm.source === 'DUNGEON_ALCHEMIST'"
(click)="setBattlemapSource(bm, 'DUNGEON_ALCHEMIST')">
{{ 'sceneEdit.battlemapSourceDA' | translate }}
</button>
<button type="button" [class.active]="bm.source === 'DUNGEONDRAFT'"
(click)="setBattlemapSource(bm, 'DUNGEONDRAFT')">
{{ 'sceneEdit.battlemapSourceDD' | translate }}
</button>
</div>
@if (bm.source === 'DUNGEON_ALCHEMIST') {
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingMedia"
(filesDropped)="onBattlemapMediaDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapMedia' | translate }}</span>
@if (bm.mediaFileId) {
<span class="battlemap-file">{{ bm.mediaName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeBattlemapMedia(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingMedia ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept="image/*,video/mp4,video/webm" hidden (change)="onBattlemapMediaSelected(bm, $event)" />
</label>
}
</div>
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingData"
(filesDropped)="onBattlemapDataDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapData' | translate }}</span>
@if (bm.dataFileId) {
<span class="battlemap-file">{{ bm.dataName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeBattlemapData(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingData ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept=".json,.dd2vtt,.uvtt,application/json" hidden (change)="onBattlemapDataSelected(bm, $event)" />
</label>
}
</div>
} @else {
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingData"
(filesDropped)="onDd2vttDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapDd2vttSlot' | translate }}</span>
@if (bm.dataFileId) {
<span class="battlemap-file">{{ bm.dataName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeDd2vtt(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingData ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept=".dd2vtt,.uvtt,application/json" hidden (change)="onDd2vttSelected(bm, $event)" />
</label>
}
</div>
@if (bm.dd2vttNoImage) {
<small class="field-hint battlemap-warn">{{ 'sceneEdit.battlemapDd2vttNoImage' | translate }}</small>
}
<small class="field-hint">{{ 'sceneEdit.battlemapDd2vttHint' | translate }}</small>
}
</div>
}
<button type="button" class="battlemap-add" (click)="addBattlemap()">
+ {{ 'sceneEdit.battlemapAdd' | translate }}
</button>
</app-expandable-section>
<!-- Section : Contexte et ambiance -->
<app-expandable-section [title]="'sceneEdit.contextSectionTitle' | translate" icon="📍" [initiallyOpen]="true" [filled]="contextFilled">
<div class="field-row">
<div class="field">
<div class="field-label-row">
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.setting"></app-writing-coach-trigger>
</div>
<input id="scene-edit-location" type="text" formControlName="location" [placeholder]="'sceneEdit.locationPlaceholder' | translate" />
</div>
<div class="field">
<label for="scene-edit-timing">{{ 'sceneEdit.timingLabel' | translate }}</label>
<input id="scene-edit-timing" type="text" formControlName="timing" [placeholder]="'sceneEdit.timingPlaceholder' | translate" />
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.description"></app-writing-coach-trigger>
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.atmosphere"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-atmosphere"
formControlName="atmosphere"
[placeholder]="'sceneEdit.atmospherePlaceholder' | translate"
rows="4">
</textarea>
</div>
</app-expandable-section>
<textarea
id="scene-edit-description"
formControlName="description"
[placeholder]="'sceneEdit.descriptionPlaceholder' | translate"
rows="3">
</textarea>
</div>
<!-- Section : Narration pour les joueurs -->
<app-expandable-section [title]="'sceneEdit.narrationSectionTitle' | translate" coachTopic="scene.narration" icon="📖" [initiallyOpen]="focusSection === 'narration'" [filled]="narrationFilled">
@@ -335,50 +190,210 @@
}
</app-expandable-section>
<!-- Section : Combat ou rencontre -->
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" coachTopic="scene.combat" icon="⚔️" [initiallyOpen]="focusSection === 'combat'" [filled]="combatFilled">
<div class="field">
<label for="scene-edit-combat-difficulty">{{ 'sceneEdit.combatDifficultyLabel' | translate }}</label>
<input id="scene-edit-combat-difficulty" type="text" formControlName="combatDifficulty" [placeholder]="'sceneEdit.combatDifficultyPlaceholder' | translate" />
</div>
<div class="field">
<label>{{ 'sceneEdit.bestiaryEnemiesLabel' | translate }}</label>
<app-enemy-link-picker
[value]="enemyIds"
<!-- ═══ RUBRIQUES : optionnelles. Affichées si le type de scène les appelle, si elles ont
déjà du contenu ou si l'auteur les a demandées (voir scene-blocks.ts et campaigns/entity-blocks.ts). ═══ -->
@if (shows('context')) {
<!-- Section : Contexte et ambiance -->
<app-expandable-section [title]="'sceneEdit.contextSectionTitle' | translate" icon="📍" [initiallyOpen]="contextFilled || blocks.isAdded('context')" [filled]="contextFilled">
<div class="field-row">
<div class="field">
<div class="field-label-row">
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.setting"></app-writing-coach-trigger>
</div>
<input id="scene-edit-location" type="text" formControlName="location" [placeholder]="'sceneEdit.locationPlaceholder' | translate" />
</div>
<div class="field">
<label for="scene-edit-timing">{{ 'sceneEdit.timingLabel' | translate }}</label>
<input id="scene-edit-timing" type="text" formControlName="timing" [placeholder]="'sceneEdit.timingPlaceholder' | translate" />
</div>
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.atmosphere"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-atmosphere"
formControlName="atmosphere"
[placeholder]="'sceneEdit.atmospherePlaceholder' | translate"
rows="4">
</textarea>
</div>
</app-expandable-section>
}
@if (shows('combat')) {
<!-- Section : Combat ou rencontre -->
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" coachTopic="scene.combat" icon="⚔️" [initiallyOpen]="focusSection === 'combat' || blocks.isAdded('combat')" [filled]="combatFilled">
<div class="field">
<label for="scene-edit-combat-difficulty">{{ 'sceneEdit.combatDifficultyLabel' | translate }}</label>
<input id="scene-edit-combat-difficulty" type="text" formControlName="combatDifficulty" [placeholder]="'sceneEdit.combatDifficultyPlaceholder' | translate" />
</div>
<div class="field">
<label>{{ 'sceneEdit.bestiaryEnemiesLabel' | translate }}</label>
<app-enemy-link-picker
[value]="enemyIds"
[availableEnemies]="availableEnemies"
[campaignId]="campaignId"
(valueChange)="enemyIds = $event">
</app-enemy-link-picker>
<small class="field-hint">
{{ 'sceneEdit.bestiaryEnemiesHint' | translate }}
</small>
</div>
<div class="field">
<label for="scene-edit-enemies">{{ 'sceneEdit.enemiesLabel' | translate }}</label>
<textarea
id="scene-edit-enemies"
formControlName="enemies"
[placeholder]="'sceneEdit.enemiesPlaceholder' | translate"
rows="4">
</textarea>
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-tactics">{{ 'sceneEdit.tacticsLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.tactics"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-tactics"
formControlName="tactics"
[placeholder]="'sceneEdit.tacticsPlaceholder' | translate"
rows="3">
</textarea>
</div>
</app-expandable-section>
}
@if (shows('rooms')) {
<!-- Lieu explorable : pièces / donjon -->
<app-expandable-section [title]="'sceneEdit.dungeonSectionTitle' | translate" icon="🏰" [initiallyOpen]="rooms.length > 0 || focusSection === 'rooms' || blocks.isAdded('rooms')" [filled]="dungeonFilled">
<small class="field-hint">
{{ 'sceneEdit.dungeonHint' | translate }}
</small>
<app-rooms-editor
[rooms]="rooms"
[availableEnemies]="availableEnemies"
[campaignId]="campaignId"
(valueChange)="enemyIds = $event">
</app-enemy-link-picker>
<small class="field-hint">
{{ 'sceneEdit.bestiaryEnemiesHint' | translate }}
</small>
</div>
<div class="field">
<label for="scene-edit-enemies">{{ 'sceneEdit.enemiesLabel' | translate }}</label>
<textarea
id="scene-edit-enemies"
formControlName="enemies"
[placeholder]="'sceneEdit.enemiesPlaceholder' | translate"
rows="4">
</textarea>
</div>
<div class="field">
<div class="field-label-row">
<label for="scene-edit-tactics">{{ 'sceneEdit.tacticsLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.tactics"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-tactics"
formControlName="tactics"
[placeholder]="'sceneEdit.tacticsPlaceholder' | translate"
rows="3">
</textarea>
</div>
</app-expandable-section>
(roomsChange)="onRoomsChange($event)">
</app-rooms-editor>
</app-expandable-section>
}
@if (shows('battlemap')) {
<!-- Battlemaps Foundry : LISTE de variantes (Jour/Nuit, étages…), chacune selon
sa source (Dungeon Alchemist = media + .json, DungeonDraft = .dd2vtt unique).
Non affichées dans l'appli (export only). -->
<app-expandable-section [title]="'sceneEdit.battlemapLabel' | translate" icon="🗺️" [initiallyOpen]="blocks.isAdded('battlemap')" [filled]="battlemapFilled">
<small class="field-hint">{{ 'sceneEdit.battlemapHint' | translate }}</small>
@for (bm of battlemaps; track $index; let i = $index) {
<div class="battlemap-card">
<div class="battlemap-card-head">
<input class="battlemap-label-input" type="text" [value]="bm.label"
(input)="updateBattlemapLabel(i, $any($event.target).value)"
[placeholder]="'sceneEdit.battlemapLabelPlaceholder' | translate" />
<button type="button" class="battlemap-remove" (click)="removeBattlemap(i)">
{{ 'sceneEdit.battlemapRemoveMap' | translate }}
</button>
</div>
<div class="battlemap-source" role="group" [attr.aria-label]="'sceneEdit.battlemapSourceLabel' | translate">
<button type="button" [class.active]="bm.source === 'DUNGEON_ALCHEMIST'"
(click)="setBattlemapSource(bm, 'DUNGEON_ALCHEMIST')">
{{ 'sceneEdit.battlemapSourceDA' | translate }}
</button>
<button type="button" [class.active]="bm.source === 'DUNGEONDRAFT'"
(click)="setBattlemapSource(bm, 'DUNGEONDRAFT')">
{{ 'sceneEdit.battlemapSourceDD' | translate }}
</button>
</div>
@if (bm.source === 'DUNGEON_ALCHEMIST') {
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingMedia"
(filesDropped)="onBattlemapMediaDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapMedia' | translate }}</span>
@if (bm.mediaFileId) {
<span class="battlemap-file">{{ bm.mediaName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeBattlemapMedia(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingMedia ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept="image/*,video/mp4,video/webm" hidden (change)="onBattlemapMediaSelected(bm, $event)" />
</label>
}
</div>
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingData"
(filesDropped)="onBattlemapDataDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapData' | translate }}</span>
@if (bm.dataFileId) {
<span class="battlemap-file">{{ bm.dataName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeBattlemapData(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingData ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept=".json,.dd2vtt,.uvtt,application/json" hidden (change)="onBattlemapDataSelected(bm, $event)" />
</label>
}
</div>
} @else {
<div class="battlemap-slot"
appFileDrop [dropDisabled]="bm.uploadingData"
(filesDropped)="onDd2vttDropped(bm, $event)">
<span class="battlemap-slot-label">{{ 'sceneEdit.battlemapDd2vttSlot' | translate }}</span>
@if (bm.dataFileId) {
<span class="battlemap-file">{{ bm.dataName || ('sceneEdit.battlemapAttached' | translate) }}</span>
<button type="button" class="battlemap-remove" (click)="removeDd2vtt(bm)">
{{ 'sceneEdit.battlemapRemove' | translate }}
</button>
} @else {
<label class="battlemap-pick">
{{ (bm.uploadingData ? 'sceneEdit.battlemapUploading' : 'sceneEdit.battlemapChoose') | translate }}
<input type="file" accept=".dd2vtt,.uvtt,application/json" hidden (change)="onDd2vttSelected(bm, $event)" />
</label>
}
</div>
@if (bm.dd2vttNoImage) {
<small class="field-hint battlemap-warn">{{ 'sceneEdit.battlemapDd2vttNoImage' | translate }}</small>
}
<small class="field-hint">{{ 'sceneEdit.battlemapDd2vttHint' | translate }}</small>
}
</div>
}
<button type="button" class="battlemap-add" (click)="addBattlemap()">
+ {{ 'sceneEdit.battlemapAdd' | translate }}
</button>
</app-expandable-section>
}
@if (shows('illustrations')) {
<!-- Illustrations (galerie editable, rendu editorial) -->
<app-expandable-section [title]="'sceneEdit.illustrationsLabel' | translate" icon="🖼️" [initiallyOpen]="blocks.isAdded('illustrations')" [filled]="illustrationsFilled">
<app-image-gallery
[imageIds]="illustrationImageIds"
[editable]="true"
[layout]="'EDITORIAL'"
(imageIdsChange)="illustrationImageIds = $event"
[placements]="illustrationPlacements"
(placementsChange)="illustrationPlacements = $event">
</app-image-gallery>
<small class="field-hint">{{ 'sceneEdit.illustrationsHint' | translate }}</small>
</app-expandable-section>
}
<!-- Section : Pages Lore associées (B2 cross-context) -->
@if (loreId) {
<app-expandable-section [title]="'sceneEdit.loreSectionTitle' | translate" icon="🔗" [filled]="loreFilled">
@if (loreId && shows('lore')) {
<app-expandable-section [title]="'sceneEdit.loreSectionTitle' | translate" icon="🔗" [initiallyOpen]="blocks.isAdded('lore')" [filled]="loreFilled">
<div class="field">
<app-lore-link-picker
[value]="relatedPageIds"
@@ -393,6 +408,32 @@
</app-expandable-section>
}
@if (shows('purpose')) {
<!-- Utilité : ce que l'histoire perd si on coupe la scène (aide à trier et à rythmer). -->
<div class="field">
<div class="field-label-row">
<label for="scene-edit-purpose">{{ 'sceneEdit.purposeLabel' | translate }}</label>
<app-writing-coach-trigger topic="scene.purpose"></app-writing-coach-trigger>
</div>
<textarea
id="scene-edit-purpose"
formControlName="purpose"
[placeholder]="'sceneEdit.purposePlaceholder' | translate"
rows="2">
</textarea>
</div>
}
@if (shows('icon')) {
<div class="field">
<label>{{ 'sceneEdit.iconLabel' | translate }}</label>
<app-icon-picker [options]="campaignIconOptions" [(selected)]="selectedIcon"></app-icon-picker>
</div>
}
<!-- Rubriques encore disponibles : on n'ajoute que ce dont la fiche a besoin. -->
<app-block-adder [choices]="addableBlocks" (add)="addBlock($event)"></app-block-adder>
@if (!loreId) {
<div class="field">
<small class="field-hint">
@@ -400,20 +441,6 @@
</small>
</div>
}
<!-- Lieu explorable : pièces / donjon -->
<app-expandable-section [title]="'sceneEdit.dungeonSectionTitle' | translate" icon="🏰" [initiallyOpen]="rooms.length > 0 || focusSection === 'rooms'" [filled]="dungeonFilled">
<small class="field-hint">
{{ 'sceneEdit.dungeonHint' | translate }}
</small>
<app-rooms-editor
[rooms]="rooms"
[availableEnemies]="availableEnemies"
[campaignId]="campaignId"
(roomsChange)="onRoomsChange($event)">
</app-rooms-editor>
</app-expandable-section>
</form>
</div>
@@ -15,15 +15,20 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Scene, SceneBattlemap, SceneBranch, Room, SceneType, LinkType } from '../../../services/campaign.model';
import { Chapter, Scene, SceneBattlemap, SceneBranch, Room, SceneType, LinkType, ImagePlacement } from '../../../services/campaign.model';
import { Page } from '../../../services/page.model';
import { Enemy } from '../../../services/enemy.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
import { GuidedRoleHintComponent } from '../../guided/guided-role-hint.component';
import { BlockChoice, BlockState, choicesOf, filledOf } from '../../entity-blocks';
import { SCENE_BLOCK_LABELS, SceneBlock, addableBlocks, visibleBlocks } from '../scene-blocks';
import { BlockAdderComponent } from '../../../shared/block-adder/block-adder.component';
import { ExpandableSectionComponent } from '../../../shared/expandable-section/expandable-section.component';
import { LoreLinkPickerComponent } from '../../../shared/lore-link-picker/lore-link-picker.component';
import { EnemyLinkPickerComponent } from '../../../shared/enemy-link-picker/enemy-link-picker.component';
import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-drawer.component';
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
import { prunePlacements } from '../../../shared/image-placements/image-placement';
import { IconPickerComponent } from '../../../shared/icon-picker/icon-picker.component';
import { RoomsEditorComponent } from '../../../shared/rooms-editor/rooms-editor.component';
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
@@ -65,7 +70,7 @@ interface BattlemapEdit {
*/
@Component({
selector: 'app-scene-edit',
imports: [ReactiveFormsModule, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
imports: [ReactiveFormsModule, BlockAdderComponent, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent, GuidedRoleHintComponent],
templateUrl: './scene-edit.component.html',
styleUrls: ['./scene-edit.component.scss']
})
@@ -95,6 +100,8 @@ export class SceneEditComponent implements OnInit {
chapterId = '';
sceneId = '';
scene: Scene | null = null;
/** Chapitre de la scène : il porte la méthode guidée dont la scène tient un rôle. */
chapter: Chapter | null = null;
/**
* Section à déplier d'office (query param `?focus=combat|branches|rooms|narration|choices`) — posé par
@@ -109,6 +116,8 @@ export class SceneEditComponent implements OnInit {
availableEnemies: Enemy[] = [];
enemyIds: string[] = [];
illustrationImageIds: string[] = [];
/** Placement choisi pour certaines illustrations dans le livret PDF (bind sur app-image-gallery). */
illustrationPlacements: Record<string, ImagePlacement> = {};
/**
* Battlemaps Foundry de la scene : une entree par variante (Jour/Nuit, etage…).
@@ -159,6 +168,40 @@ export class SceneEditComponent implements OnInit {
get loreFilled(): boolean { return this.relatedPageIds.length > 0; }
get dungeonFilled(): boolean { return this.rooms.length > 0; }
// ─────────────── Noyau + rubriques (voir scene-blocks.ts, campaigns/entity-blocks.ts) ───────────────
// Le noyau est toujours affiché ; une rubrique ne l'est que si le type de scène l'appelle,
// si elle a du contenu ou si l'auteur l'a demandée. Les autres attendent dans « Ajouter ».
readonly blocks = new BlockState<SceneBlock>();
private get filledBlocks(): SceneBlock[] {
return filledOf<SceneBlock>({
context: this.contextFilled,
combat: this.combatFilled,
rooms: this.dungeonFilled,
battlemap: this.battlemapFilled,
illustrations: this.illustrationsFilled,
lore: this.loreFilled,
purpose: !!this.form.value.purpose,
icon: !!this.selectedIcon
});
}
get visibleBlocks(): SceneBlock[] {
return visibleBlocks(this.form.value.type, this.blocks.shownBlocks, this.filledBlocks, this.focusSection);
}
get addableBlocks(): BlockChoice[] {
return choicesOf(addableBlocks(this.visibleBlocks, !!this.loreId), SCENE_BLOCK_LABELS);
}
shows(block: SceneBlock): boolean {
return this.visibleBlocks.includes(block);
}
addBlock(id: string): void {
this.blocks.add(id as SceneBlock);
}
constructor(
private fb: FormBuilder,
private route: ActivatedRoute,
@@ -237,6 +280,7 @@ export class SceneEditComponent implements OnInit {
takeUntilDestroyed(this.destroyRef)
).subscribe(({ campaign, allCampaigns, scene, chapterScenes, treeData, pages, loreId }) => {
this.scene = scene;
this.chapter = (treeData.chaptersByArc[this.arcId] ?? []).find(c => c.id === this.chapterId) ?? null;
this.pageTitleService.set(scene.name);
this.loreId = loreId;
this.availablePages = pages;
@@ -245,6 +289,7 @@ export class SceneEditComponent implements OnInit {
this.enemyIds = [...(scene.enemyIds ?? [])];
this.selectedIcon = scene.icon ?? null;
this.illustrationImageIds = [...(scene.illustrationImageIds ?? [])];
this.illustrationPlacements = { ...(scene.illustrationPlacements ?? {}) };
this.battlemaps = (scene.battlemaps ?? []).map(bm => {
const entry: BattlemapEdit = {
label: bm.label ?? '',
@@ -288,6 +333,8 @@ export class SceneEditComponent implements OnInit {
tactics: scene.tactics ?? '',
purpose: scene.purpose ?? ''
});
// Ce qui a déjà du contenu reste affiché pendant toute l'édition, même une fois vidé.
this.blocks.reset(this.filledBlocks);
this.layoutService.show(buildCampaignSidebarConfig(campaign, allCampaigns, treeData, this.campaignId, this.translate));
});
@@ -314,6 +361,7 @@ export class SceneEditComponent implements OnInit {
enemyIds: this.enemyIds,
relatedPageIds: this.relatedPageIds,
illustrationImageIds: this.illustrationImageIds,
illustrationPlacements: prunePlacements(this.illustrationPlacements, this.illustrationImageIds),
// Seules les cartes portant au moins un fichier sont persistees (une entree
// ajoutee puis laissee vide n'est pas une carte).
battlemaps: this.battlemaps
@@ -21,6 +21,7 @@
</button>
</div>
</header>
<app-guided-role-hint [chapter]="chapter" [scene]="scene" [chapterLink]="structureLink"></app-guided-role-hint>
<!-- Illustrations (rendu editorial magazine) -->
@if ((scene.illustrationImageIds?.length ?? 0) > 0) {
<section class="view-section">
@@ -36,8 +36,8 @@
font-size: 0.78rem;
padding: 0.15rem 0.55rem;
border-radius: 999px;
background: rgba(66, 133, 244, 0.1);
color: #2c6cd6;
background: rgba(66, 133, 244, 0.15);
color: #93c5fd; // bleu clair : lisible sur la carte sombre
}
.room-readonly-desc {
@@ -14,7 +14,8 @@ import { EnemyService } from '../../../services/enemy.service';
import { PageService } from '../../../services/page.service';
import { LayoutService } from '../../../services/layout.service';
import { PageTitleService } from '../../../services/page-title.service';
import { Scene, Room } from '../../../services/campaign.model';
import { Chapter, Scene, Room } from '../../../services/campaign.model';
import { GuidedRoleHintComponent } from '../../guided/guided-role-hint.component';
import { Page } from '../../../services/page.model';
import { Enemy } from '../../../services/enemy.model';
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
@@ -27,7 +28,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
*/
@Component({
selector: 'app-scene-view',
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe],
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedRoleHintComponent],
templateUrl: './scene-view.component.html',
styleUrls: ['./scene-view.component.scss']
})
@@ -41,6 +42,10 @@ export class SceneViewComponent implements OnInit {
chapterId = '';
sceneId = '';
scene: Scene | null = null;
/** Chapitre de la scène : il porte la méthode guidée dont la scène tient un rôle. */
chapter: Chapter | null = null;
/** Où voir toute la méthode : la quête dont ce chapitre est le conteneur, sinon le chapitre. */
structureLink: string[] = [];
loreId: string | null = null;
availablePages: Page[] = [];
@@ -95,6 +100,12 @@ export class SceneViewComponent implements OnInit {
})
).subscribe(({ campaign, allCampaigns, scene, treeData, pages, loreId }) => {
this.scene = scene;
this.chapter = (treeData.chaptersByArc[this.arcId] ?? []).find(c => c.id === this.chapterId) ?? null;
const quest = (treeData.quests ?? []).find(q =>
(q.nodes ?? []).some(n => n.nodeType === 'CHAPTER' && n.nodeId === this.chapterId));
this.structureLink = quest
? ['/campaigns', this.campaignId, 'quests', quest.id ?? '']
: ['/campaigns', this.campaignId, 'arcs', this.arcId, 'chapters', this.chapterId];
this.loreId = loreId;
this.availablePages = pages;
this.availableEnemies = treeData.enemies ?? [];
@@ -0,0 +1,79 @@
@if (visible) {
<section class="sheet-spells">
<h2>
<lucide-icon [img]="WandSparkles" [size]="16"></lucide-icon>
{{ 'sheetSpells.title' | translate }}
</h2>
@if (mode === 'view') {
<app-spell-list [spells]="known" [fields]="fields"></app-spell-list>
} @else {
<p class="sheet-spells-hint">{{ 'sheetSpells.hint' | translate }}</p>
@if (loadFailed) {
<p class="sheet-spells-error" role="alert">{{ 'sheetSpells.loadFailed' | translate }}</p>
} @else {
@if (known.length > 0) {
<ul class="sheet-spells-known">
@for (spell of known; track spell.id) {
<li class="known-chip">
@if (spell.level?.trim()) {
<span class="known-level">{{ spell.level }}</span>
}
<span class="known-name">{{ spell.name }}</span>
<button type="button" class="known-remove" (click)="remove(spell)"
[title]="'sheetSpells.remove' | translate:{ name: spell.name }"
[attr.aria-label]="'sheetSpells.remove' | translate:{ name: spell.name }">
<lucide-icon [img]="X" [size]="13"></lucide-icon>
</button>
</li>
}
</ul>
} @else {
<p class="sheet-spells-hint">{{ 'sheetSpells.none' | translate }}</p>
}
<div class="sheet-spells-search">
<lucide-icon [img]="Search" [size]="14"></lucide-icon>
<input type="search" [(ngModel)]="query" name="sheet-spell-query"
[placeholder]="'sheetSpells.addPlaceholder' | translate"
[attr.aria-label]="'sheetSpells.addPlaceholder' | translate" />
</div>
@if (addable; as spells) {
@if (spells.length > 0) {
<ul class="sheet-spells-add">
@for (spell of spells.slice(0, maxSuggestions); track spell.id) {
<li>
<button type="button" class="add-spell" (click)="add(spell)">
<lucide-icon [img]="Plus" [size]="13"></lucide-icon>
@if (spell.level?.trim()) {
<span class="known-level">{{ spell.level }}</span>
}
<span class="add-name">{{ spell.name }}</span>
@if (spell.school?.trim()) {
<span class="add-school">{{ spell.school }}</span>
}
</button>
</li>
}
</ul>
@if (spells.length > maxSuggestions) {
<p class="sheet-spells-hint">
{{ 'sheetSpells.more' | translate:{ count: spells.length - maxSuggestions } }}
</p>
}
} @else {
<p class="sheet-spells-hint">
{{ (query.trim() ? 'sheetSpells.noMatch' : 'sheetSpells.allKnown') | translate }}
</p>
}
}
@if (saveFailed) {
<p class="sheet-spells-error" role="alert">{{ 'sheetSpells.saveFailed' | translate }}</p>
}
}
}
</section>
}
@@ -0,0 +1,130 @@
.sheet-spells {
display: flex;
flex-direction: column;
gap: 0.65rem;
margin-top: 1.5rem;
padding-top: 1.25rem;
border-top: 1px solid #1f2937;
h2 {
display: flex;
align-items: center;
gap: 0.45rem;
margin: 0;
color: white;
font-size: 1rem;
font-weight: 600;
}
}
.sheet-spells-hint {
margin: 0;
color: #6b7280;
font-size: 0.85rem;
}
.sheet-spells-error {
margin: 0;
color: #fca5a5;
font-size: 0.85rem;
}
// --- Sorts connus (édition) --------------------------------------------------
.sheet-spells-known,
.sheet-spells-add {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.known-chip {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.25rem 0.3rem 0.25rem 0.55rem;
background: rgba(108, 99, 255, 0.14);
border: 1px solid rgba(108, 99, 255, 0.45);
border-radius: 999px;
}
.known-level {
padding: 0 0.4rem;
border-radius: 999px;
background: rgba(108, 99, 255, 0.25);
color: #ddd6fe;
font-size: 0.7rem;
font-weight: 700;
white-space: nowrap;
}
.known-name {
color: white;
font-size: 0.88rem;
font-weight: 500;
}
.known-remove {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.4rem;
height: 1.4rem;
background: transparent;
border: none;
border-radius: 999px;
color: #9ca3af;
cursor: pointer;
&:hover { color: #fca5a5; background: rgba(255, 255, 255, 0.06); }
}
// --- Ajout depuis le catalogue ------------------------------------------------
.sheet-spells-search {
display: flex;
align-items: center;
gap: 0.4rem;
max-width: 24rem;
padding: 0 0.6rem;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 8px;
color: #6b7280;
&:focus-within { border-color: #a78bfa; }
input {
flex: 1;
min-width: 0;
padding: 0.45rem 0;
background: transparent;
border: none;
outline: none;
color: #e5e7eb;
font-size: 0.9rem;
font-family: inherit;
}
}
.add-spell {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.25rem 0.6rem;
background: transparent;
border: 1px dashed #374151;
border-radius: 999px;
color: #d1d5db;
font-size: 0.85rem;
font-family: inherit;
cursor: pointer;
&:hover { border-color: #a78bfa; border-style: solid; color: white; }
}
.add-school {
color: #6b7280;
font-size: 0.75rem;
}
@@ -0,0 +1,148 @@
import { Component, Input, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, Plus, Search, WandSparkles, X } from 'lucide-angular';
import { Observable, Subscription, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { CampaignSpellsService, SpellSheet } from '../../services/campaign-spells.service';
import { Spell } from '../../services/spell.model';
import { TemplateField } from '../../services/template.model';
import { SpellListComponent } from '../../shared/spell-list/spell-list.component';
import { MAX_SUGGESTIONS, addableSpells, knownSpells, sameIds } from './sheet-spells.util';
/**
* Sorts connus d'une fiche (PJ, PNJ ou ennemi), choisis dans le catalogue du système de la
* campagne.
*
* `mode="view"` les donne à lire ; `mode="edit"` permet d'en ajouter et d'en retirer. En
* édition rien n'est enregistré ici : l'écran de la fiche appelle {@link save} une fois la
* fiche enregistrée, y compris pour une fiche tout juste créée.
*
* Le bloc ne s'affiche pas quand le système n'a pas de catalogue (ou, en lecture, quand la
* fiche ne connaît aucun sort) : les fiches des systèmes sans magie restent comme avant.
*/
@Component({
selector: 'app-sheet-spells',
imports: [FormsModule, TranslatePipe, LucideAngularModule, SpellListComponent],
templateUrl: './sheet-spells.component.html',
styleUrls: ['./sheet-spells.component.scss']
})
export class SheetSpellsComponent implements OnChanges, OnDestroy {
readonly Plus = Plus;
readonly Search = Search;
readonly WandSparkles = WandSparkles;
readonly X = X;
readonly maxSuggestions = MAX_SUGGESTIONS;
@Input() campaignId: string | null = null;
@Input() sheet: SpellSheet = 'character';
/** Identifiant de la fiche ; absent pendant sa création. */
@Input() ownerId: string | null = null;
@Input() mode: 'view' | 'edit' = 'view';
catalogue: Spell[] = [];
fields: TemplateField[] = [];
/** Sorts connus, dans l'ordre choisi. */
spellIds: string[] = [];
query = '';
/** Les sorts connus n'ont pas pu être lus : on ne les enregistre pas, pour ne pas les effacer. */
loadFailed = false;
saveFailed = false;
/** Sorts connus tels que lus sur le serveur (null tant qu'ils ne l'ont pas été). */
private savedIds: string[] | null = null;
private catalogueSub: Subscription | null = null;
private knownSub: Subscription | null = null;
constructor(private service: CampaignSpellsService) {}
ngOnChanges(changes: SimpleChanges): void {
if (changes['campaignId']) this.loadCatalogue();
if (changes['ownerId'] || changes['sheet']) this.loadKnown();
}
ngOnDestroy(): void {
this.catalogueSub?.unsubscribe();
this.knownSub?.unsubscribe();
}
private loadCatalogue(): void {
this.catalogueSub?.unsubscribe();
this.catalogue = [];
this.fields = [];
if (!this.campaignId) return;
this.catalogueSub = this.service.catalogue(this.campaignId).subscribe(result => {
this.catalogue = result.spells;
this.fields = result.template;
});
}
private loadKnown(): void {
this.knownSub?.unsubscribe();
this.loadFailed = false;
this.saveFailed = false;
this.spellIds = [];
// Fiche en cours de création : elle ne connaît encore aucun sort.
this.savedIds = this.ownerId ? null : [];
if (!this.ownerId) return;
this.knownSub = this.service.known(this.sheet, this.ownerId).subscribe({
next: ids => {
this.savedIds = ids;
this.spellIds = [...ids];
},
error: () => { this.loadFailed = true; }
});
}
// ─────────────── Lecture ───────────────
get known(): Spell[] {
return knownSpells(this.catalogue, this.spellIds);
}
/** Le bloc a-t-il quelque chose à montrer ? */
get visible(): boolean {
if (this.catalogue.length === 0) return false;
return this.mode === 'edit' || this.known.length > 0;
}
// ─────────────── Édition ───────────────
/** Sorts proposés à l'ajout (les premiers seulement : la recherche affine). */
get addable(): Spell[] {
return addableSpells(this.catalogue, this.spellIds, this.query);
}
add(spell: Spell): void {
if (!spell.id || this.spellIds.includes(String(spell.id))) return;
this.spellIds = [...this.spellIds, String(spell.id)];
this.query = '';
}
remove(spell: Spell): void {
this.spellIds = this.spellIds.filter(id => id !== String(spell.id));
}
/**
* Enregistre les sorts connus de la fiche `ownerId` (celle qui vient d'être enregistrée ou
* créée). Renvoie `false` si l'enregistrement a échoué ; `true` sinon, y compris quand il
* n'y avait rien à enregistrer.
*/
save(ownerId: string | null | undefined): Observable<boolean> {
this.saveFailed = false;
// Rien à faire : pas de catalogue, sorts connus jamais lus, ou liste inchangée.
if (!ownerId || this.catalogue.length === 0 || this.savedIds === null || sameIds(this.savedIds, this.spellIds)) {
return of(true);
}
return this.service.saveKnown(this.sheet, ownerId, this.spellIds).pipe(
map(ids => {
this.savedIds = ids;
return true;
}),
catchError(() => {
this.saveFailed = true;
return of(false);
})
);
}
}
@@ -0,0 +1,38 @@
import { Spell } from '../../services/spell.model';
import { addableSpells, knownSpells, sameIds } from './sheet-spells.util';
const spell = (id: string | null, name: string, extra: Partial<Spell> = {}): Spell =>
({ id, name, values: {}, ...extra });
const CATALOGUE = [
spell('1', 'Éclair de givre', { level: 'Rang 1', school: 'Tempête' }),
spell('2', 'Voile de brume', { level: 'Rang 1', school: 'Voile' }),
spell('3', 'Tempête de cendres', { level: 'Rang 3', school: 'Tempête' }),
spell(null, 'Pas encore enregistré')
];
describe('sheet-spells.util', () => {
it('retrouve les sorts connus dans l\'ordre choisi, sans ceux qui ont quitté le catalogue', () => {
expect(knownSpells(CATALOGUE, ['3', '99', '1']).map(s => s.name)).toEqual(['Tempête de cendres', 'Éclair de givre']);
expect(knownSpells(CATALOGUE, [])).toEqual([]);
expect(knownSpells([], ['1'])).toEqual([]);
});
it('propose à l\'ajout les sorts pas encore connus, cherchés par nom, niveau ou école', () => {
const names = (ids: string[], query: string) => addableSpells(CATALOGUE, ids, query).map(s => s.name);
expect(names([], '')).toEqual(['Éclair de givre', 'Voile de brume', 'Tempête de cendres']);
expect(names(['2'], '')).toEqual(['Éclair de givre', 'Tempête de cendres']);
expect(names([], ' TEMPÊTE ')).toEqual(['Éclair de givre', 'Tempête de cendres']);
expect(names([], 'rang 3')).toEqual(['Tempête de cendres']);
expect(names(['1', '2', '3'], '')).toEqual([]);
expect(names([], 'zzz')).toEqual([]);
});
it('compare deux listes de sorts connus, ordre compris', () => {
expect(sameIds(['1', '2'], ['1', '2'])).toBe(true);
expect(sameIds(['1', '2'], ['2', '1'])).toBe(false);
expect(sameIds(['1'], ['1', '2'])).toBe(false);
expect(sameIds([], [])).toBe(true);
});
});
@@ -0,0 +1,31 @@
import { Spell } from '../../services/spell.model';
/**
* Sorts connus d'une fiche : logique pure (sorts retrouvés dans le catalogue, sorts à
* proposer à l'ajout).
*/
/** Nombre de sorts proposés à l'ajout sans défilement. */
export const MAX_SUGGESTIONS = 8;
/**
* Sorts connus, dans l'ordre choisi. Un identifiant absent du catalogue (sort d'un autre
* système, après un changement de système de la campagne) est laissé de côté.
*/
export function knownSpells(catalogue: Spell[], spellIds: string[]): Spell[] {
const byId = new Map(catalogue.filter(s => s.id).map(s => [String(s.id), s]));
return spellIds.map(id => byId.get(id)).filter((s): s is Spell => !!s);
}
/** Sorts du catalogue que la fiche ne connaît pas encore et qui correspondent à la recherche. */
export function addableSpells(catalogue: Spell[], spellIds: string[], query: string): Spell[] {
const known = new Set(spellIds);
const needle = query.trim().toLowerCase();
return catalogue.filter(s => s.id && !known.has(String(s.id))
&& (!needle || [s.name, s.level, s.school].some(text => (text ?? '').toLowerCase().includes(needle))));
}
/** Deux listes d'identifiants sont-elles les mêmes, dans le même ordre ? */
export function sameIds(a: string[], b: string[]): boolean {
return a.length === b.length && a.every((id, index) => id === b[index]);
}
@@ -28,6 +28,41 @@ export function remarkAction(remark: WritingRemark, campaignId: string): GapActi
}
}
/** Méthode guidée qui répond à une remarque : son identifiant et où l'ouvrir. */
export interface RemarkMethodHint {
methodId: string;
action: GapAction;
}
/**
* Pont de la relecture vers les méthodes guidées : certaines remarques décrivent exactement
* le problème qu'une méthode résout. Dans un chapitre, le lien ouvre sa vue avec la méthode
* proposée (elle se pose sur les scènes déjà écrites) ; sinon il ouvre l'assistant.
* Le Core signale un chapitre qui suit déjà une méthode par le paramètre `guidedMethod`.
*/
export function remarkMethodHint(remark: WritingRemark, campaignId: string): RemarkMethodHint | null {
const methodId = METHOD_BY_RULE[remark.ruleId];
// Chapitre qui suit déjà une méthode : on ne lui en conseille pas une autre.
if (!methodId || remark.params?.['guidedMethod']) return null;
const base = ['/campaigns', campaignId];
if (remark.arcId && remark.chapterId) {
return {
methodId,
action: { link: [...base, 'arcs', remark.arcId, 'chapters', remark.chapterId], queryParams: { method: methodId } }
};
}
return { methodId, action: { link: [...base, 'guided', methodId] } };
}
/** Méthode guidée conseillée selon la règle (clé = ruleId complet). */
const METHOD_BY_RULE: Record<string, string> = {
'WRITE-003-SINGLE-CLUE': 'investigation',
'WRITE-012-CHOKEPOINT': 'investigation',
'WRITE-014-NO-PROACTIVE': 'investigation',
'WRITE-015-SAME-SOURCE-CLUES': 'investigation',
'WRITE-016-NPC-NO-MOTIVATION': 'villain-plan'
};
/** Section de l'éditeur à déplier selon la règle (clé = ruleId complet). */
const FOCUS_BY_RULE: Record<string, string> = {
'WRITE-002-FAKE-CHOICE': 'branches',
@@ -41,5 +76,7 @@ const FOCUS_BY_RULE: Record<string, string> = {
'WRITE-012-CHOKEPOINT': 'choices',
'WRITE-013-LINEAR-DUNGEON': 'rooms',
'WRITE-015-SAME-SOURCE-CLUES': 'branches',
'WRITE-017-SINGLE-HOOK': 'hooks'
'WRITE-017-SINGLE-HOOK': 'hooks',
'WRITE-019-TRIAL-IS-COMBAT': 'combat',
'WRITE-020-CONCLUSION-FEW-CLUES': 'branches'
};
@@ -9,198 +9,372 @@
<lucide-icon [img]="Dices" [size]="22"></lucide-icon>
{{ (id ? 'gameSystemEdit.editTitle' : 'gameSystemEdit.createTitle') | translate }}
</h1>
@if (id && name.trim()) {
<p class="gse-system-name">{{ name }}</p>
}
</div>
<!-- Un onglet par partie du système : la présentation, les règles, la structure des fiches.
Pas de compteur sur les onglets : un nombre de champs se lirait comme un nombre de fiches. Tout reste
dans le même formulaire : changer d'onglet ne perd rien, et « Enregistrer » enregistre tout. -->
<div class="gse-tabs" role="tablist" [attr.aria-label]="'gameSystemEdit.tabsLabel' | translate">
@for (t of tabs; track t) {
<button type="button" role="tab" class="gse-tab" [class.active]="tab === t"
[attr.aria-selected]="tab === t" (click)="selectTab(t)">
<lucide-icon [img]="tabIcon(t)" [size]="15"></lucide-icon>
{{ ('gameSystemEdit.tabs.' + t) | translate }}
</button>
}
</div>
<div class="gse-form">
<div class="field">
<label for="gs-name">{{ 'gameSystemEdit.nameLabel' | translate }}</label>
<input id="gs-name" type="text" [(ngModel)]="name" name="name" [placeholder]="'gameSystemEdit.namePlaceholder' | translate" />
</div>
@switch (tab) {
<div class="field">
<label for="gs-description">{{ 'gameSystemEdit.descriptionLabel' | translate }}</label>
<textarea id="gs-description" [(ngModel)]="description" name="description" rows="2" [placeholder]="'gameSystemEdit.descriptionPlaceholder' | translate"></textarea>
</div>
<!-- ─── Présentation ─────────────────────────────────────── -->
@case ('general') {
<div class="tab-panel" role="tabpanel">
<div class="field">
<label for="gs-name">{{ 'gameSystemEdit.nameLabel' | translate }}</label>
<input id="gs-name" type="text" [(ngModel)]="name" name="name" [placeholder]="'gameSystemEdit.namePlaceholder' | translate" />
</div>
<div class="field">
<label for="gs-author">{{ 'gameSystemEdit.authorLabel' | translate }}</label>
<input id="gs-author" type="text" [(ngModel)]="author" name="author" [placeholder]="'gameSystemEdit.authorPlaceholder' | translate" />
</div>
<div class="field">
<label for="gs-description">{{ 'gameSystemEdit.descriptionLabel' | translate }}</label>
<textarea id="gs-description" [(ngModel)]="description" name="description" rows="2" [placeholder]="'gameSystemEdit.descriptionPlaceholder' | translate"></textarea>
</div>
<!-- Sections de règles -->
<div class="sections-area">
<h2 class="sections-title">{{ 'gameSystemEdit.rulesTitle' | translate }}</h2>
<p class="sections-hint">{{ 'gameSystemEdit.rulesHint' | translate }}</p>
<!-- Import d'un PDF de règles : l'IA propose un découpage en sections,
que l'utilisateur révise ci-dessous avant d'enregistrer. -->
<div class="import-row">
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
<button type="button" class="btn-import" [disabled]="importing" (click)="pdfInput.click()">
<lucide-icon [img]="Upload" [size]="14"></lucide-icon>
{{ (importing ? 'gameSystemEdit.importInProgress' : 'gameSystemEdit.importButton') | translate }}
</button>
@if (!importing) {
<span class="import-hint">{{ 'gameSystemEdit.importHint' | translate }}</span>
}
</div>
<!-- Progression live de l'import (étape + barre + sections trouvées). -->
@if (importing) {
<div class="import-progress">
<p class="import-phase">{{ importPhase }}</p>
@if (importProgress) {
<div class="progress-bar">
<div class="progress-fill"
[style.width.%]="importProgress.total ? (importProgress.current / importProgress.total) * 100 : 0">
</div>
</div>
}
@if (importStatus) {
<p class="import-status" role="status">{{ importStatus }}</p>
}
@if (importWaitLabel) {
<p class="import-waiting">{{ 'gameSystemEdit.importWaiting' | translate:{ time: importWaitLabel } }}</p>
}
@if (importFound.length) {
<p class="import-found">
{{ 'gameSystemEdit.sectionsFound' | translate:{ titles: importFound.join(' · ') } }}
</p>
}
<div class="field">
<label for="gs-author">{{ 'gameSystemEdit.authorLabel' | translate }}</label>
<input id="gs-author" type="text" [(ngModel)]="author" name="author" [placeholder]="'gameSystemEdit.authorPlaceholder' | translate" />
</div>
</div>
}
@if (importNote) {
<p class="import-note">{{ importNote }}</p>
}
@if (importError) {
<p class="import-error">{{ importError }}</p>
}
<!-- ─── Règles ───────────────────────────────────────────── -->
@case ('rules') {
<div class="tab-panel" role="tabpanel">
<h2 class="sections-title">{{ 'gameSystemEdit.rulesTitle' | translate }}</h2>
<p class="sections-hint">{{ 'gameSystemEdit.rulesHint' | translate }}</p>
<!-- Règles en deux langues : un onglet par version (l'import d'un PDF remplit les deux). -->
<div class="rules-langs" role="tablist" [attr.aria-label]="'gameSystemEdit.langTabs' | translate">
@for (lang of rulesLangs; track lang) {
<button type="button" role="tab" class="rules-lang" [class.active]="rulesLang === lang"
[attr.aria-selected]="rulesLang === lang" (click)="rulesLang = lang">
{{ ('gameSystemEdit.lang.' + lang) | translate }}
<span class="rules-lang-count">{{ sectionCount(lang) }}</span>
</button>
}
</div>
<p class="sections-hint">{{ 'gameSystemEdit.langHint' | translate }}</p>
<!-- Import d'un PDF de règles : l'IA propose un découpage en sections,
que l'utilisateur révise ci-dessous avant d'enregistrer. -->
<div class="import-row">
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
<button type="button" class="btn-import" [disabled]="importing" (click)="pdfInput.click()">
<lucide-icon [img]="Upload" [size]="14"></lucide-icon>
{{ (importing ? 'gameSystemEdit.importInProgress' : 'gameSystemEdit.importButton') | translate }}
</button>
@if (!importing) {
<span class="import-hint">{{ 'gameSystemEdit.importHint' | translate }}</span>
}
</div>
<div class="section-list">
@for (section of sections; track section; let i = $index) {
<div class="section-card" [class.collapsed]="section.collapsed">
<div class="section-head">
<button type="button" class="btn-collapse" (click)="toggleCollapse(section)">
<lucide-icon [img]="section.collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
</button>
<input
type="text"
class="section-title-input"
[(ngModel)]="section.title"
[name]="'title-' + i"
[placeholder]="'gameSystemEdit.sectionTitlePlaceholder' | translate"
/>
<button type="button" class="btn-remove" (click)="removeSection(i)" [title]="'gameSystemEdit.removeSection' | translate">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
</button>
</div>
@if (!section.collapsed) {
<textarea
class="section-content"
[(ngModel)]="section.content"
[name]="'content-' + i"
rows="6"
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
></textarea>
<!-- Progression live de l'import (étape + barre + sections trouvées). -->
@if (importing) {
<div class="import-progress">
<p class="import-phase">{{ importPhase }}</p>
@if (importProgress) {
<div class="progress-bar">
<div class="progress-fill"
[style.width.%]="importProgress.total ? (importProgress.current / importProgress.total) * 100 : 0">
</div>
</div>
}
@if (importStatus) {
<p class="import-status" role="status">{{ importStatus }}</p>
}
@if (importWaitLabel) {
<p class="import-waiting">{{ 'gameSystemEdit.importWaiting' | translate:{ time: importWaitLabel } }}</p>
}
@if (importFound.length) {
<p class="import-found">
{{ 'gameSystemEdit.sectionsFound' | translate:{ titles: importFound.join(' · ') } }}
</p>
}
</div>
}
@if (sections.length === 0) {
<div class="empty-hint">
{{ 'gameSystemEdit.noSections' | translate }}
</div>
@if (importNote) {
<p class="import-note">{{ importNote }}</p>
}
</div>
<div class="add-row">
<span class="add-label">{{ 'gameSystemEdit.addSection' | translate }}</span>
@for (name of suggestedSections; track name) {
<button
type="button"
class="chip"
[class.disabled]="isSectionUsed(name)"
(click)="addSuggested(name)"
[disabled]="isSectionUsed(name)">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon>
{{ name }}
</button>
@if (importError) {
<p class="import-error">{{ importError }}</p>
}
<button type="button" class="chip chip-custom" (click)="addBlank()">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon>
{{ 'gameSystemEdit.addOther' | translate }}
</button>
</div>
</div>
<!-- Templates de fiches PJ/PNJ -->
<div class="templates-area">
<h2 class="sections-title">{{ 'gameSystemEdit.charactersTitle' | translate }}</h2>
<p class="sections-hint">{{ 'gameSystemEdit.charactersHint' | translate }}</p>
<app-template-fields-editor
[label]="'gameSystemEdit.pcFieldsLabel' | translate"
[hint]="'gameSystemEdit.pcFieldsHint' | translate"
[fields]="characterTemplate"
[suggestions]="characterFieldSuggestions"
(fieldsChange)="characterTemplate = $event">
</app-template-fields-editor>
<app-template-fields-editor
[label]="'gameSystemEdit.npcFieldsLabel' | translate"
[hint]="'gameSystemEdit.npcFieldsHint' | translate"
[fields]="npcTemplate"
[suggestions]="npcFieldSuggestions"
(fieldsChange)="npcTemplate = $event">
</app-template-fields-editor>
@if (id) {
<div class="structure-import">
<button type="button" class="btn-secondary" [disabled]="importingStructure" (click)="structureInput.click()">
<lucide-icon [img]="Upload" [size]="14"></lucide-icon>
{{ (importingStructure ? 'gameSystemEdit.structureImporting' : 'gameSystemEdit.structureImport') | translate }}
</button>
<input #structureInput type="file" accept=".json,application/json" hidden (change)="onStructureSelected($event)" />
@if (foundryActorType) {
<span class="structure-actor-type">{{ 'gameSystemEdit.structureActorType' | translate:{ type: foundryActorType } }}</span>
}
@if (importStructureError) {
<span class="structure-error">{{ importStructureError }}</span>
<!-- Règles en deux langues : un onglet par version (l'import d'un PDF remplit les deux). -->
<div class="rules-langs" role="tablist" [attr.aria-label]="'gameSystemEdit.langTabs' | translate">
@for (lang of rulesLangs; track lang) {
<button type="button" role="tab" class="rules-lang" [class.active]="rulesLang === lang"
[attr.aria-selected]="rulesLang === lang" (click)="rulesLang = lang">
{{ ('gameSystemEdit.lang.' + lang) | translate }}
<span class="rules-lang-count">{{ sectionCount(lang) }}</span>
</button>
}
</div>
}
<p class="sections-hint">{{ 'gameSystemEdit.langHint' | translate }}</p>
<app-template-fields-editor
[label]="'gameSystemEdit.enemyFieldsLabel' | translate"
[hint]="'gameSystemEdit.enemyFieldsHint' | translate"
[fields]="enemyTemplate"
[suggestions]="enemyFieldSuggestions"
(fieldsChange)="enemyTemplate = $event">
</app-template-fields-editor>
</div>
<!-- Un livre importé fait vite cinquante sections : on les retrouve par leur titre ou
leur texte, et on les replie d'un clic. -->
@if (sections.length > 1) {
<div class="rules-toolbar">
<div class="rules-search">
<lucide-icon [img]="Search" [size]="14"></lucide-icon>
<input type="search" [(ngModel)]="sectionFilter" name="section-filter"
[placeholder]="'gameSystemEdit.sectionFilterPlaceholder' | translate"
[attr.aria-label]="'gameSystemEdit.sectionFilterPlaceholder' | translate" />
</div>
@if (sectionFilter.trim()) {
<span class="import-hint" role="status">
{{ 'gameSystemEdit.sectionFilterCount' | translate:{ shown: visibleSections.length, total: sections.length } }}
</span>
}
<button type="button" class="link-button" (click)="toggleAllCollapsed()">
{{ (allCollapsed ? 'gameSystemEdit.expandAll' : 'gameSystemEdit.collapseAll') | translate }}
</button>
</div>
}
<div class="actions">
<button type="button" class="btn-primary" [disabled]="!name.trim()" (click)="submit()">
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
{{ (id ? 'common.save' : 'common.create') | translate }}
</button>
<button type="button" class="btn-secondary" (click)="back()">{{ 'common.cancel' | translate }}</button>
</div>
<div class="section-list">
@for (section of visibleSections; track section; let i = $index) {
<div class="section-card" [class.collapsed]="section.collapsed">
<div class="section-head">
<button type="button" class="btn-collapse" (click)="toggleCollapse(section)"
[attr.aria-expanded]="!section.collapsed">
<lucide-icon [img]="section.collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
</button>
<input
type="text"
class="section-title-input"
[(ngModel)]="section.title"
[name]="'title-' + i"
[placeholder]="'gameSystemEdit.sectionTitlePlaceholder' | translate"
/>
@if (section.collapsed && section.content.trim()) {
<span class="section-size">{{ 'gameSystemEdit.sectionSize' | translate:{ count: section.content.trim().length } }}</span>
}
<button type="button" class="btn-remove" (click)="removeSection(section)" [title]="'gameSystemEdit.removeSection' | translate">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
</button>
</div>
@if (!section.collapsed) {
<textarea
class="section-content"
[(ngModel)]="section.content"
[name]="'content-' + i"
rows="6"
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
></textarea>
}
</div>
}
@if (sections.length === 0) {
<div class="empty-hint">
{{ 'gameSystemEdit.noSections' | translate }}
</div>
} @else if (visibleSections.length === 0) {
<div class="empty-hint">
{{ 'gameSystemEdit.sectionFilterEmpty' | translate }}
</div>
}
</div>
<div class="add-row">
<span class="add-label">{{ 'gameSystemEdit.addSection' | translate }}</span>
@for (name of suggestedSections; track name) {
<button
type="button"
class="chip"
[class.disabled]="isSectionUsed(name)"
(click)="addSuggested(name)"
[disabled]="isSectionUsed(name)">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon>
{{ name }}
</button>
}
<button type="button" class="chip chip-custom" (click)="addBlank()">
<lucide-icon [img]="Plus" [size]="12"></lucide-icon>
{{ 'gameSystemEdit.addOther' | translate }}
</button>
</div>
</div>
}
<!-- ─── Structure des fiches (PJ / PNJ / Ennemi) ─────────── -->
@case ('sheets') {
<div class="tab-panel" role="tabpanel">
<h2 class="sections-title">{{ 'gameSystemEdit.charactersTitle' | translate }}</h2>
<p class="sections-hint">{{ 'gameSystemEdit.charactersHint' | translate }}</p>
<div class="rules-langs" role="tablist" [attr.aria-label]="'gameSystemEdit.sheetTabsLabel' | translate">
@for (kind of sheetKinds; track kind) {
<button type="button" role="tab" class="rules-lang" [class.active]="sheetKind === kind"
[attr.aria-selected]="sheetKind === kind" (click)="selectSheet(kind)">
{{ ('gameSystemEdit.sheetTabs.' + kind) | translate }}
</button>
}
</div>
<div class="templates-area">
@switch (sheetKind) {
@case ('character') {
<app-template-fields-editor
[label]="'gameSystemEdit.pcFieldsLabel' | translate"
[hint]="'gameSystemEdit.pcFieldsHint' | translate"
[fields]="characterTemplate"
[suggestions]="characterFieldSuggestions"
(fieldsChange)="characterTemplate = $event">
</app-template-fields-editor>
<ng-container *ngTemplateOutlet="sheetProposal; context: { kind: 'character' }"></ng-container>
}
@case ('npc') {
<app-template-fields-editor
[label]="'gameSystemEdit.npcFieldsLabel' | translate"
[hint]="'gameSystemEdit.npcFieldsHint' | translate"
[fields]="npcTemplate"
[suggestions]="npcFieldSuggestions"
(fieldsChange)="npcTemplate = $event">
</app-template-fields-editor>
<ng-container *ngTemplateOutlet="sheetProposal; context: { kind: 'npc' }"></ng-container>
}
@case ('enemy') {
@if (id) {
<div class="structure-import">
<button type="button" class="btn-secondary" [disabled]="importingStructure" (click)="structureInput.click()">
<lucide-icon [img]="Upload" [size]="14"></lucide-icon>
{{ (importingStructure ? 'gameSystemEdit.structureImporting' : 'gameSystemEdit.structureImport') | translate }}
</button>
<input #structureInput type="file" accept=".json,application/json" hidden (change)="onStructureSelected($event)" />
@if (foundryActorType) {
<span class="structure-actor-type">{{ 'gameSystemEdit.structureActorType' | translate:{ type: foundryActorType } }}</span>
}
@if (importStructureError) {
<span class="structure-error">{{ importStructureError }}</span>
}
</div>
}
<app-template-fields-editor
[label]="'gameSystemEdit.enemyFieldsLabel' | translate"
[hint]="'gameSystemEdit.enemyFieldsHint' | translate"
[fields]="enemyTemplate"
[suggestions]="enemyFieldSuggestions"
(fieldsChange)="enemyTemplate = $event">
</app-template-fields-editor>
<ng-container *ngTemplateOutlet="sheetProposal; context: { kind: 'enemy' }"></ng-container>
}
}
</div>
</div>
}
<!-- ─── Sorts (catalogue, champs d'un sort) ──────────────── -->
@case ('spells') {
<div class="tab-panel" role="tabpanel">
@if (spellsLoadFailed) {
<p class="import-error" role="alert">{{ 'spellCatalog.loadFailed' | translate }}</p>
} @else if (!spellsLoaded) {
<p class="sections-hint" role="status">{{ 'spellCatalog.loading' | translate }}</p>
} @else {
<app-spell-catalog-editor [(spells)]="spells" [(template)]="spellTemplate" [(view)]="spellView"
[rules]="proposalRules" [systemName]="name">
</app-spell-catalog-editor>
}
</div>
}
}
<!-- Toujours visible : un seul enregistrement pour tous les onglets. -->
<div class="actions">
<button type="button" class="btn-primary" [disabled]="!name.trim() || saving" (click)="submit()">
<lucide-icon [img]="Save" [size]="16"></lucide-icon>
{{ (id ? 'common.save' : 'common.create') | translate }}
</button>
<button type="button" class="btn-secondary" (click)="back()">{{ 'common.cancel' | translate }}</button>
@if (!name.trim()) {
<span class="actions-hint">
{{ 'gameSystemEdit.needsName' | translate }}
@if (tab !== 'general') {
<button type="button" class="link-button" (click)="selectTab('general')">
{{ 'gameSystemEdit.tabs.general' | translate }}
</button>
}
</span>
} @else if (saveError) {
<span class="actions-error" role="alert">{{ saveError | translate }}</span>
}
</div>
</div>
</div>
<!-- Proposition de champs pour une fiche, tirée des règles par l'IA. Elle ne fait
qu'AJOUTER : un champ déjà présent est grisé, aucun champ existant n'est modifié,
et rien n'est enregistré avant l'enregistrement du système. -->
<ng-template #sheetProposal let-kind="kind">
<div class="sheet-proposal">
<div class="sheet-proposal-row">
<button type="button" class="btn-import"
[disabled]="proposal(kind).loading || !hasRulesForProposal" (click)="proposeSheet(kind)">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ (proposal(kind).loading ? 'gameSystemEdit.sheetProposing' : 'gameSystemEdit.sheetPropose') | translate }}
</button>
@if (!hasRulesForProposal) {
<span class="import-hint">{{ 'gameSystemEdit.sheetNeedsRules' | translate }}</span>
} @else if (proposal(kind).loading) {
<span class="import-hint" role="status">{{ 'gameSystemEdit.sheetProposingHint' | translate }}</span>
}
</div>
@if (proposal(kind).error) {
<p class="import-error sheet-proposal-message">{{ proposal(kind).error }}</p>
}
@if (proposal(kind).fields; as fields) {
@if (fields.length === 0) {
<p class="import-note sheet-proposal-message">{{ 'gameSystemEdit.sheetNothingFound' | translate }}</p>
} @else {
<div class="sheet-proposal-list">
<p class="sheet-proposal-intro">{{ 'gameSystemEdit.sheetIntro' | translate }}</p>
@for (f of fields; track f.name) {
<label class="sheet-proposal-item" [class.present]="isInSheet(kind, f.name)">
<input type="checkbox"
[checked]="isProposedSelected(kind, f.name)"
[disabled]="isInSheet(kind, f.name)"
(change)="toggleProposed(kind, f.name)" />
<span class="sp-main">
<span class="sp-name">{{ f.name }}</span>
<span class="sp-type">{{ proposedTypeKey(f.type) | translate }}</span>
@if (isInSheet(kind, f.name)) {
<span class="sp-present">{{ 'gameSystemEdit.sheetAlreadyPresent' | translate }}</span>
} @else if (f.source) {
<span class="sp-source">{{ 'gameSystemEdit.sheetSource' | translate:{ section: f.source } }}</span>
}
@if (f.labels.length) {
<span class="sp-labels">{{ f.labels.join(' · ') }}</span>
}
</span>
</label>
}
@if (proposal(kind).added) {
<p class="sheet-proposal-added" role="status">
{{ 'gameSystemEdit.sheetAdded' | translate:{ count: proposal(kind).added } }}
</p>
}
<div class="sheet-proposal-actions">
<button type="button" class="btn-primary"
[disabled]="selectedProposals(kind).length === 0" (click)="addSelectedProposals(kind)">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'gameSystemEdit.sheetAdd' | translate:{ count: selectedProposals(kind).length } }}
</button>
<button type="button" class="btn-secondary" (click)="dismissProposal(kind)">
{{ 'gameSystemEdit.sheetClose' | translate }}
</button>
</div>
</div>
}
}
</div>
</ng-template>
@@ -6,14 +6,14 @@
}
.templates-area {
margin-top: 24px;
margin-top: 0;
display: flex;
flex-direction: column;
gap: 16px;
}
.gse-header {
margin-bottom: 2rem;
margin-bottom: 1.25rem;
h1 {
display: flex;
@@ -76,11 +76,6 @@
/* ─── Sections ──────────────────────────────────────────────── */
.sections-area {
border-top: 1px solid #1f2937;
padding-top: 1.5rem;
margin-top: 0.5rem;
}
.sections-title {
font-size: 1rem;
@@ -334,10 +329,32 @@
/* ─── Actions ──────────────────────────────────────────────── */
/* Toujours à portée : la barre reste collée en bas de la fenêtre, quel que soit l'onglet. */
.actions {
position: sticky;
// La zone de contenu a une marge basse (2rem) dans laquelle le texte continuerait de
// défiler sous la barre : on y descend la barre, et on rend la hauteur en marge interne.
bottom: -2rem;
z-index: 2;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.75rem;
margin-top: 0.5rem;
padding: 0.85rem 0 calc(0.85rem + 2rem);
margin-bottom: -2rem;
background: #0a0a14;
border-top: 1px solid #1f2937;
}
.actions-hint {
color: #9ca3af;
font-size: 0.85rem;
}
.actions-error {
color: #fca5a5;
font-size: 0.85rem;
}
.btn-primary {
@@ -395,3 +412,221 @@
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
// --- Proposition de champs de fiche (à partir des règles) -------------------
.sheet-proposal {
margin-top: -6px;
}
.sheet-proposal-row {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.sheet-proposal-message {
margin: 0.6rem 0 0;
}
.sheet-proposal-list {
margin-top: 0.6rem;
padding: 0.8rem 0.9rem;
background: #0b1220;
border: 1px solid rgba(108, 99, 255, 0.35);
border-radius: 10px;
}
.sheet-proposal-intro {
margin: 0 0 0.6rem;
color: #9ca3af;
font-size: 0.82rem;
line-height: 1.4;
}
.sheet-proposal-item {
display: flex;
align-items: flex-start;
gap: 0.6rem;
padding: 0.4rem 0.3rem;
border-top: 1px solid #1f2937;
cursor: pointer;
input { margin-top: 0.2rem; accent-color: #a78bfa; }
&.present {
cursor: default;
.sp-name, .sp-type, .sp-labels { opacity: 0.5; }
}
}
.sp-main {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.25rem 0.6rem;
min-width: 0;
}
.sp-name {
color: white;
font-size: 0.92rem;
font-weight: 500;
}
.sp-type {
font-size: 0.72rem;
padding: 0.05rem 0.45rem;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
color: #d1d5db;
}
.sp-source {
font-size: 0.78rem;
color: #6b7280;
}
.sp-present {
font-size: 0.78rem;
color: #c4b5fd;
}
.sp-labels {
flex-basis: 100%;
color: #9ca3af;
font-size: 0.8rem;
line-height: 1.4;
}
.sheet-proposal-added {
margin: 0.6rem 0 0;
color: #86efac;
font-size: 0.85rem;
}
.sheet-proposal-actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 0.8rem;
.btn-primary, .btn-secondary {
padding: 0.45rem 0.9rem;
font-size: 0.85rem;
}
}
// --- Onglets de l'écran (Présentation / Règles / Structure des fiches) -------
.gse-system-name {
margin: 0.25rem 0 0;
color: #9ca3af;
font-size: 0.95rem;
}
.gse-tabs {
display: flex;
gap: 0.25rem;
margin-bottom: 1.5rem;
border-bottom: 1px solid #1f2937;
overflow-x: auto;
}
.gse-tab {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.65rem 1rem;
margin-bottom: -1px;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
color: #9ca3af;
font-size: 0.95rem;
font-weight: 500;
white-space: nowrap;
cursor: pointer;
&:hover { color: #e5e7eb; }
&.active { color: white; border-bottom-color: #a78bfa; }
&:focus-visible { outline: 2px solid #a78bfa; outline-offset: -2px; }
}
.tab-panel {
display: flex;
flex-direction: column;
gap: 1.25rem;
.sections-title, .sections-hint, .import-row, .rules-langs { margin-top: 0; margin-bottom: 0; }
.sections-title + .sections-hint { margin-top: -1rem; }
.rules-langs + .sections-hint { margin-top: -0.9rem; }
.section-list { margin-bottom: 0; }
.import-progress { margin: 0; }
}
// --- Recherche et repli des sections ----------------------------------------
.rules-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.75rem;
.link-button { margin-left: auto; }
}
.rules-search {
display: flex;
align-items: center;
gap: 0.4rem;
flex: 1 1 16rem;
max-width: 24rem;
padding: 0 0.6rem;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 8px;
color: #6b7280;
&:focus-within { border-color: #a78bfa; }
input {
flex: 1;
min-width: 0;
padding: 0.45rem 0;
background: transparent;
border: none;
outline: none;
color: #e5e7eb;
font-size: 0.9rem;
font-family: inherit;
}
}
.link-button {
background: transparent;
border: none;
padding: 0;
color: #a78bfa;
font-size: 0.85rem;
cursor: pointer;
&:hover { text-decoration: underline; }
}
.section-size {
flex-shrink: 0;
color: #6b7280;
font-size: 0.75rem;
white-space: nowrap;
}
// --- Import d'une structure Foundry (fiche Ennemi) ---------------------------
.structure-import {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.75rem;
}
.structure-actor-type { color: #9ca3af; font-size: 0.85rem; }
.structure-error { color: #fca5a5; font-size: 0.85rem; }
@@ -1,19 +1,32 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { Subscription, map, of, switchMap } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { LucideAngularModule, Save, ArrowLeft, Dices, Plus, Trash2, ChevronDown, ChevronRight, Upload } from 'lucide-angular';
import {
LucideAngularModule, LucideIconData, Save, ArrowLeft, Dices, Plus, Trash2, ChevronDown, ChevronRight, Upload,
Sparkles, Info, BookOpen, LayoutTemplate, Search, WandSparkles
} from 'lucide-angular';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { GameSystemService } from '../../services/game-system.service';
import { TemplateField } from '../../services/template.model';
import { SheetFieldProposal, SheetKind } from '../../services/game-system.model';
import { FieldType, TemplateField } from '../../services/template.model';
import { addProposedFields, isAlreadyInSheet, rulesForProposal } from '../sheet-proposal.util';
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
import { SpellCatalogEditorComponent, SpellView } from '../spell-catalog-editor/spell-catalog-editor.component';
import { SpellDraft, firstUnnamedSpell, hasInvalidField, toDraft, toPayload } from '../spell-catalog.util';
/**
* Éditeur plein écran d'un GameSystem. Rôle double création/édition :
* - `/game-systems/create` → POST au submit
* - `/game-systems/:id/edit` → PUT au submit
*
* UI par sections : au lieu d'un gros textarea de markdown, on présente
* Quatre onglets (Présentation / Règles / Structure des fiches / Sorts) sur UN seul formulaire : changer
* d'onglet ne perd rien, et l'enregistrement porte sur tout. L'onglet affiché est
* rappelé dans l'URL (`?tab=rules`, `&sheet=enemy`) pour survivre à un rechargement.
*
* Règles par sections : au lieu d'un gros textarea de markdown, on présente
* une liste de cartes repliables (une par section H2). Au load on parse
* le markdown existant, au submit on le reconstruit. Les noms suggérés
* (Combat, Classes…) guident sans imposer — c'est le même mapping que
@@ -46,9 +59,35 @@ const ENEMY_FIELD_SUGGESTIONS = ['Stats', 'Attaques', 'Capacités', 'Faiblesses'
/** Langue d'une version des règles. */
type RulesLang = 'fr' | 'en';
/** Onglets de l'écran. */
type EditTab = 'general' | 'rules' | 'sheets' | 'spells';
const TABS: EditTab[] = ['general', 'rules', 'sheets', 'spells'];
const SHEET_KINDS: SheetKind[] = ['character', 'npc', 'enemy'];
/** Au-delà, les sections s'ouvrent repliées : un livre importé en compte vite cinquante. */
const COLLAPSE_ABOVE = 5;
/**
* Proposition de champs pour une fiche, tirée des règles par l'IA. `fields` vaut null
* tant qu'aucune proposition n'est affichée, et [] si les règles ne décrivent pas la fiche.
*/
interface SheetProposalState {
loading: boolean;
error: string | null;
fields: SheetFieldProposal[] | null;
/** Noms (en minuscules) des champs cochés. */
selected: Set<string>;
/** Nombre de champs ajoutés au dernier clic (message de confirmation). */
added: number | null;
}
const emptyProposal = (): SheetProposalState =>
({ loading: false, error: null, fields: null, selected: new Set<string>(), added: null });
@Component({
selector: 'app-game-system-edit',
imports: [FormsModule, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent],
imports: [FormsModule, NgTemplateOutlet, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent,
SpellCatalogEditorComponent],
templateUrl: './game-system-edit.component.html',
styleUrls: ['./game-system-edit.component.scss']
})
@@ -61,9 +100,23 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
readonly ChevronDown = ChevronDown;
readonly ChevronRight = ChevronRight;
readonly Upload = Upload;
readonly Sparkles = Sparkles;
readonly Search = Search;
id: string | null = null;
readonly tabs = TABS;
tab: EditTab = 'general';
readonly sheetKinds = SHEET_KINDS;
/** Fiche dont la structure est affichée (onglet Structure des fiches). */
sheetKind: SheetKind = 'character';
/** Recherche dans les sections de règles (titre ou texte). */
sectionFilter = '';
/** Enregistrement en cours. */
saving = false;
/** Clé de traduction du dernier refus d'enregistrement. */
saveError: string | null = null;
/** Import PDF en cours (appel LLM long) → désactive le bouton + spinner. */
importing = false;
/** Message de succès post-import (sections ajoutées, pages, OCR). */
@@ -107,6 +160,18 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
npcTemplate: TemplateField[] = [];
enemyTemplate: TemplateField[] = [];
/** Catalogue de sorts : les sorts eux-mêmes, et les champs propres au système que porte chacun. */
spells: SpellDraft[] = [];
spellTemplate: TemplateField[] = [];
spellView: SpellView = 'catalog';
/**
* Le catalogue est-il celui du serveur ? Tant qu'il n'a pas été lu (ou si sa lecture a
* échoué), l'enregistrement ne l'envoie pas : un catalogue vide effacerait les sorts.
*/
spellsLoaded = false;
spellsLoadFailed = false;
@ViewChild(SpellCatalogEditorComponent) private spellEditor?: SpellCatalogEditorComponent;
/** Type d'acteur Foundry (posé par l'import de structure). */
foundryActorType: string | null = null;
/** Import de structure Foundry en cours. */
@@ -118,6 +183,12 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
readonly npcFieldSuggestions = NPC_FIELD_SUGGESTIONS;
readonly enemyFieldSuggestions = ENEMY_FIELD_SUGGESTIONS;
/** Propositions de champs par fiche (PJ, PNJ, ennemi), indépendantes les unes des autres. */
proposals: Record<SheetKind, SheetProposalState> = {
character: emptyProposal(), npc: emptyProposal(), enemy: emptyProposal()
};
private proposalSubs: Partial<Record<SheetKind, Subscription>> = {};
constructor(
private route: ActivatedRoute,
private router: Router,
@@ -129,6 +200,10 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
// Onglet de règles par défaut : la langue de l'interface.
this.rulesLang = this.translate.getCurrentLang() === 'en' ? 'en' : 'fr';
this.id = this.route.snapshot.paramMap.get('id');
// Création : on commence par le nom. Édition : on vient le plus souvent pour les règles.
const query = this.route.snapshot.queryParamMap;
this.tab = TABS.find(t => t === query.get('tab')) ?? (this.id ? 'rules' : 'general');
this.sheetKind = SHEET_KINDS.find(k => k === query.get('sheet')) ?? 'character';
if (this.id) {
this.service.getById(this.id).subscribe({
next: (gs) => {
@@ -136,8 +211,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
this.description = gs.description ?? '';
this.author = gs.author ?? '';
this.sectionsByLang = {
fr: this.parseMarkdown(gs.rulesMarkdown ?? ''),
en: this.parseMarkdown(gs.rulesMarkdownEn ?? '')
fr: this.collapseIfMany(this.parseMarkdown(gs.rulesMarkdown ?? '')),
en: this.collapseIfMany(this.parseMarkdown(gs.rulesMarkdownEn ?? ''))
};
this.characterTemplate = gs.characterTemplate ? [...gs.characterTemplate] : [];
this.npcTemplate = gs.npcTemplate ? [...gs.npcTemplate] : [];
@@ -146,9 +221,73 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
},
error: () => this.back()
});
this.service.getSpells(this.id).subscribe({
next: catalog => {
this.spellTemplate = catalog.template ?? [];
this.spells = (catalog.spells ?? []).map(toDraft);
this.spellsLoaded = true;
},
error: () => { this.spellsLoadFailed = true; }
});
} else {
// Nouveau système : son catalogue est celui qu'on saisit ici.
this.spellsLoaded = true;
}
}
// --- Onglets --------------------------------------------------------------
selectTab(tab: EditTab): void {
this.tab = tab;
this.rememberTab();
}
selectSheet(kind: SheetKind): void {
this.sheetKind = kind;
this.rememberTab();
}
/** Garde l'onglet dans l'URL, sans ajouter d'entrée à l'historique. */
private rememberTab(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { tab: this.tab, sheet: this.tab === 'sheets' ? this.sheetKind : null },
queryParamsHandling: 'merge',
replaceUrl: true
});
}
tabIcon(tab: EditTab): LucideIconData {
if (tab === 'general') return Info;
if (tab === 'spells') return WandSparkles;
return tab === 'rules' ? BookOpen : LayoutTemplate;
}
// --- Sections de règles : recherche et repli -------------------------------
/** Sections affichées : toutes, ou celles dont le titre ou le texte contient la recherche. */
get visibleSections(): RuleSection[] {
const needle = this.sectionFilter.trim().toLowerCase();
if (!needle) return this.sections;
return this.sections.filter(s =>
s.title.toLowerCase().includes(needle) || s.content.toLowerCase().includes(needle));
}
get allCollapsed(): boolean {
return this.visibleSections.length > 0 && this.visibleSections.every(s => s.collapsed);
}
/** Replie tout, ou déplie tout si tout l'est déjà (sections affichées seulement). */
toggleAllCollapsed(): void {
const collapsed = !this.allCollapsed;
this.visibleSections.forEach(s => { s.collapsed = collapsed; });
}
private collapseIfMany(sections: RuleSection[]): RuleSection[] {
if (sections.length > COLLAPSE_ABOVE) sections.forEach(s => { s.collapsed = true; });
return sections;
}
/** Noms de section déjà utilisés — pour désactiver les suggestions en doublon. */
isSectionUsed(title: string): boolean {
const lower = title.toLowerCase();
@@ -158,11 +297,13 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
/** Ajoute une section avec un nom suggéré. */
addSuggested(title: string): void {
if (this.isSectionUsed(title)) return;
this.sectionFilter = '';
this.sections.push({ title, content: '', collapsed: false });
}
/** Ajoute une section vierge (titre à remplir). */
addBlank(): void {
this.sectionFilter = '';
this.sections.push({ title: '', content: '', collapsed: false });
}
@@ -254,6 +395,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
target: translatedLangs.map(l => this.translate.instant('gameSystemEdit.lang.' + l)).join(', ')
});
}
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importSheetHint');
}
/** Nombre de sections non vides d'une langue (badge de l'onglet). */
@@ -270,6 +412,114 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
ngOnDestroy(): void {
this.stopImportWait();
Object.values(this.proposalSubs).forEach(sub => sub?.unsubscribe());
}
// --- Proposition de champs de fiche à partir des règles -------------------
/**
* Règles envoyées à l'IA (fiches et sorts) : la version affichée, sinon l'autre
* (cf. rulesForProposal).
*/
get proposalRules(): { title: string; content: string }[] {
const other: RulesLang = this.rulesLang === 'fr' ? 'en' : 'fr';
return rulesForProposal(this.sections, this.sectionsByLang[other]);
}
/** Sans règle, il n'y a rien à lire : le bouton de proposition est désactivé. */
get hasRulesForProposal(): boolean {
return this.proposalRules.length > 0;
}
/** Etat de la proposition d'une fiche (le gabarit partage passe `kind` sans type). */
proposal(kind: SheetKind): SheetProposalState {
return this.proposals[kind];
}
templateOf(kind: SheetKind): TemplateField[] {
if (kind === 'character') return this.characterTemplate;
return kind === 'npc' ? this.npcTemplate : this.enemyTemplate;
}
/**
* Demande à l'IA les champs de la fiche d'après les règles affichées (enregistrées ou
* non). Rien n'est modifié tant que l'utilisateur n'a pas choisi des champs.
*/
proposeSheet(kind: SheetKind): void {
const sections = this.proposalRules;
if (this.proposals[kind].loading || !sections.length) return;
this.proposals[kind] = { ...emptyProposal(), loading: true };
this.proposalSubs[kind]?.unsubscribe();
this.proposalSubs[kind] = this.service.proposeSheet({
sheet: kind,
systemName: this.name.trim(),
sections,
existingFields: this.templateOf(kind).map(f => f.name?.trim()).filter((n): n is string => !!n)
}).subscribe({
next: ({ fields }) => {
const proposed = fields ?? [];
// Cochés d'office : les champs nouveaux. Ceux déjà dans la fiche restent grisés.
const selected = new Set(proposed
.filter(f => !isAlreadyInSheet(this.templateOf(kind), f.name))
.map(f => f.name.trim().toLowerCase()));
this.proposals[kind] = { ...emptyProposal(), fields: proposed, selected };
},
error: (err) => {
const reason = err?.error?.error;
this.proposals[kind] = {
...emptyProposal(),
error: reason
? this.translate.instant('gameSystemEdit.sheetFailedReason', { reason })
: this.translate.instant('gameSystemEdit.sheetFailed')
};
}
});
}
isInSheet(kind: SheetKind, name: string): boolean {
return isAlreadyInSheet(this.templateOf(kind), name);
}
isProposedSelected(kind: SheetKind, name: string): boolean {
return !this.isInSheet(kind, name) && this.proposals[kind].selected.has(name.trim().toLowerCase());
}
toggleProposed(kind: SheetKind, name: string): void {
const key = name.trim().toLowerCase();
const selected = this.proposals[kind].selected;
if (!selected.delete(key)) selected.add(key);
}
/** Champs cochés qui ne sont pas encore dans la fiche. */
selectedProposals(kind: SheetKind): SheetFieldProposal[] {
return (this.proposals[kind].fields ?? []).filter(f => this.isProposedSelected(kind, f.name));
}
/**
* Ajoute les champs cochés à la suite du modèle. Les champs existants ne sont ni
* renommés ni retirés : les fiches déjà remplies gardent tout leur contenu.
*/
addSelectedProposals(kind: SheetKind): void {
const chosen = this.selectedProposals(kind);
if (!chosen.length) return;
const next = addProposedFields(this.templateOf(kind), chosen);
const added = next.length - this.templateOf(kind).length;
if (kind === 'character') this.characterTemplate = next;
else if (kind === 'npc') this.npcTemplate = next;
else this.enemyTemplate = next;
this.proposals[kind].selected = new Set<string>();
this.proposals[kind].added = added;
}
dismissProposal(kind: SheetKind): void {
this.proposalSubs[kind]?.unsubscribe();
this.proposals[kind] = emptyProposal();
}
/** Clé de traduction du type d'un champ proposé (libellés de l'éditeur de modèle). */
proposedTypeKey(type: FieldType): string {
if (type === 'NUMBER') return 'templateFieldsEditor.typeNumber';
return type === 'KEY_VALUE_LIST' ? 'templateFieldsEditor.typeKeyValue' : 'templateFieldsEditor.typeText';
}
/** Le compteur ne s'affiche qu'au-delà de quelques secondes sans nouvelle. */
@@ -361,8 +611,9 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
});
}
removeSection(index: number): void {
this.sections.splice(index, 1);
removeSection(section: RuleSection): void {
const index = this.sections.indexOf(section);
if (index >= 0) this.sections.splice(index, 1);
}
toggleCollapse(section: RuleSection): void {
@@ -370,9 +621,28 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
}
submit(): void {
if (!this.name.trim()) return;
if (this.hasInvalidTemplateFields()) {
console.warn('Champs templates invalides (noms vides ou doublons) — sauvegarde bloquee.');
if (!this.name.trim() || this.saving) return;
this.saveError = null;
// Un champ sans nom ou en double bloque l'enregistrement : on montre la fiche en cause.
const invalid = SHEET_KINDS.find(kind => this.hasInvalidList(this.templateOf(kind)));
if (invalid) {
this.saveError = 'gameSystemEdit.invalidFields';
this.tab = 'sheets';
this.selectSheet(invalid);
return;
}
if (this.spellsLoaded && hasInvalidField(this.spellTemplate)) {
this.saveError = 'spellCatalog.invalidFields';
this.spellView = 'fields';
this.selectTab('spells');
return;
}
const unnamed = this.spellsLoaded ? firstUnnamedSpell(this.spells) : null;
if (unnamed) {
this.saveError = 'spellCatalog.unnamedSpell';
this.selectTab('spells');
// L'onglet vient peut-être d'être affiché : on attend que son contenu existe.
setTimeout(() => this.spellEditor?.reveal(unnamed));
return;
}
const payload = {
@@ -390,9 +660,24 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
const req = this.id
? this.service.update(this.id, payload)
: this.service.create(payload);
req.subscribe({
this.saving = true;
let systemSaved = false;
req.pipe(
switchMap(saved => {
systemSaved = true;
// Un système tout juste créé a maintenant un identifiant : un nouvel essai le
// mettra à jour au lieu d'en créer un second.
if (saved.id) this.id = saved.id;
if (!this.spellsLoaded || !saved.id) return of(saved);
return this.service.saveSpells(saved.id, { template: this.spellTemplate, spells: toPayload(this.spells) })
.pipe(map(() => saved));
})
).subscribe({
next: () => this.back(),
error: () => console.error('Erreur sauvegarde GameSystem')
error: () => {
this.saving = false;
this.saveError = systemSaved ? 'spellCatalog.saveFailed' : 'gameSystemEdit.saveFailed';
}
});
}
@@ -401,12 +686,6 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
}
/** Validation cote front : nom vide ou doublons (case-insensitive). */
private hasInvalidTemplateFields(): boolean {
return this.hasInvalidList(this.characterTemplate)
|| this.hasInvalidList(this.npcTemplate)
|| this.hasInvalidList(this.enemyTemplate);
}
private hasInvalidList(fields: TemplateField[]): boolean {
const seen = new Set<string>();
for (const f of fields) {
@@ -0,0 +1,52 @@
import { SheetFieldProposal } from '../services/game-system.model';
import { TemplateField } from '../services/template.model';
import { addProposedFields, isAlreadyInSheet, rulesForProposal } from './sheet-proposal.util';
/**
* Proposition d'un modèle de fiche : elle ajoute des champs et ne touche jamais à ceux
* qui existent — les fiches déjà remplies ne perdent rien.
*/
describe('sheet-proposal.util', () => {
const existing: TemplateField[] = [
{ name: 'Histoire', type: 'TEXT', layout: null },
{ name: 'Caractéristiques', type: 'KEY_VALUE_LIST', labels: ['FOR', 'DEX'] }
];
const proposal = (name: string, type: SheetFieldProposal['type'] = 'TEXT', labels: string[] = []): SheetFieldProposal =>
({ name, type, labels, source: '' });
it('reconnaît un champ déjà présent sans tenir compte de la casse ni des espaces', () => {
expect(isAlreadyInSheet(existing, ' histoire ')).toBe(true);
expect(isAlreadyInSheet(existing, 'Classe')).toBe(false);
expect(isAlreadyInSheet(existing, ' ')).toBe(false);
});
it('ajoute les nouveaux champs à la suite, sans modifier les existants', () => {
const result = addProposedFields(existing, [
proposal('Classe'),
proposal('caractéristiques', 'KEY_VALUE_LIST', ['Force', 'Agilité']),
proposal('Points de vie', 'NUMBER'),
proposal('Compétences', 'KEY_VALUE_LIST', ['Discrétion', 'Athlétisme']),
proposal('classe', 'NUMBER'),
proposal(' ')
]);
expect(result.slice(0, 2)).toEqual(existing);
expect(result.slice(2)).toEqual([
{ name: 'Classe', type: 'TEXT', layout: null },
{ name: 'Points de vie', type: 'NUMBER', layout: null },
{ name: 'Compétences', type: 'KEY_VALUE_LIST', layout: null, labels: ['Discrétion', 'Athlétisme'] }
]);
expect(existing).toHaveLength(2);
expect(existing[1].labels).toEqual(['FOR', 'DEX']);
});
it('envoie les règles de la version affichée, sinon celles de l\'autre version', () => {
const fr = [{ title: ' Combat ', content: ' Initiative. ' }, { title: 'Vide', content: ' ' }, { title: '', content: 'x' }];
const en = [{ title: 'Combat', content: 'Initiative.' }, { title: 'Magic', content: 'Spells.' }];
expect(rulesForProposal(fr, en)).toEqual([{ title: 'Combat', content: 'Initiative.' }]);
expect(rulesForProposal([{ title: 'Vide', content: '' }], en)).toEqual(en);
expect(rulesForProposal([], [])).toEqual([]);
});
});
@@ -0,0 +1,51 @@
import { SheetFieldProposal } from '../services/game-system.model';
import { TemplateField } from '../services/template.model';
/**
* Proposition d'un modèle de fiche à partir des règles : logique pure de l'éditeur.
*
* Règle d'or pour les systèmes déjà utilisés : la proposition ne fait qu'AJOUTER. Les
* valeurs des fiches sont rangées par nom de champ ; renommer ou retirer un champ
* existant ferait disparaître ce que les utilisateurs ont déjà saisi.
*/
interface RuleSectionLike {
title: string;
content: string;
}
const sameName = (a: string | undefined | null, b: string | undefined | null): boolean =>
(a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
/** Le modèle contient-il déjà un champ de ce nom (insensible à la casse) ? */
export function isAlreadyInSheet(fields: TemplateField[], name: string): boolean {
return !!name?.trim() && fields.some(f => sameName(f.name, name));
}
/**
* Ajoute au modèle les champs proposés qui n'y sont pas encore, à la suite des champs
* existants. Aucun champ existant n'est modifié, retiré ni déplacé.
*/
export function addProposedFields(fields: TemplateField[], proposals: SheetFieldProposal[]): TemplateField[] {
const out = [...fields];
for (const p of proposals) {
const name = p.name?.trim();
if (!name || isAlreadyInSheet(out, name)) continue;
out.push(p.type === 'KEY_VALUE_LIST'
? { name, type: p.type, layout: null, labels: [...(p.labels ?? [])] }
: { name, type: p.type, layout: null });
}
return out;
}
/**
* Sections de règles à envoyer : celles de la version affichée si elle a du contenu,
* sinon celles de l'autre version (un système importé dans une seule langue).
*/
export function rulesForProposal<T extends RuleSectionLike>(displayed: T[], other: T[]): { title: string; content: string }[] {
const filled = (sections: T[]) => sections
.filter(s => s.title?.trim() && s.content?.trim())
.map(s => ({ title: s.title.trim(), content: s.content.trim() }));
const current = filled(displayed);
return current.length ? current : filled(other);
}
@@ -0,0 +1,180 @@
<h2 class="sections-title">{{ 'spellCatalog.title' | translate }}</h2>
<p class="sections-hint">{{ 'spellCatalog.hint' | translate }}</p>
<div class="spell-views" role="tablist" [attr.aria-label]="'spellCatalog.viewsLabel' | translate">
@for (v of views; track v) {
<button type="button" role="tab" class="spell-view" [class.active]="view === v"
[attr.aria-selected]="view === v" (click)="selectView(v)">
{{ ('spellCatalog.views.' + v) | translate }}
</button>
}
</div>
@if (view === 'catalog') {
<div class="spell-toolbar">
<div class="spell-search">
<lucide-icon [img]="Search" [size]="14"></lucide-icon>
<input type="search" [(ngModel)]="filter.text" name="spell-filter-text"
[placeholder]="'spellCatalog.searchPlaceholder' | translate"
[attr.aria-label]="'spellCatalog.searchPlaceholder' | translate" />
</div>
@if (levels.length > 1) {
<select [(ngModel)]="filter.level" name="spell-filter-level" [attr.aria-label]="'spellCatalog.levelLabel' | translate">
<option value="">{{ 'spellCatalog.allLevels' | translate }}</option>
@for (level of levels; track level) {
<option [value]="level">{{ level }}</option>
}
</select>
}
@if (schools.length > 1) {
<select [(ngModel)]="filter.school" name="spell-filter-school" [attr.aria-label]="'spellCatalog.schoolLabel' | translate">
<option value="">{{ 'spellCatalog.allSchools' | translate }}</option>
@for (school of schools; track school) {
<option [value]="school">{{ school }}</option>
}
</select>
}
<span class="spell-toolbar-actions">
@if (!proposing) {
<button type="button" class="btn-propose-spells" (click)="proposing = true">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'spellCatalog.proposal.open' | translate }}
</button>
}
<button type="button" class="btn-add-spell" (click)="addSpell()">
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
{{ 'spellCatalog.add' | translate }}
</button>
</span>
</div>
<!-- Proposition de sorts tirée des règles par l'IA. Elle ne fait qu'AJOUTER : un sort déjà
au catalogue est grisé, et rien n'est enregistré avant l'enregistrement du système. -->
@if (proposing) {
<app-spell-proposal [rules]="rules" [systemName]="systemName" [fields]="fields" [catalogue]="spells"
(add)="onProposed($event)" (closed)="proposing = false">
</app-spell-proposal>
}
@if (spells.length > 0) {
<div class="spell-status">
<span role="status">
@if (filtering) {
{{ 'spellCatalog.countFiltered' | translate:{ shown: visibleSpells.length, total: spells.length } }}
<button type="button" class="link-button" (click)="clearFilter()">{{ 'spellCatalog.clearFilter' | translate }}</button>
} @else {
{{ (spells.length === 1 ? 'spellCatalog.countOne' : 'spellCatalog.countMany') | translate:{ count: spells.length } }}
}
</span>
@if (spells.length > 1) {
<span class="spell-status-actions">
<button type="button" class="link-button" (click)="sort()" [title]="'spellCatalog.sortTitle' | translate">
<lucide-icon [img]="ArrowDownNarrowWide" [size]="13"></lucide-icon>
{{ 'spellCatalog.sort' | translate }}
</button>
<button type="button" class="link-button" (click)="toggleAllCollapsed()">
{{ (allCollapsed ? 'spellCatalog.expandAll' : 'spellCatalog.collapseAll') | translate }}
</button>
</span>
}
</div>
}
<div class="spell-list">
@for (spell of visibleSpells; track spell; let i = $index) {
<article class="spell-card" [class.collapsed]="spell.collapsed">
<header class="spell-head">
<button type="button" class="spell-toggle" (click)="toggle(spell)" [attr.aria-expanded]="!spell.collapsed"
[attr.aria-label]="(spell.collapsed ? 'spellCatalog.open' : 'spellCatalog.close') | translate">
<lucide-icon [img]="spell.collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
</button>
@if (spell.collapsed) {
<!-- Carte repliée : le sort se lit d'un coup d'œil, un clic l'ouvre. -->
<button type="button" class="spell-summary" (click)="toggle(spell)">
@if (spell.level?.trim()) {
<span class="spell-level">{{ spell.level }}</span>
}
<span class="spell-title" [class.spell-title--empty]="!spell.name.trim()">
{{ spell.name.trim() || ('spellCatalog.unnamed' | translate) }}
</span>
@if (spell.school?.trim()) {
<span class="spell-school">{{ spell.school }}</span>
}
@if (summaryOf(spell); as text) {
<span class="spell-excerpt">{{ text }}</span>
}
</button>
} @else {
<input type="text" class="spell-name" maxlength="255" [(ngModel)]="spell.name" [name]="'spell-name-' + i"
[placeholder]="'spellCatalog.namePlaceholder' | translate"
[attr.aria-label]="'spellCatalog.nameLabel' | translate" />
}
<button type="button" class="spell-remove" (click)="removeSpell(spell)" [title]="'spellCatalog.remove' | translate">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
</button>
</header>
@if (!spell.collapsed) {
<div class="spell-body">
<div class="spell-grid">
<label class="spell-field">
<span>{{ 'spellCatalog.levelLabel' | translate }}</span>
<input type="text" maxlength="255" [(ngModel)]="spell.level" [name]="'spell-level-' + i"
[placeholder]="'spellCatalog.levelPlaceholder' | translate" />
</label>
<label class="spell-field">
<span>{{ 'spellCatalog.schoolLabel' | translate }}</span>
<input type="text" maxlength="255" [(ngModel)]="spell.school" [name]="'spell-school-' + i"
[placeholder]="'spellCatalog.schoolPlaceholder' | translate" />
</label>
@for (field of fields; track field.name) {
<label class="spell-field">
<span>{{ field.name }}</span>
<!-- Type lié et non écrit en dur : la valeur reste une chaîne, même pour un nombre. -->
<input [type]="field.type === 'NUMBER' ? 'number' : 'text'" [(ngModel)]="spell.values[field.name]"
[name]="'spell-' + i + '-' + field.name" />
</label>
}
</div>
<label class="spell-field spell-field--wide">
<span>{{ 'spellCatalog.descriptionLabel' | translate }}</span>
<textarea rows="4" [(ngModel)]="spell.description" [name]="'spell-description-' + i"
[placeholder]="'spellCatalog.descriptionPlaceholder' | translate"></textarea>
</label>
@if (fields.length === 0) {
<p class="spell-fields-hint">
{{ 'spellCatalog.noFieldsHint' | translate }}
<button type="button" class="link-button" (click)="selectView('fields')">
{{ 'spellCatalog.views.fields' | translate }}
</button>
</p>
}
</div>
}
</article>
}
@if (spells.length === 0) {
<div class="spell-empty">
<lucide-icon [img]="WandSparkles" [size]="22"></lucide-icon>
<p>{{ 'spellCatalog.empty' | translate }}</p>
</div>
} @else if (visibleSpells.length === 0) {
<div class="spell-empty">
<p>{{ 'spellCatalog.noMatch' | translate }}</p>
</div>
}
</div>
}
@if (view === 'fields') {
<app-template-fields-editor
[label]="'spellCatalog.fieldsLabel' | translate"
[hint]="'spellCatalog.fieldsHint' | translate"
[fields]="template"
[suggestions]="fieldSuggestions"
[simpleOnly]="true"
(fieldsChange)="onTemplateChange($event)">
</app-template-fields-editor>
<p class="spell-fields-hint">{{ 'spellCatalog.fieldsRenameHint' | translate }}</p>
}
@@ -0,0 +1,363 @@
:host {
display: flex;
flex-direction: column;
gap: 1rem;
}
.sections-title {
font-size: 1rem;
font-weight: 600;
color: white;
margin: 0;
}
.sections-hint {
color: #6b7280;
font-size: 0.85rem;
margin: -0.75rem 0 0;
}
.link-button {
display: inline-flex;
align-items: center;
gap: 0.3rem;
background: transparent;
border: none;
padding: 0;
color: #a78bfa;
font-size: 0.85rem;
cursor: pointer;
&:hover { text-decoration: underline; }
}
// --- Catalogue / Champs d'un sort ------------------------------------------
.spell-views {
display: flex;
gap: 0.4rem;
}
.spell-view {
padding: 0.4rem 0.85rem;
border-radius: 999px;
border: 1px solid #374151;
background: transparent;
color: #d1d5db;
font-size: 0.85rem;
cursor: pointer;
&.active { border-color: #6c63ff; background: rgba(108, 99, 255, 0.15); color: white; }
}
// --- Recherche, filtres, ajout ----------------------------------------------
.spell-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
select {
padding: 0.45rem 0.6rem;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 8px;
color: #e5e7eb;
font-size: 0.85rem;
font-family: inherit;
max-width: 14rem;
&:focus { outline: none; border-color: #a78bfa; }
}
}
.spell-search {
display: flex;
align-items: center;
gap: 0.4rem;
flex: 1 1 14rem;
max-width: 22rem;
padding: 0 0.6rem;
background: #0b1220;
border: 1px solid #1f2937;
border-radius: 8px;
color: #6b7280;
&:focus-within { border-color: #a78bfa; }
input {
flex: 1;
min-width: 0;
padding: 0.45rem 0;
background: transparent;
border: none;
outline: none;
color: #e5e7eb;
font-size: 0.9rem;
font-family: inherit;
}
}
.spell-toolbar-actions {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
margin-left: auto;
}
.btn-propose-spells {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.9rem;
background: #1f2937;
color: #e5e7eb;
border: 1px solid #374151;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
&:hover { background: #273244; border-color: #6c63ff; }
}
.btn-add-spell {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.9rem;
background: rgba(167, 139, 250, 0.14);
color: #ddd6fe;
border: 1px solid rgba(167, 139, 250, 0.45);
border-radius: 8px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
&:hover { background: rgba(167, 139, 250, 0.24); border-color: #a78bfa; }
}
.spell-status {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.75rem;
color: #9ca3af;
font-size: 0.85rem;
> span:first-child { display: inline-flex; align-items: center; gap: 0.6rem; }
}
.spell-status-actions {
display: inline-flex;
align-items: center;
gap: 1rem;
}
// --- Cartes de sort ---------------------------------------------------------
.spell-list {
display: flex;
flex-direction: column;
gap: 0.55rem;
}
.spell-card {
background: #0b1220;
border: 1px solid #1f2937;
border-left: 3px solid #6c63ff;
border-radius: 10px;
overflow: hidden;
transition: border-color 0.15s;
&.collapsed {
background: #0a0f1a;
border-left-color: #312e81;
&:hover { border-color: #374151; border-left-color: #6c63ff; }
}
&:focus-within { border-color: #374151; border-left-color: #a78bfa; }
}
.spell-head {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.45rem 0.5rem 0.45rem 0.25rem;
}
.spell-toggle,
.spell-remove {
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.9rem;
height: 1.9rem;
background: transparent;
border: none;
border-radius: 6px;
color: #6b7280;
cursor: pointer;
&:hover { color: #e5e7eb; background: rgba(255, 255, 255, 0.05); }
}
.spell-remove:hover { color: #fca5a5; }
.spell-summary {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.15rem 0;
background: transparent;
border: none;
color: inherit;
font-family: inherit;
text-align: left;
cursor: pointer;
}
.spell-level {
flex-shrink: 0;
min-width: 1.75rem;
max-width: 9rem;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background: rgba(108, 99, 255, 0.2);
border: 1px solid rgba(108, 99, 255, 0.5);
color: #ddd6fe;
font-size: 0.75rem;
font-weight: 700;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.spell-title {
flex-shrink: 0;
max-width: 45%;
color: white;
font-size: 0.95rem;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&--empty { color: #fca5a5; font-weight: 500; font-style: italic; }
}
.spell-school {
flex-shrink: 0;
max-width: 10rem;
padding: 0.1rem 0.5rem;
border-radius: 999px;
background: #1f2937;
color: #9ca3af;
font-size: 0.72rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.spell-excerpt {
flex: 1;
min-width: 0;
color: #6b7280;
font-size: 0.82rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.spell-name {
flex: 1;
min-width: 0;
padding: 0.4rem 0.6rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 8px;
color: white;
font-size: 0.95rem;
font-weight: 600;
font-family: inherit;
&:focus { outline: none; border-color: #a78bfa; }
}
.spell-body {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0.25rem 0.9rem 0.9rem 2.5rem;
}
.spell-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr));
gap: 0.6rem 0.75rem;
}
.spell-field {
display: flex;
flex-direction: column;
gap: 0.25rem;
min-width: 0;
> span {
color: #9ca3af;
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.03em;
text-transform: uppercase;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
input, textarea {
padding: 0.45rem 0.6rem;
background: #111827;
border: 1px solid #1f2937;
border-radius: 8px;
color: #e5e7eb;
font-size: 0.9rem;
font-family: inherit;
&:focus { outline: none; border-color: #a78bfa; }
}
textarea { resize: vertical; line-height: 1.5; }
}
.spell-fields-hint {
margin: 0;
color: #6b7280;
font-size: 0.8rem;
}
.spell-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 1.75rem 1rem;
border: 1px dashed #1f2937;
border-radius: 10px;
color: #6b7280;
font-size: 0.9rem;
text-align: center;
p { margin: 0; max-width: 34rem; }
}
@media (max-width: 767.98px) {
.spell-body { padding-left: 0.9rem; }
.spell-excerpt { display: none; }
.spell-title { max-width: none; flex: 1; }
.spell-toolbar-actions { margin-left: 0; }
}
@@ -0,0 +1,166 @@
import { Component, ElementRef, EventEmitter, Input, Output, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TranslatePipe } from '@ngx-translate/core';
import {
LucideAngularModule, ArrowDownNarrowWide, ChevronDown, ChevronRight, Plus, Search, Sparkles, Trash2, WandSparkles, X
} from 'lucide-angular';
import { ProposedSpell } from '../../services/spell.model';
import { TemplateField } from '../../services/template.model';
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
import {
NO_FILTER, SpellDraft, SpellFilter, distinctValues, filterSpells, isFiltering, newSpell, sortByLevelThenName,
summary, usableFields
} from '../spell-catalog.util';
import { SpellProposalComponent } from '../spell-proposal/spell-proposal.component';
import { RuleText, addProposedSpells } from '../spell-proposal.util';
/** Les deux vues de l'onglet : le catalogue, et les champs que porte chaque sort. */
export type SpellView = 'catalog' | 'fields';
/** Champs souvent utiles à un sort, proposés en ajout rapide (comme pour les fiches). */
const FIELD_SUGGESTIONS = ['Portée', 'Durée', 'Temps d\'incantation', 'Coût en mana', 'Composantes', 'Cible'];
/**
* Onglet « Sorts » de l'édition d'un système : le catalogue des sorts eux-mêmes (un sort =
* une fiche) et le modèle de sort (champs propres au système). Les règles de magie, elles,
* restent dans l'onglet Règles.
*
* Le composant ne fait qu'éditer les listes que lui prête l'écran parent : rien n'est
* enregistré ici, c'est l'enregistrement du système qui envoie le catalogue.
*/
@Component({
selector: 'app-spell-catalog-editor',
imports: [FormsModule, TranslatePipe, LucideAngularModule, TemplateFieldsEditorComponent, SpellProposalComponent],
templateUrl: './spell-catalog-editor.component.html',
styleUrls: ['./spell-catalog-editor.component.scss']
})
export class SpellCatalogEditorComponent {
readonly ArrowDownNarrowWide = ArrowDownNarrowWide;
readonly ChevronDown = ChevronDown;
readonly ChevronRight = ChevronRight;
readonly Plus = Plus;
readonly Search = Search;
readonly Sparkles = Sparkles;
readonly Trash2 = Trash2;
readonly WandSparkles = WandSparkles;
readonly X = X;
readonly views: SpellView[] = ['catalog', 'fields'];
readonly fieldSuggestions = FIELD_SUGGESTIONS;
private readonly host: ElementRef<HTMLElement> = inject(ElementRef);
/** Sorts du catalogue. La liste est remplacée (jamais modifiée sur place) à chaque ajout, retrait ou tri. */
@Input() spells: SpellDraft[] = [];
@Output() spellsChange = new EventEmitter<SpellDraft[]>();
/** Modèle de sort : champs propres au système. */
@Input() template: TemplateField[] = [];
@Output() templateChange = new EventEmitter<TemplateField[]>();
@Input() view: SpellView = 'catalog';
@Output() viewChange = new EventEmitter<SpellView>();
/** Règles affichées dans l'éditeur du système : la matière de la proposition de sorts. */
@Input() rules: RuleText[] = [];
@Input() systemName = '';
filter: SpellFilter = { ...NO_FILTER };
/** La proposition de sorts à partir des règles est-elle ouverte ? */
proposing = false;
selectView(view: SpellView): void {
this.view = view;
this.viewChange.emit(view);
}
// ─────────────── Catalogue ───────────────
get visibleSpells(): SpellDraft[] {
return filterSpells(this.spells, this.filter);
}
get filtering(): boolean {
return isFiltering(this.filter);
}
get levels(): string[] {
return distinctValues(this.spells, 'level');
}
get schools(): string[] {
return distinctValues(this.spells, 'school');
}
/** Champs du modèle affichés dans chaque sort. */
get fields(): TemplateField[] {
return usableFields(this.template);
}
summaryOf(spell: SpellDraft): string {
return summary(spell);
}
clearFilter(): void {
this.filter = { ...NO_FILTER };
}
/** Nouveau sort en tête de liste, ouvert, le curseur dans son nom. */
addSpell(): void {
this.clearFilter();
this.spells = [newSpell(), ...this.spells];
this.spellsChange.emit(this.spells);
setTimeout(() => this.host.nativeElement.querySelector<HTMLInputElement>('.spell-card .spell-name')?.focus());
}
removeSpell(spell: SpellDraft): void {
this.spells = this.spells.filter(s => s !== spell);
this.spellsChange.emit(this.spells);
}
toggle(spell: SpellDraft): void {
spell.collapsed = !spell.collapsed;
}
/** Range le catalogue par niveau puis par nom, une fois : l'ordre ne bouge pas pendant la saisie. */
sort(): void {
this.spells.forEach(s => { s.collapsed = true; });
this.spells = sortByLevelThenName(this.spells);
this.spellsChange.emit(this.spells);
}
get allCollapsed(): boolean {
return this.visibleSpells.length > 0 && this.visibleSpells.every(s => s.collapsed);
}
toggleAllCollapsed(): void {
const collapsed = !this.allCollapsed;
this.visibleSpells.forEach(s => { s.collapsed = collapsed; });
}
/** Ouvre un sort et l'amène à l'écran (appelé par le parent quand il bloque l'enregistrement). */
reveal(spell: SpellDraft): void {
this.clearFilter();
this.selectView('catalog');
spell.collapsed = false;
const index = this.spells.indexOf(spell);
setTimeout(() => this.host.nativeElement.querySelectorAll<HTMLElement>('.spell-card')[index]
?.scrollIntoView({ block: 'center' }));
}
/**
* Ajoute au catalogue les sorts cochés dans la proposition, à la suite. Les sorts déjà
* présents ne sont pas touchés ; rien n'est enregistré avant l'enregistrement du système.
*/
onProposed(proposals: ProposedSpell[]): void {
this.clearFilter();
this.spells = addProposedSpells(this.spells, proposals);
this.spellsChange.emit(this.spells);
}
// ─────────────── Champs d'un sort ───────────────
onTemplateChange(template: TemplateField[]): void {
this.template = template;
this.templateChange.emit(template);
}
}
@@ -0,0 +1,97 @@
import { Spell } from '../services/spell.model';
import { TemplateField } from '../services/template.model';
import {
NO_FILTER, distinctValues, filterSpells, firstUnnamedSpell, hasInvalidField, isEmptySpell, isFiltering,
newSpell, sortByLevelThenName, summary, toDraft, toPayload, usableFields
} from './spell-catalog.util';
const spell = (name: string, extra: Partial<Spell> = {}): Spell => ({ name, values: {}, ...extra });
const field = (name: string): TemplateField => ({ name, type: 'TEXT' } as TemplateField);
describe('spell-catalog.util', () => {
it('un sort ajouté puis laissé vide n\'est ni enregistré ni bloquant', () => {
const empty = newSpell();
expect(isEmptySpell(empty)).toBe(true);
expect(isEmptySpell(spell('', { values: { Portée: ' ' } }))).toBe(true);
expect(isEmptySpell(spell('', { values: { Portée: '12 m' } }))).toBe(false);
expect(firstUnnamedSpell([empty, spell('Éclair')])).toBeNull();
});
it('un sort rempli mais sans nom bloque l\'enregistrement', () => {
const unnamed = spell(' ', { description: 'Un trait de brume.' });
expect(firstUnnamedSpell([spell('Éclair'), unnamed])).toBe(unnamed);
});
it('prépare l\'envoi : sorts vides retirés, textes nettoyés, valeurs vides retirées', () => {
const payload = toPayload([
{ id: '7', name: ' Éclair ', level: ' 1 ', school: '', description: ' Un trait. ', values: { Portée: ' 12 m ', Durée: ' ' } },
newSpell(),
spell('Voile')
]);
expect(payload).toEqual([
{ id: '7', name: 'Éclair', level: '1', school: null, description: 'Un trait.', values: { Portée: '12 m' } },
{ id: null, name: 'Voile', level: null, school: null, description: null, values: {} }
]);
});
it('charge un sort replié, sans partager ses valeurs avec la réponse du serveur', () => {
const source: Spell = { id: '3', name: 'Voile', level: null, values: { Portée: 'soi' } };
const draft = toDraft(source);
draft.values['Portée'] = 'contact';
expect(draft.collapsed).toBe(true);
expect(draft.level).toBe('');
expect(source.values['Portée']).toBe('soi');
});
it('cherche dans le nom, la description et les valeurs, et filtre par niveau et par école', () => {
const spells = [
spell('Éclair de brume', { level: '1', school: 'Évocation', description: 'Un trait glacé.' }),
spell('Voile', { level: '1', school: 'Illusion', values: { Portée: 'Brume proche' } }),
spell('Tempête', { level: '3', school: 'Évocation' })
];
const names = (filter: Partial<typeof NO_FILTER>) =>
filterSpells(spells, { ...NO_FILTER, ...filter }).map(s => s.name);
expect(names({})).toEqual(['Éclair de brume', 'Voile', 'Tempête']);
expect(names({ text: 'BRUME' })).toEqual(['Éclair de brume', 'Voile']);
expect(names({ text: 'glacé' })).toEqual(['Éclair de brume']);
expect(names({ level: '1', school: 'Évocation' })).toEqual(['Éclair de brume']);
expect(names({ school: 'Évocation', text: 'temp' })).toEqual(['Tempête']);
expect(isFiltering(NO_FILTER)).toBe(false);
expect(isFiltering({ ...NO_FILTER, text: ' ' })).toBe(false);
expect(isFiltering({ ...NO_FILTER, level: '1' })).toBe(true);
});
it('liste les niveaux et les écoles présents, dans l\'ordre naturel', () => {
const spells = [spell('A', { level: '10' }), spell('B', { level: ' 2 ' }), spell('C', { level: '2', school: 'Illusion' }),
spell('D', { school: 'Abjuration' }), spell('E', { level: 'Tour de magie' })];
expect(distinctValues(spells, 'level')).toEqual(['2', '10', 'Tour de magie']);
expect(distinctValues(spells, 'school')).toEqual(['Abjuration', 'Illusion']);
});
it('range par niveau puis par nom, les sorts sans niveau à la fin, sans modifier la liste reçue', () => {
const spells = [spell('Voile', { level: '2' }), spell('Sans niveau'), spell('Tempête', { level: '10' }),
spell('éclair', { level: '2' }), spell('Bouclier', { level: '1' })];
expect(sortByLevelThenName(spells).map(s => s.name))
.toEqual(['Bouclier', 'éclair', 'Voile', 'Tempête', 'Sans niveau']);
expect(spells[0].name).toBe('Voile');
});
it('résume la description sur une ligne', () => {
expect(summary(spell('A', { description: ' Un trait\n de brume. ' }))).toBe('Un trait de brume.');
expect(summary(spell('A', { description: 'x'.repeat(200) }), 10)).toBe('xxxxxxxxxx…');
expect(summary(spell('A'))).toBe('');
});
it('ne garde du modèle que les champs nommés, et signale un champ sans nom ou en double', () => {
expect(usableFields([field('Portée'), field(' ')]).map(f => f.name)).toEqual(['Portée']);
expect(hasInvalidField([field('Portée'), field('Durée')])).toBe(false);
expect(hasInvalidField([field('Portée'), field('portée ')])).toBe(true);
expect(hasInvalidField([field('')])).toBe(true);
expect(hasInvalidField([])).toBe(false);
});
});
@@ -0,0 +1,130 @@
import { Spell } from '../services/spell.model';
import { TemplateField } from '../services/template.model';
/**
* Catalogue de sorts : logique pure de l'onglet « Sorts » (recherche, filtres, tri, contrôle
* avant enregistrement). Le composant ne fait qu'afficher.
*/
/** Un sort en cours d'édition : replié ou non dans la liste. */
export interface SpellDraft extends Spell {
collapsed: boolean;
}
export interface SpellFilter {
/** Cherché dans le nom, la description et les valeurs. */
text: string;
/** Niveau exact, ou '' pour tous. */
level: string;
/** École exacte, ou '' pour toutes. */
school: string;
}
export const NO_FILTER: SpellFilter = { text: '', level: '', school: '' };
/** « 2 » avant « 10 », « Rang II » après « Rang I », sans tenir compte de la casse ni des accents. */
const NATURAL = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
/** Un champ « nombre » rend un nombre, pas une chaîne : tout passe par ici. */
const clean = (value: unknown): string => (value == null ? '' : String(value)).trim();
export function newSpell(): SpellDraft {
return { name: '', level: '', school: '', description: '', values: {}, collapsed: false };
}
export function toDraft(spell: Spell): SpellDraft {
return {
id: spell.id ?? null,
name: spell.name ?? '',
level: spell.level ?? '',
school: spell.school ?? '',
description: spell.description ?? '',
values: { ...(spell.values ?? {}) },
collapsed: true
};
}
/** Un sort resté entièrement vide (ajouté puis abandonné) : il n'est pas enregistré. */
export function isEmptySpell(spell: Spell): boolean {
return !clean(spell.name) && !clean(spell.level) && !clean(spell.school) && !clean(spell.description)
&& Object.values(spell.values ?? {}).every(v => !clean(v));
}
/** Premier sort rempli mais sans nom : il bloque l'enregistrement. */
export function firstUnnamedSpell<T extends Spell>(spells: T[]): T | null {
return spells.find(s => !clean(s.name) && !isEmptySpell(s)) ?? null;
}
/** Ce qui part à l'enregistrement : sorts non vides, textes nettoyés, valeurs vides retirées. */
export function toPayload(spells: Spell[]): Spell[] {
return spells.filter(s => !isEmptySpell(s)).map(s => ({
id: s.id ?? null,
name: clean(s.name),
level: clean(s.level) || null,
school: clean(s.school) || null,
description: clean(s.description) || null,
values: Object.fromEntries(Object.entries(s.values ?? {})
.map(([key, value]) => [key, clean(value)] as const)
.filter(([, value]) => value))
}));
}
export function matchesFilter(spell: Spell, filter: SpellFilter): boolean {
if (filter.level && clean(spell.level) !== filter.level) return false;
if (filter.school && clean(spell.school) !== filter.school) return false;
const needle = filter.text.trim().toLowerCase();
if (!needle) return true;
return [spell.name, spell.description, ...Object.values(spell.values ?? {})]
.some(text => clean(text).toLowerCase().includes(needle));
}
export function filterSpells<T extends Spell>(spells: T[], filter: SpellFilter): T[] {
return spells.filter(s => matchesFilter(s, filter));
}
export function isFiltering(filter: SpellFilter): boolean {
return !!(filter.text.trim() || filter.level || filter.school);
}
/** Niveaux (ou écoles) présents dans le catalogue, sans doublon, dans l'ordre naturel. */
export function distinctValues(spells: Spell[], key: 'level' | 'school'): string[] {
return [...new Set(spells.map(s => clean(s[key])).filter(Boolean))].sort(NATURAL.compare);
}
/**
* Catalogue rangé par niveau puis par nom (nouvelle liste). Les sorts sans niveau vont à la
* fin ; à égalité, l'ordre d'origine est gardé.
*/
export function sortByLevelThenName<T extends Spell>(spells: T[]): T[] {
return spells
.map((spell, index) => ({ spell, index }))
.sort((a, b) => {
const la = clean(a.spell.level);
const lb = clean(b.spell.level);
if (!la !== !lb) return la ? -1 : 1;
return NATURAL.compare(la, lb) || NATURAL.compare(clean(a.spell.name), clean(b.spell.name)) || a.index - b.index;
})
.map(entry => entry.spell);
}
/** Début de la description, sur une ligne, pour la carte repliée. */
export function summary(spell: Spell, max = 140): string {
const text = clean(spell.description).replace(/\s+/g, ' ');
return text.length > max ? text.slice(0, max).trimEnd() + '…' : text;
}
/** Champs du modèle utilisables dans un sort : ceux qui ont un nom. */
export function usableFields(template: TemplateField[]): TemplateField[] {
return template.filter(f => clean(f.name));
}
/** Le modèle a-t-il un champ sans nom ou en double (sans tenir compte de la casse) ? */
export function hasInvalidField(template: TemplateField[]): boolean {
const seen = new Set<string>();
for (const field of template) {
const name = clean(field.name).toLowerCase();
if (!name || seen.has(name)) return true;
seen.add(name);
}
return false;
}
@@ -0,0 +1,88 @@
import { ProposedSpell } from '../services/spell.model';
import { SpellDraft } from './spell-catalog.util';
import {
addProposedSpells, chunksFor, isInCatalogue, looksLikeMagic, splitText, suggestedSections
} from './spell-proposal.util';
const draft = (name: string, extra: Partial<SpellDraft> = {}): SpellDraft =>
({ name, level: '', school: '', description: '', values: {}, collapsed: true, ...extra });
const proposed = (name: string, extra: Partial<ProposedSpell> = {}): ProposedSpell =>
({ name, level: '', school: '', description: 'Un effet.', values: {}, excerpt: 'Un passage des règles.', ...extra });
describe('spell-proposal.util', () => {
it('reconnaît les sections qui parlent de magie, en français et en anglais', () => {
expect(looksLikeMagic('Magie et sorts')).toBe(true);
expect(looksLikeMagic('SPELLS')).toBe(true);
expect(looksLikeMagic('Prières et miracles')).toBe(true);
expect(looksLikeMagic('Combat')).toBe(false);
expect(suggestedSections([{ title: 'Combat', content: 'x' }, { title: 'Cast Spell', content: 'x' },
{ title: 'Mage', content: 'x' }])).toEqual(['Cast Spell', 'Mage']);
expect(suggestedSections([{ title: 'Combat', content: 'x' }])).toEqual([]);
});
it('laisse entier un texte qui tient dans un morceau', () => {
expect(splitText(' Un texte court. ', 100)).toEqual(['Un texte court.']);
expect(splitText(' ', 100)).toEqual([]);
});
it('coupe avant un titre plutôt qu\'au milieu d\'un sort', () => {
const spell = (name: string) => `### ${name}\n${'x'.repeat(30)}\n\n${'y'.repeat(30)}`;
const text = ['Préambule de la section.', spell('Éclair'), spell('Voile'), spell('Tempête')].join('\n\n');
const chunks = splitText(text, 150);
expect(chunks.every(c => c.length <= 150)).toBe(true);
// Chaque sort reste entier dans son morceau : titre, premier et second paragraphe ensemble.
for (const name of ['Éclair', 'Voile', 'Tempête']) {
const holder = chunks.filter(c => c.includes(`### ${name}`));
expect(holder).toHaveLength(1);
expect(holder[0]).toContain(`### ${name}\n${'x'.repeat(30)}\n\n${'y'.repeat(30)}`);
}
expect(chunks.join('\n\n')).toBe(text);
});
it('recoupe aux lignes vides, puis net, un bloc trop long pour un morceau', () => {
const chunks = splitText(`### Long\n${'a'.repeat(40)}\n\n${'b'.repeat(40)}\n\n${'c'.repeat(130)}`, 60);
expect(chunks.every(c => c.length <= 60)).toBe(true);
expect(chunks[0]).toBe(`### Long\n${'a'.repeat(40)}`);
expect(chunks[1]).toBe('b'.repeat(40));
expect(chunks.slice(2).join('')).toBe('c'.repeat(130));
});
it('prépare les morceaux des sections cochées, dans l\'ordre du livre, avec leur rang', () => {
const rules = [
{ title: 'Combat', content: 'Jamais lu.' },
{ title: 'Magie', content: `### A\n${'x'.repeat(50)}\n\n### B\n${'y'.repeat(50)}` },
{ title: 'Prières', content: 'Une prière courte.' },
{ title: 'Vide', content: ' ' }
];
const chunks = chunksFor(rules, new Set(['Prières', 'Magie', 'Vide']), 70);
expect(chunks.map(c => [c.title, c.part, c.parts])).toEqual([['Magie', 1, 2], ['Magie', 2, 2], ['Prières', 1, 1]]);
expect(chunks[1].text).toBe(`### B\n${'y'.repeat(50)}`);
});
it('ajoute les sorts proposés à la suite, repliés, sans toucher à ceux du catalogue', () => {
const existing = draft('Éclair de givre', { id: '7', description: 'Ma version.' });
const values = { Portée: '12 m' };
const out = addProposedSpells([existing], [
proposed(' éclair de GIVRE ', { description: 'Version des règles.' }),
proposed(' Voile de brume ', { level: '1', school: 'Illusion', values }),
proposed('voile de brume'),
proposed(' ')
]);
expect(out.map(s => s.name)).toEqual(['Éclair de givre', 'Voile de brume']);
expect(out[0]).toBe(existing);
expect(out[0].description).toBe('Ma version.');
expect(out[1]).toEqual({ name: 'Voile de brume', level: '1', school: 'Illusion', description: 'Un effet.',
values: { Portée: '12 m' }, collapsed: true });
out[1].values['Portée'] = 'soi';
expect(values.Portée).toBe('12 m');
expect(isInCatalogue(out, 'VOILE DE BRUME')).toBe(true);
expect(isInCatalogue(out, ' ')).toBe(false);
});
});
@@ -0,0 +1,140 @@
import { ProposedSpell } from '../services/spell.model';
import { SpellDraft } from './spell-catalog.util';
/**
* Proposition de sorts à partir des règles : logique pure (sections à lire, découpage en
* morceaux, ajout au catalogue).
*
* Règle d'or, comme pour les fiches : la proposition ne fait qu'AJOUTER. Un sort déjà dans
* le catalogue n'est ni modifié ni remplacé.
*/
export interface RuleText {
title: string;
content: string;
}
/** Un morceau de règles lu en un appel. `part` / `parts` : sa place dans sa section. */
export interface ReadingChunk {
title: string;
text: string;
part: number;
parts: number;
}
/** Taille d'un morceau (le Core refuse au-delà de 12 000 caractères). */
export const MAX_CHUNK_CHARS = 8_000;
/** Mots qui signalent, dans un titre de section, des règles de magie ou une liste de sorts. */
const MAGIC_WORDS = ['magie', 'magic', 'sort', 'spell', 'incantation', 'grimoire', 'pouvoir', 'power', 'prière',
'priere', 'prayer', 'rituel', 'ritual', 'arcane', 'miracle', 'enchantement', 'mage', 'wizard', 'sorcier', 'cantrip'];
const key = (name: string | null | undefined): string => (name ?? '').trim().toLowerCase();
/** Le titre de cette section laisse-t-il penser qu'elle décrit des sorts ? */
export function looksLikeMagic(title: string): boolean {
const lower = key(title);
return MAGIC_WORDS.some(word => lower.includes(word));
}
/** Sections cochées d'office : celles qui parlent de magie ; à défaut, aucune. */
export function suggestedSections(rules: RuleText[]): string[] {
return rules.filter(r => looksLikeMagic(r.title)).map(r => r.title);
}
/**
* Découpe un texte en morceaux d'au plus `max` caractères. On coupe de préférence avant un
* titre markdown (un sort commence souvent par le sien), sinon à une ligne vide, sinon net :
* un sort à cheval sur deux morceaux serait relevé à moitié.
*/
export function splitText(content: string, max = MAX_CHUNK_CHARS): string[] {
const text = content.trim();
if (!text) return [];
if (text.length <= max) return [text];
// Blocs insécables : un titre et ce qui le suit, jusqu'au titre suivant.
const blocks: string[] = [];
let current: string[] = [];
for (const line of text.split('\n')) {
if (/^#{1,6}\s/.test(line) && current.some(l => l.trim())) {
blocks.push(current.join('\n').trim());
current = [];
}
current.push(line);
}
if (current.some(l => l.trim())) blocks.push(current.join('\n').trim());
// Un bloc trop long est recoupé aux lignes vides, puis net.
const pieces = blocks.flatMap(block => block.length <= max ? [block] : splitOnBlankLines(block, max));
const chunks: string[] = [];
let buffer = '';
for (const piece of pieces) {
if (buffer && buffer.length + 2 + piece.length > max) {
chunks.push(buffer);
buffer = '';
}
buffer = buffer ? `${buffer}\n\n${piece}` : piece;
}
if (buffer) chunks.push(buffer);
return chunks;
}
function splitOnBlankLines(block: string, max: number): string[] {
const out: string[] = [];
let buffer = '';
for (let paragraph of block.split(/\n\s*\n/).map(p => p.trim()).filter(Boolean)) {
if (buffer && buffer.length + 2 + paragraph.length > max) {
out.push(buffer);
buffer = '';
}
while (paragraph.length > max) {
if (buffer) {
out.push(buffer);
buffer = '';
}
out.push(paragraph.slice(0, max));
paragraph = paragraph.slice(max).trim();
}
if (paragraph) buffer = buffer ? `${buffer}\n\n${paragraph}` : paragraph;
}
if (buffer) out.push(buffer);
return out;
}
/** Morceaux à lire pour ces sections, dans l'ordre du livre. */
export function chunksFor(rules: RuleText[], selected: ReadonlySet<string>, max = MAX_CHUNK_CHARS): ReadingChunk[] {
return rules
.filter(r => selected.has(r.title))
.flatMap(r => {
const texts = splitText(r.content, max);
return texts.map((text, index) => ({ title: r.title, text, part: index + 1, parts: texts.length }));
});
}
/** Le catalogue contient-il déjà un sort de ce nom (sans tenir compte de la casse) ? */
export function isInCatalogue(spells: { name: string }[], name: string): boolean {
const wanted = key(name);
return !!wanted && spells.some(s => key(s.name) === wanted);
}
/**
* Ajoute au catalogue les sorts proposés qui n'y sont pas encore, à la suite, repliés. Aucun
* sort existant n'est modifié, retiré ni déplacé.
*/
export function addProposedSpells(spells: SpellDraft[], proposals: ProposedSpell[]): SpellDraft[] {
const out = [...spells];
for (const p of proposals) {
const name = p.name?.trim();
if (!name || isInCatalogue(out, name)) continue;
out.push({
name,
level: p.level ?? '',
school: p.school ?? '',
description: p.description ?? '',
values: { ...(p.values ?? {}) },
collapsed: true
});
}
return out;
}
@@ -0,0 +1,133 @@
<section class="proposal" [attr.aria-label]="'spellCatalog.proposal.title' | translate">
<h3>
<lucide-icon [img]="Sparkles" [size]="15"></lucide-icon>
{{ 'spellCatalog.proposal.title' | translate }}
</h3>
@if (rules.length === 0) {
<p class="proposal-hint">{{ 'spellCatalog.proposal.needsRules' | translate }}</p>
} @else {
@if (stage === 'choose') {
<p class="proposal-hint">{{ 'spellCatalog.proposal.intro' | translate }}</p>
@if (fields.length === 0) {
<p class="proposal-hint">{{ 'spellCatalog.proposal.noFields' | translate }}</p>
}
<ul class="proposal-sections">
@for (rule of rules; track rule.title) {
<li>
<label class="proposal-check">
<input type="checkbox" [checked]="isSectionSelected(rule.title)" (change)="toggleSection(rule.title)" />
<span>{{ rule.title }}</span>
</label>
<span class="proposal-size">{{ 'spellCatalog.proposal.sectionSize' | translate:{ count: rule.content.length } }}</span>
</li>
}
</ul>
}
@if (stage === 'reading' || stage === 'paused') {
<div class="proposal-progress" role="status">
@if (currentChunk; as chunk) {
<p class="proposal-phase">
{{ (stage === 'reading' ? 'spellCatalog.proposal.reading' : 'spellCatalog.proposal.paused')
| translate:{ n: index + 1, total: chunks.length, title: chunk.title } }}
</p>
}
<div class="proposal-bar">
<div class="proposal-bar-fill" [style.width.%]="chunks.length ? (index / chunks.length) * 100 : 0"></div>
</div>
@if (stage === 'reading') {
<p class="proposal-hint">{{ 'spellCatalog.proposal.readingHint' | translate }}</p>
}
</div>
}
@if (stage === 'paused') {
<p class="proposal-error" role="alert">
{{ 'spellCatalog.proposal.failed' | translate:{ reason: error } }}
</p>
}
@if (stage === 'done') {
<p class="proposal-hint" role="status">
{{ (complete ? 'spellCatalog.proposal.done' : 'spellCatalog.proposal.stopped')
| translate:{ n: index, total: chunks.length } }}
</p>
}
@if (stage !== 'choose') {
@if (found.length > 0) {
<p class="proposal-hint">{{ 'spellCatalog.proposal.foundIntro' | translate }}</p>
<ul class="proposal-found">
@for (item of found; track item.spell.name) {
<li>
<label class="proposal-item" [class.present]="isInCatalogue(item.spell.name)">
<input type="checkbox" [checked]="isSelected(item.spell.name)"
[disabled]="isInCatalogue(item.spell.name)" (change)="toggle(item.spell.name)" />
<span class="proposal-main">
@if (item.spell.level) {
<span class="proposal-level">{{ item.spell.level }}</span>
}
<span class="proposal-name">{{ item.spell.name }}</span>
@if (item.spell.school) {
<span class="proposal-school">{{ item.spell.school }}</span>
}
@if (isInCatalogue(item.spell.name)) {
<span class="proposal-present">{{ 'spellCatalog.proposal.already' | translate }}</span>
} @else {
<span class="proposal-source">{{ 'spellCatalog.proposal.source' | translate:{ section: item.source } }}</span>
}
<span class="proposal-excerpt">{{ summaryOf(item.spell) }}</span>
</span>
</label>
</li>
}
</ul>
<p class="proposal-hint">{{ 'spellCatalog.proposal.reviewHint' | translate }}</p>
} @else if (stage === 'done') {
<p class="proposal-hint">{{ 'spellCatalog.proposal.nothing' | translate }}</p>
}
@if (dropped > 0) {
<p class="proposal-hint">
{{ (dropped === 1 ? 'spellCatalog.proposal.droppedOne' : 'spellCatalog.proposal.droppedMany')
| translate:{ count: dropped } }}
</p>
}
@if (added) {
<p class="proposal-added" role="status">{{ 'spellCatalog.proposal.added' | translate:{ count: added } }}</p>
}
}
}
<div class="proposal-actions">
@if (stage === 'choose' && rules.length > 0) {
<button type="button" class="btn-primary" [disabled]="plannedChunks === 0" (click)="start()">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'spellCatalog.proposal.start' | translate }}
</button>
@if (plannedChunks > 0) {
<span class="proposal-hint">
{{ (plannedChunks === 1 ? 'spellCatalog.proposal.plannedOne' : 'spellCatalog.proposal.plannedMany')
| translate:{ count: plannedChunks } }}
</span>
} @else {
<span class="proposal-hint">{{ 'spellCatalog.proposal.needsSection' | translate }}</span>
}
}
@if (stage !== 'choose' && found.length > 0) {
<button type="button" class="btn-primary" [disabled]="selectedSpells.length === 0" (click)="addSelected()">
{{ 'spellCatalog.proposal.add' | translate:{ count: selectedSpells.length } }}
</button>
}
@if (stage === 'reading') {
<button type="button" class="btn-secondary" (click)="stop()">{{ 'spellCatalog.proposal.stop' | translate }}</button>
}
@if (stage === 'paused') {
<button type="button" class="btn-secondary" (click)="resume()">{{ 'spellCatalog.proposal.resume' | translate }}</button>
}
@if (stage !== 'reading') {
<button type="button" class="btn-secondary" (click)="close()">{{ 'spellCatalog.proposal.close' | translate }}</button>
}
</div>
</section>
@@ -0,0 +1,216 @@
.proposal {
display: flex;
flex-direction: column;
gap: 0.7rem;
padding: 0.9rem 1rem;
background: #0b1220;
border: 1px solid rgba(167, 139, 250, 0.35);
border-radius: 10px;
h3 {
display: flex;
align-items: center;
gap: 0.45rem;
margin: 0;
color: #ddd6fe;
font-size: 0.95rem;
font-weight: 600;
}
}
.proposal-hint {
margin: 0;
color: #9ca3af;
font-size: 0.82rem;
line-height: 1.45;
}
.proposal-error {
margin: 0;
color: #fca5a5;
font-size: 0.85rem;
}
.proposal-added {
margin: 0;
color: #86efac;
font-size: 0.85rem;
}
// --- Sections à lire ---------------------------------------------------------
.proposal-sections,
.proposal-found {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.proposal-sections {
max-height: 16rem;
overflow-y: auto;
border: 1px solid #1f2937;
border-radius: 8px;
padding: 0.35rem 0.6rem;
li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.2rem 0;
}
}
.proposal-check {
display: inline-flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
color: #e5e7eb;
font-size: 0.9rem;
cursor: pointer;
input { accent-color: #a78bfa; flex-shrink: 0; }
}
.proposal-size {
flex-shrink: 0;
color: #6b7280;
font-size: 0.75rem;
white-space: nowrap;
}
// --- Lecture -----------------------------------------------------------------
.proposal-progress {
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.proposal-phase {
margin: 0;
color: #c4b5fd;
font-size: 0.88rem;
font-weight: 500;
}
.proposal-bar {
height: 6px;
background: #1f2937;
border-radius: 999px;
overflow: hidden;
}
.proposal-bar-fill {
height: 100%;
background: #a78bfa;
border-radius: 999px;
transition: width 0.3s ease;
}
// --- Sorts trouvés -------------------------------------------------------------
.proposal-found {
gap: 0.15rem;
max-height: 22rem;
overflow-y: auto;
}
.proposal-item {
display: flex;
align-items: flex-start;
gap: 0.55rem;
padding: 0.35rem 0.4rem;
border-radius: 8px;
cursor: pointer;
&:hover { background: rgba(255, 255, 255, 0.03); }
&.present { cursor: default; opacity: 0.6; }
input { margin-top: 0.2rem; accent-color: #a78bfa; flex-shrink: 0; }
}
.proposal-main {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.25rem 0.5rem;
min-width: 0;
}
.proposal-level {
padding: 0.05rem 0.45rem;
border-radius: 999px;
background: rgba(108, 99, 255, 0.2);
border: 1px solid rgba(108, 99, 255, 0.5);
color: #ddd6fe;
font-size: 0.72rem;
font-weight: 700;
}
.proposal-name {
color: white;
font-size: 0.92rem;
font-weight: 600;
}
.proposal-school {
padding: 0.05rem 0.45rem;
border-radius: 999px;
background: #1f2937;
color: #9ca3af;
font-size: 0.72rem;
}
.proposal-source,
.proposal-present {
color: #6b7280;
font-size: 0.75rem;
}
.proposal-present { font-style: italic; }
.proposal-excerpt {
flex-basis: 100%;
color: #9ca3af;
font-size: 0.82rem;
line-height: 1.4;
}
// --- Actions -------------------------------------------------------------------
.proposal-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.6rem;
}
.btn-primary {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.95rem;
background: #a78bfa;
color: #0b1220;
border: none;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
&:disabled { opacity: 0.5; cursor: not-allowed; }
&:hover:not(:disabled) { background: #c4b5fd; }
}
.btn-secondary {
padding: 0.5rem 0.95rem;
background: transparent;
border: 1px solid #1f2937;
border-radius: 8px;
color: #9ca3af;
font-size: 0.85rem;
cursor: pointer;
&:hover { border-color: #374151; color: #e5e7eb; }
}
@@ -0,0 +1,200 @@
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, inject } from '@angular/core';
import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, Sparkles } from 'lucide-angular';
import { Subscription } from 'rxjs';
import { GameSystemService } from '../../services/game-system.service';
import { ProposedSpell } from '../../services/spell.model';
import { TemplateField } from '../../services/template.model';
import { summary } from '../spell-catalog.util';
import {
ReadingChunk, RuleText, chunksFor, isInCatalogue, suggestedSections
} from '../spell-proposal.util';
/** Un sort relevé, et la section où il a été trouvé. */
interface FoundSpell {
spell: ProposedSpell;
source: string;
}
/**
* `choose` : choix des sections ; `reading` : lecture en cours ; `paused` : arrêtée par une
* erreur (on peut reprendre) ; `done` : terminée ou arrêtée par l'utilisateur.
*/
type Stage = 'choose' | 'reading' | 'paused' | 'done';
/**
* Proposition de sorts à partir des règles : le MJ coche les sections qui décrivent des
* sorts, l'IA les lit morceau par morceau (un appel par morceau, pour montrer l'avancement
* et pouvoir s'arrêter), puis il coche les sorts à ajouter au catalogue.
*
* Rien n'est enregistré ici, et aucun sort du catalogue n'est modifié : le composant ne fait
* que remettre au parent les sorts cochés.
*/
@Component({
selector: 'app-spell-proposal',
imports: [TranslatePipe, LucideAngularModule],
templateUrl: './spell-proposal.component.html',
styleUrls: ['./spell-proposal.component.scss']
})
export class SpellProposalComponent implements OnInit, OnDestroy {
readonly Sparkles = Sparkles;
private readonly service = inject(GameSystemService);
/** Règles affichées dans l'éditeur (enregistrées ou non). */
@Input() rules: RuleText[] = [];
@Input() systemName = '';
/** Champs du modèle de sort, que l'IA remplit quand le texte donne leur valeur. */
@Input() fields: TemplateField[] = [];
/** Sorts déjà dans le catalogue : jamais proposés une seconde fois. */
@Input() catalogue: { name: string }[] = [];
/** Sorts cochés que le parent ajoute au catalogue. */
@Output() add = new EventEmitter<ProposedSpell[]>();
@Output() closed = new EventEmitter<void>();
stage: Stage = 'choose';
selectedSections = new Set<string>();
chunks: ReadingChunk[] = [];
/** Rang (à partir de 0) du morceau en cours de lecture, ou du prochain à lire. */
index = 0;
found: FoundSpell[] = [];
/** Noms (en minuscules) des sorts cochés. */
selected = new Set<string>();
dropped = 0;
error = '';
/** Nombre de sorts ajoutés au dernier clic (message de confirmation). */
added: number | null = null;
private sub: Subscription | null = null;
ngOnInit(): void {
this.selectedSections = new Set(suggestedSections(this.rules));
}
ngOnDestroy(): void {
this.sub?.unsubscribe();
}
// ─────────────── Choix des sections ───────────────
isSectionSelected(title: string): boolean {
return this.selectedSections.has(title);
}
toggleSection(title: string): void {
if (!this.selectedSections.delete(title)) this.selectedSections.add(title);
}
/** Nombre de morceaux que représentent les sections cochées (un appel à l'IA chacun). */
get plannedChunks(): number {
return chunksFor(this.rules, this.selectedSections).length;
}
// ─────────────── Lecture ───────────────
start(): void {
this.chunks = chunksFor(this.rules, this.selectedSections);
if (!this.chunks.length) return;
this.index = 0;
this.found = [];
this.selected = new Set<string>();
this.dropped = 0;
this.added = null;
this.readNext();
}
get currentChunk(): ReadingChunk | null {
return this.chunks[this.index] ?? null;
}
private readNext(): void {
const chunk = this.currentChunk;
if (!chunk) {
this.stage = 'done';
return;
}
this.stage = 'reading';
this.error = '';
this.sub?.unsubscribe();
this.sub = this.service.proposeSpells({
systemName: this.systemName.trim(),
sectionTitle: chunk.title,
text: chunk.text,
fields: this.fields,
avoid: [...this.catalogue.map(s => s.name), ...this.found.map(f => f.spell.name)].filter(n => n?.trim())
}).subscribe({
next: response => {
for (const spell of response.spells ?? []) {
if (this.found.some(f => this.key(f.spell.name) === this.key(spell.name))) continue;
this.found.push({ spell, source: chunk.title });
if (!this.isInCatalogue(spell.name)) this.selected.add(this.key(spell.name));
}
this.dropped += response.dropped ?? 0;
this.index++;
this.readNext();
},
error: err => {
const reason: unknown = err?.error?.error ?? err?.error?.message;
this.error = typeof reason === 'string' ? reason : '';
this.stage = 'paused';
}
});
}
/** Arrête la lecture : les sorts déjà trouvés restent proposés. */
stop(): void {
this.sub?.unsubscribe();
this.stage = 'done';
}
/** Reprend au morceau qui a échoué. */
resume(): void {
this.readNext();
}
/** La lecture est-elle allée au bout des morceaux ? */
get complete(): boolean {
return this.index >= this.chunks.length;
}
// ─────────────── Sorts trouvés ───────────────
private key(name: string): string {
return name.trim().toLowerCase();
}
isInCatalogue(name: string): boolean {
return isInCatalogue(this.catalogue, name);
}
isSelected(name: string): boolean {
return !this.isInCatalogue(name) && this.selected.has(this.key(name));
}
toggle(name: string): void {
const key = this.key(name);
if (!this.selected.delete(key)) this.selected.add(key);
}
get selectedSpells(): ProposedSpell[] {
return this.found.map(f => f.spell).filter(s => this.isSelected(s.name));
}
summaryOf(spell: ProposedSpell): string {
return summary({ name: spell.name, description: spell.description, values: {} });
}
addSelected(): void {
const chosen = this.selectedSpells;
if (!chosen.length) return;
this.add.emit(chosen);
this.selected = new Set<string>();
this.added = chosen.length;
}
close(): void {
this.sub?.unsubscribe();
this.closed.emit();
}
}
@@ -0,0 +1,64 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { CampaignService } from './campaign.service';
import { GameSystemService } from './game-system.service';
import { Spell } from './spell.model';
import { TemplateField } from './template.model';
/** Fiche qui peut connaître des sorts. */
export type SpellSheet = 'character' | 'npc' | 'enemy';
/** Catalogue de sorts du système d'une campagne (vide si la campagne n'a pas de système). */
export interface CampaignSpells {
gameSystemId: string | null;
/** Champs propres au système portés par chaque sort. */
template: TemplateField[];
spells: Spell[];
}
const NO_SPELLS: CampaignSpells = { gameSystemId: null, template: [], spells: [] };
/**
* Les sorts vus depuis une campagne : le catalogue du système de la campagne (pour le mode
* séance et les fiches), et les sorts connus d'une fiche (PJ, PNJ ou ennemi).
*/
@Injectable({ providedIn: 'root' })
export class CampaignSpellsService {
constructor(
private http: HttpClient,
private campaignService: CampaignService,
private gameSystemService: GameSystemService
) {}
/**
* Catalogue du système de la campagne. Une campagne sans système, ou un catalogue
* illisible, donne un catalogue vide : les écrans qui l'utilisent n'affichent alors rien.
*/
catalogue(campaignId: string): Observable<CampaignSpells> {
return this.campaignService.getCampaignById(campaignId).pipe(
switchMap(campaign => {
const gameSystemId = campaign.gameSystemId ?? null;
if (!gameSystemId) return of(NO_SPELLS);
return this.gameSystemService.getSpells(gameSystemId).pipe(
map(catalog => ({ gameSystemId, template: catalog.template ?? [], spells: catalog.spells ?? [] })),
catchError(() => of({ ...NO_SPELLS, gameSystemId })));
}),
catchError(() => of(NO_SPELLS))
);
}
/** Identifiants des sorts connus d'une fiche, dans l'ordre choisi. */
known(sheet: SpellSheet, ownerId: string): Observable<string[]> {
return this.http.get<{ spellIds: string[] }>(`/api/sheet-spells/${sheet}/${ownerId}`)
.pipe(map(response => response.spellIds ?? []));
}
/** Remplace les sorts connus d'une fiche. */
saveKnown(sheet: SpellSheet, ownerId: string, spellIds: string[]): Observable<string[]> {
return this.http.put<{ spellIds: string[] }>(`/api/sheet-spells/${sheet}/${ownerId}`, { spellIds })
.pipe(map(response => response.spellIds ?? []));
}
}

Some files were not shown because too many files have changed in this diff Show More