Compare commits

..
12 Commits
Author SHA1 Message Date
ietm64 1898e8b1ae Passage 1.6.1-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 47s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 58s
Build & Push Images / build (brain) (push) Successful in 1m29s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m4s
Build & Push Images / build (web) (push) Successful in 2m20s
Build & Push Images / build-switcher (push) Successful in 24s
Build & Push Images / build (core) (push) Successful in 4m30s
2026-10-18 01:33:49 +02:00
ietm64 e77ad85be9 Import de règles : compteur d'attente et message de nouvel essai
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m2s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m48s
Après une erreur passagère du fournisseur IA, « nouvel essai dans 3s »
restait affiché pendant tout l'essai suivant, qui peut durer plusieurs
minutes : l'import paraissait bloqué alors qu'il avançait.
- Brain : un message annonce le lancement de l'essai suivant
  (« Nouvel essai en cours (tentative 2/3)… »).
- Écran du système de jeu : au-delà de 15 s sans nouvelle, un compteur
  indique depuis combien de temps l'IA travaille sur le morceau.

Vérifié : brain (234 tests), vitest, build, lint sans erreur.
À redéployer : web + brain.
2026-10-18 01:33:02 +02:00
ietm64 11939fe39e Import PDF : le résultat final ne dépasse plus la limite de 256 Ko
L'évènement de fin d'import porte tout le résultat : les règles d'un livre
entier, désormais en deux langues, ou l'arbre complet d'une campagne. La
limite par défaut de WebClient (256 Ko par évènement) faisait échouer
l'import au tout dernier moment, après toute l'analyse
(DataBufferLimitException). Les clients d'import acceptent maintenant
jusqu'à 64 Mo par évènement.

