diff --git a/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs b/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs index b999a0543..98251b91a 100644 --- a/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs +++ b/ErsatzTV.Application/MediaCollections/Commands/AddItemsToPlaylistHandler.cs @@ -84,14 +84,20 @@ public class AddItemsToPlaylistHandler : IRequestHandler collection); - private static Task> PlaylistMustExist( + private static async Task> PlaylistMustExist( TvContext dbContext, AddItemsToPlaylist request, - CancellationToken cancellationToken) => - dbContext.Playlists + CancellationToken cancellationToken) + { + Option maybePlaylist = await dbContext.Playlists .Include(c => c.Items) - .SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken) - .Map(o => o.ToValidation("Playlist does not exist.")); + .SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken); + + return maybePlaylist.ToValidation("Playlist does not exist.") + .Bind(playlist => playlist.IsSystem + ? BaseError.New("Cannot add items to system (generated) playlist") + : Success(playlist)); + } private Task> ValidateMovies(AddItemsToPlaylist request) => _movieRepository.AllMoviesExist(request.MovieIds) diff --git a/ErsatzTV.Core/Api/Search/SearchResultAllItemsResponseModel.cs b/ErsatzTV.Core/Api/Search/SearchResultAllItemsResponseModel.cs new file mode 100644 index 000000000..f94d0897d --- /dev/null +++ b/ErsatzTV.Core/Api/Search/SearchResultAllItemsResponseModel.cs @@ -0,0 +1,13 @@ +namespace ErsatzTV.Core.Api.Search; + +public record SearchResultAllItemsResponseModel( + List MovieIds, + List ShowIds, + List SeasonIds, + List EpisodeIds, + List ArtistIds, + List MusicVideoIds, + List OtherVideoIds, + List SongIds, + List ImageIds, + List RemoteStreamIds); diff --git a/ErsatzTV.Tests/Controllers/PlaylistControllerTests.cs b/ErsatzTV.Tests/Controllers/PlaylistControllerTests.cs index d75763304..07dc7a086 100644 --- a/ErsatzTV.Tests/Controllers/PlaylistControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/PlaylistControllerTests.cs @@ -15,6 +15,7 @@ using NSubstitute; using NUnit.Framework; using Shouldly; using static LanguageExt.Prelude; +using Unit = LanguageExt.Unit; namespace ErsatzTV.Tests.Controllers; @@ -44,6 +45,7 @@ public class PlaylistControllerTests ShouldHaveActionRoute(nameof(PlaylistController.Create), "POST", "/api/playlists"); ShouldHaveActionRoute(nameof(PlaylistController.Update), "PUT", "/api/playlists/{id:int}"); ShouldHaveActionRoute(nameof(PlaylistController.Delete), "DELETE", "/api/playlists/{id:int}"); + ShouldHaveActionRoute(nameof(PlaylistController.AddItems), "POST", "/api/playlists/{id:int}/items"); ShouldHaveActionRoute(nameof(PlaylistController.Preview), "POST", "/api/playlists/preview"); } @@ -445,6 +447,75 @@ public class PlaylistControllerTests result.ShouldBeOfType(); } + [Test] + public async Task AddItems_Should_Return_204_And_Map_Request() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.Some(new PlaylistViewModel(4, 1, "Kids", false))); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Right(Unit.Default)); + + IActionResult result = await _controller.AddItems( + 4, + new AddItemsToPlaylistRequest([1, 2], [3], [], [], [], [], [], [], [], []), + CancellationToken.None); + + result.ShouldBeOfType(); + await _mediator.Received(1).Send( + Arg.Is(c => + c.PlaylistId == 4 && + c.MovieIds.SequenceEqual(new List { 1, 2 }) && + c.ShowIds.SequenceEqual(new List { 3 })), + Arg.Any()); + } + + [Test] + public async Task AddItems_Should_Return_404_When_Playlist_Missing() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.None); + + IActionResult result = await _controller.AddItems( + 4, + new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []), + CancellationToken.None); + + result.ShouldBeOfType(); + await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + + [Test] + public async Task AddItems_Should_Return_422_On_System_Playlist() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.Some(new PlaylistViewModel(4, 1, "System", true))); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Left(BaseError.New("Cannot add items to system (generated) playlist"))); + + IActionResult result = await _controller.AddItems( + 4, + new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []), + CancellationToken.None); + + result.ShouldBeOfType(); + } + + [Test] + public async Task AddItems_Should_Return_422_On_Validation_Error() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Option.Some(new PlaylistViewModel(4, 1, "Kids", false))); + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(Left(BaseError.New("Movie does not exist"))); + + IActionResult result = await _controller.AddItems( + 4, + new AddItemsToPlaylistRequest([999], [], [], [], [], [], [], [], [], []), + CancellationToken.None); + + result.ShouldBeOfType(); + } + [Test] public async Task Preview_Should_Return_200_And_Format_Times() { diff --git a/ErsatzTV.Tests/Controllers/SearchControllerTests.cs b/ErsatzTV.Tests/Controllers/SearchControllerTests.cs index e7a7331ff..184fb88ed 100644 --- a/ErsatzTV.Tests/Controllers/SearchControllerTests.cs +++ b/ErsatzTV.Tests/Controllers/SearchControllerTests.cs @@ -75,6 +75,54 @@ public class SearchControllerTests ok.Value.ShouldBe(results); } + [Test] + public void Controller_Should_Expose_SearchAllItems_Route_With_Stable_Operation_Name() + { + MethodInfo action = typeof(SearchController).GetMethod(nameof(SearchController.SearchAllItems)) + ?? throw new AssertionException($"Missing action {nameof(SearchController.SearchAllItems)}"); + + var attribute = action.GetCustomAttributes().Single(); + attribute.Template.ShouldBe("/api/search/all-items"); + attribute.Name.ShouldBe("SearchAllItems"); + } + + [Test] + public async Task SearchAllItems_Should_Return_422_For_Empty_Query() + { + IActionResult result = await _controller.SearchAllItems(" ", CancellationToken.None); + + var unprocessable = result.ShouldBeOfType(); + unprocessable.StatusCode.ShouldBe(422); + await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + + [Test] + public async Task SearchAllItems_Should_Map_Id_Lists() + { + _mediator.Send(Arg.Any(), Arg.Any()) + .Returns(new SearchResultAllItemsViewModel( + [1, 2], + [3], + [], + [], + [], + [], + [], + [], + [], + [])); + + IActionResult result = await _controller.SearchAllItems("star", CancellationToken.None); + + var body = result.ShouldBeOfType().Value + .ShouldBeOfType(); + body.MovieIds.ShouldBe(new List { 1, 2 }); + body.ShowIds.ShouldBe(new List { 3 }); + await _mediator.Received(1).Send( + Arg.Is(q => q.Query == "star"), + Arg.Any()); + } + [Test] public async Task SearchCollections_Should_Map_To_Picker_Options() { diff --git a/ErsatzTV/Controllers/Api/PlaylistController.cs b/ErsatzTV/Controllers/Api/PlaylistController.cs index 8876105cb..85055617d 100644 --- a/ErsatzTV/Controllers/Api/PlaylistController.cs +++ b/ErsatzTV/Controllers/Api/PlaylistController.cs @@ -222,6 +222,31 @@ public class PlaylistController(IMediator mediator) : ControllerBase None: () => new NoContentResult()); } + [HttpPost("/api/playlists/{id:int}/items", Name = "AddItemsToPlaylist")] + [Tags("Playlists")] + [EndpointSummary("Add items to a playlist")] + [EndpointGroupName("general")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] + public async Task AddItems( + int id, + [Required] [FromBody] AddItemsToPlaylistRequest request, + CancellationToken cancellationToken) + { + Option maybePlaylist = await mediator.Send(new GetPlaylistById(id), cancellationToken); + if (maybePlaylist.IsNone) + { + return ApiResults.NotFoundProblem(); + } + + // System (generated) playlists must not have items added. The AddItemsToPlaylistHandler + // also enforces this (defense-in-depth for the Blazor path, which calls the same command + // from MultiSelectBase.AddItemsToPlaylist). + Either result = await mediator.Send(request.ToCommand(id), cancellationToken); + return result.ToDeletedResult(); + } + [HttpPost("/api/playlists/preview", Name = "PreviewPlaylist")] [Tags("Playlists")] [EndpointSummary("Preview the playout of a draft playlist")] diff --git a/ErsatzTV/Controllers/Api/Requests/AddItemsToPlaylistRequest.cs b/ErsatzTV/Controllers/Api/Requests/AddItemsToPlaylistRequest.cs new file mode 100644 index 000000000..d8d581f59 --- /dev/null +++ b/ErsatzTV/Controllers/Api/Requests/AddItemsToPlaylistRequest.cs @@ -0,0 +1,30 @@ +using ErsatzTV.Application.MediaCollections; + +namespace ErsatzTV.Controllers.Api.Requests; + +public record AddItemsToPlaylistRequest( + List MovieIds, + List ShowIds, + List SeasonIds, + List EpisodeIds, + List ArtistIds, + List MusicVideoIds, + List OtherVideoIds, + List SongIds, + List ImageIds, + List RemoteStreamIds) +{ + public AddItemsToPlaylist ToCommand(int playlistId) => + new( + playlistId, + MovieIds ?? [], + ShowIds ?? [], + SeasonIds ?? [], + EpisodeIds ?? [], + ArtistIds ?? [], + MusicVideoIds ?? [], + OtherVideoIds ?? [], + SongIds ?? [], + ImageIds ?? [], + RemoteStreamIds ?? []); +} diff --git a/ErsatzTV/Controllers/Api/SearchController.cs b/ErsatzTV/Controllers/Api/SearchController.cs index c32691453..b544522c7 100644 --- a/ErsatzTV/Controllers/Api/SearchController.cs +++ b/ErsatzTV/Controllers/Api/SearchController.cs @@ -39,6 +39,30 @@ public class SearchController(IMediator mediator) : ControllerBase return new OkObjectResult(result); } + [HttpGet("/api/search/all-items", Name = "SearchAllItems")] + [Tags("Search")] + [EndpointSummary("Search library items across all media kinds and return raw id lists")] + [EndpointDescription( + "Returns every matching item's id, grouped by media kind, with no paging. Used by the SPA's " + + "\"add all to collection/playlist\" flow to materialize ids before calling the add endpoints.")] + [EndpointGroupName("general")] + [ProducesResponseType(typeof(SearchResultAllItemsResponseModel), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)] + public async Task SearchAllItems( + [FromQuery] string query = "", + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(query)) + { + return BaseError.New("A non-empty query is required").ToErrorResult(); + } + + SearchResultAllItemsViewModel result = await mediator.Send( + new QuerySearchIndexAllItems(query), + cancellationToken); + return new OkObjectResult(Project(result)); + } + [HttpGet("/api/search/collections", Name = "SearchCollections")] [Tags("Search")] [EndpointSummary("Search collections by name")] @@ -134,4 +158,17 @@ public class SearchController(IMediator mediator) : ControllerBase cancellationToken); return results.Map(c => new SchedulingPickerOptionResponseModel(c.Id, c.Name)).ToList(); } + + private static SearchResultAllItemsResponseModel Project(SearchResultAllItemsViewModel vm) => + new( + vm.MovieIds, + vm.ShowIds, + vm.SeasonIds, + vm.EpisodeIds, + vm.ArtistIds, + vm.MusicVideoIds, + vm.OtherVideoIds, + vm.SongIds, + vm.ImageIds, + vm.RemoteStreamIds); } diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index cb5b2da7b..847e90c5a 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -6852,6 +6852,94 @@ } } } + }, + "post": { + "tags": [ + "Playlists" + ], + "summary": "Add items to a playlist", + "operationId": "AddItemsToPlaylist", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + } + ], + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/AddItemsToPlaylistRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddItemsToPlaylistRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/AddItemsToPlaylistRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/AddItemsToPlaylistRequest" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "422": { + "description": "Unprocessable Entity", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } } }, "/api/playlists/preview": { @@ -9838,6 +9926,68 @@ } } }, + "/api/search/all-items": { + "get": { + "tags": [ + "Search" + ], + "summary": "Search library items across all media kinds and return raw id lists", + "description": "Returns every matching item's id, grouped by media kind, with no paging. Used by the SPA's \"add all to collection/playlist\" flow to materialize ids before calling the add endpoints.", + "operationId": "SearchAllItems", + "parameters": [ + { + "name": "query", + "in": "query", + "schema": { + "type": "string", + "default": "" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/SearchResultAllItemsResponseModel" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SearchResultAllItemsResponseModel" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SearchResultAllItemsResponseModel" + } + } + } + }, + "422": { + "description": "Unprocessable Entity", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, "/api/search/collections": { "get": { "tags": [ @@ -13845,6 +13995,123 @@ } } }, + "AddItemsToPlaylistRequest": { + "required": [ + "movieIds", + "showIds", + "seasonIds", + "episodeIds", + "artistIds", + "musicVideoIds", + "otherVideoIds", + "songIds", + "imageIds", + "remoteStreamIds" + ], + "type": "object", + "properties": { + "movieIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "showIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "seasonIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "episodeIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "artistIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "musicVideoIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "otherVideoIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "songIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "imageIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "remoteStreamIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + } + } + }, "AddTraktListRequest": { "required": [ "url" @@ -20819,6 +21086,123 @@ } } }, + "SearchResultAllItemsResponseModel": { + "required": [ + "movieIds", + "showIds", + "seasonIds", + "episodeIds", + "artistIds", + "musicVideoIds", + "otherVideoIds", + "songIds", + "imageIds", + "remoteStreamIds" + ], + "type": "object", + "properties": { + "movieIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "showIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "seasonIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "episodeIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "artistIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "musicVideoIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "otherVideoIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "songIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "imageIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + }, + "remoteStreamIds": { + "type": [ + "null", + "array" + ], + "items": { + "type": "integer", + "format": "int32" + } + } + } + }, "SearchResultGroupResponseModel": { "required": [ "totalCount", diff --git a/docs/blazor-route-parity.md b/docs/blazor-route-parity.md index e09935ce6..bb617695a 100644 --- a/docs/blazor-route-parity.md +++ b/docs/blazor-route-parity.md @@ -64,9 +64,9 @@ redirect). > | Collections | PARITY-OK (custom-order endpoint + reorder UI, all-10-kind add picker, 2026-07-09) | — | > | Channel editor | GAPS (external logo URL, bare create, pickers) | #212 | > | Channels-numbers / Logs | PARITY-OK / minors | #213 | -> | Search | GAPS SEVERE (display-only, no mutations) | **#208** | +> | Search | PARITY-OK (card nav, per-card/multi-select add-to, add-all, save-as-smart-collection, 2026-07-10) | — | > | Media browse/detail (read paths + image browser) | PARITY-OK | — | -> | Media browse/detail (mutations, per-show scan, episode info/troubleshoot) | GAPS | **#209** | +> | Media browse/detail (mutations, per-show scan, episode info/troubleshoot) | PARITY-OK (shared Add-to layer + scan/info/troubleshoot wired, 2026-07-10) | — | > | Schedules editors | **disproven — moved to Section 3** | **#207** | > | Media sources | **disproven — moved to Section 3** | **#202** | > @@ -91,7 +91,7 @@ been added to the redirect map yet. | `/system/troubleshooting` | `Troubleshooting/Troubleshooting.razor` | `/app/troubleshooting` | | | `/system/troubleshooting/block-playout` | `Troubleshooting/BlockPlayoutTroubleshooting.razor` (+`BlockPlayoutHistory.razor`) | `/app/troubleshooting/blocks` | **covered by PR #182 / #145** | | `/system/troubleshooting/sequential-schedule` | `Troubleshooting/YamlValidator.razor` | `/app/troubleshooting/yaml` | **covered by PR #182 / #145** | -| `/system/troubleshooting/playback` | `Troubleshooting/PlaybackTroubleshooting.razor` | `/app/troubleshooting/playback` | **covered by #145** — no nav entry; entry points are the Channels table Troubleshoot action (`?channel={id}`) and the movie detail page (`?mediaItem={id}`) only for now — other media kinds (episodes, music videos, …) need a hand-built `?mediaItem={id}` URL | +| `/system/troubleshooting/playback` | `Troubleshooting/PlaybackTroubleshooting.razor` | `/app/troubleshooting/playback` | **covered by #145** — no nav entry; entry points are the Channels table Troubleshoot action (`?channel={id}`) the movie detail page, and per-episode Troubleshoot actions on season detail pages (`?mediaItem={id}`, #209) — remaining kinds (music videos, songs, …) still need a hand-built `?mediaItem={id}` URL | | `/blocks`, `/blocks/{Id:int}` | `Blocks.razor`, `BlockEditor.razor` | `/app/blocks`(`/{id}`) | allowSubPaths; #144 S1 | | `/templates`, `/templates/{Id:int}` | `Templates.razor`, `TemplateEditor.razor` | `/app/templates`(`/{id}`) | allowSubPaths; #144 S2 | | `/decos`, `/decos/{Id:int}` | `Decos.razor`, `DecoEditor.razor` | `/app/decos`(`/{id}`) | allowSubPaths; #144 S3 | @@ -113,7 +113,7 @@ been added to the redirect map yet. | `/media/movies/{MovieId:int}` | `Movie.razor` | `/app/media/movies/{id}` | detail page (`MovieDetailScreen`); PR #183 / #141 | | `/media/tv/shows`(`/page/{n}`) | `TelevisionShowList.razor` | `/app/media?kind=shows` | generic browse; PR #183 / #141 | | `/media/tv/shows/{ShowId:int}` | `TelevisionSeasonList.razor` | `/app/media/shows/{id}` | show + season list (`ShowDetailScreen`); PR #183 / #141 | -| `/media/tv/seasons`(`/page/{n}`) | `TelevisionSeasonSearchResults.razor` | `/app/media?kind=shows` | no dedicated season-list SPA screen; covered via show drill-in; PR #183 / #141 | +| `/media/tv/seasons`(`/page/{n}`) | `TelevisionSeasonSearchResults.razor` | `/app/media?kind=seasons` | seasons browsable as a top-level kind (`MediaBrowseScreen`; also reachable via show drill-in); #209 review fix | | `/media/tv/seasons/{SeasonId:int}` | `TelevisionEpisodeList.razor` | `/app/media/seasons/{id}` | season + episode list (`SeasonDetailScreen`); PR #183 / #141 | | `/media/tv/episodes`(`/page/{n}`) | `EpisodeList.razor` | `/app/media/seasons/{id}` | no standalone SPA episode browse; covered via season detail drill-in; PR #183 / #141 | | `/media/music/artists`(`/page/{n}`) | `ArtistList.razor` | `/app/media?kind=artists` | generic browse; PR #183 / #141 | @@ -180,13 +180,18 @@ REST endpoints exist and are unused; only item delete/reorder and the schedule s ### Remaining mutation-depth gaps inside Section 2 rows -Tracked as #91 phase (b) gates without moving whole rows: **#208** (search screen mutations), -**#209** (media browse/detail mutations + per-show scan + episode info/troubleshoot entries); -SHOULD-FIX: #212 (channel editor), #213 (remaining nits: logs sort + page-size persistence, -block-history page-size/gating, blocks/templates list filter — all read-only conveniences). +Tracked as #91 phase (b) gates without moving whole rows — SHOULD-FIX: #212 (channel editor), +#213 (remaining nits: logs sort + page-size persistence, block-history page-size/gating, +blocks/templates list filter — all read-only conveniences). CLOSED 2026-07-09: **#210** (playout delete/reset/erase/scheduling-context + preview calendar) and **#211** (collection custom order + all-kind add picker); the block/watermark copy, trash select-all, and Trakt-note items of #213 landed in the same PR. +CLOSED 2026-07-10: **#208** (search mutations: card drill-in, per-card + multi-select add-to, +query-wide Add All via `GET /api/search/all-items`, Save As Smart Collection) and **#209** +(media browse/detail: shared Add-to layer `web/src/media/addTo/` on tiles + all four detail +pages + child grids, per-show Quick/Deep scan gated to Plex/Jellyfin/Emby, per-episode Media +Info + Troubleshoot entries; `POST /api/playlists/{id}/items` added). Known accepted deviations +(select-mode toggle, per-card target superset) recorded in `docs/decisions.md`. ## Section 4 — Blazor home / escape hatch diff --git a/docs/decisions.md b/docs/decisions.md index 351303583..7dc4f6dec 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -201,3 +201,27 @@ array position — submitting a partial page would scramble the rest), and does the movies-only gate: the API and the playback-side `CustomOrderCollectionEnumerator` sort by `CustomIndex` regardless of item kind, so the SPA offers reorder for any manual collection with custom order enabled. Issue #211. + +## 2026-07-10 — Shared "Add to…" layer lives in `web/src/media/addTo/`; select-mode is an explicit toggle + +The media mutation surface (#208/#209) is built on one reusable component group, +`web/src/media/addTo/` (media-domain components, like `MediaPosterCard` — not generic +`components/`): `AddToCollectionDialog` (existing-collection Select + inline "(New collection)" +create, Blazor `AddToCollectionDialog.razor` parity), `AddToPlaylistDialog` (group → playlist +Selects, no inline create), `AddToScheduleDialog` (schedule Select; payload replicates Blazor's +`AddProgramScheduleItem.ForMediaItem` defaults — see `addTo/scheduleItem.ts`), +`SaveAsSmartCollectionDialog`, and `AddToMenu` (the drop-in popover for cards/detail pages via +`MediaPosterCard`'s `actions` slot). New screens wanting add-to affordances use this layer — +don't build screen-local pickers. Two deliberate deviations from Blazor, applied consistently on +the search and browse screens: **(1) multi-select is an explicit screen-level "Select" toggle** +(off = cards open, on = cards select) rather than Blazor's always-on corner-select, because +`MediaPosterCard`'s select handler takes over the card's single click gesture; **(2) the +per-card menu offers collection/playlist for a single item of any kind, plus schedule only for +shows/seasons/artists** — collection/playlist is a superset of Blazor's per-card collection-only +menu, while the schedule target is gated to exactly the kinds Blazor's +`AddProgramScheduleItem.ForMediaItem` call sites offer, because the server validator +(`ProgramScheduleItemCommandBase.CollectionTypeMustBeValid`) accepts only the +TelevisionShow/TelevisionSeason/Artist per-media-item CollectionTypes and 422s the rest. +"Add All" (query-wide) mirrors Blazor's two-step: materialize ids +via `GET /api/search/all-items`, then reuse the id-list add endpoints — no query-based add +command exists server-side. Issues #208/#209. diff --git a/docs/e2e-local.md b/docs/e2e-local.md index 77b281333..de54c04f0 100644 --- a/docs/e2e-local.md +++ b/docs/e2e-local.md @@ -32,8 +32,12 @@ which never runs the app itself). 2. **Copy `wwwroot` into the build output** (the `dotnet build` output directory does not automatically pick up `web/`'s build artifacts placed directly into the source `wwwroot`): ```bash + rm -rf ErsatzTV/bin/Debug/net10.0/wwwroot cp -R ErsatzTV/wwwroot ErsatzTV/bin/Debug/net10.0/wwwroot ``` + The `rm` matters: if the destination dir already exists (any prior run), `cp -R src dst` + copies **into** it (`dst/wwwroot/...`) and the server silently keeps serving the previous + run's stale assets. `scripts/e2e-local.sh` does the rm+copy for you. If you rebuild the SPA (`npm run build`) while the dotnet process from step 4 is already running, **re-copy and then restart the process** — see the "why" note above; it will not pick up new files live. diff --git a/docs/endpoint-index.md b/docs/endpoint-index.md index 4a9d994fe..1428189cb 100644 --- a/docs/endpoint-index.md +++ b/docs/endpoint-index.md @@ -2,7 +2,7 @@ *Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.* -129 endpoints, 202 operations. +130 endpoints, 204 operations. ## Artists @@ -214,6 +214,7 @@ | GET | `/api/playlists/{id}` | GetPlaylistById | Get a playlist by id | | PUT | `/api/playlists/{id}` | UpdatePlaylist | Update a playlist (rename and replace its items) | | GET | `/api/playlists/{id}/items` | GetPlaylistItems | Get the items in a playlist | +| POST | `/api/playlists/{id}/items` | AddItemsToPlaylist | Add items to a playlist | ## Playouts @@ -274,6 +275,7 @@ | Method | Path | Operation | Summary | |---|---|---|---| | GET | `/api/search` | Search | Search library items across all media kinds | +| GET | `/api/search/all-items` | SearchAllItems | Search library items across all media kinds and return raw id lists | | GET | `/api/search/artists` | SearchArtists | Search artists by name | | GET | `/api/search/collections` | SearchCollections | Search collections by name | | GET | `/api/search/multi-collections` | SearchMultiCollections | Search multi collections by name | diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index ffe2d810b..3e4b29422 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -109,6 +109,15 @@ manifest. **In tests, mock `hls.js` wholesale** (`vi.mock('hls.js', …)` with a touches a real `MediaSource`; assert the manifest URL via the mocked `loadSource` spy (see `PlaybackTroubleshootingScreen.test.tsx`). +## 5c. Media "Add to…" affordances + +Screens that let the user add media items to a collection/playlist/schedule use the shared layer in +`web/src/media/addTo/` — `AddToMenu` (popover for a `MediaPosterCard` `actions` slot or a detail +page's action row) and the `AddToCollectionDialog` / `AddToPlaylistDialog` / `AddToScheduleDialog` / +`SaveAsSmartCollectionDialog` it drives. Do **not** build screen-local target pickers. Multi-select +on grid screens is an explicit "Select" toggle (see `docs/decisions.md` 2026-07-10 for the rationale +and the accepted deviations from Blazor). + ## 6. Tests - **vitest**, colocated `*.test.ts` / `*.test.tsx` next to the source file. diff --git a/scripts/e2e-local.sh b/scripts/e2e-local.sh index d6fe591d0..f2877bc82 100755 --- a/scripts/e2e-local.sh +++ b/scripts/e2e-local.sh @@ -43,6 +43,9 @@ fi echo "Copying wwwroot into build output (static middleware resolves its file root at startup;" \ "a running process will never see files added later)..." +# rm first: with an existing destination dir, `cp -R src dst` copies INTO it (dst/wwwroot/...), +# silently leaving a previous run's stale assets in place. +rm -rf "$BUILD_DIR/wwwroot" cp -R "$REPO_ROOT/ErsatzTV/wwwroot" "$BUILD_DIR/wwwroot" LOG_FILE="$(mktemp)" diff --git a/web/src/api/generated/v1.d.ts b/web/src/api/generated/v1.d.ts index 81d187617..9c9024447 100644 --- a/web/src/api/generated/v1.d.ts +++ b/web/src/api/generated/v1.d.ts @@ -20,6 +20,18 @@ export interface components { "songIds": null | Array; "imageIds": null | Array; "remoteStreamIds": null | Array; + }; + "AddItemsToPlaylistRequest": { + "movieIds": null | Array; + "showIds": null | Array; + "seasonIds": null | Array; + "episodeIds": null | Array; + "artistIds": null | Array; + "musicVideoIds": null | Array; + "otherVideoIds": null | Array; + "songIds": null | Array; + "imageIds": null | Array; + "remoteStreamIds": null | Array; }; "AddTraktListRequest": { "url": null | string; @@ -1313,6 +1325,18 @@ export interface components { "SchedulingPickerOptionResponseModel": { "id": number; "name": string; + }; + "SearchResultAllItemsResponseModel": { + "movieIds": null | Array; + "showIds": null | Array; + "seasonIds": null | Array; + "episodeIds": null | Array; + "artistIds": null | Array; + "musicVideoIds": null | Array; + "otherVideoIds": null | Array; + "songIds": null | Array; + "imageIds": null | Array; + "remoteStreamIds": null | Array; }; "SearchResultGroupResponseModel": { "totalCount": number; diff --git a/web/src/api/libraries.test.ts b/web/src/api/libraries.test.ts new file mode 100644 index 000000000..f50fa5436 --- /dev/null +++ b/web/src/api/libraries.test.ts @@ -0,0 +1,40 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { scanLibrary, scanShow } from './libraries'; + +function noContent(): Response { + return new Response(null, { status: 200 }); +} + +function lastCall(fetchMock: ReturnType) { + const call = fetchMock.mock.calls[fetchMock.mock.calls.length - 1]; + return { init: call[1] as RequestInit | undefined, url: String(call[0]) }; +} + +describe('libraries api client', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('scanLibrary POSTs to the library scan endpoint', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); + await scanLibrary(4); + expect(fetchMock).toHaveBeenCalledWith('/api/libraries/4/scan', expect.objectContaining({ method: 'POST' })); + }); + + it('scanShow POSTs the show title and deepScan flag', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); + await scanShow(4, { deepScan: true, showTitle: 'The Office' }); + const { init, url } = lastCall(fetchMock); + expect(url).toBe('/api/libraries/4/scan-show'); + expect(init?.method).toBe('POST'); + expect(JSON.parse(String(init?.body))).toEqual({ deepScan: true, showTitle: 'The Office' }); + }); + + it('scanShow defaults deepScan to false when omitted', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); + await scanShow(9, { showTitle: 'Firefly' }); + const { init } = lastCall(fetchMock); + expect(JSON.parse(String(init?.body))).toEqual({ deepScan: false, showTitle: 'Firefly' }); + }); +}); diff --git a/web/src/api/libraries.ts b/web/src/api/libraries.ts index f2b78ab8b..0def1f765 100644 --- a/web/src/api/libraries.ts +++ b/web/src/api/libraries.ts @@ -51,6 +51,21 @@ export function scanLibrary(libraryId: number): Promise { return request(`/api/libraries/${libraryId}/scan`, { method: 'POST' }); } +export interface ScanShowParams { + showTitle: string; + deepScan?: boolean; +} + +// Queues a scan of a single show (by title) within a library. Returns 200 on success, 400 when +// the title can't be resolved / the library doesn't support single-show scanning. Body keys are +// `showTitle` and `deepScan` (see LibrariesController.ScanShowRequest). +export function scanShow(libraryId: number, params: ScanShowParams): Promise { + return request(`/api/libraries/${libraryId}/scan-show`, { + body: { deepScan: params.deepScan ?? false, showTitle: params.showTitle }, + method: 'POST' + }); +} + // Pure: computes the surviving pending-id set for one poll tick (success or failure) and // mutates the grace-ticks map in place (delete on promote/expire, set on decrement) - // callers must still write pendingIdsRef.current with the returned set themselves, and diff --git a/web/src/api/playlists.test.ts b/web/src/api/playlists.test.ts index 9591399bb..26f7f2a70 100644 --- a/web/src/api/playlists.test.ts +++ b/web/src/api/playlists.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { + addItemsToPlaylist, createPlaylist, createPlaylistGroup, deletePlaylist, @@ -131,6 +132,27 @@ describe('playlists api client', () => { expect(JSON.parse(String(init?.body))).toEqual({ items: [sampleItem], name: 'Draft' }); }); + it('addItemsToPlaylist POSTs the bucketed ids to the items endpoint', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent()); + const body = { + artistIds: [], + episodeIds: [], + imageIds: [], + movieIds: [12], + musicVideoIds: [], + otherVideoIds: [], + remoteStreamIds: [], + seasonIds: [], + showIds: [3], + songIds: [] + }; + await addItemsToPlaylist(6, body); + const { init, url } = lastCall(fetchMock); + expect(url).toBe('/api/playlists/6/items'); + expect(init?.method).toBe('POST'); + expect(JSON.parse(String(init?.body))).toEqual(body); + }); + it('messageFromPlaylistError prefers ApiError detail', () => { expect(messageFromPlaylistError(new ApiError(422, { detail: 'Name is required' }))).toBe('Name is required'); expect(messageFromPlaylistError('nope', 'fallback')).toBe('fallback'); diff --git a/web/src/api/playlists.ts b/web/src/api/playlists.ts index 5f96d73ba..bc6b4af49 100644 --- a/web/src/api/playlists.ts +++ b/web/src/api/playlists.ts @@ -1,6 +1,8 @@ import { ApiError, request } from './client'; import type { components } from './generated/v1'; +export type AddItemsToPlaylistRequest = components['schemas']['AddItemsToPlaylistRequest']; + export type PlaylistGroup = components['schemas']['PlaylistGroupResponseModel']; export type Playlist = components['schemas']['PlaylistResponseModel']; export type PlaylistItem = components['schemas']['PlaylistItemResponseModel']; @@ -56,6 +58,15 @@ export function previewPlaylist(body: ReplacePlaylistRequest): Promise('/api/playlists/preview', { body, method: 'POST' }); } +// Adds media items (bucketed by kind) to an existing playlist. The request body is the same +// ten-array shape as AddItemsToCollectionRequest; the server returns 204 on success, 404 for a +// missing playlist, 422 for validation failures. AddItemsToPlaylistRequest is the generated type +// for this endpoint's body, but the collection-shaped request is structurally identical, so +// callers can pipe toAddItemsRequest / toAddItemsRequestFromSearch output straight in. +export function addItemsToPlaylist(playlistId: number, body: AddItemsToPlaylistRequest): Promise { + return request(`/api/playlists/${playlistId}/items`, { body, method: 'POST' }); +} + export function messageFromPlaylistError(error: unknown, fallback = 'Unable to load playlists'): string { if (error instanceof ApiError) { return error.detail ?? error.message; diff --git a/web/src/api/search.test.ts b/web/src/api/search.test.ts index 5ea895499..ceed1af3d 100644 --- a/web/src/api/search.test.ts +++ b/web/src/api/search.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { getSearchResults } from './search'; +import { getSearchAllItems, getSearchResults, toAddItemsRequestFromSearch } from './search'; const emptyGroup = { totalCount: 0, items: [] }; const sampleResults = { @@ -61,3 +61,55 @@ describe('getSearchResults', () => { await expect(getSearchResults({ query: '' })).rejects.toMatchObject({ status: 422 }); }); }); + +describe('getSearchAllItems', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('GETs /api/search/all-items with the query', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ movieIds: [1], showIds: [2] }), { + headers: { 'Content-Type': 'application/json' }, + status: 200 + }) + ); + + await getSearchAllItems('star wars'); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/search/all-items?query=star+wars'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('GET'); + }); +}); + +describe('toAddItemsRequestFromSearch', () => { + it('fills every bucket, defaulting null arrays to []', () => { + expect( + toAddItemsRequestFromSearch({ + artistIds: null, + episodeIds: null, + imageIds: null, + movieIds: [1, 2], + musicVideoIds: null, + otherVideoIds: null, + remoteStreamIds: null, + seasonIds: null, + showIds: null, + songIds: null + }) + ).toEqual({ + artistIds: [], + episodeIds: [], + imageIds: [], + movieIds: [1, 2], + musicVideoIds: [], + otherVideoIds: [], + remoteStreamIds: [], + seasonIds: [], + showIds: [], + songIds: [] + }); + }); +}); diff --git a/web/src/api/search.ts b/web/src/api/search.ts index acefe1a4e..c3e07a756 100644 --- a/web/src/api/search.ts +++ b/web/src/api/search.ts @@ -1,9 +1,15 @@ import { ApiError, request } from './client'; import type { components } from './generated/v1'; +import type { AddItemsToCollectionRequest } from './collections'; export type SearchResults = components['schemas']['SearchResultsResponseModel']; export type SearchResultGroup = components['schemas']['SearchResultGroupResponseModel']; +// The ten media-item id arrays a search query resolves to, one bucket per addable kind. Wire keys +// match AddItemsToCollectionRequest exactly, so a result pipes straight into addItemsToCollection / +// addItemsToPlaylist via toAddItemsRequestFromSearch below. +export type SearchAllItemIds = components['schemas']['SearchResultAllItemsResponseModel']; + export interface GetSearchResultsParams { query: string; pageSize?: number; @@ -20,6 +26,31 @@ export function getSearchResults(params: GetSearchResultsParams): Promise(`/api/search?${searchParams.toString()}`); } +// Resolves a search query to the full set of matching media-item ids, bucketed by kind. Backs the +// "Add all results" flow so the caller never has to page through every result to add them. +export function getSearchAllItems(query: string): Promise { + const searchParams = new URLSearchParams(); + searchParams.set('query', query); + return request(`/api/search/all-items?${searchParams.toString()}`); +} + +// Normalizes a SearchAllItemIds result (nullable arrays) into a full AddItemsToCollectionRequest +// so it can be piped straight into addItemsToCollection / addItemsToPlaylist. +export function toAddItemsRequestFromSearch(result: SearchAllItemIds): AddItemsToCollectionRequest { + return { + artistIds: result.artistIds ?? [], + episodeIds: result.episodeIds ?? [], + imageIds: result.imageIds ?? [], + movieIds: result.movieIds ?? [], + musicVideoIds: result.musicVideoIds ?? [], + otherVideoIds: result.otherVideoIds ?? [], + remoteStreamIds: result.remoteStreamIds ?? [], + seasonIds: result.seasonIds ?? [], + showIds: result.showIds ?? [], + songIds: result.songIds ?? [] + }; +} + export function messageFromSearchError(error: unknown, fallback = 'Unable to search library'): string { if (error instanceof ApiError) { return error.detail ?? error.message; diff --git a/web/src/media/MediaPosterCard.test.tsx b/web/src/media/MediaPosterCard.test.tsx new file mode 100644 index 000000000..885c94407 --- /dev/null +++ b/web/src/media/MediaPosterCard.test.tsx @@ -0,0 +1,66 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { MediaPosterCard } from './MediaPosterCard'; +import type { LibraryBrowseItem } from '../api'; + +const movieItem = { artwork: '', id: 12, mediaType: 'Movie', title: 'Blade Runner' } as unknown as LibraryBrowseItem; + +describe('MediaPosterCard', () => { + afterEach(() => { + cleanup(); + }); + + it('renders the item title', () => { + render(); + expect(screen.getByText('Blade Runner')).toBeTruthy(); + }); + + it('calls onOpen when the card is clicked', () => { + const onOpen = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button')); + expect(onOpen).toHaveBeenCalledWith(movieItem); + }); + + it('does not trigger open/select when the actions slot is clicked', () => { + const onOpen = vi.fn(); + const onAction = vi.fn(); + render( + + Act + + } + item={movieItem} + onOpen={onOpen} + /> + ); + + fireEvent.click(screen.getByRole('button', { name: 'Act' })); + expect(onAction).toHaveBeenCalledTimes(1); + expect(onOpen).not.toHaveBeenCalled(); + }); + + it('still toggles selection from the card body while the actions slot stays isolated', () => { + const onToggleSelect = vi.fn(); + const onAction = vi.fn(); + render( + + Act + + } + item={movieItem} + onToggleSelect={onToggleSelect} + /> + ); + + fireEvent.click(screen.getByText('Blade Runner')); + expect(onToggleSelect).toHaveBeenCalledWith(movieItem); + + fireEvent.click(screen.getByRole('button', { name: 'Act' })); + expect(onToggleSelect).toHaveBeenCalledTimes(1); + }); +}); diff --git a/web/src/media/MediaPosterCard.tsx b/web/src/media/MediaPosterCard.tsx index 1327f7877..d7cbecaf8 100644 --- a/web/src/media/MediaPosterCard.tsx +++ b/web/src/media/MediaPosterCard.tsx @@ -1,22 +1,26 @@ -import type { CSSProperties } from 'react'; +import type { CSSProperties, ReactNode } from 'react'; import { Film } from 'lucide-react'; import type { LibraryBrowseItem } from '../api'; import { TYPE_ICON, TYPE_LABEL, hueOf, itemSubtitle } from './mediaKinds'; // A poster/thumbnail grid card for a browse/search item. Selectable + clickable for the media // browse/search/trash screens. Falls back to a deterministic gradient + type icon when no artwork. +// `actions` renders an overlay in the poster's top-right corner (e.g. an Add-to menu button); +// interactions inside it are isolated from the card's open/select gesture via stopPropagation. export function MediaPosterCard({ item, selected, onToggleSelect, onOpen, - height = 150 + height = 150, + actions }: { item: LibraryBrowseItem; selected?: boolean; onToggleSelect?: (item: LibraryBrowseItem) => void; onOpen?: (item: LibraryBrowseItem) => void; height?: number; + actions?: ReactNode; }) { const hue = hueOf(item.title); const Icon = TYPE_ICON[item.mediaType] ?? Film; @@ -72,6 +76,17 @@ export function MediaPosterCard({ + {actions && ( +
event.stopPropagation()} + onKeyDown={(event) => event.stopPropagation()} + > + {actions} +
+ )} {selected &&
✓
}
diff --git a/web/src/media/addTo/AddToCollectionDialog.test.tsx b/web/src/media/addTo/AddToCollectionDialog.test.tsx new file mode 100644 index 000000000..2a83455b9 --- /dev/null +++ b/web/src/media/addTo/AddToCollectionDialog.test.tsx @@ -0,0 +1,129 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AddToCollectionDialog } from './AddToCollectionDialog'; +import type { LibraryBrowseItem } from '../../api'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +const collections = [ + { collectionType: 'Collection', id: 1, name: 'Favorites', useCustomPlaybackOrder: false }, + { collectionType: 'Collection', id: 2, name: 'Kids', useCustomPlaybackOrder: false } +]; + +const movieItem = { artwork: '', id: 12, mediaType: 'Movie', title: 'Blade Runner' } as unknown as LibraryBrowseItem; + +const expectedAddBody = { + artistIds: [], + episodeIds: [], + imageIds: [], + movieIds: [12], + musicVideoIds: [], + otherVideoIds: [], + remoteStreamIds: [], + seasonIds: [], + showIds: [], + songIds: [] +}; + +interface Recorded { + url: string; + method: string; + body: unknown; +} + +function mockApi(onCreate?: (body: unknown) => Response) { + const calls: Recorded[] = []; + const fetchMock = vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { + const url = input.toString(); + const method = (init?.method ?? 'GET').toUpperCase(); + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ body, method, url }); + + if (url === '/api/collections' && method === 'GET') { + return Promise.resolve(jsonResponse(collections)); + } + + if (url === '/api/collections' && method === 'POST') { + return Promise.resolve(onCreate ? onCreate(body) : jsonResponse({ collectionType: 'Collection', id: 99, name: (body as { name: string }).name, useCustomPlaybackOrder: false }, 201)); + } + + return Promise.resolve(new Response(null, { status: 204 })); + }); + + return { calls, fetchMock }; +} + +describe('AddToCollectionDialog', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('renders nothing when closed', () => { + mockApi(); + const { container } = render( {}} open={false} />); + expect(container).toBeEmptyDOMElement(); + }); + + it('loads existing collections into the select', async () => { + mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Favorites' })).toBeTruthy()); + expect(screen.getByRole('option', { name: 'Kids' })).toBeTruthy(); + expect(screen.getByRole('option', { name: '(New collection)' })).toBeTruthy(); + }); + + it('adds the items to the selected existing collection', async () => { + const onAdded = vi.fn(); + const onClose = vi.fn(); + const { calls } = mockApi(); + render(); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Kids' })).toBeTruthy()); + fireEvent.change(screen.getByRole('combobox'), { target: { value: '2' } }); + fireEvent.click(screen.getByRole('button', { name: /Add to collection/ })); + + await waitFor(() => expect(onClose).toHaveBeenCalled()); + const addCall = calls.find((call) => call.url === '/api/collections/2/items'); + expect(addCall?.method).toBe('POST'); + expect(addCall?.body).toEqual(expectedAddBody); + expect(onAdded).toHaveBeenCalledWith('Kids'); + }); + + it('creates a new collection first, then adds the items to it', async () => { + const onAdded = vi.fn(); + const { calls } = mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: '(New collection)' })).toBeTruthy()); + fireEvent.change(screen.getByRole('combobox'), { target: { value: '__new__' } }); + fireEvent.change(screen.getByPlaceholderText('Collection name'), { target: { value: 'Sci-Fi' } }); + fireEvent.click(screen.getByRole('button', { name: /Add to collection/ })); + + await waitFor(() => expect(onAdded).toHaveBeenCalledWith('Sci-Fi')); + const createCall = calls.find((call) => call.url === '/api/collections' && call.method === 'POST'); + expect(createCall?.body).toEqual({ name: 'Sci-Fi' }); + const addCall = calls.find((call) => call.url === '/api/collections/99/items'); + expect(addCall?.body).toEqual(expectedAddBody); + }); + + it('supports a request override (query-based add-all) instead of item ids', async () => { + const override = { ...expectedAddBody, movieIds: [1, 2, 3] }; + const { calls } = mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Favorites' })).toBeTruthy()); + fireEvent.click(screen.getByRole('button', { name: /Add to collection/ })); + + await waitFor(() => expect(calls.some((call) => call.url === '/api/collections/1/items')).toBe(true)); + const addCall = calls.find((call) => call.url === '/api/collections/1/items'); + expect(addCall?.body).toEqual(override); + }); +}); diff --git a/web/src/media/addTo/AddToCollectionDialog.tsx b/web/src/media/addTo/AddToCollectionDialog.tsx new file mode 100644 index 000000000..21ffcc22b --- /dev/null +++ b/web/src/media/addTo/AddToCollectionDialog.tsx @@ -0,0 +1,184 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Plus } from 'lucide-react'; +import { Button, Dialog, Input, Select, Spinner } from '../../components'; +import { + addItemsToCollection, + createCollection, + getCollections, + messageFromCollectionError, + toAddItemsRequest, + type AddItemsToCollectionRequest, + type MediaCollection +} from '../../api'; +import type { AddToItems } from './scheduleItem'; + +export interface AddToCollectionDialogProps { + open: boolean; + onClose: () => void; + items: AddToItems; + onAdded?: (collectionName: string) => void; +} + +const NEW_COLLECTION = '__new__'; + +function resolveRequest(items: AddToItems): AddItemsToCollectionRequest { + return Array.isArray(items) ? toAddItemsRequest(items) : items.requestOverride; +} + +export function AddToCollectionDialog(props: AddToCollectionDialogProps) { + if (!props.open) { + return null; + } + + return ; +} + +function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionDialogProps) { + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(null); + const [collections, setCollections] = useState([]); + const [selected, setSelected] = useState(NEW_COLLECTION); + const [newName, setNewName] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [submitError, setSubmitError] = useState(null); + const activeRef = useRef(true); + + useEffect(() => { + activeRef.current = true; + + return () => { + activeRef.current = false; + }; + }, []); + + const load = useCallback(() => { + getCollections() + .then((result) => { + if (!activeRef.current) { + return; + } + + setCollections(result); + setSelected(result.length > 0 ? String(result[0].id) : NEW_COLLECTION); + setLoadError(null); + setLoading(false); + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setLoadError(messageFromCollectionError(error)); + setLoading(false); + }); + }, []); + + useEffect(() => { + load(); + }, [load]); + + const isNew = selected === NEW_COLLECTION; + const canSubmit = !submitting && (!isNew || newName.trim().length > 0); + + const submit = () => { + if (!canSubmit) { + return; + } + + setSubmitting(true); + setSubmitError(null); + + const request = resolveRequest(items); + + const ensureCollection: Promise<{ id: number; name: string }> = isNew + ? createCollection({ name: newName.trim() }).then((collection) => ({ + id: collection.id, + name: collection.name ?? newName.trim() + })) + : Promise.resolve({ + id: Number(selected), + name: collections.find((collection) => String(collection.id) === selected)?.name ?? 'collection' + }); + + ensureCollection + .then((collection) => addItemsToCollection(collection.id, request).then(() => collection)) + .then((collection) => { + if (!activeRef.current) { + return; + } + + onAdded?.(collection.name); + onClose(); + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setSubmitError(messageFromCollectionError(error, 'Unable to add items')); + setSubmitting(false); + }); + }; + + const options = [ + { value: NEW_COLLECTION, label: '(New collection)' }, + ...collections.map((collection) => ({ value: String(collection.id), label: collection.name ?? `Collection ${collection.id}` })) + ]; + + return ( + + + + + } + onClose={onClose} + open + title="Add to collection" + width={460} + > + {loading ? ( +
+ +
+ ) : loadError ? ( + + {loadError} + + ) : ( +
+ setNewName(event.target.value)} + placeholder="Collection name" + value={newName} + /> + )} + {submitError && ( + + {submitError} + + )} +
+ )} +
+ ); +} diff --git a/web/src/media/addTo/AddToMenu.test.tsx b/web/src/media/addTo/AddToMenu.test.tsx new file mode 100644 index 000000000..781858684 --- /dev/null +++ b/web/src/media/addTo/AddToMenu.test.tsx @@ -0,0 +1,105 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AddToMenu } from './AddToMenu'; +import type { LibraryBrowseItem } from '../../api'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +const movieItem = { artwork: '', id: 12, mediaType: 'Movie', title: 'Blade Runner' } as unknown as LibraryBrowseItem; +const showItem = { artwork: '', id: 42, mediaType: 'TelevisionShow', title: 'The Office' } as unknown as LibraryBrowseItem; + +function mockApi() { + vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { + const url = input.toString(); + if (url === '/api/collections') { + return Promise.resolve(jsonResponse([{ collectionType: 'Collection', id: 1, name: 'Favorites', useCustomPlaybackOrder: false }])); + } + if (url === '/api/playlists/groups') { + return Promise.resolve(jsonResponse([])); + } + if (url === '/api/schedules') { + return Promise.resolve(jsonResponse([])); + } + return Promise.resolve(new Response(null, { status: 204 })); + }); +} + +describe('AddToMenu', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('opens the menu and shows the requested targets for a schedulable kind', () => { + mockApi(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to…' })); + expect(screen.getByRole('menuitem', { name: /Add to collection/ })).toBeTruthy(); + expect(screen.getByRole('menuitem', { name: /Add to playlist/ })).toBeTruthy(); + expect(screen.getByRole('menuitem', { name: /Add to schedule/ })).toBeTruthy(); + }); + + it('hides the schedule target when more than one item is selected', () => { + mockApi(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to…' })); + expect(screen.queryByRole('menuitem', { name: /Add to schedule/ })).toBeNull(); + }); + + it('hides the schedule target for a non-schedulable kind (movie)', () => { + mockApi(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to…' })); + expect(screen.getByRole('menuitem', { name: /Add to collection/ })).toBeTruthy(); + expect(screen.getByRole('menuitem', { name: /Add to playlist/ })).toBeTruthy(); + expect(screen.queryByRole('menuitem', { name: /Add to schedule/ })).toBeNull(); + }); + + it('closes the menu on Escape and returns focus to the trigger', () => { + mockApi(); + render(); + + const trigger = screen.getByRole('button', { name: 'Add to…' }); + fireEvent.click(trigger); + expect(screen.getByRole('menu')).toBeTruthy(); + + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('menu')).toBeNull(); + expect(document.activeElement).toBe(trigger); + }); + + it('respects an explicit targets list', () => { + mockApi(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to…' })); + expect(screen.getByRole('menuitem', { name: /Add to collection/ })).toBeTruthy(); + expect(screen.queryByRole('menuitem', { name: /Add to playlist/ })).toBeNull(); + }); + + it('opens the collection dialog when the collection target is chosen', async () => { + mockApi(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to…' })); + fireEvent.click(screen.getByRole('menuitem', { name: /Add to collection/ })); + + await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy()); + expect(screen.getByRole('option', { name: 'Favorites' })).toBeTruthy(); + }); + + it('disables the trigger when there are no items', () => { + mockApi(); + render(); + expect(screen.getByRole('button', { name: 'Add to…' })).toHaveProperty('disabled', true); + }); +}); diff --git a/web/src/media/addTo/AddToMenu.tsx b/web/src/media/addTo/AddToMenu.tsx new file mode 100644 index 000000000..fc220c3d4 --- /dev/null +++ b/web/src/media/addTo/AddToMenu.tsx @@ -0,0 +1,121 @@ +import { useEffect, useRef, useState } from 'react'; +import { CalendarClock, FolderPlus, ListVideo, Plus } from 'lucide-react'; +import { IconButton } from '../../components'; +import type { LibraryBrowseItem } from '../../api'; +import { AddToCollectionDialog } from './AddToCollectionDialog'; +import { AddToPlaylistDialog } from './AddToPlaylistDialog'; +import { AddToScheduleDialog } from './AddToScheduleDialog'; +import { collectionTypeForMediaType } from './scheduleItem'; + +export type AddToTarget = 'collection' | 'playlist' | 'schedule'; + +const DEFAULT_TARGETS: AddToTarget[] = ['collection', 'playlist', 'schedule']; + +export interface AddToMenuProps { + items: LibraryBrowseItem[]; + targets?: AddToTarget[]; + onDone?: (message: string) => void; + compact?: boolean; +} + +// A small dropdown-button that opens the right Add-to dialog for the given items. Meant to be +// dropped onto media cards / detail pages by the wiring screens; it owns the popover + which +// dialog is open, and surfaces a success message to the caller via onDone. +export function AddToMenu({ items, targets = DEFAULT_TARGETS, onDone, compact = false }: AddToMenuProps) { + const [menuOpen, setMenuOpen] = useState(false); + const [dialog, setDialog] = useState(null); + const rootRef = useRef(null); + + useEffect(() => { + if (!menuOpen) { + return undefined; + } + + const onPointerDown = (event: MouseEvent) => { + if (rootRef.current && !rootRef.current.contains(event.target as Node)) { + setMenuOpen(false); + } + }; + // Escape closes the popover and returns focus to the trigger button. + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + setMenuOpen(false); + rootRef.current?.querySelector(':scope > button')?.focus(); + } + }; + document.addEventListener('mousedown', onPointerDown); + document.addEventListener('keydown', onKeyDown); + + return () => { + document.removeEventListener('mousedown', onPointerDown); + document.removeEventListener('keydown', onKeyDown); + }; + }, [menuOpen]); + + // Schedule adds a single media item, and the server only accepts shows / seasons / artists as + // per-media-item schedule items — only offer it when exactly one schedulable item is in play. + const scheduleItem = + items.length === 1 && collectionTypeForMediaType(items[0].mediaType) !== null ? items[0] : null; + const visibleTargets = targets.filter((target) => target !== 'schedule' || scheduleItem !== null); + const disabled = items.length === 0; + + const open = (target: AddToTarget) => { + setMenuOpen(false); + setDialog(target); + }; + + const closeDialog = () => setDialog(null); + + const handleAdded = (message: string) => { + setDialog(null); + onDone?.(message); + }; + + return ( +
+ setMenuOpen((current) => !current)} + size={compact ? 'sm' : 'md'} + title="Add to…" + variant="solid" + > + + {menuOpen && ( +
+ {visibleTargets.includes('collection') && ( + + )} + {visibleTargets.includes('playlist') && ( + + )} + {visibleTargets.includes('schedule') && ( + + )} +
+ )} + + handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'collection'} /> + handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'playlist'} /> + {scheduleItem && ( + handleAdded(`Added to “${name}”`)} + onClose={closeDialog} + open={dialog === 'schedule'} + /> + )} +
+ ); +} diff --git a/web/src/media/addTo/AddToPlaylistDialog.test.tsx b/web/src/media/addTo/AddToPlaylistDialog.test.tsx new file mode 100644 index 000000000..ec0d72001 --- /dev/null +++ b/web/src/media/addTo/AddToPlaylistDialog.test.tsx @@ -0,0 +1,121 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AddToPlaylistDialog } from './AddToPlaylistDialog'; +import type { LibraryBrowseItem } from '../../api'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +const groups = [ + { id: 1, isSystem: false, name: 'Idents', playlistCount: 2 }, + { id: 2, isSystem: false, name: 'Bumpers', playlistCount: 1 } +]; + +const playlistsByGroup: Record = { + '1': [ + { id: 10, isSystem: false, name: 'Morning', playlistGroupId: 1 }, + { id: 11, isSystem: true, name: 'System Reserved', playlistGroupId: 1 } + ], + '2': [{ id: 20, isSystem: false, name: 'Evening', playlistGroupId: 2 }] +}; + +const showItem = { artwork: '', id: 5, mediaType: 'TelevisionShow', title: 'The Office' } as unknown as LibraryBrowseItem; + +interface Recorded { + url: string; + method: string; + body: unknown; +} + +function mockApi() { + const calls: Recorded[] = []; + vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { + const url = input.toString(); + const method = (init?.method ?? 'GET').toUpperCase(); + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ body, method, url }); + + if (url === '/api/playlists/groups' && method === 'GET') { + return Promise.resolve(jsonResponse(groups)); + } + + const playlistsMatch = /^\/api\/playlists\?playlistGroupId=(\d+)$/.exec(url); + if (playlistsMatch && method === 'GET') { + return Promise.resolve(jsonResponse(playlistsByGroup[playlistsMatch[1]] ?? [])); + } + + return Promise.resolve(new Response(null, { status: 204 })); + }); + + return { calls }; +} + +describe('AddToPlaylistDialog', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('loads the first group and its playlists', async () => { + mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Morning' })).toBeTruthy()); + expect(screen.getByRole('option', { name: 'Idents' })).toBeTruthy(); + }); + + it('adds the items to the selected playlist', async () => { + const onAdded = vi.fn(); + const onClose = vi.fn(); + const { calls } = mockApi(); + render(); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Morning' })).toBeTruthy()); + fireEvent.click(screen.getByRole('button', { name: /Add to playlist/ })); + + await waitFor(() => expect(onClose).toHaveBeenCalled()); + const addCall = calls.find((call) => call.url === '/api/playlists/10/items'); + expect(addCall?.method).toBe('POST'); + expect(addCall?.body).toMatchObject({ showIds: [5], movieIds: [] }); + expect(onAdded).toHaveBeenCalledWith('Morning'); + }); + + it('filters out system playlists and groups', async () => { + vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { + const url = input.toString(); + const method = (init?.method ?? 'GET').toUpperCase(); + if (url === '/api/playlists/groups' && method === 'GET') { + return Promise.resolve( + jsonResponse([...groups, { id: 9, isSystem: true, name: 'System Group', playlistCount: 1 }]) + ); + } + const playlistsMatch = /^\/api\/playlists\?playlistGroupId=(\d+)$/.exec(url); + if (playlistsMatch && method === 'GET') { + return Promise.resolve(jsonResponse(playlistsByGroup[playlistsMatch[1]] ?? [])); + } + return Promise.resolve(new Response(null, { status: 204 })); + }); + + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Morning' })).toBeTruthy()); + expect(screen.queryByRole('option', { name: 'System Reserved' })).toBeNull(); + expect(screen.queryByRole('option', { name: 'System Group' })).toBeNull(); + }); + + it('reloads playlists when the group changes', async () => { + mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Morning' })).toBeTruthy()); + const [groupSelect] = screen.getAllByRole('combobox'); + fireEvent.change(groupSelect, { target: { value: '2' } }); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Evening' })).toBeTruthy()); + }); +}); diff --git a/web/src/media/addTo/AddToPlaylistDialog.tsx b/web/src/media/addTo/AddToPlaylistDialog.tsx new file mode 100644 index 000000000..fcb0fbc81 --- /dev/null +++ b/web/src/media/addTo/AddToPlaylistDialog.tsx @@ -0,0 +1,216 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Plus } from 'lucide-react'; +import { Button, Dialog, Select, Spinner } from '../../components'; +import { + addItemsToPlaylist, + getPlaylistGroups, + getPlaylists, + messageFromPlaylistError, + toAddItemsRequest, + type AddItemsToCollectionRequest, + type Playlist, + type PlaylistGroup +} from '../../api'; +import type { AddToItems } from './scheduleItem'; + +export interface AddToPlaylistDialogProps { + open: boolean; + onClose: () => void; + items: AddToItems; + onAdded?: (playlistName: string) => void; +} + +function resolveRequest(items: AddToItems): AddItemsToCollectionRequest { + return Array.isArray(items) ? toAddItemsRequest(items) : items.requestOverride; +} + +export function AddToPlaylistDialog(props: AddToPlaylistDialogProps) { + if (!props.open) { + return null; + } + + return ; +} + +function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialogProps) { + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(null); + const [groups, setGroups] = useState([]); + const [selectedGroup, setSelectedGroup] = useState(''); + const [playlists, setPlaylists] = useState([]); + const [playlistsLoading, setPlaylistsLoading] = useState(false); + const [selectedPlaylist, setSelectedPlaylist] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [submitError, setSubmitError] = useState(null); + const activeRef = useRef(true); + const groupSeqRef = useRef(0); + + useEffect(() => { + activeRef.current = true; + + return () => { + activeRef.current = false; + }; + }, []); + + const loadPlaylists = useCallback((groupId: number) => { + const seq = groupSeqRef.current + 1; + groupSeqRef.current = seq; + setPlaylistsLoading(true); + setPlaylists([]); + setSelectedPlaylist(''); + + getPlaylists(groupId) + .then((result) => { + if (!activeRef.current || groupSeqRef.current !== seq) { + return; + } + + // System playlists are ErsatzTV-managed (e.g. per-channel scheduling playlists) and + // must not be edited directly — mirror Blazor by hiding them from the picker. + const editable = result.filter((playlist) => !playlist.isSystem); + setPlaylists(editable); + setSelectedPlaylist(editable.length > 0 ? String(editable[0].id) : ''); + setPlaylistsLoading(false); + }) + .catch((error: unknown) => { + if (!activeRef.current || groupSeqRef.current !== seq) { + return; + } + + setSubmitError(messageFromPlaylistError(error, 'Unable to load playlists')); + setPlaylistsLoading(false); + }); + }, []); + + const load = useCallback(() => { + getPlaylistGroups() + .then((result) => { + if (!activeRef.current) { + return; + } + + const editable = result.filter((group) => !group.isSystem); + setGroups(editable); + setLoadError(null); + setLoading(false); + + if (editable.length > 0) { + setSelectedGroup(String(editable[0].id)); + loadPlaylists(editable[0].id); + } + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setLoadError(messageFromPlaylistError(error)); + setLoading(false); + }); + }, [loadPlaylists]); + + useEffect(() => { + load(); + }, [load]); + + const onGroupChange = (value: string) => { + setSelectedGroup(value); + setSubmitError(null); + loadPlaylists(Number(value)); + }; + + const canSubmit = !submitting && !playlistsLoading && selectedPlaylist !== ''; + + const submit = () => { + if (!canSubmit) { + return; + } + + setSubmitting(true); + setSubmitError(null); + + const playlistId = Number(selectedPlaylist); + const name = playlists.find((playlist) => String(playlist.id) === selectedPlaylist)?.name ?? 'playlist'; + + addItemsToPlaylist(playlistId, resolveRequest(items)) + .then(() => { + if (!activeRef.current) { + return; + } + + onAdded?.(name); + onClose(); + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setSubmitError(messageFromPlaylistError(error, 'Unable to add items')); + setSubmitting(false); + }); + }; + + return ( + + + + + } + onClose={onClose} + open + title="Add to playlist" + width={460} + > + {loading ? ( +
+ +
+ ) : loadError ? ( + + {loadError} + + ) : groups.length === 0 ? ( +

No playlist groups exist yet. Create one first.

+ ) : ( +
+ setSelectedPlaylist(event.target.value)} + options={ + playlists.length === 0 + ? [{ value: '', label: playlistsLoading ? 'Loading…' : 'No playlists in this group' }] + : playlists.map((playlist) => ({ value: String(playlist.id), label: playlist.name ?? `Playlist ${playlist.id}` })) + } + value={selectedPlaylist} + /> + {submitError && ( + + {submitError} + + )} +
+ )} +
+ ); +} diff --git a/web/src/media/addTo/AddToScheduleDialog.test.tsx b/web/src/media/addTo/AddToScheduleDialog.test.tsx new file mode 100644 index 000000000..5d318237c --- /dev/null +++ b/web/src/media/addTo/AddToScheduleDialog.test.tsx @@ -0,0 +1,151 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AddToScheduleDialog } from './AddToScheduleDialog'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +const schedules = [ + { id: 1, name: 'Weekdays', fixedStartTimeBehavior: 'Never', keepMultiPartEpisodesTogether: false, randomStartPoint: false, shuffleScheduleItems: false, treatCollectionsAsShows: false }, + { id: 2, name: 'Weekends', fixedStartTimeBehavior: 'Never', keepMultiPartEpisodesTogether: false, randomStartPoint: false, shuffleScheduleItems: false, treatCollectionsAsShows: false } +]; + +// Mirrors AddProgramScheduleItem.ForMediaItem defaults (AddProgramScheduleItem.cs:48-87), with the +// mapped collectionType + mediaItemId for a TelevisionShow item. +const expectedShowPayload = { + startType: 'Dynamic', + startTime: null, + fixedStartTimeBehavior: null, + playoutMode: 'One', + collectionType: 'TelevisionShow', + collectionId: null, + multiCollectionId: null, + smartCollectionId: null, + rerunCollectionId: null, + mediaItemId: 42, + playlistId: null, + searchTitle: null, + searchQuery: null, + playbackOrder: 'Shuffle', + marathonGroupBy: 'None', + marathonShuffleGroups: false, + marathonShuffleItems: false, + marathonBatchSize: null, + fillWithGroupMode: 'None', + multipleMode: 'Count', + multipleCount: null, + playoutDuration: null, + tailMode: 'None', + discardToFillAttempts: null, + customTitle: null, + guideMode: 'Normal', + preRollFillerId: null, + midRollFillerId: null, + postRollFillerId: null, + tailFillerId: null, + fallbackFillerId: null, + watermarkIds: [], + graphicsElementIds: [], + preferredAudioLanguageCode: null, + preferredAudioTitle: null, + preferredSubtitleLanguageCode: null, + subtitleMode: null +}; + +interface Recorded { + url: string; + method: string; + body: unknown; +} + +function mockApi() { + const calls: Recorded[] = []; + vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { + const url = input.toString(); + const method = (init?.method ?? 'GET').toUpperCase(); + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ body, method, url }); + + if (url === '/api/schedules' && method === 'GET') { + return Promise.resolve(jsonResponse(schedules)); + } + + if (/^\/api\/schedules\/\d+\/items$/.test(url) && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 500 }, 201)); + } + + return Promise.resolve(new Response(null, { status: 204 })); + }); + + return { calls }; +} + +describe('AddToScheduleDialog', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('loads schedules into the select', async () => { + mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Weekdays' })).toBeTruthy()); + expect(screen.getByRole('option', { name: 'Weekends' })).toBeTruthy(); + }); + + it('adds the media item with the ForMediaItem defaults payload', async () => { + const onAdded = vi.fn(); + const onClose = vi.fn(); + const { calls } = mockApi(); + render( + + ); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Weekends' })).toBeTruthy()); + fireEvent.change(screen.getByRole('combobox'), { target: { value: '2' } }); + fireEvent.click(screen.getByRole('button', { name: /Add to schedule/ })); + + await waitFor(() => expect(onClose).toHaveBeenCalled()); + const addCall = calls.find((call) => call.url === '/api/schedules/2/items'); + expect(addCall?.method).toBe('POST'); + expect(addCall?.body).toEqual(expectedShowPayload); + expect(onAdded).toHaveBeenCalledWith('Weekends'); + }); + + // The server validator (ProgramScheduleItemCommandBase.CollectionTypeMustBeValid) only accepts + // shows / seasons / artists as per-media-item schedule items; a movie must hit the defensive + // "can't be added" path instead of POSTing a payload the server would 422. + it('refuses a non-schedulable kind (movie) without posting', async () => { + const { calls } = mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByText(/can’t be added to a schedule/)).toBeTruthy()); + const submit = screen.getByRole('button', { name: /Add to schedule/ }); + expect(submit).toHaveProperty('disabled', true); + fireEvent.click(submit); + expect(calls.some((call) => call.method === 'POST')).toBe(false); + }); + + it('maps an Artist item to the Artist collection type', async () => { + const { calls } = mockApi(); + render( {}} open />); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Weekdays' })).toBeTruthy()); + fireEvent.click(screen.getByRole('button', { name: /Add to schedule/ })); + + await waitFor(() => expect(calls.some((call) => call.url === '/api/schedules/1/items')).toBe(true)); + const addCall = calls.find((call) => call.url === '/api/schedules/1/items'); + expect(addCall?.body).toMatchObject({ collectionType: 'Artist', mediaItemId: 7 }); + }); +}); diff --git a/web/src/media/addTo/AddToScheduleDialog.tsx b/web/src/media/addTo/AddToScheduleDialog.tsx new file mode 100644 index 000000000..c0cf444c5 --- /dev/null +++ b/web/src/media/addTo/AddToScheduleDialog.tsx @@ -0,0 +1,175 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Plus } from 'lucide-react'; +import { Button, Dialog, Select, Spinner } from '../../components'; +import { + addScheduleItem, + getSchedules, + type LibraryBrowseMediaType, + type ProgramSchedule +} from '../../api'; +import { ApiError } from '../../api/client'; +import { collectionTypeForMediaType, scheduleItemRequestForMediaItem } from './scheduleItem'; + +export interface AddToScheduleItem { + mediaType: LibraryBrowseMediaType; + id: number; + title: string; +} + +export interface AddToScheduleDialogProps { + open: boolean; + onClose: () => void; + item: AddToScheduleItem; + onAdded?: (scheduleName: string) => void; +} + +function messageFromError(error: unknown, fallback: string): string { + if (error instanceof ApiError) { + return error.detail ?? error.message; + } + + if (error instanceof Error) { + return error.message; + } + + return fallback; +} + +export function AddToScheduleDialog(props: AddToScheduleDialogProps) { + if (!props.open) { + return null; + } + + return ; +} + +function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialogProps) { + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(null); + const [schedules, setSchedules] = useState([]); + const [selected, setSelected] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [submitError, setSubmitError] = useState(null); + const activeRef = useRef(true); + + useEffect(() => { + activeRef.current = true; + + return () => { + activeRef.current = false; + }; + }, []); + + const load = useCallback(() => { + getSchedules() + .then((result) => { + if (!activeRef.current) { + return; + } + + setSchedules(result); + setSelected(result.length > 0 ? String(result[0].id) : ''); + setLoadError(null); + setLoading(false); + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setLoadError(messageFromError(error, 'Unable to load schedules')); + setLoading(false); + }); + }, []); + + useEffect(() => { + load(); + }, [load]); + + const collectionType = collectionTypeForMediaType(item.mediaType); + const canSubmit = !submitting && selected !== '' && collectionType !== null; + + const submit = () => { + if (!canSubmit || collectionType === null) { + return; + } + + setSubmitting(true); + setSubmitError(null); + + const scheduleId = Number(selected); + const name = schedules.find((schedule) => String(schedule.id) === selected)?.name ?? 'schedule'; + const payload = scheduleItemRequestForMediaItem(collectionType, item.id); + + addScheduleItem(scheduleId, payload) + .then(() => { + if (!activeRef.current) { + return; + } + + onAdded?.(name); + onClose(); + }) + .catch((error: unknown) => { + if (!activeRef.current) { + return; + } + + setSubmitError(messageFromError(error, 'Unable to add to schedule')); + setSubmitting(false); + }); + }; + + return ( + + + + + } + onClose={onClose} + open + title={`Add “${item.title}” to schedule`} + width={460} + > + {loading ? ( +
+ +
+ ) : loadError ? ( + + {loadError} + + ) : collectionType === null ? ( +

This item kind can’t be added to a schedule.

+ ) : schedules.length === 0 ? ( +

No schedules exist yet. Create one first.

+ ) : ( +
+ setSelected(event.target.value)} + options={options} + value={selected} + /> + {isNew && ( + setNewName(event.target.value)} + placeholder="Smart collection name" + value={newName} + /> + )} + {submitError && ( + + {submitError} + + )} +
+ )} +
+ ); +} diff --git a/web/src/media/addTo/index.ts b/web/src/media/addTo/index.ts new file mode 100644 index 000000000..93d69aef5 --- /dev/null +++ b/web/src/media/addTo/index.ts @@ -0,0 +1,6 @@ +export { AddToCollectionDialog, type AddToCollectionDialogProps } from './AddToCollectionDialog'; +export { AddToPlaylistDialog, type AddToPlaylistDialogProps } from './AddToPlaylistDialog'; +export { AddToScheduleDialog, type AddToScheduleDialogProps, type AddToScheduleItem } from './AddToScheduleDialog'; +export { AddToMenu, type AddToMenuProps, type AddToTarget } from './AddToMenu'; +export { SaveAsSmartCollectionDialog, type SaveAsSmartCollectionDialogProps } from './SaveAsSmartCollectionDialog'; +export { collectionTypeForMediaType, scheduleItemRequestForMediaItem, type AddToItems } from './scheduleItem'; diff --git a/web/src/media/addTo/scheduleItem.ts b/web/src/media/addTo/scheduleItem.ts new file mode 100644 index 000000000..2ea111596 --- /dev/null +++ b/web/src/media/addTo/scheduleItem.ts @@ -0,0 +1,75 @@ +import type { components } from '../../api/generated/v1'; +import type { AddItemsToCollectionRequest, LibraryBrowseItem, LibraryBrowseMediaType, ScheduleItemRequest } from '../../api'; + +type CollectionType = components['schemas']['CollectionType']; + +// The union the Add-to dialogs accept for the items they operate on: either a set of browse +// items (bucketed by kind via toAddItemsRequest) or a pre-built request body (the query-based +// "Add all results" flow supplies this so callers never page through every result). +export type AddToItems = LibraryBrowseItem[] | { requestOverride: AddItemsToCollectionRequest }; + +// Only shows, seasons and artists are schedulable as a single media item. This matches both +// Blazor's AddProgramScheduleItem.ForMediaItem call sites (only the show / season / artist list +// pages offer "Add to schedule") and the server validator +// ProgramScheduleItemCommandBase.CollectionTypeMustBeValid, which 422s every other +// per-media-item CollectionType. Every other kind maps to null (not schedulable). +const MEDIA_TYPE_TO_COLLECTION_TYPE: Partial> = { + Artist: 'Artist', + TelevisionSeason: 'TelevisionSeason', + TelevisionShow: 'TelevisionShow' +}; + +export function collectionTypeForMediaType(mediaType: LibraryBrowseMediaType): CollectionType | null { + return MEDIA_TYPE_TO_COLLECTION_TYPE[mediaType] ?? null; +} + +// Builds the ScheduleItemRequest body for adding a single media item to a schedule, replicating +// the defaults of AddProgramScheduleItem.ForMediaItem +// (ErsatzTV.Application/ProgramSchedules/Commands/AddProgramScheduleItem.cs:48-87): StartType.Dynamic, +// PlayoutMode.One, PlaybackOrder.Shuffle, MarathonGroupBy.None, FillWithGroupMode.None, +// MultipleMode.Count, TailMode.None, GuideMode.Normal, all collection/filler ids null, empty +// watermark/graphics lists — with CollectionType + MediaItemId set for this item. +export function scheduleItemRequestForMediaItem( + collectionType: CollectionType, + mediaItemId: number +): ScheduleItemRequest { + return { + startType: 'Dynamic', + startTime: null, + fixedStartTimeBehavior: null, + playoutMode: 'One', + collectionType, + collectionId: null, + multiCollectionId: null, + smartCollectionId: null, + rerunCollectionId: null, + mediaItemId, + playlistId: null, + searchTitle: null, + searchQuery: null, + playbackOrder: 'Shuffle', + marathonGroupBy: 'None', + marathonShuffleGroups: false, + marathonShuffleItems: false, + marathonBatchSize: null, + fillWithGroupMode: 'None', + multipleMode: 'Count', + multipleCount: null, + playoutDuration: null, + tailMode: 'None', + discardToFillAttempts: null, + customTitle: null, + guideMode: 'Normal', + preRollFillerId: null, + midRollFillerId: null, + postRollFillerId: null, + tailFillerId: null, + fallbackFillerId: null, + watermarkIds: [], + graphicsElementIds: [], + preferredAudioLanguageCode: null, + preferredAudioTitle: null, + preferredSubtitleLanguageCode: null, + subtitleMode: null + }; +} diff --git a/web/src/screens/MediaBrowseScreen.test.tsx b/web/src/screens/MediaBrowseScreen.test.tsx new file mode 100644 index 000000000..50812c246 --- /dev/null +++ b/web/src/screens/MediaBrowseScreen.test.tsx @@ -0,0 +1,147 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { MediaBrowseScreen } from './MediaBrowseScreen'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +const items = [ + { artwork: '', collectionType: 'Movie', id: 1, mediaType: 'Movie', title: 'Blade Runner' }, + { artwork: '', collectionType: 'Movie', id: 2, mediaType: 'Movie', title: 'Alien' } +]; + +function mockFetch() { + return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { + const url = input.toString(); + if (url.startsWith('/api/library/browse')) { + return Promise.resolve(jsonResponse({ page: items, totalCount: items.length })); + } + if (url === '/api/collections') { + return Promise.resolve(jsonResponse([{ collectionType: 'Collection', id: 7, name: 'Favorites', useCustomPlaybackOrder: false }])); + } + if (url === '/api/playlists/groups') { + return Promise.resolve(jsonResponse([])); + } + if (url === '/api/schedules') { + return Promise.resolve(jsonResponse([])); + } + return Promise.resolve(new Response(null, { status: 204 })); + }); +} + +describe('MediaBrowseScreen', () => { + beforeEach(() => { + window.localStorage.clear(); + window.history.replaceState(null, '', '/app/media?kind=movies'); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('renders a per-tile Add-to menu on every card', async () => { + mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + expect(screen.getAllByRole('button', { name: 'Add to…' })).toHaveLength(items.length); + }); + + it('supports select mode and adds the selected items to a collection', async () => { + const fetchSpy = mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + + // No selection bar until we enter select mode and pick something. + expect(screen.queryByText(/selected/)).toBeNull(); + + fireEvent.click(screen.getByRole('button', { name: 'Select' })); + fireEvent.click(screen.getByText('Blade Runner')); + expect(screen.getByText('1 selected')).toBeInTheDocument(); + + fireEvent.click(screen.getByText('Alien')); + expect(screen.getByText('2 selected')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /Add to collection/ })); + await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument()); + + // The first existing collection (Favorites, id 7) is preselected — just submit. + await waitFor(() => expect(screen.getByRole('option', { name: 'Favorites' })).toBeTruthy()); + fireEvent.click(screen.getAllByRole('button', { name: /Add to collection/ }).at(-1)!); + + await waitFor(() => { + const addCall = fetchSpy.mock.calls.find( + ([url, init]) => String(url) === '/api/collections/7/items' && (init as RequestInit | undefined)?.method === 'POST' + ); + expect(addCall).toBeTruthy(); + const body = JSON.parse(String((addCall![1] as RequestInit).body)); + expect(body.movieIds).toEqual([1, 2]); + }); + }); + + it('shows a success toast after a bulk add', async () => { + mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + fireEvent.click(screen.getByRole('button', { name: 'Select' })); + fireEvent.click(screen.getByText('Blade Runner')); + fireEvent.click(screen.getByRole('button', { name: /Add to collection/ })); + + await waitFor(() => expect(screen.getByRole('option', { name: 'Favorites' })).toBeTruthy()); + fireEvent.click(screen.getAllByRole('button', { name: /Add to collection/ }).at(-1)!); + + await waitFor(() => expect(screen.getByText('Added to “Favorites”')).toBeInTheDocument()); + // Selection cleared alongside the toast. + expect(screen.queryByText(/selected/)).toBeNull(); + }); + + it('hides the per-tile Add-to menu while select mode is on', async () => { + mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + expect(screen.getAllByRole('button', { name: 'Add to…' })).toHaveLength(items.length); + + fireEvent.click(screen.getByRole('button', { name: 'Select' })); + expect(screen.queryByRole('button', { name: 'Add to…' })).toBeNull(); + + fireEvent.click(screen.getByRole('button', { name: 'Done' })); + expect(screen.getAllByRole('button', { name: 'Add to…' })).toHaveLength(items.length); + }); + + it('offers a Seasons kind that browses TelevisionSeason items', async () => { + const fetchSpy = mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + expect(screen.getByRole('option', { name: 'Seasons' })).toBeTruthy(); + + fireEvent.change(screen.getByRole('combobox'), { target: { value: 'seasons' } }); + + await waitFor(() => { + const seasonCall = fetchSpy.mock.calls.find(([url]) => + String(url).startsWith('/api/library/browse') && String(url).includes('mediaType=TelevisionSeason') + ); + expect(seasonCall).toBeTruthy(); + }); + }); + + it('selects every loaded item with Select all on page', async () => { + mockFetch(); + render(); + + await waitFor(() => expect(screen.getByText('Blade Runner')).toBeInTheDocument()); + + fireEvent.click(screen.getByRole('button', { name: 'Select' })); + fireEvent.click(screen.getByText('Blade Runner')); + fireEvent.click(screen.getByRole('button', { name: 'Select all on page' })); + expect(screen.getByText('2 selected')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Clear selection' })); + expect(screen.queryByText(/selected/)).toBeNull(); + }); +}); diff --git a/web/src/screens/MediaBrowseScreen.tsx b/web/src/screens/MediaBrowseScreen.tsx index 5606437c1..876b9b7cf 100644 --- a/web/src/screens/MediaBrowseScreen.tsx +++ b/web/src/screens/MediaBrowseScreen.tsx @@ -1,16 +1,32 @@ import { useCallback, useEffect, useRef, useState } from 'react'; -import { ChevronLeft, ChevronRight, FolderTree, Info, RefreshCw, Search, TriangleAlert } from 'lucide-react'; -import { Button, Card, IconButton, Input, Select, Spinner } from '../components'; +import { + ChevronLeft, + ChevronRight, + FolderPlus, + FolderTree, + Info, + ListChecks, + ListVideo, + RefreshCw, + Search, + TriangleAlert +} from 'lucide-react'; +import { Button, Card, IconButton, Input, Select, Spinner, Toast } from '../components'; import { getLibraryBrowseItems, messageFromLibraryBrowseError, type LibraryBrowseItem, type LibraryBrowseMediaType } from '../api'; +import { AddToCollectionDialog, AddToMenu, AddToPlaylistDialog } from '../media/addTo'; import { MediaPosterCard } from '../media/MediaPosterCard'; import { mediaDetailPath } from '../media/mediaKinds'; import { navigateToPath } from '../routing'; +function itemKey(item: LibraryBrowseItem): string { + return `${item.mediaType}-${item.id}`; +} + const PAGE_SIZE = 100; interface MediaKind { @@ -19,10 +35,12 @@ interface MediaKind { mediaType: LibraryBrowseMediaType; } -// Matches the legacy Blazor media IA (no top-level Seasons page; seasons live under a show). +// Matches the legacy Blazor media IA, plus a top-level Seasons kind (Blazor only reaches seasons +// through a show drill-in; the browse endpoint supports them directly, so we expose them). const KINDS: MediaKind[] = [ { slug: 'movies', label: 'Movies', mediaType: 'Movie' }, { slug: 'shows', label: 'TV Shows', mediaType: 'TelevisionShow' }, + { slug: 'seasons', label: 'Seasons', mediaType: 'TelevisionSeason' }, { slug: 'episodes', label: 'Episodes', mediaType: 'Episode' }, { slug: 'artists', label: 'Artists', mediaType: 'Artist' }, { slug: 'music-videos', label: 'Music Videos', mediaType: 'MusicVideo' }, @@ -41,6 +59,8 @@ type BrowseState = | { items: []; error: string; status: 'error'; totalCount: 0 } | { items: []; error: null; status: 'loading'; totalCount: 0 }; +type Notice = { tone: 'ok' | 'error'; message: string }; + export function MediaBrowseScreen() { const params = new URLSearchParams(window.location.search); const initialKind = kindFromSlug(params.get('kind')); @@ -51,8 +71,15 @@ export function MediaBrowseScreen() { const [query, setQuery] = useState(initialQuery); const [pageNum, setPageNum] = useState(0); const [state, setState] = useState({ items: [], error: null, status: 'loading', totalCount: 0 }); + // Screen-level multi-select. Deliberately opt-in (a "Select" toggle) rather than Blazor's + // always-on selection, so the default browse experience stays a plain drill-in. + const [selectMode, setSelectMode] = useState(false); + const [selected, setSelected] = useState>(new Map()); + const [bulkDialog, setBulkDialog] = useState<'collection' | 'playlist' | null>(null); + const [notice, setNotice] = useState(null); const activeRef = useRef(true); const seqRef = useRef(0); + const lastQueryRef = useRef(initialQuery.trim()); useEffect(() => { activeRef.current = true; @@ -62,10 +89,18 @@ export function MediaBrowseScreen() { }, []); // Debounce the per-kind free-text box; it composes straight into the browse (Lucene) query. + // The no-change guard matters: this timer also fires once on mount (and after kind changes), + // and must not reset the page or wipe an in-progress selection when the query is unchanged. useEffect(() => { const handle = window.setTimeout(() => { + const next = queryInput.trim(); + if (lastQueryRef.current === next) { + return; + } + lastQueryRef.current = next; setPageNum(0); - setQuery(queryInput.trim()); + setQuery(next); + setSelected(new Map()); }, 300); return () => window.clearTimeout(handle); @@ -96,6 +131,8 @@ export function MediaBrowseScreen() { setPageNum(0); setQueryInput(''); setQuery(''); + lastQueryRef.current = ''; + setSelected(new Map()); // Keep the URL shareable/back-navigable without remounting the whole screen. window.history.replaceState(null, '', `/app/media?kind=${next.slug}`); }; @@ -105,6 +142,47 @@ export function MediaBrowseScreen() { load(); }; + const goToPage = (updater: (current: number) => number) => { + setPageNum(updater); + setSelected(new Map()); + }; + + const toggleSelectMode = () => { + setSelectMode((on) => !on); + setSelected(new Map()); + }; + + const toggleSelect = (item: LibraryBrowseItem) => { + setSelected((current) => { + const next = new Map(current); + const key = itemKey(item); + if (next.has(key)) { + next.delete(key); + } else { + next.set(key, item); + } + return next; + }); + }; + + const selectAllOnPage = () => { + setSelected((current) => { + const next = new Map(current); + for (const item of state.items) { + next.set(itemKey(item), item); + } + return next; + }); + }; + + const clearSelection = () => setSelected(new Map()); + + const onBulkAdded = (name: string) => { + clearSelection(); + setNotice({ tone: 'ok', message: `Added to “${name}”` }); + }; + + const selectedItems = Array.from(selected.values()); const totalPages = state.status === 'success' ? Math.max(1, Math.ceil(state.totalCount / PAGE_SIZE)) : 1; return ( @@ -134,6 +212,14 @@ export function MediaBrowseScreen() { Folder Browser )} +
+ {selected.size > 0 && ( +
+ {selected.size} selected + + + + + +
+ )} + + {notice && setNotice(null)} tone={notice.tone} />} + + setBulkDialog(null)} + open={bulkDialog === 'collection'} + /> + setBulkDialog(null)} + open={bulkDialog === 'playlist'} + /> + {state.status === 'error' && (