Imports PDF fidèles au livre : règles, sorts et campagnes découpés par la structure du PDF

Le texte importé est celui du livre : l'appli découpe le PDF d'après sa table des
matières (ou ses titres), sans IA, et l'IA ne fait plus que repérer, résumer à part
et traduire. Mesuré en local avec Ollama et un petit modèle (contexte 8192).

Lecture du PDF
- Découpage par les signets du PDF, sinon par les titres repérés à la taille des
  caractères ; à défaut de structure, repli sur l'IA.
- Tableaux rendus en markdown, colonnes relues dans l'ordre quand elles sont nettes,
  mots coupés en fin de ligne recollés.
- En-têtes, numéros de page, titres courants, onglets de marge et titres dessinés deux
  fois retirés du texte.

Import de règles
- Sections tirées de la structure du livre pour tous les fournisseurs ; sans structure,
  l'IA ne fait que placer des repères : le texte n'est ni réécrit ni perdu.
- Traduction en parallèle (une section à la fois en local), règles livrées dans leur
  langue si la traduction échoue, sections non traduites signalées.
- Glossaire des termes de jeu donné au modèle pour traduire les blocs de statistiques.
- Durée maximale d'un import (4 h) et message clair quand la connexion est coupée.
- Sections lues mises en forme, édition à la demande.

Sorts
- Proposition : le modèle désigne le sort, sa description est recopiée du livre.
- Niveaux et écoles harmonisés d'un clic.

Import de campagne
- Arcs, aventures, scènes et pièces tirés de la table des matières ; le texte de chaque
  scène est celui du livre, dans ses notes du MJ.
- L'IA n'ajoute que le synopsis des scènes et les fiches des PNJ, puis traduit le texte
  en entier si le livre n'est pas dans la langue de l'interface.
- Annexes (bestiaire, objets) dans un arc à part, en quelques scènes de lecture.
- PNJ : des individus seulement — groupes, créatures génériques, profils de créature et
  personnes citées en préface écartés ; un rôle unique sans nom est gardé.
- La campagne découpée est proposée même si l'IA échoue ; une note le dit à la révision.
- Fiche de scène : notes du MJ et pièces mises en forme (sous-titres, tableaux).

