Merge branch 'feature/set-layout'

This commit is contained in:
Yisroel Baum 2026-08-10 19:45:17 +03:00
commit 0049248231
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
30 changed files with 1677 additions and 61 deletions

View file

@ -87,6 +87,8 @@ intentionally unclaimed; the built-in health endpoint is `/up`.
- Put imports at the top of the file. Do not use inline fully qualified class
names when a normal `use` statement is clearer.
- Do not use arrow functions. Use regular anonymous functions.
- Do not use first-class callable syntax. Use regular anonymous functions for
callbacks so the invocation is explicit.
- Do not add default values to function or constructor parameters. Pass every
argument explicitly, including nullable arguments.
- Use descriptive names for classes, methods, parameters, and local

View file

@ -14,6 +14,11 @@ interface ElementRepository
public function find(int $id): ?Element;
/**
* @return list<Element>
*/
public function findBySet(Set $set): array;
/**
* @return list<Element>
*/

View file

@ -45,6 +45,37 @@ class EloquentElementRepository implements ElementRepository
return $model === null ? null : $this->toDomain($model);
}
public function findBySet(Set $set): array
{
$models = ElementModel::query()
->where('set_id', $set->getId())
->orderBy('id')
->get();
$elements = [];
$elementsById = [];
foreach ($models as $model) {
$parentElement = null;
if ($model->parent_element_id !== null) {
$parentElement = $elementsById[$model->parent_element_id]
?? null;
if ($parentElement === null) {
throw new RuntimeException('element parent not found');
}
}
$element = $this->toDomainWithRelations(
model: $model,
set: $set,
parentElement: $parentElement,
);
$elements[] = $element;
$elementsById[$element->getId()] = $element;
}
return $elements;
}
public function findTopLevelBySet(Set $set): array
{
$models = ElementModel::query()
@ -160,11 +191,10 @@ class EloquentElementRepository implements ElementRepository
private function findSet(int $id): Set
{
foreach ($this->setRepository->all() as $set) {
if ($set->getId() === $id) {
$set = $this->setRepository->find($id);
if ($set !== null) {
return $set;
}
}
throw new RuntimeException('element set not found');
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Exceptions;
use DomainException;
class NotFoundException extends DomainException {}

View file

@ -2,7 +2,11 @@
namespace App\Http\Controllers;
use App\Exceptions\NotFoundException;
use App\Set\Set;
use App\Set\UseCases\GetSetLayout\ElementLayoutNode;
use App\Set\UseCases\GetSetLayout\GetSetLayout;
use App\Set\UseCases\GetSetLayout\GetSetLayoutRequest;
use App\Set\UseCases\ListSets\ListSets;
use Illuminate\Http\JsonResponse;
@ -10,6 +14,7 @@ class SetController extends Controller
{
public function __construct(
private ListSets $listSets,
private GetSetLayout $getSetLayout,
) {}
public function index(): JsonResponse
@ -23,4 +28,58 @@ class SetController extends Controller
return new JsonResponse(['sets' => $sets]);
}
public function show(int $setId): JsonResponse
{
try {
$layout = $this->getSetLayout->execute(
new GetSetLayoutRequest(setId: $setId),
);
} catch (NotFoundException $exception) {
return new JsonResponse(
['error' => $exception->getMessage()],
404,
);
}
$set = $layout->getSet();
return new JsonResponse([
'set' => [
'id' => $set->getId(),
'name' => $set->getName(),
],
'elements' => array_map(
function (ElementLayoutNode $node): array {
return $this->elementPayload($node);
},
$layout->getElements(),
),
]);
}
/**
* @return array{
* id: int,
* name: string,
* kind: string,
* children: list<mixed>
* }
*/
private function elementPayload(ElementLayoutNode $node): array
{
$element = $node->getElement();
return [
'id' => $element->getId(),
'name' => $element->getName(),
'kind' => $element->getKind(),
'children' => array_map(
function (ElementLayoutNode $childNode): array {
return $this->elementPayload($childNode);
},
$node->getChildren(),
),
];
}
}

View file

@ -25,6 +25,13 @@ class EloquentSetRepository implements SetRepository
);
}
public function find(int $id): ?Set
{
$model = SetModel::find($id);
return $model === null ? null : $this->toDomain($model);
}
public function all(): array
{
$models = SetModel::query()

View file

@ -6,6 +6,8 @@ interface SetRepository
{
public function create(CreateSetDto $dto): Set;
public function find(int $id): ?Set;
/**
* @return list<Set>
*/

View file

@ -0,0 +1,29 @@
<?php
namespace App\Set\UseCases\GetSetLayout;
use App\Element\Element;
final readonly class ElementLayoutNode
{
/**
* @param list<ElementLayoutNode> $children
*/
public function __construct(
private Element $element,
private array $children,
) {}
public function getElement(): Element
{
return $this->element;
}
/**
* @return list<ElementLayoutNode>
*/
public function getChildren(): array
{
return $this->children;
}
}

View file

@ -0,0 +1,77 @@
<?php
namespace App\Set\UseCases\GetSetLayout;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\NotFoundException;
use App\Set\SetRepository;
class GetSetLayout
{
public function __construct(
private SetRepository $setRepository,
private ElementRepository $elementRepository,
) {}
/**
* @throws NotFoundException
*/
public function execute(GetSetLayoutRequest $request): SetLayout
{
$set = $this->setRepository->find($request->setId);
if ($set === null) {
throw new NotFoundException('set not found');
}
$elementsByParentId = [];
foreach ($this->elementRepository->findBySet($set) as $element) {
$parentId = $element->getParentElement()?->getId() ?? 0;
$elementsByParentId[$parentId][] = $element;
}
foreach ($elementsByParentId as &$siblings) {
usort($siblings, function (
Element $first,
Element $second,
): int {
$positionComparison = $first->getPosition()
<=> $second->getPosition();
if ($positionComparison !== 0) {
return $positionComparison;
}
return $first->getId() <=> $second->getId();
});
}
unset($siblings);
return new SetLayout(
set: $set,
elements: $this->buildNodes(0, $elementsByParentId),
);
}
/**
* @param array<int, list<Element>> $elementsByParentId
* @return list<ElementLayoutNode>
*/
private function buildNodes(
int $parentId,
array $elementsByParentId,
): array {
$nodes = [];
foreach ($elementsByParentId[$parentId] ?? [] as $element) {
$nodes[] = new ElementLayoutNode(
element: $element,
children: $this->buildNodes(
$element->getId(),
$elementsByParentId,
),
);
}
return $nodes;
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace App\Set\UseCases\GetSetLayout;
final readonly class GetSetLayoutRequest
{
public function __construct(public int $setId) {}
}

View file

@ -0,0 +1,29 @@
<?php
namespace App\Set\UseCases\GetSetLayout;
use App\Set\Set;
final readonly class SetLayout
{
/**
* @param list<ElementLayoutNode> $elements
*/
public function __construct(
private Set $set,
private array $elements,
) {}
public function getSet(): Set
{
return $this->set;
}
/**
* @return list<ElementLayoutNode>
*/
public function getElements(): array
{
return $this->elements;
}
}

View file

@ -13,5 +13,6 @@ class DatabaseSeeder extends Seeder
{
$this->call(UserSeeder::class);
$this->call(SetSeeder::class);
$this->call(ElementSeeder::class);
}
}

View file

@ -0,0 +1,217 @@
<?php
namespace Database\Seeders;
use App\Element\CreateElementDto;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Set\Set;
use App\Set\SetRepository;
use Illuminate\Database\Seeder;
class ElementSeeder extends Seeder
{
private const array ELEMENTS_BY_SET = [
'Bible' => [
[
'name' => 'Genesis',
'kind' => 'book',
'children' => [
[
'name' => 'Creation',
'kind' => 'portion',
'children' => [
[
'name' => 'Chapter 1',
'kind' => 'chapter',
'children' => [],
],
[
'name' => 'Chapter 2',
'kind' => 'chapter',
'children' => [],
],
],
],
[
'name' => 'Noah',
'kind' => 'portion',
'children' => [],
],
],
],
[
'name' => 'Exodus',
'kind' => 'book',
'children' => [
[
'name' => 'Shemot',
'kind' => 'portion',
'children' => [],
],
],
],
],
'Course' => [
[
'name' => 'Foundations',
'kind' => 'module',
'children' => [
[
'name' => 'Welcome',
'kind' => 'lesson',
'children' => [],
],
[
'name' => 'Core Concepts',
'kind' => 'lesson',
'children' => [],
],
],
],
[
'name' => 'Applied Practice',
'kind' => 'module',
'children' => [
[
'name' => 'Guided Exercise',
'kind' => 'lesson',
'children' => [],
],
[
'name' => 'Final Review',
'kind' => 'lesson',
'children' => [],
],
],
],
],
'Fitness Program' => [
[
'name' => 'Foundation Phase',
'kind' => 'phase',
'children' => [
[
'name' => 'Strength Day',
'kind' => 'workout',
'children' => [
[
'name' => 'Squat',
'kind' => 'exercise',
'children' => [],
],
[
'name' => 'Push-up',
'kind' => 'exercise',
'children' => [],
],
],
],
[
'name' => 'Mobility Day',
'kind' => 'workout',
'children' => [
[
'name' => 'Hip Flow',
'kind' => 'exercise',
'children' => [],
],
],
],
],
],
[
'name' => 'Build Phase',
'kind' => 'phase',
'children' => [
[
'name' => 'Full Body Circuit',
'kind' => 'workout',
'children' => [],
],
],
],
],
];
public function run(): void
{
$elementRepository = app(ElementRepository::class);
foreach (app(SetRepository::class)->all() as $set) {
$definitions = self::ELEMENTS_BY_SET[$set->getName()] ?? null;
if ($definitions === null) {
continue;
}
$this->seedChildren(
repository: $elementRepository,
set: $set,
parentElement: null,
definitions: $definitions,
);
}
}
/**
* @param list<array{
* name: string,
* kind: string,
* children: list<mixed>
* }> $definitions
*/
private function seedChildren(
ElementRepository $repository,
Set $set,
?Element $parentElement,
array $definitions,
): void {
$siblings = $parentElement === null
? $repository->findTopLevelBySet($set)
: $repository->findByParentElement($parentElement);
foreach ($definitions as $definition) {
$element = $this->findSibling(
siblings: $siblings,
name: $definition['name'],
kind: $definition['kind'],
);
if ($element === null) {
$element = $repository->create(new CreateElementDto(
set: $set,
name: $definition['name'],
kind: $definition['kind'],
parentElement: $parentElement,
));
$siblings[] = $element;
}
$this->seedChildren(
repository: $repository,
set: $set,
parentElement: $element,
definitions: $definition['children'],
);
}
}
/**
* @param list<Element> $siblings
*/
private function findSibling(
array $siblings,
string $name,
string $kind,
): ?Element {
foreach ($siblings as $sibling) {
if (
$sibling->getName() === $name
&& $sibling->getKind() === $kind
) {
return $sibling;
}
}
return null;
}
}

View file

@ -12,5 +12,7 @@ Route::post('/confirm-email', [AuthController::class, 'confirmEmail']);
Route::middleware(AuthMiddleware::class)->group(function (): void {
Route::get('/me', [AuthController::class, 'me']);
Route::get('/sets', [SetController::class, 'index']);
Route::get('/sets/{setId}', [SetController::class, 'show'])
->whereNumber('setId');
Route::post('/logout', [AuthController::class, 'logout']);
});

View file

@ -39,6 +39,20 @@ class FakeElementRepository implements ElementRepository
return $element === null ? null : $this->copy($element);
}
public function findBySet(Set $set): array
{
$elements = array_filter(
$this->elements,
function (Element $element) use ($set): bool {
return $element->getSet()->getId() === $set->getId();
},
);
return array_map(function (Element $element): Element {
return $this->copy($element);
}, array_values($elements));
}
public function findTopLevelBySet(Set $set): array
{
$elements = array_filter(

View file

@ -26,6 +26,13 @@ class FakeSetRepository implements SetRepository
return $this->copy($set);
}
public function find(int $id): ?Set
{
$set = $this->sets[$id] ?? null;
return $set === null ? null : $this->copy($set);
}
public function all(): array
{
$sets = array_values($this->sets);

View file

@ -3,6 +3,8 @@
namespace Tests\Feature\Database;
use App\Auth\PasswordHasher;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Set\SetRepository;
use App\Shared\ValueObject\EmailAddress;
use App\User\UserRepository;
@ -60,4 +62,60 @@ class DatabaseSeederTest extends TestCase
);
}
}
public function test_it_seeds_elements_for_every_set_idempotently(): void
{
$this->seed();
$this->seed();
$sets = app(SetRepository::class)->all();
$elementRepository = app(ElementRepository::class);
$expectedElements = [
'Bible' => [
'Chapter 1:chapter:Creation',
'Chapter 2:chapter:Creation',
'Creation:portion:Genesis',
'Exodus:book:root',
'Genesis:book:root',
'Noah:portion:Genesis',
'Shemot:portion:Exodus',
],
'Course' => [
'Applied Practice:module:root',
'Core Concepts:lesson:Foundations',
'Final Review:lesson:Applied Practice',
'Foundations:module:root',
'Guided Exercise:lesson:Applied Practice',
'Welcome:lesson:Foundations',
],
'Fitness Program' => [
'Build Phase:phase:root',
'Foundation Phase:phase:root',
'Full Body Circuit:workout:Build Phase',
'Hip Flow:exercise:Mobility Day',
'Mobility Day:workout:Foundation Phase',
'Push-up:exercise:Strength Day',
'Squat:exercise:Strength Day',
'Strength Day:workout:Foundation Phase',
],
];
$this->assertDatabaseCount('elements', 21);
foreach ($sets as $set) {
$signatures = array_map(function (Element $element): string {
$parentName = $element->getParentElement()?->getName()
?? 'root';
return "{$element->getName()}:{$element->getKind()}"
. ":{$parentName}";
}, $elementRepository->findBySet($set));
sort($signatures);
$this->assertSame(
$expectedElements[$set->getName()],
$signatures,
);
}
}
}

