add child element ordering

This commit is contained in:
Yisroel Baum 2026-06-22 09:51:21 +03:00
parent 7323925319
commit 62dc119b11
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
12 changed files with 554 additions and 11 deletions

View file

@ -9,6 +9,8 @@ use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElementRequest;
use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\GetElement\GetElementRequest;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\ReorderChildElements\ReorderChildElementsRequest;
use App\Element\UseCases\UpdateElement\UpdateElement;
use App\Element\UseCases\UpdateElement\UpdateElementRequest;
use App\Exceptions\BadRequestException;
@ -24,6 +26,7 @@ class ElementController
private GetElement $getElement,
private CreateChildElement $createChildElement,
private DeleteChildElement $deleteChildElement,
private ReorderChildElements $reorderChildElements,
private UpdateElement $updateElement,
private FileUploader $fileUploader,
) {
@ -104,6 +107,37 @@ class ElementController
return new JsonResponse(null, 204);
}
public function reorderChildren(
Request $request,
?int $parentId,
): JsonResponse {
try {
$childElements = $this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentId,
childElementIds: $this->intArrayInput(
$request,
'childElementIds',
),
)
);
} catch (BadRequestException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 400);
} catch (NotFoundException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 404);
}
return new JsonResponse([
'childElements' => $this->buildElementSummaryPayloads(
$childElements,
),
], 200);
}
public function update(Request $request): JsonResponse
{
$file = $this->uploadedFileInput($request, 'file');
@ -158,6 +192,38 @@ class ElementController
return null;
}
/**
* @return int[]|null
*/
private function intArrayInput(Request $request, string $key): ?array
{
if (! $request->exists($key)) {
return null;
}
$value = $request->input($key);
if (! is_array($value)) {
return null;
}
$integerValues = [];
foreach ($value as $item) {
if (is_int($item)) {
$integerValues[] = $item;
continue;
}
if (is_string($item) && ctype_digit($item)) {
$integerValues[] = (int) $item;
continue;
}
return null;
}
return $integerValues;
}
private function stringInput(Request $request, string $key): ?string
{
if (! $request->exists($key)) {

View file

@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $long_pdf_path
* @property string|null $youtube_url
* @property int|null $parent_element_id
* @property int $sort_order
*
* @method static Builder<static>|ElementModel newModelQuery()
* @method static Builder<static>|ElementModel newQuery()
@ -30,6 +31,7 @@ use Illuminate\Database\Eloquent\Model;
* @method static Builder<static>|ElementModel whereShortPdfPath($value)
* @method static Builder<static>|ElementModel whereLongPdfPath($value)
* @method static Builder<static>|ElementModel whereYoutubeUrl($value)
* @method static Builder<static>|ElementModel whereSortOrder($value)
*
* @mixin \Eloquent
*/
@ -49,10 +51,12 @@ class ElementModel extends Model
'long_pdf_path',
'youtube_url',
'parent_element_id',
'sort_order',
];
protected $casts = [
'set_id' => 'integer',
'parent_element_id' => 'integer',
'sort_order' => 'integer',
];
}

View file

@ -25,4 +25,13 @@ interface ElementRepository
* @return Element[]
*/
public function findByParentElement(Element $parentElement): array;
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array;
}

View file

