Merge pull request 'feat: shared Add-to layer — search + media mutation surface (#208, #209)' (#216) from feat/208-209-add-to into main
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled
Build ErsatzTV Image / Docs update reminder (push) Has been cancelled
Build ErsatzTV Image / Build & test (.NET) (push) Has been cancelled
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Has been cancelled
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled
Build ErsatzTV Image / Docs update reminder (push) Has been cancelled
Build ErsatzTV Image / Build & test (.NET) (push) Has been cancelled
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Has been cancelled
This commit was merged in pull request #216.
This commit is contained in:
@@ -84,14 +84,20 @@ public class AddItemsToPlaylistHandler : IRequestHandler<AddItemsToPlaylist, Eit
|
||||
await ValidateEpisodes(request))
|
||||
.Apply((collection, _, _, _, _) => collection);
|
||||
|
||||
private static Task<Validation<BaseError, Playlist>> PlaylistMustExist(
|
||||
private static async Task<Validation<BaseError, Playlist>> PlaylistMustExist(
|
||||
TvContext dbContext,
|
||||
AddItemsToPlaylist request,
|
||||
CancellationToken cancellationToken) =>
|
||||
dbContext.Playlists
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<Playlist> maybePlaylist = await dbContext.Playlists
|
||||
.Include(c => c.Items)
|
||||
.SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken)
|
||||
.Map(o => o.ToValidation<BaseError>("Playlist does not exist."));
|
||||
.SelectOneAsync(c => c.Id, c => c.Id == request.PlaylistId, cancellationToken);
|
||||
|
||||
return maybePlaylist.ToValidation<BaseError>("Playlist does not exist.")
|
||||
.Bind(playlist => playlist.IsSystem
|
||||
? BaseError.New("Cannot add items to system (generated) playlist")
|
||||
: Success<BaseError, Playlist>(playlist));
|
||||
}
|
||||
|
||||
private Task<Validation<BaseError, Unit>> ValidateMovies(AddItemsToPlaylist request) =>
|
||||
_movieRepository.AllMoviesExist(request.MovieIds)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace ErsatzTV.Core.Api.Search;
|
||||
|
||||
public record SearchResultAllItemsResponseModel(
|
||||
List<int> MovieIds,
|
||||
List<int> ShowIds,
|
||||
List<int> SeasonIds,
|
||||
List<int> EpisodeIds,
|
||||
List<int> ArtistIds,
|
||||
List<int> MusicVideoIds,
|
||||
List<int> OtherVideoIds,
|
||||
List<int> SongIds,
|
||||
List<int> ImageIds,
|
||||
List<int> RemoteStreamIds);
|
||||
@@ -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<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AddItems_Should_Return_204_And_Map_Request()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "Kids", false)));
|
||||
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Right<BaseError, Unit>(Unit.Default));
|
||||
|
||||
IActionResult result = await _controller.AddItems(
|
||||
4,
|
||||
new AddItemsToPlaylistRequest([1, 2], [3], [], [], [], [], [], [], [], []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NoContentResult>();
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<AddItemsToPlaylist>(c =>
|
||||
c.PlaylistId == 4 &&
|
||||
c.MovieIds.SequenceEqual(new List<int> { 1, 2 }) &&
|
||||
c.ShowIds.SequenceEqual(new List<int> { 3 })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AddItems_Should_Return_404_When_Playlist_Missing()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<PlaylistViewModel>.None);
|
||||
|
||||
IActionResult result = await _controller.AddItems(
|
||||
4,
|
||||
new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<NotFoundObjectResult>();
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AddItems_Should_Return_422_On_System_Playlist()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "System", true)));
|
||||
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, Unit>(BaseError.New("Cannot add items to system (generated) playlist")));
|
||||
|
||||
IActionResult result = await _controller.AddItems(
|
||||
4,
|
||||
new AddItemsToPlaylistRequest([1], [], [], [], [], [], [], [], [], []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AddItems_Should_Return_422_On_Validation_Error()
|
||||
{
|
||||
_mediator.Send(Arg.Any<GetPlaylistById>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Option<PlaylistViewModel>.Some(new PlaylistViewModel(4, 1, "Kids", false)));
|
||||
_mediator.Send(Arg.Any<AddItemsToPlaylist>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Left<BaseError, Unit>(BaseError.New("Movie does not exist")));
|
||||
|
||||
IActionResult result = await _controller.AddItems(
|
||||
4,
|
||||
new AddItemsToPlaylistRequest([999], [], [], [], [], [], [], [], [], []),
|
||||
CancellationToken.None);
|
||||
|
||||
result.ShouldBeOfType<UnprocessableEntityObjectResult>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Preview_Should_Return_200_And_Format_Times()
|
||||
{
|
||||
|
||||
@@ -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<HttpGetAttribute>().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<UnprocessableEntityObjectResult>();
|
||||
unprocessable.StatusCode.ShouldBe(422);
|
||||
await _mediator.DidNotReceive().Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SearchAllItems_Should_Map_Id_Lists()
|
||||
{
|
||||
_mediator.Send(Arg.Any<QuerySearchIndexAllItems>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new SearchResultAllItemsViewModel(
|
||||
[1, 2],
|
||||
[3],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[]));
|
||||
|
||||
IActionResult result = await _controller.SearchAllItems("star", CancellationToken.None);
|
||||
|
||||
var body = result.ShouldBeOfType<OkObjectResult>().Value
|
||||
.ShouldBeOfType<SearchResultAllItemsResponseModel>();
|
||||
body.MovieIds.ShouldBe(new List<int> { 1, 2 });
|
||||
body.ShowIds.ShouldBe(new List<int> { 3 });
|
||||
await _mediator.Received(1).Send(
|
||||
Arg.Is<QuerySearchIndexAllItems>(q => q.Query == "star"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SearchCollections_Should_Map_To_Picker_Options()
|
||||
{
|
||||
|
||||
@@ -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<IActionResult> AddItems(
|
||||
int id,
|
||||
[Required] [FromBody] AddItemsToPlaylistRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Option<PlaylistViewModel> 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<BaseError, Unit> 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")]
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using ErsatzTV.Application.MediaCollections;
|
||||
|
||||
namespace ErsatzTV.Controllers.Api.Requests;
|
||||
|
||||
public record AddItemsToPlaylistRequest(
|
||||
List<int> MovieIds,
|
||||
List<int> ShowIds,
|
||||
List<int> SeasonIds,
|
||||
List<int> EpisodeIds,
|
||||
List<int> ArtistIds,
|
||||
List<int> MusicVideoIds,
|
||||
List<int> OtherVideoIds,
|
||||
List<int> SongIds,
|
||||
List<int> ImageIds,
|
||||
List<int> RemoteStreamIds)
|
||||
{
|
||||
public AddItemsToPlaylist ToCommand(int playlistId) =>
|
||||
new(
|
||||
playlistId,
|
||||
MovieIds ?? [],
|
||||
ShowIds ?? [],
|
||||
SeasonIds ?? [],
|
||||
EpisodeIds ?? [],
|
||||
ArtistIds ?? [],
|
||||
MusicVideoIds ?? [],
|
||||
OtherVideoIds ?? [],
|
||||
SongIds ?? [],
|
||||
ImageIds ?? [],
|
||||
RemoteStreamIds ?? []);
|
||||
}
|
||||
@@ -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<IActionResult> 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);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)"
|
||||
|
||||
Vendored
+24
@@ -20,6 +20,18 @@ export interface components {
|
||||
"songIds": null | Array<number>;
|
||||
"imageIds": null | Array<number>;
|
||||
"remoteStreamIds": null | Array<number>;
|
||||
};
|
||||
"AddItemsToPlaylistRequest": {
|
||||
"movieIds": null | Array<number>;
|
||||
"showIds": null | Array<number>;
|
||||
"seasonIds": null | Array<number>;
|
||||
"episodeIds": null | Array<number>;
|
||||
"artistIds": null | Array<number>;
|
||||
"musicVideoIds": null | Array<number>;
|
||||
"otherVideoIds": null | Array<number>;
|
||||
"songIds": null | Array<number>;
|
||||
"imageIds": null | Array<number>;
|
||||
"remoteStreamIds": null | Array<number>;
|
||||
};
|
||||
"AddTraktListRequest": {
|
||||
"url": null | string;
|
||||
@@ -1313,6 +1325,18 @@ export interface components {
|
||||
"SchedulingPickerOptionResponseModel": {
|
||||
"id": number;
|
||||
"name": string;
|
||||
};
|
||||
"SearchResultAllItemsResponseModel": {
|
||||
"movieIds": null | Array<number>;
|
||||
"showIds": null | Array<number>;
|
||||
"seasonIds": null | Array<number>;
|
||||
"episodeIds": null | Array<number>;
|
||||
"artistIds": null | Array<number>;
|
||||
"musicVideoIds": null | Array<number>;
|
||||
"otherVideoIds": null | Array<number>;
|
||||
"songIds": null | Array<number>;
|
||||
"imageIds": null | Array<number>;
|
||||
"remoteStreamIds": null | Array<number>;
|
||||
};
|
||||
"SearchResultGroupResponseModel": {
|
||||
"totalCount": number;
|
||||
|
||||
@@ -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<typeof vi.spyOn>) {
|
||||
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' });
|
||||
});
|
||||
});
|
||||
@@ -51,6 +51,21 @@ export function scanLibrary(libraryId: number): Promise<void> {
|
||||
return request<void>(`/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<void> {
|
||||
return request<void>(`/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
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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<PlaylistP
|
||||
return request<PlaylistPreviewItem[]>('/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<void> {
|
||||
return request<void>(`/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;
|
||||
|
||||
@@ -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: []
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<Search
|
||||
return request<SearchResults>(`/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<SearchAllItemIds> {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('query', query);
|
||||
return request<SearchAllItemIds>(`/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;
|
||||
|
||||
@@ -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(<MediaPosterCard item={movieItem} />);
|
||||
expect(screen.getByText('Blade Runner')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('calls onOpen when the card is clicked', () => {
|
||||
const onOpen = vi.fn();
|
||||
render(<MediaPosterCard item={movieItem} onOpen={onOpen} />);
|
||||
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(
|
||||
<MediaPosterCard
|
||||
actions={
|
||||
<button onClick={onAction} type="button">
|
||||
Act
|
||||
</button>
|
||||
}
|
||||
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(
|
||||
<MediaPosterCard
|
||||
actions={
|
||||
<button onClick={onAction} type="button">
|
||||
Act
|
||||
</button>
|
||||
}
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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({
|
||||
<span className="ctv-media-card-icon" style={{ color: `hsl(${hue} 30% 68%)` }}>
|
||||
<Icon size={15} aria-hidden="true" />
|
||||
</span>
|
||||
{actions && (
|
||||
<div
|
||||
className="ctv-media-card-actions"
|
||||
// Keep the actions slot's own clicks/keys from bubbling up to the card's
|
||||
// open/select gesture.
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onKeyDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
{actions}
|
||||
</div>
|
||||
)}
|
||||
{selected && <div className="ctv-media-card-check">✓</div>}
|
||||
</div>
|
||||
<div className="ctv-media-card-body">
|
||||
|
||||
@@ -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(<AddToCollectionDialog items={[movieItem]} onClose={() => {}} open={false} />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('loads existing collections into the select', async () => {
|
||||
mockApi();
|
||||
render(<AddToCollectionDialog items={[movieItem]} onClose={() => {}} 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(<AddToCollectionDialog items={[movieItem]} onAdded={onAdded} onClose={onClose} open />);
|
||||
|
||||
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(<AddToCollectionDialog items={[movieItem]} onAdded={onAdded} onClose={() => {}} 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(<AddToCollectionDialog items={{ requestOverride: override }} onClose={() => {}} 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);
|
||||
});
|
||||
});
|
||||
@@ -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 <AddToCollectionDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToCollectionDialogBody({ onClose, items, onAdded }: AddToCollectionDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [collections, setCollections] = useState<MediaCollection[]>([]);
|
||||
const [selected, setSelected] = useState<string>(NEW_COLLECTION);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(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 (
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button disabled={submitting} onClick={onClose} variant="secondary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSubmit}
|
||||
loading={submitting}
|
||||
onClick={submit}
|
||||
startIcon={<Plus aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
Add to collection
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
open
|
||||
title="Add to collection"
|
||||
width={460}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{loadError}
|
||||
</span>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Select
|
||||
label="Collection"
|
||||
onChange={(event) => setSelected(event.target.value)}
|
||||
options={options}
|
||||
value={selected}
|
||||
/>
|
||||
{isNew && (
|
||||
<Input
|
||||
label="New collection name"
|
||||
onChange={(event) => setNewName(event.target.value)}
|
||||
placeholder="Collection name"
|
||||
value={newName}
|
||||
/>
|
||||
)}
|
||||
{submitError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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(<AddToMenu items={[showItem]} />);
|
||||
|
||||
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(<AddToMenu items={[showItem, showItem]} />);
|
||||
|
||||
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(<AddToMenu items={[movieItem]} />);
|
||||
|
||||
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(<AddToMenu items={[showItem]} />);
|
||||
|
||||
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(<AddToMenu items={[movieItem]} targets={['collection']} />);
|
||||
|
||||
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(<AddToMenu items={[movieItem]} />);
|
||||
|
||||
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(<AddToMenu items={[]} />);
|
||||
expect(screen.getByRole('button', { name: 'Add to…' })).toHaveProperty('disabled', true);
|
||||
});
|
||||
});
|
||||
@@ -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<AddToTarget | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(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<HTMLButtonElement>(':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 (
|
||||
<div className="ctv-addto-menu" ref={rootRef}>
|
||||
<IconButton
|
||||
active={menuOpen}
|
||||
disabled={disabled}
|
||||
onClick={() => setMenuOpen((current) => !current)}
|
||||
size={compact ? 'sm' : 'md'}
|
||||
title="Add to…"
|
||||
variant="solid"
|
||||
>
|
||||
<Plus aria-hidden="true" size={compact ? 14 : 16} />
|
||||
</IconButton>
|
||||
{menuOpen && (
|
||||
<div className="ctv-addto-menu-popover" role="menu">
|
||||
{visibleTargets.includes('collection') && (
|
||||
<button className="ctv-addto-menu-item" onClick={() => open('collection')} role="menuitem" type="button">
|
||||
<FolderPlus aria-hidden="true" size={14} />
|
||||
Add to collection
|
||||
</button>
|
||||
)}
|
||||
{visibleTargets.includes('playlist') && (
|
||||
<button className="ctv-addto-menu-item" onClick={() => open('playlist')} role="menuitem" type="button">
|
||||
<ListVideo aria-hidden="true" size={14} />
|
||||
Add to playlist
|
||||
</button>
|
||||
)}
|
||||
{visibleTargets.includes('schedule') && (
|
||||
<button className="ctv-addto-menu-item" onClick={() => open('schedule')} role="menuitem" type="button">
|
||||
<CalendarClock aria-hidden="true" size={14} />
|
||||
Add to schedule
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AddToCollectionDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'collection'} />
|
||||
<AddToPlaylistDialog items={items} onAdded={(name) => handleAdded(`Added to “${name}”`)} onClose={closeDialog} open={dialog === 'playlist'} />
|
||||
{scheduleItem && (
|
||||
<AddToScheduleDialog
|
||||
item={{ id: scheduleItem.id, mediaType: scheduleItem.mediaType, title: scheduleItem.title }}
|
||||
onAdded={(name) => handleAdded(`Added to “${name}”`)}
|
||||
onClose={closeDialog}
|
||||
open={dialog === 'schedule'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown[]> = {
|
||||
'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(<AddToPlaylistDialog items={[showItem]} onClose={() => {}} 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(<AddToPlaylistDialog items={[showItem]} onAdded={onAdded} onClose={onClose} open />);
|
||||
|
||||
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(<AddToPlaylistDialog items={[showItem]} onClose={() => {}} 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(<AddToPlaylistDialog items={[showItem]} onClose={() => {}} 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());
|
||||
});
|
||||
});
|
||||
@@ -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 <AddToPlaylistDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToPlaylistDialogBody({ onClose, items, onAdded }: AddToPlaylistDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [groups, setGroups] = useState<PlaylistGroup[]>([]);
|
||||
const [selectedGroup, setSelectedGroup] = useState<string>('');
|
||||
const [playlists, setPlaylists] = useState<Playlist[]>([]);
|
||||
const [playlistsLoading, setPlaylistsLoading] = useState(false);
|
||||
const [selectedPlaylist, setSelectedPlaylist] = useState<string>('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(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 (
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button disabled={submitting} onClick={onClose} variant="secondary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSubmit}
|
||||
loading={submitting}
|
||||
onClick={submit}
|
||||
startIcon={<Plus aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
Add to playlist
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
open
|
||||
title="Add to playlist"
|
||||
width={460}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{loadError}
|
||||
</span>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="ctv-collections-picker-note">No playlist groups exist yet. Create one first.</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Select
|
||||
label="Playlist group"
|
||||
onChange={(event) => onGroupChange(event.target.value)}
|
||||
options={groups.map((group) => ({ value: String(group.id), label: group.name ?? `Group ${group.id}` }))}
|
||||
value={selectedGroup}
|
||||
/>
|
||||
<Select
|
||||
disabled={playlistsLoading || playlists.length === 0}
|
||||
label="Playlist"
|
||||
onChange={(event) => 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 && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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(<AddToScheduleDialog item={{ id: 42, mediaType: 'TelevisionShow', title: 'The Office' }} onClose={() => {}} 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(
|
||||
<AddToScheduleDialog
|
||||
item={{ id: 42, mediaType: 'TelevisionShow', title: 'The Office' }}
|
||||
onAdded={onAdded}
|
||||
onClose={onClose}
|
||||
open
|
||||
/>
|
||||
);
|
||||
|
||||
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(<AddToScheduleDialog item={{ id: 7, mediaType: 'Movie', title: 'Alien' }} onClose={() => {}} 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(<AddToScheduleDialog item={{ id: 7, mediaType: 'Artist', title: 'Kraftwerk' }} onClose={() => {}} 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 });
|
||||
});
|
||||
});
|
||||
@@ -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 <AddToScheduleDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function AddToScheduleDialogBody({ onClose, item, onAdded }: AddToScheduleDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [schedules, setSchedules] = useState<ProgramSchedule[]>([]);
|
||||
const [selected, setSelected] = useState<string>('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(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 (
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button disabled={submitting} onClick={onClose} variant="secondary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSubmit}
|
||||
loading={submitting}
|
||||
onClick={submit}
|
||||
startIcon={<Plus aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
Add to schedule
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
open
|
||||
title={`Add “${item.title}” to schedule`}
|
||||
width={460}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{loadError}
|
||||
</span>
|
||||
) : collectionType === null ? (
|
||||
<p className="ctv-collections-picker-note">This item kind can’t be added to a schedule.</p>
|
||||
) : schedules.length === 0 ? (
|
||||
<p className="ctv-collections-picker-note">No schedules exist yet. Create one first.</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Select
|
||||
label="Schedule"
|
||||
onChange={(event) => setSelected(event.target.value)}
|
||||
options={schedules.map((schedule) => ({ value: String(schedule.id), label: schedule.name ?? `Schedule ${schedule.id}` }))}
|
||||
value={selected}
|
||||
/>
|
||||
{submitError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { SaveAsSmartCollectionDialog } from './SaveAsSmartCollectionDialog';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
const smartCollections = [
|
||||
{ id: 5, name: 'Recent Sci-Fi', query: 'genre:"Science Fiction"' },
|
||||
{ id: 6, name: 'Kids', query: 'tag:kids' }
|
||||
];
|
||||
|
||||
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/smart-collections' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse(smartCollections));
|
||||
}
|
||||
|
||||
if (url === '/api/smart-collections' && method === 'POST') {
|
||||
const name = (body as { name: string }).name;
|
||||
return Promise.resolve(jsonResponse({ id: 42, name, query: (body as { query: string }).query }, 201));
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
|
||||
return { calls };
|
||||
}
|
||||
|
||||
describe('SaveAsSmartCollectionDialog', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('renders nothing when closed', () => {
|
||||
mockApi();
|
||||
const { container } = render(
|
||||
<SaveAsSmartCollectionDialog onClose={() => {}} open={false} query="star trek" />
|
||||
);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('loads existing smart collections plus the new option', async () => {
|
||||
mockApi();
|
||||
render(<SaveAsSmartCollectionDialog onClose={() => {}} open query="star trek" />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('option', { name: 'Recent Sci-Fi' })).toBeTruthy());
|
||||
expect(screen.getByRole('option', { name: 'Kids' })).toBeTruthy();
|
||||
expect(screen.getByRole('option', { name: '(New smart collection)' })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('creates a new smart collection with the current query', async () => {
|
||||
const onSaved = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
const { calls } = mockApi();
|
||||
render(<SaveAsSmartCollectionDialog onClose={onClose} onSaved={onSaved} open query="star trek" />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('option', { name: '(New smart collection)' })).toBeTruthy());
|
||||
fireEvent.change(screen.getByPlaceholderText('Smart collection name'), { target: { value: 'Trek' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save as smart collection/ }));
|
||||
|
||||
await waitFor(() => expect(onSaved).toHaveBeenCalledWith('Trek'));
|
||||
const createCall = calls.find((call) => call.url === '/api/smart-collections' && call.method === 'POST');
|
||||
expect(createCall?.body).toEqual({ name: 'Trek', query: 'star trek' });
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates an existing smart collection query when one is chosen', async () => {
|
||||
const onSaved = vi.fn();
|
||||
const { calls } = mockApi();
|
||||
render(<SaveAsSmartCollectionDialog onClose={() => {}} onSaved={onSaved} open query="star trek" />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('option', { name: 'Kids' })).toBeTruthy());
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: '6' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save as smart collection/ }));
|
||||
|
||||
await waitFor(() => expect(onSaved).toHaveBeenCalledWith('Kids'));
|
||||
const updateCall = calls.find((call) => call.url === '/api/smart-collections/6');
|
||||
expect(updateCall?.method).toBe('PUT');
|
||||
expect(updateCall?.body).toEqual({ name: 'Kids', query: 'star trek' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Save } from 'lucide-react';
|
||||
import { Button, Dialog, Input, Select, Spinner } from '../../components';
|
||||
import {
|
||||
createSmartCollection,
|
||||
getSmartCollections,
|
||||
messageFromCollectionError,
|
||||
updateSmartCollection,
|
||||
type SmartCollection
|
||||
} from '../../api';
|
||||
|
||||
export interface SaveAsSmartCollectionDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
// The search query the saved smart collection will store.
|
||||
query: string;
|
||||
onSaved?: (collectionName: string) => void;
|
||||
}
|
||||
|
||||
const NEW_COLLECTION = '__new__';
|
||||
|
||||
export function SaveAsSmartCollectionDialog(props: SaveAsSmartCollectionDialogProps) {
|
||||
if (!props.open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <SaveAsSmartCollectionDialogBody {...props} />;
|
||||
}
|
||||
|
||||
function SaveAsSmartCollectionDialogBody({ onClose, query, onSaved }: SaveAsSmartCollectionDialogProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [collections, setCollections] = useState<SmartCollection[]>([]);
|
||||
const [selected, setSelected] = useState<string>(NEW_COLLECTION);
|
||||
const [newName, setNewName] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const activeRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = true;
|
||||
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const load = useCallback(() => {
|
||||
getSmartCollections()
|
||||
.then((result) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCollections(result);
|
||||
setSelected(NEW_COLLECTION);
|
||||
setLoadError(null);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadError(messageFromCollectionError(error, 'Unable to load smart collections'));
|
||||
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);
|
||||
|
||||
// New: create with the query baked in. Existing: overwrite its query (keeping its name).
|
||||
const save: Promise<string> = isNew
|
||||
? createSmartCollection({ name: newName.trim(), query }).then(
|
||||
(collection) => collection.name ?? newName.trim()
|
||||
)
|
||||
: (() => {
|
||||
const existing = collections.find((collection) => String(collection.id) === selected);
|
||||
const name = existing?.name ?? 'smart collection';
|
||||
return updateSmartCollection(Number(selected), { name, query }).then(() => name);
|
||||
})();
|
||||
|
||||
save
|
||||
.then((name) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
onSaved?.(name);
|
||||
onClose();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitError(messageFromCollectionError(error, 'Unable to save smart collection'));
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
|
||||
const options = [
|
||||
{ value: NEW_COLLECTION, label: '(New smart collection)' },
|
||||
...collections.map((collection) => ({
|
||||
value: String(collection.id),
|
||||
label: collection.name ?? `Smart collection ${collection.id}`
|
||||
}))
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
footer={
|
||||
<>
|
||||
<Button disabled={submitting} onClick={onClose} variant="secondary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={!canSubmit}
|
||||
loading={submitting}
|
||||
onClick={submit}
|
||||
startIcon={<Save aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
Save as smart collection
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
open
|
||||
title="Save as smart collection"
|
||||
width={460}
|
||||
>
|
||||
{loading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{loadError}
|
||||
</span>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Select
|
||||
label="Smart collection"
|
||||
onChange={(event) => setSelected(event.target.value)}
|
||||
options={options}
|
||||
value={selected}
|
||||
/>
|
||||
{isNew && (
|
||||
<Input
|
||||
label="New smart collection name"
|
||||
onChange={(event) => setNewName(event.target.value)}
|
||||
placeholder="Smart collection name"
|
||||
value={newName}
|
||||
/>
|
||||
)}
|
||||
{submitError && (
|
||||
<span className="ctv-field-error" role="alert">
|
||||
{submitError}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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<Record<LibraryBrowseMediaType, CollectionType>> = {
|
||||
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
|
||||
};
|
||||
}
|
||||
@@ -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(<MediaBrowseScreen />);
|
||||
|
||||
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(<MediaBrowseScreen />);
|
||||
|
||||
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(<MediaBrowseScreen />);
|
||||
|
||||
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(<MediaBrowseScreen />);
|
||||
|
||||
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(<MediaBrowseScreen />);
|
||||
|
||||
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(<MediaBrowseScreen />);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<BrowseState>({ 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<Map<string, LibraryBrowseItem>>(new Map());
|
||||
const [bulkDialog, setBulkDialog] = useState<'collection' | 'playlist' | null>(null);
|
||||
const [notice, setNotice] = useState<Notice | null>(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
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={toggleSelectMode}
|
||||
size="sm"
|
||||
startIcon={<ListChecks aria-hidden="true" size={14} />}
|
||||
variant={selectMode ? 'primary' : 'secondary'}
|
||||
>
|
||||
{selectMode ? 'Done' : 'Select'}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={refresh}
|
||||
size="sm"
|
||||
@@ -144,6 +230,50 @@ export function MediaBrowseScreen() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{selected.size > 0 && (
|
||||
<div className="ctv-channels-actionbar">
|
||||
<span className="ctv-channels-selected">{selected.size} selected</span>
|
||||
<Button onClick={selectAllOnPage} size="sm" variant="secondary">
|
||||
Select all on page
|
||||
</Button>
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button
|
||||
onClick={() => setBulkDialog('collection')}
|
||||
size="sm"
|
||||
startIcon={<FolderPlus aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add to collection
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setBulkDialog('playlist')}
|
||||
size="sm"
|
||||
startIcon={<ListVideo aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add to playlist
|
||||
</Button>
|
||||
<Button onClick={clearSelection} size="sm" variant="ghost">
|
||||
Clear selection
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{notice && <Toast message={notice.message} onClose={() => setNotice(null)} tone={notice.tone} />}
|
||||
|
||||
<AddToCollectionDialog
|
||||
items={selectedItems}
|
||||
onAdded={onBulkAdded}
|
||||
onClose={() => setBulkDialog(null)}
|
||||
open={bulkDialog === 'collection'}
|
||||
/>
|
||||
<AddToPlaylistDialog
|
||||
items={selectedItems}
|
||||
onAdded={onBulkAdded}
|
||||
onClose={() => setBulkDialog(null)}
|
||||
open={bulkDialog === 'playlist'}
|
||||
/>
|
||||
|
||||
{state.status === 'error' && (
|
||||
<div className="ctv-channels-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={15} />
|
||||
@@ -173,9 +303,16 @@ export function MediaBrowseScreen() {
|
||||
const detailPath = mediaDetailPath(item);
|
||||
return (
|
||||
<MediaPosterCard
|
||||
actions={
|
||||
selectMode ? undefined : (
|
||||
<AddToMenu compact items={[item]} onDone={(message) => setNotice({ tone: 'ok', message })} />
|
||||
)
|
||||
}
|
||||
item={item}
|
||||
key={`${item.mediaType}-${item.id}`}
|
||||
onOpen={detailPath ? () => navigateToPath(detailPath) : undefined}
|
||||
onToggleSelect={selectMode ? toggleSelect : undefined}
|
||||
selected={selected.has(itemKey(item))}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -187,7 +324,7 @@ export function MediaBrowseScreen() {
|
||||
<span className="ctv-channels-spacer" />
|
||||
<IconButton
|
||||
disabled={pageNum === 0}
|
||||
onClick={() => setPageNum((current) => Math.max(0, current - 1))}
|
||||
onClick={() => goToPage((current) => Math.max(0, current - 1))}
|
||||
size="sm"
|
||||
title="Previous page"
|
||||
>
|
||||
@@ -198,7 +335,7 @@ export function MediaBrowseScreen() {
|
||||
</span>
|
||||
<IconButton
|
||||
disabled={pageNum + 1 >= totalPages}
|
||||
onClick={() => setPageNum((current) => current + 1)}
|
||||
onClick={() => goToPage((current) => current + 1)}
|
||||
size="sm"
|
||||
title="Next page"
|
||||
>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MovieDetailScreen, ShowDetailScreen } from './MediaDetailScreen';
|
||||
import {
|
||||
ArtistDetailScreen,
|
||||
MovieDetailScreen,
|
||||
SeasonDetailScreen,
|
||||
ShowDetailScreen
|
||||
} from './MediaDetailScreen';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
@@ -26,6 +31,67 @@ const movie = {
|
||||
fanArt: ''
|
||||
};
|
||||
|
||||
function showDetail(mediaSourceKind: string) {
|
||||
return {
|
||||
id: 42,
|
||||
libraryId: 3,
|
||||
mediaSourceKind,
|
||||
title: 'The Show',
|
||||
year: '2001',
|
||||
plot: 'Show plot',
|
||||
genres: [],
|
||||
tags: [],
|
||||
studios: [],
|
||||
networks: [],
|
||||
contentRatings: [],
|
||||
languages: [],
|
||||
actors: [],
|
||||
poster: '',
|
||||
fanArt: ''
|
||||
};
|
||||
}
|
||||
|
||||
const season = {
|
||||
id: 8,
|
||||
showId: 42,
|
||||
title: 'The Show',
|
||||
name: 'Season 1',
|
||||
year: '2001',
|
||||
poster: '',
|
||||
fanArt: ''
|
||||
};
|
||||
|
||||
const artist = {
|
||||
id: 11,
|
||||
name: 'The Artist',
|
||||
disambiguation: '',
|
||||
biography: 'Bio',
|
||||
genres: [],
|
||||
styles: [],
|
||||
moods: [],
|
||||
languages: [],
|
||||
thumbnail: '',
|
||||
fanArt: ''
|
||||
};
|
||||
|
||||
// Serves a detail record on its /api/<kind>/<id> route, an empty child browse page, and stubs for
|
||||
// the Add-to dialog loads so opening the plus menu never errors.
|
||||
function mockDetailFetch(detail: unknown) {
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = input.toString();
|
||||
if (url.startsWith('/api/library/browse')) {
|
||||
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
|
||||
}
|
||||
if (url === '/api/collections' || url === '/api/playlists/groups' || url === '/api/schedules') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
if (url.startsWith('/api/libraries/') && url.includes('/scan-show')) {
|
||||
return Promise.resolve(new Response(null, { status: 200 }));
|
||||
}
|
||||
return Promise.resolve(jsonResponse(detail));
|
||||
});
|
||||
}
|
||||
|
||||
describe('media detail screens', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
@@ -50,4 +116,66 @@ describe('media detail screens', () => {
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Show not found.')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('offers an Add-to menu on the movie detail page', async () => {
|
||||
mockDetailFetch(movie);
|
||||
render(<MovieDetailScreen id={5} />);
|
||||
await waitFor(() => expect(screen.getByText('The Movie')).toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Add to…' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('offers an Add-to menu on the season and artist detail pages', async () => {
|
||||
mockDetailFetch(season);
|
||||
const { unmount } = render(<SeasonDetailScreen id={8} />);
|
||||
await waitFor(() => expect(screen.getByText('The Show — Season 1')).toBeInTheDocument());
|
||||
expect(screen.getAllByRole('button', { name: 'Add to…' }).length).toBeGreaterThanOrEqual(1);
|
||||
unmount();
|
||||
|
||||
mockDetailFetch(artist);
|
||||
render(<ArtistDetailScreen id={11} />);
|
||||
await waitFor(() => expect(screen.getByText('The Artist')).toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Add to…' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides per-show scan for Local libraries and shows it for Plex', async () => {
|
||||
mockDetailFetch(showDetail('Local'));
|
||||
const { unmount } = render(<ShowDetailScreen id={42} />);
|
||||
await waitFor(() => expect(screen.getByText('The Show')).toBeInTheDocument());
|
||||
expect(screen.queryByRole('button', { name: 'Quick scan' })).toBeNull();
|
||||
unmount();
|
||||
|
||||
const fetchSpy = mockDetailFetch(showDetail('Plex'));
|
||||
render(<ShowDetailScreen id={42} />);
|
||||
await waitFor(() => expect(screen.getByText('The Show')).toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Quick scan' })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deep scan' }));
|
||||
await waitFor(() => {
|
||||
const scanCall = fetchSpy.mock.calls.find(([url]) => String(url) === '/api/libraries/3/scan-show');
|
||||
expect(scanCall).toBeTruthy();
|
||||
const body = JSON.parse(String((scanCall![1] as RequestInit).body));
|
||||
expect(body).toMatchObject({ deepScan: true, showTitle: 'The Show' });
|
||||
});
|
||||
await waitFor(() => expect(screen.getByText('Scan queued')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('exposes Media Info and Troubleshoot actions on episode cards', async () => {
|
||||
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = input.toString();
|
||||
if (url.startsWith('/api/library/browse')) {
|
||||
return Promise.resolve(
|
||||
jsonResponse({ page: [{ artwork: '', collectionType: 'Episode', id: 91, mediaType: 'Episode', title: 'Pilot' }], totalCount: 1 })
|
||||
);
|
||||
}
|
||||
if (url === '/api/collections' || url === '/api/playlists/groups' || url === '/api/schedules') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
return Promise.resolve(jsonResponse(season));
|
||||
});
|
||||
|
||||
render(<SeasonDetailScreen id={8} />);
|
||||
await waitFor(() => expect(screen.getByText('Pilot')).toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'Media Info' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Troubleshoot Playback' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { ArrowLeft, ChevronLeft, ChevronRight, Info, Stethoscope, TriangleAlert } from 'lucide-react';
|
||||
import { ArrowLeft, ChevronLeft, ChevronRight, Info, ScanSearch, Stethoscope, TriangleAlert } from 'lucide-react';
|
||||
import { Button, Card, Dialog, IconButton, Spinner, Tag } from '../components';
|
||||
import {
|
||||
ApiError,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
getShow,
|
||||
messageFromLibraryBrowseError,
|
||||
messageFromMediaDetailError,
|
||||
scanShow,
|
||||
type ArtistDetail,
|
||||
type LibraryBrowseItem,
|
||||
type LibraryBrowseMediaType,
|
||||
@@ -19,12 +20,27 @@ import {
|
||||
type SeasonDetail,
|
||||
type ShowDetail
|
||||
} from '../api';
|
||||
import { AddToMenu } from '../media/addTo';
|
||||
import { MediaPosterCard } from '../media/MediaPosterCard';
|
||||
import { mediaDetailPath, parseDurationSeconds } from '../media/mediaKinds';
|
||||
import { navigateToPath } from '../routing';
|
||||
|
||||
const CHILD_PAGE_SIZE = 60;
|
||||
|
||||
// Media source kinds whose libraries support the single-show rescan endpoint.
|
||||
const REMOTE_SOURCE_KINDS = new Set(['Plex', 'Jellyfin', 'Emby']);
|
||||
|
||||
// Builds a minimal LibraryBrowseItem for a detail page's own subject so it can feed the shared
|
||||
// Add-to menu/dialogs, which only read id/mediaType/title off each item (see toAddItemsRequest /
|
||||
// AddToScheduleDialog). The remaining fields are inert here.
|
||||
function detailBrowseItem(mediaType: LibraryBrowseMediaType, id: number, title: string): LibraryBrowseItem {
|
||||
return { artwork: '', id, mediaType, title } as unknown as LibraryBrowseItem;
|
||||
}
|
||||
|
||||
function troubleshootPath(mediaItemId: number): string {
|
||||
return `/app/troubleshooting/playback?mediaItem=${mediaItemId}`;
|
||||
}
|
||||
|
||||
type DetailState<T> =
|
||||
| { status: 'loading' }
|
||||
| { status: 'notfound' }
|
||||
@@ -182,11 +198,13 @@ function StateWarning({ state, path }: { state: string | null | undefined; path?
|
||||
function ChildGrid({
|
||||
heading,
|
||||
mediaType,
|
||||
parentId
|
||||
parentId,
|
||||
renderActions
|
||||
}: {
|
||||
heading: string;
|
||||
mediaType: LibraryBrowseMediaType;
|
||||
parentId: number;
|
||||
renderActions?: (item: LibraryBrowseItem) => ReactNode;
|
||||
}) {
|
||||
const [items, setItems] = useState<LibraryBrowseItem[]>([]);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
@@ -262,6 +280,7 @@ function ChildGrid({
|
||||
const detailPath = mediaDetailPath(item);
|
||||
return (
|
||||
<MediaPosterCard
|
||||
actions={renderActions?.(item)}
|
||||
item={item}
|
||||
key={`${item.mediaType}-${item.id}`}
|
||||
onOpen={detailPath ? () => navigateToPath(detailPath) : undefined}
|
||||
@@ -514,14 +533,14 @@ export function MovieDetailScreen({ id }: { id: number }) {
|
||||
Media Info
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => navigateToPath(`/app/troubleshooting/playback?mediaItem=${id}`)}
|
||||
onClick={() => navigateToPath(troubleshootPath(id))}
|
||||
size="sm"
|
||||
startIcon={<Stethoscope size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Troubleshoot Playback
|
||||
</Button>
|
||||
{/* Add-to-collection / add-to-playlist mutations are out of scope here; tracked by #153 / #155. */}
|
||||
<AddToMenu items={[detailBrowseItem('Movie', id, movie.title)]} />
|
||||
</>
|
||||
}
|
||||
chips={
|
||||
@@ -550,6 +569,67 @@ export function MovieDetailScreen({ id }: { id: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ShowScanControls({ show }: { show: ShowDetail }) {
|
||||
const [scanning, setScanning] = useState<false | 'quick' | 'deep'>(false);
|
||||
const [message, setMessage] = useState<{ kind: 'ok' | 'error'; text: string } | null>(null);
|
||||
const activeRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = true;
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const runScan = (deepScan: boolean) => {
|
||||
setScanning(deepScan ? 'deep' : 'quick');
|
||||
setMessage(null);
|
||||
scanShow(show.libraryId, { deepScan, showTitle: show.title })
|
||||
.then(() => {
|
||||
if (activeRef.current) {
|
||||
setScanning(false);
|
||||
setMessage({ kind: 'ok', text: 'Scan queued' });
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (activeRef.current) {
|
||||
setScanning(false);
|
||||
setMessage({ kind: 'error', text: messageFromMediaDetailError(error, 'Unable to queue scan') });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={scanning !== false}
|
||||
loading={scanning === 'quick'}
|
||||
onClick={() => runScan(false)}
|
||||
size="sm"
|
||||
startIcon={<ScanSearch size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Quick scan
|
||||
</Button>
|
||||
<Button
|
||||
disabled={scanning !== false}
|
||||
loading={scanning === 'deep'}
|
||||
onClick={() => runScan(true)}
|
||||
size="sm"
|
||||
startIcon={<ScanSearch size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Deep scan
|
||||
</Button>
|
||||
{message ? (
|
||||
<span className={message.kind === 'error' ? 'ctv-field-error' : 'ctv-channels-selected'} role={message.kind === 'error' ? 'alert' : 'status'}>
|
||||
{message.text}
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ShowDetailScreen({ id }: { id: number }) {
|
||||
const state = useDetail<ShowDetail>(useCallback(() => getShow(id), [id]));
|
||||
|
||||
@@ -564,6 +644,7 @@ export function ShowDetailScreen({ id }: { id: number }) {
|
||||
}
|
||||
|
||||
const show = state.data;
|
||||
const canScanShow = REMOTE_SOURCE_KINDS.has(show.mediaSourceKind);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -571,6 +652,12 @@ export function ShowDetailScreen({ id }: { id: number }) {
|
||||
Back
|
||||
</Button>
|
||||
<DetailShell
|
||||
actions={
|
||||
<>
|
||||
<AddToMenu items={[detailBrowseItem('TelevisionShow', id, show.title)]} />
|
||||
{canScanShow ? <ShowScanControls show={show} /> : null}
|
||||
</>
|
||||
}
|
||||
chips={
|
||||
<div className="ctv-detail-chipstack">
|
||||
<ChipRow label="Genres" values={show.genres} />
|
||||
@@ -588,7 +675,12 @@ export function ShowDetailScreen({ id }: { id: number }) {
|
||||
title={show.title}
|
||||
>
|
||||
<ActorsRow actors={show.actors} />
|
||||
<ChildGrid heading="Seasons" mediaType="TelevisionSeason" parentId={id} />
|
||||
<ChildGrid
|
||||
heading="Seasons"
|
||||
mediaType="TelevisionSeason"
|
||||
parentId={id}
|
||||
renderActions={(item) => <AddToMenu compact items={[item]} />}
|
||||
/>
|
||||
</DetailShell>
|
||||
</>
|
||||
);
|
||||
@@ -596,6 +688,7 @@ export function ShowDetailScreen({ id }: { id: number }) {
|
||||
|
||||
export function SeasonDetailScreen({ id }: { id: number }) {
|
||||
const state = useDetail<SeasonDetail>(useCallback(() => getSeason(id), [id]));
|
||||
const [infoItemId, setInfoItemId] = useState<number | null>(null);
|
||||
|
||||
if (state.status === 'loading') {
|
||||
return <Loading />;
|
||||
@@ -608,6 +701,7 @@ export function SeasonDetailScreen({ id }: { id: number }) {
|
||||
}
|
||||
|
||||
const season = state.data;
|
||||
const seasonTitle = `${season.title} — ${season.name}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -620,13 +714,34 @@ export function SeasonDetailScreen({ id }: { id: number }) {
|
||||
Back to show
|
||||
</Button>
|
||||
<DetailShell
|
||||
actions={<AddToMenu items={[detailBrowseItem('TelevisionSeason', id, seasonTitle)]} />}
|
||||
fanart={season.fanArt}
|
||||
poster={season.poster}
|
||||
subtitle={season.year}
|
||||
title={`${season.title} — ${season.name}`}
|
||||
title={seasonTitle}
|
||||
>
|
||||
<ChildGrid heading="Episodes" mediaType="Episode" parentId={id} />
|
||||
<ChildGrid
|
||||
heading="Episodes"
|
||||
mediaType="Episode"
|
||||
parentId={id}
|
||||
renderActions={(item) => (
|
||||
<>
|
||||
<AddToMenu compact items={[item]} />
|
||||
<IconButton onClick={() => setInfoItemId(item.id)} size="sm" title="Media Info">
|
||||
<Info aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
<IconButton onClick={() => navigateToPath(troubleshootPath(item.id))} size="sm" title="Troubleshoot Playback">
|
||||
<Stethoscope aria-hidden="true" size={14} />
|
||||
</IconButton>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</DetailShell>
|
||||
<MediaInfoDialog
|
||||
mediaItemId={infoItemId ?? 0}
|
||||
onClose={() => setInfoItemId(null)}
|
||||
open={infoItemId !== null}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -652,6 +767,7 @@ export function ArtistDetailScreen({ id }: { id: number }) {
|
||||
Back
|
||||
</Button>
|
||||
<DetailShell
|
||||
actions={<AddToMenu items={[detailBrowseItem('Artist', id, artist.name)]} />}
|
||||
chips={
|
||||
<div className="ctv-detail-chipstack">
|
||||
<ChipRow label="Genres" values={artist.genres} />
|
||||
@@ -666,7 +782,12 @@ export function ArtistDetailScreen({ id }: { id: number }) {
|
||||
subtitle={artist.disambiguation}
|
||||
title={artist.name}
|
||||
>
|
||||
<ChildGrid heading="Music Videos" mediaType="MusicVideo" parentId={id} />
|
||||
<ChildGrid
|
||||
heading="Music Videos"
|
||||
mediaType="MusicVideo"
|
||||
parentId={id}
|
||||
renderActions={(item) => <AddToMenu compact items={[item]} />}
|
||||
/>
|
||||
</DetailShell>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { SearchScreen } from './SearchScreen';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
const movieItem = { artwork: '', duration: null, id: 12, mediaType: 'Movie', subtitle: null, title: 'Blade Runner' };
|
||||
|
||||
function emptyGroup() {
|
||||
return { totalCount: 0, items: [] };
|
||||
}
|
||||
|
||||
function searchResults() {
|
||||
return {
|
||||
movies: { totalCount: 1, items: [movieItem] },
|
||||
shows: emptyGroup(),
|
||||
seasons: emptyGroup(),
|
||||
artists: emptyGroup(),
|
||||
episodes: emptyGroup(),
|
||||
musicVideos: emptyGroup(),
|
||||
songs: emptyGroup(),
|
||||
otherVideos: emptyGroup(),
|
||||
images: emptyGroup(),
|
||||
remoteStreams: emptyGroup()
|
||||
};
|
||||
}
|
||||
|
||||
const allItems = {
|
||||
movieIds: [7, 8],
|
||||
showIds: null,
|
||||
seasonIds: null,
|
||||
episodeIds: null,
|
||||
artistIds: null,
|
||||
musicVideoIds: null,
|
||||
otherVideoIds: null,
|
||||
songIds: null,
|
||||
imageIds: null,
|
||||
remoteStreamIds: null
|
||||
};
|
||||
|
||||
const emptyBuckets = {
|
||||
artistIds: [],
|
||||
episodeIds: [],
|
||||
imageIds: [],
|
||||
movieIds: [],
|
||||
musicVideoIds: [],
|
||||
otherVideoIds: [],
|
||||
remoteStreamIds: [],
|
||||
seasonIds: [],
|
||||
showIds: [],
|
||||
songIds: []
|
||||
};
|
||||
|
||||
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.startsWith('/api/search/all-items')) {
|
||||
return Promise.resolve(jsonResponse(allItems));
|
||||
}
|
||||
if (url.startsWith('/api/search')) {
|
||||
return Promise.resolve(jsonResponse(searchResults()));
|
||||
}
|
||||
if (url === '/api/collections' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([{ collectionType: 'Collection', id: 1, name: 'Favorites', useCustomPlaybackOrder: false }]));
|
||||
}
|
||||
if (url === '/api/smart-collections' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
if (url === '/api/smart-collections' && method === 'POST') {
|
||||
const name = (body as { name: string }).name;
|
||||
return Promise.resolve(jsonResponse({ id: 42, name, query: (body as { query: string }).query }, 201));
|
||||
}
|
||||
if (url === '/api/playlists/groups') {
|
||||
return Promise.resolve(jsonResponse([]));
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
|
||||
return { calls };
|
||||
}
|
||||
|
||||
function renderWithQuery() {
|
||||
window.history.replaceState(null, '', '/app/search?query=trek');
|
||||
return render(<SearchScreen />);
|
||||
}
|
||||
|
||||
describe('SearchScreen', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
window.history.replaceState(null, '', '/');
|
||||
});
|
||||
|
||||
it('drills into a result card via its detail path', async () => {
|
||||
mockApi();
|
||||
renderWithQuery();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Blade Runner')).toBeTruthy());
|
||||
const pushState = vi.spyOn(window.history, 'pushState');
|
||||
fireEvent.click(screen.getByText('Blade Runner'));
|
||||
|
||||
expect(pushState).toHaveBeenCalledWith(null, '', '/app/media/movies/12');
|
||||
});
|
||||
|
||||
it('selects cards and adds the selection to a collection', async () => {
|
||||
const { calls } = mockApi();
|
||||
renderWithQuery();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Blade Runner')).toBeTruthy());
|
||||
|
||||
// Enter select mode, then click the card to toggle it selected.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Select/ }));
|
||||
fireEvent.click(screen.getByText('Blade Runner'));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('1 selected')).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add to collection' }));
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
await waitFor(() => expect(within(dialog).getByRole('option', { name: 'Favorites' })).toBeTruthy());
|
||||
fireEvent.click(within(dialog).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?.method).toBe('POST');
|
||||
expect(addCall?.body).toEqual({ ...emptyBuckets, movieIds: [12] });
|
||||
});
|
||||
|
||||
it('clears the selection when the query changes', async () => {
|
||||
mockApi();
|
||||
renderWithQuery();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Blade Runner')).toBeTruthy());
|
||||
fireEvent.click(screen.getByRole('button', { name: /Select/ }));
|
||||
fireEvent.click(screen.getByText('Blade Runner'));
|
||||
await waitFor(() => expect(screen.getByText('1 selected')).toBeTruthy());
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/Search movies/), { target: { value: 'alien' } });
|
||||
|
||||
// The debounced query change drops the now-stale selection.
|
||||
await waitFor(() => expect(screen.queryByText('1 selected')).toBeNull());
|
||||
});
|
||||
|
||||
it('adds all query results (not just the loaded page) to a collection', async () => {
|
||||
const { calls } = mockApi();
|
||||
renderWithQuery();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Blade Runner')).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add all to collection/ }));
|
||||
|
||||
// The whole-query id set is resolved via /api/search/all-items before the dialog opens.
|
||||
await waitFor(() => expect(calls.some((call) => call.url.startsWith('/api/search/all-items'))).toBe(true));
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
await waitFor(() => expect(within(dialog).getByRole('option', { name: 'Favorites' })).toBeTruthy());
|
||||
fireEvent.click(within(dialog).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({ ...emptyBuckets, movieIds: [7, 8] });
|
||||
});
|
||||
|
||||
it('saves the current query as a new smart collection', async () => {
|
||||
const { calls } = mockApi();
|
||||
renderWithQuery();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Blade Runner')).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Save as smart collection/ }));
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
await waitFor(() => expect(within(dialog).getByRole('option', { name: '(New smart collection)' })).toBeTruthy());
|
||||
fireEvent.change(within(dialog).getByPlaceholderText('Smart collection name'), { target: { value: 'Trek Stuff' } });
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: /Save as smart collection/ }));
|
||||
|
||||
await waitFor(() => expect(calls.some((call) => call.url === '/api/smart-collections' && call.method === 'POST')).toBe(true));
|
||||
const createCall = calls.find((call) => call.url === '/api/smart-collections' && call.method === 'POST');
|
||||
expect(createCall?.body).toEqual({ name: 'Trek Stuff', query: 'trek' });
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,31 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Search, TriangleAlert } from 'lucide-react';
|
||||
import { Button, Card, Input, Spinner } from '../components';
|
||||
import { getSearchResults, messageFromSearchError, type SearchResults } from '../api';
|
||||
import { CheckSquare, FolderPlus, ListVideo, Save, Search, TriangleAlert, X } from 'lucide-react';
|
||||
import { Button, Card, Input, Spinner, Toast } from '../components';
|
||||
import {
|
||||
getSearchAllItems,
|
||||
getSearchResults,
|
||||
messageFromSearchError,
|
||||
toAddItemsRequestFromSearch,
|
||||
type LibraryBrowseItem,
|
||||
type SearchResults
|
||||
} from '../api';
|
||||
import { navigateToPath } from '../routing';
|
||||
import { MediaPosterCard } from '../media/MediaPosterCard';
|
||||
import { mediaDetailPath } from '../media/mediaKinds';
|
||||
import {
|
||||
AddToCollectionDialog,
|
||||
AddToMenu,
|
||||
AddToPlaylistDialog,
|
||||
SaveAsSmartCollectionDialog,
|
||||
type AddToItems
|
||||
} from '../media/addTo';
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
interface GroupDef {
|
||||
key: keyof SearchResults;
|
||||
label: string;
|
||||
// MediaBrowse slug for "See all"; null for kinds without a top-level browse page (seasons).
|
||||
// MediaBrowse slug for "See all"; null for kinds without a top-level browse page.
|
||||
slug: string | null;
|
||||
}
|
||||
|
||||
@@ -18,7 +33,7 @@ interface GroupDef {
|
||||
const GROUPS: GroupDef[] = [
|
||||
{ key: 'movies', label: 'Movies', slug: 'movies' },
|
||||
{ key: 'shows', label: 'TV Shows', slug: 'shows' },
|
||||
{ key: 'seasons', label: 'Seasons', slug: null },
|
||||
{ key: 'seasons', label: 'Seasons', slug: 'seasons' },
|
||||
{ key: 'episodes', label: 'Episodes', slug: 'episodes' },
|
||||
{ key: 'artists', label: 'Artists', slug: 'artists' },
|
||||
{ key: 'musicVideos', label: 'Music Videos', slug: 'music-videos' },
|
||||
@@ -33,13 +48,32 @@ type SearchState =
|
||||
| { results: null; error: string; status: 'error' }
|
||||
| { results: null; error: null; status: 'loading' };
|
||||
|
||||
// Which whole-query / selection dialog is open. Per-card adds are owned by each card's AddToMenu.
|
||||
type ActiveDialog =
|
||||
| { kind: 'collection'; items: AddToItems }
|
||||
| { kind: 'playlist'; items: AddToItems }
|
||||
| { kind: 'save-smart' }
|
||||
| null;
|
||||
|
||||
type Notice = { tone: 'ok' | 'error'; message: string };
|
||||
|
||||
function itemKey(item: LibraryBrowseItem): string {
|
||||
return `${item.mediaType}-${item.id}`;
|
||||
}
|
||||
|
||||
export function SearchScreen() {
|
||||
const initialQuery = new URLSearchParams(window.location.search).get('query') ?? '';
|
||||
const [queryInput, setQueryInput] = useState(initialQuery);
|
||||
const [query, setQuery] = useState(initialQuery);
|
||||
const [state, setState] = useState<SearchState>({ results: null, error: null, status: 'loading' });
|
||||
const [selectMode, setSelectMode] = useState(false);
|
||||
const [selected, setSelected] = useState<Map<string, LibraryBrowseItem>>(new Map());
|
||||
const [dialog, setDialog] = useState<ActiveDialog>(null);
|
||||
const [pendingAll, setPendingAll] = useState<'collection' | 'playlist' | null>(null);
|
||||
const [notice, setNotice] = useState<Notice | null>(null);
|
||||
const activeRef = useRef(true);
|
||||
const seqRef = useRef(0);
|
||||
const lastQueryRef = useRef(initialQuery.trim());
|
||||
const hasQuery = query.trim().length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,10 +83,18 @@ export function SearchScreen() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// The no-change guard matters: this timer also fires once on mount and must not wipe an
|
||||
// in-progress selection when the query is unchanged.
|
||||
useEffect(() => {
|
||||
const handle = window.setTimeout(() => {
|
||||
const trimmed = queryInput.trim();
|
||||
if (lastQueryRef.current === trimmed) {
|
||||
return;
|
||||
}
|
||||
lastQueryRef.current = trimmed;
|
||||
setQuery(trimmed);
|
||||
// A new query means a new result set — drop any stale selection (mirrors MediaBrowseScreen).
|
||||
setSelected(new Map());
|
||||
// Keep the URL shareable without remounting.
|
||||
const next = trimmed ? `/app/search?query=${encodeURIComponent(trimmed)}` : '/app/search';
|
||||
window.history.replaceState(null, '', next);
|
||||
@@ -92,11 +134,74 @@ export function SearchScreen() {
|
||||
navigateToPath(`/app/media?kind=${slug}&q=${encodeURIComponent(query.trim())}`);
|
||||
};
|
||||
|
||||
const clearSelection = () => setSelected(new Map());
|
||||
|
||||
// Screen-level Select toggle (deliberate UX deviation from Blazor's always-on corner-select):
|
||||
// OFF => cards drill in on click; ON => cards toggle selection. Turning it off clears the set.
|
||||
const toggleSelectMode = () => {
|
||||
if (selectMode) {
|
||||
clearSelection();
|
||||
}
|
||||
setSelectMode((current) => !current);
|
||||
};
|
||||
|
||||
const toggleSelect = (item: LibraryBrowseItem) => {
|
||||
const key = itemKey(item);
|
||||
setSelected((current) => {
|
||||
const next = new Map(current);
|
||||
if (next.has(key)) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, item);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// Add the whole query's results (not just the loaded page): resolve every matching id, then open
|
||||
// the target dialog with a pre-built request override. Blazor ref: Search.razor AddAllTo*.
|
||||
const addAll = (kind: 'collection' | 'playlist') => {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingAll(kind);
|
||||
getSearchAllItems(trimmed)
|
||||
.then((result) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
setPendingAll(null);
|
||||
setDialog({ kind, items: { requestOverride: toAddItemsRequestFromSearch(result) } });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
setPendingAll(null);
|
||||
setNotice({ tone: 'error', message: messageFromSearchError(error, 'Unable to load all results') });
|
||||
});
|
||||
};
|
||||
|
||||
const addSelection = (kind: 'collection' | 'playlist') => {
|
||||
setDialog({ kind, items: [...selected.values()] });
|
||||
};
|
||||
|
||||
const onAddedToSelectionTarget = (label: string) => (name: string) => {
|
||||
setDialog(null);
|
||||
clearSelection();
|
||||
setNotice({ tone: 'ok', message: `Added to ${label} “${name}”` });
|
||||
};
|
||||
|
||||
const totalMatches =
|
||||
state.status === 'success' && state.results
|
||||
? GROUPS.reduce((sum, group) => sum + (state.results?.[group.key].totalCount ?? 0), 0)
|
||||
: 0;
|
||||
|
||||
const hasResults = hasQuery && state.status === 'success' && totalMatches > 0;
|
||||
const selectionCount = selected.size;
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<div className="ctv-channels-actionbar">
|
||||
@@ -106,8 +211,84 @@ export function SearchScreen() {
|
||||
placeholder="Search movies, shows, episodes, music…"
|
||||
value={queryInput}
|
||||
/>
|
||||
<span className="ctv-channels-spacer" />
|
||||
{hasResults && (
|
||||
<>
|
||||
<Button
|
||||
onClick={toggleSelectMode}
|
||||
size="sm"
|
||||
startIcon={<CheckSquare aria-hidden="true" size={14} />}
|
||||
variant={selectMode ? 'primary' : 'secondary'}
|
||||
>
|
||||
Select
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pendingAll !== null}
|
||||
loading={pendingAll === 'collection'}
|
||||
onClick={() => addAll('collection')}
|
||||
size="sm"
|
||||
startIcon={<FolderPlus aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add all to collection
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pendingAll !== null}
|
||||
loading={pendingAll === 'playlist'}
|
||||
onClick={() => addAll('playlist')}
|
||||
size="sm"
|
||||
startIcon={<ListVideo aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add all to playlist
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setDialog({ kind: 'save-smart' })}
|
||||
size="sm"
|
||||
startIcon={<Save aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Save as smart collection
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{notice && (
|
||||
<Toast message={notice.message} onClose={() => setNotice(null)} tone={notice.tone} />
|
||||
)}
|
||||
|
||||
{selectMode && selectionCount > 0 && (
|
||||
<div className="ctv-search-selectbar" role="region" aria-label="Selection actions">
|
||||
<span className="ctv-search-selectbar-count">{selectionCount} selected</span>
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button
|
||||
onClick={() => addSelection('collection')}
|
||||
size="sm"
|
||||
startIcon={<FolderPlus aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add to collection
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => addSelection('playlist')}
|
||||
size="sm"
|
||||
startIcon={<ListVideo aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
Add to playlist
|
||||
</Button>
|
||||
<Button
|
||||
onClick={clearSelection}
|
||||
size="sm"
|
||||
startIcon={<X aria-hidden="true" size={14} />}
|
||||
variant="ghost"
|
||||
>
|
||||
Clear selection
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasQuery && (
|
||||
<Card>
|
||||
<div className="ctv-collections-empty">Type a query to search across every media kind.</div>
|
||||
@@ -164,13 +345,51 @@ export function SearchScreen() {
|
||||
)}
|
||||
</div>
|
||||
<div className="ctv-media-grid">
|
||||
{data.items.map((item) => (
|
||||
<MediaPosterCard item={item} key={`${item.mediaType}-${item.id}`} />
|
||||
))}
|
||||
{data.items.map((item) => {
|
||||
const key = itemKey(item);
|
||||
const detailPath = mediaDetailPath(item);
|
||||
return (
|
||||
<MediaPosterCard
|
||||
actions={
|
||||
selectMode ? undefined : (
|
||||
<AddToMenu compact items={[item]} onDone={(message) => setNotice({ tone: 'ok', message })} />
|
||||
)
|
||||
}
|
||||
item={item}
|
||||
key={key}
|
||||
onOpen={!selectMode && detailPath ? () => navigateToPath(detailPath) : undefined}
|
||||
onToggleSelect={selectMode ? toggleSelect : undefined}
|
||||
selected={selectMode ? selected.has(key) : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
|
||||
<AddToCollectionDialog
|
||||
items={dialog?.kind === 'collection' ? dialog.items : []}
|
||||
onAdded={onAddedToSelectionTarget('collection')}
|
||||
onClose={() => setDialog(null)}
|
||||
open={dialog?.kind === 'collection'}
|
||||
/>
|
||||
<AddToPlaylistDialog
|
||||
items={dialog?.kind === 'playlist' ? dialog.items : []}
|
||||
onAdded={onAddedToSelectionTarget('playlist')}
|
||||
onClose={() => setDialog(null)}
|
||||
open={dialog?.kind === 'playlist'}
|
||||
/>
|
||||
<SaveAsSmartCollectionDialog
|
||||
onClose={() => setDialog(null)}
|
||||
onSaved={(name) => {
|
||||
setDialog(null);
|
||||
clearSelection();
|
||||
setNotice({ tone: 'ok', message: `Saved smart collection “${name}”` });
|
||||
}}
|
||||
open={dialog?.kind === 'save-smart'}
|
||||
query={query.trim()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/* Base typography on <body>: Dialog (and any overlay) portals into document.body, outside
|
||||
.ctv-app-shell — without this, portaled UI falls back to the browser default font. */
|
||||
body {
|
||||
font-family: var(--font-sans, system-ui, sans-serif);
|
||||
font-size: var(--text-sm, 13px);
|
||||
color: var(--text-primary, #f0ebe4);
|
||||
}
|
||||
|
||||
.ctv-app-shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
@@ -2559,6 +2567,70 @@
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.ctv-media-card-actions {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
z-index: 3;
|
||||
display: inline-flex;
|
||||
opacity: 0;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
.ctv-media-card:hover .ctv-media-card-actions,
|
||||
.ctv-media-card:focus-within .ctv-media-card-actions {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Always keep the actions reachable by keyboard even when not hovered. */
|
||||
.ctv-media-card-actions:focus-within {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Add-to menu popover */
|
||||
.ctv-addto-menu {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.ctv-addto-menu-popover {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
right: 0;
|
||||
z-index: 40;
|
||||
min-width: 160px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--ctv-surface-3, var(--surface-card));
|
||||
box-shadow: var(--shadow-md, 0 8px 24px rgb(0 0 0 / 0.35));
|
||||
}
|
||||
|
||||
.ctv-addto-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
border: none;
|
||||
border-radius: var(--radius-xs, 6px);
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font: inherit;
|
||||
font-size: var(--text-xs, 12px);
|
||||
font-weight: var(--weight-medium, 500);
|
||||
line-height: 1.2;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ctv-addto-menu-item:hover,
|
||||
.ctv-addto-menu-item:focus-visible {
|
||||
background: var(--ctv-surface-2, var(--surface-hover));
|
||||
}
|
||||
|
||||
.ctv-media-card-body {
|
||||
padding: 8px 10px 10px;
|
||||
}
|
||||
@@ -4087,3 +4159,19 @@
|
||||
border-color: var(--ctv-accent);
|
||||
color: var(--ctv-text);
|
||||
}
|
||||
|
||||
/* Search multi-select action bar (#208): appears below the actionbar while items are selected. */
|
||||
.ctv-search-selectbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-5, 10px);
|
||||
border: 1px solid var(--ctv-accent);
|
||||
border-radius: var(--radius-md, 7px);
|
||||
background: var(--ctv-accent-soft);
|
||||
padding: var(--space-4, 8px) var(--space-7, 16px);
|
||||
}
|
||||
|
||||
.ctv-search-selectbar-count {
|
||||
font-weight: 600;
|
||||
color: var(--ctv-text);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user