View file

@ -156,6 +156,45 @@ class EloquentElementRepositoryTest extends TestCase
);
}
public function testItListsEveryElementForASet(): void
{
$bible = $this->createSet('Bible');
$course = $this->createSet('Course');
$repository = app(ElementRepository::class);
$genesis = $repository->create(new CreateElementDto(
set: $bible,
name: 'Genesis',
kind: 'book',
parentElement: null,
));
$repository->create(new CreateElementDto(
set: $bible,
name: 'Creation',
kind: 'portion',
parentElement: $genesis,
));
$repository->create(new CreateElementDto(
set: $course,
name: 'Foundations',
kind: 'module',
parentElement: null,
));
$elements = $repository->findBySet($bible);
$this->assertSame(
['Genesis', 'Creation'],
array_map(function ($element): string {
return $element->getName();
}, $elements),
);
$this->assertNull($elements[0]->getParentElement());
$this->assertSame(
$genesis->getId(),
$elements[1]->getParentElement()?->getId(),
);
}
private function createSet(string $name): Set
{
$creator = app(UserRepository::class)->create(new CreateUserDto(

View file

@ -66,6 +66,23 @@ class EloquentSetRepositoryTest extends TestCase
);
}
public function test_it_finds_a_set_by_id(): void
{
$creator = $this->createUser('creator@example.com');
$repository = app(SetRepository::class);
$createdSet = $repository->create(new CreateSetDto(
name: 'Bible',
creator: $creator,
));
$foundSet = $repository->find($createdSet->getId());
$this->assertNotNull($foundSet);
$this->assertSame($createdSet->getId(), $foundSet->getId());
$this->assertSame('Bible', $foundSet->getName());
$this->assertNull($repository->find(999));
}
public function test_it_rejects_duplicate_set_names(): void
{
$creator = $this->createUser('creator@example.com');

View file

@ -0,0 +1,172 @@
<?php
namespace Tests\Feature\Set;
use App\Auth\CreateSessionDto;
use App\Auth\SessionRepository;
use App\Element\CreateElementDto;
use App\Element\ElementRepository;
use App\Http\Middleware\AuthMiddleware;
use App\Set\CreateSetDto;
use App\Set\Set;
use App\Set\SetRepository;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\User;
use App\User\UserRepository;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
class GetSetLayoutEndpointTest extends TestCase
{
use RefreshDatabase;
public function test_it_returns_a_sets_ordered_element_layout(): void
{
$user = $this->createUser();
$set = $this->createSet($user, 'Bible');
$repository = app(ElementRepository::class);
$genesis = $repository->create(new CreateElementDto(
set: $set,
name: 'Genesis',
kind: 'book',
parentElement: null,
));
$repository->create(new CreateElementDto(
set: $set,
name: 'Exodus',
kind: 'book',
parentElement: null,
));
$creation = $repository->create(new CreateElementDto(
set: $set,
name: 'Creation',
kind: 'portion',
parentElement: $genesis,
));
$chapter = $repository->create(new CreateElementDto(
set: $set,
name: 'Chapter 1',
kind: 'chapter',
parentElement: $creation,
));
$this->createSession($user);
$response = $this->credentialedGet("/api/sets/{$set->getId()}");
$response->assertOk()->assertExactJson([
'set' => [
'id' => $set->getId(),
'name' => 'Bible',
],
'elements' => [
[
'id' => $genesis->getId(),
'name' => 'Genesis',
'kind' => 'book',
'children' => [
[
'id' => $creation->getId(),
'name' => 'Creation',
'kind' => 'portion',
'children' => [
[
'id' => $chapter->getId(),
'name' => 'Chapter 1',
'kind' => 'chapter',
'children' => [],
],
],
],
],
],
[
'id' => $genesis->getId() + 1,
'name' => 'Exodus',
'kind' => 'book',
'children' => [],
],
],
]);
}
public function test_it_returns_an_empty_element_layout(): void
{
$user = $this->createUser();
$set = $this->createSet($user, 'Empty set');
$this->createSession($user);
$response = $this->credentialedGet("/api/sets/{$set->getId()}");
$response->assertOk()->assertExactJson([
'set' => [
'id' => $set->getId(),
'name' => 'Empty set',
],
'elements' => [],
]);
}
public function test_it_returns_not_found_for_an_unknown_set(): void
{
$user = $this->createUser();
$this->createSession($user);
$response = $this->credentialedGet('/api/sets/999');
$response->assertNotFound()->assertExactJson([
'error' => 'set not found',
]);
}
public function test_it_rejects_an_unauthenticated_request(): void
{
$response = $this->getJson('/api/sets/1');
$response->assertStatus(401)->assertExactJson([
'error' => 'unauthenticated',
]);
}
private function createUser(): User
{
return app(UserRepository::class)->create(new CreateUserDto(
email: new EmailAddress('reader@example.com'),
passwordHash: 'hashed-password',
));
}
private function createSet(User $user, string $name): Set
{
return app(SetRepository::class)->create(new CreateSetDto(
name: $name,
creator: $user,
));
}
private function createSession(User $user): void
{
$createdAt = new DateTimeImmutable(
'2026-08-03T12:00:00',
new DateTimeZone('UTC'),
);
app(SessionRepository::class)->create(new CreateSessionDto(
token: 'valid-token',
user: $user,
createdAt: $createdAt,
expiresAt: $createdAt->modify('+7 days'),
));
}
private function credentialedGet(string $uri): TestResponse
{
return $this->withCredentials()
->withUnencryptedCookie(
AuthMiddleware::COOKIE_NAME,
'valid-token',
)->getJson($uri);
}
}

View file

@ -0,0 +1,144 @@
<?php
namespace Tests\Unit\Set\UseCases;
use App\Element\CreateElementDto;
use App\Exceptions\NotFoundException;
use App\Set\CreateSetDto;
use App\Set\UseCases\GetSetLayout\ElementLayoutNode;
use App\Set\UseCases\GetSetLayout\GetSetLayout;
use App\Set\UseCases\GetSetLayout\GetSetLayoutRequest;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
use PHPUnit\Framework\TestCase;
use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeSetRepository;
class GetSetLayoutTest extends TestCase
{
public function test_it_builds_an_ordered_element_tree(): void
{
$creator = new User(
id: 7,
email: new EmailAddress('creator@example.com'),
passwordHash: 'hashed-password',
);
$setRepository = new FakeSetRepository;
$elementRepository = new FakeElementRepository;
$bible = $setRepository->create(new CreateSetDto(
name: 'Bible',
creator: $creator,
));
$course = $setRepository->create(new CreateSetDto(
name: 'Course',
creator: $creator,
));
$genesis = $elementRepository->create(new CreateElementDto(
set: $bible,
name: 'Genesis',
kind: 'book',
parentElement: null,
));
$elementRepository->create(new CreateElementDto(
set: $bible,
name: 'Exodus',
kind: 'book',
parentElement: null,
));
$creation = $elementRepository->create(new CreateElementDto(
set: $bible,
name: 'Creation',
kind: 'portion',
parentElement: $genesis,
));
$elementRepository->create(new CreateElementDto(
set: $bible,
name: 'Noah',
kind: 'portion',
parentElement: $genesis,
));
$elementRepository->create(new CreateElementDto(
set: $bible,
name: 'Chapter 1',
kind: 'chapter',
parentElement: $creation,
));
$elementRepository->create(new CreateElementDto(
set: $course,
name: 'Foundations',
kind: 'module',
parentElement: null,
));
$layout = (new GetSetLayout(
$setRepository,
$elementRepository,
))->execute(new GetSetLayoutRequest(
setId: $bible->getId(),
));
$this->assertSame('Bible', $layout->getSet()->getName());
$this->assertSame(
['Genesis', 'Exodus'],
$this->nodeNames($layout->getElements()),
);
$genesisNode = $layout->getElements()[0];
$this->assertSame(
['Creation', 'Noah'],
$this->nodeNames($genesisNode->getChildren()),
);
$this->assertSame(
['Chapter 1'],
$this->nodeNames(
$genesisNode->getChildren()[0]->getChildren(),
),
);
}
public function test_it_returns_an_empty_layout(): void
{
$creator = new User(
id: 7,
email: new EmailAddress('creator@example.com'),
passwordHash: 'hashed-password',
);
$setRepository = new FakeSetRepository;
$set = $setRepository->create(new CreateSetDto(
name: 'Empty set',
creator: $creator,
));
$layout = (new GetSetLayout(
$setRepository,
new FakeElementRepository,
))->execute(new GetSetLayoutRequest(
setId: $set->getId(),
));
$this->assertSame([], $layout->getElements());
}
public function test_it_rejects_an_unknown_set(): void
{
$this->expectException(NotFoundException::class);
$this->expectExceptionMessage('set not found');
(new GetSetLayout(
new FakeSetRepository,
new FakeElementRepository,
))->execute(new GetSetLayoutRequest(
setId: 999,
));
}
/**
* @param list<ElementLayoutNode> $nodes
* @return list<string>
*/
private function nodeNames(array $nodes): array
{
return array_map(function ($node): string {
return $node->getElement()->getName();
}, $nodes);
}
}

View file

@ -24,6 +24,13 @@ describe('guest authentication pages', () => {
cy.location('search').should('include', 'redirect=/dashboard')
})
it('redirects guests away from a protected set layout', () => {
cy.visit('/sets/41')
cy.location('pathname').should('equal', '/login')
cy.location('search').should('include', 'redirect=/sets/41')
})
it('shows the login form and links to signup', () => {
cy.visit('/login')

View file

@ -0,0 +1,183 @@
const authenticatedUser = {
id: 7,
email: 'user@example.com',
}
const bibleLayout = {
set: { id: 41, name: 'Bible' },
elements: [
{
id: 1,
name: 'Genesis',
kind: 'book',
children: [
{
id: 3,
name: 'Creation',
kind: 'portion',
children: [
{
id: 4,
name: 'Chapter 1',
kind: 'chapter',
children: [],
},
],
},
{ id: 5, name: 'Noah', kind: 'portion', children: [] },
],
},
{ id: 2, name: 'Exodus', kind: 'book', children: [] },
],
}
function interceptAuthenticatedUser(): void {
cy.intercept('GET', '**/api/me', {
statusCode: 200,
body: { user: authenticatedUser },
}).as('me')
}
describe('set element layout', () => {
beforeEach(() => {
interceptAuthenticatedUser()
})
it('opens a set from the dashboard and shows its full hierarchy', () => {
cy.intercept('GET', '**/api/sets', {
statusCode: 200,
body: { sets: [{ id: 41, name: 'Bible' }] },
}).as('sets')
cy.intercept('GET', '**/api/sets/41', (request) => {
expect(request.headers.accept).to.equal('application/json')
request.reply({ statusCode: 200, body: bibleLayout })
}).as('layout')
cy.visit('/dashboard')
cy.wait('@me')
cy.wait('@sets')
cy.contains('a', 'Bible').click()
cy.wait('@layout')
cy.location('pathname').should('equal', '/sets/41')
cy.get('h1').should('have.text', 'Bible')
cy.contains('a', 'Back to sets').should('have.attr', 'href', '/dashboard')
cy.get('ol[aria-label="Bible element layout"] > li').then(($nodes) => {
expect([...$nodes].map((node) => node.dataset.elementId)).to.deep.equal([
'1',
'2',
])
})
cy.get('[data-element-id="1"] > .element-node__card')
.should('contain.text', 'Genesis')
.and('contain.text', 'book')
cy.get('[data-element-id="1"] > ol > li').then(($nodes) => {
expect([...$nodes].map((node) => node.dataset.elementId)).to.deep.equal([
'3',
'5',
])
})
cy.get('[data-element-id="3"] > ol > li')
.should('have.length', 1)
.and('have.attr', 'data-element-id', '4')
cy.contains('.element-node__card', 'Chapter 1')
.should('be.visible')
.and('contain.text', 'chapter')
})
it('shows loading and empty layout states', () => {
cy.intercept('GET', '**/api/sets/41', {
delay: 500,
statusCode: 200,
body: { set: { id: 41, name: 'Empty set' }, elements: [] },
}).as('layout')
cy.visit('/sets/41')
cy.wait('@me')
cy.get('[role="status"]').should('have.text', 'Loading set layout...')
cy.wait('@layout')
cy.get('h1').should('have.text', 'Empty set')
cy.get('[role="status"]').should(
'have.text',
'This set does not have any elements yet.',
)
})
it('retries after a layout request fails', () => {
let requestCount = 0
cy.intercept('GET', '**/api/sets/41', (request) => {
requestCount += 1
request.alias = `layout${requestCount}`
if (requestCount === 1) {
request.reply({ statusCode: 500 })
return
}
request.reply({ statusCode: 200, body: bibleLayout })
})
cy.visit('/sets/41')
cy.wait('@me')
cy.wait('@layout1')
cy.get('[role="alert"]').should(
'contain.text',
"We couldn't load this set's layout.",
)
cy.contains('button', 'Try again').click()
cy.wait('@layout2')
cy.get('h1').should('have.text', 'Bible')
})
it('distinguishes missing sets from malformed responses', () => {
cy.intercept('GET', '**/api/sets/41', {
statusCode: 404,
body: { error: 'set not found' },
}).as('missing')
cy.visit('/sets/41')
cy.wait('@me')
cy.wait('@missing')
cy.get('h1').should('have.text', 'Set not found')
cy.get('[role="alert"]').should(
'contain.text',
"The set you're looking for is not available.",
)
cy.intercept('GET', '**/api/sets/42', {
statusCode: 200,
body: { set: { id: 42, name: 12 }, elements: [] },
}).as('malformed')
cy.visit('/sets/42')
cy.wait('@malformed')
cy.get('[role="alert"]').should(
'contain.text',
"We couldn't load this set's layout.",
)
cy.contains('button', 'Try again').should('be.visible')
})
it('keeps a deeply nested layout within a mobile viewport', () => {
cy.viewport(390, 844)
cy.intercept('GET', '**/api/sets/41', {
statusCode: 200,
body: bibleLayout,
}).as('layout')
cy.visit('/sets/41')
cy.wait('@me')
cy.wait('@layout')
cy.contains('.element-node__card', 'Chapter 1').should('be.visible')
cy.document().then((document) => {
expect(document.documentElement.scrollWidth).to.be.at.most(
document.documentElement.clientWidth,
)
})
})
})

View file

@ -15,7 +15,7 @@ describe('sets dashboard', () => {
interceptAuthenticatedUser()
})
it('shows every available set by name', () => {
it('shows every available set as a detail link', () => {
cy.intercept('GET', '**/api/sets', (request) => {
expect(request.headers.accept).to.equal('application/json')
request.reply({
@ -46,8 +46,13 @@ describe('sets dashboard', () => {
.should('not.contain.text', '41')
.and('not.contain.text', '58')
.and('not.contain.text', '92')
.find('a, button')
.should('not.exist')
cy.contains('a', 'Bible').should('have.attr', 'href', '/sets/41')
cy.contains('a', 'Course').should('have.attr', 'href', '/sets/58')
cy.contains('a', 'Fitness Program').should(
'have.attr',
'href',
'/sets/92',
)
})
it('shows loading and empty catalog states', () => {

View file

@ -0,0 +1,59 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import BrandWordmark from '@/components/BrandWordmark.vue'
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
const router = useRouter()
async function handleLogout(): Promise<void> {
await authStore.logout()
await router.push({ name: 'login' })
}
</script>
<template>
<header class="authenticated-header">
<BrandWordmark theme="dark" />
<button type="button" class="logout-button" @click="handleLogout">Log out</button>
</header>
</template>
<style scoped>
.authenticated-header {
display: flex;
width: min(100%, 76rem);
align-items: center;
justify-content: space-between;
margin: 0 auto;
}
.logout-button {
min-height: 2.75rem;
padding: 0.7rem 1.1rem;
border: 0;
border-radius: 0.7rem;
color: #fffdf7;
background: #183a31;
box-shadow: 0 0.55rem 1.2rem rgb(24 58 49 / 14%);
font-size: 0.82rem;
font-weight: 750;
cursor: pointer;
transition:
background-color 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.logout-button:hover {
background: #285c4e;
box-shadow: 0 0.7rem 1.4rem rgb(24 58 49 / 18%);
transform: translateY(-1px);
}
.logout-button:focus-visible {
outline: 3px solid rgb(86 127 112 / 34%);
outline-offset: 0.25rem;
}
</style>

View file

@ -0,0 +1,114 @@
<script setup lang="ts">
import type { SetElementNode } from '@/stores/setLayout'
defineProps<{
nodes: SetElementNode[]
label?: string
}>()
</script>
<template>
<ol
class="element-tree"
:class="{ 'element-tree--root': label !== undefined }"
:aria-label="label"
>
<li v-for="node in nodes" :key="node.id" class="element-tree__item" :data-element-id="node.id">
<div class="element-node__card">
<span class="element-node__name">{{ node.name }}</span>
<span class="element-node__kind">{{ node.kind }}</span>
</div>
<ElementTree v-if="node.children.length > 0" :nodes="node.children" />
</li>
</ol>
</template>
<style scoped>
.element-tree {
display: grid;
gap: 0.75rem;
margin: 0.75rem 0 0 1.25rem;
padding: 0 0 0 1.35rem;
border-left: 1px solid rgb(146 96 68 / 28%);
list-style: none;
}
.element-tree--root {
gap: 1rem;
margin: 0;
padding: 0;
border-left: 0;
}
.element-tree__item {
position: relative;
min-width: 0;
}
.element-tree:not(.element-tree--root) > .element-tree__item::before {
position: absolute;
top: 1.55rem;
left: -1.35rem;
width: 1rem;
border-top: 1px solid rgb(146 96 68 / 28%);
content: '';
}
.element-node__card {
display: flex;
min-width: 0;
min-height: 3.1rem;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.8rem 1rem;
border: 1px solid rgb(24 48 41 / 12%);
border-radius: 0.8rem;
background: rgb(255 253 247 / 88%);
box-shadow: 0 0.55rem 1.5rem rgb(40 62 52 / 6%);
}
.element-node__name {
min-width: 0;
color: #183029;
font-family: Georgia, 'Times New Roman', serif;
font-size: clamp(1.05rem, 2vw, 1.25rem);
line-height: 1.25;
overflow-wrap: anywhere;
}
.element-node__kind {
flex: 0 0 auto;
padding: 0.35rem 0.55rem;
border-radius: 999px;
color: #81533a;
background: #efe4d4;
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
@media (max-width: 37.5rem) {
.element-tree {
margin-left: 0.45rem;
padding-left: 0.65rem;
}
.element-tree:not(.element-tree--root) > .element-tree__item::before {
left: -0.65rem;
width: 0.45rem;
}
.element-node__card {
gap: 0.6rem;
padding: 0.75rem 0.7rem;
}
.element-node__kind {
padding-inline: 0.42rem;
font-size: 0.56rem;
}
}
</style>

View file

@ -63,6 +63,14 @@ const router = createRouter({
requiresAuth: true,
},
},
{
path: '/sets/:setId(\\d+)',
name: 'set-layout',
component: () => import('@/views/SetLayoutView.vue'),
meta: {
requiresAuth: true,
},
},
],
})

View file

@ -0,0 +1,102 @@
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { z } from 'zod'
import { API_BASE } from '@/utils/apiBase'
export const setElementNodeSchema = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
kind: z.string().min(1),
get children() {
return z.array(setElementNodeSchema)
},
})
export const setLayoutResponseSchema = z.object({
set: z.object({
id: z.number().int().positive(),
name: z.string().min(1),
}),
elements: z.array(setElementNodeSchema),
})
export type SetElementNode = z.infer<typeof setElementNodeSchema>
export type SetLayoutResponse = z.infer<typeof setLayoutResponseSchema>
const LOAD_ERROR = "We couldn't load this set's layout."
export const useSetLayoutStore = defineStore('set-layout', () => {
const layout = ref<SetLayoutResponse | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const notFound = ref(false)
let activeRequestId = 0
async function fetchSetLayout(setId: number): Promise<boolean> {
const requestId = ++activeRequestId
layout.value = null
loading.value = true
error.value = null
notFound.value = false
try {
const response = await fetch(`${API_BASE}/api/sets/${setId}`, {
method: 'GET',
credentials: 'include',
headers: {
Accept: 'application/json',
},
})
if (requestId !== activeRequestId) {
return false
}
if (response.status === 404) {
notFound.value = true
return false
}
if (response.status !== 200) {
error.value = LOAD_ERROR
return false
}
const responseBody: unknown = await response.json()
if (requestId !== activeRequestId) {
return false
}
const parsedLayout = setLayoutResponseSchema.parse(responseBody)
if (parsedLayout.set.id !== setId) {
throw new Error('set response did not match requested set')
}
layout.value = parsedLayout
return true
} catch {
if (requestId === activeRequestId) {
layout.value = null
error.value = LOAD_ERROR
}
return false
} finally {
if (requestId === activeRequestId) {
loading.value = false
}
}
}
return {
layout,
loading,
error,
notFound,
fetchSetLayout,
}
})

View file

@ -1,33 +1,21 @@
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import BrandWordmark from '@/components/BrandWordmark.vue'
import { useAuthStore } from '@/stores/auth'
import AuthenticatedHeader from '@/components/AuthenticatedHeader.vue'
import { useSetsStore } from '@/stores/sets'
const authStore = useAuthStore()
const setsStore = useSetsStore()
const { sets, loading, error } = storeToRefs(setsStore)
const router = useRouter()
onMounted(async () => {
await setsStore.fetchSets()
})
async function handleLogout(): Promise<void> {
await authStore.logout()
await router.push({ name: 'login' })
}
</script>
<template>
<main class="dashboard-page">
<header class="dashboard-header">
<BrandWordmark theme="dark" />
<button type="button" class="logout-button" @click="handleLogout">Log out</button>
</header>
<AuthenticatedHeader />
<section class="sets-catalog" aria-labelledby="sets-heading">
<div class="sets-catalog__introduction">
@ -51,10 +39,19 @@ async function handleLogout(): Promise<void> {
<ul v-else class="set-grid" aria-label="Available sets">
<li v-for="availableSet in sets" :key="availableSet.id">
<RouterLink
class="set-card-link"
:to="{ name: 'set-layout', params: { setId: availableSet.id } }"
>
<article class="set-card">
<p>Set</p>
<h2>{{ availableSet.name }}</h2>
<span class="set-card__action">
Explore layout
<span aria-hidden="true"></span>
</span>
</article>
</RouterLink>
</li>
</ul>
</section>
@ -70,42 +67,6 @@ async function handleLogout(): Promise<void> {
background: #f4f1e7;
}
.dashboard-header {
display: flex;
width: min(100%, 76rem);
align-items: center;
justify-content: space-between;
margin: 0 auto;
}
.logout-button {
min-height: 2.75rem;
padding: 0.7rem 1.1rem;
border: 0;
border-radius: 0.7rem;
color: #fffdf7;
background: #183a31;
box-shadow: 0 0.55rem 1.2rem rgb(24 58 49 / 14%);
font-size: 0.82rem;
font-weight: 750;
cursor: pointer;
transition:
background-color 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.logout-button:hover {
background: #285c4e;
box-shadow: 0 0.7rem 1.4rem rgb(24 58 49 / 18%);
transform: translateY(-1px);
}
.logout-button:focus-visible {
outline: 3px solid rgb(86 127 112 / 34%);
outline-offset: 0.25rem;
}
.sets-catalog {
width: min(100%, 72rem);
margin: clamp(4.5rem, 10vh, 7rem) auto 0;
@ -195,12 +156,35 @@ h1 {
}
.set-card {
height: 100%;
min-height: 11rem;
padding: 1.6rem;
border: 1px solid rgb(24 48 41 / 12%);
border-radius: 1rem;
background: linear-gradient(135deg, rgb(255 253 247 / 96%), rgb(242 236 221 / 82%));
box-shadow: 0 1rem 2.5rem rgb(40 62 52 / 8%);
transition:
border-color 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.set-card-link {
display: block;
height: 100%;
border-radius: 1rem;
text-decoration: none;
}
.set-card-link:hover .set-card {
border-color: rgb(40 92 78 / 35%);
box-shadow: 0 1.25rem 2.75rem rgb(40 62 52 / 13%);
transform: translateY(-3px);
}
.set-card-link:focus-visible {
outline: 3px solid rgb(86 127 112 / 38%);
outline-offset: 0.25rem;
}
.set-card p {
@ -222,6 +206,16 @@ h1 {
letter-spacing: -0.035em;
}
.set-card__action {
display: inline-flex;
align-items: center;
gap: 0.35rem;
margin-top: 1.4rem;
color: #567064;
font-size: 0.76rem;
font-weight: 750;
}
@media (max-width: 37.5rem) {
.dashboard-page {
padding: 1.4rem 1.1rem 2.5rem;

View file

@ -0,0 +1,218 @@
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import AuthenticatedHeader from '@/components/AuthenticatedHeader.vue'
import ElementTree from '@/components/ElementTree.vue'
import { useSetLayoutStore } from '@/stores/setLayout'
const route = useRoute()
const setLayoutStore = useSetLayoutStore()
const { layout, loading, error, notFound } = storeToRefs(setLayoutStore)
const currentSetId = ref<number | null>(null)
const EMPTY_MESSAGE = 'This set does not have any elements yet.'
watch(
() => route.params.setId,
async (setIdParameter) => {
const rawSetId = Array.isArray(setIdParameter) ? setIdParameter[0] : setIdParameter
const setId = Number(rawSetId)
currentSetId.value = setId
await setLayoutStore.fetchSetLayout(setId)
},
{ immediate: true },
)
async function retry(): Promise<void> {
if (currentSetId.value === null) {
return
}
await setLayoutStore.fetchSetLayout(currentSetId.value)
}
</script>
<template>
<main class="layout-page">
<AuthenticatedHeader />
<section class="set-layout">
<RouterLink class="back-link" :to="{ name: 'dashboard' }">
<span aria-hidden="true"></span>
Back to sets
</RouterLink>
<p v-if="loading" class="layout-state" role="status">Loading set layout...</p>
<div v-else-if="notFound" class="layout-state layout-state--error" role="alert">
<p class="set-layout__eyebrow">Your library</p>
<h1>Set not found</h1>
<p>The set you're looking for is not available.</p>
</div>
<div v-else-if="error !== null" class="layout-state layout-state--error" role="alert">
<p>{{ error }}</p>
<button type="button" class="retry-button" @click="retry">Try again</button>
</div>
<template v-else-if="layout !== null">
<header class="set-layout__introduction">
<p class="set-layout__eyebrow">Set layout</p>
<h1>{{ layout.set.name }}</h1>
<p class="set-layout__description">
Explore every element in this set and see how each level fits into the whole.
</p>
</header>
<p
v-if="layout.elements.length === 0"
class="layout-state"
role="status"
v-text="EMPTY_MESSAGE"
></p>
<div v-else class="layout-outline">
<ElementTree :nodes="layout.elements" :label="`${layout.set.name} element layout`" />
</div>
</template>
</section>
</main>
</template>
<style scoped>
.layout-page {
min-height: 100vh;
min-height: 100svh;
padding: 2rem clamp(1.5rem, 6vw, 5rem) 5rem;
color: #183029;
background: #f4f1e7;
}
.set-layout {
width: min(100%, 62rem);
margin: clamp(3.5rem, 8vh, 5.5rem) auto 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 0.45rem;
border-radius: 0.35rem;
color: #5e7067;
font-size: 0.84rem;
font-weight: 750;
text-decoration: none;
}
.back-link:hover {
color: #183a31;
}
.back-link:focus-visible {
outline: 3px solid rgb(86 127 112 / 34%);
outline-offset: 0.25rem;
}
.set-layout__introduction {
max-width: 44rem;
margin-top: 2.75rem;
}
.set-layout__eyebrow {
margin: 0 0 1rem;
color: #926044;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, 'Times New Roman', serif;
font-size: clamp(3rem, 7vw, 5.25rem);
font-weight: 500;
line-height: 1;
letter-spacing: -0.055em;
overflow-wrap: anywhere;
}
.set-layout__description {
max-width: 38rem;
margin: 1.5rem 0 0;
color: #68776f;
line-height: 1.7;
}
.layout-outline {
margin-top: 3rem;
}
.layout-state {
display: grid;
width: 100%;
min-height: 10rem;
place-items: center;
margin: 2.75rem 0 0;
padding: 2rem;
border: 1px solid rgb(24 48 41 / 12%);
border-radius: 1rem;
color: #68776f;
background: rgb(255 253 247 / 72%);
text-align: center;
}
.layout-state--error {
align-content: center;
gap: 1rem;
}
.layout-state--error p {
margin: 0;
}
.layout-state--error h1 {
font-size: clamp(2.25rem, 5vw, 3.6rem);
}
.retry-button {
min-height: 2.65rem;
padding: 0.65rem 1rem;
border: 1px solid rgb(24 58 49 / 28%);
border-radius: 0.7rem;
color: #183a31;
background: #fffdf7;
font-size: 0.82rem;
font-weight: 750;
cursor: pointer;
}
.retry-button:hover {
border-color: #285c4e;
background: #f9f5e9;
}
.retry-button:focus-visible {
outline: 3px solid rgb(86 127 112 / 34%);
outline-offset: 0.25rem;
}
@media (max-width: 37.5rem) {
.layout-page {
padding: 1.4rem 1.1rem 3rem;
}
.set-layout {
margin-top: 3rem;
}
.set-layout__introduction {
margin-top: 2.25rem;
}
.layout-outline {
margin-top: 2.25rem;
}
}
</style>