@ -5,6 +5,7 @@ namespace App\Element;
use App\Set\Set as DomainSet;
use App\Set\SetRepository;
use DomainException;
use Illuminate\Support\Facades\DB;
class EloquentElementRepository implements ElementRepository
{
@ -14,6 +15,7 @@ class EloquentElementRepository implements ElementRepository
public function create(CreateElementDto $dto): Element
{
$parentElementId = $dto->parentElement?->getId();
$model = ElementModel::create([
'set_id' => $dto->set->getId(),
'title' => $dto->title,
@ -23,7 +25,8 @@ class EloquentElementRepository implements ElementRepository
'short_pdf_path' => $dto->shortPdfPath,
'long_pdf_path' => $dto->longPdfPath,
'youtube_url' => $dto->youtubeUrl,
'parent_element_id' => $dto->parentElement?->getId(),
'parent_element_id' => $parentElementId,
'sort_order' => $this->nextSortOrder($dto->set, $parentElementId),
]);
return new Element(
@ -86,6 +89,7 @@ class EloquentElementRepository implements ElementRepository
{
$model = ElementModel::where('set_id', $set->getId())
->whereNull('parent_element_id')
->orderBy('sort_order')
->orderBy('id')
->first();
@ -117,6 +121,7 @@ class EloquentElementRepository implements ElementRepository
'parent_element_id',
$parentElement->getId(),
)
->orderBy('sort_order')
->orderBy('id')
->get();
$elements = [];
@ -127,6 +132,46 @@ class EloquentElementRepository implements ElementRepository
return $elements;
}
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array {
DB::transaction(function () use ($parentElement, $childElementIds) {
$sortOrder = 1;
foreach ($childElementIds as $childElementId) {
ElementModel::where('id', $childElementId)
->where('parent_element_id', $parentElement->getId())
->update(['sort_order' => $sortOrder]);
$sortOrder++;
}
});
return $this->findByParentElement($parentElement);
}
private function nextSortOrder(
DomainSet $set,
?int $parentElementId,
): int {
$query = ElementModel::where('set_id', $set->getId());
if ($parentElementId === null) {
$query->whereNull('parent_element_id');
} else {
$query->where('parent_element_id', $parentElementId);
}
$currentMaxSortOrder = $query->max('sort_order');
if ($currentMaxSortOrder === null) {
return 1;
}
return (int) $currentMaxSortOrder + 1;
}
private function toDomain(ElementModel $model): Element
{
$set = $this->setRepo->find($model->set_id);

View file

@ -0,0 +1,154 @@
<?php
namespace App\Element\UseCases\ReorderChildElements;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
class ReorderChildElements
{
public function __construct(private ElementRepository $elementRepository)
{
}
/**
* @return Element[]
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(ReorderChildElementsRequest $request): array
{
if ($request->parentElementId === null) {
throw new BadRequestException('parentElementId is required');
}
if ($request->childElementIds === null) {
throw new BadRequestException('childElementIds is required');
}
$parentElement = $this->elementRepository->find(
$request->parentElementId,
);
if ($parentElement === null) {
throw new NotFoundException('Parent element not found');
}
$childElementIds = $this->validatedChildElementIds(
$request->childElementIds,
);
$directChildElementIds = $this->elementIds(
$this->elementRepository->findByParentElement($parentElement),
);
$this->validateNoDuplicateIds($childElementIds);
$this->validateAllIdsAreDirectChildren(
$childElementIds,
$directChildElementIds,
);
$this->validateEveryDirectChildWasSubmitted(
$childElementIds,
$directChildElementIds,
);
return $this->elementRepository->reorderChildren(
$parentElement,
$childElementIds,
);
}
/**
* @param mixed[] $childElementIds
* @return int[]
* @throws BadRequestException
*/
private function validatedChildElementIds(array $childElementIds): array
{
$validatedChildElementIds = [];
foreach ($childElementIds as $childElementId) {
if (! is_int($childElementId)) {
throw new BadRequestException(
'childElementIds must contain integers',
);
}
$validatedChildElementIds[] = $childElementId;
}
return $validatedChildElementIds;
}
/**
* @param int[] $childElementIds
* @throws BadRequestException
*/
private function validateNoDuplicateIds(array $childElementIds): void
{
$seenChildElementIds = [];
foreach ($childElementIds as $childElementId) {
if (isset($seenChildElementIds[$childElementId])) {
throw new BadRequestException(
'Child order contains duplicate ids',
);
}
$seenChildElementIds[$childElementId] = true;
}
}
/**
* @param int[] $childElementIds
* @param int[] $directChildElementIds
* @throws BadRequestException
*/
private function validateAllIdsAreDirectChildren(
array $childElementIds,
array $directChildElementIds,
): void {
$directChildElementIdsById = [];
foreach ($directChildElementIds as $directChildElementId) {
$directChildElementIdsById[$directChildElementId] = true;
}
foreach ($childElementIds as $childElementId) {
if (! isset($directChildElementIdsById[$childElementId])) {
throw new BadRequestException(
'Child order contains invalid child',
);
}
}
}
/**
* @param int[] $childElementIds
* @param int[] $directChildElementIds
* @throws BadRequestException
*/
private function validateEveryDirectChildWasSubmitted(
array $childElementIds,
array $directChildElementIds,
): void {
if (count($childElementIds) === count($directChildElementIds)) {
return;
}
throw new BadRequestException(
'Child order must include every direct child',
);
}
/**
* @param Element[] $elements
* @return int[]
*/
private function elementIds(array $elements): array
{
$elementIds = [];
foreach ($elements as $element) {
$elementIds[] = $element->getId();
}
return $elementIds;
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Element\UseCases\ReorderChildElements;
class ReorderChildElementsRequest
{
/**
* @param int[]|null $childElementIds
*/
public function __construct(
public ?int $parentElementId,
public ?array $childElementIds,
) {
}
}

View file

@ -21,6 +21,7 @@ return new class extends Migration
$table->foreignId('parent_element_id')
->nullable()
->constrained('elements');
$table->unsignedInteger('sort_order');
});
}

View file

@ -17,6 +17,11 @@ Route::post('/elements/{parentId}/children', [
'createChild',
])
->middleware(AuthMiddleware::class);
Route::put('/elements/{parentId}/children/order', [
ElementController::class,
'reorderChildren',
])
->middleware(AuthMiddleware::class);
Route::delete('/elements/{parentId}/children/{childId}', [
ElementController::class,
'deleteChild',

View file

@ -14,6 +14,11 @@ class FakeElementRepository implements ElementRepository
*/
private array $elementsById = [];
/**
* @var array<int, int>
*/
private array $sortOrdersById = [];
public function create(CreateElementDto $dto): Element
{
$id = count($this->elementsById) + 1;
@ -30,6 +35,9 @@ class FakeElementRepository implements ElementRepository
parentElement: $dto->parentElement,
);
$this->elementsById[$id] = $element;
$this->sortOrdersById[$id] = $this->nextSortOrder(
$dto->parentElement,
);
return $element;
}
@ -45,6 +53,7 @@ class FakeElementRepository implements ElementRepository
public function delete(Element $element): void
{
unset($this->elementsById[$element->getId()]);
unset($this->sortOrdersById[$element->getId()]);
}
public function find(int $id): ?Element
@ -100,10 +109,43 @@ class FakeElementRepository implements ElementRepository
$elements[] = $this->cloneElement($element);
}
}
usort($elements, function (
Element $firstElement,
Element $secondElement,
): int {
$firstSortOrder = $this->sortOrdersById[
$firstElement->getId()
] ?? $firstElement->getId();
$secondSortOrder = $this->sortOrdersById[
$secondElement->getId()
] ?? $secondElement->getId();
if ($firstSortOrder === $secondSortOrder) {
return $firstElement->getId() <=> $secondElement->getId();
}
return $firstSortOrder <=> $secondSortOrder;
});
return $elements;
}
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array {
$sortOrder = 1;
foreach ($childElementIds as $childElementId) {
$this->sortOrdersById[$childElementId] = $sortOrder;
$sortOrder++;
}
return $this->findByParentElement($parentElement);
}
private function cloneElement(Element $element): Element
{
$parentElement = $element->getParentElement();
@ -124,4 +166,24 @@ class FakeElementRepository implements ElementRepository
parentElement: $parentElement,
);
}
private function nextSortOrder(?Element $parentElement): int
{
$parentElementId = $parentElement?->getId();
$nextSortOrder = 1;
foreach ($this->elementsById as $element) {
$currentParentElement = $element->getParentElement();
$currentParentElementId = $currentParentElement?->getId();
if ($currentParentElementId !== $parentElementId) {
continue;
}
$currentSortOrder = $this->sortOrdersById[$element->getId()] ?? 0;
if ($currentSortOrder >= $nextSortOrder) {
$nextSortOrder = $currentSortOrder + 1;
}
}
return $nextSortOrder;
}
}

