From c2947cfef8a3b4fef107042d452f9224c6e0a04a Mon Sep 17 00:00:00 2001 From: "IETM_FIXE\\ietm6" Date: Sat, 17 Oct 2026 14:00:32 +0200 Subject: [PATCH] =?UTF-8?q?S=C3=A9ances=20accessibles=20en=20un=20clic=20+?= =?UTF-8?q?=20r=C3=A8gles=20du=20syst=C3=A8me=20sous=20la=20main=20en=20s?= =?UTF-8?q?=C3=A9ance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Raccourci « Séance en cours » dans le menu principal : visible dès qu'une séance tourne (liste dépliable s'il y en a plusieurs, la plus récente en tête), rafraîchi à la navigation et au démarrage/fin d'une séance. - Hub campagne : bloc « Jouer » sous l'en-tête — reprendre la séance en cours, sinon démarrer une séance sur la partie la plus récente (menu pour en choisir une autre), ou créer une partie s'il n'y en a aucune. - Arbre de campagne : section « Jeu > Parties » avant la narration. - Onglet « Règles » en séance : sommaire des sections, sections repliables, recherche instantanée hors ligne (insensible aux accents, à la casse et aux ligatures, ne garde et ne surligne que les lignes concernées), sections épinglables (mémorisées par système), « Demander à l'IA » qui bascule sur l'onglet IA avec la question préremplie ; liens utiles si la campagne n'a pas de système ou si le système n'a pas de règles. - Core : GET /api/sessions?active=true (séances en cours sans tout l'historique) ; l'arbre /campaigns/{id}/tree inclut les parties. Vérifié : core test-compile + tests, web build + vitest (recherche dans les règles, bloc « Jouer »), lint sans nouvelle erreur, testé desktop et 375 px. À redéployer : core (aucune migration) + web. --- .../playcontext/SessionService.java | 5 + .../playcontext/ports/SessionRepository.java | 3 + .../persistence/jpa/SessionJpaRepository.java | 2 + .../postgres/PostgresSessionRepository.java | 7 + .../controller/CampaignTreeController.java | 16 +- .../web/controller/SessionController.java | 20 +- .../CampaignTreeControllerTest.java | 6 + .../web/controller/SessionControllerTest.java | 20 + .../campaigns/campaign-tree.helper.spec.ts | 23 ++ web/src/app/campaigns/campaign-tree.helper.ts | 33 +- .../campaign-detail.component.html | 8 + .../campaign-detail.component.ts | 23 +- .../campaign-play-block.component.html | 54 +++ .../campaign-play-block.component.scss | 117 ++++++ .../campaign-play-block.component.ts | 80 ++++ .../play-target.util.spec.ts | 54 +++ .../campaign-play-block/play-target.util.ts | 45 +++ .../app/services/active-sessions.service.ts | 87 +++++ web/src/app/services/campaign.service.ts | 4 +- web/src/app/services/session.service.ts | 22 +- .../active-session-shortcut.component.html | 41 ++ .../active-session-shortcut.component.scss | 113 ++++++ .../active-session-shortcut.component.ts | 74 ++++ .../session-ai-chat-panel.component.html | 2 +- .../session-ai-chat-panel.component.ts | 13 + .../session-reference-panel.component.html | 16 + .../session-reference-panel.component.scss | 5 +- .../session-reference-panel.component.ts | 17 +- .../rules-reference.util.spec.ts | 195 ++++++++++ .../rules-reference.util.ts | 308 +++++++++++++++ .../session-rules-panel.component.html | 136 +++++++ .../session-rules-panel.component.scss | 358 ++++++++++++++++++ .../session-rules-panel.component.ts | 249 ++++++++++++ web/src/app/sidebar/sidebar.component.html | 3 + web/src/app/sidebar/sidebar.component.ts | 3 +- web/src/assets/i18n/en.json | 47 ++- web/src/assets/i18n/fr.json | 47 ++- .../assets/i18n/fragments/play-access.en.json | 49 +++ .../assets/i18n/fragments/play-access.fr.json | 49 +++ 39 files changed, 2322 insertions(+), 32 deletions(-) create mode 100644 web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.html create mode 100644 web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.scss create mode 100644 web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.ts create mode 100644 web/src/app/campaigns/campaign/campaign-play-block/play-target.util.spec.ts create mode 100644 web/src/app/campaigns/campaign/campaign-play-block/play-target.util.ts create mode 100644 web/src/app/services/active-sessions.service.ts create mode 100644 web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.html create mode 100644 web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.scss create mode 100644 web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.ts create mode 100644 web/src/app/sessions/session-rules-panel/rules-reference.util.spec.ts create mode 100644 web/src/app/sessions/session-rules-panel/rules-reference.util.ts create mode 100644 web/src/app/sessions/session-rules-panel/session-rules-panel.component.html create mode 100644 web/src/app/sessions/session-rules-panel/session-rules-panel.component.scss create mode 100644 web/src/app/sessions/session-rules-panel/session-rules-panel.component.ts create mode 100644 web/src/assets/i18n/fragments/play-access.en.json create mode 100644 web/src/assets/i18n/fragments/play-access.fr.json diff --git a/core/src/main/java/com/loremind/application/playcontext/SessionService.java b/core/src/main/java/com/loremind/application/playcontext/SessionService.java index f31c1f5..a5d60c7 100644 --- a/core/src/main/java/com/loremind/application/playcontext/SessionService.java +++ b/core/src/main/java/com/loremind/application/playcontext/SessionService.java @@ -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 getAllActive() { + return sessionRepository.findAllActive(); + } + public Optional getActiveByPlaythrough(String playthroughId) { return sessionRepository.findActiveByPlaythroughId(playthroughId); } diff --git a/core/src/main/java/com/loremind/domain/playcontext/ports/SessionRepository.java b/core/src/main/java/com/loremind/domain/playcontext/ports/SessionRepository.java index 6eb6a90..18bc8d8 100644 --- a/core/src/main/java/com/loremind/domain/playcontext/ports/SessionRepository.java +++ b/core/src/main/java/com/loremind/domain/playcontext/ports/SessionRepository.java @@ -21,6 +21,9 @@ public interface SessionRepository { /** Retourne UNE session active dans l'app (sémantique « legacy » — multi-actives possibles). */ Optional findActive(); + /** Toutes les sessions en cours (toutes Parties confondues), la plus récente d'abord. */ + List findAllActive(); + /** Retourne la session active du Playthrough donné, s'il y en a une. */ Optional findActiveByPlaythroughId(String playthroughId); diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SessionJpaRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SessionJpaRepository.java index 1111ff2..1f4464f 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SessionJpaRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/jpa/SessionJpaRepository.java @@ -17,5 +17,7 @@ public interface SessionJpaRepository extends JpaRepository findFirstByEndedAtIsNull(); + List findByEndedAtIsNullOrderByStartedAtDesc(); + Optional findFirstByPlaythroughIdAndEndedAtIsNull(Long playthroughId); } diff --git a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSessionRepository.java b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSessionRepository.java index ea1e3a1..56a3940 100644 --- a/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSessionRepository.java +++ b/core/src/main/java/com/loremind/infrastructure/persistence/postgres/PostgresSessionRepository.java @@ -52,6 +52,13 @@ public class PostgresSessionRepository implements SessionRepository { return jpaRepository.findFirstByEndedAtIsNull().map(this::toDomain); } + @Override + public List findAllActive() { + return jpaRepository.findByEndedAtIsNullOrderByStartedAtDesc().stream() + .map(this::toDomain) + .toList(); + } + @Override public Optional findActiveByPlaythroughId(String playthroughId) { return jpaRepository.findFirstByPlaythroughIdAndEndedAtIsNull(Long.parseLong(playthroughId)) diff --git a/core/src/main/java/com/loremind/infrastructure/web/controller/CampaignTreeController.java b/core/src/main/java/com/loremind/infrastructure/web/controller/CampaignTreeController.java index 8d6dd6d..3a3cd5a 100644 --- a/core/src/main/java/com/loremind/infrastructure/web/controller/CampaignTreeController.java +++ b/core/src/main/java/com/loremind/infrastructure/web/controller/CampaignTreeController.java @@ -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. * *

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 randomTables, List enemies, List quests, + List 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))); } } diff --git a/core/src/main/java/com/loremind/infrastructure/web/controller/SessionController.java b/core/src/main/java/com/loremind/infrastructure/web/controller/SessionController.java index 40a8a22..94454d8 100644 --- a/core/src/main/java/com/loremind/infrastructure/web/controller/SessionController.java +++ b/core/src/main/java/com/loremind/infrastructure/web/controller/SessionController.java @@ -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> getSessions(@RequestParam(value = "playthroughId", required = false) String playthroughId) { - List sessions = (playthroughId == null || playthroughId.isBlank()) - ? sessionService.getAll() - : sessionService.getByPlaythroughId(playthroughId); + public ResponseEntity> getSessions( + @RequestParam(value = "playthroughId", required = false) String playthroughId, + @RequestParam(value = "active", defaultValue = "false") boolean active) { + List sessions; + if (active) { + sessions = sessionService.getAllActive(); + } else if (playthroughId == null || playthroughId.isBlank()) { + sessions = sessionService.getAll(); + } else { + sessions = sessionService.getByPlaythroughId(playthroughId); + } List dtos = sessions.stream() .map(sessionMapper::toDTO) .toList(); diff --git a/core/src/test/java/com/loremind/infrastructure/web/controller/CampaignTreeControllerTest.java b/core/src/test/java/com/loremind/infrastructure/web/controller/CampaignTreeControllerTest.java index 0b8f0aa..ea02468 100644 --- a/core/src/test/java/com/loremind/infrastructure/web/controller/CampaignTreeControllerTest.java +++ b/core/src/test/java/com/loremind/infrastructure/web/controller/CampaignTreeControllerTest.java @@ -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()); } diff --git a/core/src/test/java/com/loremind/infrastructure/web/controller/SessionControllerTest.java b/core/src/test/java/com/loremind/infrastructure/web/controller/SessionControllerTest.java index 0406296..d31a7c7 100644 --- a/core/src/test/java/com/loremind/infrastructure/web/controller/SessionControllerTest.java +++ b/core/src/test/java/com/loremind/infrastructure/web/controller/SessionControllerTest.java @@ -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(); diff --git a/web/src/app/campaigns/campaign-tree.helper.spec.ts b/web/src/app/campaigns/campaign-tree.helper.spec.ts index 77b3004..4d7f83d 100644 --- a/web/src/app/campaigns/campaign-tree.helper.spec.ts +++ b/web/src/app/campaigns/campaign-tree.helper.spec.ts @@ -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 }, diff --git a/web/src/app/campaigns/campaign-tree.helper.ts b/web/src/app/campaigns/campaign-tree.helper.ts index 3ff8a04..0317369 100644 --- a/web/src/app/campaigns/campaign-tree.helper.ts +++ b/web/src/app/campaigns/campaign-tree.helper.ts @@ -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 + ]; } /** diff --git a/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.html b/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.html index c1300e9..7cd0f4b 100644 --- a/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.html +++ b/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.html @@ -59,6 +59,14 @@ } + + @if (!editing && campaign.id) { + + + } @if (!editing && campaign.id) { diff --git a/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts b/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts index 006b529..53d781e 100644 --- a/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts +++ b/web/src/app/campaigns/campaign/campaign-detail/campaign-detail.component.ts @@ -32,11 +32,12 @@ 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 { 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, CampaignPlayBlockComponent, FoundryExportDialogComponent], templateUrl: './campaign-detail.component.html', styleUrls: ['./campaign-detail.component.scss'] }) @@ -94,14 +95,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 +207,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 }); } /** diff --git a/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.html b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.html new file mode 100644 index 0000000..05428b6 --- /dev/null +++ b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.html @@ -0,0 +1,54 @@ +

+
+ +

{{ 'playAccess.block.title' | translate }}

+
+ + @if (target.kind === 'resume') { +
    + @for (r of target.sessions; track r.session.id) { +
  • + +
    + {{ 'playAccess.block.running' | translate }} + {{ r.session.name }} · {{ r.playthrough.name }} +
    + +
  • + } +
+ } @else if (target.kind === 'start') { +
+
+ @if (target.playthroughs.length > 1) { + + + } @else { + {{ 'playAccess.block.nextSession' | translate }} + {{ target.playthroughs[0].name }} + } +
+ +
+ } @else { +
+
+ {{ 'playAccess.block.noPlaythrough' | translate }} +
+ +
+ } +
diff --git a/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.scss b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.scss new file mode 100644 index 0000000..2cfba4c --- /dev/null +++ b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.scss @@ -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; } +} diff --git a/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.ts b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.ts new file mode 100644 index 0000000..463e329 --- /dev/null +++ b/web/src/app/campaigns/campaign/campaign-play-block/campaign-play-block.component.ts @@ -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(); + + 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; } + }); + } +} diff --git a/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.spec.ts b/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.spec.ts new file mode 100644 index 0000000..60b0c98 --- /dev/null +++ b/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.spec.ts @@ -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'); + } + }); +}); diff --git a/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.ts b/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.ts new file mode 100644 index 0000000..aa4be60 --- /dev/null +++ b/web/src/app/campaigns/campaign/campaign-play-block/play-target.util.ts @@ -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! }; +} diff --git a/web/src/app/services/active-sessions.service.ts b/web/src/app/services/active-sessions.service.ts new file mode 100644 index 0000000..5424c31 --- /dev/null +++ b/web/src/app/services/active-sessions.service.ts @@ -0,0 +1,87 @@ +import { Injectable } from '@angular/core'; +import { NavigationEnd, Router } from '@angular/router'; +import { BehaviorSubject, Observable, forkJoin, merge, of } from 'rxjs'; +import { catchError, filter, map, startWith, switchMap } from 'rxjs/operators'; +import { SessionService } from './session.service'; +import { PlaythroughService } from './playthrough.service'; +import { CampaignService } from './campaign.service'; +import { Session } from './session.model'; + +/** Séance en cours enrichie de quoi l'identifier (Partie + Campagne). */ +export interface ActiveSessionEntry { + session: Session; + playthroughName: string | null; + campaignId: string | null; + campaignName: string | null; +} + +interface PlaythroughLabel { + playthroughName: string | null; + campaignId: string | null; + campaignName: string | null; +} + +/** + * État partagé des séances en cours (toutes Parties confondues), la plus récente d'abord. + * + *

Alimente le raccourci « Séance en cours » du menu principal et le bloc « Jouer » + * du hub campagne : une séance ne doit plus se perdre au fond d'une page. Rafraîchi à + * chaque navigation et après chaque démarrage/fin/suppression ({@link SessionService.changed$}). + * Les libellés Partie/Campagne sont mis en cache (une séance active change rarement de Partie).

+ */ +@Injectable({ providedIn: 'root' }) +export class ActiveSessionsService { + private readonly subject = new BehaviorSubject([]); + readonly active$: Observable = this.subject.asObservable(); + + private readonly labels = new Map(); + + constructor( + router: Router, + private sessionService: SessionService, + private playthroughService: PlaythroughService, + private campaignService: CampaignService + ) { + merge( + router.events.pipe(filter(e => e instanceof NavigationEnd)), + this.sessionService.changed$ + ).pipe( + startWith(null), + // switchMap : une navigation rapide annule le fetch précédent (pas de réponse périmée). + switchMap(() => this.fetch()) + ).subscribe(list => this.subject.next(list)); + } + + /** Force un rafraîchissement (ex. après une action hors SessionService). */ + refresh(): void { + this.fetch().subscribe(list => this.subject.next(list)); + } + + private fetch(): Observable { + return this.sessionService.getActiveSessions().pipe( + // Back indisponible / ancienne version : on garde l'état connu plutôt que de faire clignoter. + catchError(() => of(null)), + switchMap(sessions => { + if (!sessions) return of(this.subject.value); + if (sessions.length === 0) return of([] as ActiveSessionEntry[]); + return forkJoin(sessions.map(s => this.labelOf(s.playthroughId).pipe( + map(label => ({ session: s, ...label })) + ))); + }) + ); + } + + private labelOf(playthroughId: string): Observable { + const cached = this.labels.get(playthroughId); + if (cached) return of(cached); + const unknown: PlaythroughLabel = { playthroughName: null, campaignId: null, campaignName: null }; + return this.playthroughService.getById(playthroughId).pipe( + switchMap(p => this.campaignService.getCampaignById(p.campaignId).pipe( + map(c => ({ playthroughName: p.name, campaignId: p.campaignId, campaignName: c.name })), + catchError(() => of({ ...unknown, playthroughName: p.name, campaignId: p.campaignId })) + )), + map(label => { this.labels.set(playthroughId, label); return label; }), + catchError(() => of(unknown)) + ); + } +} diff --git a/web/src/app/services/campaign.service.ts b/web/src/app/services/campaign.service.ts index a3ac598..417658a 100644 --- a/web/src/app/services/campaign.service.ts +++ b/web/src/app/services/campaign.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs'; -import { Campaign, CampaignCreate, Arc, ArcCreate, Chapter, ChapterCreate, Scene, SceneCreate, Quest } from './campaign.model'; +import { Campaign, CampaignCreate, Arc, ArcCreate, Chapter, ChapterCreate, Scene, SceneCreate, Quest, Playthrough } from './campaign.model'; import { CampaignReadinessAssessment } from './readiness.model'; import { Npc } from './npc.model'; import { RandomTable } from './random-table.model'; @@ -19,6 +19,8 @@ export interface CampaignTreeResponse { randomTables: RandomTable[]; enemies: Enemy[]; quests: Quest[]; + /** Parties (Playthroughs) de la campagne — nœud « Parties » de l'arbre. */ + playthroughs?: Playthrough[]; readiness: CampaignReadinessAssessment; } diff --git a/web/src/app/services/session.service.ts b/web/src/app/services/session.service.ts index dc86c31..0de4958 100644 --- a/web/src/app/services/session.service.ts +++ b/web/src/app/services/session.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; -import { Observable } from 'rxjs'; +import { Observable, Subject, tap } from 'rxjs'; import { Session } from './session.model'; /** @@ -13,11 +13,23 @@ import { Session } from './session.model'; export class SessionService { private apiUrl = '/api/sessions'; + /** + * Émet après chaque mutation qui change l'ensemble des séances en cours + * (démarrage, fin, renommage, suppression) — écouté par {@link ActiveSessionsService} + * pour rafraîchir le raccourci « Séance en cours » sans attendre une navigation. + */ + readonly changed$ = new Subject(); + constructor(private http: HttpClient) {} /** Lance une nouvelle session sur la Partie (Playthrough) donnée. */ startSession(playthroughId: string): Observable { - return this.http.post(this.apiUrl, { playthroughId }); + return this.http.post(this.apiUrl, { playthroughId }).pipe(tap(() => this.changed$.next())); + } + + /** Toutes les séances en cours (toutes Parties confondues), la plus récente d'abord. */ + getActiveSessions(): Observable { + return this.http.get(this.apiUrl, { params: new HttpParams().set('active', 'true') }); } /** @@ -49,15 +61,15 @@ export class SessionService { } endSession(id: string): Observable { - return this.http.post(`${this.apiUrl}/${id}/end`, {}); + return this.http.post(`${this.apiUrl}/${id}/end`, {}).pipe(tap(() => this.changed$.next())); } renameSession(id: string, name: string): Observable { - return this.http.patch(`${this.apiUrl}/${id}`, { name }); + return this.http.patch(`${this.apiUrl}/${id}`, { name }).pipe(tap(() => this.changed$.next())); } deleteSession(id: string): Observable { - return this.http.delete(`${this.apiUrl}/${id}`); + return this.http.delete(`${this.apiUrl}/${id}`).pipe(tap(() => this.changed$.next())); } /** Épingle (sceneId) ou dés-épingle (null) la scène courante — mode cockpit. */ diff --git a/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.html b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.html new file mode 100644 index 0000000..439f753 --- /dev/null +++ b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.html @@ -0,0 +1,41 @@ +@if (entries.length > 0) { +
+ + + @if (expanded && entries.length > 1) { +
    + @for (e of entries; track e.session.id) { +
  • + +
  • + } +
+ } +
+} diff --git a/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.scss b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.scss new file mode 100644 index 0000000..bf33853 --- /dev/null +++ b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.scss @@ -0,0 +1,113 @@ +:host { display: block; } + +.active-shortcut { + display: flex; + flex-direction: column; + gap: 0.25rem; + margin-top: 0.75rem; +} + +.shortcut-main { + display: flex; + align-items: center; + gap: 0.45rem; + width: 100%; + min-height: 44px; // cible tactile + padding: 0.45rem 0.5rem 0.45rem 0.6rem; + background: rgba(16, 185, 129, 0.1); + border: 1px solid rgba(16, 185, 129, 0.45); + border-radius: 8px; + color: #d1fae5; + cursor: pointer; + text-align: left; + transition: background 0.15s, border-color 0.15s; + + &:hover { background: rgba(16, 185, 129, 0.18); border-color: #10b981; } + &:focus-visible { outline: 2px solid #10b981; outline-offset: 2px; } + + &--current { background: rgba(16, 185, 129, 0.22); } +} + +.live-dot { + flex: 0 0 auto; + width: 8px; + height: 8px; + border-radius: 50%; + background: #10b981; + box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.6); + 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 6px 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; } +} + +.shortcut-texts { + display: flex; + flex-direction: column; + min-width: 0; + flex: 1; +} + +.shortcut-label { + font-size: 0.8rem; + font-weight: 600; + line-height: 1.25; + overflow-wrap: anywhere; // sidebar étroite : passe à la ligne plutôt que de tronquer +} + +.shortcut-sub { + font-size: 0.72rem; + color: #6ee7b7; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.shortcut-icon { flex: 0 0 auto; color: #6ee7b7; } + +.shortcut-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.2rem; +} + +.shortcut-item { + display: flex; + flex-direction: column; + gap: 0.1rem; + width: 100%; + min-height: 44px; + justify-content: center; + padding: 0.4rem 0.7rem; + background: #161628; + border: 1px solid #2a2a45; + border-radius: 6px; + color: #e5e7eb; + cursor: pointer; + text-align: left; + + &:hover { border-color: #10b981; } + &:focus-visible { outline: 2px solid #10b981; outline-offset: 2px; } + &--current { border-color: #10b981; background: rgba(16, 185, 129, 0.12); } +} + +.shortcut-item-name, +.shortcut-item-ctx { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} + +.shortcut-item-name { font-size: 0.8rem; font-weight: 500; } +.shortcut-item-ctx { font-size: 0.7rem; color: #9ca3af; } diff --git a/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.ts b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.ts new file mode 100644 index 0000000..18d2494 --- /dev/null +++ b/web/src/app/sessions/active-session-shortcut/active-session-shortcut.component.ts @@ -0,0 +1,74 @@ +import { Component, DestroyRef, OnInit } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { NavigationEnd, Router } from '@angular/router'; +import { filter } from 'rxjs/operators'; +import { TranslatePipe } from '@ngx-translate/core'; +import { LucideAngularModule, ChevronDown, ChevronUp } from 'lucide-angular'; +import { ActiveSessionEntry, ActiveSessionsService } from '../../services/active-sessions.service'; + +/** + * Raccourci « Séance en cours » du menu principal : visible dès qu'une séance tourne, + * un clic y ramène depuis n'importe quel écran. Plusieurs séances (plusieurs tables) : + * le bouton déplie la liste, la plus récente en tête. + * + *

Composant autonome (styles propres) pour pouvoir le réutiliser tel quel dans la + * barre haute mobile.

+ */ +@Component({ + selector: 'app-active-session-shortcut', + imports: [LucideAngularModule, TranslatePipe], + templateUrl: './active-session-shortcut.component.html', + styleUrls: ['./active-session-shortcut.component.scss'] +}) +export class ActiveSessionShortcutComponent implements OnInit { + readonly ChevronDown = ChevronDown; + readonly ChevronUp = ChevronUp; + + entries: ActiveSessionEntry[] = []; + expanded = false; + currentUrl = ''; + + constructor( + private activeSessions: ActiveSessionsService, + private router: Router, + private destroyRef: DestroyRef + ) {} + + ngOnInit(): void { + this.currentUrl = this.router.url; + this.router.events.pipe( + filter((e): e is NavigationEnd => e instanceof NavigationEnd), + takeUntilDestroyed(this.destroyRef) + ).subscribe(e => { + this.currentUrl = e.urlAfterRedirects; + this.expanded = false; + }); + this.activeSessions.active$.pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(list => { + this.entries = list; + if (list.length < 2) this.expanded = false; + }); + } + + /** Une seule séance : on y va ; plusieurs : on déplie la liste. */ + onMainClick(): void { + if (this.entries.length === 1) { + this.open(this.entries[0]); + } else { + this.expanded = !this.expanded; + } + } + + open(entry: ActiveSessionEntry): void { + this.router.navigate(['/sessions', entry.session.id]); + } + + isCurrent(entry: ActiveSessionEntry): boolean { + return this.currentUrl.split(/[?#]/)[0] === `/sessions/${entry.session.id}`; + } + + /** « Partie · Campagne » (ce qui est connu). */ + contextOf(entry: ActiveSessionEntry): string { + return [entry.playthroughName, entry.campaignName].filter(Boolean).join(' · '); + } +} diff --git a/web/src/app/sessions/session-ai-chat-panel/session-ai-chat-panel.component.html b/web/src/app/sessions/session-ai-chat-panel/session-ai-chat-panel.component.html index b261e0c..faf9942 100644 --- a/web/src/app/sessions/session-ai-chat-panel/session-ai-chat-panel.component.html +++ b/web/src/app/sessions/session-ai-chat-panel/session-ai-chat-panel.component.html @@ -42,7 +42,7 @@
-