Export PDF : mise en page module (renvois, annexes MJ, cartes pleine page)
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 46s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 54s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 54s

- Renvois internes : les sorties d'une scène, les adversaires d'un combat et
  les nœuds d'une quête renvoient à leur cible avec son numéro de page
  (« La crypte (p. 12) », « Goule (p. 24) »). Un renvoi vers une partie non
  exportée devient du texte simple (pas de numéro faux ou vide).
- Annexes MJ (nouvelle partie, jamais en version joueurs) :
  - Révélations et indices : pour chaque révélation, les scènes qui y mènent,
    leur page et la nature du lien (indice, piste) ; signalée si rien n'y mène.
  - Index des PNJ et index des adversaires (dossier, niveau, scènes où chaque
    adversaire apparaît, page de la fiche).
- Cartes en pleine page : chaque battlemap et chaque plan de pièce sur sa
  propre page paysage, en plus haute résolution, prête à imprimer ; la scène
  y renvoie au lieu de l'afficher en petit.
- Fenêtre d'export : cases « Annexes MJ » et « Cartes en pleine page »
  (version joueurs : cartes cochées, annexes non).

Vérifié : core clean verify (1264 tests, dont renvois, renvois morts
neutralisés, annexes, version joueurs sans annexe, pages paysage dans le
PDF réel), web build + 367 vitest, lint sans erreur, rendu visuel du livret
de démonstration en A4 et A5.
À redéployer : core + web (aucune migration).
This commit is contained in:
2026-10-17 16:40:20 +02:00
parent cbd59a5bd9
commit dae0508c93
15 changed files with 636 additions and 69 deletions
@@ -0,0 +1,230 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.domain.campaigncontext.structure.LinkType;
import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneType;
import com.loremind.infrastructure.persistence.entity.ArcJpaEntity;
import com.loremind.infrastructure.persistence.entity.ChapterJpaEntity;
import com.loremind.infrastructure.persistence.entity.SceneJpaEntity;
import java.util.*;
import static com.loremind.infrastructure.transfer.pdf.PdfHtml.*;
/**
* Annexes d'un module publie : ce que le MJ consulte en jeu sans feuilleter tout le livret.
* <ul>
* <li>Revelations et indices : pour chaque revelation, les scenes qui y menent (et leur page) —
* le MJ voit d'un coup d'oeil ce que les joueurs peuvent encore decouvrir ;</li>
* <li>index des PNJ et des adversaires (avec les scenes ou ces derniers apparaissent) ;</li>
* <li>cartes : chaque battlemap et plan de piece sur sa propre page paysage, en grand,
* prete a imprimer ou a montrer aux joueurs.</li>
* </ul>
* Les renvois vers des parties absentes sont neutralises en fin de rendu ({@link PdfHtml#resolveRefs}).
*/
final class PdfAppendices {
/** Une carte rendue en pleine page paysage dans l'annexe. */
record MapPage(String anchor, String title, PdfImage image) {}
/** Ligne d'index (PNJ ou adversaire). */
record IndexRow(String anchor, String name, String folder, String level) {}
/** Resolution des cartes en annexe (plus fine que les illustrations : elles sont imprimees en grand). */
static final int MAP_MAX = 2400;
private static final String TD_OPEN = "<td>";
private static final String TD_CLOSE = "</td>";
private PdfAppendices() {}
// ====================================================================== Cartes
/**
* Cartes de chaque scene, dans l'ordre du livret : battlemaps (images uniquement) puis
* plans des pieces. Encodees UNE fois : la scene y renvoie, l'annexe les affiche.
*/
static Map<Long, List<MapPage>> collectMaps(Structure st, PdfImageEncoder encoder) {
Map<Long, List<MapPage>> maps = new LinkedHashMap<>();
for (SceneJpaEntity sc : scenesInOrder(st)) {
List<MapPage> pages = new ArrayList<>();
if (sc.getBattlemaps() != null) {
int i = 0;
for (var bm : sc.getBattlemaps()) {
PdfImage img = encoder.fileImage(bm.mediaFileId(), MAP_MAX);
if (img == null) continue;
String label = notBlank(bm.label()) ? sc.getName() + " — " + bm.label().trim() : sc.getName();
pages.add(new MapPage("map-" + sc.getId() + "-" + (i++), label, img));
}
}
if (sc.getRooms() != null) {
List<Room> rooms = new ArrayList<>(sc.getRooms());
rooms.sort(Comparator.comparingInt(Room::getOrder));
for (Room r : rooms) {
PdfImage img = encoder.image(r.getMapImageId(), MAP_MAX);
if (img != null) {
pages.add(new MapPage(roomMapAnchor(sc.getId(), r.getId()),
sc.getName() + " — Plan : " + r.getName(), img));
}
}
}
if (!pages.isEmpty()) maps.put(sc.getId(), pages);
}
return maps;
}
static String roomMapAnchor(Long sceneId, String roomId) {
return "map-room-" + sceneId + "-" + (roomId == null ? "x" : roomId.replaceAll("[^A-Za-z0-9_-]", ""));
}
/**
* Partie « Cartes » : une carte par page paysage (page nommee {@code landscape}), titre
* en tete, image la plus grande possible sans deformation.
*/
static void mapsPart(PdfExportService.Ctx ctx, Map<Long, List<MapPage>> maps) {
if (maps.isEmpty()) return;
StringBuilder b = ctx.body;
PdfExportOptions.PageFormat format = ctx.opt.format();
// Page paysage : largeur = hauteur du format portrait. Marges 1 cm, ~1,6 cm pour le titre.
double pageW = format.landscapeWidthCm() - 2.0;
double pageH = format.widthCm - 2.0 - 1.6;
StringBuilder bms = new StringBuilder();
boolean first = true;
for (List<MapPage> pages : maps.values()) {
for (MapPage p : pages) {
b.append("<div class=\"map-page\"");
if (first) b.append(" id=\"part-maps\"");
b.append("><div class=\"map-title\" id=\"").append(p.anchor()).append("\">")
.append(esc(p.title())).append("</div>");
double w = Math.min(pageW, pageH * p.image().w() / p.image().h());
b.append("<img style=\"width:").append(cm(w)).append("\" src=\"").append(p.image().uri()).append("\"/>");
b.append(DIV_CLOSE);
bms.append(bookmark(p.title(), p.anchor(), ""));
first = false;
}
}
ctx.addToc(0, "Cartes", "part-maps");
ctx.bookmarks.append(bookmark("Cartes", "part-maps", bms.toString()));
}
// ====================================================================== Annexes MJ
/** Revelations et indices : chaque scene REVELATION, et les scenes qui y menent. */
static void revelations(StringBuilder b, Structure st) {
List<SceneJpaEntity> scenes = scenesInOrder(st);
List<SceneJpaEntity> revelations = scenes.stream()
.filter(s -> s.getType() == SceneType.REVELATION).toList();
if (revelations.isEmpty()) return;
b.append("<h2 class=\"section-head\" id=\"annex-revelations\">Révélations et indices</h2>");
b.append("<p class=\"prose annex-intro\">Pour chaque révélation, les scènes qui permettent de la "
+ "découvrir. Visez au moins trois chemins : les joueurs en manqueront toujours un.</p>");
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Révélation</th>"
+ "<th>Y mènent</th></tr></thead><tbody>");
int row = 0;
for (SceneJpaEntity rev : revelations) {
String anchor = "scene-" + rev.getId();
b.append(trTag(row++)).append(TD_OPEN).append(xref(anchor, rev.getName())).append(' ')
.append(pageRef(anchor)).append(TD_CLOSE).append(TD_OPEN);
List<String> sources = incoming(rev, scenes);
if (sources.isEmpty()) {
b.append("<span class=\"annex-warn\">Aucune scène n'y mène.</span>");
} else {
b.append("<ul class=\"annex-list\">");
for (String s : sources) b.append("<li>").append(s).append("</li>");
b.append("</ul>");
}
b.append(TD_TR_CLOSE);
}
b.append(TBODY_TABLE_CLOSE);
}
/** Scenes (du meme chapitre) qui ont un lien vers {@code target}, en HTML avec renvoi. */
private static List<String> incoming(SceneJpaEntity target, List<SceneJpaEntity> scenes) {
String targetId = String.valueOf(target.getId());
List<String> out = new ArrayList<>();
for (SceneJpaEntity s : scenes) {
if (s.getBranches() == null || Objects.equals(s.getId(), target.getId())) continue;
for (SceneBranch br : s.getBranches()) {
if (!targetId.equals(br.targetSceneId())) continue;
String anchor = "scene-" + s.getId();
StringBuilder line = new StringBuilder(xref(anchor, s.getName())).append(' ').append(pageRef(anchor));
if (br.kind() == LinkType.CLUE) line.append(" <span class=\"annex-kind\">indice</span>");
else if (br.kind() == LinkType.LEAD) line.append(" <span class=\"annex-kind\">piste</span>");
if (notBlank(br.label())) line.append(" — ").append(esc(br.label().trim()));
out.add(line.toString());
break; // une ligne par scene source
}
}
return out;
}
/** Index alphabetique : nom (renvoi), dossier, niveau eventuel, apparitions eventuelles, page. */
static void index(StringBuilder b, String anchorId, String title, List<IndexRow> rows,
Map<String, List<String>> appearances) {
if (rows.isEmpty()) return;
List<IndexRow> sorted = new ArrayList<>(rows);
sorted.sort(Comparator.comparing(r -> r.name() == null ? "" : r.name().toLowerCase(Locale.ROOT)));
boolean withLevel = sorted.stream().anyMatch(r -> notBlank(r.level()));
boolean withAppearances = appearances != null && !appearances.isEmpty();
b.append("<h2 class=\"section-head\" id=\"").append(anchorId).append("\">").append(esc(title)).append("</h2>");
b.append("<table class=\"stats-table annex-table\"><thead><tr><th>Nom</th><th>Dossier</th>");
if (withLevel) b.append("<th>Niv.</th>");
if (withAppearances) b.append("<th>Apparaît dans</th>");
b.append("<th class=\"page-col\">Page</th></tr></thead><tbody>");
int row = 0;
for (IndexRow r : sorted) {
b.append(trTag(row++)).append(TD_OPEN).append(xref(r.anchor(), r.name())).append(TD_CLOSE)
.append(TD_OPEN).append(esc(notBlank(r.folder()) ? r.folder().replace("/", " / ") : "—")).append(TD_CLOSE);
if (withLevel) b.append(TD_OPEN).append(esc(notBlank(r.level()) ? r.level() : "—")).append(TD_CLOSE);
if (withAppearances) {
List<String> where = appearances.getOrDefault(r.anchor(), List.of());
b.append(TD_OPEN).append(where.isEmpty() ? "—" : String.join(", ", where)).append(TD_CLOSE);
}
b.append("<td class=\"page-col\">").append(pageRef(r.anchor())).append(TD_TR_CLOSE);
}
b.append(TBODY_TABLE_CLOSE);
}
/**
* Ou apparait chaque adversaire : ancre de sa fiche ({@code enemy-<id>}) -&gt; scenes
* (renvois) qui le citent, dans la scene elle-meme ou dans l'une de ses pieces.
*/
static Map<String, List<String>> enemyAppearances(Structure st) {
Map<String, Set<Long>> sceneIdsByEnemy = new LinkedHashMap<>();
Map<Long, SceneJpaEntity> byId = new LinkedHashMap<>();
for (SceneJpaEntity sc : scenesInOrder(st)) {
byId.put(sc.getId(), sc);
List<String> ids = new ArrayList<>();
if (sc.getEnemyIds() != null) ids.addAll(sc.getEnemyIds());
if (sc.getRooms() != null) {
for (Room r : sc.getRooms()) if (r.getEnemyIds() != null) ids.addAll(r.getEnemyIds());
}
for (String id : ids) {
if (notBlank(id)) sceneIdsByEnemy.computeIfAbsent("enemy-" + id.trim(), k -> new LinkedHashSet<>()).add(sc.getId());
}
}
Map<String, List<String>> out = new LinkedHashMap<>();
sceneIdsByEnemy.forEach((enemyAnchor, sceneIds) -> {
List<String> refs = new ArrayList<>();
for (Long sid : sceneIds) {
String anchor = "scene-" + sid;
refs.add(xref(anchor, byId.get(sid).getName()) + " " + pageRef(anchor));
}
out.put(enemyAnchor, refs);
});
return out;
}
/** Toutes les scenes dans l'ordre du livret (arcs, chapitres, scenes). */
private static List<SceneJpaEntity> scenesInOrder(Structure st) {
List<SceneJpaEntity> out = new ArrayList<>();
for (ArcJpaEntity arc : st.arcs) {
for (ChapterJpaEntity ch : st.chaptersByArc.getOrDefault(arc.getId(), List.of())) {
out.addAll(st.scenesByChapter.getOrDefault(ch.getId(), List.of()));
}
}
return out;
}
}
@@ -17,8 +17,12 @@ import java.util.Set;
public record PdfExportOptions(boolean gmContent, PageFormat format, boolean printFriendly,
Set<Section> sections, LoreScope loreScope) {
/** Parties du livret qu'on peut inclure ou non. */
public enum Section { NARRATIVE, QUESTS, NPCS, ENEMIES, TABLES, LORE }
/**
* Parties du livret qu'on peut inclure ou non. APPENDIX = annexes MJ (revelations et
* indices, index PNJ et adversaires ; jamais en version joueurs) ; MAPS = cartes en
* pleine page paysage (les scenes y renvoient au lieu de les afficher en petit).
*/
public enum Section { NARRATIVE, QUESTS, NPCS, ENEMIES, TABLES, LORE, APPENDIX, MAPS }
/** Pages de lore exportées : toutes, ou seulement celles liées au contenu de la campagne. */
public enum LoreScope { ALL, LINKED }
@@ -28,12 +32,13 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
* A5 : marges et corps réduits pour garder une ligne lisible sur une page étroite.
*/
public enum PageFormat {
A4("A4", 21.0, 2.2, 1.7, 2.0, 10.0, 12.5),
A5("A5", 14.8, 1.7, 1.3, 1.6, 9.0, 7.0),
LETTER("letter", 21.59, 2.2, 1.8, 2.0, 10.0, 12.0);
A4("A4", 21.0, 29.7, 2.2, 1.7, 2.0, 10.0, 12.5),
A5("A5", 14.8, 21.0, 1.7, 1.3, 1.6, 9.0, 7.0),
LETTER("letter", 21.59, 27.94, 2.2, 1.8, 2.0, 10.0, 12.0);
final String cssSize;
final double widthCm;
final double heightCm;
final double marginTopCm;
final double marginSideCm;
final double marginBottomCm;
@@ -41,10 +46,11 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
/** Hauteur max de l'illustration de couverture : la couverture tient sur une page. */
final double coverArtMaxCm;
PageFormat(String cssSize, double widthCm, double marginTopCm, double marginSideCm,
PageFormat(String cssSize, double widthCm, double heightCm, double marginTopCm, double marginSideCm,
double marginBottomCm, double bodyPt, double coverArtMaxCm) {
this.cssSize = cssSize;
this.widthCm = widthCm;
this.heightCm = heightCm;
this.marginTopCm = marginTopCm;
this.marginSideCm = marginSideCm;
this.marginBottomCm = marginBottomCm;
@@ -52,6 +58,11 @@ public record PdfExportOptions(boolean gmContent, PageFormat format, boolean pri
this.coverArtMaxCm = coverArtMaxCm;
}
/** Largeur d'une page tournée en paysage (= hauteur en portrait). */
double landscapeWidthCm() {
return heightCm;
}
/** Largeur utile (page moins les deux marges latérales). */
double contentWidthCm() {
return widthCm - 2 * marginSideCm;
@@ -178,11 +178,13 @@ public class PdfExportService {
* Contexte de rendu : les sections ecrivent leur corps et alimentent les signets,
* le sommaire et les compteurs (repris ensuite sur la couverture).
*/
private static final class Ctx {
static final class Ctx {
final PdfExportOptions opt;
/** Version MJ : les contenus reserves au MJ (secrets, consequences, combats...) sont rendus. */
final boolean gm;
final StringBuilder body = new StringBuilder();
/** Cartes rendues en annexe (par scene), ou null si l'annexe Cartes n'est pas demandee. */
Map<Long, List<PdfAppendices.MapPage>> maps;
final StringBuilder bookmarks = new StringBuilder();
final List<TocEntry> toc = new ArrayList<>();
int scenes;
@@ -226,33 +228,60 @@ public class PdfExportService {
// et le sommaire sont assembles ensuite en tete de document.
Structure st = structureLoader.load(campaign);
Ctx ctx = new Ctx(opt);
// Cartes encodees d'abord : les scenes y renvoient au lieu de les afficher en petit.
if (opt.includes(Section.MAPS)) ctx.maps = PdfAppendices.collectMaps(st, imageEncoder);
List<PersonaRow> npcRows = opt.includes(Section.NPCS) ? npcEntries(campaign) : List.of();
List<PersonaRow> enemyRows = opt.includes(Section.ENEMIES) ? enemyEntries(campaign) : List.of();
introduction(ctx, campaign, pub, st);
if (opt.includes(Section.NARRATIVE)) narrative(ctx, st);
if (opt.includes(Section.QUESTS)) {
ctx.quests = st.quests.size();
quests(ctx, st);
}
if (opt.includes(Section.NPCS)) {
personas(ctx, "part-npcs", "Personnages non-joueurs (PNJ)", npcEntries(campaign), npcTemplate, false);
}
if (opt.includes(Section.ENEMIES)) {
personas(ctx, "part-enemies", "Bestiaire", enemyEntries(campaign), enemyTemplate, true);
}
personas(ctx, "part-npcs", "Personnages non-joueurs (PNJ)", npcRows, npcTemplate, false);
personas(ctx, "part-enemies", "Bestiaire", enemyRows, enemyTemplate, true);
if (opt.includes(Section.TABLES)) randomTables(ctx, campaign);
if (opt.includes(Section.LORE)) lore(ctx, campaign, st);
if (opt.includes(Section.APPENDIX) && ctx.gm) appendix(ctx, st, npcRows, enemyRows);
if (ctx.maps != null) PdfAppendices.mapsPart(ctx, ctx.maps);
StringBuilder full = new StringBuilder();
cover(full, ctx, campaign, pub);
creditsPage(full, campaign, pub);
full.append(tocHtml(ctx.toc));
full.append(ctx.body);
String body = resolveRefs(full.toString());
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr\" xml:lang=\"fr\"><head><meta charset=\"utf-8\"/>\n"
+ documentInfo(campaign, pub)
+ "<style>" + cssFor(campaign.getName(), opt) + "</style>\n"
+ "<bookmarks>" + ctx.bookmarks + "</bookmarks>\n"
+ "</head><body>" + full + "</body></html>";
+ "</head><body>" + body + "</body></html>";
}
/**
* Annexes MJ : revelations et indices, index des PNJ et des adversaires (avec leurs
* apparitions). Les index ne listent que les fiches presentes dans le livret.
*/
private void appendix(Ctx ctx, Structure st, List<PersonaRow> npcRows, List<PersonaRow> enemyRows) {
StringBuilder annex = new StringBuilder();
PdfAppendices.revelations(annex, st);
PdfAppendices.index(annex, "annex-npcs", "Index des PNJ", indexRows(npcRows, "npc-"), null);
PdfAppendices.index(annex, "annex-enemies", "Index des adversaires", indexRows(enemyRows, "enemy-"),
PdfAppendices.enemyAppearances(st));
if (annex.isEmpty()) return;
ctx.body.append("<h1 class=\"part\" id=\"part-annex\">Annexes</h1>").append(annex);
ctx.addToc(0, "Annexes", "part-annex");
ctx.bookmarks.append(bookmark("Annexes", "part-annex", ""));
}
private static List<PdfAppendices.IndexRow> indexRows(List<PersonaRow> rows, String anchorPrefix) {
List<PdfAppendices.IndexRow> out = new ArrayList<>();
for (PersonaRow r : rows) {
out.add(new PdfAppendices.IndexRow(anchorPrefix + r.id(), r.name(), r.folder(), r.level()));
}
return out;
}
/**
@@ -550,7 +579,7 @@ public class PdfExportService {
illustrations(ctx, fused.getIllustrationImageIds());
ctx.gmBlock(LABEL_DESCRIPTION, mergeField(ch.getDescription(), fused.getDescription()));
ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(fused.getPrerequisites(), st.questNames));
ctx.gmBlock(LABEL_NOEUDS, renderQuestNodes(fused, st));
if (ctx.gm) blockHtml(ctx.body, LABEL_NOEUDS, questNodeItems(fused, st));
block(ctx.body, LABEL_OBJECTIFS_JOUEURS, mergeField(ch.getPlayerObjectives(), fused.getPlayerObjectives()));
ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, mergeField(ch.getNarrativeStakes(), fused.getNarrativeStakes()));
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, mergeField(ch.getGmNotes(), fused.getGmNotes()));
@@ -603,13 +632,16 @@ public class PdfExportService {
box(b, "readaloud", "À lire aux joueurs", sc.getPlayerNarration());
ctx.gmBox(CSS_SECRET, "Notes secrètes MJ", sc.getGmSecretNotes());
ctx.gmBlock("Choix et conséquences", sc.getChoicesConsequences());
ctx.gmBlock("Sorties", renderSceneBranches(sc.getBranches(), st));
// Combat : difficulte + ennemis de la rencontre (refs bestiaire resolues en noms
// + texte libre) dans le meme encadre rouge.
ctx.gmBox("combat", "Combat", joinNonBlank(sc.getCombatDifficulty(),
enemyLines(sc.getEnemyIds(), sc.getEnemies(), st)));
if (ctx.gm) blockHtml(b, "Sorties", sceneBranchItems(sc.getBranches(), st));
// Combat : difficulte + ennemis de la rencontre (fiches du bestiaire en renvoi
// « p. N » + texte libre) dans le meme encadre rouge.
combatBox(ctx, "Combat", sc.getCombatDifficulty(), sc.getEnemyIds(), sc.getEnemies(), st);
illustrations(ctx, sc.getIllustrationImageIds());
if (ctx.maps != null) {
mapLinks(ctx, sc);
} else {
sceneBattlemaps(ctx, sc);
}
rooms(ctx, sc, st);
b.append(DIV_CLOSE);
}
@@ -632,6 +664,16 @@ public class PdfExportService {
}
}
/** Annexe Cartes demandee : la scene renvoie a ses cartes pleine page (« p. N »). */
private static void mapLinks(Ctx ctx, SceneJpaEntity sc) {
List<String> items = new ArrayList<>();
String prefix = "map-" + sc.getId() + "-";
for (PdfAppendices.MapPage p : ctx.maps.getOrDefault(sc.getId(), List.of())) {
if (p.anchor().startsWith(prefix)) items.add(xref(p.anchor(), p.title()) + " " + pageRef(p.anchor()));
}
blockHtml(ctx.body, "Cartes", items);
}
/**
* Battlemaps (images uniquement ; les videos ne sont pas rendables en PDF). Le libellé
* de la variante (Jour/Nuit…) est rendu en légende sous l'image.
@@ -664,12 +706,11 @@ public class PdfExportService {
if (r.getFloor() != null) b.append(" · Étage ").append(r.getFloor());
b.append(SPAN_CLOSE).append(esc(r.getName())).append(DIV_CLOSE);
ctx.gmBlock(LABEL_DESCRIPTION, r.getDescription());
ctx.gmBox("combat", "Ennemis", enemyLines(r.getEnemyIds(), r.getEnemies(), st));
combatBox(ctx, "Ennemis", null, r.getEnemyIds(), r.getEnemies(), st);
ctx.gmBlock("Butin", r.getLoot());
ctx.gmBlock("Pièges", r.getTraps());
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, r.getGmNotes());
PdfImage map = imageEncoder.image(r.getMapImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
if (map != null) illustration(ctx, map, "Plan — " + r.getName());
roomMap(ctx, sc, r);
illustrations(ctx, r.getIllustrationImageIds());
if (ctx.gm && r.getBranches() != null && !r.getBranches().isEmpty()) {
List<String> parts = new ArrayList<>();
@@ -683,20 +724,42 @@ public class PdfExportService {
}
}
/** Sorties narratives d'une scene, cibles resolues en noms de scenes. */
private String renderSceneBranches(List<SceneBranch> branches, Structure st) {
if (branches == null || branches.isEmpty()) return null;
List<String> parts = new ArrayList<>();
/** Plan d'une piece : en annexe pleine page si demandee (renvoi), sinon en illustration. */
private void roomMap(Ctx ctx, SceneJpaEntity sc, Room r) {
if (ctx.maps != null) {
String anchor = PdfAppendices.roomMapAnchor(sc.getId(), r.getId());
boolean inAnnex = ctx.maps.getOrDefault(sc.getId(), List.of()).stream()
.anyMatch(p -> p.anchor().equals(anchor));
if (inAnnex) blockHtml(ctx.body, "Plan", List.of("carte en annexe " + pageRef(anchor)));
return;
}
PdfImage map = imageEncoder.image(r.getMapImageId(), PdfImageEncoder.ILLUSTRATION_MAX);
if (map != null) illustration(ctx, map, "Plan — " + r.getName());
}
/**
* Sorties narratives d'une scene en HTML : nom de la scene cible cliquable et sa page
* (« Vers « La crypte » (p. 12) — Si les PJ fouillent [indice] »).
*/
private static List<String> sceneBranchItems(List<SceneBranch> branches, Structure st) {
List<String> items = new ArrayList<>();
if (branches == null) return items;
for (SceneBranch br : branches) {
String anchor = "scene-" + br.targetSceneId();
StringBuilder line = new StringBuilder("Vers « ")
.append(xref(anchor, st.sceneNames.getOrDefault(br.targetSceneId(), "?")))
.append(" » ").append(pageRef(anchor));
if (notBlank(br.label())) line.append(" — ").append(esc(br.label().trim()));
String kind = switch (br.kind()) {
case CLUE -> "indice";
case LEAD -> "piste";
case EXIT -> null;
};
parts.add(branchLine(st.sceneNames.getOrDefault(br.targetSceneId(), "?"),
br.label(), kind, br.condition()));
if (kind != null) line.append(" [").append(kind).append("]");
if (notBlank(br.condition())) line.append(" (condition : ").append(esc(br.condition().trim())).append(")");
items.add(line.toString());
}
return joinAsList(parts);
return items;
}
/** "Vers <cible> — <libelle> [indice] (condition : ...)" avec les morceaux presents. */
@@ -709,29 +772,30 @@ public class PdfExportService {
}
/**
* Ennemis d'une rencontre : refs bestiaire resolues en noms (liste a puces)
* + texte libre eventuel en paragraphe. Null si rien.
* Encadre de combat (reserve au MJ) : difficulte, adversaires du bestiaire en renvoi vers
* leur fiche (« Bandit (p. 24) »), puis texte libre. Rien si tout est vide.
*/
private String enemyLines(List<String> enemyIds, String freeText, Structure st) {
List<String> names = new ArrayList<>();
private static void combatBox(Ctx ctx, String label, String difficulty, List<String> enemyIds,
String freeText, Structure st) {
if (!ctx.gm) return;
List<String> enemies = new ArrayList<>();
if (enemyIds != null) {
for (String id : enemyIds) {
String name = st.enemyNames.get(id);
if (name != null) names.add(name);
if (name != null) enemies.add(xref("enemy-" + id, name) + " " + pageRef("enemy-" + id));
}
}
return joinNonBlank(joinAsList(names), freeText);
if (!notBlank(difficulty) && enemies.isEmpty() && !notBlank(freeText)) return;
StringBuilder b = ctx.body;
b.append("<div class=\"box combat\"><div class=\"box-label\">").append(esc(label)).append(DIV_CLOSE);
prose(b, difficulty);
if (!enemies.isEmpty()) {
b.append("<ul class=\"prose-list\">");
for (String e : enemies) b.append("<li>").append(e).append("</li>");
b.append("</ul>");
}
/** Joint les morceaux non vides par une ligne vide (nouveau paragraphe). Null si rien. */
private static String joinNonBlank(String... parts) {
StringBuilder out = new StringBuilder();
for (String p : parts) {
if (!notBlank(p)) continue;
if (!out.isEmpty()) out.append("\n\n");
out.append(p);
}
return out.isEmpty() ? null : out.toString();
prose(b, freeText);
b.append(DIV_CLOSE);
}
// ----- Quetes libres / transversales (celles SANS conteneur dans la narration) -----
@@ -761,7 +825,7 @@ public class PdfExportService {
illustrations(ctx, q.getIllustrationImageIds());
ctx.gmBlock(LABEL_DESCRIPTION, q.getDescription());
ctx.gmBlock(LABEL_CONDITIONS, renderPrerequisites(q.getPrerequisites(), st.questNames));
ctx.gmBlock(LABEL_NOEUDS, renderQuestNodes(q, st));
if (ctx.gm) blockHtml(ctx.body, LABEL_NOEUDS, questNodeItems(q, st));
block(b, LABEL_OBJECTIFS_JOUEURS, q.getPlayerObjectives());
ctx.gmBlock(LABEL_ENJEUX_NARRATIFS, q.getNarrativeStakes());
ctx.gmBox(CSS_SECRET, LABEL_NOTES_MJ, q.getGmNotes());
@@ -810,18 +874,20 @@ public class PdfExportService {
* Les chapitres-CONTENEURS de la quete sont exclus : c'est de la plomberie (le jumeau
* porte le meme nom que la quete), pas un lien narratif.
*/
private String renderQuestNodes(QuestJpaEntity q, Structure st) {
if (q.getNodes() == null || q.getNodes().isEmpty()) return null;
private static List<String> questNodeItems(QuestJpaEntity q, Structure st) {
List<String> items = new ArrayList<>();
if (q.getNodes() == null) return items;
Set<String> containers = st.containerChapterIds(q);
List<String> parts = new ArrayList<>();
for (QuestNodeRef n : q.getNodes()) {
if (n.nodeType() == NodeType.SCENE) {
parts.add("Scène : " + st.sceneNames.getOrDefault(n.nodeId(), "?"));
String anchor = "scene-" + n.nodeId();
items.add("Scène : " + xref(anchor, st.sceneNames.getOrDefault(n.nodeId(), "?")) + " " + pageRef(anchor));
} else if (!containers.contains(n.nodeId())) {
parts.add("Chapitre : " + st.chapterNames.getOrDefault(n.nodeId(), "?"));
String anchor = "ch-" + n.nodeId();
items.add("Chapitre : " + xref(anchor, st.chapterNames.getOrDefault(n.nodeId(), "?")) + " " + pageRef(anchor));
}
}
return joinAsList(parts);
return items;
}
/** Plusieurs elements -> lignes "- ..." (rendues en vraies puces par parseBlocks). */
@@ -839,14 +905,14 @@ public class PdfExportService {
// ----- PNJ / Ennemis (groupes par dossier) -----
/** Une fiche persona generique pour la mise en page (PNJ ou ennemi). */
private record PersonaRow(int order, String name, String folder, String level, String portraitId,
record PersonaRow(Long id, int order, String name, String folder, String level, String portraitId,
Map<String, String> values, Map<String, Map<String, String>> keyValueValues,
Map<String, List<String>> imageValues, Map<String, String> foundryStats) {}
private List<PersonaRow> npcEntries(CampaignJpaEntity c) {
List<PersonaRow> out = new ArrayList<>();
for (NpcJpaEntity n : npcRepo.findByCampaignIdOrderByOrderAsc(c.getId())) {
out.add(new PersonaRow(n.getOrder(), n.getName(), n.getFolder(), null, n.getPortraitImageId(),
out.add(new PersonaRow(n.getId(), n.getOrder(), n.getName(), n.getFolder(), null, n.getPortraitImageId(),
n.getValues(), n.getKeyValueValues(), n.getImageValues(), null));
}
return out;
@@ -855,7 +921,7 @@ public class PdfExportService {
private List<PersonaRow> enemyEntries(CampaignJpaEntity c) {
List<PersonaRow> out = new ArrayList<>();
for (EnemyJpaEntity e : enemyRepo.findByCampaignIdOrderByOrderAsc(c.getId())) {
out.add(new PersonaRow(e.getOrder(), e.getName(), e.getFolder(), e.getLevel(), e.getPortraitImageId(),
out.add(new PersonaRow(e.getId(), e.getOrder(), e.getName(), e.getFolder(), e.getLevel(), e.getPortraitImageId(),
e.getValues(), e.getKeyValueValues(), e.getImageValues(), e.getFoundryStats()));
}
return out;
@@ -926,7 +992,8 @@ public class PdfExportService {
StringBuilder b = ctx.body;
// Mise en page en TABLE (portrait | contenu) : openhtmltopdf gere mal le float
// + overflow (le texte se superposait au portrait).
b.append("<div class=\"card\"><table class=\"persona\"><tr>");
b.append("<div class=\"card\" id=\"").append(enemy ? "enemy-" : "npc-").append(r.id())
.append("\"><table class=\"persona\"><tr>");
PdfImage portrait = imageEncoder.image(r.portraitId(), PdfImageEncoder.PORTRAIT_MAX);
if (portrait != null) {
double widthCm = Math.min(3.0, PORTRAIT_MAX_HEIGHT_CM * portrait.w() / portrait.h());
@@ -139,6 +139,57 @@ final class PdfHtml {
b.append(DIV_CLOSE);
}
// ----- Renvois internes (« voir p. 12 ») -----
private static final java.util.regex.Pattern ID_ATTR = java.util.regex.Pattern.compile(" id=\"([^\"]+)\"");
private static final java.util.regex.Pattern XREF = java.util.regex.Pattern.compile(
"<a class=\"xref\" href=\"#([^\"]+)\">(.*?)</a>");
private static final java.util.regex.Pattern PREF = java.util.regex.Pattern.compile(
"<a class=\"pref\" href=\"#([^\"]+)\"></a>");
/** Nom cliquable vers une ancre du livret (retire par {@link #resolveRefs} si l'ancre manque). */
static String xref(String anchor, String text) {
return "<a class=\"xref\" href=\"#" + anchor + "\">" + esc(text) + "</a>";
}
/** Numero de page de l'ancre, rendu « (p. 12) » par target-counter (cf. export.css). */
static String pageRef(String anchor) {
return "<a class=\"pref\" href=\"#" + anchor + "\"></a>";
}
/**
* Neutralise les renvois vers des ancres absentes du document (partie non exportee,
* scene d'une quete exclue...) : le nom reste en texte simple, le numero de page disparait.
* openhtmltopdf ne sait pas resoudre target-counter vers une ancre inexistante.
*/
static String resolveRefs(String html) {
java.util.Set<String> ids = new java.util.HashSet<>();
java.util.regex.Matcher m = ID_ATTR.matcher(html);
while (m.find()) ids.add(m.group(1));
String out = XREF.matcher(html).replaceAll(r -> ids.contains(r.group(1))
? java.util.regex.Matcher.quoteReplacement(r.group())
: java.util.regex.Matcher.quoteReplacement(r.group(2)));
return PREF.matcher(out).replaceAll(r -> ids.contains(r.group(1))
? java.util.regex.Matcher.quoteReplacement(r.group()) : "");
}
/**
* Champ « libelle + elements » dont les elements sont DEJA du HTML (renvois, liens) :
* un seul element en ligne apres le libelle, plusieurs en liste a puces.
*/
static void blockHtml(StringBuilder b, String label, List<String> htmlItems) {
if (htmlItems == null || htmlItems.isEmpty()) return;
b.append("<div class=\"field\"><span class=\"field-label\">").append(esc(label)).append(SPAN_CLOSE);
if (htmlItems.size() == 1) {
b.append(htmlItems.get(0));
} else {
b.append("<ul>");
for (String item : htmlItems) b.append("<li>").append(item).append("</li>");
b.append("</ul>");
}
b.append(DIV_CLOSE);
}
/** Texte courant sans libelle : paragraphes et listes a puces (« - ... »). */
static void prose(StringBuilder b, String value) {
if (!notBlank(value)) return;
@@ -65,6 +65,11 @@ class PdfImageEncoder {
/** Battlemap (fichier stocke) re-encodee, seulement si c'est une image (pas une video). */
PdfImage fileImage(String fileId) {
return fileImage(fileId, ILLUSTRATION_MAX);
}
/** Idem, avec une cote max choisie (cartes pleine page de l'annexe : plus fines). */
PdfImage fileImage(String fileId, int maxDim) {
if (fileId == null || fileId.isBlank()) return null;
StoredFileJpaEntity e;
try {
@@ -75,7 +80,7 @@ class PdfImageEncoder {
if (e == null) return null;
String ct = e.getContentType();
if (ct == null || !ct.startsWith("image/")) return null; // mp4/webm -> ignore
return encode(fileStorage.download(e.getStorageKey()), ILLUSTRATION_MAX, fileId);
return encode(fileStorage.download(e.getStorageKey()), maxDim, fileId);
}
/** Lit un flux image, le redimensionne (max maxDim) et le re-encode en data-URI JPEG. */
+20
View File
@@ -131,3 +131,23 @@ div.field-label { margin: .12cm 0 .06cm; padding-right: 0; }
.stat-array th { background: #f1eef9; color: #4a3f7a; border: 1pt solid #ddd6ee;
padding: 2.5pt 9pt; text-align: center; }
.stat-array td { border: 1pt solid #e6e2f2; padding: 2.5pt 9pt; text-align: center; }
/* --- Renvois internes : nom cliquable + numero de page « (p. 12) » --- */
a.xref { color: #463b78; border-bottom: .5pt dotted #b9aede; }
a.pref:after { content: "(p. " target-counter(attr(href), page) ")"; font-family: 'DejaVu Sans', sans-serif;
font-size: 7.5pt; color: #8a7bc8; }
/* --- Annexes --- */
.annex-intro { color: #555; font-size: 9pt; }
.annex-table td { vertical-align: top; }
.annex-table .page-col { width: 1.6cm; text-align: right; }
ul.annex-list { margin: 0; padding-left: .45cm; }
ul.annex-list li { margin: 0 0 .04cm; }
.annex-kind { font-family: 'DejaVu Sans', sans-serif; font-size: 7pt; text-transform: uppercase;
letter-spacing: .06em; color: #7d6fb0; }
.annex-warn { color: #a84f49; font-style: italic; }
/* --- Cartes en pleine page paysage (page nommee) --- */
@page landscape { size: __PAGE_SIZE__ landscape; margin: 1cm; @top-center { content: none; }
@bottom-center { content: counter(page); font-family: 'DejaVu Sans', sans-serif; font-size: 8pt; color: #999; } }
.map-page { page: landscape; page-break-before: always; text-align: center; }
.map-title { font-family: 'DejaVu Sans', sans-serif; font-size: 11pt; font-weight: bold; color: #2e2a4a;
text-align: left; margin: 0 0 .3cm; }
.map-page img { display: block; margin: 0 auto; border: 1pt solid #cfc9e0; }
@@ -0,0 +1,171 @@
package com.loremind.infrastructure.transfer.pdf;
import com.loremind.domain.campaigncontext.structure.LinkType;
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneType;
import com.loremind.domain.files.ports.FileStorage;
import com.loremind.infrastructure.persistence.entity.*;
import com.loremind.infrastructure.persistence.jpa.*;
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.LoreScope;
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.PageFormat;
import com.loremind.infrastructure.transfer.pdf.PdfExportOptions.Section;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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 javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
/**
* Mise en page « module » : renvois « (p. N) » vers les scènes et les fiches, renvois morts
* neutralisés, annexes MJ (révélations et indices, index PNJ et adversaires avec leurs
* apparitions) et cartes en pleine page paysage.
*/
@SpringBootTest
@Transactional
class PdfExportModuleLayoutTest {
@Autowired private PdfExportService service;
@Autowired private CampaignJpaRepository campaignRepo;
@Autowired private ArcJpaRepository arcRepo;
@Autowired private ChapterJpaRepository chapterRepo;
@Autowired private SceneJpaRepository sceneRepo;
@Autowired private NpcJpaRepository npcRepo;
@Autowired private EnemyJpaRepository enemyRepo;
@Autowired private StoredFileJpaRepository storedFileRepo;
@MockitoBean private FileStorage fileStorage;
private String campaignId;
private Long revId;
private Long enemyId;
private Long npcId;
@BeforeEach
void seed() throws Exception {
byte[] png = png(300, 200);
StoredFileJpaEntity map = storedFileRepo.save(StoredFileJpaEntity.builder()
.filename("map.png").contentType("image/png").sizeBytes(png.length).storageKey("files/layout-map.png").build());
when(fileStorage.download("files/layout-map.png")).thenAnswer(inv -> new ByteArrayInputStream(png));
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("Module").arcsCount(1).build());
campaignId = String.valueOf(camp.getId());
enemyId = enemyRepo.save(EnemyJpaEntity.builder().campaignId(camp.getId()).name("Goule").level("3")
.folder("Morts-vivants").order(0).build()).getId();
npcId = npcRepo.save(NpcJpaEntity.builder().campaignId(camp.getId()).name("Maëlis").folder("Valfroide")
.order(0).build()).getId();
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Acte I").campaignId(camp.getId()).order(0).build());
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("La foire").arcId(arc.getId()).order(0).build());
chapterRepo.save(ChapterJpaEntity.builder().name("La crypte").arcId(arc.getId()).order(1).build());
revId = sceneRepo.save(SceneJpaEntity.builder().name("Le secret du stand").chapterId(ch.getId()).order(2)
.type(SceneType.REVELATION).build()).getId();
sceneRepo.save(SceneJpaEntity.builder().name("L'auberge").chapterId(ch.getId()).order(0)
.branches(new ArrayList<>(List.of(
new SceneBranch("Fouiller le stand", String.valueOf(revId), null, LinkType.CLUE),
SceneBranch.of("Vers nulle part", "999999"))))
.build());
sceneRepo.save(SceneJpaEntity.builder().name("L'embuscade").chapterId(ch.getId()).order(1)
.type(SceneType.ENCOUNTER).combatDifficulty("Moyenne")
.enemyIds(new ArrayList<>(List.of(String.valueOf(enemyId))))
.battlemaps(new ArrayList<>(List.of(new SceneBattlemap("Nuit", String.valueOf(map.getId()), null))))
.branches(new ArrayList<>(List.of(SceneBranch.of("Le carnet", String.valueOf(revId)))))
.build());
}
private static PdfExportOptions options(boolean gm, Section... sections) {
return new PdfExportOptions(gm, PageFormat.A4, false,
sections.length == 0 ? EnumSet.allOf(Section.class) : EnumSet.of(sections[0], sections), LoreScope.ALL);
}
@Test
void sceneExitsAndEnemies_pointToTheirPage() {
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
String rev = "#scene-" + revId;
assertTrue(x.contains("<a class=\"xref\" href=\"" + rev + "\">Le secret du stand</a>"), "nom de scène cliquable");
assertTrue(x.contains("<a class=\"pref\" href=\"" + rev + "\"></a>"), "numéro de page de la scène");
assertTrue(x.contains("<a class=\"xref\" href=\"#enemy-" + enemyId + "\">Goule</a>"), "adversaire renvoyé à sa fiche");
assertTrue(x.contains("id=\"enemy-" + enemyId + "\""), "fiche du bestiaire ancrée");
assertTrue(x.contains("id=\"npc-" + npcId + "\""), "fiche PNJ ancrée");
}
@Test
void deadReferences_areReducedToPlainText() {
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
assertFalse(x.contains("#scene-999999"), "lien vers une scène inexistante neutralisé");
// Sans bestiaire : le nom de l'adversaire reste, sans lien ni page.
String noBestiary = service.xhtml(campaignId, options(true, Section.NARRATIVE));
assertFalse(noBestiary.contains("#enemy-" + enemyId));
assertTrue(noBestiary.contains("Goule"));
}
@Test
void gmAppendix_listsRevelationSourcesAndIndexes() {
String x = service.xhtml(campaignId, PdfExportOptions.defaults());
assertTrue(x.contains("id=\"part-annex\""));
assertTrue(x.contains("Révélations et indices"));
int table = x.indexOf("id=\"annex-revelations\"");
String annex = x.substring(table);
assertTrue(annex.contains(">L'auberge</a>"), "source de la révélation listée");
assertTrue(annex.contains(">L'embuscade</a>"));
assertTrue(annex.contains("indice"), "nature du lien");
assertTrue(annex.contains("Index des PNJ"));
assertTrue(annex.contains("Index des adversaires"));
assertTrue(annex.contains("Morts-vivants"));
}
@Test
void playerEdition_hasNoGmAppendix() {
String x = service.xhtml(campaignId, options(false));
assertFalse(x.contains("id=\"part-annex\""));
assertFalse(x.contains("Révélations et indices"));
}
@Test
void mapsAppendix_replacesInlineBattlemaps() {
String withMaps = service.xhtml(campaignId, PdfExportOptions.defaults());
assertTrue(withMaps.contains("class=\"map-page\""));
assertTrue(withMaps.contains("L'embuscade — Nuit"));
assertFalse(withMaps.contains("Battlemap — Nuit"), "pas de doublon en petit dans la scène");
String inline = service.xhtml(campaignId, options(true, Section.NARRATIVE));
assertFalse(inline.contains("class=\"map-page\""));
assertTrue(inline.contains("Battlemap — Nuit"), "sans annexe, la carte reste dans la scène");
}
@Test
void mapPages_areLandscape() throws Exception {
byte[] pdf = service.export(campaignId, PdfExportOptions.defaults());
try (PDDocument doc = PDDocument.load(pdf)) {
PDRectangle last = doc.getPage(doc.getNumberOfPages() - 1).getMediaBox();
assertTrue(last.getWidth() > last.getHeight(), "la carte est sur une page paysage");
PDRectangle first = doc.getPage(0).getMediaBox();
assertTrue(first.getWidth() < first.getHeight(), "le reste du livret reste en portrait");
}
}
private static byte[] png(int w, int h) throws Exception {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(img, "png", out);
return out.toByteArray();
}
}
@@ -10,6 +10,7 @@ import com.loremind.domain.campaigncontext.structure.Room;
import com.loremind.domain.campaigncontext.structure.RoomBranch;
import com.loremind.domain.campaigncontext.structure.SceneBattlemap;
import com.loremind.domain.campaigncontext.structure.SceneBranch;
import com.loremind.domain.campaigncontext.structure.SceneType;
import com.loremind.domain.files.ports.FileStorage;
import com.loremind.domain.images.ports.ImageStorage;
import com.loremind.domain.shared.template.TemplateField;
@@ -158,6 +159,7 @@ class PdfExportPreviewTest {
"si un PJ a repéré Maëlis", LinkType.CLUE)))
.build(),
SceneJpaEntity.builder().id(301L).chapterId(200L).order(1).name("Le stand du colporteur")
.type(SceneType.REVELATION)
.location("Allée marchande, place du Guet.")
.atmosphere("Le stand est intact mais abandonné ; la marchandise n'a pas été pillée, ce qui inquiète plus que tout.")
.gmSecretNotes("Sous le comptoir : un carnet dont trois pages ont été arrachées, imprégnées d'odeur de cendre.")
@@ -171,6 +173,7 @@ class PdfExportPreviewTest {
.enemies("Le sergent : profil du sbire avec +5 PV et une rapière (+1 aux dégâts).")
.battlemaps(List.of(new SceneBattlemap("Nuit", "500", null),
new SceneBattlemap("Jour", "501", null)))
.branches(List.of(new SceneBranch("Le carnet volé désigne le stand", "301", null, LinkType.CLUE)))
.build()));
when(sceneRepo.findByChapterId(201L)).thenReturn(List.of(
SceneJpaEntity.builder().id(303L).chapterId(201L).order(0).name("Le seuil scellé")
@@ -7,13 +7,13 @@ describe('PDF export presets', () => {
it('GM edition = complete booklet, whole lore', () => {
expect(toExportOptions(gm())).toEqual({
edition: 'gm', format: 'A4', print: false,
sections: ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE'], lore: 'ALL',
sections: ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE', 'APPENDIX', 'MAPS'], lore: 'ALL',
});
});
it('player edition preselects player-safe parts and linked lore only', () => {
const o = toExportOptions({ edition: 'player', format: 'A5', print: true, ...editionPreset('player') })!;
expect(o.sections).toEqual(['NARRATIVE', 'NPCS', 'LORE']);
expect(o.sections).toEqual(['NARRATIVE', 'NPCS', 'LORE', 'MAPS']);
expect(o.lore).toBe('LINKED');
expect(o.format).toBe('A5');
expect(o.print).toBe(true);
@@ -11,11 +11,12 @@ export interface PdfExportChoice {
/**
* Préréglages d'une version : MJ = livret complet ; joueurs = ce qu'on peut leur montrer
* (narration, PNJ, lore limité aux pages liées), sans bestiaire, quêtes ni tables.
* (narration, PNJ, lore limité aux pages liées, cartes en grand), sans bestiaire, quêtes,
* tables ni annexes MJ.
*/
export function editionPreset(edition: 'gm' | 'player'): Pick<PdfExportChoice, 'sections' | 'lore'> {
return edition === 'player'
? { sections: new Set<PdfSection>(['NARRATIVE', 'NPCS', 'LORE']), lore: 'LINKED' }
? { sections: new Set<PdfSection>(['NARRATIVE', 'NPCS', 'LORE', 'MAPS']), lore: 'LINKED' }
: { sections: new Set<PdfSection>(PDF_SECTIONS), lore: 'ALL' };
}
+2 -2
View File
@@ -1,8 +1,8 @@
/** Parties du livret PDF qu'on peut inclure ou non (miroir de PdfExportOptions.Section). */
export type PdfSection = 'NARRATIVE' | 'QUESTS' | 'NPCS' | 'ENEMIES' | 'TABLES' | 'LORE';
export type PdfSection = 'NARRATIVE' | 'QUESTS' | 'NPCS' | 'ENEMIES' | 'TABLES' | 'LORE' | 'APPENDIX' | 'MAPS';
/** Ordre canonique des parties dans le livret. */
export const PDF_SECTIONS: PdfSection[] = ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE'];
export const PDF_SECTIONS: PdfSection[] = ['NARRATIVE', 'QUESTS', 'NPCS', 'ENEMIES', 'TABLES', 'LORE', 'APPENDIX', 'MAPS'];
/**
* Options de l'export PDF (modale) :
+3 -1
View File
@@ -2671,7 +2671,9 @@
"NPCS": "NPCs",
"ENEMIES": "Bestiary",
"TABLES": "Random tables",
"LORE": "Lore"
"LORE": "Lore",
"APPENDIX": "GM appendix (revelations, indexes)",
"MAPS": "Full-page maps"
},
"loreLinked": "Only pages linked to the campaign",
"loreAll": "The whole lore",
+3 -1
View File
@@ -2671,7 +2671,9 @@
"NPCS": "PNJ",
"ENEMIES": "Bestiaire",
"TABLES": "Tables aléatoires",
"LORE": "Lore"
"LORE": "Lore",
"APPENDIX": "Annexes MJ (révélations, index)",
"MAPS": "Cartes en pleine page"
},
"loreLinked": "Seulement les pages liées à la campagne",
"loreAll": "Tout le lore",
@@ -63,7 +63,9 @@
"NPCS": "NPCs",
"ENEMIES": "Bestiary",
"TABLES": "Random tables",
"LORE": "Lore"
"LORE": "Lore",
"APPENDIX": "GM appendix (revelations, indexes)",
"MAPS": "Full-page maps"
},
"loreLinked": "Only pages linked to the campaign",
"loreAll": "The whole lore",
@@ -63,7 +63,9 @@
"NPCS": "PNJ",
"ENEMIES": "Bestiaire",
"TABLES": "Tables aléatoires",
"LORE": "Lore"
"LORE": "Lore",
"APPENDIX": "Annexes MJ (révélations, index)",
"MAPS": "Cartes en pleine page"
},
"loreLinked": "Seulement les pages liées à la campagne",
"loreAll": "Tout le lore",