Compare commits
8
Commits
v1.0.3
...
v1.2.1-beta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c6b642975 | ||
|
|
d926545e3d | ||
|
|
b323c681f8 | ||
|
|
e7063b31e3 | ||
|
|
ab658f27b0 | ||
|
|
c2947cfef8 | ||
|
|
67ac4cc68f | ||
|
|
c2f162d823 |
@@ -0,0 +1,44 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
|
||||
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
|
||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||
*
|
||||
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
||||
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
||||
* Exactement l'un des deux.</p>
|
||||
*
|
||||
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||
* @param chapter le chapitre (nom obligatoire)
|
||||
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
||||
* @param linkSequentially relier chaque scène à la suivante par une sortie
|
||||
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel
|
||||
) {
|
||||
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
}
|
||||
|
||||
public record SceneSpec(
|
||||
String name, String description, SceneType type, String location,
|
||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||
}
|
||||
|
||||
/** Ce qui a été créé, pour que le front ouvre directement le chapitre. */
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||
*
|
||||
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedSkeletonService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final ArcService arcService;
|
||||
private final ChapterService chapterService;
|
||||
private final SceneService sceneService;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||
* arc d'une autre campagne ou non linéaire)
|
||||
*/
|
||||
@Transactional
|
||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||
validate(skeleton);
|
||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
||||
.filter(s -> s != null && !isBlank(s.name()))
|
||||
.toList();
|
||||
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : specs) {
|
||||
scenes.add(sceneService.createScene(Scene.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||
.location(blankToNull(spec.location()))
|
||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||
.enemies(blankToNull(spec.enemies()))
|
||||
.chapterId(chapter.getId())
|
||||
.order(order++)
|
||||
.build()));
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
|
||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList());
|
||||
}
|
||||
|
||||
private static void validate(GuidedSkeleton skeleton) {
|
||||
if (skeleton == null) {
|
||||
throw new IllegalArgumentException("Squelette manquant.");
|
||||
}
|
||||
boolean hasArc = !isBlank(skeleton.arcId());
|
||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||
if (hasArc == hasNewArc) {
|
||||
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||
}
|
||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
|
||||
}
|
||||
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
|
||||
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
|
||||
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
|
||||
if (!isBlank(skeleton.arcId())) {
|
||||
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||
if (arc.getType() != ArcType.LINEAR) {
|
||||
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
|
||||
}
|
||||
return arc.getId();
|
||||
}
|
||||
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
|
||||
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
|
||||
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
|
||||
return arcService.createArc(Arc.builder()
|
||||
.name(skeleton.newArcName().trim())
|
||||
.campaignId(campaignId)
|
||||
.type(ArcType.LINEAR)
|
||||
.order(nextOrder)
|
||||
.build()).getId();
|
||||
}
|
||||
|
||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||
return chapterService.createChapter(Chapter.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.arcId(arcId)
|
||||
.order(nextOrder)
|
||||
.build());
|
||||
}
|
||||
|
||||
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
|
||||
private void linkInChain(List<Scene> scenes, String label) {
|
||||
for (int i = 0; i < scenes.size() - 1; i++) {
|
||||
Scene scene = scenes.get(i);
|
||||
scene.setBranches(new ArrayList<>(List.of(
|
||||
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
|
||||
sceneRepository.save(scene);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return isBlank(s) ? null : s.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Une remarque de relecture d'éditeur (Mentor d'écriture, phase M2) : un conseil
|
||||
* d'auteur sur la QUALITÉ de l'écriture, pas sur la complétude (ça, c'est le readiness).
|
||||
*
|
||||
* <p>Contrairement à {@link ReadinessGap}, le back ne rédige pas le texte : il
|
||||
* renvoie la règle et ses paramètres, et le front compose observation / pourquoi /
|
||||
* question depuis l'i18n ({@code writingReview.rules.<ruleId>}), en fr comme en en.</p>
|
||||
*
|
||||
* @param entityType type de l'entité concernée (réutilise celui du readiness pour les liens profonds)
|
||||
* @param entityId id de l'entité concernée
|
||||
* @param entityName libellé lisible de l'entité
|
||||
* @param ruleId identifiant stable de la règle (ex. {@code WRITE-002-FAKE-CHOICE})
|
||||
* @param category famille de la remarque (regroupement à l'affichage)
|
||||
* @param params valeurs à injecter dans le texte i18n (ex. {@code count}, {@code phrase})
|
||||
* @param arcId arc parent (navigation), ou {@code null}
|
||||
* @param chapterId chapitre parent (navigation), ou {@code null}
|
||||
*/
|
||||
public record WritingRemark(
|
||||
ReadinessEntityType entityType,
|
||||
String entityId,
|
||||
String entityName,
|
||||
String ruleId,
|
||||
WritingRemarkCategory category,
|
||||
Map<String, String> params,
|
||||
String arcId,
|
||||
String chapterId
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur d'une campagne (Mentor d'écriture, phase M2).
|
||||
*
|
||||
* @param campaignId campagne relue
|
||||
* @param remarks remarques dans l'ordre de l'arbre (campagne, puis arc par arc)
|
||||
*/
|
||||
public record WritingReviewReport(String campaignId, List<WritingRemark> remarks) {
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur (Mentor d'écriture, phase M2 — voir docs/conception-mentor-ecriture.md) :
|
||||
* conseils d'auteur sur la QUALITÉ de l'écriture (vrais choix, rythme, enjeux, narration),
|
||||
* là où le readiness ({@link CampaignReadinessService}) ne juge que la complétude.
|
||||
*
|
||||
* <p><b>Déterministe, sans IA, sans persistance</b> ; même chargement en une passe que le
|
||||
* readiness (arcs → chapitres → scènes). Purement indicatif : une remarque est un conseil,
|
||||
* jamais un blocage. Le texte est composé côté front à partir de {@code ruleId} + {@code params}.</p>
|
||||
*
|
||||
* <p>L'arc SYSTEM (« Quêtes libres ») est de la plomberie invisible : ses chapitres-conteneurs
|
||||
* ne reçoivent pas de remarque de niveau chapitre, mais leurs scènes sont relues comme les autres.</p>
|
||||
*/
|
||||
@Service
|
||||
public class WritingReviewService {
|
||||
|
||||
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||
static final int CORRIDOR_MIN_SCENES = 3;
|
||||
/** WRITE-003 : nombre minimal de chemins menant à une révélation (en deçà : un seul chemin). */
|
||||
static final int REVELATION_MIN_INCOMING = 2;
|
||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||
static final int MONOTONOUS_RUN = 3;
|
||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||
static final int LONG_NARRATION_CHARS = 1200;
|
||||
/** WRITE-010 : nombre minimal de scènes pour juger la part de scènes non typées. */
|
||||
static final int UNTYPED_MIN_SCENES = 5;
|
||||
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||
static final double UNTYPED_RATIO = 0.7;
|
||||
|
||||
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||
static final String KIND_COMBAT = "COMBAT";
|
||||
|
||||
/**
|
||||
* WRITE-007 : la narration décide à la place des personnages (action ou émotion imposée).
|
||||
* Volontairement restreint aux tournures sans ambiguïté, pour éviter les faux positifs.
|
||||
*/
|
||||
private static final Pattern NARRATION_DECIDES = Pattern.compile(
|
||||
"\\b(vous (?:décidez|choisissez|ressentez|avez (?:très |si )?peur"
|
||||
+ "|êtes (?:terrifié|effrayé|terrorisé|paniqué|soulagé|ému)e?s?"
|
||||
+ "|entrez|vous précipitez|dégainez|attaquez|fuyez)"
|
||||
+ "|you (?:decide|choose|feel (?:afraid|scared|uneasy|relieved|guilty)"
|
||||
+ "|are (?:afraid|scared|terrified|relieved|panicking)"
|
||||
+ "|enter|rush|draw your|attack|flee))\\b",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS);
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final QuestRepository questRepository;
|
||||
|
||||
public WritingReviewService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
||||
public WritingReviewReport review(String campaignId) {
|
||||
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||
|
||||
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
||||
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||
|
||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||
|
||||
int totalScenes = 0;
|
||||
int genericScenes = 0;
|
||||
for (Arc arc : arcs) {
|
||||
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||
|
||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||
if (visibleArc && isBlank(arc.getStakes())
|
||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
|
||||
List<Scene> lastChapterScenes = List.of();
|
||||
for (Chapter chapter : chapters) {
|
||||
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||
totalScenes += scenes.size();
|
||||
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||
|
||||
if (visibleArc) {
|
||||
reviewChapter(arc, chapter, scenes, treeRemarks);
|
||||
}
|
||||
for (Scene scene : scenes) {
|
||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||
}
|
||||
if (!scenes.isEmpty()) {
|
||||
lastChapterScenes = scenes;
|
||||
}
|
||||
}
|
||||
|
||||
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
||||
}
|
||||
}
|
||||
|
||||
// WRITE-010 — trop de scènes non typées pour juger le rythme.
|
||||
if (totalScenes >= UNTYPED_MIN_SCENES && (double) genericScenes / totalScenes > UNTYPED_RATIO) {
|
||||
String campaignName = campaignRepository.findById(campaignId).map(Campaign::getName).orElse(null);
|
||||
int pct = (int) Math.round(100.0 * genericScenes / totalScenes);
|
||||
campaignRemarks.add(new WritingRemark(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||
"WRITE-010-UNTYPED-SCENES", WritingRemarkCategory.PACING,
|
||||
Map.of("percent", String.valueOf(pct), "count", String.valueOf(genericScenes)),
|
||||
null, null));
|
||||
}
|
||||
|
||||
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||
remarks.addAll(treeRemarks);
|
||||
return new WritingReviewReport(campaignId, remarks);
|
||||
}
|
||||
|
||||
// --- Niveau chapitre ---------------------------------------------------------------
|
||||
|
||||
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||
|
||||
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||
boolean anyBranch = scenes.stream().anyMatch(WritingReviewService::hasBranches);
|
||||
boolean anyChoice = scenes.stream().anyMatch(s -> !isBlank(s.getChoicesConsequences()));
|
||||
if (scenes.size() >= CORRIDOR_MIN_SCENES && !anyBranch && !anyChoice) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-001-CORRIDOR", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(scenes.size()))));
|
||||
}
|
||||
|
||||
// WRITE-004 — rythme monotone : N scènes d'affilée du même genre.
|
||||
MonotonousRun run = findMonotonousRun(scenes);
|
||||
if (run != null) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-004-MONOTONOUS-PACING", WritingRemarkCategory.PACING,
|
||||
Map.of("count", String.valueOf(run.length()), "kind", run.kind())));
|
||||
}
|
||||
|
||||
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||
if (isBlank(chapter.getNarrativeStakes())) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
private record MonotonousRun(String kind, int length) {}
|
||||
|
||||
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||
private static MonotonousRun findMonotonousRun(List<Scene> scenes) {
|
||||
String currentKind = null;
|
||||
int length = 0;
|
||||
MonotonousRun found = null;
|
||||
for (Scene scene : scenes) {
|
||||
String kind = pacingKind(scene);
|
||||
if (kind != null && kind.equals(currentKind)) {
|
||||
length++;
|
||||
} else {
|
||||
if (found != null) return found;
|
||||
currentKind = kind;
|
||||
length = kind == null ? 0 : 1;
|
||||
}
|
||||
if (length >= MONOTONOUS_RUN) {
|
||||
found = new MonotonousRun(currentKind, length);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Genre d'une scène pour le rythme : COMBAT, sinon son type s'il est renseigné, sinon null. */
|
||||
private static String pacingKind(Scene scene) {
|
||||
if (isCombat(scene)) return KIND_COMBAT;
|
||||
SceneType type = typeOf(scene);
|
||||
return type == SceneType.GENERIC ? null : type.name();
|
||||
}
|
||||
|
||||
// --- Niveau scène -------------------------------------------------------------------
|
||||
|
||||
private void reviewScene(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
checkFakeChoice(arc, chapter, scene, chapterScenes, out);
|
||||
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
||||
checkNarration(arc, chapter, scene, out);
|
||||
checkCombatPurpose(arc, chapter, scene, out);
|
||||
}
|
||||
|
||||
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
||||
private void checkFakeChoice(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
List<SceneBranch> branches = scene.getBranches();
|
||||
if (branches == null || branches.size() < 2) return;
|
||||
Set<String> targets = branches.stream().map(SceneBranch::targetSceneId).collect(Collectors.toSet());
|
||||
if (targets.size() != 1) return;
|
||||
String target = targets.iterator().next();
|
||||
if (isBlank(target)) return; // Branche cassée : c'est l'affaire du readiness (SCENE-010).
|
||||
String targetName = chapterScenes.stream()
|
||||
.filter(s -> target.equals(s.getId())).map(Scene::getName)
|
||||
.filter(n -> !isBlank(n)).findFirst().orElse("?");
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-002-FAKE-CHOICE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(branches.size()), "target", targetName)));
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-003 — révélation à chemin unique (règle des 3 indices). Seulement dans un
|
||||
* chapitre qui utilise des liens : sans aucun lien, c'est WRITE-001 qui parle.
|
||||
*/
|
||||
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||
long incoming = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
||||
.filter(scene.getId()::equals)
|
||||
.count();
|
||||
if (incoming < REVELATION_MIN_INCOMING) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("incoming", String.valueOf(incoming))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-006 — narration trop longue ; WRITE-007 — narration qui décide à la place des PJ. */
|
||||
private void checkNarration(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
String narration = scene.getPlayerNarration();
|
||||
if (isBlank(narration)) return;
|
||||
int length = narration.strip().length();
|
||||
if (length > LONG_NARRATION_CHARS) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-006-LONG-NARRATION", WritingRemarkCategory.NARRATION,
|
||||
Map.of("chars", String.valueOf(length))));
|
||||
}
|
||||
Matcher m = NARRATION_DECIDES.matcher(narration);
|
||||
if (m.find()) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-007-NARRATION-DECIDES", WritingRemarkCategory.NARRATION,
|
||||
Map.of("phrase", m.group(1))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
|
||||
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
||||
Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Niveau arc -----------------------------------------------------------------------
|
||||
|
||||
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
||||
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ----------------------------------------------------------------------------
|
||||
|
||||
private static boolean isCombat(Scene scene) {
|
||||
return typeOf(scene) == SceneType.ENCOUNTER
|
||||
|| !isBlank(scene.getCombatDifficulty())
|
||||
|| !isBlank(scene.getEnemies())
|
||||
|| (scene.getEnemyIds() != null && scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id)));
|
||||
}
|
||||
|
||||
private static boolean hasBranches(Scene scene) {
|
||||
return scene.getBranches() != null && !scene.getBranches().isEmpty();
|
||||
}
|
||||
|
||||
private static SceneType typeOf(Scene scene) {
|
||||
return Objects.requireNonNullElse(scene.getType(), SceneType.GENERIC);
|
||||
}
|
||||
|
||||
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||
Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||
ruleId, category, params, arc.getId(), null);
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String labelOr(String value, String fallback) {
|
||||
return isBlank(value) ? fallback : value;
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,11 @@ public class SessionService {
|
||||
return sessionRepository.findActive();
|
||||
}
|
||||
|
||||
/** Toutes les sessions en cours, la plus récente d'abord (raccourci « Séance en cours »). */
|
||||
public List<Session> getAllActive() {
|
||||
return sessionRepository.findAllActive();
|
||||
}
|
||||
|
||||
public Optional<Session> getActiveByPlaythrough(String playthroughId) {
|
||||
return sessionRepository.findActiveByPlaythroughId(playthroughId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
|
||||
* le système. Logique pure (testable sans Windows).
|
||||
*
|
||||
* @param supported vérification possible (Windows)
|
||||
* @param ready rien ne bloque côté PC
|
||||
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
|
||||
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
|
||||
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
|
||||
* @param program exécutable concerné
|
||||
*/
|
||||
public record NetworkReadiness(
|
||||
boolean supported,
|
||||
boolean ready,
|
||||
List<String> publicNetworks,
|
||||
boolean firewallAllowed,
|
||||
boolean firewallBlocked,
|
||||
String program
|
||||
) {
|
||||
|
||||
static final String PUBLIC = "Public";
|
||||
static final String PRIVATE = "Private";
|
||||
|
||||
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
|
||||
if (snapshot == null || !snapshot.supported()) {
|
||||
return new NetworkReadiness(false, false, List.of(), false, false, null);
|
||||
}
|
||||
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
|
||||
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
|
||||
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
|
||||
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
|
||||
|
||||
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
|
||||
.stream()
|
||||
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
|
||||
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
|
||||
.toList();
|
||||
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
|
||||
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
|
||||
|
||||
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
|
||||
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, snapshot.program());
|
||||
}
|
||||
|
||||
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
|
||||
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
|
||||
return rules.stream()
|
||||
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
|
||||
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
|
||||
}
|
||||
|
||||
private static List<String> profiles(String raw) {
|
||||
if (raw == null) return List.of();
|
||||
return Arrays.stream(raw.split(","))
|
||||
.map(s -> s.trim().toLowerCase(Locale.ROOT))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Vue publique d'un appareil appairé (jamais l'empreinte du jeton). */
|
||||
public record PairedDevice(String id, String name, String userAgent, Instant createdAt, Instant lastSeenAt) {
|
||||
|
||||
static PairedDevice of(RemoteDevice d) {
|
||||
return new PairedDevice(d.getId(), d.getName(), d.getUserAgent(), d.getCreatedAt(), d.getLastSeenAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Code d'appairage à 6 chiffres affiché sur le PC (usage unique). */
|
||||
public record PairingCode(String code, Instant expiresAt) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/** Appairage refusé : code absent, faux, expiré, ou trop d'essais. Message prêt à afficher. */
|
||||
public class PairingRejectedException extends RuntimeException {
|
||||
|
||||
public PairingRejectedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/**
|
||||
* Résultat d'un appairage réussi.
|
||||
*
|
||||
* @param token jeton d'appareil en clair : à poser en cookie, jamais renvoyé dans le corps
|
||||
* @param device l'appareil enregistré
|
||||
*/
|
||||
public record PairingResult(String token, PairedDevice device) {
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
* <p>
|
||||
* Modèle de confiance : le connecteur habituel reste limité à la machine (127.0.0.1) et
|
||||
* n'exige rien, comme avant. Quand le MJ active l'accès distant, un SECOND connecteur
|
||||
* s'ouvre sur le réseau local ; tout ce qui y arrive doit présenter un jeton d'appareil,
|
||||
* obtenu en saisissant un code à 6 chiffres affiché sur le PC (usage unique, 5 minutes,
|
||||
* 5 essais). Les Paramètres restent réservés à la machine (filtre {@code RemoteAccessFilter}).
|
||||
* <p>
|
||||
* Uniquement en mode bureau (profil {@code local}) : en Docker, rien de tout ceci n'existe.
|
||||
*/
|
||||
@Service
|
||||
@Profile("local")
|
||||
public class RemoteAccessService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RemoteAccessService.class);
|
||||
|
||||
static final Duration CODE_TTL = Duration.ofMinutes(5);
|
||||
static final int CODE_MAX_ATTEMPTS = 5;
|
||||
/** Garde-fou anti force brute tous codes confondus : au-delà, plus aucun essai pendant 1 min. */
|
||||
static final int GLOBAL_MAX_FAILURES_PER_MINUTE = 20;
|
||||
/** On ne réécrit « vu pour la dernière fois » qu'au plus une fois par minute et par appareil. */
|
||||
static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1);
|
||||
static final int DEVICE_NAME_MAX = 100;
|
||||
static final int USER_AGENT_MAX = 300;
|
||||
|
||||
private final RemoteAccessConfigRepository configRepository;
|
||||
private final RemoteDeviceRepository deviceRepository;
|
||||
private final LanConnector lanConnector;
|
||||
private final int localPort;
|
||||
private final Clock clock;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
private PairingCode currentCode;
|
||||
private int attemptsLeft;
|
||||
private final Deque<Instant> recentFailures = new ArrayDeque<>();
|
||||
private String lastError;
|
||||
|
||||
@Autowired
|
||||
public RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
@Value("${server.port:8080}") int localPort) {
|
||||
this(configRepository, deviceRepository, lanConnector, localPort, Clock.systemUTC());
|
||||
}
|
||||
|
||||
RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
int localPort,
|
||||
Clock clock) {
|
||||
this.configRepository = configRepository;
|
||||
this.deviceRepository = deviceRepository;
|
||||
this.lanConnector = lanConnector;
|
||||
this.localPort = localPort;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// --- Réglage -----------------------------------------------------------------------
|
||||
|
||||
/** Au démarrage : rouvre le connecteur si l'accès distant était activé. Ne bloque jamais le lancement. */
|
||||
public synchronized void applySavedConfig() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
if (!config.enabled()) return;
|
||||
try {
|
||||
lanConnector.start(config.port());
|
||||
lastError = null;
|
||||
} catch (IllegalStateException e) {
|
||||
lastError = e.getMessage();
|
||||
log.warn("Accès distant activé mais connecteur impossible à ouvrir : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Active ou désactive l'accès distant. À l'activation, le connecteur est ouvert AVANT
|
||||
* d'enregistrer le réglage : un port occupé laisse l'accès désactivé.
|
||||
*
|
||||
* @throws IllegalArgumentException port hors plage ou identique au port local
|
||||
* @throws IllegalStateException port déjà occupé
|
||||
*/
|
||||
public synchronized RemoteAccessStatus configure(boolean enabled, int port) {
|
||||
if (port < 1024 || port > 65535) {
|
||||
throw new IllegalArgumentException("Le port doit être compris entre 1024 et 65535.");
|
||||
}
|
||||
if (port == localPort) {
|
||||
throw new IllegalArgumentException("Choisissez un port différent de celui de l'application (" + localPort + ").");
|
||||
}
|
||||
if (enabled) {
|
||||
lanConnector.start(port);
|
||||
} else {
|
||||
lanConnector.stop();
|
||||
currentCode = null;
|
||||
}
|
||||
lastError = null;
|
||||
configRepository.save(new RemoteAccessConfig(enabled, port));
|
||||
return status();
|
||||
}
|
||||
|
||||
public synchronized RemoteAccessStatus status() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
int running = lanConnector.runningPort();
|
||||
List<String> urls = running > 0
|
||||
? lanConnector.lanAddresses().stream().map(ip -> "http://" + ip + ":" + running).toList()
|
||||
: List.of();
|
||||
List<PairedDevice> devices = deviceRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(RemoteDevice::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(PairedDevice::of)
|
||||
.toList();
|
||||
return new RemoteAccessStatus(config.enabled(), config.port(), running > 0, urls, lastError, devices);
|
||||
}
|
||||
|
||||
private RemoteAccessConfig currentConfig() {
|
||||
return configRepository.find().orElseGet(RemoteAccessConfig::disabledByDefault);
|
||||
}
|
||||
|
||||
// --- Appairage -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Nouveau code d'appairage (remplace le précédent).
|
||||
*
|
||||
* @throws IllegalStateException si l'accès distant n'est pas ouvert
|
||||
*/
|
||||
public synchronized PairingCode newPairingCode() {
|
||||
if (lanConnector.runningPort() <= 0) {
|
||||
throw new IllegalStateException("Activez d'abord l'accès depuis le réseau local.");
|
||||
}
|
||||
String code = String.format("%06d", random.nextInt(1_000_000));
|
||||
currentCode = new PairingCode(code, clock.instant().plus(CODE_TTL));
|
||||
attemptsLeft = CODE_MAX_ATTEMPTS;
|
||||
return currentCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Échange un code valide contre un jeton d'appareil (à poser en cookie). Le code est
|
||||
* consommé : un second appareil demande un nouveau code.
|
||||
*
|
||||
* @throws PairingRejectedException code absent, faux, expiré ou trop d'essais
|
||||
*/
|
||||
public synchronized PairingResult pair(String code, String deviceName, String userAgent) {
|
||||
Instant now = clock.instant();
|
||||
pruneFailures(now);
|
||||
if (recentFailures.size() >= GLOBAL_MAX_FAILURES_PER_MINUTE) {
|
||||
throw new PairingRejectedException("Trop d'essais. Patientez une minute.");
|
||||
}
|
||||
if (currentCode == null || now.isAfter(currentCode.expiresAt())) {
|
||||
currentCode = null;
|
||||
recordFailure(now);
|
||||
throw new PairingRejectedException("Aucun code valide : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
if (code == null || !constantTimeEquals(code.trim(), currentCode.code())) {
|
||||
recordFailure(now);
|
||||
if (--attemptsLeft <= 0) {
|
||||
currentCode = null;
|
||||
throw new PairingRejectedException("Trop d'essais : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
throw new PairingRejectedException("Code incorrect.");
|
||||
}
|
||||
currentCode = null;
|
||||
|
||||
String token = newToken();
|
||||
RemoteDevice device = deviceRepository.save(RemoteDevice.builder()
|
||||
.name(clean(deviceName, DEVICE_NAME_MAX, "Appareil"))
|
||||
.tokenHash(sha256(token))
|
||||
.userAgent(clean(userAgent, USER_AGENT_MAX, null))
|
||||
.createdAt(now)
|
||||
.lastSeenAt(now)
|
||||
.build());
|
||||
log.info("Accès distant : appareil appairé « {} »", device.getName());
|
||||
return new PairingResult(token, PairedDevice.of(device));
|
||||
}
|
||||
|
||||
/** Appareil correspondant au jeton présenté, s'il est connu (sinon : appairage requis). */
|
||||
public Optional<RemoteDevice> authenticate(String token) {
|
||||
if (token == null || token.isBlank()) return Optional.empty();
|
||||
Optional<RemoteDevice> device = deviceRepository.findByTokenHash(sha256(token));
|
||||
device.ifPresent(d -> {
|
||||
Instant now = clock.instant();
|
||||
if (d.getLastSeenAt() == null || d.getLastSeenAt().plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||
deviceRepository.touch(d.getId(), now);
|
||||
}
|
||||
});
|
||||
return device;
|
||||
}
|
||||
|
||||
/** Coupe l'accès d'un appareil. */
|
||||
public boolean revoke(String deviceId) {
|
||||
return deviceRepository.deleteById(deviceId);
|
||||
}
|
||||
|
||||
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
||||
public int lanPort() {
|
||||
return lanConnector.runningPort();
|
||||
}
|
||||
|
||||
// --- Outils -----------------------------------------------------------------------------
|
||||
|
||||
private void recordFailure(Instant now) {
|
||||
recentFailures.addLast(now);
|
||||
}
|
||||
|
||||
private void pruneFailures(Instant now) {
|
||||
Instant limit = now.minus(Duration.ofMinutes(1));
|
||||
while (!recentFailures.isEmpty() && recentFailures.peekFirst().isBefore(limit)) {
|
||||
recentFailures.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
static String sha256(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 indisponible", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean constantTimeEquals(String a, String b) {
|
||||
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String clean(String value, int max, String fallback) {
|
||||
if (value == null || value.isBlank()) return fallback;
|
||||
String trimmed = value.strip();
|
||||
return trimmed.length() > max ? trimmed.substring(0, max) : trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* État de l'accès distant, pour l'écran Paramètres du PC.
|
||||
*
|
||||
* @param enabled accès activé (réglage enregistré)
|
||||
* @param port port réseau dédié
|
||||
* @param running connecteur réseau effectivement ouvert
|
||||
* @param urls adresses à taper sur la tablette (une par interface réseau locale)
|
||||
* @param lastError dernière erreur d'ouverture (ex. port occupé au démarrage), ou null
|
||||
* @param devices appareils appairés
|
||||
*/
|
||||
public record RemoteAccessStatus(
|
||||
boolean enabled,
|
||||
int port,
|
||||
boolean running,
|
||||
List<String> urls,
|
||||
String lastError,
|
||||
List<PairedDevice> devices
|
||||
) {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.loremind.domain.campaigncontext.writingreview;
|
||||
|
||||
/**
|
||||
* Famille d'une remarque de relecture (Mentor d'écriture, phase M2). Sert à
|
||||
* regrouper les conseils côté front ; n'implique aucune gravité : une remarque de
|
||||
* relecture est un conseil d'auteur, jamais un blocage.
|
||||
*/
|
||||
public enum WritingRemarkCategory {
|
||||
/** Pouvoir des joueurs : vrais choix, chemins multiples, issues alternatives. */
|
||||
AGENCY,
|
||||
/** Rythme : variété des scènes, lisibilité de la structure. */
|
||||
PACING,
|
||||
/** Enjeux : ce que les joueurs risquent, pourquoi l'adversité agit. */
|
||||
STAKES,
|
||||
/** Narration : textes lus aux joueurs. */
|
||||
NARRATION
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public interface SessionRepository {
|
||||
/** Retourne UNE session active dans l'app (sémantique « legacy » — multi-actives possibles). */
|
||||
Optional<Session> findActive();
|
||||
|
||||
/** Toutes les sessions en cours (toutes Parties confondues), la plus récente d'abord. */
|
||||
List<Session> findAllActive();
|
||||
|
||||
/** Retourne la session active du Playthrough donné, s'il y en a une. */
|
||||
Optional<Session> findActiveByPlaythroughId(String playthroughId);
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.loremind.domain.remoteaccess;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Faits bruts sur la machine hôte, lus par le système (pas d'interprétation ici) :
|
||||
* réseaux connectés avec leur catégorie Windows, et règles ENTRANTES du pare-feu qui
|
||||
* visent l'exécutable de l'application.
|
||||
*
|
||||
* @param supported vérification possible sur ce système (Windows uniquement)
|
||||
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
|
||||
* @param networks réseaux connectés
|
||||
* @param rules règles entrantes du pare-feu pour ce programme
|
||||
*/
|
||||
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules) {
|
||||
|
||||
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
|
||||
public record Network(String name, String alias, String category) {}
|
||||
|
||||
/**
|
||||
* @param action {@code Allow} ou {@code Block}
|
||||
* @param profile profils couverts : {@code Any}, ou liste comme {@code Private, Public}
|
||||
* @param enabled {@code True} / {@code False}
|
||||
*/
|
||||
public record FirewallRule(String action, String profile, String enabled) {}
|
||||
|
||||
public static NetworkSnapshot unsupported() {
|
||||
return new NetworkSnapshot(false, null, List.of(), List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.loremind.domain.remoteaccess;
|
||||
|
||||
/**
|
||||
* Réglage de l'accès distant (singleton) : activé ou non, et port réseau ouvert
|
||||
* sur le réseau local quand il l'est.
|
||||
*
|
||||
* @param enabled accès depuis le réseau local autorisé
|
||||
* @param port port réseau dédié (distinct du port local de l'application)
|
||||
*/
|
||||
public record RemoteAccessConfig(boolean enabled, int port) {
|
||||
|
||||
/** Port proposé par défaut : libre en pratique, et distinct du 8080 local. */
|
||||
public static final int DEFAULT_PORT = 8765;
|
||||
|
||||
public static RemoteAccessConfig disabledByDefault() {
|
||||
return new RemoteAccessConfig(false, DEFAULT_PORT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.loremind.domain.remoteaccess;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Appareil (tablette, téléphone) autorisé à accéder à l'application de bureau depuis
|
||||
* le réseau local, après appairage par code.
|
||||
* <p>
|
||||
* <b>Sécurité :</b> seule l'empreinte SHA-256 du jeton est conservée ; le jeton en
|
||||
* clair n'existe que dans le cookie de l'appareil. Révoquer = supprimer la ligne.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class RemoteDevice {
|
||||
|
||||
private String id;
|
||||
|
||||
/** Nom choisi à l'appairage (« Tablette de Léa »), pour s'y retrouver dans la liste. */
|
||||
private String name;
|
||||
|
||||
/** Empreinte SHA-256 (hex) du jeton d'appareil. */
|
||||
private String tokenHash;
|
||||
|
||||
private String userAgent;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
private Instant lastSeenAt;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
|
||||
/**
|
||||
* Port vers le système hôte pour que l'accès distant fonctionne vraiment : sans règle
|
||||
* de pare-feu, ou sur un réseau classé « Public », Windows jette en silence les requêtes
|
||||
* de la tablette (elle charge sans fin).
|
||||
*/
|
||||
public interface HostNetworkAccess {
|
||||
|
||||
/** Résultat de la demande d'autorisation dans le pare-feu. */
|
||||
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
|
||||
|
||||
/** Lecture seule, sans droits administrateur. */
|
||||
NetworkSnapshot inspect();
|
||||
|
||||
/**
|
||||
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
|
||||
* administrateur du système (UAC) : bloque jusqu'à la réponse de l'utilisateur.
|
||||
*/
|
||||
FirewallFixOutcome allowThroughFirewall();
|
||||
|
||||
/** Ouvre la page des réglages réseau du système (pour passer un Wi-Fi en « Privé »). */
|
||||
void openNetworkSettings();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Port vers le « second guichet » réseau de l'application de bureau : un connecteur
|
||||
* HTTP ouvert sur le réseau local (toutes interfaces) à côté du connecteur habituel,
|
||||
* qui reste limité à la machine (127.0.0.1).
|
||||
* <p>
|
||||
* Tout ce qui arrive par ce connecteur vient d'un autre appareil (ou de la machine
|
||||
* elle-même via son adresse réseau) et doit présenter un jeton d'appareil.
|
||||
*/
|
||||
public interface LanConnector {
|
||||
|
||||
/**
|
||||
* Ouvre le connecteur sur ce port (le referme d'abord s'il tournait sur un autre).
|
||||
*
|
||||
* @throws IllegalStateException si le port est déjà occupé ou ne peut pas être ouvert
|
||||
*/
|
||||
void start(int port);
|
||||
|
||||
void stop();
|
||||
|
||||
/** Port du connecteur ouvert, ou -1 s'il est fermé. */
|
||||
int runningPort();
|
||||
|
||||
/** Adresses IPv4 de la machine sur le réseau local (pour composer l'URL à taper). */
|
||||
List<String> lanAddresses();
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Port de persistance du réglage d'accès distant (singleton). */
|
||||
public interface RemoteAccessConfigRepository {
|
||||
|
||||
Optional<RemoteAccessConfig> find();
|
||||
|
||||
RemoteAccessConfig save(RemoteAccessConfig config);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Port de persistance des appareils appairés. */
|
||||
public interface RemoteDeviceRepository {
|
||||
|
||||
RemoteDevice save(RemoteDevice device);
|
||||
|
||||
Optional<RemoteDevice> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RemoteDevice> findAll();
|
||||
|
||||
void touch(String id, Instant lastSeenAt);
|
||||
|
||||
boolean deleteById(String id);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Mode bureau : rouvre l'accès distant au démarrage s'il avait été activé. */
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class RemoteAccessBootstrap {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessBootstrap(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void reopenIfEnabled() {
|
||||
remoteAccessService.applySavedConfig();
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,13 @@ public class SystemTrayManager {
|
||||
open.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||
popup.add(open);
|
||||
|
||||
// Acces distant : ouvre la section Parametres ou l'on active l'acces
|
||||
// depuis une tablette et ou l'on affiche le code d'appairage.
|
||||
MenuItem remote = new MenuItem("Connecter une tablette…");
|
||||
remote.addActionListener(e -> DesktopSingleInstance.openUrl(
|
||||
"http://localhost:" + DesktopUserConfig.runningPort() + "/settings?section=remote-access"));
|
||||
popup.add(remote);
|
||||
|
||||
popup.addSeparator();
|
||||
|
||||
// Reglages : ouvre loremind.properties (port, identifiants admin) dans
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import org.apache.catalina.connector.Connector;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.apache.coyote.http11.AbstractHttp11Protocol;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.SocketException;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Second connecteur HTTP de Tomcat, ouvert À CHAUD sur toutes les interfaces quand le MJ
|
||||
* active l'accès distant (mode bureau uniquement).
|
||||
* <p>
|
||||
* Pourquoi un second connecteur plutôt que d'ouvrir le principal : le connecteur habituel
|
||||
* reste sur 127.0.0.1 (aucun changement de comportement, pas d'alerte du pare-feu Windows
|
||||
* chez qui n'active rien), et le port d'arrivée suffit à distinguer une requête locale d'une
|
||||
* requête venue du réseau (cf. {@code RemoteAccessFilter}). Ouverture et fermeture sans
|
||||
* redémarrer l'application.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class TomcatLanConnector implements LanConnector {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TomcatLanConnector.class);
|
||||
|
||||
/** Interfaces à ignorer pour composer l'URL : réseaux virtuels (VM, WSL, Docker, VPN…). */
|
||||
private static final List<String> VIRTUAL_HINTS = List.of(
|
||||
"virtual", "vmware", "vbox", "hyper-v", "vethernet", "docker", "wsl", "loopback", "tap-", "tun");
|
||||
|
||||
private final ApplicationContext context;
|
||||
private Connector connector;
|
||||
|
||||
public TomcatLanConnector(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start(int port) {
|
||||
if (connector != null && connector.getPort() == port) return;
|
||||
stop();
|
||||
ensurePortFree(port);
|
||||
|
||||
Tomcat tomcat = tomcat();
|
||||
Connector main = tomcat.getConnector();
|
||||
Connector lan = new Connector(main.getProtocolHandlerClassName());
|
||||
lan.setPort(port);
|
||||
lan.setProperty("address", "0.0.0.0");
|
||||
// Mêmes limites d'upload que le connecteur principal (imports PDF volumineux).
|
||||
lan.setMaxPostSize(main.getMaxPostSize());
|
||||
if (main.getProtocolHandler() instanceof AbstractHttp11Protocol<?> mainProtocol
|
||||
&& lan.getProtocolHandler() instanceof AbstractHttp11Protocol<?> lanProtocol) {
|
||||
lanProtocol.setMaxSwallowSize(mainProtocol.getMaxSwallowSize());
|
||||
}
|
||||
try {
|
||||
tomcat.getService().addConnector(lan); // démarre le connecteur : le service tourne déjà
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalStateException("Impossible d'ouvrir le port " + port + " : " + e.getMessage(), e);
|
||||
}
|
||||
connector = lan;
|
||||
log.info("Accès distant : connecteur réseau ouvert sur le port {}", port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
if (connector == null) return;
|
||||
try {
|
||||
tomcat().getService().removeConnector(connector);
|
||||
connector.destroy();
|
||||
} catch (Exception e) {
|
||||
log.warn("Fermeture du connecteur réseau incomplète : {}", e.getMessage());
|
||||
}
|
||||
log.info("Accès distant : connecteur réseau fermé (port {})", connector.getPort());
|
||||
connector = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int runningPort() {
|
||||
return connector != null ? connector.getPort() : -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> lanAddresses() {
|
||||
try {
|
||||
return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
|
||||
.filter(TomcatLanConnector::isPhysicalAndUp)
|
||||
.flatMap(nic -> Collections.list(nic.getInetAddresses()).stream())
|
||||
.filter(a -> a instanceof Inet4Address && a.isSiteLocalAddress())
|
||||
.map(a -> a.getHostAddress())
|
||||
.distinct()
|
||||
// Box domestique d'abord (192.168.x), puis 10.x / 172.16-31.x.
|
||||
.sorted(Comparator.comparing((String ip) -> !ip.startsWith("192.168.")).thenComparing(ip -> ip))
|
||||
.toList();
|
||||
} catch (SocketException e) {
|
||||
log.warn("Lecture des interfaces réseau impossible : {}", e.getMessage());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPhysicalAndUp(NetworkInterface nic) {
|
||||
try {
|
||||
if (!nic.isUp() || nic.isLoopback() || nic.isVirtual() || nic.isPointToPoint()) return false;
|
||||
} catch (SocketException e) {
|
||||
return false;
|
||||
}
|
||||
String label = (nic.getName() + " " + nic.getDisplayName()).toLowerCase(Locale.ROOT);
|
||||
return VIRTUAL_HINTS.stream().noneMatch(label::contains);
|
||||
}
|
||||
|
||||
/** Vérification préalable pour un message clair (sinon Tomcat ne log qu'une trace obscure). */
|
||||
private static void ensurePortFree(int port) {
|
||||
try (ServerSocket probe = new ServerSocket()) {
|
||||
probe.setReuseAddress(false);
|
||||
probe.bind(new InetSocketAddress(port));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Le port " + port + " est déjà utilisé par une autre application.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Tomcat tomcat() {
|
||||
if (context instanceof ServletWebServerApplicationContext web) {
|
||||
WebServer server = web.getWebServer();
|
||||
if (server instanceof TomcatWebServer tomcatServer) {
|
||||
return tomcatServer.getTomcat();
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Serveur web embarqué indisponible.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Accès au réseau et au pare-feu de Windows pour l'accès distant (mode bureau).
|
||||
* <p>
|
||||
* Lecture via PowerShell, sans droits administrateur. L'autorisation dans le pare-feu
|
||||
* passe par {@code Start-Process -Verb RunAs} : Windows affiche sa confirmation
|
||||
* administrateur (UAC) et l'utilisateur garde la main. La règle créée n'ouvre DM Loremind
|
||||
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
|
||||
* (réglage système, jamais modifié par l'application).
|
||||
* <p>
|
||||
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
||||
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
||||
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
|
||||
|
||||
static final String RULE_NAME = "DM Loremind (accès tablette)";
|
||||
private static final long INSPECT_TIMEOUT_S = 20;
|
||||
/** Le temps pour l'utilisateur de lire et de répondre à la fenêtre UAC. */
|
||||
private static final long ELEVATION_TIMEOUT_S = 180;
|
||||
/** Code Windows ERROR_CANCELLED : l'utilisateur a refusé la confirmation administrateur. */
|
||||
private static final int EXIT_CANCELLED = 1223;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public WindowsHostNetworkAccess(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NetworkSnapshot inspect() {
|
||||
String program = currentProgram();
|
||||
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
|
||||
try {
|
||||
String json = runPowerShell(inspectScript(program), INSPECT_TIMEOUT_S).output();
|
||||
return parseSnapshot(objectMapper, program, json);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("Accès distant : lecture du réseau / pare-feu impossible : {}", e.getMessage());
|
||||
return NetworkSnapshot.unsupported();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return NetworkSnapshot.unsupported();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FirewallFixOutcome allowThroughFirewall() {
|
||||
String program = currentProgram();
|
||||
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
|
||||
String outer = "try {\n"
|
||||
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
|
||||
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
|
||||
+ encode(allowScript(program)) + "')\n"
|
||||
+ " exit $p.ExitCode\n"
|
||||
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
|
||||
try {
|
||||
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
|
||||
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
||||
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
||||
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
||||
return outcome;
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("Accès distant : autorisation pare-feu impossible : {}", e.getMessage());
|
||||
return FirewallFixOutcome.FAILED;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return FirewallFixOutcome.FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openNetworkSettings() {
|
||||
if (!isWindows()) return;
|
||||
try {
|
||||
// « État du réseau » : le réseau connecté et son bouton « Propriétés » (type de profil).
|
||||
new ProcessBuilder("cmd", "/c", "start", "", "ms-settings:network-status").start();
|
||||
} catch (IOException e) {
|
||||
log.warn("Ouverture des réglages réseau impossible : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// --- Scripts --------------------------------------------------------------------------
|
||||
|
||||
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
|
||||
static String inspectScript(String program) {
|
||||
return "$ErrorActionPreference = 'SilentlyContinue'\n"
|
||||
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
|
||||
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
|
||||
+ "$p = '" + psQuote(program) + "'\n"
|
||||
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
||||
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
|
||||
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
|
||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules } | ConvertTo-Json -Depth 4 -Compress\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Exécuté ÉLEVÉ : retire les blocages entrants visant CE programme (créés par un « Annuler »
|
||||
* dans la fenêtre du pare-feu, ils l'emporteraient sur toute autorisation), remplace notre
|
||||
* propre règle si elle existe, puis autorise sur les réseaux privés uniquement.
|
||||
*/
|
||||
static String allowScript(String program) {
|
||||
String name = psQuote(RULE_NAME);
|
||||
return "try {\n"
|
||||
+ " $p = '" + psQuote(program) + "'\n"
|
||||
+ " Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' -and $_.Action.ToString() -eq 'Block' } | "
|
||||
+ "Remove-NetFirewallRule\n"
|
||||
+ " Get-NetFirewallRule -DisplayName '" + name + "' -ErrorAction SilentlyContinue | Remove-NetFirewallRule\n"
|
||||
+ " New-NetFirewallRule -DisplayName '" + name + "' -Direction Inbound -Program $p -Action Allow "
|
||||
+ "-Profile Private -ErrorAction Stop | Out-Null\n"
|
||||
+ " exit 0\n"
|
||||
+ "} catch { exit 2 }\n";
|
||||
}
|
||||
|
||||
static NetworkSnapshot parseSnapshot(ObjectMapper mapper, String program, String json) throws IOException {
|
||||
JsonNode root = mapper.readTree(json == null || json.isBlank() ? "{}" : json.trim());
|
||||
List<NetworkSnapshot.Network> networks = new ArrayList<>();
|
||||
for (JsonNode n : array(root.path("networks"))) {
|
||||
networks.add(new NetworkSnapshot.Network(text(n, "name"), text(n, "alias"), text(n, "category")));
|
||||
}
|
||||
List<NetworkSnapshot.FirewallRule> rules = new ArrayList<>();
|
||||
for (JsonNode r : array(root.path("rules"))) {
|
||||
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
|
||||
}
|
||||
return new NetworkSnapshot(true, program, networks, rules);
|
||||
}
|
||||
|
||||
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
|
||||
private static Iterable<JsonNode> array(JsonNode node) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) return List.of();
|
||||
return node.isArray() ? node : List.of(node);
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return v == null || v.isNull() ? null : v.asText();
|
||||
}
|
||||
|
||||
static String psQuote(String value) {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
static String encode(String script) {
|
||||
return Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
|
||||
}
|
||||
|
||||
// --- Exécution ------------------------------------------------------------------------
|
||||
|
||||
private record Result(int exitCode, String output) {}
|
||||
|
||||
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
||||
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
|
||||
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
process.getOutputStream().close();
|
||||
// Lecture en parallèle : un tampon de sortie plein bloquerait le processus avant sa fin.
|
||||
CompletableFuture<String> output = CompletableFuture.supplyAsync(() -> {
|
||||
try (InputStream out = process.getInputStream()) {
|
||||
return new String(out.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("PowerShell n'a pas répondu en " + timeoutSeconds + " s");
|
||||
}
|
||||
return new Result(process.exitValue(), output.join());
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
||||
}
|
||||
|
||||
/** Exécutable du processus courant : DM Loremind.exe en bureau (java.exe en développement). */
|
||||
private static String currentProgram() {
|
||||
return ProcessHandle.current().info().command().orElse(null);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entité JPA du réglage d'accès distant (migration V25). Singleton : une seule ligne,
|
||||
* {@code id = "current"}, comme la licence.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "remote_access_config")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteAccessConfigJpaEntity {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int port;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Entité JPA d'un appareil appairé pour l'accès distant (migration V25). */
|
||||
@Entity
|
||||
@Table(name = "remote_devices")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteDeviceJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, length = 64, unique = true)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "user_agent", length = 300)
|
||||
private String userAgent;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "last_seen_at")
|
||||
private Instant lastSeenAt;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface RemoteAccessConfigJpaRepository extends JpaRepository<RemoteAccessConfigJpaEntity, String> {
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RemoteDeviceJpaRepository extends JpaRepository<RemoteDeviceJpaEntity, Long> {
|
||||
|
||||
Optional<RemoteDeviceJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
/** Mise à jour ciblée (pas de relecture de l'entité à chaque requête d'une tablette). */
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("update RemoteDeviceJpaEntity d set d.lastSeenAt = :seenAt where d.id = :id")
|
||||
void touch(@Param("id") Long id, @Param("seenAt") Instant seenAt);
|
||||
}
|
||||
+2
@@ -17,5 +17,7 @@ public interface SessionJpaRepository extends JpaRepository<SessionJpaEntity, Lo
|
||||
|
||||
Optional<SessionJpaEntity> findFirstByEndedAtIsNull();
|
||||
|
||||
List<SessionJpaEntity> findByEndedAtIsNullOrderByStartedAtDesc();
|
||||
|
||||
Optional<SessionJpaEntity> findFirstByPlaythroughIdAndEndedAtIsNull(Long playthroughId);
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteAccessConfigJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteAccessConfigRepository implements RemoteAccessConfigRepository {
|
||||
|
||||
static final String CURRENT_ID = "current";
|
||||
|
||||
private final RemoteAccessConfigJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteAccessConfigRepository(RemoteAccessConfigJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteAccessConfig> find() {
|
||||
return jpa.findById(CURRENT_ID).map(e -> new RemoteAccessConfig(e.isEnabled(), e.getPort()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteAccessConfig save(RemoteAccessConfig config) {
|
||||
jpa.save(RemoteAccessConfigJpaEntity.builder()
|
||||
.id(CURRENT_ID)
|
||||
.enabled(config.enabled())
|
||||
.port(config.port())
|
||||
.updatedAt(Instant.now())
|
||||
.build());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteDeviceJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteDeviceRepository implements RemoteDeviceRepository {
|
||||
|
||||
private final RemoteDeviceJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteDeviceRepository(RemoteDeviceJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteDevice save(RemoteDevice device) {
|
||||
RemoteDeviceJpaEntity entity = RemoteDeviceJpaEntity.builder()
|
||||
.id(device.getId() != null ? Long.parseLong(device.getId()) : null)
|
||||
.name(device.getName())
|
||||
.tokenHash(device.getTokenHash())
|
||||
.userAgent(device.getUserAgent())
|
||||
.createdAt(device.getCreatedAt() != null ? device.getCreatedAt() : Instant.now())
|
||||
.lastSeenAt(device.getLastSeenAt())
|
||||
.build();
|
||||
return toDomain(jpa.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteDevice> findByTokenHash(String tokenHash) {
|
||||
return jpa.findByTokenHash(tokenHash).map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RemoteDevice> findAll() {
|
||||
return jpa.findAll().stream().map(this::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touch(String id, Instant lastSeenAt) {
|
||||
jpa.touch(Long.parseLong(id), lastSeenAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteById(String id) {
|
||||
Long key = Long.parseLong(id);
|
||||
if (!jpa.existsById(key)) return false;
|
||||
jpa.deleteById(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
private RemoteDevice toDomain(RemoteDeviceJpaEntity e) {
|
||||
return RemoteDevice.builder()
|
||||
.id(String.valueOf(e.getId()))
|
||||
.name(e.getName())
|
||||
.tokenHash(e.getTokenHash())
|
||||
.userAgent(e.getUserAgent())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.lastSeenAt(e.getLastSeenAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+7
@@ -52,6 +52,13 @@ public class PostgresSessionRepository implements SessionRepository {
|
||||
return jpaRepository.findFirstByEndedAtIsNull().map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Session> findAllActive() {
|
||||
return jpaRepository.findByEndedAtIsNullOrderByStartedAtDesc().stream()
|
||||
.map(this::toDomain)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Session> findActiveByPlaythroughId(String playthroughId) {
|
||||
return jpaRepository.findFirstByPlaythroughIdAndEndedAtIsNull(Long.parseLong(playthroughId))
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Garde de l'accès distant (mode bureau). Ne concerne QUE les requêtes arrivées par le
|
||||
* connecteur réseau local (port dédié) : celles du connecteur habituel (127.0.0.1) passent
|
||||
* sans changement.
|
||||
* <ul>
|
||||
* <li>front statique (hors {@code /api/}) : libre — la tablette doit pouvoir afficher l'écran d'appairage ;</li>
|
||||
* <li>{@code /api/config}, {@code /api/version}, appairage : libres ;</li>
|
||||
* <li>administration (Paramètres, données, mises à jour, licence) : refusée, toujours, même appairé ;</li>
|
||||
* <li>tout le reste de l'API : cookie d'appareil valide, sinon 401 {@code remote_pairing_required}.</li>
|
||||
* </ul>
|
||||
* Pas un {@code @Component} : instancié par {@link SecurityConfig} pour ne pas être enregistré
|
||||
* deux fois (chaîne de sécurité + filtre servlet automatique).
|
||||
*/
|
||||
public class RemoteAccessFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String DEVICE_COOKIE = "lm_device";
|
||||
|
||||
private static final List<String> PUBLIC_PATHS = List.of(
|
||||
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
|
||||
private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
|
||||
"/api/settings", "/api/admin", "/api/license");
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessFilter(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (!isFromLan(request, remoteAccessService.lanPort())) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String path = request.getRequestURI();
|
||||
if (!path.startsWith("/api/") || PUBLIC_PATHS.contains(path)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
if (LOCAL_ONLY_PREFIXES.stream().anyMatch(path::startsWith)) {
|
||||
reject(response, HttpServletResponse.SC_FORBIDDEN, "remote_forbidden");
|
||||
return;
|
||||
}
|
||||
if (remoteAccessService.authenticate(deviceToken(request)).isPresent()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
reject(response, HttpServletResponse.SC_UNAUTHORIZED, "remote_pairing_required");
|
||||
}
|
||||
|
||||
/** Arrivée par le connecteur réseau local ? (le port d'arrivée suffit : l'autre connecteur est sur 127.0.0.1). */
|
||||
public static boolean isFromLan(HttpServletRequest request, int lanPort) {
|
||||
return lanPort > 0 && request.getLocalPort() == lanPort;
|
||||
}
|
||||
|
||||
public static String deviceToken(HttpServletRequest request) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) return null;
|
||||
for (Cookie cookie : cookies) {
|
||||
if (DEVICE_COOKIE.equals(cookie.getName())) return cookie.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void reject(HttpServletResponse response, int status, String error) throws IOException {
|
||||
response.setStatus(status);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.getWriter().write("{\"error\":\"" + error + "\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -14,6 +16,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* Configuration Spring Security.
|
||||
@@ -24,6 +27,9 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
* l'UI elle-meme n'est pas authentifiee (trust model : reseau local ou
|
||||
* reverse-proxy front amont).
|
||||
* <p>
|
||||
* Mode bureau : l'acces depuis une tablette passe par un connecteur reseau dedie,
|
||||
* garde par {@link RemoteAccessFilter} (jeton d'appareil obtenu par code d'appairage).
|
||||
* <p>
|
||||
* Fail-closed : refuse de demarrer si admin.password n'est pas defini.
|
||||
*/
|
||||
@Configuration
|
||||
@@ -58,7 +64,15 @@ public class SecurityConfig {
|
||||
// S4502 : API stateless en HTTP Basic sans cookie — CSRF sans objet (voir javadoc de classe).
|
||||
@SuppressWarnings("java:S4502")
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
public SecurityFilterChain filterChain(HttpSecurity http,
|
||||
ObjectProvider<RemoteAccessService> remoteAccess) throws Exception {
|
||||
// Mode bureau : garde de l'accès distant (tablette sur le réseau local), placée AVANT
|
||||
// le HTTP Basic pour qu'un appareil du réseau ne puisse même pas tenter le mot de
|
||||
// passe admin. Absente en Docker (le service n'existe que sous le profil local).
|
||||
RemoteAccessService remoteAccessService = remoteAccess.getIfAvailable();
|
||||
if (remoteAccessService != null) {
|
||||
http.addFilterBefore(new RemoteAccessFilter(remoteAccessService), BasicAuthenticationFilter.class);
|
||||
}
|
||||
http
|
||||
// API stateless : pas de session, pas de cookie => CSRF sans objet.
|
||||
// Les credentials HTTP Basic sont envoyes a chaque requete, donc
|
||||
|
||||
+14
-2
@@ -13,15 +13,18 @@ import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.RandomTableRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ArcDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ChapterDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.NpcDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.QuestDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.RandomTableDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.SceneDTO;
|
||||
import com.loremind.infrastructure.web.dto.playcontext.PlaythroughDTO;
|
||||
import com.loremind.infrastructure.web.mapper.ArcMapper;
|
||||
import com.loremind.infrastructure.web.mapper.ChapterMapper;
|
||||
import com.loremind.infrastructure.web.mapper.NpcMapper;
|
||||
import com.loremind.infrastructure.web.mapper.PlaythroughMapper;
|
||||
import com.loremind.infrastructure.web.mapper.QuestMapper;
|
||||
import com.loremind.infrastructure.web.mapper.RandomTableMapper;
|
||||
import com.loremind.infrastructure.web.mapper.SceneMapper;
|
||||
@@ -37,7 +40,7 @@ import java.util.Map;
|
||||
|
||||
/**
|
||||
* Endpoint AGRÉGÉ de l'arbre de campagne : tout ce dont la sidebar a besoin en UNE
|
||||
* requête HTTP — arcs → chapitres → scènes, PNJ, tables, ennemis, quêtes et readiness.
|
||||
* requête HTTP — arcs → chapitres → scènes, PNJ, tables, ennemis, quêtes, parties et readiness.
|
||||
*
|
||||
* <p>Remplace la rafale d'appels du front (~1 + N arcs + M chapitres + 5 listes ≈ 15-20
|
||||
* requêtes À CHAQUE navigation) : la latence HTTP par appel dominait le temps de rendu
|
||||
@@ -56,6 +59,7 @@ public class CampaignTreeController {
|
||||
private final RandomTableRepository randomTableRepository;
|
||||
private final EnemyRepository enemyRepository;
|
||||
private final QuestRepository questRepository;
|
||||
private final PlaythroughRepository playthroughRepository;
|
||||
private final CampaignReadinessService readinessService;
|
||||
private final ArcMapper arcMapper;
|
||||
private final ChapterMapper chapterMapper;
|
||||
@@ -63,6 +67,7 @@ public class CampaignTreeController {
|
||||
private final NpcMapper npcMapper;
|
||||
private final RandomTableMapper randomTableMapper;
|
||||
private final QuestMapper questMapper;
|
||||
private final PlaythroughMapper playthroughMapper;
|
||||
|
||||
// S107 (trop de paramètres) : constructeur d'INJECTION pur, sans logique — l'endpoint
|
||||
// est un agrégat volontaire (une requête pour toute la sidebar), il consomme donc
|
||||
@@ -77,13 +82,15 @@ public class CampaignTreeController {
|
||||
RandomTableRepository randomTableRepository,
|
||||
EnemyRepository enemyRepository,
|
||||
QuestRepository questRepository,
|
||||
PlaythroughRepository playthroughRepository,
|
||||
CampaignReadinessService readinessService,
|
||||
ArcMapper arcMapper,
|
||||
ChapterMapper chapterMapper,
|
||||
SceneMapper sceneMapper,
|
||||
NpcMapper npcMapper,
|
||||
RandomTableMapper randomTableMapper,
|
||||
QuestMapper questMapper) {
|
||||
QuestMapper questMapper,
|
||||
PlaythroughMapper playthroughMapper) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
@@ -92,6 +99,7 @@ public class CampaignTreeController {
|
||||
this.randomTableRepository = randomTableRepository;
|
||||
this.enemyRepository = enemyRepository;
|
||||
this.questRepository = questRepository;
|
||||
this.playthroughRepository = playthroughRepository;
|
||||
this.readinessService = readinessService;
|
||||
this.arcMapper = arcMapper;
|
||||
this.chapterMapper = chapterMapper;
|
||||
@@ -99,6 +107,7 @@ public class CampaignTreeController {
|
||||
this.npcMapper = npcMapper;
|
||||
this.randomTableMapper = randomTableMapper;
|
||||
this.questMapper = questMapper;
|
||||
this.playthroughMapper = playthroughMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,6 +122,7 @@ public class CampaignTreeController {
|
||||
List<RandomTableDTO> randomTables,
|
||||
List<Enemy> enemies,
|
||||
List<QuestDTO> quests,
|
||||
List<PlaythroughDTO> playthroughs,
|
||||
CampaignReadinessAssessment readiness
|
||||
) {}
|
||||
|
||||
@@ -147,6 +157,8 @@ public class CampaignTreeController {
|
||||
enemyRepository.findByCampaignId(campaignId),
|
||||
questRepository.findByCampaignId(campaignId).stream()
|
||||
.map(questMapper::toDTO).toList(),
|
||||
playthroughRepository.findByCampaignId(campaignId).stream()
|
||||
.map(playthroughMapper::toDTO).toList(),
|
||||
readinessService.assess(campaignId)));
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.GuidedSkeleton;
|
||||
import com.loremind.application.campaigncontext.GuidedSkeletonService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller des méthodes guidées (Mentor d'écriture, phase M3) : persiste le
|
||||
* squelette (arc → chapitre → scènes) construit question par question par le MJ.
|
||||
*
|
||||
* <p>201 + ids créés ; 400 si le squelette est invalide ({@code GlobalExceptionHandler}) ;
|
||||
* 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/guided-skeleton")
|
||||
public class GuidedSkeletonController {
|
||||
|
||||
private final GuidedSkeletonService guidedSkeletonService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public GuidedSkeletonController(GuidedSkeletonService guidedSkeletonService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.guidedSkeletonService = guidedSkeletonService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<GuidedSkeleton.Result> create(@PathVariable String campaignId,
|
||||
@RequestBody GuidedSkeleton skeleton) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
// Squelette invalide : IllegalArgumentException → 400 via GlobalExceptionHandler.
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(guidedSkeletonService.create(campaignId, skeleton));
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.NetworkReadiness;
|
||||
import com.loremind.application.remoteaccess.PairingCode;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessStatus;
|
||||
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Réglage de l'accès distant, côté PC (mode bureau). Sous {@code /api/settings} : réservé
|
||||
* à l'admin (HTTP Basic) ET à la machine elle-même ({@code RemoteAccessFilter} refuse ces
|
||||
* routes à tout appareil du réseau, même appairé). 404 en Docker (profil {@code local} absent).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/settings/remote-access")
|
||||
public class RemoteAccessAdminController {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
private final HostNetworkAccess hostNetworkAccess;
|
||||
|
||||
public RemoteAccessAdminController(RemoteAccessService remoteAccessService, HostNetworkAccess hostNetworkAccess) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
this.hostNetworkAccess = hostNetworkAccess;
|
||||
}
|
||||
|
||||
public record ConfigureRequest(boolean enabled, int port) {}
|
||||
|
||||
/** Réponse du bouton « Autoriser dans le pare-feu » : ce qui s'est passé + le nouvel état. */
|
||||
public record FirewallFixResponse(HostNetworkAccess.FirewallFixOutcome outcome, NetworkReadiness readiness) {}
|
||||
|
||||
@GetMapping
|
||||
public RemoteAccessStatus status() {
|
||||
return remoteAccessService.status();
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public RemoteAccessStatus configure(@RequestBody ConfigureRequest request) {
|
||||
return remoteAccessService.configure(request.enabled(), request.port());
|
||||
}
|
||||
|
||||
@PostMapping("/pairing-code")
|
||||
public PairingCode newPairingCode() {
|
||||
return remoteAccessService.newPairingCode();
|
||||
}
|
||||
|
||||
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
|
||||
@GetMapping("/network-check")
|
||||
public NetworkReadiness networkCheck() {
|
||||
return NetworkReadiness.evaluate(hostNetworkAccess.inspect());
|
||||
}
|
||||
|
||||
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
|
||||
@PostMapping("/firewall-rule")
|
||||
public FirewallFixResponse allowThroughFirewall() {
|
||||
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
|
||||
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect()));
|
||||
}
|
||||
|
||||
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
|
||||
@PostMapping("/open-network-settings")
|
||||
public ResponseEntity<Void> openNetworkSettings() {
|
||||
hostNetworkAccess.openNetworkSettings();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@DeleteMapping("/devices/{id}")
|
||||
public ResponseEntity<Void> revoke(@PathVariable String id) {
|
||||
return remoteAccessService.revoke(id) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
/** Port occupé, accès non ouvert… : conflit d'état, message prêt à afficher. */
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<Map<String, String>> conflict(IllegalStateException e) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.PairedDevice;
|
||||
import com.loremind.application.remoteaccess.PairingRejectedException;
|
||||
import com.loremind.application.remoteaccess.PairingResult;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Appairage d'une tablette (mode bureau) : seules routes d'API joignables depuis le réseau
|
||||
* sans jeton (avec {@code /api/config} et {@code /api/version}).
|
||||
* <p>
|
||||
* Le jeton est posé en cookie {@code HttpOnly} + {@code SameSite=Strict} : envoyé
|
||||
* automatiquement par le navigateur (y compris pour les {@code <img>}), illisible par le
|
||||
* JavaScript de la page, et jamais joint à une requête venue d'un autre site (anti-CSRF).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/remote-access")
|
||||
public class RemotePairingController {
|
||||
|
||||
static final Duration COOKIE_LIFETIME = Duration.ofDays(365);
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemotePairingController(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
public record PairRequest(String code, String deviceName) {}
|
||||
|
||||
/** Ce que le front a besoin de savoir pour décider d'afficher l'écran d'appairage. */
|
||||
public record SessionInfo(boolean remote, boolean paired, String deviceName) {}
|
||||
|
||||
@PostMapping("/pair")
|
||||
public ResponseEntity<PairedDevice> pair(@RequestBody PairRequest request,
|
||||
@RequestHeader(value = HttpHeaders.USER_AGENT, required = false) String userAgent) {
|
||||
PairingResult result = remoteAccessService.pair(request.code(), request.deviceName(), userAgent);
|
||||
ResponseCookie cookie = ResponseCookie.from(RemoteAccessFilter.DEVICE_COOKIE, result.token())
|
||||
.httpOnly(true)
|
||||
.sameSite("Strict")
|
||||
.path("/")
|
||||
.maxAge(COOKIE_LIFETIME)
|
||||
.build();
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()).body(result.device());
|
||||
}
|
||||
|
||||
@GetMapping("/session")
|
||||
public SessionInfo session(HttpServletRequest request) {
|
||||
boolean remote = RemoteAccessFilter.isFromLan(request, remoteAccessService.lanPort());
|
||||
if (!remote) return new SessionInfo(false, true, null);
|
||||
Optional<RemoteDevice> device = remoteAccessService.authenticate(RemoteAccessFilter.deviceToken(request));
|
||||
return new SessionInfo(true, device.isPresent(), device.map(RemoteDevice::getName).orElse(null));
|
||||
}
|
||||
|
||||
@ExceptionHandler(PairingRejectedException.class)
|
||||
public ResponseEntity<Map<String, String>> rejected(PairingRejectedException e) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+16
-4
@@ -56,11 +56,23 @@ public class SessionController {
|
||||
.orElse(ResponseEntity.noContent().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste des sessions. {@code active=true} : uniquement celles en cours, toutes Parties
|
||||
* confondues, la plus récente d'abord (raccourci « Séance en cours » du menu, rafraîchi
|
||||
* à chaque navigation — évite de rapatrier tout l'historique).
|
||||
*/
|
||||
@GetMapping
|
||||
public ResponseEntity<List<SessionDTO>> getSessions(@RequestParam(value = "playthroughId", required = false) String playthroughId) {
|
||||
List<Session> sessions = (playthroughId == null || playthroughId.isBlank())
|
||||
? sessionService.getAll()
|
||||
: sessionService.getByPlaythroughId(playthroughId);
|
||||
public ResponseEntity<List<SessionDTO>> getSessions(
|
||||
@RequestParam(value = "playthroughId", required = false) String playthroughId,
|
||||
@RequestParam(value = "active", defaultValue = "false") boolean active) {
|
||||
List<Session> sessions;
|
||||
if (active) {
|
||||
sessions = sessionService.getAllActive();
|
||||
} else if (playthroughId == null || playthroughId.isBlank()) {
|
||||
sessions = sessionService.getAll();
|
||||
} else {
|
||||
sessions = sessionService.getByPlaythroughId(playthroughId);
|
||||
}
|
||||
List<SessionDTO> dtos = sessions.stream()
|
||||
.map(sessionMapper::toDTO)
|
||||
.toList();
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.WritingReviewReport;
|
||||
import com.loremind.application.campaigncontext.WritingReviewService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller de la relecture d'éditeur (Mentor d'écriture, phase M2) : conseils
|
||||
* d'auteur sur la qualité de l'écriture d'une campagne.
|
||||
*
|
||||
* <p>Read-model pur, toujours 200 quand la campagne existe (les remarques conseillent,
|
||||
* elles ne bloquent rien). 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/writing-review")
|
||||
public class WritingReviewController {
|
||||
|
||||
private final WritingReviewService writingReviewService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public WritingReviewController(WritingReviewService writingReviewService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.writingReviewService = writingReviewService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<WritingReviewReport> getWritingReview(@PathVariable String campaignId) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(writingReviewService.review(campaignId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
-- remote_access_config : réglage singleton (id = 'current') — activé ou non, port réseau.
|
||||
-- remote_devices : appareils appairés par code ; seule l'EMPREINTE SHA-256 du jeton
|
||||
-- est stockée (le jeton lui-même ne vit que dans le cookie de l'appareil).
|
||||
-- Tables présentes partout (Docker compris) mais utilisées uniquement en mode bureau.
|
||||
-- Compatible Postgres et H2 (MODE=PostgreSQL).
|
||||
create table remote_access_config (
|
||||
id varchar(32) not null,
|
||||
enabled boolean not null,
|
||||
port integer not null,
|
||||
updated_at timestamp(6) with time zone not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table remote_devices (
|
||||
id bigint generated by default as identity,
|
||||
name varchar(100) not null,
|
||||
token_hash varchar(64) not null,
|
||||
user_agent varchar(300),
|
||||
created_at timestamp(6) with time zone not null,
|
||||
last_seen_at timestamp(6) with time zone,
|
||||
primary key (id)
|
||||
);
|
||||
create unique index ux_remote_device_token on remote_devices (token_hash);
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link GuidedSkeletonService} (Mentor d'écriture, phase M3) :
|
||||
* placement (nouvel arc / arc existant), champs reportés, chaînage des scènes, validations.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GuidedSkeletonServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private ArcService arcService;
|
||||
@Mock private ChapterService chapterService;
|
||||
@Mock private SceneService sceneService;
|
||||
|
||||
@InjectMocks private GuidedSkeletonService service;
|
||||
|
||||
private final List<Scene> createdScenes = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void stubCreations() {
|
||||
AtomicInteger ids = new AtomicInteger();
|
||||
when(arcService.createArc(any(Arc.class))).thenAnswer(inv -> {
|
||||
Arc a = inv.getArgument(0);
|
||||
a.setId("new-arc");
|
||||
return a;
|
||||
});
|
||||
when(chapterService.createChapter(any(Chapter.class))).thenAnswer(inv -> {
|
||||
Chapter c = inv.getArgument(0);
|
||||
c.setId("new-chap");
|
||||
return c;
|
||||
});
|
||||
when(sceneService.createScene(any(Scene.class))).thenAnswer(inv -> {
|
||||
Scene s = inv.getArgument(0);
|
||||
s.setId("scene-" + ids.incrementAndGet());
|
||||
createdScenes.add(s);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
private static GuidedSkeleton.SceneSpec room(String name, SceneType type) {
|
||||
return new GuidedSkeleton.SceneSpec(name, "Ce qui s'y passe", type, "La crypte",
|
||||
"Combattre ou négocier", "Le gardien protège son frère", null);
|
||||
}
|
||||
|
||||
private static GuidedSkeleton skeleton(String arcId, String newArcName, boolean link) {
|
||||
return new GuidedSkeleton(arcId, newArcName,
|
||||
new GuidedSkeleton.ChapterSpec("La crypte oubliée", "Une accroche", "Retrouver le reliquaire", "Le village sera maudit"),
|
||||
List.of(room("Salle 1", SceneType.ENCOUNTER), room("Salle 2", SceneType.LOCATION), room("Salle 3", SceneType.REVELATION)),
|
||||
link, "Vers la salle suivante");
|
||||
}
|
||||
|
||||
@Test
|
||||
void newArc_isLinear_andPlacedAfterVisibleArcs_beforeSystemArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build(),
|
||||
Arc.builder().id("a2").type(ArcType.HUB).order(1).build(),
|
||||
Arc.builder().id("sys").type(ArcType.SYSTEM).order(9999).build()));
|
||||
|
||||
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Les terres brûlées", false));
|
||||
|
||||
ArgumentCaptor<Arc> arc = ArgumentCaptor.forClass(Arc.class);
|
||||
verify(arcService).createArc(arc.capture());
|
||||
assertEquals(ArcType.LINEAR, arc.getValue().getType());
|
||||
assertEquals(2, arc.getValue().getOrder());
|
||||
assertEquals(CAMP, arc.getValue().getCampaignId());
|
||||
assertEquals("new-arc", result.arcId());
|
||||
assertEquals("new-chap", result.chapterId());
|
||||
assertEquals(List.of("scene-1", "scene-2", "scene-3"), result.sceneIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingArc_chapterAppendedAfterExistingChapters_withItsFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build()));
|
||||
when(chapterRepository.findByArcId("a1")).thenReturn(List.of(
|
||||
Chapter.builder().id("c1").arcId("a1").order(0).build(),
|
||||
Chapter.builder().id("c2").arcId("a1").order(3).build()));
|
||||
|
||||
service.create(CAMP, skeleton("a1", null, false));
|
||||
|
||||
verify(arcService, never()).createArc(any(Arc.class));
|
||||
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||
verify(chapterService).createChapter(chapter.capture());
|
||||
assertEquals("a1", chapter.getValue().getArcId());
|
||||
assertEquals(4, chapter.getValue().getOrder());
|
||||
assertEquals("Retrouver le reliquaire", chapter.getValue().getPlayerObjectives());
|
||||
assertEquals("Le village sera maudit", chapter.getValue().getNarrativeStakes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scenes_keepOrderTypeAndFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", false));
|
||||
|
||||
assertEquals(3, createdScenes.size());
|
||||
Scene first = createdScenes.get(0);
|
||||
assertEquals(0, first.getOrder());
|
||||
assertEquals("new-chap", first.getChapterId());
|
||||
assertEquals(SceneType.ENCOUNTER, first.getType());
|
||||
assertEquals("La crypte", first.getLocation());
|
||||
assertEquals("Combattre ou négocier", first.getChoicesConsequences());
|
||||
assertEquals("Le gardien protège son frère", first.getGmSecretNotes());
|
||||
assertEquals(SceneType.REVELATION, createdScenes.get(2).getType());
|
||||
assertEquals(2, createdScenes.get(2).getOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkSequentially_chainsEachSceneToTheNext_lastHasNoExit() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", true));
|
||||
|
||||
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||
assertEquals("scene-2", createdScenes.get(0).getBranches().get(0).targetSceneId());
|
||||
assertEquals("Vers la salle suivante", createdScenes.get(0).getBranches().get(0).label());
|
||||
assertEquals("scene-3", createdScenes.get(1).getBranches().get(0).targetSceneId());
|
||||
assertTrue(createdScenes.get(2).getBranches() == null || createdScenes.get(2).getBranches().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedScenes_areSkipped_andBlankFieldsStoredAsNull() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
GuidedSkeleton s = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", " ", null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("Salle", " ", null, "", null, null, null),
|
||||
new GuidedSkeleton.SceneSpec(" ", "ignorée", SceneType.EVENT, null, null, null, null)),
|
||||
false, null);
|
||||
|
||||
service.create(CAMP, s);
|
||||
|
||||
assertEquals(1, createdScenes.size());
|
||||
assertNull(createdScenes.get(0).getDescription());
|
||||
assertNull(createdScenes.get(0).getLocation());
|
||||
assertEquals(SceneType.GENERIC, createdScenes.get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_ambiguousPlacement() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("a1", "Arc", false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton(null, " ", false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_arcOfAnotherCampaign_orNonLinearArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("hub").type(ArcType.HUB).order(0).build()));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("ailleurs", null, false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("hub", null, false)));
|
||||
verify(chapterService, never()).createChapter(any(Chapter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_missingChapterName_orNoNamedScene() {
|
||||
GuidedSkeleton noChapterName = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec(" ", null, null, null), List.of(room("S", null)), false, null);
|
||||
GuidedSkeleton noScene = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", null, null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("", null, null, null, null, null, null)), false, null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link WritingReviewService} (Mentor d'écriture, phase M2).
|
||||
* Chaque règle WRITE-xxx a son cas positif ET un cas qui ne doit PAS la déclencher
|
||||
* (le mentor doit rester sobre : un faux positif décourage le débutant).
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WritingReviewServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private CampaignRepository campaignRepository;
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private QuestRepository questRepository;
|
||||
|
||||
@InjectMocks private WritingReviewService service;
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static Arc arc(String id, ArcType type) {
|
||||
return Arc.builder().id(id).name(id).campaignId(CAMP).type(type).order(0).stakes("Le village brûle").build();
|
||||
}
|
||||
|
||||
private static Chapter chapter(String id, String arcId) {
|
||||
return Chapter.builder().id(id).name(id).arcId(arcId).order(0).narrativeStakes("Un allié en danger").build();
|
||||
}
|
||||
|
||||
/** Scène « propre » : typée, avec un choix décrit (ne déclenche aucune règle seule). */
|
||||
private static Scene.SceneBuilder scene(String id, int order) {
|
||||
return Scene.builder().id(id).name(id).chapterId("chap").order(order)
|
||||
.type(SceneType.NPC).choicesConsequences("Convaincre ou menacer");
|
||||
}
|
||||
|
||||
private void tree(Arc arc, Chapter chapter, List<Scene> scenes) {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId(arc.getId())).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId(chapter.getId())).thenReturn(scenes);
|
||||
}
|
||||
|
||||
private void tree(List<Scene> scenes) {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"), scenes);
|
||||
}
|
||||
|
||||
private Set<String> ruleIds() {
|
||||
return service.review(CAMP).remarks().stream().map(WritingRemark::ruleId).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private WritingRemark remark(String ruleId) {
|
||||
return service.review(CAMP).remarks().stream().filter(r -> r.ruleId().equals(ruleId))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("Règle absente : " + ruleId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCampaign_hasNoRemark() {
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wellWrittenChapter_hasNoRemark() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("s2", 1).type(SceneType.LOCATION).build()));
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
// --- WRITE-001 : couloir ---
|
||||
|
||||
@Test
|
||||
void corridor_threeScenesWithoutChoiceNorBranch() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).choicesConsequences(null).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-001-CORRIDOR");
|
||||
assertEquals(ReadinessEntityType.CHAPTER, r.entityType());
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corridor_notRaised_whenOneSceneOffersAChoice() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-001-CORRIDOR"));
|
||||
}
|
||||
|
||||
// --- WRITE-002 : faux carrefour ---
|
||||
|
||||
@Test
|
||||
void fakeChoice_allBranchesLeadToSameScene() {
|
||||
Scene target = scene("s2", 1).name("La crypte").type(SceneType.LOCATION).build();
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s2"))).build(),
|
||||
target));
|
||||
|
||||
WritingRemark r = remark("WRITE-002-FAKE-CHOICE");
|
||||
assertEquals("s1", r.entityId());
|
||||
assertEquals("La crypte", r.params().get("target"));
|
||||
assertEquals("2", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fakeChoice_notRaised_whenBranchesDiverge() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s3"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-002-FAKE-CHOICE"));
|
||||
}
|
||||
|
||||
// --- WRITE-003 : révélation à chemin unique ---
|
||||
|
||||
@Test
|
||||
void singleClue_revelationReachableByOnePath() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
|
||||
assertEquals("1", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_withTwoPaths_orInChapterWithoutLinks() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(SceneBranch.of("B", "rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_inChapterWithoutAnyLink() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
// --- WRITE-004 : rythme monotone ---
|
||||
|
||||
@Test
|
||||
void monotonousPacing_threeFightsInARow() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).enemies("Deux gobelins").build(),
|
||||
scene("s3", 2).combatDifficulty("Difficile").build(),
|
||||
scene("s4", 3).type(SceneType.LOCATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-004-MONOTONOUS-PACING");
|
||||
assertEquals("COMBAT", r.params().get("kind"));
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monotonousPacing_notRaised_whenVaried_orUntyped() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).type(SceneType.NPC).build(),
|
||||
scene("s3", 2).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s4", 3).type(SceneType.GENERIC).build(),
|
||||
scene("s5", 4).type(SceneType.GENERIC).build(),
|
||||
scene("s6", 5).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-004-MONOTONOUS-PACING"));
|
||||
}
|
||||
|
||||
// --- WRITE-005 : sans enjeu ---
|
||||
|
||||
@Test
|
||||
void noStakes_onChapterAndArc() {
|
||||
Arc a = Arc.builder().id("arc").name("Arc").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Chapter c = Chapter.builder().id("chap").name("Chap").arcId("arc").order(0).build();
|
||||
tree(a, c, List.of(scene("s1", 0).branches(List.of(SceneBranch.of("A", "s1"))).build()));
|
||||
|
||||
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||
.filter(r -> r.ruleId().equals("WRITE-005-NO-STAKES")).toList();
|
||||
assertEquals(Set.of(ReadinessEntityType.ARC, ReadinessEntityType.CHAPTER),
|
||||
remarks.stream().map(WritingRemark::entityType).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_notRaised_onEmptyArc_norOnSystemArc() {
|
||||
Arc empty = Arc.builder().id("empty").name("Vide").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Arc system = Arc.builder().id("sys").name("Quêtes libres").campaignId(CAMP).type(ArcType.SYSTEM).order(9999).build();
|
||||
Chapter container = Chapter.builder().id("box").name("Q").arcId("sys").order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(empty, system));
|
||||
when(chapterRepository.findByArcId("empty")).thenReturn(List.of());
|
||||
when(chapterRepository.findByArcId("sys")).thenReturn(List.of(container));
|
||||
when(sceneRepository.findByChapterId("box")).thenReturn(List.of(scene("s1", 0).build()));
|
||||
|
||||
assertFalse(ruleIds().contains("WRITE-005-NO-STAKES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_raisedOnHubArcCarriedByQuests() {
|
||||
Arc hub = Arc.builder().id("hub").name("Hub").campaignId(CAMP).type(ArcType.HUB).order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(hub));
|
||||
when(questRepository.findByCampaignId(CAMP))
|
||||
.thenReturn(List.of(Quest.builder().id("q").campaignId(CAMP).arcId("hub").build()));
|
||||
|
||||
assertEquals(ReadinessEntityType.ARC, remark("WRITE-005-NO-STAKES").entityType());
|
||||
}
|
||||
|
||||
// --- WRITE-006 / WRITE-007 : narration ---
|
||||
|
||||
@Test
|
||||
void longNarration_overThreshold() {
|
||||
String text = "a".repeat(WritingReviewService.LONG_NARRATION_CHARS + 1);
|
||||
tree(List.of(scene("s1", 0).playerNarration(text).build()));
|
||||
|
||||
assertEquals(String.valueOf(text.length()), remark("WRITE-006-LONG-NARRATION").params().get("chars"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_capturesThePhrase_inFrenchAndEnglish() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("La porte grince. Vous avez peur et reculez.").build()));
|
||||
assertEquals("Vous avez peur", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_english() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("The door creaks open. You enter the hall.").build()));
|
||||
assertEquals("You enter", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narration_notRaised_whenDescriptiveAndShort() {
|
||||
tree(List.of(scene("s1", 0)
|
||||
.playerNarration("La porte grince. Une odeur de cire flotte dans l'air. Que faites-vous ?").build()));
|
||||
Set<String> ids = ruleIds();
|
||||
assertFalse(ids.contains("WRITE-006-LONG-NARRATION"));
|
||||
assertFalse(ids.contains("WRITE-007-NARRATION-DECIDES"));
|
||||
}
|
||||
|
||||
// --- WRITE-008 : combat sans but ---
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null).build()));
|
||||
assertEquals("s1", remark("WRITE-008-COMBAT-NO-PURPOSE").entityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose_notRaised_whenGmNotesExplainMotives() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||
.gmSecretNotes("Ils veulent couler la barque").build()));
|
||||
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||
}
|
||||
|
||||
// --- WRITE-009 : fin unique ---
|
||||
|
||||
@Test
|
||||
void singleEnding_onLastSceneOfLinearArc() {
|
||||
tree(arc("arc", ArcType.LINEAR), chapter("chap", "arc"), List.of(
|
||||
scene("s1", 0).build(),
|
||||
scene("final", 1).type(SceneType.LOCATION).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-009-SINGLE-ENDING");
|
||||
assertEquals("final", r.entityId());
|
||||
assertEquals("arc", r.params().get("arc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleEnding_notRaised_onHubArc_orWhenFinaleHasChoices() {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"),
|
||||
List.of(scene("final", 0).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-009-SINGLE-ENDING"));
|
||||
}
|
||||
|
||||
// --- WRITE-010 : scènes non typées ---
|
||||
|
||||
@Test
|
||||
void untypedScenes_whenMostScenesAreGeneric() {
|
||||
List<Scene> scenes = new ArrayList<>(IntStream.range(0, 5)
|
||||
.mapToObj(i -> scene("s" + i, i).type(SceneType.GENERIC).build()).toList());
|
||||
tree(scenes);
|
||||
when(campaignRepository.findById(CAMP))
|
||||
.thenReturn(Optional.of(Campaign.builder().id(CAMP).name("Ma campagne").build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-010-UNTYPED-SCENES");
|
||||
assertEquals(ReadinessEntityType.CAMPAIGN, r.entityType());
|
||||
assertEquals("100", r.params().get("percent"));
|
||||
// Remarque de campagne en tête de liste.
|
||||
assertEquals("WRITE-010-UNTYPED-SCENES", service.review(CAMP).remarks().get(0).ruleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untypedScenes_notRaised_belowMinimumSceneCount() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot.FirewallRule;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot.Network;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Test du verdict « une tablette peut-elle joindre ce PC ? » à partir des faits lus sur Windows. */
|
||||
class NetworkReadinessTest {
|
||||
|
||||
private static final Network HOME_PRIVATE = new Network("Bbox-Maison", "Wi-Fi", "Private");
|
||||
private static final Network HOME_PUBLIC = new Network("Bbox-Maison", "Wi-Fi", "Public");
|
||||
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
|
||||
|
||||
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
|
||||
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupported_whenNotWindows() {
|
||||
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.unsupported());
|
||||
assertFalse(r.supported());
|
||||
assertFalse(r.ready());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ready_onPrivateNetwork_withAllowRule() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE));
|
||||
assertTrue(r.ready());
|
||||
assertTrue(r.firewallAllowed());
|
||||
assertTrue(r.publicNetworks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notReady_withoutAnyRule_evenOnPrivateNetwork() {
|
||||
// Cas réel du 2026-10-17 : Wi-Fi passé en privé, mais aucune règle → la tablette charge sans fin.
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of());
|
||||
assertFalse(r.ready());
|
||||
assertFalse(r.firewallAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notReady_onPublicNetwork_evenWithPrivateRule() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(ALLOW_PRIVATE));
|
||||
assertFalse(r.ready());
|
||||
assertEquals(List.of("Bbox-Maison"), r.publicNetworks());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicNetwork_isNotAnObstacle_whenPublicExplicitlyAllowed() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(new FirewallRule("Allow", "Private, Public", "True")));
|
||||
assertTrue(r.ready());
|
||||
assertTrue(r.publicNetworks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockRule_winsOverAllow() {
|
||||
NetworkReadiness r = eval(List.of(HOME_PRIVATE),
|
||||
List.of(ALLOW_PRIVATE, new FirewallRule("Block", "Any", "True")));
|
||||
assertFalse(r.ready());
|
||||
assertTrue(r.firewallBlocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledRules_areIgnored_andAnyCoversPrivate() {
|
||||
assertFalse(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Private", "False"))).ready());
|
||||
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicNetwork_withoutName_usesInterfaceAlias() {
|
||||
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
|
||||
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessService} avec des doublures en mémoire (pas de Mockito :
|
||||
* l'état des appareils et du connecteur doit vraiment évoluer d'un appel à l'autre).
|
||||
*/
|
||||
class RemoteAccessServiceTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
|
||||
private MutableClock clock;
|
||||
private FakeLan lan;
|
||||
private InMemoryDevices devices;
|
||||
private InMemoryConfig config;
|
||||
private RemoteAccessService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock(Instant.parse("2026-10-17T10:00:00Z"));
|
||||
lan = new FakeLan();
|
||||
devices = new InMemoryDevices();
|
||||
config = new InMemoryConfig();
|
||||
service = new RemoteAccessService(config, devices, lan, LOCAL_PORT, clock);
|
||||
}
|
||||
|
||||
private String freshCode() {
|
||||
service.configure(true, 8765);
|
||||
return service.newPairingCode().code();
|
||||
}
|
||||
|
||||
// --- Réglage ---
|
||||
|
||||
@Test
|
||||
void disabledByDefault_noConnector() {
|
||||
RemoteAccessStatus status = service.status();
|
||||
assertFalse(status.enabled());
|
||||
assertFalse(status.running());
|
||||
assertEquals(RemoteAccessConfig.DEFAULT_PORT, status.port());
|
||||
assertTrue(status.urls().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_opensConnector_persists_andListsUrls() {
|
||||
RemoteAccessStatus status = service.configure(true, 8765);
|
||||
|
||||
assertEquals(8765, lan.port);
|
||||
assertTrue(status.running());
|
||||
assertEquals(List.of("http://192.168.1.20:8765"), status.urls());
|
||||
assertEquals(new RemoteAccessConfig(true, 8765), config.saved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_onBusyPort_staysDisabled() {
|
||||
lan.busy = true;
|
||||
assertThrows(IllegalStateException.class, () -> service.configure(true, 8765));
|
||||
assertNull(config.saved);
|
||||
assertFalse(service.status().enabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_portOutOfRange_orSameAsLocalPort() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, 80));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, LOCAL_PORT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disable_closesConnector_andInvalidatesPendingCode() {
|
||||
String code = freshCode();
|
||||
service.configure(false, 8765);
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void applySavedConfig_reopensOnBoot_withoutCrashingOnBusyPort() {
|
||||
config.saved = new RemoteAccessConfig(true, 8765);
|
||||
lan.busy = true;
|
||||
|
||||
service.applySavedConfig();
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertNotNull(service.status().lastError());
|
||||
}
|
||||
|
||||
// --- Appairage ---
|
||||
|
||||
@Test
|
||||
void pairingCode_requiresOpenConnector() {
|
||||
assertThrows(IllegalStateException.class, () -> service.newPairingCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pairingCode_isSixDigits() {
|
||||
assertTrue(freshCode().matches("\\d{6}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_withRightCode_issuesToken_storesOnlyItsHash_andConsumesTheCode() {
|
||||
String code = freshCode();
|
||||
|
||||
PairingResult result = service.pair(code, " Tablette de Léa ", "Mozilla/5.0 (iPad)");
|
||||
|
||||
assertEquals("Tablette de Léa", result.device().name());
|
||||
RemoteDevice stored = devices.items.get(0);
|
||||
assertNotEquals(result.token(), stored.getTokenHash());
|
||||
assertEquals(RemoteAccessService.sha256(result.token()), stored.getTokenHash());
|
||||
assertTrue(service.authenticate(result.token()).isPresent());
|
||||
// Code à usage unique.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Autre", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_rejectsExpiredCode() {
|
||||
String code = freshCode();
|
||||
clock.advance(RemoteAccessService.CODE_TTL.plusSeconds(1));
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(devices.items.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_invalidatesCodeAfterTooManyWrongAttempts() {
|
||||
String code = freshCode();
|
||||
String wrong = code.equals("000000") ? "111111" : "000000";
|
||||
for (int i = 0; i < RemoteAccessService.CODE_MAX_ATTEMPTS; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(wrong, "Tablette", null));
|
||||
}
|
||||
// Même le bon code ne passe plus : il faut en afficher un nouveau.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_globalThrottle_blocksBurstAcrossCodes() {
|
||||
for (int i = 0; i < RemoteAccessService.GLOBAL_MAX_FAILURES_PER_MINUTE; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair("123456", "x", null));
|
||||
}
|
||||
String code = freshCode();
|
||||
PairingRejectedException blocked =
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(blocked.getMessage().contains("minute"));
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
assertDoesNotThrow(() -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceName_defaultsAndIsTruncated() {
|
||||
PairingResult unnamed = service.pair(freshCode(), " ", null);
|
||||
assertEquals("Appareil", unnamed.device().name());
|
||||
|
||||
PairingResult longName = service.pair(service.newPairingCode().code(), "x".repeat(300), null);
|
||||
assertEquals(RemoteAccessService.DEVICE_NAME_MAX, longName.device().name().length());
|
||||
}
|
||||
|
||||
// --- Authentification & révocation ---
|
||||
|
||||
@Test
|
||||
void authenticate_unknownOrBlankToken_isEmpty() {
|
||||
assertTrue(service.authenticate(null).isEmpty());
|
||||
assertTrue(service.authenticate("").isEmpty());
|
||||
assertTrue(service.authenticate("inconnu").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticate_touchesLastSeen_atMostOncePerMinute() {
|
||||
String token = service.pair(freshCode(), "Tablette", null).token();
|
||||
devices.touches = 0;
|
||||
|
||||
service.authenticate(token);
|
||||
assertEquals(0, devices.touches);
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
service.authenticate(token);
|
||||
assertEquals(1, devices.touches);
|
||||
}
|
||||
|
||||
@Test
|
||||
void revoke_cutsAccess() {
|
||||
PairingResult result = service.pair(freshCode(), "Tablette", null);
|
||||
|
||||
assertTrue(service.revoke(result.device().id()));
|
||||
assertTrue(service.authenticate(result.token()).isEmpty());
|
||||
assertFalse(service.revoke(result.device().id()));
|
||||
}
|
||||
|
||||
// --- Doublures ---
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
MutableClock(Instant now) { this.now = now; }
|
||||
|
||||
void advance(Duration d) { now = now.plus(d); }
|
||||
|
||||
@Override public Instant instant() { return now; }
|
||||
@Override public java.time.ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
}
|
||||
|
||||
private static final class FakeLan implements LanConnector {
|
||||
int port = -1;
|
||||
boolean busy;
|
||||
|
||||
@Override public void start(int p) {
|
||||
if (busy) throw new IllegalStateException("Le port " + p + " est déjà utilisé par une autre application.");
|
||||
port = p;
|
||||
}
|
||||
@Override public void stop() { port = -1; }
|
||||
@Override public int runningPort() { return port; }
|
||||
@Override public List<String> lanAddresses() { return List.of("192.168.1.20"); }
|
||||
}
|
||||
|
||||
private static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
private static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
final List<RemoteDevice> items = new ArrayList<>();
|
||||
int touches;
|
||||
private int nextId = 1;
|
||||
|
||||
@Override public RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(nextId++));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) {
|
||||
touches++;
|
||||
items.stream().filter(d -> d.getId().equals(id)).forEach(d -> d.setLastSeenAt(at));
|
||||
}
|
||||
@Override public boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import com.loremind.infrastructure.web.controller.RemotePairingController;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test d'intégration de l'accès distant sur un VRAI Tomcat : ouverture à chaud du second
|
||||
* connecteur, garde du filtre, appairage par code avec pose du cookie, puis fermeture.
|
||||
* Contexte Spring minimal (ni base, ni sécurité) : seules les briques de l'accès distant.
|
||||
*/
|
||||
@SpringBootTest(classes = TomcatLanConnectorIntegrationTest.App.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "spring.main.banner-mode=off")
|
||||
class TomcatLanConnectorIntegrationTest {
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration(exclude = {
|
||||
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, FlywayAutoConfiguration.class,
|
||||
SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
|
||||
@Import(App.Ping.class)
|
||||
static class App {
|
||||
|
||||
@RestController
|
||||
static class Ping {
|
||||
@GetMapping("/api/ping")
|
||||
String ping() { return "pong"; }
|
||||
|
||||
@GetMapping("/api/settings/secret")
|
||||
String secret() { return "admin"; }
|
||||
}
|
||||
|
||||
@Bean
|
||||
TomcatLanConnector lanConnector(ApplicationContext context) {
|
||||
return new TomcatLanConnector(context);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RemoteAccessService remoteAccessService(LanConnector lan) {
|
||||
return new RemoteAccessService(new InMemoryConfig(), new InMemoryDevices(), lan, 1);
|
||||
}
|
||||
|
||||
/** En @Bean : un @Import ignorerait la classe, annotée @Profile("local"). */
|
||||
@Bean
|
||||
RemotePairingController remotePairingController(RemoteAccessService service) {
|
||||
return new RemotePairingController(service);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<RemoteAccessFilter> remoteAccessFilter(RemoteAccessService service) {
|
||||
return new FilterRegistrationBean<>(new RemoteAccessFilter(service));
|
||||
}
|
||||
}
|
||||
|
||||
@LocalServerPort private int localPort;
|
||||
@Autowired private RemoteAccessService service;
|
||||
@Autowired private TomcatLanConnector lan;
|
||||
|
||||
private final HttpClient http = HttpClient.newHttpClient();
|
||||
|
||||
@AfterEach
|
||||
void closeLan() {
|
||||
lan.stop();
|
||||
}
|
||||
|
||||
private HttpResponse<String> get(int port, String path, String cookie) throws Exception {
|
||||
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).GET();
|
||||
if (cookie != null) req.header("Cookie", cookie);
|
||||
return http.send(req.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private HttpResponse<String> post(int port, String path, String json) throws Exception {
|
||||
return http.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static int freePort() throws IOException {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
return s.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanConnector_guardsApi_pairsWithCode_andClosesCleanly() throws Exception {
|
||||
// Connecteur habituel : inchangé, aucun jeton demandé.
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
|
||||
int lanPort = freePort();
|
||||
assertTrue(service.configure(true, lanPort).running());
|
||||
|
||||
// Depuis le réseau : appairage exigé, administration interdite.
|
||||
HttpResponse<String> unpaired = get(lanPort, "/api/ping", null);
|
||||
assertEquals(401, unpaired.statusCode());
|
||||
assertTrue(unpaired.body().contains("remote_pairing_required"));
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", null).statusCode());
|
||||
|
||||
// Mauvais code puis bon code : le bon pose un cookie HttpOnly + SameSite=Strict.
|
||||
assertEquals(403, post(lanPort, "/api/remote-access/pair", "{\"code\":\"abcdef\",\"deviceName\":\"x\"}").statusCode());
|
||||
String code = service.newPairingCode().code();
|
||||
HttpResponse<String> paired = post(lanPort, "/api/remote-access/pair",
|
||||
"{\"code\":\"" + code + "\",\"deviceName\":\"Tablette de test\"}");
|
||||
assertEquals(200, paired.statusCode());
|
||||
String setCookie = paired.headers().firstValue("Set-Cookie").orElseThrow();
|
||||
assertTrue(setCookie.startsWith(RemoteAccessFilter.DEVICE_COOKIE + "="));
|
||||
assertTrue(setCookie.contains("HttpOnly"));
|
||||
assertTrue(setCookie.contains("SameSite=Strict"));
|
||||
String cookie = setCookie.split(";", 2)[0];
|
||||
|
||||
HttpResponse<String> authorized = get(lanPort, "/api/ping", cookie);
|
||||
assertEquals(200, authorized.statusCode());
|
||||
assertEquals("pong", authorized.body());
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", cookie).statusCode());
|
||||
assertTrue(get(lanPort, "/api/remote-access/session", cookie).body().contains("\"paired\":true"));
|
||||
|
||||
// Désactivation : le port réseau se ferme, le connecteur local continue.
|
||||
service.configure(false, lanPort);
|
||||
assertThrows(ConnectException.class, () -> get(lanPort, "/api/ping", cookie));
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void busyPort_isReportedClearly() throws Exception {
|
||||
try (ServerSocket occupied = new ServerSocket(0)) {
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> service.configure(true, occupied.getLocalPort()));
|
||||
assertTrue(e.getMessage().contains("déjà utilisé"));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Doublures de persistance ---
|
||||
|
||||
static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
private RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
private final List<RemoteDevice> items = new ArrayList<>();
|
||||
|
||||
@Override public synchronized RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(items.size() + 1));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public synchronized Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public synchronized List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) { /* sans objet ici */ }
|
||||
@Override public synchronized boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.loremind.domain.remoteaccess.NetworkSnapshot;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledOnOs;
|
||||
import org.junit.jupiter.api.condition.OS;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test de {@link WindowsHostNetworkAccess} : lecture du JSON de PowerShell (objet seul ou
|
||||
* tableau), contenu des scripts, et — sur Windows seulement — un vrai appel en lecture seule.
|
||||
*/
|
||||
class WindowsHostNetworkAccessTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void parse_handlesSingleObjectsAndArrays() throws Exception {
|
||||
// ConvertTo-Json écrit un objet (pas un tableau) quand il n'y a qu'un élément.
|
||||
String json = "{\"networks\":{\"name\":\"Bbox\",\"alias\":\"Wi-Fi\",\"category\":\"Private\"},"
|
||||
+ "\"rules\":[{\"action\":\"Allow\",\"profile\":\"Private\",\"enabled\":\"True\"},"
|
||||
+ "{\"action\":\"Block\",\"profile\":\"Public\",\"enabled\":\"True\"}]}";
|
||||
|
||||
NetworkSnapshot s = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", json);
|
||||
|
||||
assertTrue(s.supported());
|
||||
assertEquals(1, s.networks().size());
|
||||
assertEquals("Private", s.networks().get(0).category());
|
||||
assertEquals(2, s.rules().size());
|
||||
assertEquals("Block", s.rules().get(1).action());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_handlesEmptyLists_andEmptyOutput() throws Exception {
|
||||
NetworkSnapshot empty = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", "{\"networks\":[],\"rules\":[]}");
|
||||
assertTrue(empty.networks().isEmpty());
|
||||
assertTrue(empty.rules().isEmpty());
|
||||
|
||||
NetworkSnapshot blank = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", " ");
|
||||
assertTrue(blank.networks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scripts_quoteThePath_andOnlyOpenPrivateNetworks() {
|
||||
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
|
||||
String allow = WindowsHostNetworkAccess.allowScript(path);
|
||||
|
||||
assertTrue(allow.contains("'C:\\Users\\l''MJ\\DM Loremind.exe'"), "apostrophe doublée dans la chaîne PowerShell");
|
||||
assertTrue(allow.contains("-Profile Private"));
|
||||
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
|
||||
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
|
||||
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
|
||||
String encoded = WindowsHostNetworkAccess.encode("é");
|
||||
assertEquals("é", new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledOnOs(OS.WINDOWS)
|
||||
void inspect_readsTheRealSystem_onWindows() {
|
||||
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect();
|
||||
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
|
||||
assertNotNull(s.program());
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,15 @@ class FlywayMigrationTest {
|
||||
"values ('C', 0, now(), now())");
|
||||
st.executeUpdate("insert into arcs (name, campaign_id, \"order\", type, created_at, updated_at) " +
|
||||
"select 'Quêtes libres', id, 9999, 'SYSTEM', now(), now() from campaigns");
|
||||
|
||||
// V25 : accès distant — réglage singleton + appareils, empreinte de jeton unique.
|
||||
st.executeUpdate("insert into remote_access_config (id, enabled, port, updated_at) " +
|
||||
"values ('current', true, 8765, now())");
|
||||
st.executeUpdate("insert into remote_devices (name, token_hash, created_at) values ('Tablette', 'abc', now())");
|
||||
assertThrows(SQLException.class,
|
||||
() -> st.executeUpdate("insert into remote_devices (name, token_hash, created_at) " +
|
||||
"values ('Doublon', 'abc', now())"),
|
||||
"remote_devices.token_hash doit être unique (V25)");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessFilter} : ce qui passe et ce qui est refusé selon
|
||||
* le connecteur d'arrivée (local / réseau), le chemin et le cookie d'appareil.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class RemoteAccessFilterTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
private static final int LAN_PORT = 8765;
|
||||
|
||||
@Mock private RemoteAccessService service;
|
||||
private RemoteAccessFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
filter = new RemoteAccessFilter(service);
|
||||
when(service.lanPort()).thenReturn(LAN_PORT);
|
||||
when(service.authenticate("bon-jeton")).thenReturn(Optional.of(RemoteDevice.builder().id("1").name("Tablette").build()));
|
||||
when(service.authenticate(null)).thenReturn(Optional.empty());
|
||||
when(service.authenticate("mauvais")).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
private record Outcome(boolean passed, int status, String body) {}
|
||||
|
||||
private Outcome run(int localPort, String path, String token) throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", path);
|
||||
request.setLocalPort(localPort);
|
||||
if (token != null) request.setCookies(new Cookie(RemoteAccessFilter.DEVICE_COOKIE, token));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
return new Outcome(chain.getRequest() != null, response.getStatus(), response.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void localConnector_isUntouched_evenForSettings() throws Exception {
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
assertTrue(run(LOCAL_PORT, "/api/settings", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanClosed_meansEverythingIsLocal() throws Exception {
|
||||
when(service.lanPort()).thenReturn(-1);
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_staticFrontAndPublicApi_passWithoutToken() throws Exception {
|
||||
assertTrue(run(LAN_PORT, "/", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/main-ABC123.js", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/config", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/session", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_api_requiresValidDeviceToken() throws Exception {
|
||||
Outcome none = run(LAN_PORT, "/api/campaigns", null);
|
||||
assertFalse(none.passed());
|
||||
assertEquals(401, none.status());
|
||||
assertTrue(none.body().contains("remote_pairing_required"));
|
||||
|
||||
assertEquals(401, run(LAN_PORT, "/api/images/42", "mauvais").status());
|
||||
assertTrue(run(LAN_PORT, "/api/campaigns", "bon-jeton").passed());
|
||||
assertTrue(run(LAN_PORT, "/api/images/42", "bon-jeton").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_adminRoutes_areAlwaysForbidden_evenWhenPaired() throws Exception {
|
||||
for (String path : new String[]{"/api/settings", "/api/settings/remote-access", "/api/admin/data/export", "/api/license"}) {
|
||||
Outcome outcome = run(LAN_PORT, path, "bon-jeton");
|
||||
assertFalse(outcome.passed(), path);
|
||||
assertEquals(403, outcome.status(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -11,6 +11,8 @@ import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -39,6 +41,7 @@ class CampaignTreeControllerTest {
|
||||
@Autowired private ChapterRepository chapterRepository;
|
||||
@Autowired private SceneRepository sceneRepository;
|
||||
@Autowired private QuestRepository questRepository;
|
||||
@Autowired private PlaythroughRepository playthroughRepository;
|
||||
|
||||
private String campaignId;
|
||||
private String arcId;
|
||||
@@ -52,6 +55,7 @@ class CampaignTreeControllerTest {
|
||||
chapterId = chapterRepository.save(Chapter.builder().arcId(arcId).name("Chap").order(0).build()).getId();
|
||||
sceneRepository.save(Scene.builder().chapterId(chapterId).name("Scène").order(0).build());
|
||||
questRepository.save(Quest.builder().campaignId(campaignId).arcId(arcId).name("Quête").order(0).build());
|
||||
playthroughRepository.save(Playthrough.builder().campaignId(campaignId).name("Partie 1").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,6 +69,8 @@ class CampaignTreeControllerTest {
|
||||
.andExpect(jsonPath("$.scenesByChapter." + chapterId + "[0].name").value("Scène"))
|
||||
.andExpect(jsonPath("$.quests", hasSize(1)))
|
||||
.andExpect(jsonPath("$.quests[0].arcId").value(arcId))
|
||||
.andExpect(jsonPath("$.playthroughs", hasSize(1)))
|
||||
.andExpect(jsonPath("$.playthroughs[0].name").value("Partie 1"))
|
||||
.andExpect(jsonPath("$.readiness.campaignId").value(campaignId))
|
||||
.andExpect(jsonPath("$.readiness.gaps").isArray());
|
||||
}
|
||||
|
||||
+20
@@ -20,6 +20,11 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||
@@ -98,6 +103,21 @@ class SessionControllerTest {
|
||||
.andExpect(jsonPath("$").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSessions_activeOnly_excludesEnded() throws Exception {
|
||||
Session running = saveSession();
|
||||
Session ended = sessionRepository.save(Session.builder()
|
||||
.name("ended").playthroughId(playthroughId)
|
||||
.startedAt(FIXED_TIME.minusHours(2))
|
||||
.endedAt(FIXED_TIME.minusHours(1))
|
||||
.build());
|
||||
mockMvc.perform(get("/api/sessions").param("active", "true"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[*].active", everyItem(is(true))))
|
||||
.andExpect(jsonPath("$[*].id", hasItem(running.getId())))
|
||||
.andExpect(jsonPath("$[*].id", not(hasItem(ended.getId()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getActive_global_returnsActive() throws Exception {
|
||||
saveSession();
|
||||
|
||||
+25
-2
@@ -18,7 +18,9 @@
|
||||
Le code source de ce script est public et auditable a l'adresse indiquee dans .LINK.
|
||||
|
||||
.PARAMETER InstallDir
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind
|
||||
Dossier d'installation. Defaut : %LOCALAPPDATA%\DM Loremind Docker
|
||||
(PAS "%LOCALAPPDATA%\DM Loremind" : ce dossier est celui de l'application
|
||||
bureau .msi — les deux produits ne doivent jamais partager un dossier).
|
||||
|
||||
.PARAMETER ComposeUrl
|
||||
URL du fichier docker-compose.yml a recuperer. Defaut : version officielle du depot.
|
||||
@@ -48,7 +50,7 @@
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind",
|
||||
[string]$InstallDir = "$env:LOCALAPPDATA\DM Loremind Docker",
|
||||
[string]$ComposeUrl = "https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/docker-compose.yml",
|
||||
[int]$WebPort = 8081,
|
||||
[switch]$NonInteractive
|
||||
@@ -204,6 +206,27 @@ if (Test-Docker) {
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Dossier d'installation + docker-compose.yml
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compat : les stacks historiques vivaient dans "%LOCALAPPDATA%\DM Loremind",
|
||||
# desormais reserve a l'application bureau (.msi jpackage, meme nom produit —
|
||||
# une maj du .msi pouvait ecraser compose/.env). Si un stack y est deja
|
||||
# installe (compose present, pas d'exe bureau), on le reutilise plutot que
|
||||
# d'en creer un second qui entrerait en conflit (memes noms de conteneurs).
|
||||
$legacyDir = "$env:LOCALAPPDATA\DM Loremind"
|
||||
if ($InstallDir -eq "$env:LOCALAPPDATA\DM Loremind Docker" -and
|
||||
(Test-Path (Join-Path $legacyDir 'docker-compose.yml')) -and
|
||||
-not (Test-Path (Join-Path $legacyDir 'DM Loremind.exe'))) {
|
||||
Write-Warn2 "Stack Docker existant detecte dans $legacyDir - reutilise (pas de duplication)."
|
||||
$InstallDir = $legacyDir
|
||||
}
|
||||
|
||||
# Garde-fou : jamais d'installation du stack Docker dans le dossier de
|
||||
# l'application bureau (le .msi et le stack s'ecraseraient mutuellement).
|
||||
if (Test-Path (Join-Path $InstallDir 'DM Loremind.exe')) {
|
||||
Write-Err "Le dossier $InstallDir contient l'application bureau DM Loremind (.msi)."
|
||||
Write-Err "La version Docker doit vivre ailleurs : relancez avec -InstallDir <autre dossier>."
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Step "Preparation du dossier $InstallDir"
|
||||
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
|
||||
Set-Location $InstallDir
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
"zone.js"
|
||||
],
|
||||
"tsConfig": "tsconfig.json",
|
||||
"allowedCommonJsDependencies": [
|
||||
"qrcode"
|
||||
],
|
||||
"assets": [
|
||||
"src/favicon.ico",
|
||||
"src/assets"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Page, expect } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Ajoute un bloc Texte au builder de template (grille de blocs) et le renomme.
|
||||
*
|
||||
* Le builder n'a plus de champ « + Ajouter un champ » : un clic sur un type de
|
||||
* la palette ajoute en bas de la grille un bloc au nom par défaut (« Texte »,
|
||||
* « Texte 2 »…), qu'on renomme dans son en-tête. Le nom est validé au blur.
|
||||
*/
|
||||
export async function addTextBlock(page: Page, name: string): Promise<void> {
|
||||
const blocks = page.locator('.grid-block');
|
||||
const before = await blocks.count();
|
||||
|
||||
await page.locator('.palette-item', { hasText: /^\s*Texte\s*$/ }).click();
|
||||
await expect(blocks).toHaveCount(before + 1);
|
||||
|
||||
const nameInput = blocks.last().locator('.block-name-input');
|
||||
await nameInput.fill(name);
|
||||
await nameInput.blur();
|
||||
await expect(page.locator(`.grid-block[data-block-name="${name}"]`)).toBeVisible();
|
||||
}
|
||||
@@ -113,7 +113,10 @@ test.describe('Scene edit', () => {
|
||||
|
||||
const branchItem = branchesSection.locator('.branch-item').first();
|
||||
await branchItem.getByPlaceholder(/Ex: Si les joueurs attaquent/i).fill('Si les PJ fuient');
|
||||
await branchItem.locator('select').selectOption({ label: sibling.name });
|
||||
// Une branche a 2 selects (scène cible + type de lien) : on vise celui qui liste la scène.
|
||||
await branchItem
|
||||
.locator('select', { has: page.locator('option', { hasText: sibling.name }) })
|
||||
.selectOption({ label: sibling.name });
|
||||
await branchItem.getByPlaceholder(/Jet de Persuasion/i).fill('Sur échec initiative');
|
||||
|
||||
await page.getByRole('button', { name: /^Sauvegarder$/i }).click();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { seedLoreWithFolder, deleteLore, getTemplatesForLore, type SeededLore } from '../../fixtures/api';
|
||||
import { addTextBlock } from '../../fixtures/template-builder';
|
||||
|
||||
test.describe('Template creation', () => {
|
||||
let seeded: SeededLore;
|
||||
@@ -50,14 +51,8 @@ test.describe('Template creation', () => {
|
||||
await page.getByLabel(/Nom du template/i).fill(templateName);
|
||||
await page.getByLabel(/Dossier par défaut/i).selectOption({ label: seeded.rootFolderName });
|
||||
|
||||
const addFieldInput = page.getByPlaceholder('+ Ajouter un champ');
|
||||
await addFieldInput.fill('Pouvoir');
|
||||
await addFieldInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Pouvoir"]')).toBeVisible();
|
||||
|
||||
await addFieldInput.fill('Origine');
|
||||
await addFieldInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Origine"]')).toBeVisible();
|
||||
await addTextBlock(page, 'Pouvoir');
|
||||
await addTextBlock(page, 'Origine');
|
||||
|
||||
const origineBlock = page.locator('.grid-block[data-block-name="Origine"]');
|
||||
await origineBlock.getByRole('button', { name: 'Supprimer' }).click();
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type SeededLore,
|
||||
type SeededTemplate,
|
||||
} from '../../fixtures/api';
|
||||
import { addTextBlock } from '../../fixtures/template-builder';
|
||||
|
||||
test.describe('Template edit', () => {
|
||||
let seeded: SeededLore;
|
||||
@@ -55,10 +56,9 @@ test.describe('Template edit', () => {
|
||||
test('adds a new field, removes an existing one, and persists the order', async ({ page, request }) => {
|
||||
await page.goto(`/lore/${seeded.id}/templates/${template.id}`);
|
||||
|
||||
const addInput = page.getByPlaceholder('+ Ajouter un champ');
|
||||
await addInput.fill('Stats');
|
||||
await addInput.press('Enter');
|
||||
await expect(page.locator('.grid-block[data-block-name="Stats"]')).toBeVisible();
|
||||
// Attendre les champs existants (chargés en asynchrone) avant d'en ajouter un.
|
||||
await expect(page.locator('.grid-block[data-block-name="Description"]')).toBeVisible();
|
||||
await addTextBlock(page, 'Stats');
|
||||
|
||||
const descriptionBlock = page.locator('.grid-block[data-block-name="Description"]');
|
||||
await descriptionBlock.getByRole('button', { name: 'Supprimer' }).click();
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { test, expect, type APIRequestContext, type Page } from '@playwright/test';
|
||||
import {
|
||||
seedCampaign,
|
||||
seedArc,
|
||||
seedChapter,
|
||||
seedScene,
|
||||
deleteCampaign,
|
||||
type SeededCampaign,
|
||||
type SeededArc,
|
||||
type SeededChapter,
|
||||
type SeededScene,
|
||||
} from '../../fixtures/api';
|
||||
|
||||
/**
|
||||
* Shell responsive au viewport téléphone (projet Playwright « mobile », 375 px).
|
||||
*
|
||||
* Sous 1024 px, le menu principal et l'arborescence deviennent des tiroirs
|
||||
* off-canvas ouverts depuis une barre haute. On vérifie :
|
||||
* - qu'aucun écran clé ne défile horizontalement — ni le document, ni
|
||||
* `main.main-content` (le conteneur qui défile réellement : un débordement
|
||||
* y produirait une barre horizontale sans toucher au document) ;
|
||||
* - que la navigation reste accessible au doigt (ouverture, navigation,
|
||||
* fermeture au changement de route / Échap / clic extérieur).
|
||||
*/
|
||||
|
||||
async function expectNoHorizontalScroll(page: Page): Promise<void> {
|
||||
const m = await page.evaluate(() => {
|
||||
const main = document.querySelector('main.main-content');
|
||||
return {
|
||||
doc: document.documentElement.scrollWidth,
|
||||
vw: window.innerWidth,
|
||||
mainScroll: main?.scrollWidth ?? 0,
|
||||
mainClient: main?.clientWidth ?? 0,
|
||||
};
|
||||
});
|
||||
expect(m.doc, 'scroll horizontal du document').toBeLessThanOrEqual(m.vw);
|
||||
expect(m.mainScroll, 'scroll horizontal de main.main-content').toBeLessThanOrEqual(m.mainClient);
|
||||
}
|
||||
|
||||
async function seedPlaythroughWithSession(
|
||||
request: APIRequestContext,
|
||||
campaignId: string,
|
||||
): Promise<{ playthroughId: string; sessionId: string }> {
|
||||
const ptRes = await request.post('/api/playthroughs', {
|
||||
data: { campaignId, name: `E2E Partie ${Date.now()}`, description: 'Seeded by Playwright' },
|
||||
});
|
||||
expect(ptRes.ok(), `POST /api/playthroughs -> ${ptRes.status()}`).toBeTruthy();
|
||||
const pt = await ptRes.json();
|
||||
|
||||
const clockRes = await request.post(`/api/playthroughs/${pt.id}/clocks`, {
|
||||
data: { name: 'Le rituel du nécromancien', description: '', segments: 6 },
|
||||
});
|
||||
expect(clockRes.ok(), `POST clocks -> ${clockRes.status()}`).toBeTruthy();
|
||||
|
||||
const sRes = await request.post('/api/sessions', { data: { playthroughId: pt.id } });
|
||||
expect(sRes.ok(), `POST /api/sessions -> ${sRes.status()}`).toBeTruthy();
|
||||
const session = await sRes.json();
|
||||
|
||||
const eRes = await request.post(`/api/sessions/${session.id}/entries`, {
|
||||
data: { type: 'NOTE', content: 'Les PJ arrivent à Brumecombe sous la pluie.', occurredAt: null },
|
||||
});
|
||||
expect(eRes.ok(), `POST entries -> ${eRes.status()}`).toBeTruthy();
|
||||
|
||||
return { playthroughId: pt.id, sessionId: session.id };
|
||||
}
|
||||
|
||||
test.describe('Shell mobile (375 px)', () => {
|
||||
test('liste des campagnes : pas de scroll horizontal, menu en tiroir', async ({ page }) => {
|
||||
await page.goto('/campaigns');
|
||||
await expect(page.getByRole('heading', { name: /Vos Campagnes/i })).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// Le menu principal est hors écran tant que le tiroir est fermé.
|
||||
const menu = page.locator('app-sidebar');
|
||||
await expect(menu).toBeHidden();
|
||||
|
||||
// Le libellé du burger alterne Ouvrir / Fermer : on le cible par aria-controls.
|
||||
const burger = page.locator('button[aria-controls="app-main-nav"]');
|
||||
await expect(burger).toHaveAccessibleName('Ouvrir le menu');
|
||||
await burger.tap();
|
||||
await expect(menu).toBeVisible();
|
||||
await expect(burger).toHaveAttribute('aria-expanded', 'true');
|
||||
await expect(burger).toHaveAccessibleName('Fermer le menu');
|
||||
|
||||
// Échap referme et rend le focus au bouton burger.
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(burger).toBeFocused();
|
||||
|
||||
// Clic hors du tiroir (voile) : referme aussi.
|
||||
await burger.tap();
|
||||
await expect(menu).toBeVisible();
|
||||
await page.mouse.click(360, 400);
|
||||
await expect(menu).toBeHidden();
|
||||
|
||||
// Navigation depuis le tiroir : la page change et le tiroir se ferme.
|
||||
await burger.tap();
|
||||
await menu.getByRole('button', { name: 'Lore', exact: true }).tap();
|
||||
await expect(page).toHaveURL(/\/lore$/);
|
||||
await expect(page.getByRole('heading', { name: /Vos Univers/i })).toBeVisible();
|
||||
await expect(menu).toBeHidden();
|
||||
await expectNoHorizontalScroll(page);
|
||||
});
|
||||
|
||||
test.describe('avec une campagne', () => {
|
||||
let campaign: SeededCampaign;
|
||||
let arc: SeededArc;
|
||||
let chapter: SeededChapter;
|
||||
let scene: SeededScene;
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
// Nom long volontaire : c'est lui qui faisait déborder l'en-tête du hub.
|
||||
campaign = await seedCampaign(request, {
|
||||
name: `E2E La Chute de la Maison Valcourt — campagne longue ${Date.now()}`,
|
||||
});
|
||||
arc = await seedArc(request, { campaignId: campaign.id });
|
||||
chapter = await seedChapter(request, { arcId: arc.id });
|
||||
scene = await seedScene(request, { chapterId: chapter.id, name: 'La taverne du Corbeau Borgne' });
|
||||
});
|
||||
|
||||
test.afterEach(async ({ request }) => {
|
||||
if (campaign?.id) await deleteCampaign(request, campaign.id);
|
||||
});
|
||||
|
||||
test('hub campagne → scène via l’arborescence en tiroir', async ({ page }) => {
|
||||
await page.goto(`/campaigns/${campaign.id}`);
|
||||
await expect(page.getByRole('heading', { level: 1, name: campaign.name })).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// L'arborescence s'ouvre depuis la barre haute (bouton titré par la campagne).
|
||||
const tree = page.locator('app-secondary-sidebar');
|
||||
await expect(tree).toBeHidden();
|
||||
await page.getByRole('button', { name: "Ouvrir l'arborescence" }).tap();
|
||||
await expect(tree).toBeVisible();
|
||||
|
||||
// Déplie « Scènes » puis l'arc / le chapitre jusqu'à la scène, au doigt.
|
||||
for (const label of [/Scènes/, new RegExp(arc.name), new RegExp(chapter.name)]) {
|
||||
const row = tree.locator('.tree-row', { has: page.locator('.tree-btn', { hasText: label }) }).first();
|
||||
if (await tree.getByRole('button', { name: scene.name }).isVisible()) break;
|
||||
const chevron = row.locator('.chevron-btn');
|
||||
if (await chevron.count()) await chevron.tap();
|
||||
}
|
||||
await tree.getByRole('button', { name: scene.name }).tap();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/scenes/${scene.id}$`));
|
||||
await expect(page.getByRole('heading', { level: 1, name: scene.name })).toBeVisible();
|
||||
await expect(tree).toBeHidden();
|
||||
await expectNoHorizontalScroll(page);
|
||||
});
|
||||
|
||||
test('écran de séance : journal et horloges lisibles sans scroll horizontal', async ({ page, request }) => {
|
||||
const { sessionId } = await seedPlaythroughWithSession(request, campaign.id);
|
||||
|
||||
await page.goto(`/sessions/${sessionId}`);
|
||||
await expect(page.getByText('Les PJ arrivent à Brumecombe sous la pluie.')).toBeVisible();
|
||||
await expect(page.getByText('Le rituel du nécromancien')).toBeVisible();
|
||||
await expectNoHorizontalScroll(page);
|
||||
|
||||
// Le menu reste accessible depuis la séance.
|
||||
await page.getByRole('button', { name: 'Ouvrir le menu' }).tap();
|
||||
await expect(page.locator('app-sidebar')).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
Generated
+254
-47
@@ -22,6 +22,7 @@
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"zone.js": "~0.15.1"
|
||||
@@ -34,6 +35,7 @@
|
||||
"@emnapi/runtime": "^1.11.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"angular-eslint": "21.4.0",
|
||||
"eslint": "^10.3.0",
|
||||
@@ -570,7 +572,6 @@
|
||||
"integrity": "sha512-BaUSLSyS+43fzDoJkTMkGqNdCXq3fGnUZsfXTmrlZPJf5AYFbgAlAPGZXDJyoNWw43fux+DafdlrlKcYUSgSIw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@angular-eslint/bundled-angular-compiler": "21.4.0",
|
||||
"eslint-scope": "9.1.2"
|
||||
@@ -601,7 +602,6 @@
|
||||
"integrity": "sha512-zOW8FFa9qfbVkZ5TulxDkl1C3+gEjWfAAD5Z2MycA6pjVJQlLYPiTAGq+flOQ3yZfTT0z6kd5rejQMXWI81Dvg==",
|
||||
"deprecated": "@angular/animations is deprecated. Use `animate.enter` and `animate.leave` instead. For more information see: https://v22.angular.dev/guide/animations.",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -734,7 +734,6 @@
|
||||
"integrity": "sha512-WOZF4p0SnrmBpNeiOA2pdp9OBvGnOSLWbGdRLXJykyseIiEn7+N+GZp+ZA1aNZB4SWolpYCZfTYwkpo6Sf/LXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@angular-devkit/architect": "0.2102.18",
|
||||
"@angular-devkit/core": "21.2.18",
|
||||
@@ -769,7 +768,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@angular/common/-/common-21.2.17.tgz",
|
||||
"integrity": "sha512-hqAQxRfi5ldFE42suAXRcY+JCANrUh7fuSQ/DtZ7L896id5BT/exuv6dWNBC1PyAfQmRbpD5Pt6/pd+tNLyhDQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -786,7 +784,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.2.17.tgz",
|
||||
"integrity": "sha512-p+NdjYiwAz9Zmu2yul0LlMXaFjMISVVa24+/MVMoKFeQeI82QE8jDywPlnOSHQHvdCcQVpS7saeEriZzX3JuBQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -800,7 +797,6 @@
|
||||
"integrity": "sha512-KithZ3b0HBFH0NbUcswBcjpN9y09vLbarMD7qmGWTnGUBk4W8cn4sbT8zJyv9CRKg9ZcuUBeJYKUfUPn/u/5OQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/core": "7.29.0",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14",
|
||||
@@ -881,7 +877,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@angular/core/-/core-21.2.17.tgz",
|
||||
"integrity": "sha512-wYHpwIdnUnjQFOJJNqRcGx7LS3u64jT+R9L0TnMR/ViBM9dQgGYImlSikkftg2yrFCNo5aKRxhG2LLskQurVdg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -926,7 +921,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.2.17.tgz",
|
||||
"integrity": "sha512-ROdSliejY37g1EphYmweYdm5cHM8HY3X4tbWt4ubxmhTyYgfN3nxrxfGQ/n7Mz5tDY9VXVLIGDgjLOGYOo4uTQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -1012,7 +1006,6 @@
|
||||
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.29.7",
|
||||
"@babel/generator": "^7.29.7",
|
||||
@@ -2746,7 +2739,6 @@
|
||||
"integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.2",
|
||||
"tslib": "^2.4.0"
|
||||
@@ -2758,7 +2750,6 @@
|
||||
"integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
@@ -3663,7 +3654,6 @@
|
||||
"integrity": "sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@inquirer/checkbox": "^4.3.2",
|
||||
"@inquirer/confirm": "^5.1.21",
|
||||
@@ -4903,7 +4893,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@ngx-translate/core/-/core-18.0.0.tgz",
|
||||
"integrity": "sha512-Z9u9AXaeuyeHHimivvJQvhal/LJNB+5tlH+FimSU4QQ61FrtRDqgyn6nfFbc6Cb+59NDZdsh4QeTJyPCldFUwA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
@@ -6540,6 +6529,16 @@
|
||||
"undici-types": "~8.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/qrcode": {
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
|
||||
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/qs": {
|
||||
"version": "6.15.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
|
||||
@@ -7211,7 +7210,6 @@
|
||||
"integrity": "sha512-xyLtl9DUBBFrcJS4x2pIqGLH68/tC2uOa4Z7pUteW09D3bXnnXUom4dyPikzWgB7llmIc1zoeI3aoUdC4rPK/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
@@ -7254,7 +7252,6 @@
|
||||
"integrity": "sha512-fUKaeAvrTuQg/Tgt3nliAUSZHJM6DlCcfyEmxCvlX8kieWSStBX+5O5Fnidtc3i2JrH+9c/GL4RY2iasd/GPTA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.9.1",
|
||||
"@typescript-eslint/scope-manager": "8.63.0",
|
||||
@@ -7323,7 +7320,6 @@
|
||||
"integrity": "sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@bcoe/v8-coverage": "^1.0.2",
|
||||
"@vitest/utils": "4.1.10",
|
||||
@@ -7681,7 +7677,6 @@
|
||||
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -7757,7 +7752,6 @@
|
||||
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -8303,7 +8297,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.10.42",
|
||||
"caniuse-lite": "^1.0.30001800",
|
||||
@@ -8447,6 +8440,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001802",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001802.tgz",
|
||||
@@ -8673,7 +8675,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
@@ -8686,7 +8687,6 @@
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/colorette": {
|
||||
@@ -9038,6 +9038,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/deep-is": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
|
||||
@@ -9127,6 +9136,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dns-packet": {
|
||||
"version": "5.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
|
||||
@@ -9469,7 +9484,6 @@
|
||||
"integrity": "sha512-6lVbcqSodALYo+4ELD0heG6lFiFxnLMuLkiMi2qV8LMp54N8tE8FT1GMH+ev4Ti00nFjNze2+Su6DsV5OQW3Dg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -9800,7 +9814,6 @@
|
||||
"integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.1",
|
||||
@@ -10137,7 +10150,6 @@
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
@@ -10332,7 +10344,6 @@
|
||||
"integrity": "sha512-YwUvVpSF7m1yOblFPrU3Hbo8XhPheBoiyfGuII6z19LnOr6JpDnyyp7LFNrfV56wS8tpvtBFGRISHN02pDdLOA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
}
|
||||
@@ -11221,7 +11232,6 @@
|
||||
"integrity": "sha512-j1n1IuTX1VQjIy3tT7cyGbX7nvQOsFLoIqobZv4ttI5axP923gA44zUj6miiA6R5Aoms4sEGVIIcucXUbRI14g==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"copy-anything": "^2.0.1",
|
||||
"parse-node-version": "^1.0.1",
|
||||
@@ -12627,6 +12637,15 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pacote": {
|
||||
"version": "21.5.1",
|
||||
"resolved": "https://registry.npmjs.org/pacote/-/pacote-21.5.1.tgz",
|
||||
@@ -12787,7 +12806,6 @@
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -12959,6 +12977,15 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.12",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.12.tgz",
|
||||
@@ -12979,7 +13006,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -13231,6 +13257,177 @@
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qrcode/node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/qrcode/node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode/node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
@@ -13406,6 +13603,15 @@
|
||||
"regjsparser": "bin/parser"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-from-string": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||
@@ -13416,6 +13622,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/requires-port": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
|
||||
@@ -13643,7 +13855,6 @@
|
||||
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
|
||||
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.1.0"
|
||||
}
|
||||
@@ -13682,7 +13893,6 @@
|
||||
"integrity": "sha512-fDz1zJpd5GycprAbu4Q2PV/RprsRtKC/0z82z0JLgdytmcq0+ujJbJ/09bPGDxCLkKY3Np5cRAOcWiVkLXJURg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"chokidar": "^4.0.0",
|
||||
"immutable": "^5.0.2",
|
||||
@@ -14048,6 +14258,12 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
@@ -14808,8 +15024,7 @@
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD",
|
||||
"peer": true
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tsyringe": {
|
||||
"version": "4.10.0",
|
||||
@@ -14905,7 +15120,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -14920,7 +15134,6 @@
|
||||
"integrity": "sha512-pJw051uomb3ZeCzGTpRb8RbEqB5Y4WWet8gl/GcTlU35BSx0PVdZ86/bqkQCyKKuraVQEK7r6kBHQXF+fBhkoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "8.59.2",
|
||||
"@typescript-eslint/parser": "8.59.2",
|
||||
@@ -15259,7 +15472,6 @@
|
||||
"integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.27.0 || ^0.28.0",
|
||||
"fdir": "^6.5.0",
|
||||
@@ -15350,7 +15562,6 @@
|
||||
"integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vitest/expect": "4.1.10",
|
||||
"@vitest/mocker": "4.1.10",
|
||||
@@ -15473,7 +15684,6 @@
|
||||
"integrity": "sha512-dRXm0a2qcHPUBEzVk8uph0xWSjV/xZxenQQbLwnwP7caQCYpqG1qddwlyEkIDkYn0K8tvmcrZ+bOrzoQ3HxCDw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/eslint-scope": "^3.7.7",
|
||||
"@types/estree": "^1.0.8",
|
||||
@@ -16187,6 +16397,12 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||
@@ -16225,7 +16441,6 @@
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
@@ -16240,7 +16455,6 @@
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -16250,7 +16464,6 @@
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
@@ -16266,14 +16479,12 @@
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -16283,7 +16494,6 @@
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
@@ -16298,7 +16508,6 @@
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
@@ -16477,7 +16686,6 @@
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
@@ -16496,8 +16704,7 @@
|
||||
"version": "0.15.1",
|
||||
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.15.1.tgz",
|
||||
"integrity": "sha512-XE96n56IQpJM7NAoXswY3XRLcWFW83xe0BiAOeMD7K5k5xecOeul3Qcpx6GqEeeHNkW5DWL5zOyTbEfB4eti8w==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"zone.js": "~0.15.1"
|
||||
@@ -46,6 +47,7 @@
|
||||
"@emnapi/runtime": "^1.11.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"angular-eslint": "21.4.0",
|
||||
"eslint": "^10.3.0",
|
||||
|
||||
@@ -30,7 +30,21 @@ export default defineConfig({
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
testIgnore: /responsive\//,
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
// Téléphone (375 px, tactile) : shell en tiroirs, absence de scroll horizontal.
|
||||
// Chromium « Desktop Chrome » redimensionné plutôt qu'un preset d'appareil :
|
||||
// même navigateur que la CI (seul chromium y est installé), largeur exacte.
|
||||
{
|
||||
name: 'mobile',
|
||||
testMatch: /responsive\/.*\.spec\.ts/,
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
viewport: { width: 375, height: 812 },
|
||||
isMobile: true,
|
||||
hasTouch: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,10 +1,52 @@
|
||||
<app-update-banner></app-update-banner>
|
||||
|
||||
<div class="app-container">
|
||||
<app-sidebar></app-sidebar>
|
||||
<!-- Barre haute (< 1024 px) : ouvre les tiroirs menu / arborescence. Masquée en CSS sur desktop. -->
|
||||
<header class="mobile-topbar">
|
||||
<button #mainToggle type="button" class="topbar-btn"
|
||||
aria-controls="app-main-nav"
|
||||
[attr.aria-expanded]="openDrawer() === 'main'"
|
||||
[attr.aria-label]="(openDrawer() === 'main' ? 'mobileShell.closeMenu' : 'mobileShell.openMenu') | translate"
|
||||
(click)="toggleDrawer('main')">
|
||||
<lucide-icon [img]="openDrawer() === 'main' ? X : Menu" [size]="20"></lucide-icon>
|
||||
</button>
|
||||
@if (sidebarConfig$ | async; as config) {
|
||||
<button #treeToggle type="button" class="topbar-btn topbar-tree"
|
||||
aria-controls="app-tree-nav"
|
||||
[attr.aria-expanded]="openDrawer() === 'tree'"
|
||||
[attr.aria-label]="(openDrawer() === 'tree' ? 'mobileShell.closeTree' : 'mobileShell.openTree') | translate"
|
||||
(click)="toggleDrawer('tree')">
|
||||
<lucide-icon [img]="PanelLeft" [size]="18"></lucide-icon>
|
||||
<span class="topbar-title">{{ config.title }}</span>
|
||||
</button>
|
||||
} @else {
|
||||
<span class="topbar-brand">
|
||||
<img src="assets/logo.png" alt="" />
|
||||
<span>DM Loremind</span>
|
||||
</span>
|
||||
}
|
||||
<!-- Séance en cours : un tap y ramène (visible seulement si une séance tourne). -->
|
||||
<app-active-session-shortcut compact class="topbar-session"></app-active-session-shortcut>
|
||||
<button type="button" class="topbar-btn topbar-search"
|
||||
[attr.aria-label]="'mobileShell.search' | translate"
|
||||
(click)="openSearch()">
|
||||
<lucide-icon [img]="Search" [size]="18"></lucide-icon>
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<app-sidebar id="app-main-nav"
|
||||
[class.drawer-open]="openDrawer() === 'main'"
|
||||
[attr.role]="isCompact() ? 'dialog' : null"
|
||||
[attr.aria-modal]="isCompact() && openDrawer() === 'main' ? 'true' : null"
|
||||
[attr.aria-label]="'mobileShell.mainNav' | translate"></app-sidebar>
|
||||
|
||||
@if (sidebarConfig$ | async; as config) {
|
||||
<app-secondary-sidebar
|
||||
<app-secondary-sidebar id="app-tree-nav"
|
||||
[class.drawer-open]="openDrawer() === 'tree'"
|
||||
[attr.role]="isCompact() ? 'dialog' : null"
|
||||
[attr.aria-modal]="isCompact() && openDrawer() === 'tree' ? 'true' : null"
|
||||
[attr.aria-label]="'mobileShell.treeNav' | translate"
|
||||
[drawerMode]="isCompact()"
|
||||
[title]="config.title"
|
||||
[titleRoute]="config.titleRoute || null"
|
||||
[items]="config.items"
|
||||
@@ -16,10 +58,15 @@
|
||||
</app-secondary-sidebar>
|
||||
}
|
||||
|
||||
<main class="main-content">
|
||||
@if (openDrawer()) {
|
||||
<div class="drawer-backdrop" aria-hidden="true" (click)="closeDrawer()"></div>
|
||||
}
|
||||
|
||||
<main #mainContent class="main-content" tabindex="-1">
|
||||
<router-outlet></router-outlet>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<app-global-search></app-global-search>
|
||||
<app-confirm-dialog-host></app-confirm-dialog-host>
|
||||
<app-writing-coach-panel></app-writing-coach-panel>
|
||||
|
||||
@@ -1,14 +1,144 @@
|
||||
// Points de rupture du shell (cf. styles/_responsive.scss) :
|
||||
// - >= 1024 px : colonnes fixes (menu + arborescence + contenu) ;
|
||||
// - < 1024 px : barre haute + menu et arborescence en tiroirs off-canvas ;
|
||||
// - < 768 px : une seule colonne, marges réduites.
|
||||
$compact: 1023.98px;
|
||||
$phone: 767.98px;
|
||||
$topbar-height: 52px;
|
||||
|
||||
.app-container {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
// min-width: 0 — sans ça un contenu large (tableau, graphe) élargit la colonne
|
||||
// flex au lieu de défiler dedans, et toute la page déborde horizontalement.
|
||||
min-width: 0;
|
||||
// padding-top: 0 — sinon le contenu defile dans la zone de padding
|
||||
// au-dessus du `.page-header` sticky (top: 0 pin sur l'edge interne du
|
||||
// padding-box). Chaque page-wrapper definit deja son propre padding-top
|
||||
// qui devient l'unique source d'espacement haut.
|
||||
padding: 0 2rem 2rem;
|
||||
overflow-y: auto;
|
||||
|
||||
// Focus programmatique après navigation depuis un tiroir : pas d'anneau visible.
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
|
||||
.mobile-topbar,
|
||||
.drawer-backdrop { display: none; }
|
||||
|
||||
@media (max-width: $compact) {
|
||||
.app-container { flex-direction: column; }
|
||||
|
||||
.mobile-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
flex: 0 0 auto;
|
||||
height: $topbar-height;
|
||||
padding: 0 0.5rem;
|
||||
background: #0f0f1a;
|
||||
border-bottom: 1px solid #1e1e3a;
|
||||
position: relative;
|
||||
z-index: 120;
|
||||
}
|
||||
|
||||
.topbar-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 44px;
|
||||
height: 44px;
|
||||
padding: 0 0.6rem;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
color: #d1d5db;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover, &[aria-expanded='true'] { background: #1f2937; color: white; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: -2px; }
|
||||
}
|
||||
|
||||
// Le bouton arborescence porte le titre de la section (campagne, lore) et prend
|
||||
// toute la place disponible : c'est la cible la plus utilisée au doigt.
|
||||
.topbar-tree {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
justify-content: flex-start;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.topbar-title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.topbar-brand {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
padding-left: 0.25rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
|
||||
img { width: 1.5rem; height: 1.5rem; border-radius: 5px; }
|
||||
}
|
||||
|
||||
// Les deux sidebars deviennent des tiroirs : hors flux, cachés à gauche.
|
||||
// visibility: hidden (retardée le temps de l'animation) les sort aussi de
|
||||
// l'ordre de tabulation quand ils sont fermés.
|
||||
app-sidebar,
|
||||
app-secondary-sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 150;
|
||||
max-width: 88vw;
|
||||
transform: translateX(-100%);
|
||||
visibility: hidden;
|
||||
transition: transform 0.25s ease, visibility 0s linear 0.25s;
|
||||
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.5);
|
||||
|
||||
&.drawer-open {
|
||||
transform: none;
|
||||
visibility: visible;
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-backdrop {
|
||||
display: block;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 149;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
padding: 0 1.25rem 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: $phone) {
|
||||
.main-content { padding: 0 0.75rem 1.25rem; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
app-sidebar,
|
||||
app-secondary-sidebar,
|
||||
app-sidebar.drawer-open,
|
||||
app-secondary-sidebar.drawer-open { transition: none; }
|
||||
}
|
||||
|
||||
@@ -1,24 +1,43 @@
|
||||
import { Component, HostListener } from '@angular/core';
|
||||
import { Component, ElementRef, HostListener, effect, inject, signal, viewChild } from '@angular/core';
|
||||
import { AsyncPipe } from '@angular/common';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { BreakpointObserver } from '@angular/cdk/layout';
|
||||
import { NavigationEnd, NavigationSkipped, Router, RouterOutlet } from '@angular/router';
|
||||
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 { 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';
|
||||
import { ConfirmDialogHostComponent } from './shared/confirm-dialog/confirm-dialog-host.component';
|
||||
import { WritingCoachPanelComponent } from './shared/writing-coach/writing-coach-panel.component';
|
||||
import { ActiveSessionShortcutComponent } from './sessions/active-session-shortcut/active-session-shortcut.component';
|
||||
import { LayoutService } from './services/layout.service';
|
||||
import { GlobalSearchService } from './services/global-search.service';
|
||||
import { VersionCheckerService } from './services/version-checker.service';
|
||||
|
||||
/** Sous cette largeur, les deux sidebars deviennent des tiroirs off-canvas (tablette, téléphone). */
|
||||
const COMPACT_QUERY = '(max-width: 1023.98px)';
|
||||
|
||||
/** Tiroir ouvert en mode compact : menu principal, arborescence secondaire, ou aucun. */
|
||||
type ShellDrawer = 'main' | 'tree' | null;
|
||||
|
||||
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [
|
||||
RouterOutlet,
|
||||
LucideAngularModule,
|
||||
TranslatePipe,
|
||||
SidebarComponent,
|
||||
SecondarySidebarComponent,
|
||||
GlobalSearchComponent,
|
||||
UpdateBannerComponent,
|
||||
ConfirmDialogHostComponent,
|
||||
WritingCoachPanelComponent,
|
||||
ActiveSessionShortcutComponent,
|
||||
AsyncPipe
|
||||
],
|
||||
templateUrl: './app.component.html',
|
||||
@@ -27,6 +46,29 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
export class AppComponent {
|
||||
readonly sidebarConfig$ = this.layoutService.secondarySidebar$;
|
||||
|
||||
readonly Menu = Menu;
|
||||
readonly PanelLeft = PanelLeft;
|
||||
readonly Search = Search;
|
||||
readonly X = X;
|
||||
|
||||
private readonly breakpoints = inject(BreakpointObserver);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
/** True sous 1024 px : barre haute + tiroirs au lieu des colonnes fixes. */
|
||||
readonly isCompact = toSignal(
|
||||
this.breakpoints.observe(COMPACT_QUERY).pipe(map(state => state.matches)),
|
||||
{ initialValue: this.breakpoints.isMatched(COMPACT_QUERY) }
|
||||
);
|
||||
|
||||
/** Tiroir ouvert (mode compact uniquement). */
|
||||
readonly openDrawer = signal<ShellDrawer>(null);
|
||||
|
||||
private readonly mainDrawerRef = viewChild(SidebarComponent, { read: ElementRef });
|
||||
private readonly treeDrawerRef = viewChild(SecondarySidebarComponent, { read: ElementRef });
|
||||
private readonly mainToggleRef = viewChild<ElementRef<HTMLButtonElement>>('mainToggle');
|
||||
private readonly treeToggleRef = viewChild<ElementRef<HTMLButtonElement>>('treeToggle');
|
||||
private readonly mainContentRef = viewChild<ElementRef<HTMLElement>>('mainContent');
|
||||
|
||||
constructor(
|
||||
private layoutService: LayoutService,
|
||||
private globalSearch: GlobalSearchService,
|
||||
@@ -36,6 +78,48 @@ export class AppComponent {
|
||||
// Si une nouvelle version est deployee pendant la session, l'UpdateBanner
|
||||
// s'affichera automatiquement.
|
||||
versionChecker.start();
|
||||
|
||||
// Retour en largeur desktop : les tiroirs n'ont plus de sens, on les referme.
|
||||
effect(() => {
|
||||
if (!this.isCompact()) this.openDrawer.set(null);
|
||||
});
|
||||
|
||||
// Une navigation (y compris vers l'URL courante, NavigationSkipped) referme le
|
||||
// tiroir : on choisit une page, on veut la voir. Le focus part sur le contenu.
|
||||
this.router.events.pipe(
|
||||
filter(e => e instanceof NavigationEnd || e instanceof NavigationSkipped),
|
||||
takeUntilDestroyed(),
|
||||
).subscribe(() => {
|
||||
if (!this.openDrawer()) return;
|
||||
this.openDrawer.set(null);
|
||||
this.mainContentRef()?.nativeElement.focus({ preventScroll: true });
|
||||
});
|
||||
|
||||
// La recherche globale passe au-dessus : inutile de laisser le tiroir ouvert dessous.
|
||||
this.globalSearch.open$.pipe(filter(Boolean), takeUntilDestroyed()).subscribe(() => this.openDrawer.set(null));
|
||||
}
|
||||
|
||||
toggleDrawer(drawer: Exclude<ShellDrawer, null>): void {
|
||||
if (this.openDrawer() === drawer) {
|
||||
this.closeDrawer();
|
||||
return;
|
||||
}
|
||||
this.openDrawer.set(drawer);
|
||||
// Focus sur le premier élément du tiroir une fois rendu visible.
|
||||
setTimeout(() => this.focusables(this.drawerElement())[0]?.focus());
|
||||
}
|
||||
|
||||
/** Ferme le tiroir et rend le focus au bouton de la barre haute qui l'a ouvert. */
|
||||
closeDrawer(): void {
|
||||
const drawer = this.openDrawer();
|
||||
if (!drawer) return;
|
||||
this.openDrawer.set(null);
|
||||
const toggle = drawer === 'main' ? this.mainToggleRef() : this.treeToggleRef();
|
||||
toggle?.nativeElement.focus();
|
||||
}
|
||||
|
||||
openSearch(): void {
|
||||
this.globalSearch.open();
|
||||
}
|
||||
|
||||
@HostListener('document:keydown', ['$event'])
|
||||
@@ -44,6 +128,45 @@ export class AppComponent {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault();
|
||||
this.globalSearch.toggle();
|
||||
return;
|
||||
}
|
||||
if (!this.openDrawer()) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closeDrawer();
|
||||
} else if (event.key === 'Tab') {
|
||||
this.trapFocus(event);
|
||||
}
|
||||
}
|
||||
|
||||
/** Garde le focus clavier dans le tiroir ouvert (comportement de modale). */
|
||||
private trapFocus(event: KeyboardEvent): void {
|
||||
const drawer = this.drawerElement();
|
||||
const items = this.focusables(drawer);
|
||||
if (!drawer || !items.length) return;
|
||||
const first = items[0];
|
||||
const last = items[items.length - 1];
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = !!active && drawer.contains(active);
|
||||
if (event.shiftKey && (active === first || !inside)) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && (active === last || !inside)) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private drawerElement(): HTMLElement | null {
|
||||
const drawer = this.openDrawer();
|
||||
if (drawer === 'main') return this.mainDrawerRef()?.nativeElement ?? null;
|
||||
if (drawer === 'tree') return this.treeDrawerRef()?.nativeElement ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
private focusables(root: HTMLElement | null): HTMLElement[] {
|
||||
if (!root) return [];
|
||||
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE))
|
||||
.filter(el => el.offsetParent !== null || el.getClientRects().length > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ export const routes: Routes = [
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId/edit', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId', loadComponent: () => import('./campaigns/random-table/random-table-view/random-table-view.component').then(m => m.RandomTableViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/create', loadComponent: () => import('./campaigns/arc/arc-create/arc-create.component').then(m => m.ArcCreateComponent) },
|
||||
{ path: 'campaigns/:campaignId/guided/:method', loadComponent: () => import('./campaigns/guided/guided-wizard/guided-wizard.component').then(m => m.GuidedWizardComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId', loadComponent: () => import('./campaigns/arc/arc-view/arc-view.component').then(m => m.ArcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/edit', loadComponent: () => import('./campaigns/arc/arc-edit/arc-edit.component').then(m => m.ArcEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/arcs/:arcId/chapters/create', loadComponent: () => import('./campaigns/chapter/chapter-create/chapter-create.component').then(m => m.ChapterCreateComponent) },
|
||||
@@ -60,6 +61,8 @@ export const routes: Routes = [
|
||||
{ path: 'game-systems/:id/edit', loadComponent: () => import('./game-systems/game-system-edit/game-system-edit.component').then(m => m.GameSystemEditComponent) },
|
||||
// Routes masquees en mode demo : ajouter canActivate: [hiddenInDemoGuard]
|
||||
// (a prevoir aussi sur la future route d'export VTT).
|
||||
// Accès distant (mode bureau) : appairage d'une tablette par code.
|
||||
{ path: 'pair', loadComponent: () => import('./remote-access/remote-pair/remote-pair.component').then(m => m.RemotePairComponent) },
|
||||
{ path: 'settings', canActivate: [hiddenInDemoGuard], loadComponent: () => import('./settings/settings.component').then(m => m.SettingsComponent) },
|
||||
{ path: '', redirectTo: '/lore', pathMatch: 'full' }
|
||||
];
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
<!-- Tout est optionnel sauf le titre : identité visible, le reste replié. -->
|
||||
<p class="optional-hint">{{ 'arcEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="ARC" [entityId]="arcId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, validation champ par champ → remplit le formulaire. -->
|
||||
<app-entity-assist-panel
|
||||
[entityType]="'arc'" [entityId]="arcId" [campaignId]="campaignId"
|
||||
@@ -47,7 +50,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-description">{{ 'arcEdit.synopsisLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.synopsis"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-description"
|
||||
formControlName="description"
|
||||
@@ -89,10 +95,13 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Thèmes et enjeux -->
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [filled]="themesStakesFilled">
|
||||
<app-expandable-section [title]="'arcEdit.themesStakesSectionTitle' | translate" icon="🎭" [initiallyOpen]="focusSection === 'stakes'" [filled]="themesStakesFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-themes">{{ 'arcEdit.themesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.themes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-themes"
|
||||
formControlName="themes"
|
||||
@@ -101,7 +110,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-stakes">{{ 'arcEdit.stakesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.stakes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-stakes"
|
||||
formControlName="stakes"
|
||||
@@ -129,7 +141,10 @@
|
||||
<!-- Récompenses et dénouement -->
|
||||
<app-expandable-section [title]="'arcEdit.rewardsResolutionSectionTitle' | translate" icon="🎁" [filled]="rewardsResolutionFilled">
|
||||
<div class="field">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-rewards">{{ 'arcEdit.rewardsLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.rewards"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-rewards"
|
||||
formControlName="rewards"
|
||||
@@ -138,7 +153,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="arc-edit-resolution">{{ 'arcEdit.resolutionLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="arc.resolution"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="arc-edit-resolution"
|
||||
formControlName="resolution"
|
||||
|
||||
@@ -26,6 +26,8 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
|
||||
import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* Écran de détail/modification d'un Arc.
|
||||
@@ -38,7 +40,7 @@ import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, ExpandableSectionComponent, EntityAssistPanelComponent, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
|
||||
templateUrl: './arc-edit.component.html',
|
||||
styleUrls: ['./arc-edit.component.scss']
|
||||
})
|
||||
@@ -74,6 +76,9 @@ export class ArcEditComponent implements OnInit {
|
||||
arcId = '';
|
||||
arc: Arc | null = null;
|
||||
|
||||
/** `?focus=stakes` (lien « Voir » de la relecture d'éditeur) → section dépliée d'office. */
|
||||
focusSection: string | null = null;
|
||||
|
||||
/** Pages disponibles pour le picker (vide si la campagne n'a pas de loreId). */
|
||||
availablePages: Page[] = [];
|
||||
/** ID du Lore associé à la campagne (null si campagne sans univers). */
|
||||
@@ -135,6 +140,7 @@ export class ArcEditComponent implements OnInit {
|
||||
if (newArcId !== this.arcId || newCampaignId !== this.campaignId) {
|
||||
this.campaignId = newCampaignId;
|
||||
this.arcId = newArcId;
|
||||
this.focusSection = this.route.snapshot.queryParamMap.get('focus');
|
||||
this.loadAll();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -23,6 +23,29 @@ describe('buildCampaignTree', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('place un nœud « Parties » en tête (avant la narration), une entrée par partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({
|
||||
arcs: [{ id: 'a1', name: 'Arc', type: 'LINEAR' }] as never,
|
||||
chaptersByArc: { a1: [{ id: 'ch1', name: 'C1' }, { id: 'ch2', name: 'C2' }] } as never,
|
||||
playthroughs: [
|
||||
{ id: 'p1', campaignId: 'c1', name: 'Table du mardi' },
|
||||
{ id: 'p2', campaignId: 'c1', name: 'Table du jeudi' },
|
||||
],
|
||||
}), t);
|
||||
expect(tree[0].id).toBe('playthroughs-root');
|
||||
expect(tree[0].sectionHeaderBefore).toBe('campaignTree.sectionPlay');
|
||||
expect(tree[0].meta).toBe('2');
|
||||
expect(tree[0].children!.map((c) => c.route)).toEqual([
|
||||
'/campaigns/c1/playthroughs/p1', '/campaigns/c1/playthroughs/p2',
|
||||
]);
|
||||
expect(tree[1].id).toBe('arc-a1');
|
||||
});
|
||||
|
||||
it('pas de nœud « Parties » sans partie', () => {
|
||||
const tree = buildCampaignTree('c1', data({ playthroughs: [] }), t);
|
||||
expect(tree.some((n) => n.id === 'playthroughs-root')).toBe(false);
|
||||
});
|
||||
|
||||
it('trie les arcs par ordre manuel (champ order, réagencé au glisser-déposer)', () => {
|
||||
const arcs = [
|
||||
{ id: 'a', name: 'Final', order: 2 },
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RandomTableService } from '../services/random-table.service';
|
||||
import { EnemyService } from '../services/enemy.service';
|
||||
import { TreeItem, TreeCreateAction, SecondarySidebarConfig, GlobalItem, ReorderKind } from '../services/layout.service';
|
||||
import { groupByFolder, byOrder } from '../shared/folder-grouping.util';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest } from '../services/campaign.model';
|
||||
import { Arc, Chapter, Scene, Campaign, Quest, Playthrough } from '../services/campaign.model';
|
||||
import { Npc } from '../services/npc.model';
|
||||
import { RandomTable } from '../services/random-table.model';
|
||||
import { Enemy } from '../services/enemy.model';
|
||||
@@ -34,6 +34,8 @@ export interface CampaignTreeData {
|
||||
quests?: Quest[];
|
||||
/** Bilan de readiness complet — évite un fetch séparé pour le panneau du hub. */
|
||||
readiness?: CampaignReadinessAssessment | null;
|
||||
/** Parties (Playthroughs) — nœud « Parties » en tête d'arbre (accès direct aux séances). Optionnel. */
|
||||
playthroughs?: Playthrough[];
|
||||
}
|
||||
|
||||
export function loadCampaignTreeData(
|
||||
@@ -56,13 +58,14 @@ export function loadCampaignTreeData(
|
||||
randomTables: tree.randomTables ?? [],
|
||||
enemies: tree.enemies ?? [],
|
||||
quests: tree.quests ?? [],
|
||||
playthroughs: tree.playthroughs ?? [],
|
||||
gaps: tree.readiness?.gaps ?? [],
|
||||
readiness: tree.readiness ?? null
|
||||
} as CampaignTreeData)),
|
||||
// Dégradation gracieuse : sidebar vide plutôt qu'écran cassé si le back est indisponible.
|
||||
catchError(() => of({
|
||||
arcs: [], chaptersByArc: {}, scenesByChapter: {},
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], gaps: [], readiness: null
|
||||
npcs: [], randomTables: [], enemies: [], quests: [], playthroughs: [], gaps: [], readiness: null
|
||||
} as CampaignTreeData))
|
||||
);
|
||||
}
|
||||
@@ -459,7 +462,31 @@ export function buildCampaignTree(
|
||||
}]
|
||||
};
|
||||
|
||||
return [...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode];
|
||||
// Parties (Playthroughs) : EN TÊTE d'arbre, avant la narration — c'est par une Partie
|
||||
// qu'on lance/reprend une séance ; enfouies en bas du hub, on finissait par les manquer.
|
||||
const playthroughItems: TreeItem[] = (data.playthroughs ?? [])
|
||||
.filter(p => !!p.id)
|
||||
.map(p => ({
|
||||
id: `playthrough-${p.id}`,
|
||||
label: p.name,
|
||||
iconKey: 'c-dice',
|
||||
route: `/campaigns/${campaignId}/playthroughs/${p.id}`
|
||||
}));
|
||||
const playthroughsNode: TreeItem | null = playthroughItems.length ? {
|
||||
id: 'playthroughs-root',
|
||||
label: translate.instant('campaignTree.playthroughs'),
|
||||
iconKey: 'c-dice',
|
||||
children: playthroughItems,
|
||||
meta: String(playthroughItems.length),
|
||||
// Libellé → hub (bloc « Jouer » + liste des Parties) ; chevron → une Partie par nœud.
|
||||
route: `/campaigns/${campaignId}`,
|
||||
sectionHeaderBefore: translate.instant('campaignTree.sectionPlay')
|
||||
} : null;
|
||||
|
||||
return [
|
||||
...(playthroughsNode ? [playthroughsNode] : []),
|
||||
...narrationNodes, questsNode, npcsNode, enemiesNode, tablesNode, notebooksNode, catalogsNode, importNode
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -59,9 +59,19 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<!-- ============ Jouer : reprendre / démarrer une séance (accès direct) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-campaign-play-block
|
||||
[playthroughs]="playthroughs"
|
||||
[creatingPlaythrough]="newPlaythroughInFlight"
|
||||
(createPlaythrough)="createPlaythrough()">
|
||||
</app-campaign-play-block>
|
||||
}
|
||||
<!-- ============ Guidage co-MJ : « Prochaines étapes » (Pilier B) ============ -->
|
||||
@if (!editing && campaign.id) {
|
||||
<app-readiness-panel [campaignId]="campaign.id" [assessment]="readiness"></app-readiness-panel>
|
||||
<!-- Mentor d'écriture (M2) : conseils d'auteur sur la qualité, à côté de la complétude. -->
|
||||
<app-writing-review-panel [campaignId]="campaign.id"></app-writing-review-panel>
|
||||
}
|
||||
<!-- ============ Header : mode édition inline ============ -->
|
||||
@if (editing) {
|
||||
@@ -206,6 +216,11 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.newArc' | translate }}
|
||||
</button>
|
||||
<!-- Mentor d'écriture (M3) : écrire une aventure question par question. -->
|
||||
<a class="btn-add btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entry' | translate }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@if (arcs.length > 0 && !showQuickAddScene) {
|
||||
@@ -235,6 +250,10 @@
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
{{ 'campaignDetail.quickSceneFirst' | translate }}
|
||||
</button>
|
||||
<a class="btn-add-first btn-guided" [routerLink]="['/campaigns', campaign.id, 'guided', 'five-room']">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ 'guided.entryFirst' | translate }}
|
||||
</a>
|
||||
<button type="button" class="empty-alt-action" (click)="createArc()">
|
||||
{{ 'campaignDetail.organizeInArcs' | translate }}
|
||||
</button>
|
||||
|
||||
@@ -173,16 +173,28 @@
|
||||
border-bottom: 1px solid #1f2937;
|
||||
margin-bottom: 1.5rem;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1.5rem;
|
||||
gap: 1rem 1.5rem;
|
||||
|
||||
.header-texts { flex: 1; min-width: 0; }
|
||||
// Le bloc titre réclame ~280 px ; s'il ne les a pas à côté des actions
|
||||
// (tablette, desktop étroit), les actions passent dessous et s'y répartissent.
|
||||
.header-texts { flex: 1 1 280px; min-width: 0; }
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// Téléphone : l'en-tête (titre + 5 actions) mangerait la moitié de l'écran
|
||||
// s'il restait collé en haut pendant le défilement.
|
||||
@media (max-width: 767.98px) {
|
||||
position: static;
|
||||
|
||||
h1 { overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
// Variante mode édition : champs empilés verticalement.
|
||||
@@ -295,8 +307,10 @@
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap; // écran étroit : les actions passent sous le titre au lieu de déborder
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
h2 { color: #d1d5db; font-size: 1rem; font-weight: 600; }
|
||||
@@ -304,6 +318,7 @@
|
||||
|
||||
.section-header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
@@ -486,6 +501,18 @@
|
||||
&:hover { background: #5b52e0; }
|
||||
}
|
||||
|
||||
// Entrée « Méthode guidée » (Mentor d'écriture, M3) : un lien stylé en bouton,
|
||||
// accent ambré du mentor pour le distinguer des créations « à la main ».
|
||||
.btn-guided {
|
||||
text-decoration: none;
|
||||
background: rgba(251, 191, 36, 0.12);
|
||||
color: #fde68a;
|
||||
border: 1px solid rgba(251, 191, 36, 0.35);
|
||||
|
||||
&:hover { background: rgba(251, 191, 36, 0.2); }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; }
|
||||
}
|
||||
|
||||
// Action secondaire de l'état vide (« ou créer un arc ») — bouton texte discret.
|
||||
.empty-alt-action {
|
||||
background: none;
|
||||
|
||||
@@ -32,11 +32,13 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
import { FolderGroup, groupByFolder, byOrder } from '../../../shared/folder-grouping.util';
|
||||
import { CampaignReadinessAssessment } from '../../../services/readiness.model';
|
||||
import { ReadinessPanelComponent } from '../../../shared/readiness-panel/readiness-panel.component';
|
||||
import { WritingReviewPanelComponent } from '../../../shared/writing-review/writing-review-panel.component';
|
||||
import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play-block.component';
|
||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, FoundryExportDialogComponent],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink, TranslatePipe, CdkDropList, CdkDrag, ReadinessPanelComponent, WritingReviewPanelComponent, CampaignPlayBlockComponent, FoundryExportDialogComponent],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
@@ -94,14 +96,6 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
editPlaythroughName = '';
|
||||
/** Sessions de jeu (passées et en cours) liées à cette campagne. */
|
||||
sessions: Session[] = [];
|
||||
/**
|
||||
* Session active globale (toutes campagnes confondues).
|
||||
* Sert à désactiver le bouton "Lancer" si une session tourne déjà ailleurs.
|
||||
* Null si aucune session active dans l'app.
|
||||
*/
|
||||
activeSessionGlobal: Session | null = null;
|
||||
/** Indicateur de lancement en cours pour éviter les double-clics. */
|
||||
startingSession = false;
|
||||
|
||||
/** Parties (Playthroughs) de cette campagne. */
|
||||
playthroughs: Playthrough[] = [];
|
||||
@@ -214,6 +208,18 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||
this.showLayout(allCampaigns, treeData);
|
||||
this.pageTitleService.set(campaign.name);
|
||||
this.openEditFromQueryParam();
|
||||
}
|
||||
|
||||
/**
|
||||
* `?edit=system` (lien « Choisir le système » de l'onglet Règles en séance) : ouvre
|
||||
* directement l'édition inline, puis retire le paramètre pour qu'un rechargement
|
||||
* ne la rouvre pas.
|
||||
*/
|
||||
private openEditFromQueryParam(): void {
|
||||
if (!this.route.snapshot.queryParamMap.has('edit')) return;
|
||||
this.startEdit();
|
||||
this.router.navigate([], { relativeTo: this.route, queryParams: { edit: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<section class="play-block" [class.play-block--live]="target.kind === 'resume'" [attr.aria-label]="'playAccess.block.title' | translate">
|
||||
<div class="play-head">
|
||||
<lucide-icon [img]="Play" [size]="16" class="play-head-icon"></lucide-icon>
|
||||
<h2 class="play-title">{{ 'playAccess.block.title' | translate }}</h2>
|
||||
</div>
|
||||
|
||||
@if (target.kind === 'resume') {
|
||||
<ul class="play-rows">
|
||||
@for (r of target.sessions; track r.session.id) {
|
||||
<li class="play-row">
|
||||
<span class="live-dot" aria-hidden="true"></span>
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-label">{{ 'playAccess.block.running' | translate }}</span>
|
||||
<span class="play-row-sub">{{ r.session.name }} · {{ r.playthrough.name }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" (click)="resume(r.session)">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.resume' | translate }}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else if (target.kind === 'start') {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
@if (target.playthroughs.length > 1) {
|
||||
<label class="play-row-label" for="play-block-playthrough">{{ 'playAccess.block.playthroughLabel' | translate }}</label>
|
||||
<select id="play-block-playthrough" class="play-select" [(ngModel)]="selectedPlaythroughId">
|
||||
@for (p of target.playthroughs; track p.id) {
|
||||
<option [value]="p.id">{{ p.name }}</option>
|
||||
}
|
||||
</select>
|
||||
} @else {
|
||||
<span class="play-row-label">{{ 'playAccess.block.nextSession' | translate }}</span>
|
||||
<span class="play-row-sub">{{ target.playthroughs[0].name }}</span>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="starting" (click)="start()">
|
||||
<lucide-icon [img]="Play" [size]="15"></lucide-icon>
|
||||
{{ (starting ? 'playAccess.block.starting' : 'playAccess.block.start') | translate }}
|
||||
</button>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="play-row">
|
||||
<div class="play-row-texts">
|
||||
<span class="play-row-sub">{{ 'playAccess.block.noPlaythrough' | translate }}</span>
|
||||
</div>
|
||||
<button type="button" class="btn-primary play-btn" [disabled]="creatingPlaythrough" (click)="createPlaythrough.emit()">
|
||||
<lucide-icon [img]="Plus" [size]="15"></lucide-icon>
|
||||
{{ 'playAccess.block.createPlaythrough' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
:host { display: block; }
|
||||
|
||||
.play-block {
|
||||
margin: 0 0 1.25rem;
|
||||
padding: 0.8rem 0.9rem;
|
||||
background: #0d1117;
|
||||
border: 1px solid #2d2a5a;
|
||||
border-radius: 10px;
|
||||
|
||||
&--live { border-color: rgba(16, 185, 129, 0.55); background: rgba(16, 185, 129, 0.05); }
|
||||
}
|
||||
|
||||
.play-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
margin-bottom: 0.55rem;
|
||||
}
|
||||
|
||||
.play-head-icon { color: #a5a0ff; }
|
||||
.play-block--live .play-head-icon { color: #34d399; }
|
||||
|
||||
.play-title {
|
||||
margin: 0;
|
||||
font-size: 0.92rem;
|
||||
font-weight: 600;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
|
||||
.play-rows {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.play-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.play-row-texts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
flex: 1 1 12rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.play-row-label {
|
||||
font-size: 0.75rem;
|
||||
color: #9ca3af;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.play-row-sub {
|
||||
font-size: 0.9rem;
|
||||
color: #e5e7eb;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.play-select {
|
||||
width: 100%;
|
||||
max-width: 22rem;
|
||||
min-height: 44px;
|
||||
padding: 0.45rem 0.6rem;
|
||||
background: #111827;
|
||||
color: #e5e7eb;
|
||||
border: 1px solid #374151;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.play-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 44px;
|
||||
padding: 0.55rem 1.1rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.play-block--live .play-btn {
|
||||
background: #059669;
|
||||
&:hover:not(:disabled) { background: #047857; }
|
||||
}
|
||||
|
||||
.live-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #10b981;
|
||||
animation: live-pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes live-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6); }
|
||||
70% { box-shadow: 0 0 0 7px rgba(16, 185, 129, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.live-dot { animation: none; }
|
||||
}
|
||||
|
||||
// Téléphone : bouton pleine largeur sous le texte.
|
||||
@media (max-width: 480px) {
|
||||
.play-btn { flex: 1 1 100%; }
|
||||
.play-select { max-width: none; }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Component, DestroyRef, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { TranslatePipe } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, Play, Plus } from 'lucide-angular';
|
||||
import { ActiveSessionsService } from '../../../services/active-sessions.service';
|
||||
import { SessionService } from '../../../services/session.service';
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
import { PlayTarget, computePlayTarget } from './play-target.util';
|
||||
|
||||
/**
|
||||
* Bloc « Jouer » en tête du hub campagne : reprendre la séance en cours, ou en démarrer
|
||||
* une sur la Partie la plus récente (ou en créer une s'il n'y en a aucune). La liste
|
||||
* complète des Parties reste en bas du hub ; ce bloc n'est qu'un accès direct.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-campaign-play-block',
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe],
|
||||
templateUrl: './campaign-play-block.component.html',
|
||||
styleUrls: ['./campaign-play-block.component.scss']
|
||||
})
|
||||
export class CampaignPlayBlockComponent implements OnInit, OnChanges {
|
||||
readonly Play = Play;
|
||||
readonly Plus = Plus;
|
||||
|
||||
@Input() playthroughs: Playthrough[] = [];
|
||||
/** Création de Partie déléguée au hub (même nom par défaut, même navigation). */
|
||||
@Input() creatingPlaythrough = false;
|
||||
@Output() createPlaythrough = new EventEmitter<void>();
|
||||
|
||||
target: PlayTarget = { kind: 'create' };
|
||||
selectedPlaythroughId = '';
|
||||
starting = false;
|
||||
|
||||
private activeSessions: Session[] = [];
|
||||
|
||||
constructor(
|
||||
private activeSessionsService: ActiveSessionsService,
|
||||
private sessionService: SessionService,
|
||||
private router: Router,
|
||||
private destroyRef: DestroyRef
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.activeSessionsService.active$.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(list => {
|
||||
this.activeSessions = list.map(e => e.session);
|
||||
this.recompute();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnChanges(): void {
|
||||
this.recompute();
|
||||
}
|
||||
|
||||
private recompute(): void {
|
||||
this.target = computePlayTarget(this.playthroughs, this.activeSessions);
|
||||
if (this.target.kind === 'start') {
|
||||
const ids = this.target.playthroughs.map(p => p.id);
|
||||
if (!ids.includes(this.selectedPlaythroughId)) {
|
||||
this.selectedPlaythroughId = this.target.defaultPlaythroughId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resume(session: Session): void {
|
||||
this.router.navigate(['/sessions', session.id]);
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.starting || !this.selectedPlaythroughId) return;
|
||||
this.starting = true;
|
||||
this.sessionService.startSession(this.selectedPlaythroughId).subscribe({
|
||||
next: s => { this.starting = false; this.router.navigate(['/sessions', s.id]); },
|
||||
error: () => { this.starting = false; }
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computePlayTarget, sortPlaythroughsRecentFirst } from './play-target.util';
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
|
||||
const pt = (id: string, createdAt?: string): Playthrough => ({ id, campaignId: 'c1', name: `P${id}`, createdAt });
|
||||
const session = (id: string, playthroughId: string, startedAt: string, active = true): Session => ({
|
||||
id, name: `S${id}`, playthroughId, startedAt, endedAt: active ? null : startedAt,
|
||||
createdAt: startedAt, updatedAt: startedAt, active
|
||||
});
|
||||
|
||||
describe('sortPlaythroughsRecentFirst', () => {
|
||||
it('trie par date de création décroissante', () => {
|
||||
const r = sortPlaythroughsRecentFirst([pt('1', '2026-01-01'), pt('2', '2026-03-01'), pt('3', '2026-02-01')]);
|
||||
expect(r.map(p => p.id)).toEqual(['2', '3', '1']);
|
||||
});
|
||||
|
||||
it('sans dates : la dernière de la liste est la plus récente', () => {
|
||||
expect(sortPlaythroughsRecentFirst([pt('1'), pt('2')]).map(p => p.id)).toEqual(['2', '1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computePlayTarget', () => {
|
||||
it('aucune partie → create', () => {
|
||||
expect(computePlayTarget([], [])).toEqual({ kind: 'create' });
|
||||
});
|
||||
|
||||
it('pas de séance en cours → start sur la partie la plus récente', () => {
|
||||
const t = computePlayTarget([pt('1', '2026-01-01'), pt('2', '2026-05-01')], []);
|
||||
expect(t.kind).toBe('start');
|
||||
if (t.kind === 'start') {
|
||||
expect(t.defaultPlaythroughId).toBe('2');
|
||||
expect(t.playthroughs.map(p => p.id)).toEqual(['2', '1']);
|
||||
}
|
||||
});
|
||||
|
||||
it('ignore les séances des autres campagnes et les séances terminées', () => {
|
||||
const t = computePlayTarget([pt('1')], [session('a', 'other', '2026-01-01'), session('b', '1', '2026-01-01', false)]);
|
||||
expect(t.kind).toBe('start');
|
||||
});
|
||||
|
||||
it('séance(s) en cours sur la campagne → resume, la plus récente d\'abord', () => {
|
||||
const t = computePlayTarget([pt('1'), pt('2')], [
|
||||
session('a', '1', '2026-01-01T10:00:00'),
|
||||
session('b', '2', '2026-01-02T10:00:00'),
|
||||
session('c', 'other', '2026-01-03T10:00:00')
|
||||
]);
|
||||
expect(t.kind).toBe('resume');
|
||||
if (t.kind === 'resume') {
|
||||
expect(t.sessions.map(s => s.session.id)).toEqual(['b', 'a']);
|
||||
expect(t.sessions[0].playthrough.id).toBe('2');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Playthrough } from '../../../services/campaign.model';
|
||||
import { Session } from '../../../services/session.model';
|
||||
|
||||
/**
|
||||
* Ce que propose le bloc « Jouer » du hub campagne :
|
||||
* - resume : une (ou plusieurs) séance(s) tourne(nt) sur une Partie de la campagne ;
|
||||
* - start : aucune séance en cours → démarrer sur une Partie (la plus récente par défaut) ;
|
||||
* - create : aucune Partie → en créer une d'abord.
|
||||
*/
|
||||
export type PlayTarget =
|
||||
| { kind: 'resume'; sessions: { session: Session; playthrough: Playthrough }[] }
|
||||
| { kind: 'start'; playthroughs: Playthrough[]; defaultPlaythroughId: string }
|
||||
| { kind: 'create' };
|
||||
|
||||
const timeOf = (p: Playthrough): number => {
|
||||
const t = Date.parse(p.createdAt ?? p.updatedAt ?? '');
|
||||
return Number.isNaN(t) ? 0 : t;
|
||||
};
|
||||
|
||||
/** Parties de la plus récente à la plus ancienne (création ; à défaut, ordre d'origine). */
|
||||
export function sortPlaythroughsRecentFirst(playthroughs: Playthrough[]): Playthrough[] {
|
||||
return playthroughs
|
||||
.map((p, i) => ({ p, i }))
|
||||
.sort((a, b) => (timeOf(b.p) - timeOf(a.p)) || (b.i - a.i))
|
||||
.map(x => x.p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Décide du bloc « Jouer » à partir des Parties de la campagne et des séances en cours
|
||||
* de TOUTE l'appli (filtrées ici sur les Parties de la campagne, plus récente d'abord).
|
||||
*/
|
||||
export function computePlayTarget(playthroughs: Playthrough[], activeSessions: Session[]): PlayTarget {
|
||||
const withId = playthroughs.filter((p): p is Playthrough & { id: string } => !!p.id);
|
||||
if (withId.length === 0) return { kind: 'create' };
|
||||
|
||||
const byId = new Map(withId.map(p => [p.id, p]));
|
||||
const running = activeSessions
|
||||
.filter(s => s.active && byId.has(s.playthroughId))
|
||||
.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt))
|
||||
.map(session => ({ session, playthrough: byId.get(session.playthroughId)! }));
|
||||
if (running.length > 0) return { kind: 'resume', sessions: running };
|
||||
|
||||
const sorted = sortPlaythroughsRecentFirst(withId);
|
||||
return { kind: 'start', playthroughs: sorted, defaultPlaythroughId: sorted[0].id! };
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
text-align: center;
|
||||
margin-bottom: 3rem;
|
||||
|
||||
@media (max-width: 767.98px) { margin-bottom: 1.5rem; }
|
||||
|
||||
.hero-icon { display: block; margin-bottom: 1rem; color: #6c63ff; }
|
||||
|
||||
h1 { font-size: 2rem; font-weight: 700; color: white; margin-bottom: 0.5rem; }
|
||||
@@ -19,7 +21,9 @@
|
||||
|
||||
.campaigns-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
// 3 colonnes sur desktop (max-width 900px), moins dès que la carte passerait
|
||||
// sous 240 px : 2 sur tablette portrait, 1 sur téléphone.
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr));
|
||||
gap: 1.5rem;
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
<!-- Tout est optionnel sauf le titre : identité visible, le reste replié. -->
|
||||
<p class="optional-hint">{{ 'chapterEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="CHAPTER" [entityId]="chapterId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, validation champ par champ → remplit le formulaire. -->
|
||||
<app-entity-assist-panel
|
||||
[entityType]="'chapter'" [entityId]="chapterId" [campaignId]="campaignId"
|
||||
@@ -53,7 +56,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="chapter-edit-description">{{ 'chapterEdit.synopsisLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-description">{{ 'chapterEdit.synopsisLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.synopsis"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-description"
|
||||
formControlName="description"
|
||||
@@ -93,10 +99,13 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Objectifs et enjeux -->
|
||||
<app-expandable-section [title]="'chapterEdit.objectivesStakesSectionTitle' | translate" icon="🎯" [filled]="objectivesStakesFilled">
|
||||
<app-expandable-section [title]="'chapterEdit.objectivesStakesSectionTitle' | translate" icon="🎯" [initiallyOpen]="focusSection === 'stakes'" [filled]="objectivesStakesFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="chapter-edit-player-objectives">{{ 'chapterEdit.playerObjectivesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-player-objectives">{{ 'chapterEdit.playerObjectivesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.objectives"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-player-objectives"
|
||||
formControlName="playerObjectives"
|
||||
@@ -105,7 +114,10 @@
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="chapter-edit-narrative-stakes">{{ 'chapterEdit.narrativeStakesLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="chapter-edit-narrative-stakes">{{ 'chapterEdit.narrativeStakesLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="chapter.stakes"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="chapter-edit-narrative-stakes"
|
||||
formControlName="narrativeStakes"
|
||||
|
||||
@@ -27,6 +27,8 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
import { EntityAssistPanelComponent } from '../../../shared/entity-assist-panel/entity-assist-panel.component';
|
||||
import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { SceneDraftPanelComponent } from '../../../shared/scene-draft-panel/scene-draft-panel.component';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* Écran d'édition d'un Chapitre. Donnée de SCÉNARIO uniquement.
|
||||
@@ -47,7 +49,8 @@ import { SceneDraftPanelComponent } from '../../../shared/scene-draft-panel/scen
|
||||
ExpandableSectionComponent,
|
||||
EntityAssistPanelComponent,
|
||||
SceneDraftPanelComponent,
|
||||
TranslatePipe
|
||||
TranslatePipe,
|
||||
WritingCoachTriggerComponent, WritingReviewHintsComponent
|
||||
],
|
||||
templateUrl: './chapter-edit.component.html',
|
||||
styleUrls: ['./chapter-edit.component.scss']
|
||||
@@ -88,6 +91,9 @@ export class ChapterEditComponent implements OnInit {
|
||||
/** `?assist=draft-scenes` (bouton « Corriger » du guidage) → panneau IA déployé d'office. */
|
||||
assistParam: string | null = null;
|
||||
|
||||
/** `?focus=stakes` (lien « Voir » de la relecture d'éditeur) → section dépliée d'office. */
|
||||
focusSection: string | null = null;
|
||||
|
||||
availablePages: Page[] = [];
|
||||
loreId: string | null = null;
|
||||
relatedPageIds: string[] = [];
|
||||
@@ -144,6 +150,7 @@ export class ChapterEditComponent implements OnInit {
|
||||
this.arcId = newArcId;
|
||||
this.chapterId = newChapterId;
|
||||
this.assistParam = this.route.snapshot.queryParamMap.get('assist');
|
||||
this.focusSection = this.route.snapshot.queryParamMap.get('focus');
|
||||
this.loadAll();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -308,3 +308,10 @@
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
// Écrans sans survol (tactile) : poignées de liaison et de renommage visibles
|
||||
// en permanence (elles n'apparaissaient qu'au survol du nœud).
|
||||
@media (hover: none) {
|
||||
.node .node-connect { opacity: 0.9; }
|
||||
.node .node-rename { opacity: 1; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { GuidedChapterSpec, GuidedSceneSpec } from '../../services/guided-skeleton.model';
|
||||
|
||||
/**
|
||||
* Définition d'une méthode guidée (Mentor d'écriture, phases M3/M5). L'assistant
|
||||
* `guided-wizard` est générique : il affiche les étapes d'une méthode et lui délègue
|
||||
* la construction du squelette. Ajouter une méthode = un fichier de définition + ses
|
||||
* textes i18n (`guided.<i18nKey>.*`) + son entrée dans `GUIDED_METHODS`.
|
||||
*
|
||||
* Conventions i18n (préfixe `guided.<i18nKey>.`) :
|
||||
* - `name`, `tagline` : présentation de la méthode ;
|
||||
* - `steps.<stepId>.title|why|example` : chaque étape (pourquoi + exemple, posture mentor) ;
|
||||
* - `fields.<fieldKey>.label|placeholder` : chaque champ (`fieldKey` peut contenir des points) ;
|
||||
* - `options.<fieldKey>.<option>` : libellés des choix ;
|
||||
* - `defaults.<fieldKey>` : valeur proposée d'office (ex. nom d'une salle).
|
||||
*/
|
||||
|
||||
/** Réponses du MJ, par clé de champ. */
|
||||
export type GuidedAnswers = Record<string, string>;
|
||||
|
||||
export interface GuidedField {
|
||||
key: string;
|
||||
kind: 'text' | 'textarea' | 'choice';
|
||||
required?: boolean;
|
||||
/** Valeurs possibles d'un champ `choice` (la 1re est sélectionnée par défaut). */
|
||||
options?: string[];
|
||||
/** Pré-remplir avec `defaults.<key>` (traduit) à la première visite. */
|
||||
prefilled?: boolean;
|
||||
/** Sujet du coach d'écriture (💡) associé, ex. `scene.choices`. */
|
||||
coachTopic?: string;
|
||||
}
|
||||
|
||||
export interface GuidedStep {
|
||||
id: string;
|
||||
/** `placement` : où ranger l'aventure ; `form` : questions ; `review` : récapitulatif. */
|
||||
kind: 'placement' | 'form' | 'review';
|
||||
fields?: GuidedField[];
|
||||
}
|
||||
|
||||
/** Ce que la méthode produit à partir des réponses (le placement est ajouté par l'assistant). */
|
||||
export interface GuidedDraft {
|
||||
chapter: GuidedChapterSpec;
|
||||
scenes: GuidedSceneSpec[];
|
||||
}
|
||||
|
||||
export interface GuidedMethod {
|
||||
/** Identifiant d'URL (`/campaigns/:id/guided/:method`). */
|
||||
id: string;
|
||||
/** Préfixe i18n sous `guided.`. */
|
||||
i18nKey: string;
|
||||
steps: GuidedStep[];
|
||||
toDraft(answers: GuidedAnswers): GuidedDraft;
|
||||
}
|
||||
|
||||
/** Valeur nettoyée d'une réponse (chaîne vide → null). */
|
||||
export function answer(answers: GuidedAnswers, key: string): string | null {
|
||||
const value = answers[key]?.trim();
|
||||
return value ? value : null;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { GuidedField, GuidedStep } from './guided-method.model';
|
||||
import { GUIDED_METHODS } from './guided-methods';
|
||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||
|
||||
/**
|
||||
* Garde-fous des méthodes guidées : chaque étape / champ / option / valeur par défaut
|
||||
* a son texte en fr ET en en (sinon l'assistant afficherait des clés brutes), et la
|
||||
* méthode « 5 salles » produit le bon squelette.
|
||||
*/
|
||||
const FRAGMENTS_DIR = join(process.cwd(), 'src/assets/i18n/fragments');
|
||||
|
||||
function i18n(lang: 'fr' | 'en'): Record<string, unknown> {
|
||||
return JSON.parse(readFileSync(join(FRAGMENTS_DIR, `guided.${lang}.json`), 'utf-8')).guided;
|
||||
}
|
||||
|
||||
function lookup(root: Record<string, unknown>, path: string): unknown {
|
||||
return path.split('.').reduce<unknown>((node, part) =>
|
||||
node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined, root);
|
||||
}
|
||||
|
||||
function fieldKeys(p: string, f: GuidedField): string[] {
|
||||
return [
|
||||
`${p}.fields.${f.key}.label`,
|
||||
...(f.kind === 'choice' ? [] : [`${p}.fields.${f.key}.placeholder`]),
|
||||
...(f.options ?? []).map(o => `${p}.options.${f.key}.${o}`),
|
||||
...(f.prefilled ? [`${p}.defaults.${f.key}`] : [])
|
||||
];
|
||||
}
|
||||
|
||||
function stepKeys(p: string, step: GuidedStep): string[] {
|
||||
return [
|
||||
`${p}.steps.${step.id}.title`,
|
||||
`${p}.steps.${step.id}.why`,
|
||||
...(step.kind === 'review' ? [] : [`${p}.steps.${step.id}.example`]),
|
||||
...(step.fields ?? []).flatMap(f => fieldKeys(p, f))
|
||||
];
|
||||
}
|
||||
|
||||
function requiredKeys(): string[] {
|
||||
return GUIDED_METHODS.flatMap(m => [`${m.i18nKey}.name`, ...m.steps.flatMap(s => stepKeys(m.i18nKey, s))]);
|
||||
}
|
||||
|
||||
describe('guided methods content', () => {
|
||||
const keys = requiredKeys();
|
||||
|
||||
for (const lang of ['fr', 'en'] as const) {
|
||||
it.each(keys)(`${lang}: guided.%s is a non-empty text`, key => {
|
||||
const value = lookup(i18n(lang), key);
|
||||
expect(typeof value === 'string' && value.trim().length > 0, `guided.${key} (${lang})`).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it('has unique method ids and step ids', () => {
|
||||
expect(new Set(GUIDED_METHODS.map(m => m.id)).size).toBe(GUIDED_METHODS.length);
|
||||
for (const m of GUIDED_METHODS) {
|
||||
expect(new Set(m.steps.map(s => s.id)).size).toBe(m.steps.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('five-room method', () => {
|
||||
const answers = {
|
||||
title: ' Le reliquaire volé ',
|
||||
location: 'La crypte',
|
||||
hook: 'Le prêtre a disparu',
|
||||
objectives: 'Ramener la relique',
|
||||
stakes: '',
|
||||
'room1.name': "L'entrée gardée",
|
||||
'room1.nature': 'social',
|
||||
'room1.choices': 'Convaincre ou ruser',
|
||||
'room2.name': "L'épreuve",
|
||||
'room2.nature': 'puzzle',
|
||||
'room3.name': 'Le revers',
|
||||
'room4.name': 'Le climax',
|
||||
'room4.enemies': "L'envoûteuse",
|
||||
'room5.name': 'La récompense',
|
||||
'room5.secret': 'Le symbole de la confrérie'
|
||||
};
|
||||
|
||||
it('builds the chapter from the frame and stakes answers', () => {
|
||||
expect(FIVE_ROOM_METHOD.toDraft(answers).chapter).toEqual({
|
||||
name: 'Le reliquaire volé',
|
||||
description: 'Le prêtre a disparu',
|
||||
playerObjectives: 'Ramener la relique',
|
||||
narrativeStakes: null
|
||||
});
|
||||
});
|
||||
|
||||
it('builds five typed scenes in the same place', () => {
|
||||
const scenes = FIVE_ROOM_METHOD.toDraft(answers).scenes;
|
||||
expect(scenes.map(s => s.type)).toEqual(['NPC', 'LOCATION', 'EVENT', 'ENCOUNTER', 'REVELATION']);
|
||||
expect(scenes.every(s => s.location === 'La crypte')).toBe(true);
|
||||
expect(scenes[0].choicesConsequences).toBe('Convaincre ou ruser');
|
||||
expect(scenes[3].enemies).toBe("L'envoûteuse");
|
||||
expect(scenes[4].gmSecretNotes).toBe('Le symbole de la confrérie');
|
||||
});
|
||||
|
||||
it('defaults room 1 to a fight when no nature was chosen', () => {
|
||||
expect(FIVE_ROOM_METHOD.toDraft({}).scenes[0].type).toBe('ENCOUNTER');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { GuidedMethod } from './guided-method.model';
|
||||
import { FIVE_ROOM_METHOD } from './methods/five-room.method';
|
||||
|
||||
/** Méthodes guidées disponibles (M5 : préparation minimale, enquête, casse, bac à sable…). */
|
||||
export const GUIDED_METHODS: GuidedMethod[] = [FIVE_ROOM_METHOD];
|
||||
|
||||
export function findGuidedMethod(id: string | null): GuidedMethod | undefined {
|
||||
return GUIDED_METHODS.find(m => m.id === id);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
@if (method && step) {
|
||||
<div class="wizard">
|
||||
|
||||
<header class="wizard-top">
|
||||
<a class="wizard-back" [routerLink]="['/campaigns', campaignId]">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
{{ 'guided.backToCampaign' | translate }}
|
||||
</a>
|
||||
<div class="wizard-method">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ k('name') | translate }}
|
||||
</div>
|
||||
<div class="wizard-progress" role="progressbar"
|
||||
[attr.aria-valuenow]="stepIndex + 1" aria-valuemin="1" [attr.aria-valuemax]="total"
|
||||
[attr.aria-label]="'guided.progress' | translate: { n: stepIndex + 1, total: total }">
|
||||
<span class="progress-text">{{ 'guided.progress' | translate: { n: stepIndex + 1, total: total } }}</span>
|
||||
<span class="progress-track"><span class="progress-fill" [style.width.%]="progress"></span></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="wizard-step">
|
||||
<h1 #stepTitle tabindex="-1">{{ k('steps.' + step.id + '.title') | translate }}</h1>
|
||||
<p class="step-why">{{ k('steps.' + step.id + '.why') | translate }}</p>
|
||||
|
||||
@if (step.kind !== 'review') {
|
||||
<aside class="step-example">
|
||||
<span class="example-label">{{ 'guided.exampleLabel' | translate }}</span>
|
||||
<p>{{ k('steps.' + step.id + '.example') | translate }}</p>
|
||||
</aside>
|
||||
}
|
||||
|
||||
<!-- Où ranger l'aventure -->
|
||||
@if (step.kind === 'placement') {
|
||||
<fieldset class="placement">
|
||||
<legend class="sr-only">{{ k('steps.placement.title') | translate }}</legend>
|
||||
@if (linearArcs.length > 0) {
|
||||
<label class="option-card" [class.selected]="answers['placement.mode'] === 'existing'">
|
||||
<input type="radio" name="placement-mode" value="existing"
|
||||
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
|
||||
<span>{{ 'guided.placementExisting' | translate }}</span>
|
||||
</label>
|
||||
@if (answers['placement.mode'] === 'existing') {
|
||||
<div class="field nested">
|
||||
<label for="guided-arc">{{ 'guided.placementArcLabel' | translate }}</label>
|
||||
<select id="guided-arc" [ngModel]="answers['placement.arcId']"
|
||||
(ngModelChange)="setAnswer('placement.arcId', $event)">
|
||||
@for (arc of linearArcs; track arc.id) {
|
||||
<option [value]="arc.id">{{ arc.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<label class="option-card" [class.selected]="answers['placement.mode'] === 'new'">
|
||||
<input type="radio" name="placement-mode" value="new"
|
||||
[ngModel]="answers['placement.mode']" (ngModelChange)="setAnswer('placement.mode', $event)" />
|
||||
<span>{{ 'guided.placementNew' | translate }}</span>
|
||||
</label>
|
||||
@if (answers['placement.mode'] === 'new') {
|
||||
<div class="field nested">
|
||||
<label for="guided-new-arc">{{ 'guided.placementNewArcLabel' | translate }} *</label>
|
||||
<input id="guided-new-arc" type="text" [ngModel]="answers['placement.newArcName']"
|
||||
(ngModelChange)="setAnswer('placement.newArcName', $event)"
|
||||
[placeholder]="'guided.placementNewArcPlaceholder' | translate" />
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
<!-- Questions de l'étape -->
|
||||
@if (step.kind === 'form') {
|
||||
<div class="step-fields">
|
||||
@for (field of step.fields; track field.key) {
|
||||
@if (field.kind === 'choice') {
|
||||
<fieldset class="field choice-field">
|
||||
<legend>{{ k('fields.' + field.key + '.label') | translate }}</legend>
|
||||
<div class="choice-row">
|
||||
@for (option of field.options; track option) {
|
||||
<label class="choice-chip" [class.selected]="answers[field.key] === option">
|
||||
<!-- attr.* : name/value doivent exister dans le DOM (groupe radio natif,
|
||||
navigation clavier) ; [value] seul est consommé par le ControlValueAccessor. -->
|
||||
<input type="radio" [attr.name]="fieldId(field)" [attr.value]="option" [value]="option"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)" />
|
||||
{{ k('options.' + field.key + '.' + option) | translate }}
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
} @else {
|
||||
<div class="field">
|
||||
<div class="field-label-row">
|
||||
<label [for]="fieldId(field)">
|
||||
{{ k('fields.' + field.key + '.label') | translate }}@if (field.required) { * }
|
||||
</label>
|
||||
@if (field.coachTopic) {
|
||||
<app-writing-coach-trigger [topic]="field.coachTopic"></app-writing-coach-trigger>
|
||||
}
|
||||
</div>
|
||||
@if (field.kind === 'textarea') {
|
||||
<textarea [id]="fieldId(field)" rows="3"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)"
|
||||
[placeholder]="k('fields.' + field.key + '.placeholder') | translate"></textarea>
|
||||
} @else {
|
||||
<input [id]="fieldId(field)" type="text"
|
||||
[ngModel]="answers[field.key]" (ngModelChange)="setAnswer(field.key, $event)"
|
||||
[placeholder]="k('fields.' + field.key + '.placeholder') | translate" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Récapitulatif -->
|
||||
@if (step.kind === 'review' && draft; as d) {
|
||||
<div class="review">
|
||||
<dl class="review-meta">
|
||||
<dt>{{ 'guided.reviewArc' | translate }}</dt>
|
||||
<dd>{{ placementLabel }}</dd>
|
||||
<dt>{{ 'guided.reviewChapter' | translate }}</dt>
|
||||
<dd>{{ d.chapter.name }}</dd>
|
||||
</dl>
|
||||
<ol class="review-scenes">
|
||||
@for (scene of d.scenes; track $index) {
|
||||
<li>
|
||||
<span class="scene-name">{{ scene.name }}</span>
|
||||
<span class="scene-type">{{ ('sceneType.' + scene.type) | translate }}</span>
|
||||
</li>
|
||||
}
|
||||
</ol>
|
||||
<label class="link-toggle">
|
||||
<input type="checkbox" [(ngModel)]="linkScenes" />
|
||||
{{ 'guided.linkScenes' | translate }}
|
||||
</label>
|
||||
<p class="review-after">{{ 'guided.reviewAfter' | translate }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (error) {
|
||||
<p class="wizard-error" role="alert">{{ error }}</p>
|
||||
}
|
||||
</main>
|
||||
|
||||
<footer class="wizard-nav">
|
||||
<button type="button" class="btn-secondary" (click)="previous()" [disabled]="stepIndex === 0">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon>
|
||||
{{ 'guided.previous' | translate }}
|
||||
</button>
|
||||
<button type="button" class="btn-ghost" (click)="restart()">
|
||||
<lucide-icon [img]="RotateCcw" [size]="14"></lucide-icon>
|
||||
{{ 'guided.restart' | translate }}
|
||||
</button>
|
||||
@if (isLast) {
|
||||
<button type="button" class="btn-primary" (click)="create()" [disabled]="submitting">
|
||||
<lucide-icon [img]="Check" [size]="14"></lucide-icon>
|
||||
{{ (submitting ? 'guided.creating' : 'guided.create') | translate }}
|
||||
</button>
|
||||
} @else {
|
||||
<button type="button" class="btn-primary" (click)="next()" [disabled]="!canProceed()">
|
||||
{{ 'guided.next' | translate }}
|
||||
<lucide-icon [img]="ArrowRight" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</footer>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="wizard">
|
||||
<p class="wizard-error">{{ 'guided.unknownMethod' | translate }}</p>
|
||||
<a [routerLink]="['/campaigns', campaignId]">{{ 'guided.backToCampaign' | translate }}</a>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// Une étape par écran, colonne unique et étroite : lisible sur ordinateur comme
|
||||
// sur téléphone (la barre de navigation reste collée en bas de l'écran).
|
||||
.wizard {
|
||||
max-width: 680px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 0 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.wizard-top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.6rem 1rem;
|
||||
}
|
||||
|
||||
.wizard-back {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover { color: #e5e7eb; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; outline-offset: 2px; border-radius: 4px; }
|
||||
}
|
||||
|
||||
.wizard-method {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
color: #fbbf24;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.wizard-progress {
|
||||
flex-basis: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #9ca3af;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: #1f2937;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: #6c63ff;
|
||||
border-radius: 999px;
|
||||
transition: width 0.25s ease;
|
||||
}
|
||||
|
||||
.wizard-step {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.1rem;
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
color: white;
|
||||
text-wrap: balance;
|
||||
|
||||
&:focus { outline: none; }
|
||||
}
|
||||
}
|
||||
|
||||
.step-why {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.6;
|
||||
color: #d1d5db;
|
||||
}
|
||||
|
||||
.step-example {
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 8px;
|
||||
background: rgba(108, 99, 255, 0.08);
|
||||
border: 1px solid rgba(108, 99, 255, 0.25);
|
||||
|
||||
p {
|
||||
margin: 0.3rem 0 0;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.55;
|
||||
font-style: italic;
|
||||
color: #d1d5db;
|
||||
}
|
||||
}
|
||||
|
||||
.example-label {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: #a5b4fc;
|
||||
}
|
||||
|
||||
.step-fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.1rem;
|
||||
}
|
||||
|
||||
// --- Placement & choix ---------------------------------------------------------------
|
||||
|
||||
.placement {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.option-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
padding: 0.9rem 1rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #374151;
|
||||
background: #111827;
|
||||
color: #e5e7eb;
|
||||
font-size: 0.92rem;
|
||||
cursor: pointer;
|
||||
|
||||
&.selected { border-color: #6c63ff; background: rgba(108, 99, 255, 0.1); }
|
||||
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
||||
}
|
||||
|
||||
.nested {
|
||||
margin: 0 0 0.4rem 1.6rem;
|
||||
}
|
||||
|
||||
.choice-field {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
|
||||
legend {
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #d1d5db;
|
||||
}
|
||||
}
|
||||
|
||||
.choice-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.choice-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
min-height: 44px;
|
||||
padding: 0 1rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid #374151;
|
||||
background: #111827;
|
||||
color: #d1d5db;
|
||||
font-size: 0.88rem;
|
||||
cursor: pointer;
|
||||
|
||||
&.selected { border-color: #6c63ff; color: white; background: rgba(108, 99, 255, 0.15); }
|
||||
input { accent-color: #6c63ff; margin: 0; }
|
||||
&:focus-within { outline: 2px solid #6c63ff; outline-offset: 2px; }
|
||||
}
|
||||
|
||||
// --- Récapitulatif --------------------------------------------------------------------
|
||||
|
||||
.review {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.review-meta {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.4rem 1rem;
|
||||
margin: 0;
|
||||
|
||||
dt { color: #9ca3af; font-size: 0.85rem; }
|
||||
dd { margin: 0; color: #f3f4f6; font-weight: 600; font-size: 0.9rem; overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
.review-scenes {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
counter-reset: scene;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
|
||||
li {
|
||||
counter-increment: scene;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border-radius: 8px;
|
||||
background: #111827;
|
||||
border: 1px solid #1f2937;
|
||||
|
||||
&::before {
|
||||
content: counter(scene);
|
||||
flex-shrink: 0;
|
||||
width: 1.6rem;
|
||||
height: 1.6rem;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #1f2937;
|
||||
color: #a5b4fc;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.scene-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
color: #f3f4f6;
|
||||
font-size: 0.9rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.scene-type {
|
||||
flex-shrink: 0;
|
||||
padding: 0.1rem 0.55rem;
|
||||
border-radius: 999px;
|
||||
background: #1f2937;
|
||||
color: #9ca3af;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.link-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
color: #d1d5db;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
|
||||
input { accent-color: #6c63ff; width: 18px; height: 18px; margin: 0; }
|
||||
}
|
||||
|
||||
.review-after {
|
||||
margin: 0;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.wizard-error {
|
||||
margin: 0;
|
||||
color: #fca5a5;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
// --- Navigation -------------------------------------------------------------------------
|
||||
|
||||
.wizard-nav {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
margin-top: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 0;
|
||||
background: #0a0a14;
|
||||
border-top: 1px solid #1f2937;
|
||||
|
||||
.btn-primary { margin-left: auto; }
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
min-height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
padding: 0.6rem 0.8rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover { color: #e5e7eb; background: #111827; }
|
||||
&:focus-visible { outline: 2px solid #6c63ff; }
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.wizard { padding-top: 1rem; }
|
||||
.wizard-step h1 { font-size: 1.3rem; }
|
||||
.wizard-nav {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
|
||||
.btn-secondary,
|
||||
.btn-primary { flex: 1; padding-left: 0.75rem; padding-right: 0.75rem; }
|
||||
.btn-ghost { order: -1; flex-basis: 100%; justify-content: flex-start; padding-left: 0; }
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.progress-fill { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Component, DestroyRef, ElementRef, OnInit, ViewChild, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||
import { LucideAngularModule, ArrowLeft, ArrowRight, Check, RotateCcw, Sparkles } from 'lucide-angular';
|
||||
|
||||
import { Arc } from '../../../services/campaign.model';
|
||||
import { CampaignService } from '../../../services/campaign.service';
|
||||
import { GuidedSkeletonService } from '../../../services/guided-skeleton.service';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { GuidedAnswers, GuidedDraft, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
|
||||
import { findGuidedMethod } from '../guided-methods';
|
||||
|
||||
/** Clés de réponse réservées à l'assistant (placement + chaînage), communes à toutes les méthodes. */
|
||||
const PLACEMENT_MODE = 'placement.mode';
|
||||
const PLACEMENT_ARC = 'placement.arcId';
|
||||
const PLACEMENT_NEW_ARC = 'placement.newArcName';
|
||||
const LINK_SCENES = 'link';
|
||||
|
||||
/**
|
||||
* Assistant pas à pas d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* une étape par écran (lisible sur téléphone), chacune expliquée (pourquoi + exemple),
|
||||
* avec le coach 💡 sur les champs. Les réponses sont celles du MJ : rien n'est généré.
|
||||
* Le brouillon est gardé dans le navigateur pour pouvoir quitter et revenir.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-guided-wizard',
|
||||
imports: [FormsModule, RouterLink, TranslatePipe, LucideAngularModule, WritingCoachTriggerComponent],
|
||||
templateUrl: './guided-wizard.component.html',
|
||||
styleUrls: ['./guided-wizard.component.scss']
|
||||
})
|
||||
export class GuidedWizardComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly ArrowRight = ArrowRight;
|
||||
readonly Check = Check;
|
||||
readonly RotateCcw = RotateCcw;
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly translate = inject(TranslateService);
|
||||
private readonly campaignService = inject(CampaignService);
|
||||
private readonly skeletonService = inject(GuidedSkeletonService);
|
||||
private readonly confirmDialog = inject(ConfirmDialogService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
@ViewChild('stepTitle') stepTitle?: ElementRef<HTMLHeadingElement>;
|
||||
|
||||
campaignId = '';
|
||||
method: GuidedMethod | null = null;
|
||||
answers: GuidedAnswers = {};
|
||||
stepIndex = 0;
|
||||
/** Arcs linéaires de la campagne : seuls candidats pour y ranger l'aventure. */
|
||||
linearArcs: Arc[] = [];
|
||||
/** Le placement par défaut dépend des arcs : on attend leur chargement pour le choisir. */
|
||||
private arcsLoaded = false;
|
||||
submitting = false;
|
||||
error: string | null = null;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(pm => {
|
||||
this.campaignId = pm.get('campaignId') ?? '';
|
||||
this.method = findGuidedMethod(pm.get('method')) ?? null;
|
||||
if (!this.method) return;
|
||||
this.restoreDraft();
|
||||
this.arcsLoaded = false;
|
||||
this.campaignService.getArcs(this.campaignId).subscribe(arcs => {
|
||||
this.linearArcs = arcs
|
||||
.filter(a => (a.type ?? 'LINEAR') === 'LINEAR')
|
||||
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
||||
this.arcsLoaded = true;
|
||||
this.applyDefaults();
|
||||
});
|
||||
this.applyDefaults();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Navigation ------------------------------------------------------------------
|
||||
|
||||
get step(): GuidedStep | null {
|
||||
return this.method?.steps[this.stepIndex] ?? null;
|
||||
}
|
||||
|
||||
get total(): number {
|
||||
return this.method?.steps.length ?? 0;
|
||||
}
|
||||
|
||||
get progress(): number {
|
||||
return this.total ? Math.round(((this.stepIndex + 1) / this.total) * 100) : 0;
|
||||
}
|
||||
|
||||
get isLast(): boolean {
|
||||
return this.stepIndex === this.total - 1;
|
||||
}
|
||||
|
||||
next(): void {
|
||||
if (!this.canProceed() || this.isLast) return;
|
||||
this.goTo(this.stepIndex + 1);
|
||||
}
|
||||
|
||||
previous(): void {
|
||||
if (this.stepIndex > 0) this.goTo(this.stepIndex - 1);
|
||||
}
|
||||
|
||||
private goTo(index: number): void {
|
||||
this.stepIndex = index;
|
||||
this.error = null;
|
||||
this.applyDefaults();
|
||||
this.saveDraft();
|
||||
// Nouvelle étape = nouvel écran : on remonte et on place le focus sur son titre.
|
||||
setTimeout(() => {
|
||||
this.stepTitle?.nativeElement.focus();
|
||||
this.stepTitle?.nativeElement.scrollIntoView({ block: 'start' });
|
||||
});
|
||||
}
|
||||
|
||||
canProceed(): boolean {
|
||||
const step = this.step;
|
||||
if (!step) return false;
|
||||
if (step.kind === 'placement') {
|
||||
return this.answers[PLACEMENT_MODE] === 'existing'
|
||||
? !!this.answers[PLACEMENT_ARC]
|
||||
: !!answer(this.answers, PLACEMENT_NEW_ARC);
|
||||
}
|
||||
return (step.fields ?? []).every(f => !f.required || !!answer(this.answers, f.key));
|
||||
}
|
||||
|
||||
// --- Réponses ----------------------------------------------------------------------
|
||||
|
||||
/** Clé i18n de la méthode courante. */
|
||||
k(path: string): string {
|
||||
return `guided.${this.method?.i18nKey}.${path}`;
|
||||
}
|
||||
|
||||
fieldId(field: GuidedField): string {
|
||||
return `guided-${field.key.replace(/\./g, '-')}`;
|
||||
}
|
||||
|
||||
setAnswer(key: string, value: string): void {
|
||||
this.answers = { ...this.answers, [key]: value };
|
||||
this.saveDraft();
|
||||
}
|
||||
|
||||
/** Placement par défaut + valeurs pré-remplies + premier choix des champs `choice`. */
|
||||
private applyDefaults(): void {
|
||||
const a = { ...this.answers };
|
||||
if (this.arcsLoaded) this.applyPlacementDefaults(a);
|
||||
a[LINK_SCENES] ??= 'true';
|
||||
for (const field of this.step?.fields ?? []) {
|
||||
if (a[field.key] !== undefined) continue;
|
||||
if (field.kind === 'choice' && field.options?.length) a[field.key] = field.options[0];
|
||||
else if (field.prefilled) a[field.key] = this.translate.instant(this.k(`defaults.${field.key}`));
|
||||
}
|
||||
this.answers = a;
|
||||
}
|
||||
|
||||
/** Arc existant par défaut s'il y en a ; sinon (ou arc disparu) nouvel arc. */
|
||||
private applyPlacementDefaults(a: GuidedAnswers): void {
|
||||
a[PLACEMENT_MODE] ??= this.linearArcs.length > 0 ? 'existing' : 'new';
|
||||
if (a[PLACEMENT_MODE] === 'existing' && !this.linearArcs.some(arc => arc.id === a[PLACEMENT_ARC])) {
|
||||
a[PLACEMENT_ARC] = this.linearArcs[0]?.id ?? '';
|
||||
if (!a[PLACEMENT_ARC]) a[PLACEMENT_MODE] = 'new';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Récapitulatif & création --------------------------------------------------------
|
||||
|
||||
get draft(): GuidedDraft | null {
|
||||
return this.method ? this.method.toDraft(this.answers) : null;
|
||||
}
|
||||
|
||||
get placementLabel(): string {
|
||||
if (this.answers[PLACEMENT_MODE] === 'existing') {
|
||||
return this.linearArcs.find(a => a.id === this.answers[PLACEMENT_ARC])?.name ?? '';
|
||||
}
|
||||
return answer(this.answers, PLACEMENT_NEW_ARC) ?? '';
|
||||
}
|
||||
|
||||
get linkScenes(): boolean {
|
||||
return this.answers[LINK_SCENES] !== 'false';
|
||||
}
|
||||
|
||||
set linkScenes(value: boolean) {
|
||||
this.setAnswer(LINK_SCENES, String(value));
|
||||
}
|
||||
|
||||
create(): void {
|
||||
const draft = this.draft;
|
||||
if (!draft || this.submitting) return;
|
||||
const existing = this.answers[PLACEMENT_MODE] === 'existing';
|
||||
this.submitting = true;
|
||||
this.error = null;
|
||||
this.skeletonService.create(this.campaignId, {
|
||||
arcId: existing ? this.answers[PLACEMENT_ARC] : null,
|
||||
newArcName: existing ? null : answer(this.answers, PLACEMENT_NEW_ARC),
|
||||
chapter: draft.chapter,
|
||||
scenes: draft.scenes,
|
||||
linkSequentially: this.linkScenes,
|
||||
linkLabel: this.translate.instant('guided.linkLabel')
|
||||
}).subscribe({
|
||||
next: result => {
|
||||
this.clearDraft();
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'arcs', result.arcId, 'chapters', result.chapterId]);
|
||||
},
|
||||
error: () => {
|
||||
this.submitting = false;
|
||||
this.error = this.translate.instant('guided.createError');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async restart(): Promise<void> {
|
||||
const ok = await this.confirmDialog.confirm({
|
||||
title: this.translate.instant('guided.restartTitle'),
|
||||
message: this.translate.instant('guided.restartMessage'),
|
||||
confirmLabel: this.translate.instant('guided.restart')
|
||||
});
|
||||
if (!ok) return;
|
||||
this.clearDraft();
|
||||
this.answers = {};
|
||||
this.goTo(0);
|
||||
}
|
||||
|
||||
// --- Brouillon (confort par navigateur : jamais indispensable) -------------------------
|
||||
|
||||
private get storageKey(): string {
|
||||
return `loremind.guided.${this.campaignId}.${this.method?.id}`;
|
||||
}
|
||||
|
||||
private restoreDraft(): void {
|
||||
this.answers = {};
|
||||
this.stepIndex = 0;
|
||||
try {
|
||||
const raw = localStorage.getItem(this.storageKey);
|
||||
if (!raw) return;
|
||||
const saved = JSON.parse(raw) as { answers?: GuidedAnswers; step?: number };
|
||||
this.answers = saved.answers ?? {};
|
||||
this.stepIndex = Math.min(Math.max(saved.step ?? 0, 0), this.total - 1);
|
||||
} catch { /* brouillon illisible ou stockage bloqué : on repart de zéro */ }
|
||||
}
|
||||
|
||||
private saveDraft(): void {
|
||||
try {
|
||||
localStorage.setItem(this.storageKey, JSON.stringify({ answers: this.answers, step: this.stepIndex }));
|
||||
} catch { /* stockage indisponible : le brouillon n'est simplement pas gardé */ }
|
||||
}
|
||||
|
||||
private clearDraft(): void {
|
||||
try {
|
||||
localStorage.removeItem(this.storageKey);
|
||||
} catch { /* rien à nettoyer */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { SceneType } from '../../../services/campaign.model';
|
||||
import { GuidedSceneSpec } from '../../../services/guided-skeleton.model';
|
||||
import { GuidedAnswers, GuidedField, GuidedMethod, answer } from '../guided-method.model';
|
||||
|
||||
/**
|
||||
* « Donjon en 5 salles » (méthode popularisée par Johnn Four ; textes écrits pour
|
||||
* LoreMind). Une aventure courte en cinq temps : un gardien à l'entrée, une épreuve
|
||||
* qui ne se règle pas à l'épée, un revers, le climax, puis la récompense ou la
|
||||
* révélation. Le « donjon » peut être n'importe quel lieu : manoir, navire, forêt…
|
||||
*
|
||||
* Produit 1 chapitre (accroche, objectifs, enjeux) + 5 scènes typées dans le même lieu.
|
||||
*/
|
||||
|
||||
/** Champs communs à chaque salle : nom (pré-rempli), ce qui s'y passe, choix, secret du MJ. */
|
||||
function roomFields(room: number, extra: GuidedField[] = []): GuidedField[] {
|
||||
return [
|
||||
{ key: `room${room}.name`, kind: 'text', required: true, prefilled: true },
|
||||
...extra.filter(f => f.kind === 'choice'),
|
||||
{ key: `room${room}.description`, kind: 'textarea', coachTopic: 'scene.description' },
|
||||
...extra.filter(f => f.kind !== 'choice'),
|
||||
{ key: `room${room}.choices`, kind: 'textarea', coachTopic: 'scene.choices' },
|
||||
{ key: `room${room}.secret`, kind: 'textarea', coachTopic: 'scene.gmNotes' }
|
||||
];
|
||||
}
|
||||
|
||||
/** Nature de la salle (choix du MJ) → type de scène, pour que la relecture juge le rythme. */
|
||||
const NATURE_TO_TYPE: Record<string, SceneType> = {
|
||||
combat: 'ENCOUNTER',
|
||||
social: 'NPC',
|
||||
obstacle: 'LOCATION',
|
||||
puzzle: 'LOCATION',
|
||||
exploration: 'LOCATION'
|
||||
};
|
||||
|
||||
export const FIVE_ROOM_METHOD: GuidedMethod = {
|
||||
id: 'five-room',
|
||||
i18nKey: 'fiveRoom',
|
||||
steps: [
|
||||
{ id: 'placement', kind: 'placement' },
|
||||
{
|
||||
id: 'frame', kind: 'form', fields: [
|
||||
{ key: 'title', kind: 'text', required: true },
|
||||
{ key: 'location', kind: 'text', coachTopic: 'scene.setting' },
|
||||
{ key: 'hook', kind: 'textarea', coachTopic: 'chapter.synopsis' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'stakes', kind: 'form', fields: [
|
||||
{ key: 'objectives', kind: 'textarea', coachTopic: 'chapter.objectives' },
|
||||
{ key: 'stakes', kind: 'textarea', coachTopic: 'chapter.stakes' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'room1', kind: 'form', fields: roomFields(1, [
|
||||
{ key: 'room1.nature', kind: 'choice', options: ['combat', 'social', 'obstacle'] },
|
||||
{ key: 'room1.enemies', kind: 'text' }
|
||||
])
|
||||
},
|
||||
{
|
||||
id: 'room2', kind: 'form', fields: roomFields(2, [
|
||||
{ key: 'room2.nature', kind: 'choice', options: ['puzzle', 'social', 'exploration'] }
|
||||
])
|
||||
},
|
||||
{ id: 'room3', kind: 'form', fields: roomFields(3) },
|
||||
{
|
||||
id: 'room4', kind: 'form', fields: roomFields(4, [
|
||||
{ key: 'room4.enemies', kind: 'text', coachTopic: 'scene.combat' }
|
||||
])
|
||||
},
|
||||
{ id: 'room5', kind: 'form', fields: roomFields(5) },
|
||||
{ id: 'review', kind: 'review' }
|
||||
],
|
||||
|
||||
toDraft(answers: GuidedAnswers) {
|
||||
const location = answer(answers, 'location');
|
||||
const room = (n: number, type: SceneType): GuidedSceneSpec => ({
|
||||
name: answer(answers, `room${n}.name`) ?? '',
|
||||
description: answer(answers, `room${n}.description`),
|
||||
type,
|
||||
location,
|
||||
choicesConsequences: answer(answers, `room${n}.choices`),
|
||||
gmSecretNotes: answer(answers, `room${n}.secret`),
|
||||
enemies: answer(answers, `room${n}.enemies`)
|
||||
});
|
||||
return {
|
||||
chapter: {
|
||||
name: answer(answers, 'title') ?? '',
|
||||
description: answer(answers, 'hook'),
|
||||
playerObjectives: answer(answers, 'objectives'),
|
||||
narrativeStakes: answer(answers, 'stakes')
|
||||
},
|
||||
scenes: [
|
||||
room(1, NATURE_TO_TYPE[answers['room1.nature']] ?? 'ENCOUNTER'),
|
||||
room(2, NATURE_TO_TYPE[answers['room2.nature']] ?? 'LOCATION'),
|
||||
room(3, 'EVENT'),
|
||||
room(4, 'ENCOUNTER'),
|
||||
room(5, 'REVELATION')
|
||||
]
|
||||
};
|
||||
}
|
||||
};
|
||||
+8
-1
@@ -12,7 +12,14 @@
|
||||
h1 { margin: 0 0 0.2rem; font-size: 1.6rem; }
|
||||
}
|
||||
|
||||
.header-info { flex: 1; }
|
||||
.header-info { flex: 1; min-width: 0; }
|
||||
|
||||
// Téléphone : Retour et Supprimer sur la 1re ligne, titre + description en
|
||||
// pleine largeur dessous (sinon le titre tombe à un mot par ligne).
|
||||
@media (max-width: 767.98px) {
|
||||
.page-header .header-actions { margin-left: auto; flex: 0 0 auto; }
|
||||
.header-info { order: 1; flex-basis: 100%; }
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 0;
|
||||
|
||||
@@ -30,6 +30,9 @@
|
||||
est dans des sections repliables avec pastille « rempli ». -->
|
||||
<p class="optional-hint">{{ 'sceneEdit.optionalHint' | translate }}</p>
|
||||
|
||||
<!-- Mentor d'écriture (M2) : conseils de relecture qui concernent cette entité. -->
|
||||
<app-writing-review-hints [campaignId]="campaignId" entityType="SCENE" [entityId]="sceneId"></app-writing-review-hints>
|
||||
|
||||
<!-- Co-création (Pilier A) : le co-MJ propose, l'utilisateur valide champ par champ.
|
||||
Les champs retenus remplissent le formulaire ; rien n'est enregistré avant la sauvegarde. -->
|
||||
<app-entity-assist-panel
|
||||
@@ -49,7 +52,10 @@
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-description">{{ 'sceneEdit.descriptionLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.description"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="scene-edit-description"
|
||||
formControlName="description"
|
||||
@@ -65,7 +71,10 @@
|
||||
|
||||
<!-- Type narratif du nœud (Niveau 2 — graphe de nœuds typés) -->
|
||||
<div class="field">
|
||||
<label for="scene-edit-type">{{ 'sceneEdit.nodeTypeLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-type">{{ 'sceneEdit.nodeTypeLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.nodeType"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<select id="scene-edit-type" formControlName="type">
|
||||
@for (opt of sceneTypeOptions; track opt) {
|
||||
<option [value]="opt">{{ 'sceneType.' + opt | translate }}</option>
|
||||
@@ -181,7 +190,10 @@
|
||||
<app-expandable-section [title]="'sceneEdit.contextSectionTitle' | translate" icon="📍" [initiallyOpen]="true" [filled]="contextFilled">
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-location">{{ 'sceneEdit.locationLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.setting"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<input id="scene-edit-location" type="text" formControlName="location" [placeholder]="'sceneEdit.locationPlaceholder' | translate" />
|
||||
</div>
|
||||
<div class="field">
|
||||
@@ -190,7 +202,10 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
|
||||
<div class="field-label-row">
|
||||
<label for="scene-edit-atmosphere">{{ 'sceneEdit.atmosphereLabel' | translate }}</label>
|
||||
<app-writing-coach-trigger topic="scene.atmosphere"></app-writing-coach-trigger>
|
||||
</div>
|
||||
<textarea
|
||||
id="scene-edit-atmosphere"
|
||||
formControlName="atmosphere"
|
||||
@@ -201,7 +216,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Narration pour les joueurs -->
|
||||
<app-expandable-section [title]="'sceneEdit.narrationSectionTitle' | translate" icon="📖" [filled]="narrationFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.narrationSectionTitle' | translate" coachTopic="scene.narration" icon="📖" [initiallyOpen]="focusSection === 'narration'" [filled]="narrationFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="playerNarration"
|
||||
@@ -213,7 +228,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Notes et secrets du MJ (privé) -->
|
||||
<app-expandable-section [title]="'sceneEdit.gmNotesSectionTitle' | translate" icon="🔒" variant="private" [filled]="gmNotesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.gmNotesSectionTitle' | translate" coachTopic="scene.gmNotes" icon="🔒" variant="private" [filled]="gmNotesFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="gmSecretNotes"
|
||||
@@ -225,7 +240,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Choix et conséquences -->
|
||||
<app-expandable-section [title]="'sceneEdit.choicesSectionTitle' | translate" icon="🔀" [filled]="choicesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.choicesSectionTitle' | translate" coachTopic="scene.choices" icon="🔀" [initiallyOpen]="focusSection === 'choices'" [filled]="choicesFilled">
|
||||
<div class="field">
|
||||
<textarea
|
||||
formControlName="choicesConsequences"
|
||||
@@ -236,7 +251,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Branches narratives (graphe intra-chapitre) -->
|
||||
<app-expandable-section [title]="'sceneEdit.branchesSectionTitle' | translate" icon="🌿" [initiallyOpen]="focusSection === 'branches'" [filled]="branchesFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.branchesSectionTitle' | translate" coachTopic="scene.branches" icon="🌿" [initiallyOpen]="focusSection === 'branches'" [filled]="branchesFilled">
|
||||
@if (siblingScenes.length === 0) {
|
||||
<div class="branches-hint">
|
||||
<small class="field-hint">
|
||||
@@ -307,7 +322,7 @@
|
||||
</app-expandable-section>
|
||||
|
||||
<!-- Section : Combat ou rencontre -->
|
||||
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" icon="⚔️" [initiallyOpen]="focusSection === 'combat'" [filled]="combatFilled">
|
||||
<app-expandable-section [title]="'sceneEdit.combatSectionTitle' | translate" coachTopic="scene.combat" icon="⚔️" [initiallyOpen]="focusSection === 'combat'" [filled]="combatFilled">
|
||||
<div class="field">
|
||||
<label for="scene-edit-combat-difficulty">{{ 'sceneEdit.combatDifficultyLabel' | translate }}</label>
|
||||
<input id="scene-edit-combat-difficulty" type="text" formControlName="combatDifficulty" [placeholder]="'sceneEdit.combatDifficultyPlaceholder' | translate" />
|
||||
|
||||
@@ -31,6 +31,8 @@ import { FieldProposal } from '../../../services/entity-assist.model';
|
||||
import { FileDropDirective } from '../../../shared/file-drop.directive';
|
||||
import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||
import { WritingReviewHintsComponent } from '../../../shared/writing-review/writing-review-hints.component';
|
||||
|
||||
/**
|
||||
* État d'édition d'UNE battlemap de la scène (une carte par variante : Jour, Nuit,
|
||||
@@ -63,7 +65,7 @@ interface BattlemapEdit {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-scene-edit',
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, ExpandableSectionComponent, LoreLinkPickerComponent, EnemyLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent, RoomsEditorComponent, EntityAssistPanelComponent, FileDropDirective, TranslatePipe, WritingCoachTriggerComponent, WritingReviewHintsComponent],
|
||||
templateUrl: './scene-edit.component.html',
|
||||
styleUrls: ['./scene-edit.component.scss']
|
||||
})
|
||||
@@ -95,7 +97,7 @@ export class SceneEditComponent implements OnInit {
|
||||
scene: Scene | null = null;
|
||||
|
||||
/**
|
||||
* Section à déplier d'office (query param `?focus=combat|branches|rooms`) — posé par
|
||||
* Section à déplier d'office (query param `?focus=combat|branches|rooms|narration|choices`) — posé par
|
||||
* le bouton « Corriger » du guidage pour atterrir directement sur l'outil fautif.
|
||||
*/
|
||||
focusSection: string | null = null;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { WritingRemark } from '../services/writing-review.model';
|
||||
import { GapAction } from './gap-action.helper';
|
||||
|
||||
/**
|
||||
* Lien « Voir » d'une remarque de relecture : ouvre l'éditeur concerné avec la
|
||||
* section en cause dépliée (`?focus=…`), comme le « Corriger » du readiness.
|
||||
*/
|
||||
export function remarkAction(remark: WritingRemark, campaignId: string): GapAction {
|
||||
const base = ['/campaigns', campaignId];
|
||||
const focus = FOCUS_BY_RULE[remark.ruleId];
|
||||
const queryParams = focus ? { focus } : undefined;
|
||||
switch (remark.entityType) {
|
||||
case 'SCENE':
|
||||
return {
|
||||
link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.chapterId ?? '', 'scenes', remark.entityId, 'edit'],
|
||||
queryParams
|
||||
};
|
||||
case 'CHAPTER':
|
||||
// Couloir / rythme : c'est l'enchaînement des scènes qu'il faut voir (vue du chapitre).
|
||||
if (!focus) return { link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.entityId] };
|
||||
return { link: [...base, 'arcs', remark.arcId ?? '', 'chapters', remark.entityId, 'edit'], queryParams };
|
||||
case 'ARC':
|
||||
return { link: [...base, 'arcs', remark.entityId, 'edit'], queryParams };
|
||||
default:
|
||||
return { link: base };
|
||||
}
|
||||
}
|
||||
|
||||
/** Section de l'éditeur à déplier selon la règle (clé = ruleId complet). */
|
||||
const FOCUS_BY_RULE: Record<string, string> = {
|
||||
'WRITE-002-FAKE-CHOICE': 'branches',
|
||||
'WRITE-003-SINGLE-CLUE': 'branches',
|
||||
'WRITE-005-NO-STAKES': 'stakes',
|
||||
'WRITE-006-LONG-NARRATION': 'narration',
|
||||
'WRITE-007-NARRATION-DECIDES': 'narration',
|
||||
'WRITE-008-COMBAT-NO-PURPOSE': 'combat',
|
||||
'WRITE-009-SINGLE-ENDING': 'choices'
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
import { REMOTE_PAIRING_REQUIRED } from '../services/remote-access.service';
|
||||
|
||||
/**
|
||||
* Accès distant (tablette sur le réseau local) : quand le Core répond
|
||||
* `401 remote_pairing_required`, l'appareil n'est pas (ou plus) appairé — on bascule
|
||||
* sur l'écran d'appairage en retenant la page demandée. Inerte sur le PC et en Docker,
|
||||
* où ce code d'erreur n'existe pas.
|
||||
*/
|
||||
export const remotePairingInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const router = inject(Router);
|
||||
return next(req).pipe(
|
||||
catchError((err) => {
|
||||
if (err instanceof HttpErrorResponse && err.status === 401 && err.error?.error === REMOTE_PAIRING_REQUIRED
|
||||
&& !router.url.startsWith('/pair')) {
|
||||
router.navigate(['/pair'], { queryParams: { returnUrl: router.url } });
|
||||
}
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
};
|
||||
@@ -287,3 +287,8 @@
|
||||
}
|
||||
.canvas { width: 100%; }
|
||||
}
|
||||
|
||||
// Écrans sans survol (tactile) : poignée de redimensionnement pleinement visible.
|
||||
@media (hover: none) {
|
||||
.rh-se::after { opacity: 1; }
|
||||
}
|
||||
|
||||
@@ -46,11 +46,16 @@
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid #1f2937;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1.5rem;
|
||||
gap: 1rem 1.5rem;
|
||||
|
||||
.header-texts { flex: 1; min-width: 0; }
|
||||
// Téléphone : titre + actions empilés prendraient trop de hauteur en sticky.
|
||||
@media (max-width: 767.98px) { position: static; }
|
||||
|
||||
// ~280 px réservés au titre : sinon les actions passent dessous.
|
||||
.header-texts { flex: 1 1 280px; min-width: 0; }
|
||||
|
||||
h1 {
|
||||
display: inline-flex;
|
||||
@@ -60,6 +65,7 @@
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
margin-bottom: 0.5rem;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
.title-icon { color: #6c63ff; }
|
||||
}
|
||||
@@ -71,8 +77,9 @@
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,18 +24,24 @@
|
||||
padding: 1rem 0;
|
||||
border-bottom: 1px solid #1f2937;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1.5rem;
|
||||
gap: 1rem 1.5rem;
|
||||
|
||||
// Téléphone : titre + actions empilés prendraient trop de hauteur en sticky.
|
||||
@media (max-width: 767.98px) { position: static; }
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
.header-texts { flex: 1; min-width: 0; }
|
||||
// ~280 px réservés au titre : sinon les actions passent dessous.
|
||||
.header-texts { flex: 1 1 280px; min-width: 0; }
|
||||
|
||||
h1 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
margin-bottom: 0.5rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.description {
|
||||
@@ -46,8 +52,9 @@
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// Variante mode édition : input / textarea en colonne.
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
text-align: center;
|
||||
margin-bottom: 3rem;
|
||||
|
||||
@media (max-width: 767.98px) { margin-bottom: 1.5rem; }
|
||||
|
||||
.hero-icon { display: block; margin-bottom: 1rem; color: #6c63ff; }
|
||||
|
||||
h1 { font-size: 2rem; font-weight: 700; color: white; margin-bottom: 0.5rem; }
|
||||
@@ -19,7 +21,9 @@
|
||||
|
||||
.lore-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
// 3 colonnes sur desktop (max-width 900px), moins dès que la carte passerait
|
||||
// sous 240 px : 2 sur tablette portrait, 1 sur téléphone.
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr));
|
||||
gap: 1.5rem;
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<div class="pair-screen">
|
||||
<main class="pair-card">
|
||||
<div class="pair-icon" aria-hidden="true">
|
||||
<lucide-icon [img]="Tablet" [size]="28"></lucide-icon>
|
||||
</div>
|
||||
|
||||
@if (onHost) {
|
||||
<h1>{{ 'remoteAccess.pair.onHostTitle' | translate }}</h1>
|
||||
<p class="pair-text">{{ 'remoteAccess.pair.onHostText' | translate }}</p>
|
||||
<a class="btn-primary pair-link" [routerLink]="['/settings']" [queryParams]="{ section: 'remote-access' }">
|
||||
{{ 'remoteAccess.pair.onHostLink' | translate }}
|
||||
</a>
|
||||
} @else {
|
||||
<h1>{{ 'remoteAccess.pair.title' | translate }}</h1>
|
||||
<p class="pair-text">{{ 'remoteAccess.pair.text' | translate }}</p>
|
||||
|
||||
<form class="pair-form" (ngSubmit)="submit()">
|
||||
<div class="field">
|
||||
<label for="pair-code">{{ 'remoteAccess.pair.codeLabel' | translate }}</label>
|
||||
<!-- Pas de ngModel : on réécrit le champ à chaque frappe pour n'y laisser
|
||||
que des chiffres (ngModel ne rafraîchit pas la vue si la valeur nettoyée ne change pas).
|
||||
Pas de maxlength : il couperait « 123 456 » collé AVANT le nettoyage. -->
|
||||
<input id="pair-code" name="code" class="code-input"
|
||||
inputmode="numeric" autocomplete="one-time-code"
|
||||
[value]="code" (input)="onCodeInput($event)"
|
||||
placeholder="000000" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="pair-name">{{ 'remoteAccess.pair.nameLabel' | translate }}</label>
|
||||
<input id="pair-name" name="deviceName" maxlength="100" [(ngModel)]="deviceName" />
|
||||
<p class="field-hint">{{ 'remoteAccess.pair.nameHint' | translate }}</p>
|
||||
</div>
|
||||
|
||||
@if (error) {
|
||||
<p class="pair-error" role="alert">{{ error }}</p>
|
||||
}
|
||||
|
||||
<button type="submit" class="btn-primary pair-submit" [disabled]="!canSubmit">
|
||||
<lucide-icon [img]="Check" [size]="16"></lucide-icon>
|
||||
{{ (submitting ? 'remoteAccess.pair.submitting' : 'remoteAccess.pair.submit') | translate }}
|
||||
</button>
|
||||
</form>
|
||||
}
|
||||
</main>
|
||||
</div>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user