View file

@ -8,6 +8,7 @@ use App\Element\Element;
use App\Element\UseCases\CreateChildElement\CreateChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\UpdateElement\UpdateDescription;
use App\Element\UseCases\UpdateElement\UpdateElement;
use App\Element\UseCases\UpdateElement\UpdateIconImage;
@ -65,6 +66,7 @@ class ElementControllerTest extends TestCase
$getElement,
new CreateChildElement($this->elementRepo),
new DeleteChildElement($this->elementRepo, $this->fileUploader),
new ReorderChildElements($this->elementRepo),
$updateElement,
$this->fileUploader,
);

View file

@ -38,6 +38,10 @@ interface UpdateElementResponse {
element: Element
}
interface ReorderChildElementsResponse {
childElements: ChildElement[]
}
interface ElementPatchInput {
title?: string
description?: string
@ -145,6 +149,34 @@ export const useElementsStore = defineStore('elements', () => {
}
}
async function reorderChildElements(
parentElementId: string,
childElementIds: number[],
): Promise<boolean> {
childActionError.value = null
isManagingChildren.value = true
try {
const encodedParentElementId = encodeURIComponent(parentElementId)
const response = await fetch(
`${ELEMENTS_URL}/${encodedParentElementId}/children/order`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ childElementIds }),
},
)
return await handleReorderChildElementsResponse(response)
} catch {
childActionError.value = 'Network error - could not save child order'
return false
} finally {
isManagingChildren.value = false
}
}
async function deleteChildElement(
parentElementId: string,
childElementId: number,
@ -350,6 +382,32 @@ export const useElementsStore = defineStore('elements', () => {
return data.element
}
async function handleReorderChildElementsResponse(
response: Response,
): Promise<boolean> {
if (response.status === 401) {
childActionError.value = 'Please log in again'
return false
}
if (response.status === 400 || response.status === 404) {
childActionError.value = await errorMessage(
response,
'Could not save child order',
)
return false
}
if (!response.ok) {
childActionError.value = 'Could not save child order'
return false
}
const data: ReorderChildElementsResponse = await response.json()
childElements.value = data.childElements
return true
}
async function handleDeleteChildElementResponse(
response: Response,
childElementId: number,
@ -406,6 +464,7 @@ export const useElementsStore = defineStore('elements', () => {
fetchElement,
updateElement,
createChildElement,
reorderChildElements,
deleteChildElement,
uploadElementIconImage,
uploadElementShortPdf,

View file

@ -1,12 +1,18 @@
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { computed, reactive, ref, watch } from 'vue'
import {
ChevronDown as ChevronDownIcon,
ChevronUp as ChevronUpIcon,
} from 'lucide-vue-next'
import { useRoute, useRouter } from 'vue-router'
import ElementSiblingNavigation from '@/components/ElementSiblingNavigation.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'
import SiteHeader from '@/components/SiteHeader.vue'
import { useElementsStore } from '@/stores/elements'
type ChildMoveDirection = 'up' | 'down'
interface ElementForm {
title: string
description: string
@ -168,6 +174,50 @@ async function handleRemoveChild(childElementId: number): Promise<void> {
}
}
async function handleMoveChild(
childElementId: number,
direction: ChildMoveDirection,
): Promise<void> {
if (elementId.value === '') {
return
}
const currentIndex = childElements.value.findIndex((childElement) => {
return childElement.id === childElementId
})
if (currentIndex === -1) {
return
}
const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1
if (targetIndex < 0 || targetIndex >= childElements.value.length) {
return
}
const reorderedChildElements = [...childElements.value]
const movingChildElement = reorderedChildElements[currentIndex]
const targetChildElement = reorderedChildElements[targetIndex]
if (movingChildElement === undefined || targetChildElement === undefined) {
return
}
reorderedChildElements[currentIndex] = targetChildElement
reorderedChildElements[targetIndex] = movingChildElement
const childElementIds = reorderedChildElements.map((childElement) => {
return childElement.id
})
childStatus.value = null
const saved = await elementsStore.reorderChildElements(
elementId.value,
childElementIds,
)
if (saved) {
childStatus.value = 'Child order saved'
}
}
function chooseIconImage(): void {
iconImageInput.value?.click()
}
@ -522,7 +572,7 @@ function resetInput(changeEvent: Event): void {
data-cy="admin-child-list"
>
<li
v-for="childElement in childElements"
v-for="(childElement, childIndex) in childElements"
:key="childElement.id"
class="admin-element-page__child-item"
data-cy="admin-child-item"
@ -545,6 +595,34 @@ function resetInput(changeEvent: Event): void {
{{ childElement.description }}
</p>
</div>
<div class="admin-element-page__child-actions">
<div class="admin-element-page__child-order-actions">
<button
class="admin-element-page__icon-button"
data-cy="admin-move-child-up"
type="button"
:disabled="isManagingChildren || childIndex === 0"
aria-label="Move child up"
title="Move child up"
@click="handleMoveChild(childElement.id, 'up')"
>
<ChevronUpIcon :size="16" aria-hidden="true" />
</button>
<button
class="admin-element-page__icon-button"
data-cy="admin-move-child-down"
type="button"
:disabled="
isManagingChildren ||
childIndex === childElements.length - 1
"
aria-label="Move child down"
title="Move child down"
@click="handleMoveChild(childElement.id, 'down')"
>
<ChevronDownIcon :size="16" aria-hidden="true" />
</button>
</div>
<button
class="admin-element-page__secondary-button"
data-cy="admin-remove-child"
@ -554,6 +632,7 @@ function resetInput(changeEvent: Event): void {
>
Remove
</button>
</div>
</li>
</ul>
<p
@ -778,6 +857,44 @@ function resetInput(changeEvent: Event): void {
line-height: 1.45;
}
.admin-element-page__child-actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 0.45rem;
}
.admin-element-page__child-order-actions {
display: flex;
align-items: center;
gap: 0.35rem;
}
.admin-element-page__icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.25rem;
height: 2.25rem;
padding: 0;
border: 1px solid var(--color-border);
border-radius: 4px;
color: var(--color-text);
background: var(--color-white);
cursor: pointer;
}
.admin-element-page__icon-button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.admin-element-page__icon-button:hover:not(:disabled),
.admin-element-page__icon-button:focus-visible {
border-color: var(--color-slate);
color: var(--color-slate);
}
.admin-element-page__child-add {
display: flex;
align-items: end;
@ -890,5 +1007,9 @@ function resetInput(changeEvent: Event): void {
.admin-element-page__child-item {
flex-direction: column;
}
.admin-element-page__child-actions {
align-self: flex-end;
}
}
</style>