Ollama
- Réflexion coupée pour les modèles à raisonnement, qui renvoyaient des réponses vides.
This commit is contained in:
2026-11-14 10:45:55 +01:00
parent 6c1d74f9a5
commit 3c76762efc
71 changed files with 5974 additions and 368 deletions
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import { importOutcomeNotes } from './campaign-import-notes.util';
import { CampaignImportOutcome } from '../../../services/campaign-import.model';
const outcome = (over: Partial<CampaignImportOutcome> = {}): CampaignImportOutcome => ({
splitMethod: 'bookmarks', sourceLanguage: 'fr', untranslated: 0, skippedAids: 0, aiInterrupted: false, ...over,
});
describe('importOutcomeNotes', () => {
it("ne dit rien quand l'IA a fait le découpage (pas de compte rendu)", () => {
expect(importOutcomeNotes(null)).toEqual([]);
expect(importOutcomeNotes(undefined)).toEqual([]);
});
it("dit d'où vient le découpage", () => {
expect(importOutcomeNotes(outcome())).toEqual([{ key: 'campaignImport.noteSplitBookmarks' }]);
expect(importOutcomeNotes(outcome({ splitMethod: 'headings' })))
.toEqual([{ key: 'campaignImport.noteSplitHeadings' }]);
expect(importOutcomeNotes(outcome({ splitMethod: 'autre' }))).toEqual([]);
});
it('signale les aides manquantes et la traduction incomplète', () => {
expect(importOutcomeNotes(outcome({ skippedAids: 2, untranslated: 5 })).slice(1)).toEqual([
{ key: 'campaignImport.noteSkippedAids', params: { n: 2 } },
{ key: 'campaignImport.noteUntranslated', params: { n: 5 } },
]);
});
it('une IA interrompue se dit en une seule note', () => {
expect(importOutcomeNotes(outcome({ aiInterrupted: true, splitMethod: null, untranslated: 3 })))
.toEqual([{ key: 'campaignImport.noteAiInterrupted' }]);
});
});
@@ -0,0 +1,36 @@
import { CampaignImportOutcome } from '../../../services/campaign-import.model';
/** Une note à afficher au-dessus de l'arbre : clé de traduction et ses paramètres. */
export interface ImportNote {
key: string;
params?: Record<string, number>;
}
const SPLIT_NOTES: Record<string, string> = {
bookmarks: 'campaignImport.noteSplitBookmarks',
headings: 'campaignImport.noteSplitHeadings',
};
/**
* Ce qu'il faut dire à l'utilisateur sur l'import qu'il s'apprête à réviser : d'où vient le
* découpage (et que le texte est celui du livre), puis ce que l'IA n'a pas pu faire.
* Aucune note quand l'IA a reconstruit elle-même l'arborescence (pas de compte rendu).
*/
export function importOutcomeNotes(outcome: CampaignImportOutcome | null | undefined): ImportNote[] {
if (!outcome) return [];
const notes: ImportNote[] = [];
const split = SPLIT_NOTES[outcome.splitMethod ?? ''];
if (split) notes.push({ key: split });
if (outcome.aiInterrupted) {
// Rien d'autre à détailler : ni aides ni traduction n'ont été gardées.
notes.push({ key: 'campaignImport.noteAiInterrupted' });
return notes;
}
if (outcome.skippedAids > 0) {
notes.push({ key: 'campaignImport.noteSkippedAids', params: { n: outcome.skippedAids } });
}
if (outcome.untranslated > 0) {
notes.push({ key: 'campaignImport.noteUntranslated', params: { n: outcome.untranslated } });
}
return notes;
}
@@ -51,6 +51,9 @@
<p class="review-summary">
<span [innerHTML]="'campaignImport.summaryToCreate' | translate:{ arcs: arcCount, chapters: chapterCount, scenes: sceneCount }"></span>@if (npcs.length > 0) {<span [innerHTML]="'campaignImport.summaryNpcs' | translate:{ npcs: npcCount }"></span>}<span [innerHTML]="'campaignImport.summaryHint' | translate"></span>
</p>
@for (note of importNotes; track note) {
<p class="import-note">{{ note }}</p>
}
</div>
<div class="tree">
<!-- Arc -->
@@ -162,8 +165,9 @@
<div class="room-row">
<input type="text" class="room-name" [(ngModel)]="room.name"
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.roomPlaceholder' | translate" />
<input type="text" class="room-field" [(ngModel)]="room.description"
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'common.description' | translate" />
<!-- Zone de texte : la description d'une salle est le texte du livre (plusieurs paragraphes). -->
<textarea class="room-field room-desc" [(ngModel)]="room.description" rows="1"
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'common.description' | translate"></textarea>
<input type="text" class="room-field" [(ngModel)]="room.enemies"
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.enemiesPlaceholder' | translate" />
<input type="text" class="room-field" [(ngModel)]="room.loot"
@@ -114,6 +114,17 @@
// --- Revue (arbre) ----------------------------------------------------------
.review-summary { margin: 0 0 1rem; color: #d1d5db; font-size: 0.9rem; strong { color: #fff; } em { color: #9ca3af; font-style: italic; } }
.import-note {
margin: -0.4rem 0 1rem;
padding: 0.55rem 0.8rem;
background: rgba(108, 99, 255, 0.12);
border: 1px solid rgba(108, 99, 255, 0.35);
border-radius: 8px;
color: #c4b5fd;
font-size: 0.85rem;
line-height: 1.4;
}
// Nœuds déjà présents dans la campagne : grisés, lecture seule.
.existing-node {
opacity: 0.6;
@@ -283,7 +294,7 @@
.room-row {
display: flex;
align-items: center;
align-items: flex-start;
gap: 0.35rem;
}
@@ -300,6 +311,13 @@
.room-name { flex: 0 0 22%; }
.room-field { flex: 1; min-width: 0; }
.room-desc {
flex: 2;
font-family: inherit;
line-height: 1.35;
min-height: 1.75rem;
resize: vertical;
}
.scene-fields {
flex: 1;
@@ -16,6 +16,7 @@ import { CampaignSidebarService } from '../../../services/campaign-sidebar.servi
import { PageTitleService } from '../../../services/page-title.service';
import { ArcKind, ArcProposal, ChapterProposal, NpcProposal, SceneProposal } from '../../../services/campaign-import.model';
import { CampaignImportProposal } from '../../../services/campaign-import.model';
import { importOutcomeNotes } from './campaign-import-notes.util';
import { loadCampaignTreeData, CampaignTreeData } from '../../campaign-tree.helper';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
@@ -97,6 +98,8 @@ export class CampaignImportComponent implements OnInit {
importStatus: string | null = null;
importCounts: { arcs: number; chapters: number; scenes: number; npcs: number } | null = null;
importError: string | null = null;
/** Ce qu'il faut savoir sur l'import, affiché au-dessus de l'arbre (découpage, traduction…). */
importNotes: string[] = [];
/** Vrai une fois la proposition reçue (on affiche l'arbre éditable). */
reviewing = false;
@@ -161,6 +164,7 @@ export class CampaignImportComponent implements OnInit {
this.importProgress = null;
this.importStatus = null;
this.importCounts = null;
this.importNotes = [];
this.tree = [];
this.service.importStructureStream(this.campaignId, file).subscribe({
@@ -192,6 +196,7 @@ export class CampaignImportComponent implements OnInit {
} else {
this.tree = this.buildMergedTree(ev.arcs ?? []);
this.npcs = this.buildNpcNodes(ev.npcs ?? []);
this.importNotes = importOutcomeNotes(ev.outcome).map(note => this.translate.instant(note.key, note.params));
this.reviewing = true;
}
}
@@ -120,7 +120,8 @@
<span class="view-section-icon">🔒</span>
{{ 'sceneView.gmNotesSectionTitle' | translate }}
</h2>
<p class="view-section-body">{{ scene.gmSecretNotes }}</p>
<!-- Markdown : une scène importée porte le texte du livre, avec ses sous-titres et ses tableaux. -->
<div class="view-md" [innerHTML]="scene.gmSecretNotes | markdown"></div>
</section>
}
<!-- Pages Lore liées -->
@@ -154,7 +155,7 @@
}
</header>
@if (r.description?.trim()) {
<p class="room-readonly-desc">{{ r.description }}</p>
<div class="room-readonly-desc view-md" [innerHTML]="r.description | markdown"></div>
}
<div class="room-readonly-grid">
@if (r.enemies?.trim() || roomLinkedEnemies(r).length > 0) {
@@ -45,7 +45,55 @@
font-size: 0.9rem;
line-height: 1.5;
color: var(--color-text, #333);
white-space: pre-wrap;
}
// Texte rendu en markdown (notes du MJ, description d'une pièce) : paragraphes, sous-titres
// et tableaux du livre importé. Un texte saisi à la main garde ses sauts de ligne.
.view-md {
color: #e0e0e0;
font-size: 0.95rem;
line-height: 1.6;
overflow-wrap: anywhere;
min-width: 0;
&.room-readonly-desc { font-size: 0.9rem; line-height: 1.5; color: var(--color-text, #333); }
::ng-deep {
> :first-child { margin-top: 0; }
> :last-child { margin-bottom: 0; }
p { margin: 0 0 0.7em; }
h1, h2, h3, h4, h5, h6 {
margin: 1.1em 0 0.4em;
color: #f3f4f6;
font-weight: 600;
line-height: 1.25;
}
h1, h2, h3 { font-size: 1.02rem; padding-bottom: 0.25em; border-bottom: 1px solid #1f2937; }
h4 { font-size: 0.95rem; color: #c4b5fd; }
h5, h6 { font-size: 0.9rem; color: #9ca3af; }
ul, ol { margin: 0.3em 0 0.7em; padding-left: 1.4em; }
li { margin: 0.2em 0; }
// Les tableaux défilent dans leur boîte : jamais de défilement horizontal de la page.
table {
display: block;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
margin: 0.5em 0 0.8em;
font-size: 0.86rem;
}
th, td {
border: 1px solid #1f2937;
padding: 0.35em 0.65em;
text-align: left;
vertical-align: top;
}
th { background: #0f172a; color: #f3f4f6; font-weight: 600; }
}
}
.room-readonly-grid {
@@ -21,6 +21,7 @@ import { Enemy } from '../../../services/enemy.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 { MarkdownPipe } from '../../../shared/markdown.pipe';
/**
* Écran de consultation d'une Scène (lecture seule).
@@ -28,7 +29,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
*/
@Component({
selector: 'app-scene-view',
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedRoleHintComponent],
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedRoleHintComponent, MarkdownPipe],
templateUrl: './scene-view.component.html',
styleUrls: ['./scene-view.component.scss']
})
@@ -137,7 +137,7 @@
<div class="section-list">
@for (section of visibleSections; track section; let i = $index) {
<div class="section-card" [class.collapsed]="section.collapsed">
<div class="section-card" #card [class.collapsed]="section.collapsed" [class.editing]="section.editing">
<div class="section-head">
<button type="button" class="btn-collapse" (click)="toggleCollapse(section)"
[attr.aria-expanded]="!section.collapsed">
@@ -153,18 +153,36 @@
@if (section.collapsed && section.content.trim()) {
<span class="section-size">{{ 'gameSystemEdit.sectionSize' | translate:{ count: section.content.trim().length } }}</span>
}
@if (!section.collapsed) {
<button type="button" class="btn-edit" [class.active]="section.editing"
[attr.aria-pressed]="section.editing" (click)="toggleEdit(section, card)">
<lucide-icon [img]="section.editing ? Check : Pencil" [size]="13"></lucide-icon>
{{ (section.editing ? 'gameSystemEdit.sectionDone' : 'gameSystemEdit.sectionEdit') | translate }}
</button>
}
<button type="button" class="btn-remove" (click)="removeSection(section)" [title]="'gameSystemEdit.removeSection' | translate">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
</button>
</div>
<!-- Lecture par défaut : le markdown est mis en forme. Le texte brut ne s'ouvre
que sur « Modifier » (ou d'office pour une section encore vide). -->
@if (!section.collapsed) {
<textarea
class="section-content"
[(ngModel)]="section.content"
[name]="'content-' + i"
rows="6"
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
></textarea>
@if (section.editing) {
<textarea
class="section-content"
[(ngModel)]="section.content"
[name]="'content-' + i"
rows="14"
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
></textarea>
<p class="section-edit-hint">{{ 'gameSystemEdit.sectionEditHint' | translate }}</p>
} @else if (section.content.trim()) {
<div class="section-read" [innerHTML]="section.content | markdown"></div>
} @else {
<button type="button" class="section-empty" (click)="toggleEdit(section, card)">
{{ 'gameSystemEdit.sectionEmpty' | translate }}
</button>
}
}
</div>
}
@@ -258,21 +258,143 @@
}
.section-content {
display: block;
width: 100%;
background: transparent;
background: #080d18;
border: none;
border-top: 1px solid #1f2937;
color: #d1d5db;
padding: 0.75rem 1rem;
font-size: 0.9rem;
font-family: inherit;
line-height: 1.5;
font-size: 0.88rem;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
line-height: 1.55;
resize: vertical;
box-sizing: border-box;
&:focus { outline: none; }
}
// Bascule lecture / saisie d'une section.
.btn-edit {
display: inline-flex;
align-items: center;
gap: 0.3rem;
flex-shrink: 0;
background: transparent;
border: 1px solid #1f2937;
border-radius: 6px;
color: #9ca3af;
font-size: 0.78rem;
padding: 0.2rem 0.55rem;
cursor: pointer;
&:hover { color: #e5e7eb; border-color: #374151; }
&.active { color: #c4b5fd; border-color: rgba(167, 139, 250, 0.45); background: rgba(167, 139, 250, 0.08); }
}
.section-edit-hint {
margin: 0;
padding: 0.35rem 1rem 0.5rem;
background: #080d18;
color: #6b7280;
font-size: 0.75rem;
}
.section-empty {
display: block;
width: 100%;
background: transparent;
border: none;
border-top: 1px solid #1f2937;
color: #6b7280;
font-size: 0.85rem;
font-style: italic;
text-align: left;
padding: 0.75rem 1rem;
cursor: pointer;
&:hover { color: #d1d5db; }
}
// Section en lecture : markdown mis en forme (HTML injecté → ::ng-deep, limité à ce bloc).
.section-read {
border-top: 1px solid #1f2937;
padding: 0.85rem 1.1rem 1rem;
color: #d1d5db;
font-size: 0.92rem;
line-height: 1.6;
overflow-wrap: anywhere;
min-width: 0;
::ng-deep {
> :first-child { margin-top: 0; }
> :last-child { margin-bottom: 0; }
p { margin: 0 0 0.7em; }
h1, h2, h3, h4, h5, h6 {
margin: 1.15em 0 0.45em;
color: #f3f4f6;
font-weight: 600;
line-height: 1.25;
}
h1, h2, h3 { font-size: 1.02rem; padding-bottom: 0.25em; border-bottom: 1px solid #1f2937; }
h4 { font-size: 0.95rem; color: #c4b5fd; }
h5, h6 { font-size: 0.9rem; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.04em; }
strong { color: #f3f4f6; }
a { color: #a78bfa; }
ul, ol { margin: 0.3em 0 0.7em; padding-left: 1.4em; }
li { margin: 0.2em 0; }
li::marker { color: #6b7280; }
hr { border: 0; border-top: 1px solid #1f2937; margin: 1em 0; }
blockquote {
margin: 0.6em 0;
padding: 0.35em 0.9em;
border-left: 3px solid rgba(167, 139, 250, 0.5);
background: rgba(167, 139, 250, 0.05);
border-radius: 0 6px 6px 0;
color: #cbd5e1;
}
code {
background: #080d18;
border: 1px solid #1f2937;
border-radius: 3px;
padding: 0 0.3em;
font-size: 0.85em;
}
pre {
background: #080d18;
border: 1px solid #1f2937;
border-radius: 6px;
padding: 0.6em 0.8em;
overflow-x: auto;
code { background: none; border: 0; padding: 0; }
}
// Les tableaux défilent dans leur boîte : jamais de défilement horizontal de la page.
table {
display: block;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
margin: 0.5em 0 0.8em;
font-size: 0.86rem;
}
th, td {
border: 1px solid #1f2937;
padding: 0.35em 0.65em;
text-align: left;
vertical-align: top;
}
th { background: #0f172a; color: #f3f4f6; font-weight: 600; }
tr:nth-child(even) td { background: rgba(255, 255, 255, 0.02); }
}
}
.empty-hint {
color: #6b7280;
font-size: 0.85rem;
@@ -8,11 +8,14 @@ import {
LucideAngularModule, LucideIconData, Save, ArrowLeft, Dices, Plus, Trash2, ChevronDown, ChevronRight, Upload,
Sparkles, Info, BookOpen, LayoutTemplate, Search, WandSparkles
} from 'lucide-angular';
import { Check, Pencil } from 'lucide-angular';
import { MarkdownPipe } from '../../shared/markdown.pipe';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { GameSystemService } from '../../services/game-system.service';
import { SheetFieldProposal, SheetKind } from '../../services/game-system.model';
import { FieldType, TemplateField } from '../../services/template.model';
import { addProposedFields, isAlreadyInSheet, rulesForProposal } from '../sheet-proposal.util';
import { importTranslation } from '../rules-import.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';
@@ -36,6 +39,11 @@ interface RuleSection {
title: string;
content: string;
collapsed: boolean;
/**
* Vrai : le texte brut (markdown) est ouvert dans une zone de saisie. Faux : la section se
* lit mise en forme. Une section qui a du texte s'ouvre en lecture, une section vide en saisie.
*/
editing: boolean;
}
/**
@@ -66,6 +74,11 @@ 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;
/** Note d'import selon la façon dont le livre a été découpé (rien à dire quand c'est l'IA). */
const SPLIT_NOTES: Record<string, string> = {
bookmarks: 'gameSystemEdit.importSplitBookmarks',
headings: 'gameSystemEdit.importSplitHeadings'
};
/**
* Proposition de champs pour une fiche, tirée des règles par l'IA. `fields` vaut null
@@ -86,7 +99,7 @@ const emptyProposal = (): SheetProposalState =>
@Component({
selector: 'app-game-system-edit',
imports: [FormsModule, NgTemplateOutlet, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent,
imports: [FormsModule, NgTemplateOutlet, LucideAngularModule, TranslatePipe, MarkdownPipe, TemplateFieldsEditorComponent,
SpellCatalogEditorComponent],
templateUrl: './game-system-edit.component.html',
styleUrls: ['./game-system-edit.component.scss']
@@ -97,6 +110,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
readonly Dices = Dices;
readonly Plus = Plus;
readonly Trash2 = Trash2;
readonly Pencil = Pencil;
readonly Check = Check;
readonly ChevronDown = ChevronDown;
readonly ChevronRight = ChevronRight;
readonly Upload = Upload;
@@ -298,13 +313,13 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
addSuggested(title: string): void {
if (this.isSectionUsed(title)) return;
this.sectionFilter = '';
this.sections.push({ title, content: '', collapsed: false });
this.sections.push({ title, content: '', collapsed: false, editing: true });
}
/** Ajoute une section vierge (titre à remplir). */
addBlank(): void {
this.sectionFilter = '';
this.sections.push({ title: '', content: '', collapsed: false });
this.sections.push({ title: '', content: '', collapsed: false, editing: true });
}
// --- Import d'un PDF de règles -------------------------------------------
@@ -349,7 +364,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
} else if (ev.type === 'status') {
this.importStatus = ev.message;
} else if (ev.type === 'done') {
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage);
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage,
ev.untranslatedTitles ?? [], ev.splitMethod);
}
},
error: (err: Error) => {
@@ -362,7 +378,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
}
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number,
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null): void {
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null,
untranslated: string[] = [], splitMethod?: string | null): void {
this.resetImportProgress();
// Règles en deux langues (Brain récent) : chaque version va dans son onglet ; sinon,
// les sections vont dans l'onglet affiché (comportement historique).
@@ -388,16 +405,35 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
pages: pageCount,
ocr
});
const translatedLangs = this.rulesLangs.filter(l => l !== sourceLanguage && (byLanguage?.[l] && Object.keys(byLanguage[l]).length));
if (bilingual && sourceLanguage && translatedLangs.length) {
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importTranslated', {
source: this.translate.instant('gameSystemEdit.lang.' + sourceLanguage),
target: translatedLangs.map(l => this.translate.instant('gameSystemEdit.lang.' + l)).join(', ')
});
}
// Livre découpé par sa propre structure, sans IA : on le dit, les titres sont ceux du livre.
const splitKey = SPLIT_NOTES[splitMethod ?? ''];
if (splitKey) this.importNote += ' ' + this.translate.instant(splitKey);
const translationNote = this.importTranslationNote(byLanguage, sourceLanguage, untranslated);
if (translationNote) this.importNote += ' ' + translationNote;
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importSheetHint');
}
/**
* Ce que l'import dit de la traduction : faite, faite en partie (des sections gardent leur
* texte d'origine) ou non aboutie (seul l'onglet de la langue du livre est rempli).
*/
private importTranslationNote(byLanguage: Record<string, Record<string, string>> | undefined,
sourceLanguage: string | null | undefined, untranslated: string[]): string {
const outcome = importTranslation(byLanguage, sourceLanguage, untranslated, this.rulesLangs);
if (outcome.kind === 'none') return '';
const langName = (l: string) => this.translate.instant('gameSystemEdit.lang.' + l);
const source = langName(outcome.source);
const target = outcome.targets.map(langName).join(', ');
if (outcome.kind === 'failed') {
return this.translate.instant('gameSystemEdit.importNotTranslated', { source, target });
}
const translated = this.translate.instant('gameSystemEdit.importTranslated', { source, target });
if (outcome.kind === 'translated') return translated;
return translated + ' ' + this.translate.instant('gameSystemEdit.importPartlyTranslated', {
count: outcome.count, total: outcome.total, target, titles: outcome.titles
});
}
/** Nombre de sections non vides d'une langue (badge de l'onglet). */
sectionCount(lang: RulesLang): number {
return this.sectionsByLang[lang].filter(s => s.title.trim() || s.content.trim()).length;
@@ -563,7 +599,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
existing.collapsed = false;
} else {
target.push({ title, content, collapsed: false });
target.push({ title, content, collapsed: false, editing: false });
}
count++;
}
@@ -620,6 +656,18 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
section.collapsed = !section.collapsed;
}
/**
* Passe une section de la lecture à la saisie, ou l'inverse. En ouvrant la saisie, le
* curseur va dans la zone de texte de la carte.
*/
toggleEdit(section: RuleSection, card?: HTMLElement): void {
section.editing = !section.editing;
section.collapsed = false;
if (section.editing && card) {
setTimeout(() => card.querySelector<HTMLTextAreaElement>('textarea.section-content')?.focus());
}
}
submit(): void {
if (!this.name.trim() || this.saving) return;
this.saveError = null;
@@ -714,6 +762,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
const flush = () => {
if (current) {
current.content = buffer.join('\n').trim();
current.editing = !current.content;
sections.push(current);
}
buffer.length = 0;
@@ -726,7 +775,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
const match = line.match(/^##\s+(\S.*)$/);
if (match) {
flush();
current = { title: match[1].trim(), content: '', collapsed: false };
current = { title: match[1].trim(), content: '', collapsed: false, editing: false };
} else if (current) {
buffer.push(line);
}
@@ -0,0 +1,38 @@
import { describe, it, expect } from 'vitest';
import { importTranslation, MAX_UNTRANSLATED_SHOWN } from './rules-import.util';
const LANGS = ['fr', 'en'] as const;
const EN = { Combat: 'd20 roll', Magic: 'spells' };
describe('importTranslation', () => {
it("ne dit rien d'un import dans une seule langue (langue du livre inconnue)", () => {
expect(importTranslation(undefined, null, [], LANGS)).toEqual({ kind: 'none' });
expect(importTranslation({ en: EN }, null, [], LANGS)).toEqual({ kind: 'none' });
expect(importTranslation({ de: EN }, 'de', [], LANGS)).toEqual({ kind: 'none' });
});
it('annonce une traduction complète', () => {
const fr = { Combat: 'jet de d20', Magie: 'sorts' };
expect(importTranslation({ en: EN, fr }, 'en', [], LANGS))
.toEqual({ kind: 'translated', source: 'en', targets: ['fr'] });
});
it("signale une traduction qui n'a pas abouti : seul l'onglet du livre est rempli", () => {
expect(importTranslation({ en: EN }, 'en', [], LANGS))
.toEqual({ kind: 'failed', source: 'en', targets: ['fr'] });
expect(importTranslation({ en: EN, fr: {} }, 'en', [], LANGS).kind).toBe('failed');
});
it('compte et cite les sections restées dans la langue du livre', () => {
const fr = { Combat: 'jet de d20', Magic: 'spells' };
expect(importTranslation({ en: EN, fr }, 'en', ['Magic'], LANGS))
.toEqual({ kind: 'partial', source: 'en', targets: ['fr'], count: 1, total: 2, titles: 'Magic' });
});
it('abrège une longue liste de sections non traduites', () => {
const titles = Array.from({ length: MAX_UNTRANSLATED_SHOWN + 3 }, (_, i) => `S${i}`);
const all = Object.fromEntries(titles.map(t => [t, 'text']));
const outcome = importTranslation({ en: all, fr: all }, 'en', titles, LANGS);
expect(outcome).toMatchObject({ kind: 'partial', count: 8, total: 8, titles: 'S0, S1, S2, S3, S4…' });
});
});
@@ -0,0 +1,48 @@
/**
* Import d'un PDF de règles : ce qu'il faut dire de la traduction une fois l'import terminé.
*
* Le livre est extrait dans sa langue, puis traduit vers l'autre langue de l'application. La
* traduction peut aboutir, n'aboutir qu'en partie (des sections gardent leur texte d'origine)
* ou ne pas aboutir du tout (seul l'onglet de la langue du livre est rempli).
*/
/** Titres de sections non traduites cités dans la note (le reste est résumé par « … »). */
export const MAX_UNTRANSLATED_SHOWN = 5;
export type ImportTranslation =
/** Import dans une seule langue (langue du livre inconnue) : rien à dire. */
| { kind: 'none' }
/** Toutes les sections sont traduites vers `targets`. */
| { kind: 'translated'; source: string; targets: string[] }
/** `count` sections sur `total` gardent leur texte d'origine dans `targets`. */
| { kind: 'partial'; source: string; targets: string[]; count: number; total: number; titles: string }
/** Aucune traduction : seul l'onglet `source` est rempli ; `targets` restent vides. */
| { kind: 'failed'; source: string; targets: string[] };
/**
* @param byLanguage sections reçues, par langue
* @param sourceLanguage langue du livre
* @param untranslated titres des sections que la traduction n'a pas pu traiter
* @param languages langues de l'application, dans l'ordre des onglets
*/
export function importTranslation(
byLanguage: Record<string, Record<string, string>> | undefined,
sourceLanguage: string | null | undefined,
untranslated: string[],
languages: readonly string[]
): ImportTranslation {
if (!byLanguage || !sourceLanguage || !languages.includes(sourceLanguage)) return { kind: 'none' };
const others = languages.filter(l => l !== sourceLanguage);
const translated = others.filter(l => Object.keys(byLanguage[l] ?? {}).length > 0);
if (!translated.length) return { kind: 'failed', source: sourceLanguage, targets: others };
if (!untranslated.length) return { kind: 'translated', source: sourceLanguage, targets: translated };
const shown = untranslated.slice(0, MAX_UNTRANSLATED_SHOWN).join(', ');
return {
kind: 'partial',
source: sourceLanguage,
targets: translated,
count: untranslated.length,
total: Object.keys(byLanguage[sourceLanguage] ?? {}).length,
titles: untranslated.length > MAX_UNTRANSLATED_SHOWN ? `${shown}…` : shown
};
}
@@ -68,6 +68,13 @@
</span>
@if (spells.length > 1) {
<span class="spell-status-actions">
@if (harmonizable > 0) {
<button type="button" class="link-button" (click)="harmonize()"
[title]="'spellCatalog.harmonizeTitle' | translate">
<lucide-icon [img]="WandSparkles" [size]="13"></lucide-icon>
{{ 'spellCatalog.harmonize' | translate:{ count: harmonizable } }}
</button>
}
<button type="button" class="link-button" (click)="sort()" [title]="'spellCatalog.sortTitle' | translate">
<lucide-icon [img]="ArrowDownNarrowWide" [size]="13"></lucide-icon>
{{ 'spellCatalog.sort' | translate }}
@@ -79,6 +86,9 @@
}
</div>
}
@if (harmonized !== null) {
<p class="spell-note" role="status">{{ 'spellCatalog.harmonized' | translate:{ count: harmonized } }}</p>
}
<div class="spell-list">
@for (spell of visibleSpells; track spell; let i = $index) {
@@ -224,7 +224,7 @@
.spell-level {
flex-shrink: 0;
min-width: 1.75rem;
max-width: 9rem;
max-width: 12rem;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background: rgba(108, 99, 255, 0.2);
@@ -361,3 +361,14 @@
.spell-title { max-width: none; flex: 1; }
.spell-toolbar-actions { margin-left: 0; }
}
// Confirmation de l'harmonisation des niveaux et des écoles.
.spell-note {
margin: 0;
padding: 0.5rem 0.75rem;
border: 1px solid rgba(167, 139, 250, 0.3);
border-radius: 8px;
background: rgba(167, 139, 250, 0.06);
color: #c4b5fd;
font-size: 0.85rem;
}
@@ -4,6 +4,7 @@ import { TranslatePipe } from '@ngx-translate/core';
import {
LucideAngularModule, ArrowDownNarrowWide, ChevronDown, ChevronRight, Plus, Search, Sparkles, Trash2, WandSparkles, X
} from 'lucide-angular';
import { LanguageService } from '../../services/language.service';
import { ProposedSpell } from '../../services/spell.model';
import { TemplateField } from '../../services/template.model';
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
@@ -11,6 +12,7 @@ import {
NO_FILTER, SpellDraft, SpellFilter, distinctValues, filterSpells, isFiltering, newSpell, sortByLevelThenName,
summary, usableFields
} from '../spell-catalog.util';
import { cantripLabel, harmonizeSpells } from '../spell-harmonize.util';
import { SpellProposalComponent } from '../spell-proposal/spell-proposal.component';
import { RuleText, addProposedSpells } from '../spell-proposal.util';
@@ -48,6 +50,7 @@ export class SpellCatalogEditorComponent {
readonly fieldSuggestions = FIELD_SUGGESTIONS;
private readonly host: ElementRef<HTMLElement> = inject(ElementRef);
private readonly language = inject(LanguageService);
/** Sorts du catalogue. La liste est remplacée (jamais modifiée sur place) à chaque ajout, retrait ou tri. */
@Input() spells: SpellDraft[] = [];
@@ -67,6 +70,10 @@ export class SpellCatalogEditorComponent {
filter: SpellFilter = { ...NO_FILTER };
/** La proposition de sorts à partir des règles est-elle ouverte ? */
proposing = false;
/** Nombre de sorts réécrits par la dernière harmonisation (message de confirmation). */
harmonized: number | null = null;
/** Dernier calcul de `harmonizable`, tant que niveaux et écoles n'ont pas bougé. */
private harmonizableCache: { signature: string; count: number } | null = null;
selectView(view: SpellView): void {
this.view = view;
@@ -104,6 +111,33 @@ export class SpellCatalogEditorComponent {
this.filter = { ...NO_FILTER };
}
// ─────────────── Niveaux et écoles écrits de la même façon ───────────────
/**
* Nombre de sorts dont le niveau ou l'école changerait à l'harmonisation (« Niveau 1 » →
* « 1 », « Cantrip » → « Tour de magie », « Sorts de foudre » → « Foudre »…). Le bouton
* n'apparaît que s'il y a quelque chose à faire.
*/
get harmonizable(): number {
const signature = this.language.current + '\u0001'
+ this.spells.map(s => `${s.level ?? ''}\u0002${s.school ?? ''}`).join('\u0001');
if (this.harmonizableCache?.signature !== signature) {
const count = harmonizeSpells(this.spells, cantripLabel(this.language.current)).changed;
this.harmonizableCache = { signature, count };
}
return this.harmonizableCache.count;
}
/** Réécrit niveaux et écoles d'une seule façon. Rien n'est enregistré avant l'enregistrement du système. */
harmonize(): void {
const { spells, changed } = harmonizeSpells(this.spells, cantripLabel(this.language.current));
if (!changed) return;
this.clearFilter();
this.spells = spells;
this.harmonized = changed;
this.spellsChange.emit(this.spells);
}
/** Nouveau sort en tête de liste, ouvert, le curseur dans son nom. */
addSpell(): void {
this.clearFilter();
@@ -152,6 +186,7 @@ export class SpellCatalogEditorComponent {
* présents ne sont pas touchés ; rien n'est enregistré avant l'enregistrement du système.
*/
onProposed(proposals: ProposedSpell[]): void {
this.harmonized = null;
this.clearFilter();
this.spells = addProposedSpells(this.spells, proposals);
this.spellsChange.emit(this.spells);
@@ -68,7 +68,8 @@ describe('spell-catalog.util', () => {
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']);
// Les tours de magie passent avant le niveau 1.
expect(distinctValues(spells, 'level')).toEqual(['Tour de magie', '2', '10']);
expect(distinctValues(spells, 'school')).toEqual(['Abjuration', 'Illusion']);
});
+10 -5
View File
@@ -1,5 +1,6 @@
import { Spell } from '../services/spell.model';
import { TemplateField } from '../services/template.model';
import { compareLevels } from './spell-harmonize.util';
/**
* Catalogue de sorts : logique pure de l'onglet « Sorts » (recherche, filtres, tri, contrôle
@@ -86,14 +87,18 @@ 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. */
/**
* Niveaux (ou écoles) présents dans le catalogue, sans doublon, dans l'ordre naturel ; pour
* les niveaux, les tours de magie passent avant le niveau 1.
*/
export function distinctValues(spells: Spell[], key: 'level' | 'school'): string[] {
return [...new Set(spells.map(s => clean(s[key])).filter(Boolean))].sort(NATURAL.compare);
return [...new Set(spells.map(s => clean(s[key])).filter(Boolean))]
.sort(key === 'level' ? compareLevels : 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é.
* Catalogue rangé par niveau puis par nom (nouvelle liste). Les tours de magie viennent avant
* le niveau 1 et 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
@@ -102,7 +107,7 @@ export function sortByLevelThenName<T extends Spell>(spells: T[]): T[] {
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;
return compareLevels(la, lb) || NATURAL.compare(clean(a.spell.name), clean(b.spell.name)) || a.index - b.index;
})
.map(entry => entry.spell);
}
@@ -0,0 +1,140 @@
import { describe, it, expect } from 'vitest';
import {
cantripLabel, compareLevels, harmonizeSpells, isCantrip, normalizeLevel, tidySchool
} from './spell-harmonize.util';
import { Spell } from '../services/spell.model';
const FR = cantripLabel('fr');
const spell = (name: string, level: string, school = ''): Spell => ({ name, level, school, description: '', values: {} });
describe('normalizeLevel', () => {
it('écrit un niveau numéroté par son seul nombre', () => {
for (const raw of ['1', 'Niveau 1', 'NIVEAU 1', 'niveau 1', 'Niv. 1', 'Level 1', 'Sort de niveau 1',
'1er niveau', '1st level', '01']) {
expect(normalizeLevel(raw, FR), raw).toBe('1');
}
expect(normalizeLevel('3e niveau', FR)).toBe('3');
expect(normalizeLevel('Niveau 10', FR)).toBe('10');
});
it('laisse de côté ce qui suit le niveau', () => {
expect(normalizeLevel('NIVEAU 3, ZONE', FR)).toBe('3');
expect(normalizeLevel('Niveau 9, Zone', FR)).toBe('9');
expect(normalizeLevel('5 (zone)', FR)).toBe('5');
});
it('donne un seul nom aux sorts de niveau 0', () => {
for (const raw of ['Tour de magie', 'TOUR DE MAGIE', 'Tours de magie', 'Tour', 'TOUR', 'Cantrip', 'cantrips',
'Sort mineur']) {
expect(normalizeLevel(raw, FR), raw).toBe('Tour de magie');
}
expect(normalizeLevel('Tour de magie', cantripLabel('en'))).toBe('Cantrip');
expect(cantripLabel('de')).toBe('Tour de magie');
});
it('garde la précision qui suit', () => {
expect(normalizeLevel('CANTRIP UTILITAIRE', FR)).toBe('Tour de magie utilitaire');
expect(normalizeLevel('Cantrip utilitaire', FR)).toBe('Tour de magie utilitaire');
});
it("ne prend pas pour un niveau 0 un mot qui commence pareil", () => {
expect(normalizeLevel('Tourmente', FR)).toBe('Tourmente');
expect(isCantrip('Tourmente')).toBe(false);
expect(isCantrip(' tour ')).toBe(true);
});
it("garde le vocabulaire d'un autre système, casse rangée", () => {
expect(normalizeLevel('Rang II', FR)).toBe('Rang II');
expect(normalizeLevel('RANG II', FR)).toBe('Rang II');
expect(normalizeLevel('Cercle 3', FR)).toBe('Cercle 3');
// Livre en anglais : « TIER 3, AOE » et « Tier 3 » sont le même palier.
expect(normalizeLevel('TIER 3, AOE', FR)).toBe('Tier 3');
expect(normalizeLevel('Tier 3', FR)).toBe('Tier 3');
expect(normalizeLevel('tier 1', FR)).toBe('Tier 1');
expect(normalizeLevel('RANG 2', FR)).toBe('Rang 2');
expect(normalizeLevel('RITUEL MAJEUR', FR)).toBe('Rituel majeur');
expect(normalizeLevel('1-3', FR)).toBe('1-3');
expect(normalizeLevel('1/2', FR)).toBe('1/2');
expect(normalizeLevel(' ', FR)).toBe('');
expect(normalizeLevel(null, FR)).toBe('');
});
});
describe('tidySchool', () => {
it("retire l'habillage d'une école", () => {
expect(tidySchool('Sorts de foudre')).toBe('Foudre');
expect(tidySchool('Sorts radiants')).toBe('Radiants');
expect(tidySchool("École d'évocation")).toBe('Évocation');
expect(tidySchool('Magie du feu')).toBe('Feu');
expect(tidySchool('Fire spells')).toBe('Fire');
expect(tidySchool('School of Necromancy')).toBe('Necromancy');
expect(tidySchool('NÉCROTIQUE')).toBe('Nécrotique');
});
it("ne vide pas une école et ne coupe pas un nom qui se tient seul", () => {
expect(tidySchool('Magie blanche')).toBe('Magie blanche');
expect(tidySchool('Sorts')).toBe('Sorts');
expect(tidySchool('vent')).toBe('Vent');
expect(tidySchool('')).toBe('');
});
});
describe('harmonizeSpells', () => {
it('rassemble les écritures relevées sur un vrai catalogue', () => {
const spells = [
spell('Arc Lightning', '1', 'Sorts de foudre'),
spell('Heal', 'NIVEAU 1', 'Sorts radiants'),
spell('Vampiric Greed', 'NIVEAU 3, ZONE', 'Sorts nécrotiques'),
spell('Beautify', 'Cantrip', 'Radiant'),
spell('False Face', 'Cantrip', 'Nécrotique'),
spell('Fire Step', 'CANTRIP UTILITAIRE', 'Feu'),
spell('Spark Buddy', 'CANTRIP UTILITAIRE', 'Foudre'),
spell('Razor Wind', 'Tour', 'Sorts de vent'),
spell('Rebuke', 'TOUR', 'Sorts radiants'),
spell('Flame Dart', 'Tour de magie', 'Sorts de feu'),
spell('Withering Touch', 'TOUR DE MAGIE', 'Sorts nécrotiques')
];
const { spells: out, changed } = harmonizeSpells(spells, FR);
expect(out.map(s => s.level)).toEqual(['1', '1', '3', 'Tour de magie', 'Tour de magie',
'Tour de magie utilitaire', 'Tour de magie utilitaire', 'Tour de magie', 'Tour de magie',
'Tour de magie', 'Tour de magie']);
expect(out.map(s => s.school)).toEqual(['Foudre', 'Radiant', 'Nécrotique', 'Radiant', 'Nécrotique',
'Feu', 'Foudre', 'Vent', 'Radiant', 'Feu', 'Nécrotique']);
expect(changed).toBe(11);
// Rien d'autre ne bouge, et l'entrée n'est pas modifiée.
expect(out.map(s => s.name)).toEqual(spells.map(s => s.name));
expect(spells[1].level).toBe('NIVEAU 1');
});
it('rend le même objet pour un sort déjà harmonisé', () => {
const tidy = spell('Zap', 'Tour de magie', 'Foudre');
const { spells: out, changed } = harmonizeSpells([tidy, spell('Heal', '1')], FR);
expect(changed).toBe(0);
expect(out[0]).toBe(tidy);
// Une seconde passe ne change plus rien.
const once = harmonizeSpells([spell('A', 'NIVEAU 2', 'Sorts de glace')], FR).spells;
expect(harmonizeSpells(once, FR).changed).toBe(0);
});
it("aligne une proposition sur l'écriture du catalogue, sans toucher au catalogue", () => {
const catalogue = [spell('Zap', 'Tour de magie', 'Évocation'), spell('Bolt', '1', 'Évocation')];
const { spells: out } = harmonizeSpells([spell('Spark', 'cantrip', 'evocations')], FR, catalogue);
expect(out[0]).toMatchObject({ level: 'Tour de magie', school: 'Évocation' });
expect(catalogue[0].school).toBe('Évocation');
});
it('retient l’écriture la plus fréquente, sinon la plus courte', () => {
const out = harmonizeSpells([spell('A', 'Rituel'), spell('B', 'rituel'), spell('C', 'rituel'),
spell('D', '', 'Ombres'), spell('E', '', 'Ombre')], FR).spells;
expect(out.map(s => s.level)).toEqual(['rituel', 'rituel', 'rituel', '', '']);
expect(out.slice(3).map(s => s.school)).toEqual(['Ombre', 'Ombre']);
});
});
describe('compareLevels', () => {
it('range les tours de magie avant le niveau 1, puis les nombres dans l’ordre', () => {
const levels = ['10', 'Rang II', '2', 'Tour de magie utilitaire', '1', 'Tour de magie'];
expect(levels.sort(compareLevels)).toEqual(
['Tour de magie', 'Tour de magie utilitaire', '1', '2', '10', 'Rang II']);
});
});
@@ -0,0 +1,253 @@
import { Spell } from '../services/spell.model';
/**
* Harmonisation des niveaux et des écoles d'un catalogue de sorts.
*
* Les sorts proposés par l'IA sont relevés morceau par morceau : d'un morceau à l'autre, le
* même niveau sort écrit « 1 », « Niveau 1 » ou « NIVEAU 1, ZONE », le même palier « Tour de
* magie », « Tour » ou « Cantrip », la même école « Sorts de foudre » ou « Foudre ». Ici, une
* seule écriture par niveau et par école — sans rien demander à l'IA, donc toujours pareil :
*
* - un niveau numéroté s'écrit par son seul nombre (« Niveau 3, zone » → « 3 ») ; un palier
* propre au système garde son mot (« TIER 3, AOE » → « Tier 3 ») ;
* - les sorts de niveau 0 portent tous le même nom (« Tour de magie » en français, « Cantrip »
* en anglais), suivi de leur précision s'ils en ont une (« Cantrip utilitaire » → « Tour de
* magie utilitaire ») ;
* - une école perd son habillage (« Sorts de foudre » → « Foudre », « Fire spells » → « Fire ») ;
* - deux écritures qui ne diffèrent que par la casse, les accents ou un pluriel n'en font
* qu'une : pour un niveau la plus fréquente, pour une école la plus courte (le singulier).
*/
/** Nom des sorts de niveau 0, par langue de l'interface. */
export const CANTRIP_LABELS: Record<string, string> = { fr: 'Tour de magie', en: 'Cantrip' };
export function cantripLabel(language: string): string {
return CANTRIP_LABELS[language] ?? CANTRIP_LABELS['fr'];
}
const clean = (value: unknown): string => (value == null ? '' : String(value)).replace(/\s+/g, ' ').trim();
/** Comparaison sans casse ni accents. */
const fold = (text: string): string => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
const isLetterOrDigit = (char: string): boolean => /[\p{L}\d]/u.test(char);
/** Début de `words` égal à l'une des suites de mots de `heads` (sans casse ni accents) : sa longueur, sinon 0. */
function leadingWords(words: string[], heads: string[][]): number {
const folded = words.map(fold);
const found = heads.find(head => head.every((word, i) => folded[i] === word));
return found ? found.length : 0;
}
/** Noms donnés aux sorts de niveau 0, du plus long au plus court. */
const CANTRIP_NAMES = [
['tour', 'de', 'magie'], ['tours', 'de', 'magie'], ['sort', 'mineur'], ['sorts', 'mineurs'],
['minor', 'spell'], ['minor', 'spells'], ['cantrip'], ['cantrips'], ['tour'], ['tours']
];
/** Mots d'un niveau, ponctuation de fin de mot mise de côté : « Cantrip, utilitaire » → Cantrip · utilitaire. */
const levelWords = (text: string): string[] => text.split(' ').map(withoutTrailingPunctuation).filter(Boolean);
const PUNCTUATION = new Set([',', ':', ';', '.']);
function withoutTrailingPunctuation(word: string): string {
let end = word.length;
while (end > 0 && PUNCTUATION.has(word.charAt(end - 1))) end--;
return word.slice(0, end);
}
/** Nombre de mots que prend le nom des sorts de niveau 0 en tête du niveau (0 : ce n'en est pas un). */
function cantripLead(text: string): number {
return leadingWords(levelWords(text), CANTRIP_NAMES);
}
/** Mots qui annoncent un niveau numéroté : « Niveau 3 », « Niv. 3 », « Level 3 ». */
const LEVEL_WORDS = new Set(['niveau', 'niv', 'level', 'lvl']);
/** « Sort de niveau 3 », « Spell of level 3 ». */
const LEVEL_INTROS = [['sort', 'de'], ['sorts', 'de'], ['spell', 'of'], ['spells', 'of']];
/** « 1er », « 3e », « 1st »… */
const ORDINALS = new Set(['er', 're', 'e', 'eme', 'st', 'nd', 'rd', 'th']);
/** Le nombre en tête de `text`, s'il se lit comme un niveau : pas une plage (« 1-3 »), ni un dé (« 1d6 »). */
function leadingLevelNumber(text: string): number | null {
const digits = /^\d+/.exec(text)?.[0];
if (!digits) return null;
const after = text.slice(digits.length);
if (/^\s*[/–-]\s*\d/.test(after)) return null;
const suffix = /^\p{L}+/u.exec(after)?.[0] ?? '';
if (suffix && !ORDINALS.has(fold(suffix))) return null;
return Number(digits);
}
/** Niveau numéroté : « 3 », « 3e niveau », « Niveau 3, zone », « Sort de niveau 3 » → 3. */
function numberedLevel(text: string): number | null {
const direct = leadingLevelNumber(text);
if (direct !== null) return direct;
let words = levelWords(text);
words = words.slice(leadingWords(words, LEVEL_INTROS));
if (!words.length || !LEVEL_WORDS.has(fold(words[0]))) return null;
return leadingLevelNumber(words.slice(1).join(' '));
}
/** Paliers propres à un système, gardés avec leur mot : « Tier 3 », « Rang 2 », « Cercle 4 ». */
const TIER_WORDS = new Set(['tier', 'rang', 'rank', 'cercle', 'circle', 'palier']);
/** « TIER 3, AOE » → « Tier 3 » : le mot du système et son nombre, sans ce qui suit. */
function tieredLevel(text: string): string | null {
const words = levelWords(text);
if (words.length < 2 || !TIER_WORDS.has(fold(words[0]))) return null;
const number = leadingLevelNumber(words.slice(1).join(' '));
return number === null ? null : `${capitalize(words[0].toLowerCase())} ${number}`;
}
const ROMAN = /^[IVXLCDM]+$/;
/** « TOUR DE MAGIE » → « Tour de magie » ; un texte déjà en minuscules n'est pas touché. */
function tidyCase(text: string): string {
const letters = text.replace(/[^\p{L}]/gu, '');
if (letters.length < 4 || text !== text.toUpperCase()) return text;
const lowered = text.split(' ').map(word => (ROMAN.test(word) ? word : word.toLowerCase())).join(' ');
return lowered.charAt(0).toUpperCase() + lowered.slice(1);
}
const capitalize = (text: string): string => text.charAt(0).toUpperCase() + text.slice(1);
/** Le niveau désigne-t-il les sorts de niveau 0 (tour de magie, cantrip…) ? */
export function isCantrip(level: string | null | undefined): boolean {
return cantripLead(clean(level)) > 0;
}
/** Écriture unique d'un niveau. `cantrip` : nom donné aux sorts de niveau 0. */
export function normalizeLevel(raw: string | null | undefined, cantrip: string): string {
const text = clean(raw);
if (!text) return '';
const lead = cantripLead(text);
if (lead) {
const rest = levelWords(text).slice(lead).join(' ');
return rest && isLetterOrDigit(rest.charAt(0)) ? `${cantrip} ${rest.toLowerCase()}` : cantrip;
}
const numbered = numberedLevel(text);
if (numbered !== null) return String(numbered);
return tieredLevel(text) ?? tidyCase(text);
}
/** « Sorts de », « Sortilèges », « Spells of »… : toujours retirés en tête d'une école. */
const SCHOOL_HEADS = new Set(['sort', 'sorts', 'sortilege', 'sortileges', 'spell', 'spells']);
/** « École de », « Magie du », « School of »… : retirés seulement avec leur article. */
const SCHOOL_HEADS_LINKED = new Set(['ecole', 'ecoles', 'magie', 'magies', 'liste', 'listes', 'school', 'schools', 'magic']);
/** « Fire spells », « Fire magic » : retirés en fin d'école. */
const SCHOOL_TAILS = new Set(['spell', 'spells', 'magic', 'school']);
/** `words` sans l'article qui les ouvre (« de la », « du », « d' », « of the »…), ou null s'il n'y en a pas. */
function withoutLink(words: string[]): string[] | null {
if (!words.length) return null;
const first = fold(words[0]);
if (first === 'du' || first === 'des') return words.slice(1);
if (first.startsWith("d'") || first.startsWith('d’')) return [words[0].slice(2), ...words.slice(1)];
if (first !== 'de' && first !== 'of') return null;
const second = fold(words[1] ?? '');
if (second === 'la' || second === 'the') return words.slice(2);
if (second.startsWith("l'") || second.startsWith('l’')) return [words[1].slice(2), ...words.slice(2)];
return words.slice(1);
}
/** Une école sans son habillage : « Sorts de foudre » → « Foudre ». */
export function tidySchool(raw: string | null | undefined): string {
const text = clean(raw);
if (!text) return '';
let words = text.split(' ');
const head = fold(words[0]);
if (SCHOOL_HEADS.has(head) || SCHOOL_HEADS_LINKED.has(head)) {
const linked = withoutLink(words.slice(1));
if (linked) words = linked;
else if (SCHOOL_HEADS.has(head)) words = words.slice(1);
}
if (words.length > 1 && SCHOOL_TAILS.has(fold(words[words.length - 1]))) words = words.slice(0, -1);
const bare = words.join(' ').trim();
return capitalize(tidyCase(bare || text));
}
/** Deux écoles de même clé n'en font qu'une : casse, accents et pluriel ignorés. */
function schoolKey(tidy: string): string {
const key = fold(tidy);
return key.length > 4 && key.endsWith('s') ? key.slice(0, -1) : key;
}
/**
* Pour chaque clé, l'écriture retenue. Niveaux : la plus fréquente, sinon la plus courte.
* Écoles (`shortestFirst`) : la plus courte d'abord — entre « Radiants » et « Radiant », le
* singulier —, sinon la plus fréquente. À égalité, la première rencontrée.
*/
function canonicalForms(values: string[], keyOf: (value: string) => string, shortestFirst = false): Map<string, string> {
const counts = new Map<string, Map<string, number>>();
for (const value of values) {
if (!value) continue;
const forms = counts.get(keyOf(value)) ?? new Map<string, number>();
forms.set(value, (forms.get(value) ?? 0) + 1);
counts.set(keyOf(value), forms);
}
const better = (form: string, count: number, best: string, bestCount: number): boolean => {
const shorter = form.length < best.length;
const sameLength = form.length === best.length;
return shortestFirst
? shorter || (sameLength && count > bestCount)
: count > bestCount || (count === bestCount && shorter);
};
const out = new Map<string, string>();
for (const [key, forms] of counts) {
let best = '';
let bestCount = 0;
for (const [form, count] of forms) {
if (!best || better(form, count, best, bestCount)) {
best = form;
bestCount = count;
}
}
out.set(key, best);
}
return out;
}
export interface Harmonized<T> {
/** Les sorts, dans le même ordre ; un sort inchangé est le même objet qu'en entrée. */
spells: T[];
/** Nombre de sorts dont le niveau ou l'école a changé. */
changed: number;
}
/**
* Écrit de la même façon les niveaux et les écoles de `spells`.
*
* @param cantrip nom donné aux sorts de niveau 0 (cf. cantripLabel)
* @param reference sorts déjà là (catalogue, propositions précédentes) : ils ne sont pas
* modifiés, mais leurs écritures comptent pour choisir celle qui est retenue
*/
export function harmonizeSpells<T extends Spell>(spells: T[], cantrip: string, reference: Spell[] = []): Harmonized<T> {
const levelOf = (spell: Spell) => normalizeLevel(spell.level, cantrip);
const schoolOf = (spell: Spell) => tidySchool(spell.school);
const all = [...reference, ...spells];
const levels = canonicalForms(all.map(levelOf), fold);
const schools = canonicalForms(all.map(schoolOf), schoolKey, true);
let changed = 0;
const out = spells.map(spell => {
const level = levelOf(spell);
const school = schoolOf(spell);
const nextLevel = level ? levels.get(fold(level)) ?? level : '';
const nextSchool = school ? schools.get(schoolKey(school)) ?? school : '';
if (nextLevel === clean(spell.level) && nextSchool === clean(spell.school)) return spell;
changed++;
return { ...spell, level: nextLevel, school: nextSchool };
});
return { spells: out, changed };
}
const NATURAL = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
/** Ordre des niveaux : tours de magie d'abord, puis « 2 » avant « 10 », puis le reste. */
export function compareLevels(a: string, b: string): number {
const ca = isCantrip(a);
const cb = isCantrip(b);
if (ca !== cb) return ca ? -1 : 1;
return NATURAL.compare(a, b);
}
@@ -3,9 +3,11 @@ 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 { LanguageService } from '../../services/language.service';
import { ProposedSpell, Spell } from '../../services/spell.model';
import { TemplateField } from '../../services/template.model';
import { summary } from '../spell-catalog.util';
import { cantripLabel, harmonizeSpells } from '../spell-harmonize.util';
import {
ReadingChunk, RuleText, chunksFor, isInCatalogue, suggestedSections
} from '../spell-proposal.util';
@@ -40,14 +42,18 @@ export class SpellProposalComponent implements OnInit, OnDestroy {
readonly Sparkles = Sparkles;
private readonly service = inject(GameSystemService);
private readonly language = inject(LanguageService);
/** 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 déjà dans le catalogue : jamais proposés une seconde fois. Leurs niveaux et leurs
* écoles servent aussi de modèle d'écriture aux sorts proposés.
*/
@Input() catalogue: Spell[] = [];
/** Sorts cochés que le parent ajoute au catalogue. */
@Output() add = new EventEmitter<ProposedSpell[]>();
@@ -125,7 +131,12 @@ export class SpellProposalComponent implements OnInit, OnDestroy {
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 ?? []) {
// D'un morceau à l'autre, l'IA n'écrit pas un niveau ou une école de la même façon
// (« 1 », « Niveau 1 » ; « Tour », « Cantrip ») : une seule écriture, alignée sur le
// catalogue et sur les sorts déjà relevés.
const incoming = harmonizeSpells(response.spells ?? [], cantripLabel(this.language.current),
[...this.catalogue, ...this.found.map(f => f.spell)]).spells;
for (const spell of incoming) {
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));
+17 -1
View File
@@ -52,6 +52,22 @@ export interface CampaignImportProposal {
npcs?: NpcProposal[];
}
/**
* Compte rendu d'un import découpé d'après la structure du livre (absent si l'IA a
* reconstruit l'arborescence).
*/
export interface CampaignImportOutcome {
/** 'bookmarks' (table des matières du PDF) ou 'headings' (titres repérés). */
splitMethod?: string | null;
sourceLanguage?: string | null;
/** Textes restés dans la langue du livre faute de traduction. */
untranslated: number;
/** Lots de scènes pour lesquels l'IA n'a pas rendu ses aides. */
skippedAids: number;
/** Les passes de l'IA n'ont pas abouti : campagne livrée avec le seul texte du livre. */
aiInterrupted: boolean;
}
/** Récapitulatif renvoyé après création effective des entités. */
export interface CampaignImportApplyResult {
arcsCreated: number;
@@ -81,5 +97,5 @@ export type CampaignImportStreamEvent =
sceneCount: number;
npcCount: number;
}
| { type: 'done'; arcs: ArcProposal[]; npcs: NpcProposal[] }
| { type: 'done'; arcs: ArcProposal[]; npcs: NpcProposal[]; outcome?: CampaignImportOutcome | null }
| { type: 'error'; message: string };
@@ -8,7 +8,7 @@ import {
CampaignImportStreamEvent
} from './campaign-import.model';
import { LanguageService } from './language.service';
import { parseSseStream, sseFetch } from '../shared/sse.util';
import { parseSseStream, replaceNetworkError, sseFetch } from '../shared/sse.util';
/**
* Service HTTP pour l'import d'un PDF de campagne.
@@ -32,7 +32,8 @@ export class CampaignImportService {
body: form
},
(body, subscriber) => this.consumeSse(body, subscriber)
);
// Connexion coupée : le navigateur ne donne qu'un texte brut (« Error in input stream »).
).pipe(replaceNetworkError(() => this.translate.instant('services.importInterrupted')));
}
applyStructure(campaignId: string, proposal: CampaignImportProposal): Observable<CampaignImportApplyResult> {
@@ -68,7 +69,7 @@ export class CampaignImportService {
const obj = JSON.parse(data);
if (event === 'done') {
terminated = true;
subscriber.next({ type: 'done', arcs: obj.arcs ?? [], npcs: obj.npcs ?? [] });
subscriber.next({ type: 'done', arcs: obj.arcs ?? [], npcs: obj.npcs ?? [], outcome: obj.outcome ?? null });
subscriber.complete();
} else {
subscriber.next({ type: 'progress', ...obj });
+5 -1
View File
@@ -47,7 +47,11 @@ export type RulesImportStreamEvent =
| { type: 'status'; message: string }
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number;
/** Règles en deux langues : {fr|en → sections} ; langue d'origine du livre. */
sectionsByLanguage?: Record<string, Record<string, string>>; sourceLanguage?: string | null }
sectionsByLanguage?: Record<string, Record<string, string>>; sourceLanguage?: string | null;
/** Titres des sections que la traduction n'a pas pu traiter (texte d'origine gardé). */
untranslatedTitles?: string[];
/** Découpage du livre : « bookmarks » ou « headings » (sans IA), « ai », ou absent. */
splitMethod?: string | null }
| { type: 'error'; message: string };
/** Payload de creation/mise a jour (sans id). */
+3 -2
View File
@@ -8,7 +8,7 @@ import {
SheetFieldProposal, SheetProposalRequest
} from './game-system.model';
import { LanguageService } from './language.service';
import { parseSseStream, sseFetch } from '../shared/sse.util';
import { parseSseStream, replaceNetworkError, sseFetch } from '../shared/sse.util';
/**
* Service HTTP pour les GameSystems (systèmes de JDR).
@@ -110,7 +110,8 @@ export class GameSystemService {
body: form
},
(body, subscriber) => this.consumeImportSse(body, subscriber)
);
// Connexion coupée : le navigateur ne donne qu'un texte brut (« Error in input stream »).
).pipe(replaceNetworkError(() => this.translate.instant('services.importInterrupted')));
}
/** Mappe les évènements SSE bruts vers les évènements d'import typés. */
@@ -37,7 +37,7 @@
.spell-level {
flex-shrink: 0;
max-width: 8rem;
max-width: 12rem;
padding: 0.1rem 0.45rem;
border-radius: 999px;
background: rgba(108, 99, 255, 0.2);
+22 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { parseSseStream, sseFetch, SseEvent } from './sse.util';
import { firstValueFrom, throwError } from 'rxjs';
import { isNetworkError, parseSseStream, replaceNetworkError, sseFetch, SseEvent } from './sse.util';
/** Construit un ReadableStream à partir d'une chaîne (un seul chunk). */
function streamFrom(text: string): ReadableStream<Uint8Array> {
@@ -110,3 +111,23 @@ describe('sseFetch', () => {
expect(abortedSignal?.aborted).toBe(true);
});
});
describe('replaceNetworkError', () => {
const readable = () => 'Import interrompu.';
it('reconnaît une coupure réseau quel que soit le texte du navigateur', () => {
expect(isNetworkError(new TypeError('Error in input stream'))).toBe(true);
expect(isNetworkError(new TypeError('Failed to fetch'))).toBe(true);
expect(isNetworkError(new Error('HTTP 502'))).toBe(false);
});
it('remplace le texte brut du navigateur par un message lisible', async () => {
const failing = throwError(() => new TypeError('Error in input stream')).pipe(replaceNetworkError(readable));
await expect(firstValueFrom(failing)).rejects.toThrow('Import interrompu.');
});
it("laisse passer une erreur déjà parlante (message du serveur)", async () => {
const failing = throwError(() => new Error('Le fournisseur IA a refusé la clé.')).pipe(replaceNetworkError(readable));
await expect(firstValueFrom(failing)).rejects.toThrow('Le fournisseur IA a refusé la clé.');
});
});
+19 -1
View File
@@ -1,4 +1,4 @@
import { Observable, Subscriber } from 'rxjs';
import { MonoTypeOperatorFunction, Observable, Subscriber, catchError, throwError } from 'rxjs';
/**
* Plumbing SSE mutualisé entre les services qui streament depuis le backend
@@ -108,3 +108,21 @@ export function sseFetch<T>(
return () => controller.abort();
});
}
/**
* Vrai si l'erreur vient du réseau (connexion coupée, serveur injoignable). `fetch()` et la
* lecture de son flux lèvent alors un `TypeError` dont le texte dépend du navigateur
* (« Failed to fetch », « network error », « Error in input stream »…) : rien de lisible
* pour l'utilisateur.
*/
export function isNetworkError(err: unknown): boolean {
return err instanceof TypeError;
}
/**
* Remplace une erreur réseau par un message lisible (fourni à la demande, pour être traduit
* dans la langue du moment). Les autres erreurs, déjà parlantes, passent telles quelles.
*/
export function replaceNetworkError<T>(message: () => string): MonoTypeOperatorFunction<T> {
return catchError((err: unknown) => throwError(() => (isNetworkError(err) ? new Error(message()) : err)));
}
+23 -7
View File
@@ -676,7 +676,7 @@
"pageTitle": "Import a campaign",
"back": "Back to the campaign",
"title": "Import a campaign PDF",
"subtitle": "The AI proposes an arc → adventure → scene tree. You review and adjust it before creating anything.",
"subtitle": "The book is split into arcs, adventures and scenes from its table of contents, with its text as written. The AI adds a synopsis for each scene and the NPC sheets. You review and adjust before creating anything.",
"importing": "Import in progress…",
"choosePdf": "Choose a campaign PDF",
"phaseExtracting": "Extracting text…",
@@ -719,9 +719,14 @@
"chapter": "Adventure",
"addArc": "Add an arc",
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
"npcReviewHint": "Check the ones to create in the campaign (description taken from the book). Those already present in the campaign are greyed out and will not be recreated.",
"npcReviewHint": "Check the ones to create in the campaign (sheet written by the AI from the book). Those already present in the campaign are greyed out and will not be recreated.",
"creating": "Creating…",
"createInCampaign": "Create in the campaign"
"createInCampaign": "Create in the campaign",
"noteSplitBookmarks": "Split from the table of contents of the PDF. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
"noteSplitHeadings": "Split from the headings of the book. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
"noteAiInterrupted": "The AI could not finish its work. The campaign is proposed with the text of the book, without translation or NPC sheets; each synopsis is the beginning of the text of its scene.",
"noteSkippedAids": "The AI did not answer for {{n}} batch(es) of scenes: their synopsis is the beginning of their text.",
"noteUntranslated": "Incomplete translation: {{n}} text(s) stayed in the language of the book."
},
"chapterCreate": {
"titleQuest": "Create a new adventure",
@@ -1266,7 +1271,7 @@
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
"importButton": "Import a rules PDF",
"importInProgress": "Importing…",
"importHint": "The AI suggests a breakdown into sections — you review it before saving.",
"importHint": "The book is split into sections following its table of contents — you review it before saving.",
"sectionsFound": "Sections found: {{titles}}",
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
"removeSection": "Remove this section",
@@ -1337,7 +1342,15 @@
"sectionSize": "{{count}} chars",
"needsName": "Give the system a name to save it.",
"invalidFields": "This sheet has a field with no name or a duplicate: fix it to save.",
"saveFailed": "Saving failed. Your changes are still on screen: try again."
"saveFailed": "Saving failed. Your changes are still on screen: try again.",
"importPartlyTranslated": "Translation incomplete: {{count}} of {{total}} section(s) could not be translated and keep their original text in the {{target}} tab ({{titles}}).",
"importNotTranslated": "The translation to the {{target}} tab did not complete: only the {{source}} tab is filled. The app and the AI use these rules in both languages.",
"sectionEdit": "Edit",
"sectionDone": "Done",
"sectionEmpty": "Empty section — click to write its rules.",
"sectionEditHint": "Markdown formatting: ### subheading, **bold**, - list, | table |. Click Done to read the result.",
"importSplitBookmarks": "Sections taken from the PDF's table of contents, without AI: their titles are those of the book.",
"importSplitHeadings": "Sections found from the book's headings, without AI: their titles are those of the book."
},
"ollamaModelManager": {
"installedModels": "Installed models",
@@ -3611,13 +3624,16 @@
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
"already": "already in the catalogue",
"source": "from “{{section}}”",
"reviewHint": "The name and a passage of each spell were found in your rules. The description and values are picked out by the AI: review them after adding.",
"reviewHint": "The description of each spell is taken from your rules, word for word. The level, school and field values are picked out by the AI: review them after adding.",
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
"add": "Add the ticked spells ({{count}})",
"added": "{{count}} spell(s) added at the end of the catalogue. Review them, then save the system.",
"close": "Close the suggestion"
}
},
"harmonize": "Harmonize levels and schools ({{count}})",
"harmonizeTitle": "Writes levels and schools one single way: “Level 1” becomes “1”, “Tour de magie” becomes “Cantrip”, “Fire spells” becomes “Fire”.",
"harmonized": "{{count}} spell(s) rewritten: levels and schools are now written one single way. Save to keep."
},
"sheetSpells": {
"title": "Known spells",
+23 -7
View File
@@ -676,7 +676,7 @@
"pageTitle": "Importer une campagne",
"back": "Retour à la campagne",
"title": "Importer un PDF de campagne",
"subtitle": "L'IA propose une arborescence arc → aventure → scène. Vous la révisez et l'ajustez avant de créer quoi que ce soit.",
"subtitle": "Le livre est découpé en arcs, aventures et scènes d'après sa table des matières, avec son texte tel qu'il est écrit. L'IA y ajoute un synopsis par scène et les fiches des PNJ. Vous révisez et ajustez avant de créer quoi que ce soit.",
"importing": "Import en cours…",
"choosePdf": "Choisir un PDF de campagne",
"phaseExtracting": "Extraction du texte…",
@@ -719,9 +719,14 @@
"chapter": "Aventure",
"addArc": "Ajouter un arc",
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
"npcReviewHint": "Cochez ceux à créer dans la campagne (description issue du livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
"npcReviewHint": "Cochez ceux à créer dans la campagne (fiche rédigée par l'IA d'après le livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
"creating": "Création…",
"createInCampaign": "Créer dans la campagne"
"createInCampaign": "Créer dans la campagne",
"noteSplitBookmarks": "Découpage d'après la table des matières du PDF. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
"noteSplitHeadings": "Découpage d'après les titres du livre. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
"noteAiInterrupted": "L'IA n'a pas pu terminer son travail. La campagne est proposée avec le texte du livre, sans traduction ni fiches de PNJ ; chaque synopsis reprend le début du texte de sa scène.",
"noteSkippedAids": "L'IA n'a pas répondu pour {{n}} lot(s) de scènes : leur synopsis reprend le début de leur texte.",
"noteUntranslated": "Traduction incomplète : {{n}} texte(s) sont restés dans la langue du livre."
},
"chapterCreate": {
"titleQuest": "Créer une nouvelle aventure",
@@ -1266,7 +1271,7 @@
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
"importButton": "Importer un PDF de règles",
"importInProgress": "Import en cours…",
"importHint": "L'IA propose un découpage en sections — vous révisez avant d'enregistrer.",
"importHint": "Le livre est découpé en sections d'après sa table des matières — vous révisez avant d'enregistrer.",
"sectionsFound": "Sections trouvées : {{titles}}",
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
"removeSection": "Supprimer cette section",
@@ -1337,7 +1342,15 @@
"sectionSize": "{{count}} car.",
"needsName": "Donnez un nom au système pour l'enregistrer.",
"invalidFields": "Cette fiche contient un champ sans nom ou en double : corrigez-le pour enregistrer.",
"saveFailed": "L'enregistrement a échoué. Vos modifications sont toujours à l'écran : réessayez."
"saveFailed": "L'enregistrement a échoué. Vos modifications sont toujours à l'écran : réessayez.",
"importPartlyTranslated": "Traduction incomplète : {{count}} section(s) sur {{total}} n'ont pas pu être traduites et gardent leur texte d'origine dans l'onglet {{target}} ({{titles}}).",
"importNotTranslated": "La traduction vers l'onglet {{target}} n'a pas abouti : seul l'onglet {{source}} est rempli. L'appli et l'IA utilisent ces règles dans les deux langues.",
"sectionEdit": "Modifier",
"sectionDone": "Terminer",
"sectionEmpty": "Section vide — cliquez pour écrire ses règles.",
"sectionEditHint": "Mise en forme markdown : ### sous-titre, **gras**, - liste, | tableau |. Cliquez sur Terminer pour relire le résultat.",
"importSplitBookmarks": "Sections reprises de la table des matières du PDF, sans IA : leurs titres sont ceux du livre.",
"importSplitHeadings": "Sections repérées d'après les titres du livre, sans IA : leurs titres sont ceux du livre."
},
"ollamaModelManager": {
"installedModels": "Modèles installés",
@@ -3611,13 +3624,16 @@
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
"already": "déjà dans le catalogue",
"source": "d'après « {{section}} »",
"reviewHint": "Le nom et un passage de chaque sort ont été retrouvés dans vos règles. La description et les valeurs sont relevées par l'IA : relisez-les après l'ajout.",
"reviewHint": "La description de chaque sort est reprise de vos règles, mot pour mot. Le niveau, l'école et les valeurs des champs sont relevés par l'IA : relisez-les après l'ajout.",
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
"add": "Ajouter les sorts cochés ({{count}})",
"added": "{{count}} sort(s) ajouté(s) à la fin du catalogue. Relisez-les, puis enregistrez le système.",
"close": "Fermer la proposition"
}
},
"harmonize": "Harmoniser niveaux et écoles ({{count}})",
"harmonizeTitle": "Écrit les niveaux et les écoles d'une seule façon : « Niveau 1 » devient « 1 », « Cantrip » ou « Tour » devient « Tour de magie », « Sorts de foudre » devient « Foudre ».",
"harmonized": "{{count}} sort(s) réécrit(s) : niveaux et écoles s'écrivent maintenant d'une seule façon. Enregistrez pour conserver."
},
"sheetSpells": {
"title": "Sorts connus",
@@ -130,7 +130,7 @@
"pageTitle": "Import a campaign",
"back": "Back to the campaign",
"title": "Import a campaign PDF",
"subtitle": "The AI proposes an arc → adventure → scene tree. You review and adjust it before creating anything.",
"subtitle": "The book is split into arcs, adventures and scenes from its table of contents, with its text as written. The AI adds a synopsis for each scene and the NPC sheets. You review and adjust before creating anything.",
"importing": "Import in progress…",
"choosePdf": "Choose a campaign PDF",
"phaseExtracting": "Extracting text…",
@@ -173,8 +173,13 @@
"chapter": "Adventure",
"addArc": "Add an arc",
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
"npcReviewHint": "Check the ones to create in the campaign (description taken from the book). Those already present in the campaign are greyed out and will not be recreated.",
"npcReviewHint": "Check the ones to create in the campaign (sheet written by the AI from the book). Those already present in the campaign are greyed out and will not be recreated.",
"creating": "Creating…",
"createInCampaign": "Create in the campaign"
"createInCampaign": "Create in the campaign",
"noteSplitBookmarks": "Split from the table of contents of the PDF. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
"noteSplitHeadings": "Split from the headings of the book. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
"noteAiInterrupted": "The AI could not finish its work. The campaign is proposed with the text of the book, without translation or NPC sheets; each synopsis is the beginning of the text of its scene.",
"noteSkippedAids": "The AI did not answer for {{n}} batch(es) of scenes: their synopsis is the beginning of their text.",
"noteUntranslated": "Incomplete translation: {{n}} text(s) stayed in the language of the book."
}
}
@@ -130,7 +130,7 @@
"pageTitle": "Importer une campagne",
"back": "Retour à la campagne",
"title": "Importer un PDF de campagne",
"subtitle": "L'IA propose une arborescence arc → aventure → scène. Vous la révisez et l'ajustez avant de créer quoi que ce soit.",
"subtitle": "Le livre est découpé en arcs, aventures et scènes d'après sa table des matières, avec son texte tel qu'il est écrit. L'IA y ajoute un synopsis par scène et les fiches des PNJ. Vous révisez et ajustez avant de créer quoi que ce soit.",
"importing": "Import en cours…",
"choosePdf": "Choisir un PDF de campagne",
"phaseExtracting": "Extraction du texte…",
@@ -173,8 +173,13 @@
"chapter": "Aventure",
"addArc": "Ajouter un arc",
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
"npcReviewHint": "Cochez ceux à créer dans la campagne (description issue du livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
"npcReviewHint": "Cochez ceux à créer dans la campagne (fiche rédigée par l'IA d'après le livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
"creating": "Création…",
"createInCampaign": "Créer dans la campagne"
"createInCampaign": "Créer dans la campagne",
"noteSplitBookmarks": "Découpage d'après la table des matières du PDF. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
"noteSplitHeadings": "Découpage d'après les titres du livre. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
"noteAiInterrupted": "L'IA n'a pas pu terminer son travail. La campagne est proposée avec le texte du livre, sans traduction ni fiches de PNJ ; chaque synopsis reprend le début du texte de sa scène.",
"noteSkippedAids": "L'IA n'a pas répondu pour {{n}} lot(s) de scènes : leur synopsis reprend le début de leur texte.",
"noteUntranslated": "Traduction incomplète : {{n}} texte(s) sont restés dans la langue du livre."
}
}
@@ -26,11 +26,15 @@
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
"importButton": "Import a rules PDF",
"importInProgress": "Importing…",
"importHint": "The AI suggests a breakdown into sections — you review it before saving.",
"importHint": "The book is split into sections following its table of contents — you review it before saving.",
"sectionsFound": "Sections found: {{titles}}",
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
"removeSection": "Remove this section",
"sectionContentPlaceholder": "Describe the rules of this section...",
"sectionEdit": "Edit",
"sectionDone": "Done",
"sectionEmpty": "Empty section — click to write its rules.",
"sectionEditHint": "Markdown formatting: ### subheading, **bold**, - list, | table |. Click Done to read the result.",
"noSections": "No sections yet — add one with the buttons below.",
"addSection": "Add a section:",
"addOther": "Other…",
@@ -62,6 +66,10 @@
},
"langHint": "Rules exist in two versions: the app and the AI use the one matching the interface language (or the other if it's empty). Importing a PDF fills both, whatever its language.",
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab.",
"importSplitBookmarks": "Sections taken from the PDF's table of contents, without AI: their titles are those of the book.",
"importSplitHeadings": "Sections found from the book's headings, without AI: their titles are those of the book.",
"importPartlyTranslated": "Translation incomplete: {{count}} of {{total}} section(s) could not be translated and keep their original text in the {{target}} tab ({{titles}}).",
"importNotTranslated": "The translation to the {{target}} tab did not complete: only the {{source}} tab is filled. The app and the AI use these rules in both languages.",
"importSheetHint": "You can then ask for suggested fields for each sheet, in the Sheet structure tab.",
"sheetPropose": "Suggest fields from the rules",
"sheetProposing": "Reading the rules…",
@@ -26,11 +26,15 @@
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
"importButton": "Importer un PDF de règles",
"importInProgress": "Import en cours…",
"importHint": "L'IA propose un découpage en sections — vous révisez avant d'enregistrer.",
"importHint": "Le livre est découpé en sections d'après sa table des matières — vous révisez avant d'enregistrer.",
"sectionsFound": "Sections trouvées : {{titles}}",
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
"removeSection": "Supprimer cette section",
"sectionContentPlaceholder": "Décrivez les règles de cette section...",
"sectionEdit": "Modifier",
"sectionDone": "Terminer",
"sectionEmpty": "Section vide — cliquez pour écrire ses règles.",
"sectionEditHint": "Mise en forme markdown : ### sous-titre, **gras**, - liste, | tableau |. Cliquez sur Terminer pour relire le résultat.",
"noSections": "Aucune section pour l'instant — ajoutez-en une avec les boutons ci-dessous.",
"addSection": "Ajouter une section :",
"addOther": "Autre…",
@@ -62,6 +66,10 @@
},
"langHint": "Les règles existent en deux versions : l'appli et l'IA utilisent celle de la langue de l'interface (ou l'autre si elle est vide). Importer un PDF remplit les deux, dans n'importe quelle langue.",
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet.",
"importSplitBookmarks": "Sections reprises de la table des matières du PDF, sans IA : leurs titres sont ceux du livre.",
"importSplitHeadings": "Sections repérées d'après les titres du livre, sans IA : leurs titres sont ceux du livre.",
"importPartlyTranslated": "Traduction incomplète : {{count}} section(s) sur {{total}} n'ont pas pu être traduites et gardent leur texte d'origine dans l'onglet {{target}} ({{titles}}).",
"importNotTranslated": "La traduction vers l'onglet {{target}} n'a pas abouti : seul l'onglet {{source}} est rempli. L'appli et l'IA utilisent ces règles dans les deux langues.",
"importSheetHint": "Vous pouvez ensuite demander une proposition de champs pour chaque fiche, dans l'onglet Structure des fiches.",
"sheetPropose": "Proposer des champs à partir des règles",
"sheetProposing": "Lecture des règles…",
@@ -17,6 +17,9 @@
"clearFilter": "Show all",
"sort": "Sort by level",
"sortTitle": "Sorts the catalogue by level, then by name",
"harmonize": "Harmonize levels and schools ({{count}})",
"harmonizeTitle": "Writes levels and schools one single way: “Level 1” becomes “1”, “Tour de magie” becomes “Cantrip”, “Fire spells” becomes “Fire”.",
"harmonized": "{{count}} spell(s) rewritten: levels and schools are now written one single way. Save to keep.",
"collapseAll": "Collapse all",
"expandAll": "Expand all",
"open": "Open the spell",
@@ -65,7 +68,7 @@
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
"already": "already in the catalogue",
"source": "from “{{section}}”",
"reviewHint": "The name and a passage of each spell were found in your rules. The description and values are picked out by the AI: review them after adding.",
"reviewHint": "The description of each spell is taken from your rules, word for word. The level, school and field values are picked out by the AI: review them after adding.",
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
"add": "Add the ticked spells ({{count}})",
@@ -17,6 +17,9 @@
"clearFilter": "Tout afficher",
"sort": "Ranger par niveau",
"sortTitle": "Range le catalogue par niveau, puis par nom",
"harmonize": "Harmoniser niveaux et écoles ({{count}})",
"harmonizeTitle": "Écrit les niveaux et les écoles d'une seule façon : « Niveau 1 » devient « 1 », « Cantrip » ou « Tour » devient « Tour de magie », « Sorts de foudre » devient « Foudre ».",
"harmonized": "{{count}} sort(s) réécrit(s) : niveaux et écoles s'écrivent maintenant d'une seule façon. Enregistrez pour conserver.",
"collapseAll": "Tout replier",
"expandAll": "Tout déplier",
"open": "Ouvrir le sort",
@@ -65,7 +68,7 @@
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
"already": "déjà dans le catalogue",
"source": "d'après « {{section}} »",
"reviewHint": "Le nom et un passage de chaque sort ont été retrouvés dans vos règles. La description et les valeurs sont relevées par l'IA : relisez-les après l'ajout.",
"reviewHint": "La description de chaque sort est reprise de vos règles, mot pour mot. Le niveau, l'école et les valeurs des champs sont relevés par l'IA : relisez-les après l'ajout.",
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
"add": "Ajouter les sorts cochés ({{count}})",