Vérifié : test avec un vrai serveur HTTP local et un évènement d'environ
1,8 Mo (échoue avec l'ancienne limite, passe avec la nouvelle) ; core
clean verify (1300 tests).
À redéployer : core.
2026-10-18 01:33:01 +02:00
ietm64 8958822545 Méthodes guidées : l'IA part de l'idée du MJ et suit la méthode étape par étape
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 55s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m3s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 55s
Build & Push Images / build (brain) (push) Successful in 2m30s
Build & Push Images / build (core) (push) Successful in 4m8s
Build & Push Images / build-switcher (push) Successful in 16s
Build & Push Images / build (web) (push) Successful in 2m46s
- L'idée de départ est obligatoire : les boutons « Proposer » restent
  inactifs tant qu'elle est vide, avec un message qui l'explique. Le champ
  est plus grand et invite à raconter son idée (lieu, adversaire, envies).
- L'IA reçoit la méthode telle que le MJ la suit à la main : le principe,
  puis le rôle de chaque étape (le « pourquoi » affiché dans l'assistant).
  Avant, elle ne voyait que les libellés des champs. Les exemples ne sont
  pas transmis, pour qu'elle ne les recopie pas.
- Prompt : garder le ton et le sujet de l'idée, et faire jouer à chaque
  réponse le rôle de son étape.

Vérifié : brain (233 tests), vitest (867), build, lint sans erreur, core
clean test-compile. Pas essayé avec un vrai modèle.
À redéployer : web + brain.
2026-10-18 00:43:46 +02:00
ietm64 007bcce8a7 Règles des systèmes en deux langues ; import de campagne dans la langue de l'UI
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 50s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m26s
- Règles d'un système de jeu stockées en français et en anglais (migration
  V28, rules_markdown_en). L'import d'un PDF garde l'extraction fidèle dans
  la langue du livre (détectée) et traduit section par section vers l'autre
  langue, noms propres conservés ; la progression de la traduction s'affiche.
  Un échec de traduction n'annule pas l'import.
- Éditeur du système : onglets Français / English ; l'import remplit les
  deux. Règles en séance et contexte de l'IA : version de la langue de
  l'interface, avec repli sur l'autre si elle est vide.
- Import de campagne : textes rédigés (ou traduits) dans la langue de
  l'interface ; titres et noms propres conservés tels quels ; arc par défaut
  nommé dans la bonne langue.
- Les règles anglaises suivent l'export/import de sauvegarde.

Vérifié : brain (détection, découpe, traduction, flux d'import, langue de
l'import de campagne), core clean verify (1299 tests), web build + vitest +
lint. Traduction non essayée avec un vrai modèle.
2026-10-18 00:37:01 +02:00
ietm64 a985bbd018 Méthodes guidées : propositions de l'IA à partir d'une idée de départ
- Champ « Ton idée de départ » dans l'assistant, avec « Proposer toute
  l'aventure » et « Proposer pour cette étape ».
- L'IA ne remplit que les champs vides, ou restés à leur valeur d'office et
  jamais modifiés : elle ne touche jamais à ce que le MJ a écrit, qui lui
  est transmis comme contexte. « Annuler la proposition » restaure l'état.
- Questions à choix : seule une valeur proposée est acceptée.
- Core : POST /api/campaigns/{id}/guided-assist (contexte de la campagne,
  filtrage des réponses, 502 si l'IA est indisponible).
- Brain : POST /generate/guided-answers, réponses dans la langue de
  l'interface.

Vérifié : brain (prompt, nettoyage), core (service, contrôleur), vitest
(champs libres, fusion, étape), parcours dans le navigateur (réponse
simulée, champ du MJ préservé, annulation, message d'erreur sans IA).
2026-10-18 00:37:00 +02:00
ietm64 1c9ac524db IA : la langue de l'interface suit les traitements de fond
La langue (en-tête X-User-Language, gardée dans un ThreadLocal) était perdue
dans l'exécuteur des flux SSE : imports de PDF (règles, campagne), ateliers
et chat partaient toujours en français, même avec l'interface en anglais.
Un TaskDecorator relaie désormais la langue du thread de la requête vers la
tâche de fond, puis la restaure (pas de fuite entre tâches du pool).

Vérifié : core (exécuteur applicationTaskExecutor en anglais, restauration).
2026-10-18 00:37:00 +02:00
ietm64 abf66733fe Paramètres : page vide dès qu'un appareil tablette est appairé
La date des appareils appairés était formatée avec `translate.currentLang`,
qui est un signal en ngx-translate 18 : converti en texte, il donnait une
locale invalide, et toLocaleString levait une RangeError qui interrompait
l'affichage de toute la page Paramètres (titres et libellés vides).
Utilise getCurrentLang() avec une locale explicite, et un repli sûr.

Vérifié : reproduit avec la version installée sur une base de test avec un
appareil appairé (RangeError en console, titres vides), puis corrigé (date
affichée, plus d'erreur). Web build + vitest + lint sans erreur.
2026-10-18 00:36:59 +02:00
ietm64 763219412b Mode plat : seulement quand l'arc et le chapitre uniques sont vides
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 38s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m4s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m52s
Une méthode guidée lancée dans une campagne vide crée un arc et un chapitre
qui portent le contenu écrit (titre, accroche, enjeux, vérité cachée ou plan
du méchant en notes MJ). Le mode plat les masquait : ce contenu devenait
introuvable derrière le nœud « Scènes ».

- Règle commune (flat-structure.ts) : un seul arc linéaire, un seul
  chapitre, et aucun contenu d'écriture dans l'un ou l'autre (les noms ne
  comptent pas, « Arc principal » / « Chapitre 1 » étant créés d'office).
- Appliquée au volet de gauche, à la page de la campagne (cartes d'arc
  visibles dès qu'il y a du contenu) et au livret PDF (en-têtes d'arc et de
  chapitre conservés ; un arc HUB n'est plus jamais mis à plat).

Vérifié : core clean verify (1289 tests, dont livret plat / non plat),
web build + 860 vitest (règle du mode plat), lint sans erreur.
À redéployer : core + web (aucune migration).
2026-10-17 23:53:23 +02:00
ietm64 cccf2b85db Correction test PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m25s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 58s
Build & Push Images / build (brain) (push) Successful in 1m51s
Build & Push Images / build (web) (push) Successful in 2m21s
Build & Push Images / build (core) (push) Successful in 4m16s
Build & Push Images / build-switcher (push) Successful in 16s
2026-10-17 19:17:37 +02:00
ietm64 6ae9238fee passage v1.5.0-beta
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 49s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 52s
Build & Push Images / build (brain) (push) Successful in 1m24s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m6s
Build & Push Images / build (web) (push) Successful in 2m36s
Build & Push Images / build (core) (push) Successful in 4m19s
Build & Push Images / build-switcher (push) Successful in 22s
2026-10-17 19:05:52 +02:00
ietm64 0ef1380265 Améliore la navigation et la mise en page des exports PDF
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 37s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m37s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 1m1s
- Ajoute les fils d’Ariane, les favoris et l’historique de navigation
- Étend la recherche aux arcs, chapitres, scènes et quêtes
- Regroupe les actions de campagne dans le menu Gérer
- Améliore la navigation au clavier et sur mobile
- Refonte de l’export A4 : deux colonnes, couverture illustrée et encadrés
- Ajoute des motifs décoratifs en pied de page et une variante pour l’impression
- Vérifie la pagination, les renvois et la confidentialité de l’édition joueurs
2026-10-17 19:05:15 +02:00
114 changed files with 3499 additions and 148 deletions
+80
View File
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
from app.application.llm_json import load_json_object
from app.application.llm_retry import generate_with_retry
from app.application.prompts import conversation_title as title_prompts
from app.application.prompts import guided_answers as guided_answers_prompts
from app.application.prompts import narrative_fields as narrative_fields_prompts
from app.application.prompts import scene_drafts as scene_drafts_prompts
from app.application.prompts import session_recap as session_recap_prompts
@@ -290,3 +291,82 @@ async def generate_session_recap(
if not recap:
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
return SessionRecapResponseDTO(recap=recap)
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
class GuidedOptionDTO(BaseModel):
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
value: str
label: str = Field(default="")
class GuidedFieldDTO(BaseModel):
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
key: str
label: str = Field(default="")
hint: str = Field(default="")
step: str = Field(default="")
options: list[GuidedOptionDTO] = Field(default_factory=list)
class GuidedAnswersRequestDTO(BaseModel):
method_name: str = Field(default="")
method_principle: str = Field(default="")
idea: str = Field(default="")
context: str = Field(default="")
fields: list[GuidedFieldDTO] = Field(default_factory=list)
existing: dict[str, str] = Field(default_factory=dict)
class GuidedAnswersResponseDTO(BaseModel):
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
answers: dict[str, str]
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
async def generate_guided_answers(
body: GuidedAnswersRequestDTO,
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
language: Annotated[str, Depends(get_user_language)],
) -> GuidedAnswersResponseDTO:
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
"""
by_key = {f.key: f for f in body.fields if f.key}
prompt = guided_answers_prompts.guided_answers_prompt(
body.method_name, body.method_principle, body.idea, body.context,
[f.model_dump() for f in body.fields], body.existing, language)
try:
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
except LLMProviderError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
parsed, _ = load_json_object(raw)
if not isinstance(parsed, dict):
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
out: dict[str, str] = {}
if not isinstance(raw, dict):
return out
for key, value in raw.items():
field = by_key.get(str(key))
if field is None or not isinstance(value, (str, int, float)):
continue
text = str(value).strip()
if not text:
continue
if field.options and text not in {o.value for o in field.options}:
continue
out[field.key] = text
return out
+7 -1
View File
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
sections: dict[str, str]
page_count: int
ocr_page_count: int
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
sections_by_language: dict[str, dict[str, str]] = {}
source_language: str = ""
@router.post("/import/rules", response_model=RulesImportResponseDTO)
@@ -70,6 +73,8 @@ async def import_rules(
sections=result.sections,
page_count=result.page_count,
ocr_page_count=result.ocr_page_count,
sections_by_language=result.sections_by_language,
source_language=result.source_language,
)
@@ -115,6 +120,7 @@ async def import_rules_stream(
@router.post("/import/campaign/stream")
async def import_campaign_stream(
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
language: Annotated[str, Depends(get_user_language)],
file: UploadFile = File(...),
) -> StreamingResponse:
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
@@ -131,7 +137,7 @@ async def import_campaign_stream(
yield sse_event("error", {"message": upload_error})
return
try:
async for ev in use_case.stream(content):
async for ev in use_case.stream(content, language=language):
event_type = ev.pop("type")
yield sse_event(event_type, ev)
except PdfExtractionError as exc:
+14 -12
View File
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
self._map_concurrency = max(1, map_concurrency)
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
doc = self._extractor.extract(pdf_bytes)
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
for start in range(0, total, self._map_concurrency):
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
results = await asyncio.gather(*(
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
for i, c in wave
))
for res in results:
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
npcs=merger.npcs(),
)
async def stream(self, pdf_bytes: bytes):
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
"""Variante streamée : yield des évènements d'avancement.
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
for start in range(0, total, self._map_concurrency):
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
gathered = asyncio.gather(
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
for i, c in wave),
return_exceptions=True,
)
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
# --- MAP : un morceau → sous-arbre ---------------------------------------
async def _map_chunk(
self, chunk: str, *, index: int, total: int, toc_block: str = ""
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
) -> dict:
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
return await self._extract_payload(
chunk, index=index, total=total, depth=0, toc_block=toc_block)
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
async def _extract_payload(
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
language: str = "fr",
) -> dict:
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
prompt = (
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
+ prompts.language_block(language)
+ toc_section
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
"Renvoie maintenant le JSON de l'arborescence."
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
f"Le modèle est trop lent sur le morceau {index + 1} : "
"re-découpage en 2 moitiés plus digestes…")
a = await self._extract_payload(
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
b = await self._extract_payload(
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
payload, truncated = self._parse_payload(raw, index=index)
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
f"Réponse du modèle coupée sur le morceau {index + 1} : "
"re-découpage en 2 moitiés plus digestes…")
a = await self._extract_payload(
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
b = await self._extract_payload(
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
if truncated:
logger.warning(
+63 -1
View File
@@ -26,6 +26,7 @@ from app.application.import_status import (
from app.application.llm_json import load_json_object, looks_like_truncated_json
from app.application.llm_retry import generate_with_retry
from app.application.prompts import import_rules as prompts
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
from app.application.streaming import with_heartbeat
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
}
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
_DETECT_CHARS = 20_000
class _SectionMerger:
"""Fusionne les sections issues des différents morceaux, ordre préservé.
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
merger = _SectionMerger()
for i, chunk in enumerate(chunks):
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
sections = merger.result()
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
by_language = {source: sections}
translator = RulesTranslator(self._llm)
for target in other_languages(source):
try:
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
by_language[target] = {
titles.get(title, title): await translator.translate_content(content, source, target)
for title, content in sections.items()
}
except LLMProviderError as exc:
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
return RulesImportResult(
sections=merger.result(),
sections=sections,
page_count=doc.page_count,
ocr_page_count=doc.ocr_page_count,
sections_by_language=by_language,
source_language=source,
)
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
"de contexte (num_ctx) ou essayez un autre modèle."}
return
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
# langue de l'application. Un échec de traduction n'annule pas l'import.
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
by_language: dict[str, dict[str, str]] = {source: sections}
for target in other_languages(source):
try:
async for ev in self._translate_events(sections, source, target):
if ev["type"] == "_translated":
by_language[target] = ev["sections"]
else:
yield ev
except LLMProviderError as exc:
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
yield {"type": "status",
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
yield {
"type": "done",
"sections": sections,
"sections_by_language": by_language,
"source_language": source,
"page_count": doc.page_count,
"ocr_page_count": doc.ocr_page_count,
"skipped": skipped,
}
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
"""Évènements d'avancement de la traduction ; le dernier est
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
translator = RulesTranslator(self._llm)
titles = list(sections)
total = len(titles)
label = language_name(target)
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
mapping: dict[str, str] = {}
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
if kind == "heartbeat":
yield {"type": "heartbeat", "current": 0, "total": total}
elif kind == "result":
mapping = unique_titles(payload)
out: dict[str, str] = {}
for i, title in enumerate(titles):
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
"current": i + 1, "total": total}
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
if kind == "heartbeat":
yield {"type": "heartbeat", "current": i + 1, "total": total}
elif kind == "result":
out[mapping.get(title, title)] = payload
yield {"type": "_translated", "sections": out}
# --- MAP : un morceau → sections -----------------------------------------
async def _map_chunk(self, chunk: str, *, index: int, total: int,
+3
View File
@@ -113,5 +113,8 @@ async def generate_with_retry(
+ str(exc)[:160]
)
await asyncio.sleep(wait)
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
# l'essai suivant est lancé (il peut durer plusieurs minutes).
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
assert last_error is not None
raise last_error
@@ -0,0 +1,71 @@
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
Plan du méchant…).
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
dans l'assistant manuel) et ses questions (clé, libellé,
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
"""
from app.core.language import language_name
def _field_line(field: dict) -> str:
key = str(field.get("key") or "").strip()
label = str(field.get("label") or key).strip()
hint = str(field.get("hint") or "").strip()
step = str(field.get("step") or "").strip()
line = f'- "{key}"'
if step:
line += f" [{step}]"
line += f" : {label}"
if hint:
line += f" — {hint}"
options = field.get("options") or []
if options:
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
line += f" — UNE valeur parmi : {values}"
return line
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
fields: list[dict], existing: dict[str, str], language: str) -> str:
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
existing_lines = "\n".join(
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
existing_block = (
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
f"{existing_lines}\n" if existing_lines else ""
)
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
guide = method_principle.strip() if method_principle else ""
guide_block = (
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
f"{guide}\n" if guide else ""
)
return (
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
f"{guide_block}\n"
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
f"{context_block}{existing_block}\n"
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
f"{fields_list}\n\n"
"Règles IMPÉRATIVES :\n"
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
"valeurs proposées.\n"
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
"pas le sujet.\n"
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
"les étapes.\n"
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
"(noms, lieux, motivations précises ; pas de généralités).\n"
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
f"- Rédige les réponses en {language_name(language)}.\n"
"Renvoie maintenant le JSON."
)
@@ -1,7 +1,29 @@
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
from app.core.language import language_name
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
DEFAULT_ARC_NAME = "Aventure principale"
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
def default_arc_name(language: str) -> str:
"""Nom de l'arc unique, dans la langue de l'interface."""
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
def language_block(language: str) -> str:
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
name = language_name(language)
return (
"\n\nLANGUE DE SORTIE :\n"
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
"fidèlement, sans les résumer davantage.\n"
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
)
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
+136
View File
@@ -0,0 +1,136 @@
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
pour rester sous les limites de sortie des modèles.
"""
from __future__ import annotations
import re
from app.application.llm_json import load_json_object
from app.application.llm_retry import generate_with_retry
from app.core.language import language_name
from app.domain.ports import LLMProvider
LANGUAGES = ("fr", "en")
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
CHUNK_CHARS = 6000
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
def detect_language(text: str, default: str = "fr") -> str:
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
fr = sum(1 for w in words if w in _FR_WORDS)
en = sum(1 for w in words if w in _EN_WORDS)
if fr == en:
return default if default in LANGUAGES else "fr"
return "fr" if fr > en else "en"
def other_languages(source: str) -> list[str]:
return [lang for lang in LANGUAGES if lang != source]
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
if len(text) <= max_chars:
return [text]
chunks: list[str] = []
current = ""
for para in re.split(r"(\n\s*\n)", text):
if len(current) + len(para) <= max_chars:
current += para
continue
if current.strip():
chunks.append(current)
current = ""
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
cut = para.rfind("\n", 0, max_chars)
cut = cut if cut > 0 else max_chars
chunks.append(para[:cut])
para = para[cut:]
current = para
if current.strip():
chunks.append(current)
return chunks
def content_prompt(text: str, source: str, target: str) -> str:
return (
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
f"vers la langue « {language_name(target)} ».\n\n"
"Règles IMPÉRATIVES :\n"
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
"objets nommés.\n"
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
"Extrait :\n"
f"{text}"
)
def titles_prompt(titles: list[str], source: str, target: str) -> str:
listing = "\n".join(f"- {t}" for t in titles)
return (
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
"Garde les noms propres tels quels.\n"
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
f"{listing}"
)
class RulesTranslator:
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
def __init__(self, llm: LLMProvider) -> None:
self._llm = llm
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
if not titles:
return {}
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
output_format="json", temperature=0.2)
parsed, _ = load_json_object(raw)
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
out: dict[str, str] = {}
for title in titles:
value = mapping.get(title) if isinstance(mapping, dict) else None
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
return out
async def translate_content(self, text: str, source: str, target: str) -> str:
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
if not text or not text.strip():
return text
parts = []
for chunk in split_markdown(text):
if not chunk.strip():
parts.append(chunk)
continue
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
temperature=0.2)
parts.append(translated.strip())
return "\n\n".join(p for p in parts if p.strip())
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
seen: dict[str, int] = {}
out: dict[str, str] = {}
for original, translated in titles.items():
count = seen.get(translated, 0)
seen[translated] = count + 1
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
return out
+4
View File
@@ -367,6 +367,10 @@ class RulesImportResult:
sections: dict[str, str]
page_count: int
ocr_page_count: int
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
source_language: str = ""
def to_markdown(self) -> str:
"""Assemble les sections en un markdown monolithique (## titre + contenu).
+1 -1
View File
@@ -26,7 +26,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
app = FastAPI(
title="LoreMind Brain",
description="Backend IA pour la génération de contenu narratif.",
version="1.4.0-beta",
version="1.6.1-beta",
)
logger = logging.getLogger(__name__)
+62
View File
@@ -0,0 +1,62 @@
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
from __future__ import annotations
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
from app.application.prompts.guided_answers import guided_answers_prompt
def _fields() -> dict[str, GuidedFieldDTO]:
return {
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
}
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
prompt = guided_answers_prompt(
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
{"truth": "Le notaire est coupable", "empty": " "}, "en")
assert "Une tour qui se rallume" in prompt
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
assert "Le notaire est coupable" in prompt
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
assert "Campagne : Valfroide" in prompt
assert "anglais" in prompt
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
guide = ("Cinq temps dans un même lieu.\n\n"
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
"- Salle 3 : le revers : les choses se compliquent.")
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
assert "telle que le MJ la suit à la main" in p
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
assert "rôle de SON étape" in p
assert "Idée de départ du MJ : Une crypte" in p
def test_prompt_without_idea_asks_for_an_original_adventure():
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
assert "propose une aventure originale" in prompt
assert "français" in prompt
def test_clean_keeps_requested_keys_and_valid_choices_only():
out = _clean_guided_answers({
"title": " L'héritage empoisonné ",
"node1.nature": "npc",
"unknown": "ignorée",
"empty": "",
}, _fields())
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
def test_clean_rejects_an_invalid_choice_and_non_text_values():
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
assert out == {}
assert _clean_guided_answers("pas un objet", _fields()) == {}
+52
View File
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
monkeypatch.setattr("app.application.import_rules.chunk_text",
lambda *a, **k: ["AAA premier", "BBB second"])
llm = ContentLLM([
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
("Traduis cet extrait", "spells"),
("AAA premier", LLMProviderError("HTTP 503 saturé")),
("BBB second", '{"Magie":"sorts"}'),
])
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
assert done["type"] == "done"
assert done["sections"] == {"Magie": "sorts"}
assert done["skipped"] == 1
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
assert done["source_language"] == "fr"
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
llm = ContentLLM([
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
])
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
events = [e async for e in uc.stream(b"pdf")]
done = events[-1]
assert done["type"] == "done"
assert done["source_language"] == "en"
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
events = [e async for e in uc.stream(b"pdf")]
assert events[-1]["type"] == "error"
class _RecordingLLM(ScriptedLLM):
"""ScriptedLLM qui garde les prompts reçus."""
def __init__(self, responses: list) -> None:
super().__init__(responses)
self.prompts: list[str] = []
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
self.prompts.append(prompt)
return await super().generate(prompt, output_format=output_format, temperature=temperature)
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
llm = _RecordingLLM([_TREE])
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
events = [e async for e in uc.stream(b"pdf", language="en")]
assert events[-1]["type"] == "done"
prompt = llm.prompts[0]
assert "LANGUE DE SORTIE" in prompt
assert "en anglais" in prompt
assert "noms propres" in prompt
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
async def test_campaign_import_defaults_to_french():
llm = _RecordingLLM([_TREE])
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
assert "en français" in llm.prompts[0]
assert '"Aventure principale"' in llm.prompts[0]
+18
View File
@@ -110,3 +110,21 @@ async def test_rate_limit_respects_suggested_retry_after(slept):
assert await generate_with_retry(llm, "p") == "ok"
# min(8 + 2, 60) = 10
assert slept == [10.0]
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
import asyncio
from app.application.import_status import reset_status_queue, set_status_queue
queue: asyncio.Queue = asyncio.Queue()
token = set_status_queue(queue)
try:
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
assert await generate_with_retry(llm, "p") == "ok"
finally:
reset_status_queue(token)
messages = [queue.get_nowait() for _ in range(queue.qsize())]
assert "nouvel essai dans 3s" in messages[0]
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
+60
View File
@@ -0,0 +1,60 @@
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
from __future__ import annotations
from app.application.rules_translation import (
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
)
class EchoLLM:
"""Traduit « en majuscules » et garde trace des prompts reçus."""
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
self.prompts: list[str] = []
self._titles_json = titles_json
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
self.prompts.append(prompt)
if "Traduis ces titres" in prompt:
return self._titles_json
return prompt.split("Extrait :\n", 1)[1].upper()
def test_detect_language():
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
assert detect_language("", default="en") == "en"
assert other_languages("fr") == ["en"]
assert other_languages("en") == ["fr"]
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
assert split_markdown("court") == ["court"]
text = "\n\n".join(["a" * 40] * 10)
chunks = split_markdown(text, max_chars=100)
assert all(len(c) <= 100 for c in chunks)
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
def test_split_markdown_cuts_a_giant_paragraph():
chunks = split_markdown("x" * 250, max_chars=100)
assert [len(c) for c in chunks] == [100, 100, 50]
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
llm = EchoLLM()
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
assert out == "## COMBAT\n\nCHAQUE ROUND."
assert "noms propres" in llm.prompts[0]
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
async def test_translate_titles_falls_back_to_the_original_title():
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
assert out == {"Combat": "Fighting", "Magie": "Magie"}
def test_unique_titles_avoids_collisions():
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
+1 -1
View File
@@ -14,7 +14,7 @@
<groupId>com.loremind</groupId>
<artifactId>loremind-core</artifactId>
<version>1.4.0-beta</version>
<version>1.6.1-beta</version>
<name>LoreMind Core</name>
<description>Backend Core - Architecture Hexagonale</description>
@@ -0,0 +1,20 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CampaignContentSearchService {
private final CampaignContentSearchRepository repository;
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
this.repository = repository;
}
public List<CampaignContentHit> search(String query) {
String value = query == null ? "" : query.strip();
return value.length() < 2 ? List.of() : repository.searchByName(value);
}
}
@@ -0,0 +1,86 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
* front remplit les champs vides et le MJ relit, corrige ou relance.
*
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
* n'accepte qu'une des valeurs proposées.</p>
*/
@Service
public class GuidedAssistService {
static final int MAX_QUESTIONS = 80;
static final int MAX_TEXT = 4_000;
private final GuidedMethodAssistant assistant;
private final CampaignContextFormatter contextFormatter;
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
this.assistant = assistant;
this.contextFormatter = contextFormatter;
}
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
List<Question> questions, Map<String, String> existing) {
List<Question> valid = questions == null ? List.of() : questions.stream()
.filter(Objects::nonNull)
.filter(q -> q.key() != null && !q.key().isBlank())
.limit(MAX_QUESTIONS)
.toList();
if (valid.isEmpty()) {
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
}
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
contextFormatter.format(campaignId), valid, capAll(existing));
return keepValid(answers, valid);
}
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
Map<String, String> out = new LinkedHashMap<>();
if (answers == null) return out;
Map<String, Question> byKey = questions.stream()
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
for (Map.Entry<String, String> e : answers.entrySet()) {
Question q = byKey.get(e.getKey());
String value = e.getValue() == null ? "" : e.getValue().trim();
if (q == null || value.isEmpty()) continue;
if (q.options() != null && !q.options().isEmpty()) {
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
if (!allowed.contains(value)) continue;
}
out.put(q.key(), cap(value));
}
return out;
}
private static Map<String, String> capAll(Map<String, String> existing) {
Map<String, String> out = new LinkedHashMap<>();
if (existing == null) return out;
existing.forEach((k, v) -> {
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
});
return out;
}
private static String cap(String s) {
if (s == null) return "";
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
}
}
@@ -1,6 +1,7 @@
package com.loremind.application.gamesystemcontext;
import com.loremind.domain.gamesystemcontext.GameSystem;
import com.loremind.domain.shared.ports.CurrentLanguage;
import com.loremind.domain.gamesystemcontext.GenerationIntent;
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
import com.loremind.domain.generationcontext.GameSystemContext;
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
private final GameSystemRepository gameSystemRepository;
private final CurrentLanguage currentLanguage;
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
this.gameSystemRepository = gameSystemRepository;
this.currentLanguage = currentLanguage;
}
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
}
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
// Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
Map<String, String> filtered = filterByIntent(allSections, intent);
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
}
@@ -59,6 +59,7 @@ public class GameSystemService {
String name,
String description,
String rulesMarkdown,
String rulesMarkdownEn,
List<TemplateField> characterTemplate,
List<TemplateField> npcTemplate,
List<TemplateField> enemyTemplate,
@@ -72,6 +73,7 @@ public class GameSystemService {
.name(data.name())
.description(data.description())
.rulesMarkdown(data.rulesMarkdown())
.rulesMarkdownEn(data.rulesMarkdownEn())
.foundryActorType(normalize(data.foundryActorType()))
.author(normalize(data.author()))
.isPublic(data.isPublic())
@@ -96,6 +98,7 @@ public class GameSystemService {
existing.setName(data.name());
existing.setDescription(data.description());
existing.setRulesMarkdown(data.rulesMarkdown());
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
existing.replaceCharacterTemplate(data.characterTemplate());
existing.replaceNpcTemplate(data.npcTemplate());
existing.replaceEnemyTemplate(data.enemyTemplate());
@@ -0,0 +1,6 @@
package com.loremind.domain.campaigncontext;
/** Lightweight search projection with the ancestors needed to open a result. */
public record CampaignContentHit(String kind, String id, String name,
String campaignId, String campaignName, String arcId, String arcName,
String chapterId, String chapterName) {}
@@ -0,0 +1,8 @@
package com.loremind.domain.campaigncontext.ports;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import java.util.List;
public interface CampaignContentSearchRepository {
List<CampaignContentHit> searchByName(String query);
}
@@ -0,0 +1,38 @@
package com.loremind.domain.campaigncontext.ports;
import java.util.List;
import java.util.Map;
/**
* Port de sortie (Mentor d'écriture) : demande à l'IA de proposer des réponses aux
* questions d'une méthode guidée à partir de l'idée de départ du MJ. Implémenté par un
* client du Brain. One-shot ; rien n'est enregistré (le MJ relit et corrige dans l'assistant).
*/
public interface GuidedMethodAssistant {
/** Choix possible d'une question à choix : valeur technique + libellé lisible. */
record Choice(String value, String label) {}
/**
* Une question de la méthode, décrite par le front (libellés dans la langue du MJ).
*
* @param key clé de réponse (ex. {@code node1.name})
* @param label libellé de la question
* @param hint aide (exemple de réponse attendue), optionnelle
* @param step titre de l'étape, optionnel
* @param options choix possibles (vide pour une question libre)
*/
record Question(String key, String label, String hint, String step, List<Choice> options) {}
/**
* @param methodName nom de la méthode (« Enquête en nœuds »…)
* @param principle principe de la méthode, suivi du rôle de chaque étape (comme dans l'assistant manuel)
* @param idea idée de départ du MJ (peut être vide)
* @param context contexte de la campagne (nom, description, système)
* @param questions questions auxquelles répondre
* @param existing réponses déjà écrites par le MJ (à respecter)
* @return une réponse proposée par clé (clés demandées uniquement)
*/
Map<String, String> answer(String methodName, String principle, String idea, String context,
List<Question> questions, Map<String, String> existing);
}
@@ -35,6 +35,9 @@ public class GameSystem {
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
private String rulesMarkdown;
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
private String rulesMarkdownEn;
/**
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
@@ -161,4 +164,15 @@ public class GameSystem {
if (a == null || b == null) return a == null && b == null;
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
}
/**
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
*/
public String rulesFor(String language) {
boolean english = "en".equalsIgnoreCase(language);
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
return preferred != null && !preferred.isBlank() ? preferred : fallback;
}
}
@@ -16,5 +16,14 @@ import java.util.Map;
public record RulesImportResult(
Map<String, String> sections,
int pageCount,
int ocrPageCount) {
int ocrPageCount,
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
Map<String, Map<String, String>> sectionsByLanguage,
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
String sourceLanguage) {
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
this(sections, pageCount, ocrPageCount, Map.of(), null);
}
}
@@ -0,0 +1,11 @@
package com.loremind.domain.shared.ports;
/**
* Port : langue de l'interface de l'utilisateur courant ({@code fr} ou {@code en}), pour les
* contenus qui existent en deux langues (règles d'un système de jeu). Implémenté côté web.
*/
public interface CurrentLanguage {
/** Code court de la langue courante ({@code fr} par défaut). */
String get();
}
@@ -53,7 +53,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
@Value("${brain.base-url}") String baseUrl,
@Value("${brain.import-timeout-seconds:600}") long importTimeoutSeconds,
@Value("${brain.paths.import-campaign:/import/campaign/stream}") String importCampaignStreamPath) {
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
this.sse = new BrainSseImportSupport(objectMapper);
this.importTimeoutSeconds = importTimeoutSeconds;
this.importCampaignStreamPath = importCampaignStreamPath;
@@ -0,0 +1,102 @@
package com.loremind.infrastructure.ai;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Adapter de sortie : propositions de réponses aux méthodes guidées via le Brain
* ({@code POST /generate/guided-answers}, one-shot). La langue de l'interface est relayée par
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
*/
@Component
public class BrainGuidedAnswersClient implements GuidedMethodAssistant {
private static final String PATH = "/generate/guided-answers";
private final RestTemplate restTemplate;
private final String baseUrl;
public BrainGuidedAnswersClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
this.restTemplate = restTemplate;
this.baseUrl = baseUrl;
}
@Override
public Map<String, String> answer(String methodName, String principle, String idea, String context,
List<Question> questions, Map<String, String> existing) {
Map<String, Object> req = new LinkedHashMap<>();
req.put("method_name", nz(methodName));
req.put("method_principle", nz(principle));
req.put("idea", nz(idea));
req.put("context", nz(context));
req.put("fields", toPayload(questions));
req.put("existing", existing == null ? Map.of() : existing);
return parse(call(req));
}
static List<Map<String, Object>> toPayload(List<Question> questions) {
List<Map<String, Object>> out = new ArrayList<>();
for (Question q : questions) {
Map<String, Object> f = new LinkedHashMap<>();
f.put("key", q.key());
f.put("label", nz(q.label()).isEmpty() ? q.key() : q.label());
f.put("hint", nz(q.hint()));
f.put("step", nz(q.step()));
List<Map<String, String>> options = new ArrayList<>();
if (q.options() != null) {
for (Choice c : q.options()) {
if (c != null && c.value() != null) options.add(Map.of("value", c.value(), "label", nz(c.label())));
}
}
f.put("options", options);
out.add(f);
}
return out;
}
@SuppressWarnings("unchecked")
private Map<String, Object> call(Map<String, Object> req) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> resp;
try {
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
} catch (ResourceAccessException e) {
throw new NarrativeAssistException("Le Brain est injoignable (timeout ou arrêté).", e);
} catch (RestClientResponseException e) {
throw new NarrativeAssistException(
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
} catch (Exception e) {
throw new NarrativeAssistException("Erreur inattendue lors de l'appel au Brain.", e);
}
if (resp == null) throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
return resp;
}
private static Map<String, String> parse(Map<String, Object> resp) {
Map<String, String> out = new LinkedHashMap<>();
if (resp.get("answers") instanceof Map<?, ?> m) {
m.forEach((k, v) -> {
if (k != null && v != null) out.put(k.toString(), v.toString());
});
}
return out;
}
private static String nz(String s) {
return s == null ? "" : s;
}
}
@@ -70,7 +70,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
@Value("${brain.paths.import-rules:/import/rules}") String importRulesPath,
@Value("${brain.paths.import-rules-stream:/import/rules/stream}") String importRulesStreamPath) {
this.restTemplate = restTemplate;
this.webClient = webClientBuilder.baseUrl(baseUrl).build();
this.webClient = BrainSseImportSupport.importWebClient(webClientBuilder, baseUrl);
this.sse = new BrainSseImportSupport(objectMapper);
this.baseUrl = baseUrl;
this.importTimeoutSeconds = importTimeoutSeconds;
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
return new RulesImportResult(
Map.copyOf(response.getSections()),
response.getPageCount(),
response.getOcrPageCount());
response.getOcrPageCount(),
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
response.getSourceLanguage());
} catch (ResourceAccessException e) {
throw new RulesImportException(
"Le Brain est injoignable (timeout ou service arrêté).", e);
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
callbacks.onDone().accept(new RulesImportResult(
toStringMap(node.path("sections")),
node.path("page_count").asInt(),
node.path("ocr_page_count").asInt()));
node.path("ocr_page_count").asInt(),
toLanguageMap(node.path("sections_by_language")),
node.path("source_language").asText(null)));
}
}
// --- Helpers -------------------------------------------------------------
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
if (node != null && node.isObject()) {
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
}
return out;
}
private List<String> toStringList(JsonNode array) {
List<String> out = new ArrayList<>();
if (array != null && array.isArray()) {
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
@JsonProperty("ocr_page_count")
private int ocrPageCount;
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
@JsonProperty("sections_by_language")
private Map<String, Map<String, String>> sectionsByLanguage;
@JsonProperty("source_language")
private String sourceLanguage;
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import java.time.Duration;
@@ -25,6 +26,21 @@ final class BrainSseImportSupport {
/** Champ JSON standard des events SSE du Brain portant un message lisible. */
private static final String MESSAGE_FIELD = "message";
/**
* Taille max d'UN évènement SSE. L'évènement {@code done} porte tout le résultat de
* l'import (règles d'un livre entier, en deux langues ; arbre complet d'une campagne) :
* la limite par défaut de WebClient (256 Ko) faisait échouer l'import au tout dernier
* moment (DataBufferLimitException), après des minutes d'analyse.
*/
static final int MAX_EVENT_BYTES = 64 * 1024 * 1024;
/** WebClient d'import : évènements volumineux acceptés (voir {@link #MAX_EVENT_BYTES}). */
static WebClient importWebClient(WebClient.Builder builder, String baseUrl) {
return builder.baseUrl(baseUrl)
.codecs(c -> c.defaultCodecs().maxInMemorySize(MAX_EVENT_BYTES))
.build();
}
private final ObjectMapper objectMapper;
BrainSseImportSupport(ObjectMapper objectMapper) {
@@ -37,6 +37,9 @@ public class GameSystemJpaEntity {
@Column(name = "rules_markdown", columnDefinition = "TEXT")
private String rulesMarkdown;
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
private String rulesMarkdownEn;
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
@Convert(converter = TemplateFieldListJsonConverter.class)
@Column(name = "character_template", columnDefinition = "TEXT")
@@ -0,0 +1,57 @@
package com.loremind.infrastructure.persistence.postgres;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/** One bounded query; never loads complete scenes or one tree per campaign. */
@Repository
public class PostgresCampaignContentSearchRepository implements CampaignContentSearchRepository {
private final NamedParameterJdbcTemplate jdbc;
public PostgresCampaignContentSearchRepository(NamedParameterJdbcTemplate jdbc) {
this.jdbc = jdbc;
}
private static final String SQL = """
SELECT * FROM (
SELECT 'arc' AS kind, a.id, a.name, c.id AS campaign_id, c.name AS campaign_name,
a.id AS arc_id, a.name AS arc_name, CAST(NULL AS BIGINT) AS chapter_id,
CAST(NULL AS VARCHAR) AS chapter_name
FROM arcs a JOIN campaigns c ON c.id = a.campaign_id
WHERE a.type <> 'SYSTEM' AND LOWER(a.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'chapter', ch.id, ch.name, c.id, c.name, a.id, a.name, ch.id, ch.name
FROM chapters ch JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
WHERE a.type <> 'SYSTEM' AND LOWER(ch.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'scene', s.id, s.name, c.id, c.name, a.id,
CASE WHEN a.type = 'SYSTEM' THEN NULL ELSE a.name END, ch.id, ch.name
FROM scenes s JOIN chapters ch ON ch.id = s.chapter_id
JOIN arcs a ON a.id = ch.arc_id JOIN campaigns c ON c.id = a.campaign_id
WHERE LOWER(s.name) LIKE :query ESCAPE '!'
UNION ALL
SELECT 'quest', q.id, q.name, c.id, c.name, a.id, a.name, NULL, NULL
FROM quests q JOIN campaigns c ON c.id = q.campaign_id
LEFT JOIN arcs a ON a.id = q.arc_id AND a.campaign_id = c.id
WHERE LOWER(q.name) LIKE :query ESCAPE '!'
) hits
ORDER BY LOWER(name), campaign_id, kind, id
LIMIT 80
""";
@Override
public List<CampaignContentHit> searchByName(String query) {
String pattern = "%" + query.toLowerCase(Locale.ROOT)
.replace("!", "!!").replace("%", "!%").replace("_", "!_") + "%";
return jdbc.query(SQL, Map.of("query", pattern), (rs, row) -> new CampaignContentHit(
rs.getString("kind"), rs.getString("id"), rs.getString("name"),
rs.getString("campaign_id"), rs.getString("campaign_name"),
rs.getString("arc_id"), rs.getString("arc_name"),
rs.getString("chapter_id"), rs.getString("chapter_name")));
}
}
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
.name(e.getName())
.description(e.getDescription())
.rulesMarkdown(e.getRulesMarkdown())
.rulesMarkdownEn(e.getRulesMarkdownEn())
.characterTemplate(e.getCharacterTemplate() != null
? new java.util.ArrayList<>(e.getCharacterTemplate())
: new java.util.ArrayList<>())
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
.name(g.getName())
.description(g.getDescription())
.rulesMarkdown(g.getRulesMarkdown())
.rulesMarkdownEn(g.getRulesMarkdownEn())
.characterTemplate(g.getCharacterTemplate() != null
? new java.util.ArrayList<>(g.getCharacterTemplate())
: new java.util.ArrayList<>())
@@ -577,7 +577,8 @@ public class ExportService {
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic());
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
e.getRulesMarkdownEn());
}
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
@@ -49,6 +49,7 @@ class LoreContentInserter {
e.setName(d.name());
e.setDescription(d.description());
e.setRulesMarkdown(d.rulesMarkdown());
e.setRulesMarkdownEn(d.rulesMarkdownEn());
e.setCharacterTemplate(d.characterTemplate());
e.setNpcTemplate(d.npcTemplate());
e.setEnemyTemplate(d.enemyTemplate());
@@ -77,7 +77,9 @@ public record ContentExport(
List<TemplateField> enemyTemplate,
String foundryActorType,
String author,
boolean isPublic
boolean isPublic,
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
String rulesMarkdownEn
) {}
public record LoreDto(
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
import com.loremind.domain.campaigncontext.quest.NodeType;
import com.loremind.domain.campaigncontext.quest.Prerequisite;
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
import com.loremind.domain.campaigncontext.structure.ArcType;
import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.RoomBranch;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
@@ -116,6 +117,7 @@ public class PdfExportService {
/** Construit le PDF de la campagne selon les options. @throws NoSuchElementException si absente. */
public byte[] export(String campaignId, PdfExportOptions options) {
options = options != null ? options : PdfExportOptions.defaults();
String xhtml = xhtml(campaignId, options);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -124,7 +126,12 @@ public class PdfExportService {
registerFonts(builder);
builder.withHtmlContent(xhtml, null);
builder.toStream(out);
builder.run();
try (var renderer = builder.buildPdfRenderer(); var document = renderer.getPdfDocument()) {
renderer.layout();
renderer.createPDFWithoutClosing();
PdfPageOrnaments.draw(document, options);
document.save(out);
}
return out.toByteArray();
} catch (IOException e) {
throw new UncheckedIOException("Echec de la generation du PDF", e);
@@ -194,6 +201,7 @@ public class PdfExportService {
int enemies;
int randomTables;
int lorePages;
private boolean columns;
Ctx(PdfExportOptions opt) {
this.opt = opt;
@@ -205,7 +213,19 @@ public class PdfExportService {
}
double contentWidthCm() {
return opt.format().contentWidthCm();
double width = opt.format().contentWidthCm();
return columns ? (width - 0.8) / 2 : width;
}
/** Le petit format garde une colonne ; les tables et cartes restent hors du flux. */
void beginColumns() {
columns = opt.format() == PdfExportOptions.PageFormat.A4;
if (columns) body.append("<div class=\"editorial-flow\">");
}
void endColumns() {
if (columns) body.append(DIV_CLOSE);
columns = false;
}
/** Champ reserve au MJ : absent de la version joueurs. */
@@ -317,6 +337,10 @@ public class PdfExportService {
private void cover(StringBuilder b, Ctx ctx, CampaignJpaEntity c, CampaignPublication pub) {
boolean published = pub.hasContent();
PdfImage art = imageEncoder.image(pub.coverImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
if (art != null && ctx.opt.format() == PdfExportOptions.PageFormat.A4 && !ctx.opt.printFriendly()) {
illustratedCover(b, ctx, c, pub, art);
return;
}
b.append("<div class=\"cover").append(art != null ? " has-art" : "").append("\">");
String kicker = coverKicker(ctx, pub);
if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE);
@@ -350,6 +374,32 @@ public class PdfExportService {
b.append(DIV_CLOSE);
}
/** Couverture A4 illustree : image a fond perdu et cartouche contraste, sans etirer l'image. */
private static void illustratedCover(StringBuilder b, Ctx ctx, CampaignJpaEntity c,
CampaignPublication pub, PdfImage art) {
double scale = Math.max(21.0 / art.w(), 29.7 / art.h());
double width = art.w() * scale, height = art.h() * scale;
b.append("<div class=\"cover cover-illustrated\"><img class=\"cover-background\" style=\"width:")
.append(cm(width)).append(";height:").append(cm(height))
.append(";left:").append(cm((21.0 - width) / 2))
.append(";top:").append(cm((29.7 - height) / 2))
.append("\" src=\"").append(art.uri()).append("\"/>")
.append("<div class=\"cover-caption\">");
String kicker = coverKicker(ctx, pub);
if (kicker != null) b.append("<div class=\"cover-kicker\">").append(esc(kicker)).append(DIV_CLOSE);
int titleSize = c.getName().length() > 100 ? 20 : c.getName().length() > 60 ? 26 : 32;
b.append("<h1 class=\"cover-title\" style=\"font-size:").append(titleSize).append("pt\">")
.append(esc(c.getName())).append("</h1>");
if (notBlank(pub.subtitle())) b.append("<div class=\"cover-subtitle\">").append(esc(pub.subtitle())).append(DIV_CLOSE);
b.append("<div class=\"cover-rule\"></div>");
String meta = technicalLine(pub);
if (!meta.isEmpty()) b.append("<div class=\"cover-meta\">").append(esc(meta)).append(DIV_CLOSE);
if (!ctx.gm) b.append("<div class=\"cover-edition\">Édition joueurs</div>");
if (notBlank(pub.author())) b.append("<div class=\"cover-author\">").append(esc(pub.author())).append(DIV_CLOSE);
if (notBlank(pub.version())) b.append("<div class=\"cover-version\">Version ").append(esc(pub.version())).append(DIV_CLOSE);
b.append("</div></div>");
}
/** Surtitre : le systeme de jeu s'il est renseigne ; sinon l'intitule historique du livret. */
private static String coverKicker(Ctx ctx, CampaignPublication pub) {
if (notBlank(pub.system())) return pub.system();
@@ -399,14 +449,17 @@ public class PdfExportService {
ctx.addToc(0, "Introduction", "part-intro");
ctx.bookmarks.append(bookmark("Introduction", "part-intro", ""));
ctx.beginColumns();
technicalTable(b, pub);
String pitch = notBlank(pub.pitch()) ? pub.pitch() : c.getDescription();
introSection(b, "L'aventure en bref", pitch);
box(b, "warning", "Avertissements de contenu", pub.contentWarnings());
if (!ctx.gm) return;
introSection(b, "Contexte pour le MJ", pub.gmBackground());
introSection(b, "Accroches", pub.hooks());
if (ctx.opt.includes(Section.NARRATIVE)) introSection(b, "Structure de l'aventure", structureOutline(st));
if (ctx.gm) {
introSection(b, "Contexte pour le MJ", pub.gmBackground());
introSection(b, "Accroches", pub.hooks());
if (ctx.opt.includes(Section.NARRATIVE)) introSection(b, "Structure de l'aventure", structureOutline(st));
}
ctx.endColumns();
}
/** Tableau « Système / Niveaux / Joueurs / Durée » de la page technique. */
@@ -488,11 +541,12 @@ public class PdfExportService {
List<ArcJpaEntity> arcs = st.visibleArcs;
if (arcs.isEmpty()) return;
// Mode plat (miroir de l'UI Niveau 0) : 1 arc d'UN SEUL chapitre → on masque les
// niveaux Arc/Chapitre et on présente les scènes À PLAT (cohérent avec la sidebar).
if (arcs.size() == 1) {
// Mode plat (miroir de l'UI Niveau 0) : 1 arc linéaire d'UN SEUL chapitre, tous deux
// VIDES (créés d'office) → on masque les niveaux Arc/Chapitre et on présente les
// scènes À PLAT. Un arc ou un chapitre écrit (méthode guidée…) garde ses en-têtes.
if (arcs.size() == 1 && arcs.get(0).getType() != ArcType.HUB) {
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
if (only.size() == 1) {
if (only.size() == 1 && isBare(arcs.get(0)) && isBare(only.get(0))) {
narrativeFlat(ctx, st, arcs.get(0), only.get(0));
return;
}
@@ -502,9 +556,33 @@ public class PdfExportService {
ctx.addToc(0, "Structure narrative", ANCHOR_PART_NARRATIVE);
narrativeBookmarks(ctx, st, arcs);
ctx.beginColumns();
for (ArcJpaEntity arc : arcs) {
arcSection(ctx, st, arc);
}
ctx.endColumns();
}
/** Aucun contenu d'ecriture dans l'arc (son nom ne compte pas : « Arc principal » est cree d'office). */
static boolean isBare(ArcJpaEntity arc) {
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
&& isEmpty(arc.getIllustrationImageIds());
}
/** Aucun contenu d'ecriture dans le chapitre (son nom ne compte pas : « Chapitre 1 » est cree d'office). */
static boolean isBare(ChapterJpaEntity ch) {
return allBlank(ch.getDescription(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes())
&& isEmpty(ch.getIllustrationImageIds());
}
private static boolean allBlank(String... values) {
for (String v : values) if (notBlank(v)) return false;
return true;
}
private static boolean isEmpty(List<String> list) {
return list == null || list.isEmpty();
}
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
@@ -606,6 +684,7 @@ public class PdfExportService {
b.append("<h1 class=\"part\" id=\"part-narrative\">Scènes</h1>");
ctx.addToc(0, "Scènes", ANCHOR_PART_NARRATIVE);
ctx.beginColumns();
arcFields(ctx, arc);
chapterFields(ctx, ch, st.questByContainerChapter.get(ch.getId()), st);
@@ -617,6 +696,7 @@ public class PdfExportService {
ctx.scenes++;
}
ctx.bookmarks.append(bookmark("Scènes", ANCHOR_PART_NARRATIVE, scBms.toString()));
ctx.endColumns();
}
/**
@@ -791,7 +871,10 @@ public class PdfExportService {
}
if (!notBlank(difficulty) && enemies.isEmpty() && !notBlank(freeText) && !notBlank(tactics)) return;
StringBuilder b = ctx.body;
b.append("<div class=\"box combat\"><div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
String boxText = Objects.toString(difficulty, "") + "\n" + String.join("\n", enemies)
+ "\n" + Objects.toString(freeText, "") + "\n" + Objects.toString(tactics, "");
b.append("<div class=\"box combat").append(isLongBox(boxText) ? " flow" : "")
.append("\"><div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
prose(b, difficulty);
if (!enemies.isEmpty()) {
b.append("<ul class=\"prose-list\">");
@@ -816,10 +899,12 @@ public class PdfExportService {
for (QuestJpaEntity q : quests) qBms.append(bookmark(q.getName(), "quest-" + q.getId(), ""));
ctx.bookmarks.append(bookmark("Quêtes", "part-quests", qBms.toString()));
ctx.beginColumns();
for (QuestJpaEntity q : quests) {
ctx.addToc(1, q.getName(), "quest-" + q.getId());
standaloneQuest(ctx, q, st);
}
ctx.endColumns();
}
/** Une quete libre/transversale : ses champs + les scenes de ses conteneurs (arc SYSTEM masque). */
@@ -1377,7 +1462,9 @@ public class PdfExportService {
StringBuilder b = ctx.body;
// Hauteur bornee proportionnellement au format (A5 : environ 7,8 cm).
double maxHeight = ILLUSTRATION_MAX_HEIGHT_CM * ctx.opt.format().widthCm / PdfExportOptions.PageFormat.A4.widthCm;
double widthCm = Math.min(ctx.contentWidthCm(), maxHeight * img.w() / img.h());
// Reserve les retraits des encadres et pieces imbriques, y compris en deux colonnes.
double maxWidth = ctx.contentWidthCm() - (ctx.columns ? 1.2 : 0);
double widthCm = Math.min(maxWidth, maxHeight * img.w() / img.h());
b.append("<div class=\"illus\"><img style=\"width:").append(cm(widthCm))
.append("\" src=\"").append(img.uri()).append("\"/>");
if (caption != null) {
@@ -1422,6 +1509,9 @@ public class PdfExportService {
.replace("__PAGE_MARGIN__", margins)
.replace("__BODY_PT__", String.format(Locale.ROOT, "%.1fpt", f.bodyPt));
if (f == PdfExportOptions.PageFormat.A5) css += A5_CSS;
if (f == PdfExportOptions.PageFormat.A4) {
css += EDITORIAL_CSS.replace("__HEADER__", esc(header.replace("\\", "\\\\").replace("'", "\\'")));
}
return opt.printFriendly() ? css + PRINT_CSS : css;
}
@@ -1437,6 +1527,7 @@ public class PdfExportService {
private static final String PRINT_CSS = loadCss("/pdf/export-print.css");
/** Surcharges A5 : couverture et titres resserres pour une page etroite. */
private static final String A5_CSS = loadCss("/pdf/export-a5.css");
private static final String EDITORIAL_CSS = loadCss("/pdf/export-editorial.css");
private static String loadCss(String resource) {
try (InputStream in = PdfExportService.class.getResourceAsStream(resource)) {
@@ -88,7 +88,8 @@ final class PdfHtml {
*/
static void box(StringBuilder b, String cssClass, String label, String value) {
if (!notBlank(value)) return;
b.append("<div class=\"box ").append(cssClass).append("\">");
boolean longText = isLongBox(value);
b.append("<div class=\"box ").append(cssClass).append(longText ? " flow" : "").append("\">");
b.append("<div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
List<TextBlock> blocks = parseBlocks(value);
for (int i = 0; i < blocks.size(); i++) {
@@ -106,6 +107,11 @@ final class PdfHtml {
b.append(DIV_CLOSE);
}
/** Borne conservative des encadres qui peuvent rester entiers dans une colonne A4. */
static boolean isLongBox(String text) {
return text.length() > 900 || text.lines().count() > 12;
}
/**
* Bloc "libelle en tete de ligne + valeur" si la valeur est non vide. Le libelle est
* rendu EN LIGNE devant le premier paragraphe (style stat-block : compact et balayable),
@@ -0,0 +1,110 @@
package com.loremind.infrastructure.transfer.pdf;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.util.Matrix;
import java.awt.Color;
import java.io.IOException;
/** Motifs vectoriels originaux, confines aux 49 points de marge inferieure des pages A4.
* Les dessiner apres la pagination conserve les renvois, le texte et la mise en page. */
final class PdfPageOrnaments {
private static final Color INK = new Color(0x34594f);
private static final Color SAGE = new Color(0xa8bbae);
private static final Color PALE = new Color(0xe6ece3);
private static final Color GOLD = new Color(0xb5a278);
private static final Color PRINT = new Color(0x999999);
private PdfPageOrnaments() {}
static void draw(PDDocument document, PdfExportOptions options) throws IOException {
if (options.format() != PdfExportOptions.PageFormat.A4) return;
// Pas de decoration sur la couverture, ni sur les annexes cartographiques paysage.
for (int i = 1; i < document.getNumberOfPages(); i++) {
var page = document.getPage(i);
var bounds = page.getMediaBox();
if (bounds.getWidth() > bounds.getHeight()) continue;
try (var canvas = new PDPageContentStream(document, page,
PDPageContentStream.AppendMode.PREPEND, true, true)) {
canvas.saveGraphicsState();
canvas.addRect(0, 0, bounds.getWidth(), 49);
canvas.clip();
// Le coin exterieur est plus ample ; alternance pour les pages en vis-a-vis.
corner(canvas, 0, false, i % 2 == 1 ? 1f : .72f, options.printFriendly());
corner(canvas, bounds.getWidth(), true, i % 2 == 0 ? 1f : .72f, options.printFriendly());
folio(canvas, bounds.getWidth() / 2, options.printFriendly());
canvas.restoreGraphicsState();
}
}
}
private static void corner(PDPageContentStream c, float x, boolean mirror, float scale,
boolean print) throws IOException {
c.saveGraphicsState();
c.transform(new Matrix(mirror ? -scale : scale, 0, 0, scale, x, 0));
if (!print) {
c.setNonStrokingColor(PALE);
c.moveTo(0, 49);
c.curveTo(35, 18, 94, 9, 184, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(SAGE);
c.moveTo(0, 35);
c.curveTo(40, 8, 81, 8, 150, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(INK);
c.moveTo(0, 21);
c.curveTo(22, 9, 63, 3, 110, 0);
c.lineTo(0, 0);
c.closePath();
c.fill();
c.setNonStrokingColor(SAGE);
for (int col = 0; col < 17; col++) {
float dx = 14 + col * 8;
for (int row = 0; row < 4; row++) {
float dy = 43 - col * 1.6f - row * 6;
if (dy > 13) dot(c, dx + (row % 2) * 3, dy, .35f + row * .12f);
}
}
}
c.setStrokingColor(print ? PRINT : GOLD);
c.setLineWidth(.45f);
c.moveTo(0, 43);
c.curveTo(32, 16, 85, 7, 170, 3);
c.stroke();
c.restoreGraphicsState();
}
private static void folio(PDPageContentStream c, float center, boolean print) throws IOException {
c.setStrokingColor(print ? PRINT : GOLD);
c.setNonStrokingColor(print ? PRINT : GOLD);
c.setLineWidth(.4f);
for (int side : new int[]{-1, 1}) {
c.moveTo(center + side * 18, 27);
c.lineTo(center + side * 37, 27);
c.stroke();
float x = center + side * 43;
c.moveTo(x, 29);
c.lineTo(x + 2, 27);
c.lineTo(x, 25);
c.lineTo(x - 2, 27);
c.closePath();
if (print) c.stroke(); else c.fill();
}
}
private static void dot(PDPageContentStream c, float x, float y, float r) throws IOException {
float k = r * .552285f;
c.moveTo(x + r, y);
c.curveTo(x + r, y + k, x + k, y + r, x, y + r);
c.curveTo(x - k, y + r, x - r, y + k, x - r, y);
c.curveTo(x - r, y - k, x - k, y - r, x, y - r);
c.curveTo(x + k, y - r, x + r, y - k, x + r, y);
c.closePath();
c.fill();
}
}
@@ -0,0 +1,18 @@
package com.loremind.infrastructure.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
/**
* Langue de l'utilisateur dans les tâches de fond : Spring Boot applique ce décorateur unique
* à l'exécuteur auto-configuré ({@code applicationTaskExecutor}) utilisé par les flux SSE.
*/
@Configuration
public class UserLanguageConfig {
@Bean
public TaskDecorator userLanguageTaskDecorator() {
return new UserLanguageTaskDecorator();
}
}
@@ -0,0 +1,14 @@
package com.loremind.infrastructure.web.config;
import com.loremind.domain.shared.ports.CurrentLanguage;
import org.springframework.stereotype.Component;
/** Langue courante lue dans {@link UserLanguageHolder} (requête HTTP, ou tâche de fond décorée). */
@Component
public class UserLanguageCurrentLanguage implements CurrentLanguage {
@Override
public String get() {
return UserLanguageHolder.get();
}
}
@@ -0,0 +1,30 @@
package com.loremind.infrastructure.web.config;
import org.springframework.core.task.TaskDecorator;
/**
* Relaie la langue de l'utilisateur ({@link UserLanguageHolder}, un ThreadLocal) du thread
* de la requête HTTP vers le thread de fond qui exécute la tâche.
* <p>
* Sans lui, les traitements longs lancés dans {@code applicationTaskExecutor} (imports de PDF,
* ateliers, chat IA en streaming…) lisaient la valeur par défaut du ThreadLocal sur leur
* propre thread : le Brain rédigeait toujours en français, même avec l'interface en anglais.
* Spring Boot associe automatiquement ce décorateur à l'exécuteur auto-configuré.
*/
public class UserLanguageTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
String language = UserLanguageHolder.get(); // lu sur le thread de la requête
return () -> {
String previous = UserLanguageHolder.get();
UserLanguageHolder.set(language);
try {
runnable.run();
} finally {
// Threads réutilisés par le pool : on ne laisse pas la langue fuir vers la tâche suivante.
UserLanguageHolder.set(previous);
}
};
}
}
@@ -0,0 +1,21 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.campaigncontext.CampaignContentSearchService;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/campaigns/search-content")
public class CampaignContentSearchController {
private final CampaignContentSearchService service;
public CampaignContentSearchController(CampaignContentSearchService service) {
this.service = service;
}
@GetMapping
public List<CampaignContentHit> search(@RequestParam("q") String query) {
return service.search(query);
}
}
@@ -257,6 +257,7 @@ public class GameSystemController {
dto.getName(),
dto.getDescription(),
dto.getRulesMarkdown(),
dto.getRulesMarkdownEn(),
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
@@ -0,0 +1,52 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.campaigncontext.GuidedAssistService;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Map;
/**
* IA des méthodes guidées : propose des réponses aux questions d'une méthode à partir de
* l'idée de départ du MJ. Rien n'est enregistré.
*
* <p>{@code POST /api/campaigns/{campaignId}/guided-assist} → {@code {answers: {cle: valeur}}} ;
* 400 sans question, 404 campagne inconnue, 502 si l'IA est indisponible.</p>
*/
@RestController
@RequestMapping("/api/campaigns/{campaignId}/guided-assist")
public class GuidedAssistController {
/** Corps : la méthode (nom, principe), l'idée, les questions et les réponses déjà écrites. */
public record SuggestRequest(String methodName, String principle, String idea,
List<Question> questions, Map<String, String> existing) {}
public record SuggestResponse(Map<String, String> answers) {}
private final GuidedAssistService service;
private final CampaignRepository campaignRepository;
public GuidedAssistController(GuidedAssistService service, CampaignRepository campaignRepository) {
this.service = service;
this.campaignRepository = campaignRepository;
}
@PostMapping
public ResponseEntity<SuggestResponse> suggest(@PathVariable String campaignId, @RequestBody SuggestRequest body) {
if (!campaignRepository.existsById(campaignId)) {
return ResponseEntity.notFound().build();
}
try {
return ResponseEntity.ok(new SuggestResponse(service.suggest(campaignId, body.methodName(),
body.principle(), body.idea(), body.questions(), body.existing())));
} catch (NarrativeAssistException e) {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
}
}
}
@@ -17,6 +17,8 @@ public class GameSystemDTO {
private String name;
private String description;
private String rulesMarkdown;
/** Version anglaise des règles (rulesMarkdown = version française). */
private String rulesMarkdownEn;
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
@@ -20,6 +20,7 @@ public class GameSystemMapper {
dto.setName(g.getName());
dto.setDescription(g.getDescription());
dto.setRulesMarkdown(g.getRulesMarkdown());
dto.setRulesMarkdownEn(g.getRulesMarkdownEn());
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
@@ -36,6 +37,7 @@ public class GameSystemMapper {
.name(dto.getName())
.description(dto.getDescription())
.rulesMarkdown(dto.getRulesMarkdown())
.rulesMarkdownEn(dto.getRulesMarkdownEn())
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
@@ -0,0 +1,3 @@
-- Règles d'un système de jeu en deux langues : rules_markdown = version française,
-- rules_markdown_en = version anglaise (remplie à l'import d'un PDF par traduction).
ALTER TABLE game_systems ADD COLUMN rules_markdown_en TEXT;
@@ -0,0 +1,93 @@
/* Edition A4 : narration en colonnes, palette encre et sauge.
CSS pagine OpenHTMLtoPDF ; les tableaux detailles et cartes restent pleine largeur. */
@page {
@top-center { content: '__HEADER__'; font-family: 'DejaVu Sans', sans-serif; font-size: 7pt;
color: #34594f; letter-spacing: .12em; border-bottom: .5pt solid #b3bfb4; padding-bottom: 6pt; }
@bottom-center { content: counter(page); font-size: 9pt; color: #34594f; font-family: 'DejaVu Serif', serif; }
}
@page:first { @top-center { content: none; border: 0; } }
body { margin: 0; color: #292c29; line-height: 1.42; word-wrap: break-word; }
.editorial-flow { column-count: 2; column-gap: .8cm; }
.editorial-flow p, .editorial-flow .field, .editorial-flow .box { orphans: 3; widows: 3; }
.editorial-flow .prose { text-align: left; }
/* Un bloc en ligne est deplace entier par le moteur de colonnes. Les encadres longs
restent fluides, sans fond ni bordure susceptibles de deborder sur la colonne suivante. */
.editorial-flow .box, .editorial-flow .illus { display: inline-block; width: 100%; box-sizing: border-box; }
.editorial-flow .box.flow { display: block; background: none; border: 0; padding: .1cm 0; }
.editorial-flow .box.flow .box-label { border-top: 1pt solid #9a8351; padding-top: .12cm; }
.editorial-flow .arc-head, .editorial-flow .chapter-head, .editorial-flow .scene-head,
.editorial-flow .section-head { display: inline-block; width: 100%; box-sizing: border-box; }
.cover { padding-top: 3cm; }
.cover.has-art { padding-top: .3cm; }
.cover-title { font-family: 'DejaVu Serif', serif; font-size: 32pt; line-height: 1.12;
letter-spacing: -.03em; color: #193c34; }
.cover-kicker { color: #456656; font-size: 9pt; letter-spacing: .18em; }
.cover-subtitle { font-family: 'DejaVu Serif', serif; color: #545b50; font-style: italic; font-size: 13pt; }
.cover-rule { width: 5cm; border-bottom: 1.5pt solid #9a8351; }
.cover-art { margin: .35cm 0 .5cm; }
.cover-art img { border: 0; }
.cover-meta { color: #34594f; font-size: 9pt; }
.cover-author { color: #193c34; margin-top: .6cm; }
.cover-version { color: #67746a; }
@page illustrated-cover { size: A4; margin: 0;
@top-center { content: none; border: 0; }
@bottom-center { content: none; }
}
.cover-illustrated { page: illustrated-cover; position: relative; width: 21cm; height: 29.65cm;
padding: 0; margin: 0; overflow: hidden; background: #193c34; }
.cover-background { position: absolute; }
.cover-caption { position: absolute; bottom: 1.2cm; left: 1.3cm; right: 1.3cm;
background: #193c34; padding: .7cm .7cm .6cm; }
.cover-caption .cover-title { color: #fffdf4; }
.cover-caption .cover-kicker, .cover-caption .cover-meta, .cover-caption .cover-version { color: #d4dfce; }
.cover-caption .cover-subtitle, .cover-caption .cover-author { color: #fffdf4; }
.cover-caption .cover-rule { border-color: #c9b47e; }
.cover-caption .cover-edition { color: #e1ca8e; }
.credits-title, .credits-subtitle { color: #34594f; }
.legal { border-color: #b3bfb4; }
h1.part, h1.toc-title { font-family: 'DejaVu Serif', serif; font-size: 25pt; line-height: 1.15;
letter-spacing: -.02em; text-transform: none; color: #193c34; border-bottom: 1.5pt solid #9a8351;
padding-bottom: .22cm; margin-bottom: .5cm; }
.toc tr.lvl0 td { color: #193c34; border-bottom-color: #b3bfb4; }
.toc td { border-bottom-color: #d4d9d0; }
.arc { margin: 0 0 .4cm; }
.arc-head { background: none; padding: .12cm 0 .18cm; border-radius: 0;
border-top: 2pt solid #34594f; border-bottom: .5pt solid #9a8351;
color: #193c34; font-family: 'DejaVu Serif', serif; font-size: 19pt; line-height: 1.18; }
.chapter-head { background: none; border: 0; border-bottom: 1pt solid #b3bfb4;
padding: 0 0 .12cm; font-family: 'DejaVu Serif', serif; font-size: 15pt; line-height: 1.2; color: #34594f; }
.eyebrow, .eyebrow-light { color: #637767; font-size: 6.5pt; margin-bottom: .08cm; }
.scene { border: 0; border-radius: 0; background: none; padding: 0; margin: .4cm 0 .3cm; }
.scene-head { color: #193c34; font-size: 11pt; text-transform: uppercase; letter-spacing: .03em;
border-bottom: .5pt solid #b3bfb4; padding-bottom: .08cm; }
.scene-meta { color: #687365; font-size: 8.5pt; }
.room { background: none; border: 0;
padding: 0 0 0 .22cm; margin: .3cm 0; }
.room-head { color: #695a36; border-left: 1pt solid #9a8351; padding-left: .18cm; }
h2.section-head { font-family: 'DejaVu Serif', serif; font-size: 14pt; color: #34594f; border-bottom-color: #b3bfb4; }
h3.folder { color: #456656; border-bottom-color: #b3bfb4; }
.field { margin: .2cm 0; }
.field-label { color: #34594f; font-size: 7.5pt; letter-spacing: .02em; }
.box { padding: .25cm .3cm; margin: .25cm 0; border-radius: 0; }
.box-label { letter-spacing: .06em; }
.box ul { padding-left: .4cm; margin: .12cm 0; }
.readaloud { background: #edf1e7; border: .75pt solid #456656; font-style: normal; color: #234438; }
.readaloud .box-label { color: #34594f; }
.secret { background: #f5f1e7; border: 0; border-left: 2pt solid #9a8351; }
.secret .box-label { color: #79683e; }
.combat { background: #f8eeea; border-left-color: #9b5547; }
.card { background: #fafbf7; border-color: #c5cec1; border-radius: 0; }
.persona-name { font-family: 'DejaVu Serif', serif; color: #193c34; font-size: 14pt; }
.level, .illus .caption { color: #637767; }
.illus { margin: .35cm 0; }
.illus img { border: 0; border-radius: 0; }
.illus .caption { font-size: 7pt; letter-spacing: .04em; }
.tech-table { width: 100%; }
.stats-table thead th, .stat-array th { background: #e7ede2; color: #34594f; border-color: #b3bfb4; }
.stats-table tbody th { background: #f0f3eb; }
.stats-table tr.alt td { background: #f0f3eb; }
.stats-table td, .stats-table th, .stat-array td { border-color: #d4d9d0; }
.stats-table .roll-col, a.xref { color: #34594f; }
a.xref { border-bottom-color: #b3bfb4; }
a.pref:after, .annex-kind { color: #637767; }
.map-title { color: #193c34; }
@@ -0,0 +1,61 @@
package com.loremind.application.campaigncontext;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** IA des méthodes guidées : questions validées, contexte de campagne transmis, réponses filtrées. */
@ExtendWith(MockitoExtension.class)
class GuidedAssistServiceTest {
@Mock private GuidedMethodAssistant assistant;
@Mock private CampaignContextFormatter contextFormatter;
@InjectMocks private GuidedAssistService service;
private static final Question TITLE = new Question("title", "Nom de l'enquête", "Ex. : L'héritage", "Le mystère", List.of());
private static final Question NATURE = new Question("node1.nature", "Genre de scène", null, "Première piste",
List.of(new Choice("location", "Un lieu"), new Choice("npc", "Une personne")));
@Test
void suggest_sendsCampaignContextAndExistingAnswers_andFiltersTheResult() {
when(contextFormatter.format("c1")).thenReturn("Campagne : Valfroide");
when(assistant.answer(eq("Enquête en nœuds"), any(), eq("Une tour se rallume"), eq("Campagne : Valfroide"),
anyList(), anyMap())).thenReturn(Map.of(
"title", " L'héritage empoisonné ",
"node1.nature", "dragon", // choix invalide -> écarté
"invented", "clé inventée", // clé non demandée -> écartée
"node1.name", ""));
Map<String, String> out = service.suggest("c1", "Enquête en nœuds", "Trois pistes",
"Une tour se rallume", List.of(TITLE, NATURE), Map.of("truth", " Le notaire ", "blank", " "));
assertEquals(Map.of("title", "L'héritage empoisonné"), out);
verify(assistant).answer(any(), any(), any(), any(), eq(List.of(TITLE, NATURE)), eq(Map.of("truth", "Le notaire")));
}
@Test
void suggest_keepsAValidChoice() {
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap())).thenReturn(Map.of("node1.nature", "npc"));
assertEquals(Map.of("node1.nature", "npc"), service.suggest("c1", "M", "", "", List.of(NATURE), null));
}
@Test
void suggest_withoutAnyValidQuestion_isRejected() {
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée", List.of(), Map.of()));
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée",
java.util.Arrays.asList(null, new Question(" ", "x", null, null, null)), Map.of()));
}
}
@@ -23,6 +23,9 @@ class GameSystemContextBuilderTest {
@Mock
private GameSystemRepository gameSystemRepository;
@Mock
private com.loremind.domain.shared.ports.CurrentLanguage currentLanguage;
@InjectMocks
private GameSystemContextBuilder builder;
@@ -71,4 +74,24 @@ class GameSystemContextBuilderTest {
assertEquals("Règles de combat.", sections.get("Combat"));
}
@Test
void build_usesTheRulesOfTheInterfaceLanguage_withFallback() {
com.loremind.domain.gamesystemcontext.GameSystem gs = com.loremind.domain.gamesystemcontext.GameSystem.builder()
.id("gs").name("Nimble").rulesMarkdown("## Combat\nJet de d20").rulesMarkdownEn("## Fighting\nRoll a d20").build();
org.mockito.Mockito.when(gameSystemRepository.findById("gs")).thenReturn(java.util.Optional.of(gs));
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Roll a d20"));
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("fr");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Jet de d20"));
gs.setRulesMarkdownEn(null); // pas de version anglaise : repli sur le français
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
.orElseThrow().toString().contains("Jet de d20"));
}
}
@@ -347,4 +347,65 @@ class BrainRulesImportClientTest {
assertTrue(c.done.get().sections().isEmpty());
assertNull(c.error.get());
}
@Test
void streaming_done_carriesBothLanguages() {
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"d20\"},\"page_count\":2,\"ocr_page_count\":0,"
+ "\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\"d20\"},"
+ "\"en\":{\"Fighting\":\"d20 roll\"}}}\n\n";
Collector c = new Collector();
ExchangeFunction ef = req -> Mono.just(
ClientResponse.create(HttpStatus.OK)
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
.body(sse)
.build());
client(ef).importRulesStreaming(
new byte[]{1}, "r.pdf",
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
c.done::set, c.error::set);
assertNotNull(c.done.get());
assertEquals("fr", c.done.get().sourceLanguage());
assertEquals(java.util.Map.of("Fighting", "d20 roll"), c.done.get().sectionsByLanguage().get("en"));
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
}
/**
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
* passe pas par les codecs du client, donc ne verrait pas la limite).
*/
@Test
void streaming_acceptsAVeryLargeDoneEvent() throws Exception {
String big = "x".repeat(600_000);
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"" + big + "\"},\"page_count\":300,"
+ "\"ocr_page_count\":0,\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\""
+ big + "\"},\"en\":{\"Fighting\":\"" + big + "\"}}}\n\n";
byte[] payload = sse.getBytes(java.nio.charset.StandardCharsets.UTF_8);
com.sun.net.httpserver.HttpServer server =
com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/import/rules/stream", exchange -> {
exchange.getRequestBody().readAllBytes();
exchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
exchange.sendResponseHeaders(200, payload.length);
try (var out = exchange.getResponseBody()) {
out.write(payload);
}
});
server.start();
try {
String url = "http://127.0.0.1:" + server.getAddress().getPort();
BrainRulesImportClient real = new BrainRulesImportClient(restTemplate, WebClient.builder(), objectMapper,
url, 30, "/import/rules", "/import/rules/stream");
Collector c = new Collector();
real.importRulesStreaming(new byte[]{1}, "r.pdf",
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add, c.done::set, c.error::set);
assertNull(c.error.get());
assertNotNull(c.done.get());
assertEquals(600_000, c.done.get().sectionsByLanguage().get("en").get("Fighting").length());
} finally {
server.stop(0);
}
}
}
@@ -0,0 +1,101 @@
package com.loremind.infrastructure.persistence.postgres;
import com.loremind.application.campaigncontext.CampaignContentSearchService;
import com.loremind.domain.campaigncontext.CampaignContentHit;
import com.loremind.infrastructure.web.controller.CampaignContentSearchController;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** Isolated SQL/API tests: never connects to the user's database. */
class PostgresCampaignContentSearchRepositoryTest {
private EmbeddedDatabase database;
private JdbcTemplate jdbc;
private CampaignContentSearchService service;
@BeforeEach
void setup() {
database = new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(EmbeddedDatabaseType.H2).build();
jdbc = new JdbcTemplate(database);
jdbc.execute("SET MODE PostgreSQL");
jdbc.execute("CREATE TABLE campaigns (id BIGINT PRIMARY KEY, name VARCHAR NOT NULL)");
jdbc.execute("CREATE TABLE arcs (id BIGINT PRIMARY KEY, name VARCHAR, campaign_id BIGINT, type VARCHAR)");
jdbc.execute("CREATE TABLE chapters (id BIGINT PRIMARY KEY, name VARCHAR, arc_id BIGINT)");
jdbc.execute("CREATE TABLE scenes (id BIGINT PRIMARY KEY, name VARCHAR, chapter_id BIGINT)");
jdbc.execute("CREATE TABLE quests (id BIGINT PRIMARY KEY, name VARCHAR, campaign_id BIGINT, arc_id BIGINT)");
jdbc.update("INSERT INTO campaigns VALUES (1, 'Les Ombres'), (2, 'Autre campagne')");
jdbc.update("INSERT INTO arcs VALUES (10, 'Port sombre', 1, 'LINEAR'), (11, 'Technique', 1, 'SYSTEM')");
jdbc.update("INSERT INTO chapters VALUES (20, 'Nuit sombre', 10), (21, 'Le témoin', 11)");
jdbc.update("INSERT INTO scenes VALUES (30, 'Taverne sombre', 20), (31, 'Rencontre sombre', 21)");
jdbc.update("INSERT INTO quests VALUES (40, 'Secret sombre', 1, NULL), (41, 'Secret sombre', 2, NULL)");
service = new CampaignContentSearchService(new PostgresCampaignContentSearchRepository(new NamedParameterJdbcTemplate(database)));
}
@AfterEach
void cleanup() { database.shutdown(); }
@Test
void findsEveryKindWithCorrectAncestorsAndCampaignNames() {
List<CampaignContentHit> hits = service.search(" SOMBRE ");
assertEquals(6, hits.size());
assertEquals(4, hits.stream().map(CampaignContentHit::kind).distinct().count());
CampaignContentHit scene = hits.stream().filter(h -> h.id().equals("30")).findFirst().orElseThrow();
assertEquals("1", scene.campaignId());
assertEquals("Les Ombres", scene.campaignName());
assertEquals("10", scene.arcId());
assertEquals("20", scene.chapterId());
assertEquals("Nuit sombre", scene.chapterName());
assertTrue(hits.stream().anyMatch(h -> h.id().equals("41") && h.campaignName().equals("Autre campagne")));
}
@Test
void hidesSystemContainersButKeepsTheirScenesNavigable() {
assertTrue(service.search("Technique").isEmpty());
assertTrue(service.search("témoin").isEmpty());
CampaignContentHit hit = service.search("Rencontre").get(0);
assertEquals("11", hit.arcId());
assertNull(hit.arcName());
assertEquals("21", hit.chapterId());
}
@Test
void treatsSqlWildcardsAndQuotesAsLiteralUserText() {
jdbc.update("INSERT INTO scenes VALUES (32, ?, 20)", "100%_! d'ombre");
assertEquals(1, service.search("%_").size());
assertEquals(1, service.search("_!").size());
assertEquals(1, service.search("d'ombre").size());
assertTrue(service.search("' OR 1=1 --").isEmpty());
assertTrue(service.search(" ").isEmpty());
assertTrue(service.search("s").isEmpty());
assertTrue(service.search(null).isEmpty());
}
@Test
void excludesOrphansAndBoundsResults() {
jdbc.update("INSERT INTO scenes VALUES (33, 'Orpheline', 999)");
assertTrue(service.search("Orpheline").isEmpty());
for (int i = 100; i < 200; i++) jdbc.update("INSERT INTO quests VALUES (?, ?, 1, NULL)", i, "Recherche " + i);
assertEquals(80, service.search("Recherche").size());
}
@Test
void exposesSearchProjectionAtTheFrontendEndpoint() throws Exception {
MockMvcBuilders.standaloneSetup(new CampaignContentSearchController(service)).build()
.perform(get("/api/campaigns/search-content").param("q", "Taverne"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].kind").value("scene"))
.andExpect(jsonPath("$[0].chapterId").value("20"))
.andExpect(jsonPath("$[0].campaignName").value("Les Ombres"));
}
}
@@ -0,0 +1,119 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.infrastructure.persistence.entity.*;
import com.loremind.infrastructure.persistence.jpa.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/** Verifie le PDF rendu, sans Spring ni connexion a une base de donnees. */
class PdfEditorialLayoutTest {
private static final String PROSE = "Le chemin traverse la foret et rejoint les portes du village. "
+ "Les voyageurs observent les traces sur le sol et interrogent les gardiens. ";
private PdfExportService service(List<SceneJpaEntity> scenes) {
var campaign = CampaignJpaEntity.builder().id(1L).name("Le chemin des brumes").build();
var campaigns = mock(CampaignJpaRepository.class);
when(campaigns.findById(1L)).thenReturn(Optional.of(campaign));
var st = new Structure();
st.visibleArcs = List.of(ArcJpaEntity.builder().id(2L).name("Arc").build());
st.chaptersByArc.put(2L, List.of(ChapterJpaEntity.builder().id(3L).name("Chapitre").build()));
st.scenesByChapter.put(3L, scenes);
var loader = mock(PdfStructureLoader.class);
when(loader.load(campaign)).thenReturn(st);
return new PdfExportService(campaigns, mock(NpcJpaRepository.class), mock(EnemyJpaRepository.class),
mock(RandomTableJpaRepository.class), mock(GameSystemJpaRepository.class),
mock(LoreNodeJpaRepository.class), mock(PageJpaRepository.class), mock(TemplateJpaRepository.class),
loader, mock(PdfImageEncoder.class));
}
@Test
void longNarrationFlowsThroughBothColumnsWithoutLostOrDuplicatedParagraphs() throws Exception {
String text = IntStream.range(0, 45).mapToObj(i -> "Repere%03d ".formatted(i) + PROSE.repeat(3))
.reduce((a, b) -> a + "\n\n" + b).orElseThrow();
var service = service(List.of(SceneJpaEntity.builder().id(4L).name("La route")
.playerNarration(text).gmSecretNotes("CONFIDENTIEL").build()));
try (var pdf = PDDocument.load(service.export("1"))) {
var reader = new Positions();
String extracted = reader.getText(pdf);
for (int i = 0; i < 45; i++) assertEquals(1, count(extracted, "Repere%03d".formatted(i)));
var markers = reader.lines.stream().filter(l -> l.text.startsWith("Repere")).toList();
assertTrue(markers.stream().anyMatch(l -> l.x < 150));
assertTrue(markers.stream().anyMatch(l -> l.x > 300));
assertTrue(pdf.getNumberOfPages() > 3);
assertBounds(reader, pdf);
}
}
@Test
void shortReadAloudBoxesStayTogetherAtColumnAndPageBreaks() throws Exception {
List<SceneJpaEntity> scenes = IntStream.range(0, 14).mapToObj(i -> SceneJpaEntity.builder()
.id((long) i + 4).name("Etape " + i)
.playerNarration("Debut%02d ".formatted(i) + PROSE.repeat(4) + " Fin%02d".formatted(i)).build()).toList();
try (var pdf = PDDocument.load(service(scenes).export("1"))) {
var reader = new Positions();
reader.getText(pdf);
for (int i = 0; i < 14; i++) {
String start = "Debut%02d".formatted(i), end = "Fin%02d".formatted(i);
Line first = reader.lines.stream().filter(l -> l.text.contains(start)).findFirst().orElseThrow();
Line last = reader.lines.stream().filter(l -> l.text.contains(end)).findFirst().orElseThrow();
assertEquals(first.page, last.page, "Encadre coupe entre deux pages");
assertEquals(first.x < 300, last.x < 300, "Encadre coupe entre deux colonnes");
}
assertBounds(reader, pdf);
}
}
@Test
void playerEditionStillOmitsSecretsAndSmallFormatKeepsOneColumn() throws Exception {
var service = service(List.of(SceneJpaEntity.builder().id(4L).name("La route")
.playerNarration(PROSE.repeat(8)).gmSecretNotes("CONFIDENTIEL").build()));
for (String format : List.of("A4", "A5", "LETTER")) {
var options = PdfExportOptions.parse("player", format, true, "NARRATIVE", null);
try (var pdf = PDDocument.load(service.export("1", options))) {
String text = new PDFTextStripper().getText(pdf);
assertFalse(text.contains("CONFIDENTIEL"));
assertTrue(text.contains("voyageurs"));
assertEquals(format.equals("A4"), service.xhtml("1", options).contains("<div class=\"editorial-flow\">"));
}
}
}
private static int count(String text, String needle) {
return (text.length() - text.replace(needle, "").length()) / needle.length();
}
private static void assertBounds(Positions reader, PDDocument pdf) {
for (Line line : reader.lines) {
var bounds = pdf.getPage(line.page - 1).getMediaBox();
assertTrue(line.x >= 0 && line.right <= bounds.getWidth() + 1, line.toString());
assertTrue(line.y >= 0 && line.y <= bounds.getHeight(), line.toString());
}
}
private record Line(String text, int page, float x, float right, float y) {}
private static class Positions extends PDFTextStripper {
final List<Line> lines = new ArrayList<>();
Positions() throws IOException { super(); }
@Override
protected void writeString(String text, List<TextPosition> positions) throws IOException {
if (!positions.isEmpty()) {
TextPosition first = positions.get(0), last = positions.get(positions.size() - 1);
lines.add(new Line(text, getCurrentPageNo(), first.getXDirAdj(),
last.getXDirAdj() + last.getWidthDirAdj(), first.getYDirAdj()));
}
super.writeString(text, positions);
}
}
}
@@ -0,0 +1,49 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.infrastructure.persistence.entity.*;
import com.loremind.infrastructure.persistence.jpa.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
/**
* Mode plat du livret : un seul arc d'un seul chapitre n'est présenté « à plat » que si
* ces deux conteneurs sont vides. Un chapitre écrit (méthode guidée…) garde ses en-têtes.
*/
@SpringBootTest
@Transactional
class PdfExportFlatModeTest {
@Autowired private PdfExportService service;
@Autowired private CampaignJpaRepository campaignRepo;
@Autowired private ArcJpaRepository arcRepo;
@Autowired private ChapterJpaRepository chapterRepo;
@Autowired private SceneJpaRepository sceneRepo;
private String campaign(String chapterGmNotes) {
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("C").arcsCount(1).build());
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Arc principal").campaignId(camp.getId()).order(0).build());
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("L'héritage empoisonné")
.arcId(arc.getId()).order(0).gmNotes(chapterGmNotes).build());
sceneRepo.save(SceneJpaEntity.builder().name("L'arrestation").chapterId(ch.getId()).order(0).build());
return String.valueOf(camp.getId());
}
@Test
void bareArcAndChapter_areFlattened() {
String x = service.xhtml(campaign(null), PdfExportOptions.defaults());
assertTrue(x.contains("id=\"part-narrative\">Scènes</h1>"));
assertFalse(x.contains("L'héritage empoisonné</div>"), "en-tête de chapitre masqué");
}
@Test
void writtenChapter_keepsItsHeaders() {
String x = service.xhtml(campaign("Le notaire est coupable."), PdfExportOptions.defaults());
assertTrue(x.contains("id=\"part-narrative\">Structure narrative</h1>"));
assertTrue(x.contains("L'héritage empoisonné"), "le chapitre de la méthode guidée reste visible");
assertTrue(x.contains("Le notaire est coupable."));
}
}
@@ -402,6 +402,9 @@ class PdfExportPreviewTest {
Path outPlayer = Path.of("target", "campaign-preview-joueurs-a5.pdf");
Files.write(outPlayer, player);
System.out.println("[preview] PDF écrit : " + outPlayer.toAbsolutePath());
Files.write(Path.of("target", "campaign-preview-impression-a4.pdf"),
service.export("1", PdfExportOptions.parse("gm", "A4", true, null, null)));
}
/** Image placeholder deterministe : portrait carre ou battlemap avec grille. */
@@ -11,14 +11,18 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.*;
@@ -146,17 +150,29 @@ class PdfExportPublicationTest {
assertFalse(x.contains("Structure de l'aventure"));
}
@Test
void formatAndPrintMode_shapeTheStylesheet() {
String a5 = service.xhtml(campaignId, new PdfExportOptions(true, PageFormat.A5, true,
EnumSet.allOf(Section.class), LoreScope.ALL));
assertTrue(a5.contains("size: A5"));
assertTrue(a5.contains("font-size: 9.0pt"));
assertTrue(a5.contains(".arc-head { background: none"), "feuille impression ajoutée");
String a4 = service.xhtml(campaignId, PdfExportOptions.defaults());
assertTrue(a4.contains("size: A4"));
assertFalse(a4.contains(".arc-head { background: none"));
@ParameterizedTest
@EnumSource(PageFormat.class)
void formatAndPrintMode_shapeTheStylesheet(PageFormat format) throws Exception {
String printCss;
try (var in = PdfExportService.class.getResourceAsStream("/pdf/export-print.css")) {
assertNotNull(in, "feuille impression disponible");
printCss = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
for (boolean print : new boolean[]{false, true}) {
String x = service.xhtml(campaignId, new PdfExportOptions(true, format, print,
EnumSet.allOf(Section.class), LoreScope.ALL));
String css = x.substring(x.indexOf("<style>") + "<style>".length(), x.indexOf("</style>"));
assertTrue(css.contains("size: " + format.cssSize + ";"), "format " + format);
assertTrue(css.contains(String.format(Locale.ROOT, "font-size: %.1fpt", format.bodyPt)),
"corps du texte pour " + format);
// Le style A4 couleur peut aussi avoir des titres sans fond. Verifier la feuille
// complete et son ordre de cascade, plutot qu'une declaration CSS partagee.
if (print) {
assertTrue(css.endsWith(printCss), "surcharges impression appliquees en dernier : " + format);
} else {
assertFalse(css.contains(printCss), "aucune feuille impression en couleur : " + format);
}
}
}
@Test
@@ -0,0 +1,45 @@
package com.loremind.infrastructure.web.config;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.task.TaskExecutor;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* La langue de l'interface suit les traitements de fond : sans ce relais, les imports de PDF
* et les flux IA lancés dans l'exécuteur partaient toujours en français.
*/
@SpringBootTest
class UserLanguageTaskDecoratorTest {
@Autowired @Qualifier("applicationTaskExecutor") private TaskExecutor taskExecutor;
@AfterEach
void clear() {
UserLanguageHolder.clear();
}
@Test
void applicationTaskExecutor_runsTasksInTheRequestLanguage() throws Exception {
UserLanguageHolder.set("en");
CompletableFuture<String> seen = new CompletableFuture<>();
taskExecutor.execute(() -> seen.complete(UserLanguageHolder.get()));
assertEquals("en", seen.get(5, TimeUnit.SECONDS));
}
@Test
void decorator_restoresTheWorkerThreadLanguageAfterTheTask() {
UserLanguageHolder.set("en");
Runnable decorated = new UserLanguageTaskDecorator().decorate(() -> assertEquals("en", UserLanguageHolder.get()));
UserLanguageHolder.set("fr"); // le « thread de travail » avait une autre langue
decorated.run();
assertEquals("fr", UserLanguageHolder.get(), "pas de fuite vers la tâche suivante du pool");
}
}
@@ -0,0 +1,72 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.domain.campaigncontext.Campaign;
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
class GuidedAssistControllerTest {
@Autowired private MockMvc mockMvc;
@Autowired private CampaignRepository campaignRepository;
@MockitoBean private GuidedMethodAssistant assistant;
private static final String BODY = """
{"methodName":"Enquête en nœuds","principle":"Trois pistes","idea":"Une tour se rallume",
"questions":[{"key":"title","label":"Nom","hint":"","step":"Le mystère","options":[]}],
"existing":{}}""";
private String campaignId() {
return campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
}
@Test
void suggest_returnsTheFilteredAnswers() throws Exception {
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
.thenReturn(Map.of("title", "L'héritage empoisonné", "other", "x"));
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
.contentType(MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isOk())
.andExpect(jsonPath("$.answers.title").value("L'héritage empoisonné"))
.andExpect(jsonPath("$.answers.other").doesNotExist());
}
@Test
void suggest_unknownCampaign_is404_andUnavailableAi_is502() throws Exception {
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", "999999999")
.contentType(MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isNotFound());
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
.thenThrow(new NarrativeAssistException("Le Brain est injoignable"));
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
.contentType(MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isBadGateway());
}
@Test
void suggest_withoutQuestions_is400() throws Exception {
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
.contentType(MediaType.APPLICATION_JSON).content("{\"idea\":\"x\",\"questions\":[]}"))
.andExpect(status().isBadRequest());
}
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

+124
View File
@@ -0,0 +1,124 @@
import { test, expect } from '@playwright/test';
// Deterministic read-only API fixtures: no writes to a running LoreMind instance.
const campaign = { id: '1', name: 'Les Ombres', description: '', playerCount: 0 };
const arc = { id: '2', name: 'Le port', campaignId: '1', type: 'LINEAR' };
const chapter = { id: '3', name: 'La nuit', arcId: '2' };
const scene = { id: '4', name: 'La taverne', chapterId: '3', description: 'Un rendez-vous sous la pluie.' };
const scenePath = '/campaigns/1/arcs/2/chapters/3/scenes/4';
const playthrough = { id: '5', name: 'Groupe du vendredi', campaignId: '1' };
const tree = { arcs: [arc, { ...arc, id: '8', name: 'La forêt' }], chaptersByArc: { '2': [chapter] },
scenesByChapter: { '3': [scene] }, npcs: [], randomTables: [], enemies: [], quests: [],
playthroughs: [playthrough], readiness: { gaps: [], overallStatus: 'READY', counts: {} } };
test.beforeEach(async ({ page }) => {
await page.route('**/api/**', async route => {
const url = new URL(route.request().url());
const responses: Record<string, unknown> = {
'/api/config': { demoMode: true, updateCheckEnabled: false },
'/api/campaigns': [campaign, { ...campaign, id: '10', name: 'Autre campagne' }],
'/api/campaigns/1': campaign,
'/api/campaigns/1/tree': tree,
'/api/arcs/2': arc, '/api/chapters/3': chapter, '/api/scenes/4': scene,
'/api/playthroughs/5': playthrough,
'/api/playthroughs': [playthrough],
'/api/campaigns/1/writing-review': { remarks: [] },
'/api/sessions/6': { id: '6', name: 'Séance du vendredi', playthroughId: '5', active: false,
startedAt: '2026-10-16T18:00:00', endedAt: '2026-10-16T21:00:00' }
};
let json = responses[url.pathname] ?? [];
if (url.pathname === '/api/campaigns/search-content' && url.searchParams.get('q') === 'taverne') {
json = [{ kind: 'scene', ...scene, campaignId: '1', campaignName: 'Les Ombres',
arcId: '2', arcName: 'Le port', chapterName: 'La nuit' }];
}
await route.fulfill({ json });
});
});
test('scene context stays selected and breadcrumbs navigate back to its chapter', async ({ page }) => {
await page.goto(scenePath);
const breadcrumb = page.getByRole('navigation', { name: "Fil d'Ariane" });
await expect(breadcrumb).toContainText('Les Ombres');
await expect(breadcrumb).toContainText('Le port');
await expect(breadcrumb.locator('[aria-current="page"]')).toHaveText('La taverne');
await expect(page.locator('app-sidebar').getByRole('button', { name: 'Les Ombres', exact: true }))
.toHaveAttribute('aria-current', 'location');
await expect(page.locator('app-sidebar').getByRole('button', { name: 'Autre campagne', exact: true }))
.not.toHaveAttribute('aria-current', 'location');
await breadcrumb.getByRole('link', { name: 'La nuit' }).click();
await expect(page).toHaveURL(/\/chapters\/3$/);
await expect(breadcrumb.locator('[aria-current="page"]')).toHaveText('La nuit');
});
test('search opens a scene and can repeat the same query after reopening', async ({ page }) => {
await page.goto(scenePath);
await expect(page.getByRole('heading', { name: 'La taverne', exact: true })).toBeVisible();
for (let attempt = 0; attempt < 2; attempt++) {
await page.keyboard.press('Control+k');
const dialog = page.getByRole('dialog', { name: 'Recherche globale' });
await dialog.getByRole('textbox').fill('taverne');
const result = dialog.getByRole('button', { name: /^La taverne/ });
await expect(result).toContainText('Les Ombres › Le port › La nuit');
await dialog.getByRole('textbox').press('Enter');
await expect(dialog).toBeHidden();
await expect(page).toHaveURL(new RegExp(scenePath + '$'));
}
});
test('session breadcrumb includes the owning playthrough', async ({ page }) => {
await page.goto('/sessions/6');
const breadcrumb = page.getByRole('navigation', { name: "Fil d'Ariane" });
await expect(breadcrumb.getByRole('link', { name: 'Groupe du vendredi' }))
.toHaveAttribute('href', '/campaigns/1/playthroughs/5');
await expect(breadcrumb.locator('[aria-current="page"]')).toHaveText('Séance du vendredi');
await expect(page.locator('app-sidebar .toggle-btn.active')).toHaveText('Campagne');
});
test('breadcrumb and search remain readable on a narrow screen', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 375, height: 812 });
await page.goto(scenePath);
await expect(page.getByRole('navigation', { name: "Fil d'Ariane" })).toBeVisible();
const sizes = await page.locator('main').evaluate(el => ({ scroll: el.scrollWidth, client: el.clientWidth }));
expect(sizes.scroll).toBeLessThanOrEqual(sizes.client);
await page.keyboard.press('Control+k');
const dialog = page.getByRole('dialog', { name: 'Recherche globale' });
await expect(dialog).toBeVisible();
const searchSizes = await dialog.evaluate(el => ({ scroll: el.scrollWidth, client: el.clientWidth }));
expect(searchSizes.scroll).toBeLessThanOrEqual(searchSizes.client);
await page.screenshot({ path: testInfo.outputPath('mobile-shortcuts.png') });
});
test('recent pages and favorites survive reload and stars work with the keyboard', async ({ page }, testInfo) => {
await page.goto(scenePath);
await expect(page.getByRole('heading', { name: 'La taverne', exact: true })).toBeVisible();
await page.keyboard.press('Control+k');
const dialog = page.getByRole('dialog', { name: 'Recherche globale' });
await expect(dialog.getByRole('heading', { name: 'Consultés récemment' })).toBeVisible();
const star = dialog.getByRole('button', { name: 'Ajouter La taverne aux favoris', exact: true });
await star.focus();
await star.press('Enter');
await expect(dialog).toBeVisible();
await expect(dialog.getByRole('heading', { name: 'Favoris' })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('favorites.png') });
await page.reload();
await expect(page.getByRole('heading', { name: 'La taverne', exact: true })).toBeVisible();
await page.keyboard.press('Control+k');
await expect(dialog.getByRole('heading', { name: 'Favoris' })).toBeVisible();
await dialog.getByRole('button', { name: 'Retirer La taverne des favoris', exact: true }).click();
await expect(dialog.getByRole('heading', { name: 'Favoris' })).toHaveCount(0);
await dialog.getByRole('button', { name: 'Effacer l’historique' }).click();
await expect(dialog.getByRole('heading', { name: 'Consultés récemment' })).toHaveCount(0);
});
test('campaign management actions stay accessible through the compact menu', async ({ page }, testInfo) => {
await page.goto('/campaigns/1');
await expect(page.getByRole('heading', { name: 'Les Ombres', exact: true })).toBeVisible();
const menu = page.locator('.management-menu');
await expect(menu.getByRole('button', { name: 'Supprimer', exact: true })).toBeHidden();
await menu.locator('summary').click();
await expect(menu.getByRole('button', { name: 'Supprimer', exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('campaign-menu.png') });
await menu.getByRole('button', { name: 'Modifier', exact: true }).click();
await expect(page.getByRole('button', { name: 'Sauvegarder', exact: true })).toBeVisible();
await expect(page.locator('.management-menu')).toHaveCount(0);
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "loremind-web",
"version": "1.4.0-beta",
"version": "1.6.1-beta",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "loremind-web",
"version": "1.4.0-beta",
"version": "1.6.1-beta",
"dependencies": {
"@angular/animations": "^21.2.17",
"@angular/cdk": "^21.2.14",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "loremind-web",
"version": "1.4.0-beta",
"version": "1.6.1-beta",
"description": "LoreMind Frontend - Angular",
"scripts": {
"ng": "ng",
+1
View File
@@ -63,6 +63,7 @@
}
<main #mainContent class="main-content" tabindex="-1">
<app-campaign-breadcrumb></app-campaign-breadcrumb>
<router-outlet></router-outlet>
</main>
</div>
+2
View File
@@ -7,6 +7,7 @@ import { TranslatePipe } from '@ngx-translate/core';
import { LucideAngularModule, Menu, PanelLeft, Search, X } from 'lucide-angular';
import { filter, map } from 'rxjs';
import { SidebarComponent } from './sidebar/sidebar.component';
import { CampaignBreadcrumbComponent } from './shared/breadcrumb/campaign-breadcrumb.component';
import { SecondarySidebarComponent } from './shared/secondary-sidebar/secondary-sidebar.component';
import { GlobalSearchComponent } from './shared/global-search/global-search.component';
import { UpdateBannerComponent } from './shared/update-banner/update-banner.component';
@@ -29,6 +30,7 @@ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), selec
selector: 'app-root',
imports: [
RouterOutlet,
CampaignBreadcrumbComponent,
LucideAngularModule,
TranslatePipe,
SidebarComponent,
@@ -12,6 +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';
/**
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
@@ -365,12 +366,13 @@ export function buildCampaignTree(
// des scènes et l'ajout restent identiques (c'est le nœud chapitre, relabellisé
// et remonté à la racine). Dès qu'un 2e arc OU un 2e chapitre existe, la
// structure complète réapparaît automatiquement.
const onlyArc = sortedArcs.length === 1 ? sortedArcs[0] : null;
const onlyArcChapters = onlyArc ? (data.chaptersByArc[onlyArc.id!] ?? []) : [];
// Mode plat seulement si l'arc et le chapitre uniques sont VIDES (cf. flatContainer) :
// un chapitre écrit par une méthode guidée doit rester visible.
const flat = flatContainer(sortedArcs, data.chaptersByArc);
const onlyArc = flat?.arc ?? null;
let narrationNodes: TreeItem[] = arcNodes;
// Le mode plat ne s'applique PAS à un arc HUB (qui présente des quêtes, pas juste des scènes).
if (onlyArc && onlyArc.type !== 'HUB' && onlyArcChapters.length === 1) {
const ch = onlyArcChapters[0];
if (flat && onlyArc) {
const ch = flat.chapter;
const sortedScenes = [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder);
const sceneItems: TreeItem[] = sortedScenes.map(sc => ({
id: `scene-${sc.id}`,
@@ -40,22 +40,27 @@
<lucide-icon [img]="Network" [size]="14"></lucide-icon>
{{ 'campaignDetail.graph' | translate }}
</button>
<button type="button" class="btn-secondary" (click)="exportPdf()" [disabled]="exportingPdf">
<lucide-icon [img]="FileText" [size]="14"></lucide-icon>
{{ (exportingPdf ? 'campaignDetail.pdfExporting' : 'campaignDetail.pdfExport') | translate }}
</button>
<button type="button" class="btn-secondary" (click)="exportFoundry()" [disabled]="exportingFoundry">
<lucide-icon [img]="Download" [size]="14"></lucide-icon>
{{ (exportingFoundry ? 'campaignDetail.foundryExporting' : 'campaignDetail.foundryExport') | translate }}
</button>
<button type="button" class="btn-secondary" (click)="startEdit()">
<details #managementMenu class="management-menu" (keydown.escape)="managementMenu.open = false; managementToggle.focus()">
<summary #managementToggle class="btn-secondary">{{ 'campaignDetail.manage' | translate }}</summary>
<div class="management-actions">
<button type="button" class="btn-secondary" (click)="managementMenu.open = false; startEdit()">
<lucide-icon [img]="Pencil" [size]="14"></lucide-icon>
{{ 'common.edit' | translate }}
</button>
<button type="button" class="btn-danger" (click)="deleteCampaign()">
<button type="button" class="btn-secondary" (click)="managementMenu.open = false; exportPdf()" [disabled]="exportingPdf">
<lucide-icon [img]="FileText" [size]="14"></lucide-icon>
{{ (exportingPdf ? 'campaignDetail.pdfExporting' : 'campaignDetail.pdfExport') | translate }}
</button>
<button type="button" class="btn-secondary" (click)="managementMenu.open = false; exportFoundry()" [disabled]="exportingFoundry">
<lucide-icon [img]="Download" [size]="14"></lucide-icon>
{{ (exportingFoundry ? 'campaignDetail.foundryExporting' : 'campaignDetail.foundryExport') | translate }}
</button>
<button type="button" class="btn-danger" (click)="managementMenu.open = false; deleteCampaign()">
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
{{ 'common.delete' | translate }}
</button>
</div>
</details>
</div>
</div>
}
@@ -223,7 +228,7 @@
</a>
</div>
</div>
@if (arcs.length > 0 && !showQuickAddScene) {
@if (arcs.length > 0 && !flatMode) {
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
(cdkDropListDropped)="dropArc($event)">
@for (arc of arcs; track arc.id) {
@@ -237,7 +242,7 @@
}
<!-- Mode plat (un seul arc d'un seul chapitre) : on masque la carte de
l'arc par défaut, comme dans la sidebar. Les scènes vivent dans le volet. -->
@if (arcs.length > 0 && showQuickAddScene) {
@if (arcs.length > 0 && flatMode) {
<div class="empty-state empty-state--compact">
<p>{{ 'campaignDetail.flatModeHint' | translate }}</p>
</div>
@@ -6,6 +6,32 @@
line-height: 1.4;
}
.management-menu {
position: relative;
summary { cursor: pointer; list-style: none; }
summary::-webkit-details-marker { display: none; }
summary::after { content: '▾'; margin-left: 0.5rem; }
&[open] summary::after { content: '▴'; }
summary:focus-visible { outline: 2px solid #a5b4fc; outline-offset: 2px; }
}
.management-actions {
position: absolute;
right: 0;
top: calc(100% + 0.5rem);
z-index: 20;
display: flex;
flex-direction: column;
gap: 0.35rem;
width: max-content;
max-width: min(280px, 80vw);
padding: 0.5rem;
background: #131722;
border: 1px solid #374151;
border-radius: 8px;
box-shadow: 0 8px 24px #0006;
button { width: 100%; text-align: left; justify-content: flex-start; white-space: normal; }
}
// ==== Parties (Playthroughs) ====
.playthroughs-grid {
display: grid;
@@ -37,6 +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';
@Component({
selector: 'app-campaign-detail',
@@ -212,6 +213,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
// L'arc SYSTEM (« Quêtes libres ») est de la plomberie : pas de carte d'arc pour lui.
this.arcs = [...treeData.arcs].sort(byOrder).filter(a => a.type !== 'SYSTEM');
this.chapterCountByArc = this.computeChapterCounts(treeData);
this.flatMode = !!flatContainer(this.arcs, treeData.chaptersByArc);
this.showLayout(allCampaigns, treeData);
this.pageTitleService.set(campaign.name);
this.openEditFromQueryParam();
@@ -348,6 +350,12 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
// structure est simple (vide, ou un seul arc d'au plus un chapitre).
quickSceneInFlight = false;
/**
* Mode plat (arc et chapitre uniques encore vides) : les cartes d'arc sont masquées, les
* scènes vivent dans le volet. Dès qu'il y a du contenu écrit, la structure reste visible.
*/
flatMode = false;
get showQuickAddScene(): boolean {
if (this.arcs.length === 0) return true;
if (this.arcs.length === 1) return (this.chapterCountByArc[this.arcs[0].id!] ?? 0) <= 1;
@@ -0,0 +1,29 @@
import { flatContainer } from './flat-structure';
import { Arc, Chapter } from '../services/campaign.model';
describe('flatContainer (mode plat)', () => {
const arc = (extra: Partial<Arc> = {}): Arc => ({ id: 'a1', name: 'Arc principal', campaignId: 'c', type: 'LINEAR', ...extra } as Arc);
const chapter = (extra: Partial<Chapter> = {}): Chapter => ({ id: 'ch1', name: 'Chapitre 1', arcId: 'a1', ...extra } as Chapter);
it('flattens a single empty arc with a single empty chapter', () => {
expect(flatContainer([arc()], { a1: [chapter()] })?.chapter.id).toBe('ch1');
});
it('keeps the structure once the chapter or the arc has written content', () => {
expect(flatContainer([arc()], { a1: [chapter({ gmNotes: 'Le notaire est coupable' })] })).toBeNull();
expect(flatContainer([arc()], { a1: [chapter({ description: "L'affaire commence" })] })).toBeNull();
expect(flatContainer([arc({ hooks: '- Un ami disparaît' })], { a1: [chapter()] })).toBeNull();
expect(flatContainer([arc({ illustrationImageIds: ['img'] })], { a1: [chapter()] })).toBeNull();
});
it('ignores names and blank text', () => {
expect(flatContainer([arc({ name: 'Ma campagne', stakes: ' ' })], { a1: [chapter({ name: 'Début' })] })).not.toBeNull();
});
it('never flattens a HUB arc, several chapters or several arcs (system arc ignored)', () => {
expect(flatContainer([arc({ type: 'HUB' })], { a1: [chapter()] })).toBeNull();
expect(flatContainer([arc()], { a1: [chapter(), chapter({ id: 'ch2' })] })).toBeNull();
expect(flatContainer([arc(), arc({ id: 'a2' })], { a1: [chapter()], a2: [] })).toBeNull();
expect(flatContainer([arc(), arc({ id: 'sys', type: 'SYSTEM' })], { a1: [chapter()] })).not.toBeNull();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { Arc, Chapter } from '../services/campaign.model';
/**
* Mode « plat » (Niveau 0) : une campagne d'un seul arc linéaire et d'un seul chapitre
* présente directement ses scènes, sans les niveaux arc et chapitre. Seulement si ces deux
* conteneurs sont VIDES (créés d'office pour poser une première scène) : dès que l'auteur y
* a écrit quelque chose — à la main ou via une méthode guidée (titre, accroche, vérité
* cachée, plan du méchant…) — on les montre, sinon ce contenu deviendrait introuvable.
* Même règle dans le volet, sur la page de la campagne et dans le livret PDF (core).
*/
export function flatContainer(arcs: Arc[], chaptersByArc: Record<string, Chapter[]>): { arc: Arc; chapter: Chapter } | null {
const visible = arcs.filter(a => a.type !== 'SYSTEM');
if (visible.length !== 1) return null;
const arc = visible[0];
if (arc.type === 'HUB') return null; // un arc HUB présente des quêtes, pas une simple liste de scènes
const chapters = chaptersByArc[arc.id!] ?? [];
if (chapters.length !== 1) return null;
const chapter = chapters[0];
return isBareArc(arc) && isBareChapter(chapter) ? { arc, chapter } : 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]
.every(blank) && !(arc.illustrationImageIds?.length);
}
/** Aucun contenu d'écriture dans le chapitre (le nom ne compte pas : « Chapitre 1 » est créé d'office). */
export function isBareChapter(chapter: Chapter): boolean {
return [chapter.description, chapter.playerObjectives, chapter.narrativeStakes, chapter.gmNotes]
.every(blank) && !(chapter.illustrationImageIds?.length);
}
function blank(value: string | null | undefined): boolean {
return !value || !value.trim();
}
@@ -0,0 +1,70 @@
import { IDEA_KEY, applySuggestions, buildSuggestRequest, hasIdea, isFillable, markTouched } from './guided-assist';
import { INVESTIGATION_METHOD } from './methods/investigation.method';
import { GuidedField } from './guided-method.model';
/** Traduction factice : renvoie la clé, sauf les noms pré-remplis (valeurs d'office). */
const t = (key: string) => key.endsWith('defaults.node1.name') ? 'Première piste' : key;
const field = (key: string): GuidedField =>
INVESTIGATION_METHOD.steps.flatMap(s => s.fields ?? []).find(f => f.key === key)!;
describe('guided AI assist', () => {
it('treats empty fields and untouched defaults as free for the AI', () => {
expect(isFillable(INVESTIGATION_METHOD, field('truth'), {}, t)).toBe(true);
expect(isFillable(INVESTIGATION_METHOD, field('node1.name'), { 'node1.name': 'Première piste' }, t)).toBe(true);
expect(isFillable(INVESTIGATION_METHOD, field('node1.nature'), { 'node1.nature': 'location' }, t)).toBe(true);
expect(isFillable(INVESTIGATION_METHOD, field('node1.nature'), { 'node1.nature': 'npc' }, t)).toBe(false);
expect(isFillable(INVESTIGATION_METHOD, field('truth'), { truth: 'Le notaire' }, t)).toBe(false);
});
it('never considers a field the GM touched as free, even at its default value', () => {
const answers = markTouched({ 'node1.name': 'Première piste' }, 'node1.name');
expect(isFillable(INVESTIGATION_METHOD, field('node1.name'), answers, t)).toBe(false);
});
it('asks only free fields, sends what the GM wrote as context, and passes the idea', () => {
const req = buildSuggestRequest(INVESTIGATION_METHOD, { [IDEA_KEY]: ' Une tour ', truth: 'Le notaire est coupable' }, t);
expect(req.idea).toBe('Une tour');
expect(req.existing).toEqual({ truth: 'Le notaire est coupable' });
expect(req.questions.some(q => q.key === 'truth')).toBe(false);
const nature = req.questions.find(q => q.key === 'node1.nature')!;
expect(nature.options.map(o => o.value)).toEqual(['location', 'npc', 'event']);
expect(nature.hint).toBe('');
expect(req.methodName).toBe('guided.investigation.name');
});
it('sends the method as the GM follows it by hand: principle, then the role of each step', () => {
const req = buildSuggestRequest(INVESTIGATION_METHOD, { [IDEA_KEY]: 'Une tour' }, t);
const lines = req.principle.split('\n');
expect(lines[0]).toBe('guided.investigation.tagline');
expect(lines).toContain('- guided.investigation.steps.node1.title : guided.investigation.steps.node1.why');
expect(req.principle).toContain('steps.proactive.why');
expect(req.principle).not.toContain('steps.placement');
expect(req.principle).not.toContain('steps.review');
expect(req.principle).not.toContain('.example');
});
it('requires an idea before asking the AI', () => {
expect(hasIdea({})).toBe(false);
expect(hasIdea({ [IDEA_KEY]: ' ' })).toBe(false);
expect(hasIdea({ [IDEA_KEY]: 'Une tour qui se rallume' })).toBe(true);
});
it('limits the questions to the requested step', () => {
const req = buildSuggestRequest(INVESTIGATION_METHOD, {}, t, ['node2']);
expect(req.questions.length).toBeGreaterThan(0);
expect(req.questions.every(q => q.key.startsWith('node2.'))).toBe(true);
});
it('applies proposals to free fields only, and only valid choices', () => {
const answers = { truth: 'Le notaire', 'node1.nature': 'location' };
const { answers: next, filled } = applySuggestions(INVESTIGATION_METHOD, answers, {
truth: 'Autre vérité', 'node1.nature': 'npc', 'node2.nature': 'dragon', title: "L'héritage", unknown: 'x'
}, t);
expect(next['truth']).toBe('Le notaire');
expect(next['node1.nature']).toBe('npc');
expect(next['node2.nature']).toBeUndefined();
expect(next['title']).toBe("L'héritage");
expect(next['unknown']).toBeUndefined();
expect(filled).toBe(2);
});
});
@@ -0,0 +1,139 @@
import { GuidedAnswers, GuidedField, GuidedMethod, GuidedStep } from './guided-method.model';
/**
* IA des méthodes guidées (logique pure, testée sans Angular) : questions envoyées au modèle,
* champs que l'IA a le droit de remplir, et fusion des réponses proposées.
*
* Règle d'or : l'IA ne remplace JAMAIS ce que le MJ a écrit. Elle ne remplit qu'un champ
* vide, ou resté à sa valeur d'office (nom pré-rempli « Première piste », premier choix
* d'une question à choix) tant que le MJ n'y a pas touché.
*/
/** Clé de réponse réservée : l'idée de départ du MJ (gardée dans le brouillon). */
export const IDEA_KEY = 'idea';
/** Clé de réponse réservée : champs modifiés à la main par le MJ (séparés par des virgules). */
export const TOUCHED_KEY = 'touched';
/** Traduction d'une clé i18n (injectée : TranslateService.instant côté composant). */
export type Translate = (key: string) => string;
export interface GuidedQuestion {
key: string;
label: string;
hint: string;
step: string;
options: { value: string; label: string }[];
}
export interface GuidedSuggestRequest {
methodName: string;
principle: string;
idea: string;
questions: GuidedQuestion[];
existing: Record<string, string>;
}
/** Préfixe i18n de la méthode (`guided.<i18nKey>.`). */
function k(method: GuidedMethod, path: string): string {
return `guided.${method.i18nKey}.${path}`;
}
/** Valeur mise d'office par l'assistant (sans intervention du MJ), ou null. */
export function defaultValue(method: GuidedMethod, field: GuidedField, t: Translate): string | null {
if (field.kind === 'choice') return field.options?.[0] ?? null;
if (field.prefilled) return t(k(method, `defaults.${field.key}`));
return null;
}
export function touchedKeys(answers: GuidedAnswers): Set<string> {
return new Set((answers[TOUCHED_KEY] ?? '').split(',').filter(Boolean));
}
/** Marque un champ comme modifié à la main (l'IA n'y touchera plus). */
export function markTouched(answers: GuidedAnswers, key: string): GuidedAnswers {
const touched = touchedKeys(answers);
if (touched.has(key)) return answers;
touched.add(key);
return { ...answers, [TOUCHED_KEY]: [...touched].join(',') };
}
/** Le champ est-il encore libre pour l'IA ? Vide, ou à sa valeur d'office et jamais touché. */
export function isFillable(method: GuidedMethod, field: GuidedField, answers: GuidedAnswers, t: Translate): boolean {
const value = (answers[field.key] ?? '').trim();
if (!value) return true;
return !touchedKeys(answers).has(field.key) && value === defaultValue(method, field, t);
}
function formSteps(method: GuidedMethod, stepIds?: string[]): GuidedStep[] {
return method.steps.filter(s => s.kind === 'form' && (!stepIds || stepIds.includes(s.id)));
}
/**
* La méthode telle que le MJ la suit à la main : son principe, puis le rôle de chaque étape
* (le « pourquoi » affiché dans l'assistant). Sans ces consignes, l'IA ne voyait que les
* libellés des champs et pouvait, par exemple, régler l'épreuve de la salle 2 par un combat.
* Les exemples ne sont pas transmis : l'IA les recopierait.
*/
export function methodGuide(method: GuidedMethod, t: Translate): string {
const steps = formSteps(method).map(s => {
const title = t(k(method, 'steps.' + s.id + '.title'));
const why = t(k(method, 'steps.' + s.id + '.why'));
return `- ${title} : ${why}`;
});
return [t(k(method, 'tagline')), '', ...steps].join('\n');
}
/** L'IA part toujours de l'idée du MJ : pas de proposition « de but en blanc ». */
export function hasIdea(answers: GuidedAnswers): boolean {
return (answers[IDEA_KEY] ?? '').trim().length > 0;
}
/**
* Requête de propositions pour les étapes demandées (toutes si absent) : seuls les champs
* encore libres sont demandés ; tout ce que le MJ a déjà écrit est transmis comme contexte.
*/
export function buildSuggestRequest(method: GuidedMethod, answers: GuidedAnswers, t: Translate,
stepIds?: string[]): GuidedSuggestRequest {
const questions: GuidedQuestion[] = [];
const existing: Record<string, string> = {};
for (const step of formSteps(method)) {
for (const field of step.fields ?? []) {
if (!isFillable(method, field, answers, t)) {
existing[field.key] = answers[field.key];
continue;
}
if (stepIds && !stepIds.includes(step.id)) continue;
questions.push({
key: field.key,
label: t(k(method, `fields.${field.key}.label`)),
hint: field.kind === 'choice' ? '' : t(k(method, `fields.${field.key}.placeholder`)),
step: t(k(method, `steps.${step.id}.title`)),
options: (field.options ?? []).map(o => ({ value: o, label: t(k(method, `options.${field.key}.${o}`)) }))
});
}
}
return {
methodName: t(k(method, 'name')),
principle: methodGuide(method, t),
idea: (answers[IDEA_KEY] ?? '').trim(),
questions,
existing
};
}
/** Applique les propositions sur les seuls champs encore libres (jamais sur un champ du MJ). */
export function applySuggestions(method: GuidedMethod, answers: GuidedAnswers, suggestions: Record<string, string>,
t: Translate): { answers: GuidedAnswers; filled: number } {
const next = { ...answers };
let filled = 0;
for (const step of formSteps(method)) {
for (const field of step.fields ?? []) {
const proposal = suggestions[field.key]?.trim();
if (!proposal || !isFillable(method, field, answers, t)) continue;
if (field.kind === 'choice' && !field.options?.includes(proposal)) continue;
next[field.key] = proposal;
filled++;
}
}
return { answers: next, filled };
}
@@ -29,6 +29,40 @@
</aside>
}
<!-- IA : idée de départ du MJ, propositions pour toute la méthode ou pour l'étape. -->
@if (step.kind !== 'review') {
<section class="ai-idea" [attr.aria-label]="'guided.ai.title' | translate">
<label class="ai-idea-label" for="guided-idea">
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
{{ 'guided.ai.title' | translate }}
</label>
<textarea id="guided-idea" rows="4" [(ngModel)]="idea"
[placeholder]="'guided.ai.placeholder' | translate"></textarea>
<div class="ai-actions">
<button type="button" class="btn-ai" (click)="suggestAll()" [disabled]="!!suggesting || !hasIdea">
{{ (suggesting === 'all' ? 'guided.ai.thinking' : 'guided.ai.suggestAll') | translate }}
</button>
@if (step.kind === 'form') {
<button type="button" class="btn-ai-secondary" (click)="suggestStep()" [disabled]="!!suggesting || !hasIdea">
{{ (suggesting === 'step' ? 'guided.ai.thinking' : 'guided.ai.suggestStep') | translate }}
</button>
}
@if (canUndoSuggest && !suggesting) {
<button type="button" class="btn-link" (click)="undoSuggest()">{{ 'guided.ai.undo' | translate }}</button>
}
</div>
@if (suggestFilled !== null) {
<p class="ai-note" role="status">
{{ (suggestFilled > 0 ? 'guided.ai.filled' : 'guided.ai.nothingToFill') | translate:{ count: suggestFilled } }}
</p>
}
@if (suggestError) {
<p class="ai-error" role="alert">{{ suggestError }}</p>
}
<p class="ai-hint">{{ (hasIdea ? 'guided.ai.hint' : 'guided.ai.ideaFirst') | translate }}</p>
</section>
}
<!-- Où ranger l'aventure -->
@if (step.kind === 'placement') {
<fieldset class="placement">
@@ -361,3 +361,68 @@
@media (prefers-reduced-motion: reduce) {
.progress-fill { transition: none; }
}
// IA : idée de départ et propositions (ne remplit que les champs encore libres).
.ai-idea {
margin: 0 0 1.25rem;
padding: 0.8rem 0.9rem;
border: 1px solid rgba(251, 191, 36, 0.3);
background: rgba(251, 191, 36, 0.06);
border-radius: 10px;
display: flex;
flex-direction: column;
gap: 0.55rem;
textarea {
background: #1f2937;
border: 1px solid #374151;
border-radius: 8px;
padding: 0.6rem 0.8rem;
color: white;
font: inherit;
resize: vertical;
}
}
.ai-idea-label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: #fde68a;
font-weight: 600;
font-size: 0.9rem;
}
.ai-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.btn-ai, .btn-ai-secondary {
padding: 0.45rem 0.9rem;
border-radius: 8px;
font-size: 0.85rem;
cursor: pointer;
border: 1px solid rgba(251, 191, 36, 0.45);
&:disabled { opacity: 0.6; cursor: default; }
}
.btn-ai { background: rgba(251, 191, 36, 0.18); color: #fde68a; font-weight: 600; }
.btn-ai-secondary { background: transparent; color: #fde68a; }
.btn-link {
background: none;
border: none;
color: #a5b4fc;
text-decoration: underline;
cursor: pointer;
font-size: 0.85rem;
padding: 0;
}
.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; }
@@ -12,6 +12,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
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 { 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';
@@ -139,10 +140,87 @@ export class GuidedWizardComponent implements OnInit {
}
setAnswer(key: string, value: string): void {
this.answers = { ...this.answers, [key]: value };
// Un champ modifié par le MJ ne sera plus jamais remplacé par une proposition de l'IA.
this.answers = markTouched({ ...this.answers, [key]: value }, key);
this.saveDraft();
}
// --- IA : propositions à partir de l'idée de départ ------------------------------------
/** Proposition en cours (anti double-clic) ; `all` = toute la méthode, sinon l'étape. */
suggesting: 'all' | 'step' | null = null;
suggestError: string | null = null;
/** Nombre de champs remplis par la dernière proposition (message de confirmation). */
suggestFilled: number | null = null;
/** Réponses avant la dernière proposition : « Annuler » les restaure. */
private beforeSuggest: GuidedAnswers | null = null;
get idea(): string {
return this.answers[IDEA_KEY] ?? '';
}
set idea(value: string) {
this.answers = { ...this.answers, [IDEA_KEY]: value };
this.saveDraft();
}
/** Les propositions partent toujours de l'idée du MJ : boutons inactifs tant qu'elle est vide. */
get hasIdea(): boolean {
return hasIdea(this.answers);
}
get canUndoSuggest(): boolean {
return this.beforeSuggest !== null;
}
/** Propose des réponses pour tous les champs encore libres de la méthode. */
suggestAll(): void {
this.suggest('all');
}
/** Propose des réponses pour les champs encore libres de l'étape affichée. */
suggestStep(): void {
this.suggest('step');
}
undoSuggest(): void {
if (!this.beforeSuggest) return;
this.answers = this.beforeSuggest;
this.beforeSuggest = null;
this.suggestFilled = null;
this.saveDraft();
}
private suggest(scope: 'all' | 'step'): void {
const method = this.method;
if (!method || this.suggesting || !hasIdea(this.answers)) return;
const t = (key: string) => this.translate.instant(key) as string;
const stepIds = scope === 'step' && this.step ? [this.step.id] : undefined;
const request = buildSuggestRequest(method, this.answers, t, stepIds);
this.suggestError = null;
this.suggestFilled = null;
if (request.questions.length === 0) {
this.suggestFilled = 0;
return;
}
this.suggesting = scope;
this.skeletonService.suggest(this.campaignId, request).subscribe({
next: ({ answers }) => {
const before = this.answers;
const result = applySuggestions(method, this.answers, answers ?? {}, t);
this.answers = result.answers;
this.beforeSuggest = result.filled > 0 ? before : this.beforeSuggest;
this.suggestFilled = result.filled;
this.suggesting = null;
this.saveDraft();
},
error: () => {
this.suggesting = null;
this.suggestError = this.translate.instant('guided.ai.error');
}
});
}
/** Placement par défaut + valeurs pré-remplies + premier choix des champs `choice`. */
private applyDefaults(): void {
const a = { ...this.answers };
@@ -60,6 +60,9 @@
@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(' · ') } }}
@@ -75,6 +78,18 @@
<p class="import-error">{{ importError }}</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>
<div class="section-list">
@for (section of sections; track section; let i = $index) {
<div class="section-card" [class.collapsed]="section.collapsed">
@@ -173,6 +173,13 @@
line-height: 1.4;
}
.import-waiting {
margin: 0.45rem 0 0;
color: var(--text-muted, #9ca3af);
font-size: 0.8rem;
line-height: 1.4;
}
.import-note {
margin: -0.4rem 0 1rem;
padding: 0.55rem 0.8rem;
@@ -359,3 +366,32 @@
&:hover { border-color: #374151; color: #e5e7eb; }
}
// Règles en deux langues : onglets Français / English au-dessus des sections.
.rules-langs {
display: flex;
gap: 0.4rem;
margin: 0.75rem 0 0.35rem;
}
.rules-lang {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.4rem 0.85rem;
border-radius: 999px;
border: 1px solid #374151;
background: transparent;
color: #d1d5db;
cursor: pointer;
font-size: 0.85rem;
&.active { border-color: #6c63ff; background: rgba(108, 99, 255, 0.15); color: white; }
}
.rules-lang-count {
font-size: 0.72rem;
padding: 0 0.4rem;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
@@ -1,4 +1,4 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
@@ -43,13 +43,16 @@ const NPC_FIELD_SUGGESTIONS = ['Motivation', 'Apparence', 'Faction', 'Notes MJ']
/** Suggestions de champs pour la fiche ENNEMI — stats de combat. */
const ENEMY_FIELD_SUGGESTIONS = ['Stats', 'Attaques', 'Capacités', 'Faiblesses', 'Butin', 'Tactique'];
/** Langue d'une version des règles. */
type RulesLang = 'fr' | 'en';
@Component({
selector: 'app-game-system-edit',
imports: [FormsModule, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent],
templateUrl: './game-system-edit.component.html',
styleUrls: ['./game-system-edit.component.scss']
})
export class GameSystemEditComponent implements OnInit {
export class GameSystemEditComponent implements OnInit, OnDestroy {
readonly Save = Save;
readonly ArrowLeft = ArrowLeft;
readonly Dices = Dices;
@@ -79,11 +82,27 @@ export class GameSystemEditComponent implements OnInit {
* en cours, pas l'historique.
*/
importStatus: string | null = null;
/**
* Secondes écoulées depuis le dernier évènement du flux. Un morceau peut occuper
* l'IA plusieurs minutes (et un nouvel essai après une erreur autant) : sans ce
* compteur, l'écran paraît figé alors que l'import avance.
*/
importWaitSeconds = 0;
private lastImportEventAt = 0;
private importWaitTimer?: ReturnType<typeof setInterval>;
name = '';
description = '';
author = '';
sections: RuleSection[] = [];
/** Règles en deux langues : sections par langue ; l'onglet affiché est `rulesLang`. */
sectionsByLang: Record<RulesLang, RuleSection[]> = { fr: [], en: [] };
rulesLang: RulesLang = 'fr';
readonly rulesLangs: RulesLang[] = ['fr', 'en'];
/** Sections de l'onglet affiché (même tableau : push/splice modifient la bonne langue). */
get sections(): RuleSection[] {
return this.sectionsByLang[this.rulesLang];
}
characterTemplate: TemplateField[] = [];
npcTemplate: TemplateField[] = [];
enemyTemplate: TemplateField[] = [];
@@ -107,6 +126,8 @@ export class GameSystemEditComponent implements OnInit {
) {}
ngOnInit(): void {
// 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');
if (this.id) {
this.service.getById(this.id).subscribe({
@@ -114,7 +135,10 @@ export class GameSystemEditComponent implements OnInit {
this.name = gs.name;
this.description = gs.description ?? '';
this.author = gs.author ?? '';
this.sections = this.parseMarkdown(gs.rulesMarkdown ?? '');
this.sectionsByLang = {
fr: this.parseMarkdown(gs.rulesMarkdown ?? ''),
en: this.parseMarkdown(gs.rulesMarkdownEn ?? '')
};
this.characterTemplate = gs.characterTemplate ? [...gs.characterTemplate] : [];
this.npcTemplate = gs.npcTemplate ? [...gs.npcTemplate] : [];
this.enemyTemplate = gs.enemyTemplate ? [...gs.enemyTemplate] : [];
@@ -161,9 +185,12 @@ export class GameSystemEditComponent implements OnInit {
this.importProgress = null;
this.importFound = [];
this.importStatus = null;
this.startImportWait();
this.service.importRulesStream(file).subscribe({
next: (ev) => {
this.lastImportEventAt = Date.now();
this.importWaitSeconds = 0;
if (ev.type === 'progress') {
// Un morceau vient d'aboutir : le message d'attente est obsolète.
this.importStatus = null;
@@ -181,7 +208,7 @@ export class GameSystemEditComponent implements OnInit {
} else if (ev.type === 'status') {
this.importStatus = ev.message;
} else if (ev.type === 'done') {
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount);
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage);
}
},
error: (err: Error) => {
@@ -193,9 +220,21 @@ export class GameSystemEditComponent implements OnInit {
});
}
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number): void {
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number,
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null): void {
this.resetImportProgress();
const added = this.mergeImportedSections(sections);
// Règles en deux langues (Brain récent) : chaque version va dans son onglet ; sinon,
// les sections vont dans l'onglet affiché (comportement historique).
const bilingual = !!byLanguage && Object.keys(byLanguage).some(l => l === 'fr' || l === 'en');
let added = 0;
if (bilingual) {
for (const lang of this.rulesLangs) {
const merged = this.mergeImportedSections(byLanguage![lang] ?? {}, this.sectionsByLang[lang]);
if (lang === this.rulesLang || added === 0) added = Math.max(added, merged);
}
} else {
added = this.mergeImportedSections(sections, this.sections);
}
if (added === 0) {
this.importError = this.translate.instant('gameSystemEdit.importNoRules');
return;
@@ -208,12 +247,52 @@ export class GameSystemEditComponent implements OnInit {
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(', ')
});
}
}
/** 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;
}
private resetImportProgress(): void {
this.importing = false;
this.importPhase = '';
this.importProgress = null;
this.stopImportWait();
}
ngOnDestroy(): void {
this.stopImportWait();
}
/** Le compteur ne s'affiche qu'au-delà de quelques secondes sans nouvelle. */
get importWaitLabel(): string | null {
const s = this.importWaitSeconds;
if (s < 15) return null;
const m = Math.floor(s / 60);
return m > 0 ? `${m} min ${String(s % 60).padStart(2, '0')} s` : `${s} s`;
}
private startImportWait(): void {
this.stopImportWait();
this.lastImportEventAt = Date.now();
this.importWaitSeconds = 0;
this.importWaitTimer = setInterval(() => {
this.importWaitSeconds = Math.floor((Date.now() - this.lastImportEventAt) / 1000);
}, 1000);
}
private stopImportWait(): void {
if (this.importWaitTimer) clearInterval(this.importWaitTimer);
this.importWaitTimer = undefined;
this.importWaitSeconds = 0;
}
/**
@@ -221,20 +300,20 @@ export class GameSystemEditComponent implements OnInit {
* (insensible à la casse) → contenu ajouté à la suite ; sinon nouvelle carte.
* Retourne le nombre de sections effectivement intégrées.
*/
private mergeImportedSections(sections: Record<string, string>): number {
private mergeImportedSections(sections: Record<string, string>, target: RuleSection[]): number {
let count = 0;
for (const [rawTitle, rawContent] of Object.entries(sections ?? {})) {
const title = (rawTitle ?? '').trim();
const content = (rawContent ?? '').trim();
if (!title || !content) continue;
const existing = this.sections.find(
const existing = target.find(
s => s.title.trim().toLowerCase() === title.toLowerCase()
);
if (existing) {
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
existing.collapsed = false;
} else {
this.sections.push({ title, content, collapsed: false });
target.push({ title, content, collapsed: false });
}
count++;
}
@@ -300,7 +379,8 @@ export class GameSystemEditComponent implements OnInit {
name: this.name.trim(),
description: this.description.trim() || null,
author: this.author.trim() || null,
rulesMarkdown: this.serializeMarkdown(),
rulesMarkdown: this.serializeMarkdown(this.sectionsByLang.fr),
rulesMarkdownEn: this.serializeMarkdown(this.sectionsByLang.en),
characterTemplate: this.characterTemplate,
npcTemplate: this.npcTemplate,
enemyTemplate: this.enemyTemplate,
@@ -377,8 +457,8 @@ export class GameSystemEditComponent implements OnInit {
}
/** Reconstruit le markdown à partir des sections (ignore les sections vides). */
private serializeMarkdown(): string | null {
const valid = this.sections.filter(s => s.title.trim() || s.content.trim());
private serializeMarkdown(sections: RuleSection[]): string | null {
const valid = sections.filter(s => s.title.trim() || s.content.trim());
if (valid.length === 0) return null;
return valid
.map(s => {
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { CampaignContentHit, campaignContentRoute, campaignContentContext } from './campaign-content-search.model';
const hit: CampaignContentHit = { kind: 'scene', id: '4', name: 'Le témoin', campaignId: '1',
campaignName: 'Les Ombres', arcId: '2', arcName: 'Le port', chapterId: '3', chapterName: 'La nuit' };
describe('campaign search destinations', () => {
it('resolves each entity even when IDs overlap between types', () => {
expect(campaignContentRoute(hit)).toEqual(['/campaigns', '1', 'arcs', '2', 'chapters', '3', 'scenes', '4']);
expect(campaignContentRoute({ ...hit, kind: 'chapter' })).toEqual(['/campaigns', '1', 'arcs', '2', 'chapters', '4']);
expect(campaignContentRoute({ ...hit, kind: 'arc' })).toEqual(['/campaigns', '1', 'arcs', '4']);
expect(campaignContentRoute({ ...hit, kind: 'quest', arcId: null })).toEqual(['/campaigns', '1', 'quests', '4']);
});
it('keeps a system arc in the destination but out of the visible context', () => {
expect(campaignContentContext({ ...hit, arcName: null })).toBe('Les Ombres › La nuit');
expect(campaignContentContext(hit)).toBe('Les Ombres › Le port › La nuit');
expect(campaignContentRoute({ ...hit, chapterId: null })).toEqual([]);
});
});
@@ -0,0 +1,26 @@
export interface CampaignContentHit {
kind: 'arc' | 'chapter' | 'scene' | 'quest';
id: string;
name: string;
campaignId: string;
campaignName: string;
arcId: string | null;
arcName: string | null;
chapterId: string | null;
chapterName: string | null;
}
export function campaignContentRoute(hit: CampaignContentHit): string[] {
const root = ['/campaigns', hit.campaignId];
if (hit.kind === 'quest') return [...root, 'quests', hit.id];
if (hit.kind === 'arc') return [...root, 'arcs', hit.id];
if (!hit.arcId) return [];
const arc = [...root, 'arcs', hit.arcId];
if (hit.kind === 'chapter') return [...arc, 'chapters', hit.id];
return hit.chapterId ? [...arc, 'chapters', hit.chapterId, 'scenes', hit.id] : [];
}
export function campaignContentContext(hit: CampaignContentHit): string {
return [hit.campaignName, hit.kind !== 'arc' ? hit.arcName : null,
hit.kind === 'scene' ? hit.chapterName : null].filter(Boolean).join(' › ');
}
+5
View File
@@ -7,6 +7,7 @@ import { Npc } from './npc.model';
import { RandomTable } from './random-table.model';
import { Enemy } from './enemy.model';
import { PdfExportOptions } from './pdf-export.model';
import { CampaignContentHit } from './campaign-content-search.model';
/**
* Arbre de campagne AGRÉGÉ (une seule requête HTTP) — miroir de CampaignTreeDTO.
@@ -262,4 +263,8 @@ export class CampaignService {
const params = new HttpParams().set('q', q);
return this.http.get<Campaign[]>(`${this.apiUrl}/search`, { params });
}
searchContent(q: string): Observable<CampaignContentHit[]> {
return this.http.get<CampaignContentHit[]>(`${this.apiUrl}/search-content`, { params: { q } });
}
}
+7 -1
View File
@@ -12,6 +12,8 @@ export interface GameSystem {
name: string;
description?: string | null;
rulesMarkdown?: string | null;
/** Version anglaise des règles (rulesMarkdown = version française). */
rulesMarkdownEn?: string | null;
characterTemplate?: TemplateField[];
npcTemplate?: TemplateField[];
enemyTemplate?: TemplateField[];
@@ -43,7 +45,9 @@ export interface RulesImportResponse {
export type RulesImportStreamEvent =
| { type: 'progress'; current: number; total: number; pageCount: number; ocrPageCount: number; newSectionTitles: string[] }
| { type: 'status'; message: string }
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number }
| { 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 }
| { type: 'error'; message: string };
/** Payload de creation/mise a jour (sans id). */
@@ -51,6 +55,8 @@ export interface GameSystemCreate {
name: string;
description?: string | null;
rulesMarkdown?: string | null;
/** Version anglaise des règles (rulesMarkdown = version française). */
rulesMarkdownEn?: string | null;
characterTemplate?: TemplateField[];
npcTemplate?: TemplateField[];
enemyTemplate?: TemplateField[];
@@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { GuidedSkeleton, GuidedSkeletonResult } from './guided-skeleton.model';
import { GuidedSuggestRequest } from '../campaigns/guided/guided-assist';
/** Service HTTP des méthodes guidées (Mentor d'écriture, phase M3). */
@Injectable({ providedIn: 'root' })
@@ -12,4 +13,9 @@ export class GuidedSkeletonService {
create(campaignId: string, skeleton: GuidedSkeleton): Observable<GuidedSkeletonResult> {
return this.http.post<GuidedSkeletonResult>(`/api/campaigns/${campaignId}/guided-skeleton`, skeleton);
}
/** IA : réponses proposées aux questions d'une méthode, à partir de l'idée du MJ (rien n'est enregistré). */
suggest(campaignId: string, request: GuidedSuggestRequest): Observable<{ answers: Record<string, string> }> {
return this.http.post<{ answers: Record<string, string> }>(`/api/campaigns/${campaignId}/guided-assist`, request);
}
}
@@ -0,0 +1,56 @@
import { Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { LayoutService, SecondarySidebarConfig } from './layout.service';
import { campaignBreadcrumbs, isWithinRoute } from '../shared/navigation-path';
import { NavigationEntry, NavigationHistory, contentUrl, readHistory, rememberVisit, toggleFavorite } from '../shared/navigation-history';
/** Shortcuts belong to this browser and origin; unavailable storage is non-fatal. */
@Injectable({ providedIn: 'root' })
export class NavigationHistoryService {
private readonly key = 'loremind.navigation.v1';
private readonly state = signal<NavigationHistory>(this.load());
readonly history = this.state.asReadonly();
private context: SecondarySidebarConfig | null = null;
constructor(layout: LayoutService, router: Router) {
layout.secondarySidebar$.pipe(takeUntilDestroyed()).subscribe(context => {
this.context = context;
const current = this.state().recent.find(item => item.url === contentUrl(router.url));
if (current) this.visit(current.url, current.title);
});
}
private subtitleFor(url: string): string {
const path = campaignBreadcrumbs(url, this.context, '');
if (path.length > 1) return path.slice(0, -1).map(item => item.label).join(' › ');
const parent = this.context?.globalItems.find(item => item.route !== url && isWithinRoute(url, item.route));
return parent?.name ?? '';
}
private load(): NavigationHistory {
try { return readHistory(localStorage.getItem(this.key)); }
catch { return { recent: [], favorites: [] }; }
}
private save(history: NavigationHistory): void {
this.state.set(history);
try { localStorage.setItem(this.key, JSON.stringify(history)); } catch { /* Keep shortcuts in memory. */ }
}
visit(url: string, title: string, subtitle = ''): void {
const path = contentUrl(url);
if (path && title.trim()) {
const existing = this.state().recent.find(item => item.url === path);
this.save(rememberVisit(this.state(), { url: path, title, subtitle: subtitle || this.subtitleFor(path) || existing?.subtitle || '' }));
}
}
isFavorite(url: string): boolean { return this.state().favorites.some(item => item.url === url); }
toggle(entry: NavigationEntry): void {
if (contentUrl(entry.url) === entry.url) this.save(toggleFavorite(this.state(), entry));
}
clearRecent(): void { this.save({ ...this.state(), recent: [] }); }
}
+4 -1
View File
@@ -1,5 +1,7 @@
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { NavigationHistoryService } from './navigation-history.service';
/**
* Service centralisé pour le titre de l'onglet navigateur.
@@ -11,7 +13,7 @@ import { Title } from '@angular/platform-browser';
*/
@Injectable({ providedIn: 'root' })
export class PageTitleService {
constructor(private title: Title) {}
constructor(private title: Title, private router: Router, private history: NavigationHistoryService) {}
/**
* Définit le titre de l'onglet au format "LoreMind - <subject>".
@@ -21,5 +23,6 @@ export class PageTitleService {
set(subject: string | null | undefined): void {
const s = subject?.trim();
this.title.setTitle(s ? `LoreMind - ${s}` : 'LoreMind');
if (s) this.history.visit(this.router.url, s);
}
}
@@ -1,9 +1,6 @@
@if (session) {
<div class="session-detail">
<a class="back-link" [routerLink]="campaignId ? ['/campaigns', campaignId] : ['/campaigns']">
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
{{ 'sessionDetail.backToCampaign' | translate }}
</a>
<app-breadcrumb [items]="breadcrumbItems"></app-breadcrumb>
<div class="detail-header">
<div class="header-texts">
@if (!editingName) {
@@ -1,6 +1,7 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Component, OnInit, OnDestroy, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import {
@@ -15,7 +16,8 @@ import { SessionService } from '../../services/session.service';
import { Session } from '../../services/session.model';
import { PlaythroughService } from '../../services/playthrough.service';
import { CampaignService } from '../../services/campaign.service';
import { Scene } from '../../services/campaign.model';
import { Scene, Campaign, Playthrough } from '../../services/campaign.model';
import { BreadcrumbComponent, BreadcrumbItem } from '../../shared/breadcrumb/breadcrumb.component';
import {
SessionEntry, SessionEntryInput, EntryType, ENTRY_TYPE_META
} from '../../services/session-entry.model';
@@ -33,11 +35,22 @@ import { DiceRollResult } from '../session-dice-panel/session-dice-panel.compone
*/
@Component({
selector: 'app-session-detail',
imports: [CommonModule, FormsModule, LucideAngularModule, TranslatePipe, RouterLink, SessionReferencePanelComponent],
imports: [CommonModule, FormsModule, LucideAngularModule, TranslatePipe, BreadcrumbComponent, SessionReferencePanelComponent],
templateUrl: './session-detail.component.html',
styleUrls: ['./session-detail.component.scss']
})
export class SessionDetailComponent implements OnInit, OnDestroy {
private readonly destroyRef = inject(DestroyRef);
private campaign: Campaign | null = null;
private playthrough: Playthrough | null = null;
get breadcrumbItems(): BreadcrumbItem[] {
const items: BreadcrumbItem[] = [{ label: this.translate.instant('campaignTree.allCampaigns'), route: ['/campaigns'] }];
if (this.campaign) items.push({ label: this.campaign.name, route: ['/campaigns', this.campaign.id] });
if (this.playthrough) items.push({ label: this.playthrough.name, route: ['/campaigns', this.playthrough.campaignId, 'playthroughs', this.playthrough.id] });
if (this.session) items.push({ label: this.session.name });
return items;
}
readonly Dices = Dices;
readonly ArrowLeft = ArrowLeft;
readonly Square = Square;
@@ -126,18 +139,33 @@ export class SessionDetailComponent implements OnInit, OnDestroy {
filter((id): id is string => !!id),
switchMap(id => this.sessionService.getSessionById(id).pipe(
catchError(() => of(null))
))
).subscribe(session => {
)),
switchMap(session => {
this.campaignId = null;
this.campaign = null;
this.playthrough = null;
if (!session?.playthroughId) return of({ session, playthrough: null, campaign: null });
return this.playthroughService.getById(session.playthroughId).pipe(
catchError(() => of(null)),
switchMap(playthrough => {
if (!playthrough) return of({ session, playthrough, campaign: null });
return this.campaignService.getCampaignById(playthrough.campaignId).pipe(
catchError(() => of(null)),
map(campaign => ({ session, playthrough, campaign }))
);
})
);
}),
takeUntilDestroyed(this.destroyRef)
).subscribe(({ session, playthrough, campaign }) => {
this.session = session;
this.playthrough = playthrough;
this.campaign = campaign;
this.campaignId = playthrough?.campaignId ?? null;
if (session) {
this.pageTitleService.set(session.name);
this.loadEntries(session.id);
this.loadPinnedScene(session.currentSceneId ?? null);
if (session.playthroughId) {
this.playthroughService.getById(session.playthroughId).pipe(
catchError(() => of(null))
).subscribe(pt => { this.campaignId = pt ? pt.campaignId : null; });
}
}
});
}
@@ -100,7 +100,12 @@ export class SessionRulesPanelComponent implements OnChanges, OnDestroy {
private applySystem(gs: GameSystem | null): void {
this.gameSystem = gs;
if (!gs) { this.state = 'noSystem'; return; }
this.sections = parseRuleSections(gs.rulesMarkdown, this.translate.instant('sessionRules.preamble'));
// Règles dans la langue de l'interface, avec repli sur l'autre version si elle est vide.
const english = this.translate.getCurrentLang() === 'en';
const preferred = english ? gs.rulesMarkdownEn : gs.rulesMarkdown;
const fallback = english ? gs.rulesMarkdown : gs.rulesMarkdownEn;
const rules = preferred?.trim() ? preferred : fallback;
this.sections = parseRuleSections(rules, this.translate.instant('sessionRules.preamble'));
if (this.sections.length === 0) { this.state = 'noRules'; return; }
this.pinned = this.readPins();
this.opened = new Set(this.sections.filter(s => this.pinned.has(s.title)).map(s => s.id));
@@ -141,8 +141,15 @@ export class RemoteAccessSectionComponent implements OnInit, OnDestroy {
formatDate(value?: string | null): string {
if (!value) return '—';
const lang = this.translate.currentLang;
return new Date(value).toLocaleString(lang ? String(lang) : undefined, { dateStyle: 'medium', timeStyle: 'short' });
// getCurrentLang() et non `currentLang` : en ngx-translate 18, `currentLang` est un
// signal ; le convertir en texte donnait une locale invalide → RangeError qui
// interrompait l'affichage de toute la page Paramètres dès qu'un appareil était appairé.
const lang = this.translate.getCurrentLang() === 'en' ? 'en-GB' : 'fr-FR';
try {
return new Date(value).toLocaleString(lang, { dateStyle: 'medium', timeStyle: 'short' });
} catch {
return value;
}
}
private apply(status: RemoteAccessStatus): void {
@@ -11,7 +11,7 @@
class="breadcrumb-link">{{ item.label }}</a>
}
@if (!item.route || last) {
<span class="breadcrumb-text">{{ item.label }}</span>
<span class="breadcrumb-text" [attr.aria-current]="last ? 'page' : null">{{ item.label }}</span>
}
</li>
}
@@ -15,6 +15,8 @@
}
.breadcrumb-item {
min-width: 0;
overflow-wrap: anywhere;
display: inline-flex;
align-items: center;
gap: 0.35rem;
@@ -0,0 +1,33 @@
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { filter } from 'rxjs';
import { LayoutService, SecondarySidebarConfig } from '../../services/layout.service';
import { BreadcrumbComponent } from './breadcrumb.component';
import { campaignBreadcrumbs } from '../navigation-path';
@Component({
selector: 'app-campaign-breadcrumb',
imports: [BreadcrumbComponent],
template: '@if (items.length) { <div class="campaign-path"><app-breadcrumb [items]="items"></app-breadcrumb></div> }',
styles: ['.campaign-path { padding-top: 1rem; overflow-wrap: anywhere; }']
})
export class CampaignBreadcrumbComponent {
private readonly router = inject(Router);
private readonly translate = inject(TranslateService);
private config: SecondarySidebarConfig | null = null;
private url = this.router.url;
constructor() {
const destroyRef = inject(DestroyRef);
inject(LayoutService).secondarySidebar$.pipe(takeUntilDestroyed(destroyRef))
.subscribe(config => this.config = config);
this.router.events.pipe(filter(e => e instanceof NavigationEnd), takeUntilDestroyed(destroyRef))
.subscribe(e => this.url = e.urlAfterRedirects);
}
get items() {
return campaignBreadcrumbs(this.url, this.config, this.translate.instant('common.edit'));
}
}
@@ -1,23 +1,41 @@
@if (open) {
<div class="gs-overlay" (click)="close()">
<div class="gs-modal" (click)="$event.stopPropagation()">
<div class="gs-modal" role="dialog" aria-modal="true" cdkTrapFocus [cdkTrapFocusAutoCapture]="true" [attr.aria-label]="'sidebar.globalSearch' | translate" (click)="$event.stopPropagation()">
<div class="gs-input-row">
<lucide-icon [img]="Search" [size]="18" class="gs-search-icon"></lucide-icon>
<input
#searchInput
cdkFocusInitial
type="text"
class="gs-input"
[attr.aria-label]="'sidebar.globalSearch' | translate"
[placeholder]="'globalSearch.placeholder' | translate"
[ngModel]="query"
(ngModelChange)="onQueryChange($event)" />
<span class="gs-kbd">ESC</span>
<button type="button" class="gs-icon-btn" [attr.aria-label]="'globalSearch.close' | translate" (click)="close()">
<lucide-icon [img]="X" [size]="18"></lucide-icon>
</button>
</div>
@if (results.length > 0) {
@if (loading) {
<div class="gs-empty" role="status">{{ 'globalSearch.loading' | translate }}</div>
}
@if (visibleResults.length > 0) {
<div class="gs-results">
@for (r of results; track r; let i = $index) {
@for (r of visibleResults; track resultUrl(r); let i = $index) {
@if (query.trim().length < 2 && i === 0 && favorites.length > 0) {
<h2 class="gs-section-title">{{ 'globalSearch.favorites' | translate }}</h2>
}
@if (query.trim().length < 2 && i === favorites.length && recent.length > 0) {
<div class="gs-section-header">
<h2 class="gs-section-title">{{ 'globalSearch.recent' | translate }}</h2>
<button type="button" class="gs-clear" (click)="clearRecent()">{{ 'globalSearch.clearRecent' | translate }}</button>
</div>
}
<div class="gs-result-row" [class.active]="i === activeIndex">
<button
type="button"
[id]="'gs-result-' + i"
class="gs-result"
[class.active]="i === activeIndex"
(mouseenter)="activeIndex = i"
(click)="select(r)">
<lucide-icon [img]="iconFor(r.kind)" [size]="16" class="gs-result-icon"></lucide-icon>
@@ -26,9 +44,16 @@
@if (r.subtitle) {
<div class="gs-result-subtitle">{{ r.subtitle }}</div>
}
<div class="gs-result-tag">{{ r.tag }}</div>
@if (r.tag) { <div class="gs-result-tag">{{ r.tag }}</div> }
</div>
</button>
<button type="button" class="gs-icon-btn gs-favorite" [class.starred]="isFavorite(r)"
[attr.aria-pressed]="isFavorite(r)"
[attr.aria-label]="(isFavorite(r) ? 'globalSearch.removeFavorite' : 'globalSearch.addFavorite') | translate:{ name: r.title }"
(click)="toggleFavorite(r)">
<lucide-icon [img]="Star" [size]="18"></lucide-icon>
</button>
</div>
}
</div>
}
@@ -37,9 +62,9 @@
{{ 'globalSearch.noResults' | translate }}
</div>
}
@if (query.trim().length < 2) {
@if (query.trim().length < 2 && visibleResults.length === 0) {
<div class="gs-empty">
{{ 'globalSearch.minChars' | translate }}
{{ 'globalSearch.shortcutsEmpty' | translate }}
</div>
}
<div class="gs-footer">
@@ -48,7 +73,7 @@
<span><kbd>↵</kbd> {{ 'globalSearch.hintSelect' | translate }}</span>
<span><kbd>ESC</kbd> {{ 'globalSearch.hintClose' | translate }}</span>
</div>
@if (results.length > 0) {
@if (query.trim().length >= 2 && results.length > 0) {
<span class="gs-count">
{{ (results.length > 1 ? 'globalSearch.countPlural' : 'globalSearch.countSingular') | translate:{ count: results.length } }}
</span>
@@ -31,6 +31,7 @@
.gs-search-icon { color: #6b7280; flex-shrink: 0; }
.gs-input {
min-width: 0;
flex: 1;
background: transparent;
border: none;
@@ -58,6 +59,7 @@
}
.gs-result {
min-width: 0;
display: flex;
align-items: flex-start;
gap: 0.75rem;
@@ -116,3 +118,38 @@
span { display: flex; align-items: center; gap: 0.3rem; }
}
.gs-result-row {
display: flex;
align-items: center;
&.active { background: rgba(99, 102, 241, 0.18); }
}
.gs-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 44px;
width: 44px;
height: 44px;
border: 0;
border-radius: 6px;
background: transparent;
color: #9ca3af;
cursor: pointer;
&:hover { color: #e5e7eb; background: #2d3145; }
&.starred { color: #fbbf24; }
}
.gs-favorite { margin-right: 0.5rem; }
.gs-section-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; }
.gs-section-title { margin: 0; padding: 0.75rem 1.25rem 0.25rem; font-size: 0.85rem; color: #c4b5fd; }
.gs-clear { padding: 0.5rem 1.25rem; background: none; border: none; color: #9ca3af; cursor: pointer; }
.gs-result:focus-visible, .gs-icon-btn:focus-visible, .gs-clear:focus-visible {
outline: 2px solid #a5b4fc;
outline-offset: -2px;
}
.gs-result-title { overflow-wrap: anywhere; }
@media (max-width: 480px) {
.gs-footer, .gs-hints { flex-wrap: wrap; gap: 0.5rem; }
.gs-input-row { padding: 0.5rem 0.75rem; }
.gs-result { padding: 0.75rem; }
}
@@ -3,9 +3,12 @@ import { Component, ElementRef, HostListener, OnDestroy, OnInit, ViewChild } fro
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, Subject, forkJoin, of } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, switchMap, takeUntil } from 'rxjs/operators';
import { LucideAngularModule, Search, BookOpen, Folder, Users, FileText, Scroll, Drama, User, Dices, Package, Skull } from 'lucide-angular';
import { BehaviorSubject, Subject, forkJoin, of, timer } from 'rxjs';
import { catchError, distinctUntilChanged, switchMap, takeUntil } from 'rxjs/operators';
import { LucideAngularModule, Search, BookOpen, Folder, Users, FileText, Scroll, Drama, User, Dices, Package, Skull, Star, X } from 'lucide-angular';
import { A11yModule } from '@angular/cdk/a11y';
import { NavigationHistoryService } from '../../services/navigation-history.service';
import { NavigationEntry } from '../navigation-history';
import { GlobalSearchService } from '../../services/global-search.service';
import { LoreService } from '../../services/lore.service';
import { PageService } from '../../services/page.service';
@@ -24,10 +27,12 @@ import { Npc } from '../../services/npc.model';
import { RandomTable } from '../../services/random-table.model';
import { ItemCatalog } from '../../services/item-catalog.model';
import { Enemy } from '../../services/enemy.model';
import { CampaignContentHit, campaignContentRoute, campaignContentContext } from '../../services/campaign-content-search.model';
type ResultKind =
| 'lore' | 'node' | 'template' | 'page' | 'campaign'
| 'npc' | 'character' | 'random-table' | 'item-catalog' | 'enemy';
| 'npc' | 'character' | 'random-table' | 'item-catalog' | 'enemy'
| CampaignContentHit['kind'] | 'saved';
interface SearchResult {
/** Optionnel dans les DTOs (objets pas encore persistés) mais toujours
@@ -50,11 +55,13 @@ interface SearchResult {
*/
@Component({
selector: 'app-global-search',
imports: [FormsModule, LucideAngularModule, TranslatePipe],
imports: [FormsModule, LucideAngularModule, TranslatePipe, A11yModule],
templateUrl: './global-search.component.html',
styleUrls: ['./global-search.component.scss']
})
export class GlobalSearchComponent implements OnInit, OnDestroy {
readonly Star = Star;
readonly X = X;
readonly Search = Search;
readonly BookOpen = BookOpen;
readonly Folder = Folder;
@@ -90,12 +97,37 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
private randomTableService: RandomTableService,
private itemCatalogService: ItemCatalogService,
private enemyService: EnemyService,
private translate: TranslateService
private translate: TranslateService,
public history: NavigationHistoryService
) {}
private savedResult(entry: NavigationEntry): SearchResult {
return { id: entry.url, kind: 'saved', title: entry.title, subtitle: entry.subtitle, tag: '', route: [entry.url] };
}
get favorites(): SearchResult[] { return this.history.history().favorites.map(entry => this.savedResult(entry)); }
get recent(): SearchResult[] {
return this.history.history().recent.filter(entry => !this.history.isFavorite(entry.url)).map(entry => this.savedResult(entry));
}
get visibleResults(): SearchResult[] {
return this.query.trim().length < 2 ? [...this.favorites, ...this.recent] : this.results;
}
resultUrl(result: SearchResult): string { return this.router.serializeUrl(this.router.createUrlTree(result.route)); }
isFavorite(result: SearchResult): boolean { return this.history.isFavorite(this.resultUrl(result)); }
toggleFavorite(result: SearchResult): void {
this.history.toggle({ url: this.resultUrl(result), title: result.title, subtitle: result.subtitle });
this.activeIndex = Math.min(this.activeIndex, Math.max(0, this.visibleResults.length - 1));
}
clearRecent(): void { this.history.clearRecent(); this.activeIndex = 0; }
private scrollToActive(): void {
setTimeout(() => document.getElementById('gs-result-' + this.activeIndex)?.scrollIntoView({ block: 'nearest' }), 0);
}
ngOnInit(): void {
this.globalSearch.open$.pipe(takeUntil(this.destroy$)).subscribe(open => {
this.open = open;
this.queryChanges$.next('');
if (open) {
this.query = '';
this.results = [];
@@ -106,16 +138,17 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
});
this.queryChanges$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap(q => {
this.results = [];
this.activeIndex = 0;
const trimmed = q.trim();
if (trimmed.length < 2) {
this.loading = false;
return of<SearchResult[]>([]);
}
this.loading = true;
return forkJoin({
return timer(200).pipe(switchMap(() => forkJoin({
lores: this.loreService.searchLores(trimmed).pipe(catchError(() => of([]))),
nodes: this.loreService.searchLoreNodes(trimmed).pipe(catchError(() => of([]))),
templates: this.templateService.search(trimmed).pipe(catchError(() => of([]))),
@@ -125,8 +158,9 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
characters: this.characterService.search(trimmed).pipe(catchError(() => of([]))),
tables: this.randomTableService.search(trimmed).pipe(catchError(() => of([]))),
catalogs: this.itemCatalogService.search(trimmed).pipe(catchError(() => of([]))),
enemies: this.enemyService.search(trimmed).pipe(catchError(() => of([])))
}).pipe(
enemies: this.enemyService.search(trimmed).pipe(catchError(() => of([]))),
content: this.campaignService.searchContent(trimmed).pipe(catchError(() => of([])))
})),
switchMap(r => of(this.buildResults(r))),
catchError(() => of<SearchResult[]>([]))
);
@@ -151,7 +185,7 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
*/
private buildResults(r: {
lores: Lore[]; nodes: LoreNode[]; templates: Template[]; pages: Page[]; campaigns: Campaign[];
npcs: Npc[]; characters: CharacterSearchResult[]; tables: RandomTable[]; catalogs: ItemCatalog[]; enemies: Enemy[];
npcs: Npc[]; characters: CharacterSearchResult[]; tables: RandomTable[]; catalogs: ItemCatalog[]; enemies: Enemy[]; content: CampaignContentHit[];
}): SearchResult[] {
const { lores, nodes, templates, pages, campaigns, npcs, characters, tables, catalogs, enemies } = r;
const pageResults: SearchResult[] = pages.map(p => ({
@@ -236,6 +270,12 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
}));
return [
...pageResults,
...r.content.map(hit => ({
id: hit.id, kind: hit.kind, title: hit.name,
subtitle: campaignContentContext(hit),
tag: this.translate.instant('globalSearch.tags.' + hit.kind),
route: campaignContentRoute(hit)
})).filter(hit => hit.route.length > 0),
...npcResults, ...characterResults, ...enemyResults, ...tableResults, ...catalogResults,
...nodeResults, ...templateResults,
...campaignResults, ...loreResults
@@ -248,6 +288,7 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
}
select(result: SearchResult): void {
this.history.visit(this.resultUrl(result), result.title, result.subtitle);
this.router.navigate(result.route);
this.globalSearch.close();
}
@@ -263,19 +304,24 @@ export class GlobalSearchComponent implements OnInit, OnDestroy {
if (event.key === 'Escape') {
event.preventDefault();
this.close();
} else if (event.target !== this.searchInput?.nativeElement) {
// Native buttons (including stars) keep their own Enter/Space behavior.
return;
} else if (event.key === 'ArrowDown') {
event.preventDefault();
if (this.results.length > 0) {
this.activeIndex = (this.activeIndex + 1) % this.results.length;
if (this.visibleResults.length > 0) {
this.activeIndex = (this.activeIndex + 1) % this.visibleResults.length;
this.scrollToActive();
}
} else if (event.key === 'ArrowUp') {
event.preventDefault();
if (this.results.length > 0) {
this.activeIndex = (this.activeIndex - 1 + this.results.length) % this.results.length;
if (this.visibleResults.length > 0) {
this.activeIndex = (this.activeIndex - 1 + this.visibleResults.length) % this.visibleResults.length;
this.scrollToActive();
}
} else if (event.key === 'Enter') {
event.preventDefault();
const r = this.results[this.activeIndex];
const r = this.visibleResults[this.activeIndex];
if (r) this.select(r);
}
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest';
import { contentUrl, readHistory, rememberVisit, toggleFavorite } from './navigation-history';
const scene = { url: '/campaigns/1/arcs/2/chapters/3/scenes/4', title: 'La taverne', subtitle: 'Les Ombres' };
describe('navigation shortcuts', () => {
it('keeps a bounded, deduplicated recent list and refreshes renamed favorites', () => {
let state = toggleFavorite({ recent: [], favorites: [] }, scene);
for (let i = 0; i < 20; i++) state = rememberVisit(state, { ...scene, url: '/lore/' + i });
state = rememberVisit(state, scene);
state = rememberVisit(state, { ...scene, title: 'La nouvelle taverne' });
expect(state.recent).toHaveLength(12);
expect(state.recent[0].title).toBe('La nouvelle taverne');
expect(state.favorites[0].title).toBe('La nouvelle taverne');
expect(state.recent.filter(item => item.url === scene.url)).toHaveLength(1);
});
it('removes a favorite without removing its recent visit', () => {
const visited = rememberVisit({ recent: [], favorites: [] }, scene);
expect(toggleFavorite(toggleFavorite(visited, scene), scene)).toEqual(visited);
});
it('ignores broken storage, unsafe URLs and duplicate entries', () => {
expect(readHistory('{broken')).toEqual({ recent: [], favorites: [] });
const saved = readHistory(JSON.stringify({ recent: [scene, scene, { ...scene, url: 'https://example.com' }, null], favorites: [scene] }));
expect(saved).toEqual({ recent: [scene], favorites: [scene] });
});
it('never records creation or editing forms and drops query parameters', () => {
expect(contentUrl(scene.url + '?edit=1#notes')).toBe(scene.url);
for (const url of [scene.url + '/edit', '/lore/1/pages/create', '/campaigns/1/guided/five-room', '//evil.test', '/settings']) {
expect(contentUrl(url)).toBeNull();
}
});
});
+52
View File
@@ -0,0 +1,52 @@
export interface NavigationEntry {
url: string;
title: string;
subtitle: string;
}
export interface NavigationHistory {
recent: NavigationEntry[];
favorites: NavigationEntry[];
}
/** Only saved content pages, never forms, query parameters or external URLs. */
export function contentUrl(url: string): string | null {
const path = url.split(/[?#]/)[0];
if (!/^\/(campaigns|lore|sessions)\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path)) return null;
if (/(?:^|\/)(create|edit|import|guided|publication|flags)(?:\/|$)/.test(path)) return null;
return path;
}
export function readHistory(raw: string | null): NavigationHistory {
const empty: NavigationHistory = { recent: [], favorites: [] };
try {
const data: unknown = JSON.parse(raw ?? 'null');
if (!data || typeof data !== 'object') return empty;
const clean = (value: unknown): NavigationEntry[] => {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
return value.filter((entry): entry is NavigationEntry => {
if (!entry || typeof entry.url !== 'string' || contentUrl(entry.url) !== entry.url ||
typeof entry.title !== 'string' || !entry.title.trim() || typeof entry.subtitle !== 'string' || seen.has(entry.url)) return false;
seen.add(entry.url);
return true;
});
};
const saved = data as Partial<NavigationHistory>;
return { recent: clean(saved.recent).slice(0, 12), favorites: clean(saved.favorites) };
} catch { return empty; }
}
export function rememberVisit(history: NavigationHistory, entry: NavigationEntry): NavigationHistory {
return {
recent: [entry, ...history.recent.filter(item => item.url !== entry.url)].slice(0, 12),
favorites: history.favorites.map(item => item.url === entry.url ? entry : item)
};
}
export function toggleFavorite(history: NavigationHistory, entry: NavigationEntry): NavigationHistory {
const exists = history.favorites.some(item => item.url === entry.url);
return { ...history, favorites: exists
? history.favorites.filter(item => item.url !== entry.url)
: [...history.favorites, entry] };
}
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest';
import { campaignBreadcrumbs, isWithinRoute } from './navigation-path';
import type { SecondarySidebarConfig } from '../services/layout.service';
const root = '/campaigns/1';
const arc = root + '/arcs/2';
const chapter = arc + '/chapters/3';
const scene = chapter + '/scenes/4';
const config: SecondarySidebarConfig = {
title: 'Les Ombres', titleRoute: root, globalItems: [], globalBackLabel: '', globalBackRoute: '/campaigns',
createActions: [{ id: 'arc', label: 'Nouvel arc', variant: 'primary', route: root + '/arcs/create' }],
items: [{ id: 'arc', label: 'Le port', route: arc, children: [
{ id: 'chapter', label: 'La nuit', route: chapter, children: [
{ id: 'scene', label: 'La taverne', route: scene }
], createActions: [{ id: 'scene', label: 'Nouvelle scène', route: chapter + '/scenes/create' }] }
] }]
};
describe('navigation context', () => {
it('keeps the current campaign selected without matching a different numeric ID', () => {
expect(isWithinRoute(scene + '?tab=notes#title', root)).toBe(true);
expect(isWithinRoute('/campaigns/10/arcs/2', root)).toBe(false);
expect(isWithinRoute('/lore/1', root)).toBe(false);
});
it('allows returning from a scene to each named ancestor', () => {
expect(campaignBreadcrumbs(scene, config, 'Modifier')).toEqual([
{ label: 'Les Ombres', route: root }, { label: 'Le port', route: arc },
{ label: 'La nuit', route: chapter }, { label: 'La taverne', route: scene }
]);
});
it('links back to the scene while editing and to the parent while creating', () => {
expect(campaignBreadcrumbs(scene + '/edit', config, 'Modifier').at(-1)).toEqual({ label: 'Modifier' });
expect(campaignBreadcrumbs(chapter + '/scenes/create', config, 'Modifier').map(i => i.label))
.toEqual(['Les Ombres', 'Le port', 'La nuit', 'Nouvelle scène']);
expect(campaignBreadcrumbs(root + '/arcs/create', config, 'Modifier').map(i => i.label))
.toEqual(['Les Ombres', 'Nouvel arc']);
});
it('preserves the visible quest hierarchy instead of revealing its system arc', () => {
const questConfig = { ...config, items: [{ id: 'quests', label: 'Quêtes', children: [
{ id: 'quest', label: 'Le témoin', route: root + '/quests/5', children: [
{ id: 'scene', label: 'La taverne', route: scene }
] }
] }] };
expect(campaignBreadcrumbs(scene, questConfig, 'Modifier').map(i => i.label))
.toEqual(['Les Ombres', 'Quêtes', 'Le témoin', 'La taverne']);
});
it('uses the scenes graph as parent for a flattened campaign', () => {
const flat = { ...config, items: [{ id: 'chapter', label: 'Scènes', route: chapter + '/graph', children: [
{ id: 'scene', label: 'La taverne', route: scene }
] }] };
expect(campaignBreadcrumbs(scene, flat, 'Modifier')[1]).toEqual({ label: 'Scènes', route: chapter + '/graph' });
});
it('does not show stale context or invent a title for an unknown page', () => {
for (const path of [root, '/campaigns/10/arcs/2', root + '/npcs/9', '/lore/1']) {
expect(campaignBreadcrumbs(path, config, 'Modifier')).toEqual([]);
}
});
});

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