Compare commits

...
4 Commits
Author SHA1 Message Date
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
55 changed files with 1551 additions and 99 deletions
+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.5.0-beta",
)
logger = logging.getLogger(__name__)
+1 -1
View File
@@ -14,7 +14,7 @@
<groupId>com.loremind</groupId>
<artifactId>loremind-core</artifactId>
<version>1.4.0-beta</version>
<version>1.5.0-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,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,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")));
}
}
@@ -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,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);
}
}
@@ -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,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
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.5.0-beta",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "loremind-web",
"version": "1.4.0-beta",
"version": "1.5.0-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.5.0-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,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 } });
}
}
@@ -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; });
}
}
});
}
@@ -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([]);
}
});
});
+46
View File
@@ -0,0 +1,46 @@
import type { SecondarySidebarConfig, TreeItem } from '../services/layout.service';
import type { BreadcrumbItem } from './breadcrumb/breadcrumb.component';
/** Segment boundaries prevent campaign 1 from matching campaign 10. */
export function isWithinRoute(url: string, route: string): boolean {
const path = url.split(/[?#]/)[0];
return path === route || path.startsWith(route + '/');
}
/** Follow the visible tree, including flattened campaigns and quest containers. */
export function campaignBreadcrumbs(
url: string, config: SecondarySidebarConfig | null, editLabel: string
): BreadcrumbItem[] {
const root = config?.titleRoute;
if (!config || !root?.startsWith('/campaigns/') || !isWithinRoute(url, root)) return [];
const path = url.split(/[?#]/)[0];
if (path === root) return [];
let best: BreadcrumbItem[] = [];
let matchedRoute = '';
const visit = (items: TreeItem[], parents: BreadcrumbItem[]) => {
for (const item of items) {
const trail = item.route === root ? parents : [...parents, { label: item.label, route: item.route }];
if (item.route && item.route !== root && isWithinRoute(path, item.route) && item.route.length > matchedRoute.length) {
best = trail;
matchedRoute = item.route;
}
for (const action of item.createActions ?? []) {
if (path === action.route) {
best = [...trail, { label: action.label }];
matchedRoute = action.route;
}
}
visit(item.children ?? [], trail);
}
};
visit(config.items, []);
for (const action of config.createActions) {
if (action.route === path) {
best = [{ label: action.label }];
matchedRoute = path;
}
}
if (!matchedRoute || (path !== matchedRoute && path !== matchedRoute + '/edit')) return [];
if (path.endsWith('/edit')) best.push({ label: editLabel });
return [{ label: config.title, route: root }, ...best];
}
@@ -1,6 +1,6 @@
@if (assessment) {
<section class="readiness-panel" [class.ready]="isReady">
<button type="button" class="readiness-header" (click)="toggle()">
<button type="button" class="readiness-header" (click)="toggle()" [attr.aria-expanded]="!collapsed">
<lucide-icon [img]="collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
@if (isReady) {
<lucide-icon [img]="CheckCircle2" [size]="16" class="ready-icon"></lucide-icon>
+2 -1
View File
@@ -12,7 +12,7 @@
<button class="toggle-btn" [class.active]="currentRoute.startsWith('/lore')" (click)="navigateTo('/lore')">
{{ 'sidebar.tabLore' | translate }}
</button>
<button class="toggle-btn" [class.active]="currentRoute.startsWith('/campaigns')" (click)="navigateTo('/campaigns')">
<button class="toggle-btn" [class.active]="currentRoute.startsWith('/campaigns') || currentRoute.startsWith('/sessions/')" (click)="navigateTo('/campaigns')">
{{ 'sidebar.tabCampaign' | translate }}
</button>
</div>
@@ -27,6 +27,7 @@
<button
class="context-item"
[class.active]="isActive(item.route)"
[attr.aria-current]="isActive(item.route) ? 'location' : null"
(click)="navigateTo(item.route)">
{{ item.name }}
</button>
+2 -1
View File
@@ -11,6 +11,7 @@ import { ActiveSessionShortcutComponent } from '../sessions/active-session-short
// Single source of truth pour la version affichée dans le footer :
// on lit directement package.json à la compilation (resolveJsonModule).
import packageJson from '../../../package.json';
import { isWithinRoute } from '../shared/navigation-path';
@Component({
selector: 'app-sidebar',
@@ -57,7 +58,7 @@ export class SidebarComponent implements OnInit {
}
isActive(itemRoute: string): boolean {
return this.currentRoute === itemRoute;
return isWithinRoute(this.currentRoute, itemRoute);
}
openSearch(): void {
+16 -3
View File
@@ -296,8 +296,20 @@
"character": "PC",
"randomTable": "Random table",
"itemCatalog": "Item catalog",
"enemy": "Enemy"
}
"enemy": "Enemy",
"arc": "Arc",
"chapter": "Chapter",
"scene": "Scene",
"quest": "Quest"
},
"loading": "Searching…",
"favorites": "Favorites",
"recent": "Recently viewed",
"clearRecent": "Clear history",
"addFavorite": "Add {{name}} to favorites",
"removeFavorite": "Remove {{name}} from favorites",
"shortcutsEmpty": "Your recently viewed pages will appear here. Type at least 2 characters to search, then use the star to save a favorite.",
"close": "Close search"
},
"updateBanner": {
"message": "A new version of LoreMind is available (<strong>{{version}}</strong>). Reload to enjoy the latest improvements.",
@@ -653,7 +665,8 @@
"organizeInArcs": "or organize into arcs",
"defaultArcName": "Main arc",
"defaultChapterName": "Chapter 1",
"flatModeHint": "Simple mode: your scenes are in the left panel. Add one, or organize the campaign into arcs."
"flatModeHint": "Simple mode: your scenes are in the left panel. Add one, or organize the campaign into arcs.",
"manage": "Manage"
},
"campaignImport": {
"pageTitle": "Import a campaign",
+16 -3
View File
@@ -296,8 +296,20 @@
"character": "PJ",
"randomTable": "Table aléatoire",
"itemCatalog": "Catalogue d'objets",
"enemy": "Ennemi"
}
"enemy": "Ennemi",
"arc": "Arc",
"chapter": "Chapitre",
"scene": "Scène",
"quest": "Quête"
},
"loading": "Recherche en cours…",
"favorites": "Favoris",
"recent": "Consultés récemment",
"clearRecent": "Effacer l’historique",
"addFavorite": "Ajouter {{name}} aux favoris",
"removeFavorite": "Retirer {{name}} des favoris",
"shortcutsEmpty": "Vos dernières fiches consultées apparaîtront ici. Tapez au moins 2 caractères pour rechercher, puis utilisez l’étoile pour garder un favori.",
"close": "Fermer la recherche"
},
"updateBanner": {
"message": "Une nouvelle version de LoreMind est disponible (<strong>{{version}}</strong>). Recharge pour profiter des dernières améliorations.",
@@ -653,7 +665,8 @@
"organizeInArcs": "ou organiser en arcs",
"defaultArcName": "Arc principal",
"defaultChapterName": "Chapitre 1",
"flatModeHint": "Mode simple : vos scènes sont dans le volet de gauche. Ajoutez-en une, ou organisez la campagne en arcs."
"flatModeHint": "Mode simple : vos scènes sont dans le volet de gauche. Ajoutez-en une, ou organisez la campagne en arcs.",
"manage": "Gérer"
},
"campaignImport": {
"pageTitle": "Importer une campagne",
@@ -47,6 +47,7 @@
"submit": "Create the campaign"
},
"campaignDetail": {
"manage": "Manage",
"players": "{{n}} players",
"openLinkedLore": "Open the linked universe",
"loreMissingTitle": "The linked universe cannot be found",
@@ -47,6 +47,7 @@
"submit": "Créer la campagne"
},
"campaignDetail": {
"manage": "Gérer",
"players": "{{n}} joueurs",
"openLinkedLore": "Ouvrir l'univers associé",
"loreMissingTitle": "L'univers associé est introuvable",
@@ -21,6 +21,14 @@
"ariaLabel": "Breadcrumb"
},
"globalSearch": {
"favorites": "Favorites",
"recent": "Recently viewed",
"clearRecent": "Clear history",
"addFavorite": "Add {{name}} to favorites",
"removeFavorite": "Remove {{name}} from favorites",
"shortcutsEmpty": "Your recently viewed pages will appear here. Type at least 2 characters to search, then use the star to save a favorite.",
"close": "Close search",
"loading": "Searching…",
"placeholder": "Search in LoreMind...",
"noResults": "No results",
"minChars": "Type at least 2 characters",
@@ -40,7 +48,11 @@
"character": "PC",
"randomTable": "Random table",
"itemCatalog": "Item catalog",
"enemy": "Enemy"
"enemy": "Enemy",
"arc": "Arc",
"chapter": "Chapter",
"scene": "Scene",
"quest": "Quest"
}
},
"updateBanner": {
@@ -21,6 +21,14 @@
"ariaLabel": "Fil d'Ariane"
},
"globalSearch": {
"favorites": "Favoris",
"recent": "Consultés récemment",
"clearRecent": "Effacer l’historique",
"addFavorite": "Ajouter {{name}} aux favoris",
"removeFavorite": "Retirer {{name}} des favoris",
"shortcutsEmpty": "Vos dernières fiches consultées apparaîtront ici. Tapez au moins 2 caractères pour rechercher, puis utilisez l’étoile pour garder un favori.",
"close": "Fermer la recherche",
"loading": "Recherche en cours…",
"placeholder": "Rechercher dans LoreMind...",
"noResults": "Aucun résultat",
"minChars": "Tape au moins 2 caractères",
@@ -40,7 +48,11 @@
"character": "PJ",
"randomTable": "Table aléatoire",
"itemCatalog": "Catalogue d'objets",
"enemy": "Ennemi"
"enemy": "Ennemi",
"arc": "Arc",
"chapter": "Chapitre",
"scene": "Scène",
"quest": "Quête"
}
},
"updateBanner": {