Compare commits

..

11 commits

31 changed files with 1541 additions and 93 deletions

View file

@ -9,15 +9,18 @@ use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElementRequest; use App\Element\UseCases\DeleteChildElement\DeleteChildElementRequest;
use App\Element\UseCases\GetElement\GetElement; use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\GetElement\GetElementRequest; use App\Element\UseCases\GetElement\GetElementRequest;
use App\Element\UseCases\GetElementPdf\GetElementPdf;
use App\Element\UseCases\GetElementPdf\GetElementPdfRequest;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements; use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\ReorderChildElements\ReorderChildElementsRequest; use App\Element\UseCases\ReorderChildElements\ReorderChildElementsRequest;
use App\Element\UseCases\UpdateElement\UpdateElement; use App\Element\UseCases\UpdateElement\UpdateElement;
use App\Element\UseCases\UpdateElement\UpdateElementRequest; use App\Element\UseCases\UpdateElement\UpdateElementRequest;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
class ElementController class ElementController
@ -28,7 +31,8 @@ class ElementController
private DeleteChildElement $deleteChildElement, private DeleteChildElement $deleteChildElement,
private ReorderChildElements $reorderChildElements, private ReorderChildElements $reorderChildElements,
private UpdateElement $updateElement, private UpdateElement $updateElement,
private FileUploader $fileUploader, private GetElementPdf $getElementPdf,
private Filesystem $filesystem,
) { ) {
} }
@ -64,6 +68,39 @@ class ElementController
], 200); ], 200);
} }
public function showPdf(
?string $folder,
?string $fileName,
): Response|JsonResponse {
try {
$result = $this->getElementPdf->execute(
new GetElementPdfRequest(
folder: $folder,
fileName: $fileName,
)
);
} catch (BadRequestException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 400);
} catch (NotFoundException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 404);
}
return new Response(
$result->getContents(),
200,
[
'Content-Type' => $result->getMimeType(),
'Content-Disposition' => 'inline; filename="'
. $result->getFileName()
. '"',
],
);
}
public function createChild(Request $request, ?int $parentId): JsonResponse public function createChild(Request $request, ?int $parentId): JsonResponse
{ {
try { try {
@ -367,7 +404,7 @@ class ElementController
} }
if (str_starts_with($path, $folderPrefix)) { if (str_starts_with($path, $folderPrefix)) {
return $this->fileUploader->url($path); return $this->filesystem->url($path);
} }
return $path; return $path;

View file

@ -6,13 +6,13 @@ use App\Element\Element;
use App\Element\ElementRepository; use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class DeleteChildElement class DeleteChildElement
{ {
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -78,6 +78,6 @@ class DeleteChildElement
return; return;
} }
$this->fileUploader->delete($path); $this->filesystem->delete($path);
} }
} }

View file

@ -0,0 +1,63 @@
<?php
namespace App\Element\UseCases\GetElementPdf;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use App\Shared\Files\Filesystem;
class GetElementPdf
{
private const PDF_FOLDERS = ['short', 'long'];
private const PDF_MIME_TYPE = 'application/pdf';
public function __construct(private Filesystem $filesystem)
{
}
/**
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(GetElementPdfRequest $request): GetElementPdfResult
{
if ($request->folder === null) {
throw new BadRequestException('folder is required');
}
if ($request->fileName === null) {
throw new BadRequestException('fileName is required');
}
if (!$this->isAllowedPdfFolder($request->folder)) {
throw new BadRequestException('folder is invalid');
}
if (!$this->isValidPdfFileName($request->fileName)) {
throw new BadRequestException('fileName is invalid');
}
$path = "element-pdfs/$request->folder/$request->fileName";
$contents = $this->filesystem->read($path);
if ($contents === null) {
throw new NotFoundException('PDF not found');
}
return new GetElementPdfResult(
contents: $contents,
fileName: $request->fileName,
mimeType: self::PDF_MIME_TYPE,
);
}
private function isAllowedPdfFolder(string $folder): bool
{
return in_array($folder, self::PDF_FOLDERS, true);
}
private function isValidPdfFileName(string $fileName): bool
{
return preg_match('/^[A-Za-z0-9._-]+\.pdf$/', $fileName) === 1;
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace App\Element\UseCases\GetElementPdf;
class GetElementPdfRequest
{
public function __construct(
public ?string $folder,
public ?string $fileName,
) {
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace App\Element\UseCases\GetElementPdf;
class GetElementPdfResult
{
public function __construct(
private string $contents,
private string $fileName,
private string $mimeType,
) {
}
public function getContents(): string
{
return $this->contents;
}
public function getFileName(): string
{
return $this->fileName;
}
public function getMimeType(): string
{
return $this->mimeType;
}
}

View file

@ -7,7 +7,7 @@ use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileToUpload; use App\Shared\Files\FileToUpload;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateIconImage class UpdateIconImage
{ {
@ -21,7 +21,7 @@ class UpdateIconImage
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -73,7 +73,7 @@ class UpdateIconImage
mimeType: $request->fileMimeType, mimeType: $request->fileMimeType,
sizeBytes: $request->fileSizeBytes, sizeBytes: $request->fileSizeBytes,
); );
$path = $this->fileUploader->upload($iconImage, 'element-icons'); $path = $this->filesystem->upload($iconImage, 'element-icons');
$element->setIconImageUrl($path); $element->setIconImageUrl($path);
return $this->elementRepository->update($element); return $this->elementRepository->update($element);

View file

@ -6,13 +6,13 @@ use App\Element\Element;
use App\Element\ElementRepository; use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateIconImageUrl class UpdateIconImageUrl
{ {
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -60,6 +60,6 @@ class UpdateIconImageUrl
return; return;
} }
$this->fileUploader->delete($path); $this->filesystem->delete($path);
} }
} }

View file

@ -7,7 +7,7 @@ use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileToUpload; use App\Shared\Files\FileToUpload;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateLongPdf class UpdateLongPdf
{ {
@ -19,7 +19,7 @@ class UpdateLongPdf
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -67,7 +67,7 @@ class UpdateLongPdf
mimeType: $request->fileMimeType, mimeType: $request->fileMimeType,
sizeBytes: $request->fileSizeBytes, sizeBytes: $request->fileSizeBytes,
); );
$path = $this->fileUploader->upload($pdf, 'element-pdfs/long'); $path = $this->filesystem->upload($pdf, 'element-pdfs/long');
$element->setLongPdfPath($path); $element->setLongPdfPath($path);
return $this->elementRepository->update($element); return $this->elementRepository->update($element);

View file

@ -6,13 +6,13 @@ use App\Element\Element;
use App\Element\ElementRepository; use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateLongPdfPath class UpdateLongPdfPath
{ {
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -60,6 +60,6 @@ class UpdateLongPdfPath
return; return;
} }
$this->fileUploader->delete($path); $this->filesystem->delete($path);
} }
} }

View file

@ -7,7 +7,7 @@ use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileToUpload; use App\Shared\Files\FileToUpload;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateShortPdf class UpdateShortPdf
{ {
@ -19,7 +19,7 @@ class UpdateShortPdf
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -67,7 +67,7 @@ class UpdateShortPdf
mimeType: $request->fileMimeType, mimeType: $request->fileMimeType,
sizeBytes: $request->fileSizeBytes, sizeBytes: $request->fileSizeBytes,
); );
$path = $this->fileUploader->upload($pdf, 'element-pdfs/short'); $path = $this->filesystem->upload($pdf, 'element-pdfs/short');
$element->setShortPdfPath($path); $element->setShortPdfPath($path);
return $this->elementRepository->update($element); return $this->elementRepository->update($element);

View file

@ -6,13 +6,13 @@ use App\Element\Element;
use App\Element\ElementRepository; use App\Element\ElementRepository;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class UpdateShortPdfPath class UpdateShortPdfPath
{ {
public function __construct( public function __construct(
private ElementRepository $elementRepository, private ElementRepository $elementRepository,
private FileUploader $fileUploader, private Filesystem $filesystem,
) { ) {
} }
@ -60,6 +60,6 @@ class UpdateShortPdfPath
return; return;
} }
$this->fileUploader->delete($path); $this->filesystem->delete($path);
} }
} }

View file

@ -8,8 +8,8 @@ use App\Auth\PasswordHasher;
use App\Auth\RandomTokenGenerator; use App\Auth\RandomTokenGenerator;
use App\Auth\SystemClock; use App\Auth\SystemClock;
use App\Auth\TokenGenerator; use App\Auth\TokenGenerator;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
use App\Shared\Files\LaravelFileUploader; use App\Shared\Files\LaravelFilesystem;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
@ -29,8 +29,8 @@ class AppServiceProvider extends ServiceProvider
SystemClock::class, SystemClock::class,
); );
$this->app->bind( $this->app->bind(
FileUploader::class, Filesystem::class,
LaravelFileUploader::class, LaravelFilesystem::class,
); );
} }
} }

View file

@ -2,11 +2,13 @@
namespace App\Shared\Files; namespace App\Shared\Files;
interface FileUploader interface Filesystem
{ {
public function upload(FileToUpload $file, string $folder): string; public function upload(FileToUpload $file, string $folder): string;
public function url(string $path): string; public function url(string $path): string;
public function delete(string $path): void; public function delete(string $path): void;
public function read(string $path): ?string;
} }

View file

@ -5,7 +5,7 @@ namespace App\Shared\Files;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class LaravelFileUploader implements FileUploader class LaravelFilesystem implements Filesystem
{ {
public function upload(FileToUpload $file, string $folder): string public function upload(FileToUpload $file, string $folder): string
{ {
@ -25,6 +25,15 @@ class LaravelFileUploader implements FileUploader
Storage::disk('public')->delete($path); Storage::disk('public')->delete($path);
} }
public function read(string $path): ?string
{
if (!Storage::disk('public')->exists($path)) {
return null;
}
return Storage::disk('public')->get($path);
}
private function extensionFor(FileToUpload $file): string private function extensionFor(FileToUpload $file): string
{ {
$mimeExtensions = [ $mimeExtensions = [

View file

@ -12,6 +12,10 @@ Route::get('/me', [AuthController::class, 'me'])
->middleware(AuthMiddleware::class); ->middleware(AuthMiddleware::class);
Route::get('/sets', [SetController::class, 'index']); Route::get('/sets', [SetController::class, 'index']);
Route::get('/elements/{id}', [ElementController::class, 'show']); Route::get('/elements/{id}', [ElementController::class, 'show']);
Route::get('/element-pdfs/{folder}/{fileName}', [
ElementController::class,
'showPdf',
]);
Route::post('/elements/{parentId}/children', [ Route::post('/elements/{parentId}/children', [
ElementController::class, ElementController::class,
'createChild', 'createChild',

View file

@ -3,9 +3,9 @@
namespace Tests\Fakes; namespace Tests\Fakes;
use App\Shared\Files\FileToUpload; use App\Shared\Files\FileToUpload;
use App\Shared\Files\FileUploader; use App\Shared\Files\Filesystem;
class FakeFileUploader implements FileUploader class FakeFilesystem implements Filesystem
{ {
/** /**
* @var array<int, array{file: FileToUpload, folder: string}> * @var array<int, array{file: FileToUpload, folder: string}>
@ -17,6 +17,16 @@ class FakeFileUploader implements FileUploader
*/ */
public array $deletedPaths = []; public array $deletedPaths = [];
/**
* @var string[]
*/
public array $readPaths = [];
/**
* @var array<string, string>
*/
private array $filesByPath = [];
public function upload(FileToUpload $file, string $folder): string public function upload(FileToUpload $file, string $folder): string
{ {
$this->uploads[] = ['file' => $file, 'folder' => $folder]; $this->uploads[] = ['file' => $file, 'folder' => $folder];
@ -33,4 +43,16 @@ class FakeFileUploader implements FileUploader
{ {
$this->deletedPaths[] = $path; $this->deletedPaths[] = $path;
} }
public function put(string $path, string $contents): void
{
$this->filesByPath[$path] = $contents;
}
public function read(string $path): ?string
{
$this->readPaths[] = $path;
return $this->filesByPath[$path] ?? null;
}
} }

View file

@ -8,6 +8,7 @@ use App\Element\Element;
use App\Element\UseCases\CreateChildElement\CreateChildElement; use App\Element\UseCases\CreateChildElement\CreateChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElement; use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\GetElement\GetElement; use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\GetElementPdf\GetElementPdf;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements; use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\UpdateElement\UpdateDescription; use App\Element\UseCases\UpdateElement\UpdateDescription;
use App\Element\UseCases\UpdateElement\UpdateElement; use App\Element\UseCases\UpdateElement\UpdateElement;
@ -24,7 +25,7 @@ use App\Set\Set as DomainSet;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class ElementControllerTest extends TestCase class ElementControllerTest extends TestCase
@ -33,42 +34,43 @@ class ElementControllerTest extends TestCase
private FakeElementRepository $elementRepo; private FakeElementRepository $elementRepo;
private FakeFileUploader $fileUploader; private FakeFilesystem $filesystem;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepo = new FakeElementRepository(); $this->elementRepo = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->filesystem = new FakeFilesystem();
$getElement = new GetElement($this->elementRepo); $getElement = new GetElement($this->elementRepo);
$updateElement = new UpdateElement( $updateElement = new UpdateElement(
new UpdateTitle($this->elementRepo), new UpdateTitle($this->elementRepo),
new UpdateDescription($this->elementRepo), new UpdateDescription($this->elementRepo),
new UpdateIconImageUrl($this->elementRepo, $this->fileUploader), new UpdateIconImageUrl($this->elementRepo, $this->filesystem),
new UpdateRichText($this->elementRepo), new UpdateRichText($this->elementRepo),
new UpdateShortPdfPath($this->elementRepo, $this->fileUploader), new UpdateShortPdfPath($this->elementRepo, $this->filesystem),
new UpdateLongPdfPath($this->elementRepo, $this->fileUploader), new UpdateLongPdfPath($this->elementRepo, $this->filesystem),
new UpdateYoutubeUrl($this->elementRepo), new UpdateYoutubeUrl($this->elementRepo),
new UpdateIconImage( new UpdateIconImage(
$this->elementRepo, $this->elementRepo,
$this->fileUploader, $this->filesystem,
), ),
new UpdateShortPdf( new UpdateShortPdf(
$this->elementRepo, $this->elementRepo,
$this->fileUploader, $this->filesystem,
), ),
new UpdateLongPdf( new UpdateLongPdf(
$this->elementRepo, $this->elementRepo,
$this->fileUploader, $this->filesystem,
), ),
$this->elementRepo, $this->elementRepo,
); );
$this->controller = new ElementController( $this->controller = new ElementController(
$getElement, $getElement,
new CreateChildElement($this->elementRepo), new CreateChildElement($this->elementRepo),
new DeleteChildElement($this->elementRepo, $this->fileUploader), new DeleteChildElement($this->elementRepo, $this->filesystem),
new ReorderChildElements($this->elementRepo), new ReorderChildElements($this->elementRepo),
$updateElement, $updateElement,
$this->fileUploader, new GetElementPdf($this->filesystem),
$this->filesystem,
); );
} }
@ -244,6 +246,82 @@ class ElementControllerTest extends TestCase
); );
} }
public function testShowPdfReturnsPdfResponse(): void
{
$this->filesystem->put(
'element-pdfs/short/baderech.pdf',
'pdf-bytes',
);
$response = $this->controller->showPdf('short', 'baderech.pdf');
$this->assertEquals(200, $response->getStatusCode());
$this->assertSame('pdf-bytes', $response->getContent());
$this->assertSame(
'application/pdf',
$response->headers->get('Content-Type'),
);
$this->assertSame(
'inline; filename="baderech.pdf"',
$response->headers->get('Content-Disposition'),
);
}
public function testShowPdfReturns404WhenPdfDoesNotExist(): void
{
$response = $this->controller->showPdf('short', 'missing.pdf');
$this->assertEquals(404, $response->getStatusCode());
$this->assertSame(
['error' => 'PDF not found'],
json_decode($response->getContent(), true),
);
}
public function testShowPdfReturns400WhenFolderIsInvalid(): void
{
$response = $this->controller->showPdf('archive', 'baderech.pdf');
$this->assertEquals(400, $response->getStatusCode());
$this->assertSame(
['error' => 'folder is invalid'],
json_decode($response->getContent(), true),
);
}
public function testShowPdfReturns400WhenFolderIsMissing(): void
{
$response = $this->controller->showPdf(null, 'baderech.pdf');
$this->assertEquals(400, $response->getStatusCode());
$this->assertSame(
['error' => 'folder is required'],
json_decode($response->getContent(), true),
);
}
public function testShowPdfReturns400WhenFileNameIsInvalid(): void
{
$response = $this->controller->showPdf('short', '../baderech.pdf');
$this->assertEquals(400, $response->getStatusCode());
$this->assertSame(
['error' => 'fileName is invalid'],
json_decode($response->getContent(), true),
);
}
public function testShowPdfReturns400WhenFileNameIsMissing(): void
{
$response = $this->controller->showPdf('short', null);
$this->assertEquals(400, $response->getStatusCode());
$this->assertSame(
['error' => 'fileName is required'],
json_decode($response->getContent(), true),
);
}
public function testUpdateWithIconImageReturnsElementPayload(): void public function testUpdateWithIconImageReturnsElementPayload(): void
{ {
$set = $this->createSet(1, 'Baderech'); $set = $this->createSet(1, 'Baderech');
@ -273,7 +351,7 @@ class ElementControllerTest extends TestCase
); );
$this->assertSame( $this->assertSame(
'element-icons', 'element-icons',
$this->fileUploader->uploads[0]['folder'], $this->filesystem->uploads[0]['folder'],
); );
} }
@ -307,7 +385,7 @@ class ElementControllerTest extends TestCase
$this->assertArrayNotHasKey('pdfPath', $body['element']); $this->assertArrayNotHasKey('pdfPath', $body['element']);
$this->assertSame( $this->assertSame(
'element-pdfs/short', 'element-pdfs/short',
$this->fileUploader->uploads[0]['folder'], $this->filesystem->uploads[0]['folder'],
); );
} }
@ -340,7 +418,7 @@ class ElementControllerTest extends TestCase
); );
$this->assertSame( $this->assertSame(
'element-pdfs/long', 'element-pdfs/long',
$this->fileUploader->uploads[0]['folder'], $this->filesystem->uploads[0]['folder'],
); );
} }

View file

@ -10,21 +10,21 @@ use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class DeleteChildElementTest extends TestCase class DeleteChildElementTest extends TestCase
{ {
private FakeElementRepository $elementRepository; private FakeElementRepository $elementRepository;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
private DeleteChildElement $deleteChildElement; private DeleteChildElement $deleteChildElement;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepository = new FakeElementRepository(); $this->elementRepository = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
$this->deleteChildElement = new DeleteChildElement( $this->deleteChildElement = new DeleteChildElement(
$this->elementRepository, $this->elementRepository,
$this->fileUploader, $this->fileUploader,

View file

@ -0,0 +1,120 @@
<?php
namespace Tests\Unit\Element\UseCases;
use App\Element\UseCases\GetElementPdf\GetElementPdf;
use App\Element\UseCases\GetElementPdf\GetElementPdfRequest;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use Tests\Fakes\FakeFilesystem;
use Tests\TestCase;
class GetElementPdfTest extends TestCase
{
private FakeFilesystem $filesystem;
private GetElementPdf $useCase;
protected function setUp(): void
{
$this->filesystem = new FakeFilesystem();
$this->useCase = new GetElementPdf($this->filesystem);
}
public function testReturnsShortPdfFile(): void
{
$this->filesystem->put(
'element-pdfs/short/baderech.pdf',
'short-pdf-bytes',
);
$result = $this->useCase->execute(new GetElementPdfRequest(
folder: 'short',
fileName: 'baderech.pdf',
));
$this->assertSame('short-pdf-bytes', $result->getContents());
$this->assertSame('baderech.pdf', $result->getFileName());
$this->assertSame('application/pdf', $result->getMimeType());
$this->assertSame(
['element-pdfs/short/baderech.pdf'],
$this->filesystem->readPaths,
);
}
public function testReturnsLongPdfFile(): void
{
$this->filesystem->put(
'element-pdfs/long/baderech-long.pdf',
'long-pdf-bytes',
);
$result = $this->useCase->execute(new GetElementPdfRequest(
folder: 'long',
fileName: 'baderech-long.pdf',
));
$this->assertSame('long-pdf-bytes', $result->getContents());
$this->assertSame('baderech-long.pdf', $result->getFileName());
$this->assertSame('application/pdf', $result->getMimeType());
$this->assertSame(
['element-pdfs/long/baderech-long.pdf'],
$this->filesystem->readPaths,
);
}
public function testInvalidFolderThrowsBadRequest(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('folder is invalid');
$this->useCase->execute(new GetElementPdfRequest(
folder: 'archive',
fileName: 'baderech.pdf',
));
}
public function testMissingFolderThrowsBadRequest(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('folder is required');
$this->useCase->execute(new GetElementPdfRequest(
folder: null,
fileName: 'baderech.pdf',
));
}
public function testMissingFileNameThrowsBadRequest(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('fileName is required');
$this->useCase->execute(new GetElementPdfRequest(
folder: 'short',
fileName: null,
));
}
public function testInvalidFileNameThrowsBadRequest(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('fileName is invalid');
$this->useCase->execute(new GetElementPdfRequest(
folder: 'short',
fileName: '../baderech.pdf',
));
}
public function testMissingStorageFileThrowsNotFound(): void
{
$this->expectException(NotFoundException::class);
$this->expectExceptionMessage('PDF not found');
$this->useCase->execute(new GetElementPdfRequest(
folder: 'short',
fileName: 'missing.pdf',
));
}
}

View file

@ -21,19 +21,19 @@ use App\Element\UseCases\UpdateElement\UpdateYoutubeUrlRequest;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class UpdateElementFieldsTest extends TestCase class UpdateElementFieldsTest extends TestCase
{ {
private FakeElementRepository $elementRepo; private FakeElementRepository $elementRepo;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepo = new FakeElementRepository(); $this->elementRepo = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
} }
public function testUpdateTitleUpdatesOnlyTitle(): void public function testUpdateTitleUpdatesOnlyTitle(): void

View file

@ -20,21 +20,21 @@ use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class UpdateElementTest extends TestCase class UpdateElementTest extends TestCase
{ {
private FakeElementRepository $elementRepo; private FakeElementRepository $elementRepo;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
private UpdateElement $updateElement; private UpdateElement $updateElement;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepo = new FakeElementRepository(); $this->elementRepo = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
$this->updateElement = new UpdateElement( $this->updateElement = new UpdateElement(
new UpdateTitle($this->elementRepo), new UpdateTitle($this->elementRepo),
new UpdateDescription($this->elementRepo), new UpdateDescription($this->elementRepo),

View file

@ -10,21 +10,21 @@ use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class UpdateIconImageTest extends TestCase class UpdateIconImageTest extends TestCase
{ {
private FakeElementRepository $elementRepository; private FakeElementRepository $elementRepository;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
private UpdateIconImage $useCase; private UpdateIconImage $useCase;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepository = new FakeElementRepository(); $this->elementRepository = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
$this->useCase = new UpdateIconImage( $this->useCase = new UpdateIconImage(
$this->elementRepository, $this->elementRepository,
$this->fileUploader, $this->fileUploader,

View file

@ -9,21 +9,21 @@ use App\Element\UseCases\UpdateElement\UpdateLongPdfRequest;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class UpdateLongPdfTest extends TestCase class UpdateLongPdfTest extends TestCase
{ {
private FakeElementRepository $elementRepository; private FakeElementRepository $elementRepository;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
private UpdateLongPdf $useCase; private UpdateLongPdf $useCase;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepository = new FakeElementRepository(); $this->elementRepository = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
$this->useCase = new UpdateLongPdf( $this->useCase = new UpdateLongPdf(
$this->elementRepository, $this->elementRepository,
$this->fileUploader, $this->fileUploader,

View file

@ -10,21 +10,21 @@ use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException; use App\Exceptions\NotFoundException;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository; use Tests\Fakes\FakeElementRepository;
use Tests\Fakes\FakeFileUploader; use Tests\Fakes\FakeFilesystem;
use Tests\TestCase; use Tests\TestCase;
class UpdateShortPdfTest extends TestCase class UpdateShortPdfTest extends TestCase
{ {
private FakeElementRepository $elementRepository; private FakeElementRepository $elementRepository;
private FakeFileUploader $fileUploader; private FakeFilesystem $fileUploader;
private UpdateShortPdf $useCase; private UpdateShortPdf $useCase;
protected function setUp(): void protected function setUp(): void
{ {
$this->elementRepository = new FakeElementRepository(); $this->elementRepository = new FakeElementRepository();
$this->fileUploader = new FakeFileUploader(); $this->fileUploader = new FakeFilesystem();
$this->useCase = new UpdateShortPdf( $this->useCase = new UpdateShortPdf(
$this->elementRepository, $this->elementRepository,
$this->fileUploader, $this->fileUploader,

View file

@ -1,4 +1,5 @@
import { execSync } from 'node:child_process' import { execSync } from 'node:child_process'
import { cpSync, mkdirSync, rmSync } from 'node:fs'
import { dirname, resolve } from 'node:path' import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { defineConfig } from 'cypress' import { defineConfig } from 'cypress'
@ -7,7 +8,9 @@ import { Client } from 'pg'
const configDirectory = dirname(fileURLToPath(import.meta.url)) const configDirectory = dirname(fileURLToPath(import.meta.url))
const backendDirectory = resolve(configDirectory, '../../backend') const backendDirectory = resolve(configDirectory, '../../backend')
const seedAssetDirectory = resolve(backendDirectory, 'database/seeders/assets')
const socketDirectory = resolve(configDirectory, '../../.postgres') const socketDirectory = resolve(configDirectory, '../../.postgres')
const storagePublicDirectory = resolve(backendDirectory, 'storage/app/public')
const appDatabase = 'postgres' const appDatabase = 'postgres'
const templateDatabase = 'postgres_cypress_template' const templateDatabase = 'postgres_cypress_template'
@ -47,6 +50,7 @@ async function buildTemplate(): Promise<void> {
stdio: 'pipe', stdio: 'pipe',
env: seedEnvironment, env: seedEnvironment,
}) })
resetSeedStorage()
const markClient = controlClient() const markClient = controlClient()
await markClient.connect() await markClient.connect()
@ -72,10 +76,24 @@ async function resetFromTemplate(): Promise<null> {
TEMPLATE ${templateDatabase}`, TEMPLATE ${templateDatabase}`,
) )
await client.end() await client.end()
resetSeedStorage()
return null return null
} }
function resetSeedStorage(): void {
rmSync(resolve(storagePublicDirectory, 'element-icons'), {
recursive: true,
force: true,
})
rmSync(resolve(storagePublicDirectory, 'element-pdfs'), {
recursive: true,
force: true,
})
mkdirSync(storagePublicDirectory, { recursive: true })
cpSync(seedAssetDirectory, storagePublicDirectory, { recursive: true })
}
export default defineConfig({ export default defineConfig({
e2e: { e2e: {
baseUrl: 'http://localhost:5173', baseUrl: 'http://localhost:5173',

View file

@ -281,14 +281,12 @@ describe('admin element editing', () => {
.should('be.visible') .should('be.visible')
.and('have.attr', 'src') .and('have.attr', 'src')
.and('include', '/storage/element-icons/') .and('include', '/storage/element-icons/')
cy.get('[data-cy="element-short-pdf-link"]') cy.get('[data-cy="element-short-pdf-viewer-button"]')
.should('be.visible') .should('be.visible')
.and('have.attr', 'href') .and('contain.text', 'View Short PDF')
.and('include', '/storage/element-pdfs/short/') cy.get('[data-cy="element-long-pdf-viewer-button"]')
cy.get('[data-cy="element-long-pdf-link"]')
.should('be.visible') .should('be.visible')
.and('have.attr', 'href') .and('contain.text', 'View Long PDF')
.and('include', '/storage/element-pdfs/long/')
cy.resetDb() cy.resetDb()
}) })
@ -341,8 +339,8 @@ describe('admin element editing', () => {
cy.contains('header.site-header a', 'View Element').click() cy.contains('header.site-header a', 'View Element').click()
cy.get('[data-cy="element-icon"]').should('not.exist') cy.get('[data-cy="element-icon"]').should('not.exist')
cy.get('[data-cy="element-short-pdf-link"]').should('not.exist') cy.get('[data-cy="element-short-pdf-viewer-button"]').should('not.exist')
cy.get('[data-cy="element-long-pdf-link"]').should('not.exist') cy.get('[data-cy="element-long-pdf-viewer-button"]').should('not.exist')
cy.resetDb() cy.resetDb()
}) })

View file

@ -51,8 +51,8 @@ describe('media page sets', () => {
cy.get('[data-cy="element-rich-text"]').should('not.exist') cy.get('[data-cy="element-rich-text"]').should('not.exist')
cy.get('[data-cy="element-youtube-embed"]') cy.get('[data-cy="element-youtube-embed"]')
.should('not.exist') .should('not.exist')
cy.get('[data-cy="element-short-pdf-link"]').should('not.exist') cy.get('[data-cy="element-short-pdf-viewer-button"]').should('not.exist')
cy.get('[data-cy="element-long-pdf-link"]').should('not.exist') cy.get('[data-cy="element-long-pdf-viewer-button"]').should('not.exist')
cy.get('[data-cy="child-element-list"]').should('be.visible') cy.get('[data-cy="child-element-list"]').should('be.visible')
cy.get('[data-cy="child-element-list"]') cy.get('[data-cy="child-element-list"]')
.should( .should(
@ -117,14 +117,34 @@ describe('media page sets', () => {
) )
.should('have.css', 'text-align', 'center') .should('have.css', 'text-align', 'center')
cy.get('[data-cy="element-youtube-embed"]').should('not.exist') cy.get('[data-cy="element-youtube-embed"]').should('not.exist')
cy.contains('[data-cy="element-short-pdf-link"]', 'View Short PDF') cy.contains(
.as('shortPdfLink') '[data-cy="element-short-pdf-viewer-button"]',
'View Short PDF',
)
.as('shortPdfButton')
.should('be.visible')
cy.get('[data-cy="element-long-pdf-viewer-button"]').should('not.exist')
cy.get('@shortPdfButton').click()
cy.get('[data-cy="pdf-viewer-modal"]').should('be.visible')
cy.contains('[data-cy="pdf-viewer-title"]', 'Short PDF').should(
'be.visible',
)
cy.get('[data-cy="pdf-viewer-document"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-page-status"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-previous-page"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-next-page"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-zoom-out"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-zoom-in"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-search-input"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-download"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-print"]').should('be.visible')
cy.get('[data-cy="pdf-viewer-open-link"]')
.should('be.visible') .should('be.visible')
.and('have.attr', 'target', '_blank') .and('have.attr', 'target', '_blank')
cy.get('@shortPdfLink')
.and('have.attr', 'href') .and('have.attr', 'href')
.and('include', '/storage/element-pdfs/short/baderech.pdf') .and('include', '/storage/element-pdfs/short/baderech.pdf')
cy.get('[data-cy="element-long-pdf-link"]').should('not.exist') cy.get('[data-cy="pdf-viewer-close"]').click()
cy.get('[data-cy="pdf-viewer-modal"]').should('not.exist')
cy.contains('[data-cy="child-element-link"]', introductionAudioTitle) cy.contains('[data-cy="child-element-link"]', introductionAudioTitle)
.as('introductionAudioLink') .as('introductionAudioLink')
.should('have.attr', 'href', '/element/8') .should('have.attr', 'href', '/element/8')
@ -134,8 +154,8 @@ describe('media page sets', () => {
cy.contains('h1', introductionAudioTitle).should('be.visible') cy.contains('h1', introductionAudioTitle).should('be.visible')
cy.get('[data-cy="element-icon"]').should('not.exist') cy.get('[data-cy="element-icon"]').should('not.exist')
cy.get('[data-cy="element-rich-text"]').should('not.exist') cy.get('[data-cy="element-rich-text"]').should('not.exist')
cy.get('[data-cy="element-short-pdf-link"]').should('not.exist') cy.get('[data-cy="element-short-pdf-viewer-button"]').should('not.exist')
cy.get('[data-cy="element-long-pdf-link"]').should('not.exist') cy.get('[data-cy="element-long-pdf-viewer-button"]').should('not.exist')
cy.get('[data-cy="child-element-list"]').should('not.exist') cy.get('[data-cy="child-element-list"]').should('not.exist')
cy.get('[data-cy="element-youtube-embed"]') cy.get('[data-cy="element-youtube-embed"]')
.should('be.visible') .should('be.visible')

View file

@ -19,6 +19,7 @@
"lucide-vue-next": "^1.0.0", "lucide-vue-next": "^1.0.0",
"pinia": "^3.0.4", "pinia": "^3.0.4",
"vue": "beta", "vue": "beta",
"vue-pdf-embed": "^2.1.5",
"vue-router": "^5.0.4" "vue-router": "^5.0.4"
}, },
"devDependencies": { "devDependencies": {
@ -1275,6 +1276,271 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@napi-rs/canvas": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.100.tgz",
"integrity": "sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA==",
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "0.1.100",
"@napi-rs/canvas-darwin-arm64": "0.1.100",
"@napi-rs/canvas-darwin-x64": "0.1.100",
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100",
"@napi-rs/canvas-linux-arm64-gnu": "0.1.100",
"@napi-rs/canvas-linux-arm64-musl": "0.1.100",
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-gnu": "0.1.100",
"@napi-rs/canvas-linux-x64-musl": "0.1.100",
"@napi-rs/canvas-win32-arm64-msvc": "0.1.100",
"@napi-rs/canvas-win32-x64-msvc": "0.1.100"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.100.tgz",
"integrity": "sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.100.tgz",
"integrity": "sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.100.tgz",
"integrity": "sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.100.tgz",
"integrity": "sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.100.tgz",
"integrity": "sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw==",
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.100.tgz",
"integrity": "sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ==",
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.100.tgz",
"integrity": "sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw==",
"cpu": [
"riscv64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.100.tgz",
"integrity": "sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg==",
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.100.tgz",
"integrity": "sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA==",
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.100.tgz",
"integrity": "sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "0.1.100",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.100.tgz",
"integrity": "sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/wasm-runtime": { "node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.4", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",
@ -7007,6 +7273,18 @@
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/pdfjs-dist": {
"version": "5.7.284",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.7.284.tgz",
"integrity": "sha512-h4EdYQczmGhbOlqc3PPZwxevn7ApdWPbovAuWXOB/DjIyigSnwfy2oze7c6mRcSr9XgLp3eN3EeL4DyySTPMFw==",
"license": "Apache-2.0",
"engines": {
"node": ">=22.13.0 || >=24"
},
"optionalDependencies": {
"@napi-rs/canvas": "^0.1.100"
}
},
"node_modules/pend": { "node_modules/pend": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
@ -8784,6 +9062,18 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/vue-pdf-embed": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/vue-pdf-embed/-/vue-pdf-embed-2.1.5.tgz",
"integrity": "sha512-IGFVBYlnOz2zSql1zk4YJyBu584EZa6RUykk5f8wkHF/AR31khCa+ruJoRag+Ff2UyntkWu0brENIKoikQ7F8g==",
"license": "MIT",
"dependencies": {
"pdfjs-dist": "^5.7.284"
},
"peerDependencies": {
"vue": "^3.3.0"
}
},
"node_modules/vue-router": { "node_modules/vue-router": {
"version": "5.0.7", "version": "5.0.7",
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.0.7.tgz", "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.0.7.tgz",

View file

@ -28,6 +28,7 @@
"lucide-vue-next": "^1.0.0", "lucide-vue-next": "^1.0.0",
"pinia": "^3.0.4", "pinia": "^3.0.4",
"vue": "beta", "vue": "beta",
"vue-pdf-embed": "^2.1.5",
"vue-router": "^5.0.4" "vue-router": "^5.0.4"
}, },
"devDependencies": { "devDependencies": {

View file

@ -0,0 +1,662 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import {
ChevronLeft as ChevronLeftIcon,
ChevronRight as ChevronRightIcon,
Download as DownloadIcon,
ExternalLink as ExternalLinkIcon,
Printer as PrinterIcon,
Search as SearchIcon,
X as XIcon,
ZoomIn as ZoomInIcon,
ZoomOut as ZoomOutIcon,
} from 'lucide-vue-next'
import VuePdfEmbed, { usePdfDocument, usePdfSearch } from 'vue-pdf-embed'
import 'vue-pdf-embed/dist/styles/annotationLayer.css'
import 'vue-pdf-embed/dist/styles/textLayer.css'
import type { PDFDocumentProxy } from 'pdfjs-dist'
interface Props {
isOpen: boolean
openUrl: string
pdfTitle: string
pdfUrl: string
}
interface PdfEmbedActions {
download: (filename: string) => Promise<void>
print: (dpi: number, filename: string, allPages: boolean) => Promise<void>
}
const props = defineProps<Props>()
const emit = defineEmits<{
close: []
}>()
const closeButton = ref<HTMLButtonElement | null>(null)
const viewerFrame = ref<HTMLDivElement | null>(null)
const pdfEmbed = ref<PdfEmbedActions | null>(null)
const pageCount = ref(0)
const currentPage = ref(1)
const zoomLevel = ref(1)
const viewerWidth = ref(720)
const isLoading = ref(false)
const isRendering = ref(false)
const errorMessage = ref<string | null>(null)
const searchQuery = ref('')
const minimumZoom = 0.75
const maximumZoom = 2
const zoomStep = 0.25
const defaultViewerWidth = 720
const pdfSource = computed(() => {
if (!props.isOpen || props.pdfUrl === '') {
return null
}
return props.pdfUrl
})
const safeTitle = computed(() => {
return props.pdfTitle.trim() === '' ? 'PDF' : props.pdfTitle
})
const downloadFileName = computed(() => {
const normalizedTitle = safeTitle.value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
return normalizedTitle === '' ? 'document.pdf' : `${normalizedTitle}.pdf`
})
const renderedWidth = computed(() => {
return Math.round(viewerWidth.value * zoomLevel.value)
})
const canGoToPreviousPage = computed(() => {
return currentPage.value > 1
})
const canGoToNextPage = computed(() => {
return pageCount.value > 0 && currentPage.value < pageCount.value
})
const pageStatus = computed(() => {
if (pageCount.value === 0) {
return 'Page -'
}
return `Page ${currentPage.value} of ${pageCount.value}`
})
const searchStatus = computed(() => {
if (searchQuery.value.trim() === '') {
return ''
}
if (matchCount.value === 0) {
return 'No matches'
}
return `${currentMatch.value} of ${matchCount.value}`
})
const { doc: pdfDocument } = usePdfDocument({
source: pdfSource,
onError: handlePdfLoadingError,
})
const {
clear: clearSearchResults,
currentMatch,
currentMatchPage,
find,
findController,
matchCount,
next: nextSearchResult,
previous: previousSearchResult,
} = usePdfSearch(pdfDocument)
watch(
() => [props.isOpen, props.pdfUrl],
() => {
if (!props.isOpen) {
return
}
resetViewerState()
void focusCloseButton()
},
{ immediate: true },
)
watch(currentMatchPage, (matchedPage) => {
if (matchedPage < 1 || matchedPage > pageCount.value) {
return
}
currentPage.value = matchedPage
})
watch(searchQuery, (query) => {
if (query.trim() !== '') {
return
}
clearSearchResults()
})
watch(
() => [currentPage.value, renderedWidth.value],
() => {
if (!props.isOpen || pdfDocument.value === null) {
return
}
isRendering.value = true
},
)
onMounted(() => {
window.addEventListener('keydown', handleWindowKeydown)
window.addEventListener('resize', updateViewerWidth)
updateViewerWidth()
})
onBeforeUnmount(() => {
window.removeEventListener('keydown', handleWindowKeydown)
window.removeEventListener('resize', updateViewerWidth)
})
async function focusCloseButton(): Promise<void> {
await nextTick()
closeButton.value?.focus()
updateViewerWidth()
}
function resetViewerState(): void {
pdfDocument.value = null
pageCount.value = 0
currentPage.value = 1
zoomLevel.value = 1
isLoading.value = true
isRendering.value = false
errorMessage.value = null
searchQuery.value = ''
clearSearchResults()
}
function handlePdfLoaded(loadedDocument: PDFDocumentProxy): void {
pageCount.value = loadedDocument.numPages
currentPage.value = 1
isLoading.value = false
errorMessage.value = null
}
function handlePdfLoadingError(): void {
isLoading.value = false
isRendering.value = false
pageCount.value = 0
errorMessage.value = 'Could not load PDF'
}
function handlePdfRendered(): void {
isRendering.value = false
}
function handlePdfRenderingError(): void {
isRendering.value = false
errorMessage.value = 'Could not render PDF'
}
function goToPreviousPage(): void {
if (!canGoToPreviousPage.value) {
return
}
currentPage.value -= 1
}
function goToNextPage(): void {
if (!canGoToNextPage.value) {
return
}
currentPage.value += 1
}
function zoomOut(): void {
zoomLevel.value = Math.max(minimumZoom, zoomLevel.value - zoomStep)
}
function zoomIn(): void {
zoomLevel.value = Math.min(maximumZoom, zoomLevel.value + zoomStep)
}
function searchPdf(): void {
const query = searchQuery.value.trim()
if (query === '') {
clearSearchResults()
return
}
find(query)
}
async function downloadPdf(): Promise<void> {
await pdfEmbed.value?.download(downloadFileName.value)
}
async function printPdf(): Promise<void> {
await pdfEmbed.value?.print(150, downloadFileName.value, true)
}
function closeViewer(): void {
emit('close')
}
function handleWindowKeydown(keyboardEvent: KeyboardEvent): void {
if (!props.isOpen || keyboardEvent.key !== 'Escape') {
return
}
closeViewer()
}
function updateViewerWidth(): void {
const frameWidth = viewerFrame.value?.clientWidth ?? defaultViewerWidth
const paddedWidth = frameWidth - 32
viewerWidth.value = Math.max(320, Math.min(defaultViewerWidth, paddedWidth))
}
</script>
<template>
<Teleport to="body">
<div
v-if="isOpen"
class="pdf-viewer"
data-cy="pdf-viewer-modal"
role="dialog"
aria-modal="true"
:aria-label="safeTitle"
@click.self="closeViewer"
>
<section class="pdf-viewer__panel">
<header class="pdf-viewer__header">
<h2 class="pdf-viewer__title" data-cy="pdf-viewer-title">
{{ safeTitle }}
</h2>
<button
ref="closeButton"
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-close"
title="Close PDF"
aria-label="Close PDF"
@click="closeViewer"
>
<XIcon :size="20" aria-hidden="true" />
</button>
</header>
<div class="pdf-viewer__toolbar" aria-label="PDF tools">
<div class="pdf-viewer__tool-group">
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-previous-page"
title="Previous page"
aria-label="Previous page"
:disabled="!canGoToPreviousPage"
@click="goToPreviousPage"
>
<ChevronLeftIcon :size="18" aria-hidden="true" />
</button>
<span
class="pdf-viewer__page-status"
data-cy="pdf-viewer-page-status"
>
{{ pageStatus }}
</span>
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-next-page"
title="Next page"
aria-label="Next page"
:disabled="!canGoToNextPage"
@click="goToNextPage"
>
<ChevronRightIcon :size="18" aria-hidden="true" />
</button>
</div>
<div class="pdf-viewer__tool-group">
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-zoom-out"
title="Zoom out"
aria-label="Zoom out"
:disabled="zoomLevel === minimumZoom"
@click="zoomOut"
>
<ZoomOutIcon :size="18" aria-hidden="true" />
</button>
<span class="pdf-viewer__zoom-status">
{{ Math.round(zoomLevel * 100) }}%
</span>
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-zoom-in"
title="Zoom in"
aria-label="Zoom in"
:disabled="zoomLevel === maximumZoom"
@click="zoomIn"
>
<ZoomInIcon :size="18" aria-hidden="true" />
</button>
</div>
<form class="pdf-viewer__search" @submit.prevent="searchPdf">
<input
v-model="searchQuery"
class="pdf-viewer__search-input"
data-cy="pdf-viewer-search-input"
type="search"
aria-label="Search PDF"
placeholder="Search"
/>
<button
type="submit"
class="pdf-viewer__icon-button"
title="Search PDF"
aria-label="Search PDF"
>
<SearchIcon :size="18" aria-hidden="true" />
</button>
<button
type="button"
class="pdf-viewer__icon-button"
title="Previous match"
aria-label="Previous match"
:disabled="matchCount === 0"
@click="previousSearchResult"
>
<ChevronLeftIcon :size="18" aria-hidden="true" />
</button>
<button
type="button"
class="pdf-viewer__icon-button"
title="Next match"
aria-label="Next match"
:disabled="matchCount === 0"
@click="nextSearchResult"
>
<ChevronRightIcon :size="18" aria-hidden="true" />
</button>
<span class="pdf-viewer__search-status">
{{ searchStatus }}
</span>
</form>
<div class="pdf-viewer__tool-group">
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-download"
title="Download PDF"
aria-label="Download PDF"
@click="downloadPdf"
>
<DownloadIcon :size="18" aria-hidden="true" />
</button>
<button
type="button"
class="pdf-viewer__icon-button"
data-cy="pdf-viewer-print"
title="Print PDF"
aria-label="Print PDF"
@click="printPdf"
>
<PrinterIcon :size="18" aria-hidden="true" />
</button>
<a
:href="openUrl"
class="pdf-viewer__icon-link"
data-cy="pdf-viewer-open-link"
target="_blank"
rel="noreferrer"
title="Open PDF in new tab"
aria-label="Open PDF in new tab"
>
<ExternalLinkIcon :size="18" aria-hidden="true" />
</a>
</div>
</div>
<div ref="viewerFrame" class="pdf-viewer__frame">
<p v-if="isLoading" class="pdf-viewer__status">Loading PDF...</p>
<p
v-if="errorMessage !== null"
class="pdf-viewer__status pdf-viewer__status--error"
data-cy="pdf-viewer-error"
>
{{ errorMessage }}
</p>
<div
v-if="errorMessage === null"
class="pdf-viewer__document"
data-cy="pdf-viewer-document"
>
<VuePdfEmbed
ref="pdfEmbed"
annotation-layer
text-layer
:find-controller="findController"
:page="currentPage"
:source="pdfDocument"
:width="renderedWidth"
@loaded="handlePdfLoaded"
@rendered="handlePdfRendered"
@rendering-failed="handlePdfRenderingError"
/>
<p v-if="isRendering" class="pdf-viewer__rendering-status">
Rendering page...
</p>
</div>
</div>
</section>
</div>
</Teleport>
</template>
<style scoped>
.pdf-viewer {
position: fixed;
inset: 0;
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
background: rgb(31 31 31 / 62%);
}
.pdf-viewer__panel {
display: grid;
grid-template-rows: auto auto minmax(0, 1fr);
width: min(72rem, 100%);
height: min(52rem, calc(100vh - 2rem));
overflow: hidden;
background: var(--color-white);
border-radius: 8px;
box-shadow: 0 24px 80px rgb(31 31 31 / 26%);
}
.pdf-viewer__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.85rem 1rem;
border-bottom: 1px solid var(--color-border);
}
.pdf-viewer__title {
margin: 0;
color: var(--color-slate-dark);
font-family: var(--font-serif);
font-size: 1.1rem;
line-height: 1.25;
}
.pdf-viewer__toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.65rem;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--color-border);
background: #f8f6ef;
}
.pdf-viewer__tool-group,
.pdf-viewer__search {
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.pdf-viewer__icon-button,
.pdf-viewer__icon-link {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.25rem;
height: 2.25rem;
padding: 0;
color: var(--color-slate);
background: var(--color-white);
border: 1px solid var(--color-border);
border-radius: 6px;
line-height: 1;
transition:
border-color 180ms ease,
color 180ms ease,
background-color 180ms ease;
}
.pdf-viewer__icon-button:hover:not(:disabled),
.pdf-viewer__icon-button:focus-visible:not(:disabled),
.pdf-viewer__icon-link:hover,
.pdf-viewer__icon-link:focus-visible {
color: var(--color-white);
background: var(--color-slate);
border-color: var(--color-slate);
}
.pdf-viewer__icon-button:focus-visible,
.pdf-viewer__icon-link:focus-visible,
.pdf-viewer__search-input:focus-visible {
outline: 3px solid rgb(61 78 93 / 24%);
outline-offset: 3px;
}
.pdf-viewer__icon-button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.pdf-viewer__page-status,
.pdf-viewer__zoom-status,
.pdf-viewer__search-status {
min-width: max-content;
color: var(--color-text-muted);
font-size: 0.88rem;
font-weight: 700;
}
.pdf-viewer__search {
flex: 1 1 18rem;
}
.pdf-viewer__search-input {
width: min(16rem, 100%);
min-height: 2.25rem;
padding: 0.45rem 0.65rem;
border: 1px solid var(--color-border);
border-radius: 6px;
color: var(--color-text);
background: var(--color-white);
font: inherit;
}
.pdf-viewer__frame {
min-height: 0;
overflow: auto;
padding: 1rem;
background: #e9e4d7;
}
.pdf-viewer__status {
margin: 0 0 1rem;
color: var(--color-text-muted);
font-size: 0.95rem;
font-weight: 700;
text-align: center;
}
.pdf-viewer__status--error {
color: #8f2f25;
}
.pdf-viewer__document {
display: flex;
flex-direction: column;
align-items: center;
min-width: max-content;
}
.pdf-viewer__document :deep(.vue-pdf-embed) {
display: block;
}
.pdf-viewer__document :deep(.vue-pdf-embed__page) {
overflow: hidden;
background: var(--color-white);
box-shadow: 0 10px 32px rgb(31 31 31 / 16%);
}
.pdf-viewer__rendering-status {
margin: 0.8rem 0 0;
color: var(--color-text-muted);
font-size: 0.85rem;
font-weight: 700;
}
@media (max-width: 700px) {
.pdf-viewer {
padding: 0;
}
.pdf-viewer__panel {
width: 100%;
height: 100vh;
border-radius: 0;
}
.pdf-viewer__header,
.pdf-viewer__toolbar,
.pdf-viewer__frame {
padding-right: 0.75rem;
padding-left: 0.75rem;
}
.pdf-viewer__search {
flex-basis: 100%;
}
}
</style>

View file

@ -1,16 +1,26 @@
<script setup lang="ts"> <script setup lang="ts">
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { computed, watch } from 'vue' import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import ElementParentLink from '@/components/ElementParentLink.vue' import ElementParentLink from '@/components/ElementParentLink.vue'
import ElementSiblingNavigation from '@/components/ElementSiblingNavigation.vue' import ElementSiblingNavigation from '@/components/ElementSiblingNavigation.vue'
import PdfViewerModal from '@/components/PdfViewerModal.vue'
import SiteHeader from '@/components/SiteHeader.vue' import SiteHeader from '@/components/SiteHeader.vue'
import { useElementsStore } from '@/stores/elements' import { useElementsStore } from '@/stores/elements'
type TimestampPart = string | undefined type TimestampPart = string | undefined
type ElementPdfFolder = 'short' | 'long'
interface ActivePdf {
openUrl: string
sourceUrl: string
title: string
}
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL as string
const route = useRoute() const route = useRoute()
const elementsStore = useElementsStore() const elementsStore = useElementsStore()
const activePdf = ref<ActivePdf | null>(null)
const { const {
element, element,
childElements, childElements,
@ -46,9 +56,23 @@ const youtubeEmbedUrl = computed(() => {
return getYoutubeEmbedUrl(youtubeUrl) return getYoutubeEmbedUrl(youtubeUrl)
}) })
const activePdfTitle = computed(() => {
return activePdf.value?.title ?? ''
})
const activePdfUrl = computed(() => {
return activePdf.value?.sourceUrl ?? ''
})
const activePdfOpenUrl = computed(() => {
return activePdf.value?.openUrl ?? ''
})
watch( watch(
elementId, elementId,
(currentElementId) => { (currentElementId) => {
activePdf.value = null
if (typeof currentElementId !== 'string' || currentElementId === '') { if (typeof currentElementId !== 'string' || currentElementId === '') {
return return
} }
@ -58,6 +82,61 @@ watch(
{ immediate: true }, { immediate: true },
) )
function openPdfViewer(pdfTitle: string, pdfUrl: string | null): void {
if (pdfUrl === null) {
return
}
activePdf.value = {
openUrl: pdfUrl,
sourceUrl: getPdfViewerUrl(pdfUrl),
title: pdfTitle,
}
}
function closePdfViewer(): void {
activePdf.value = null
}
function getPdfViewerUrl(pdfUrl: string): string {
let parsedPdfUrl: URL
try {
parsedPdfUrl = new URL(pdfUrl, window.location.origin)
} catch {
return pdfUrl
}
const pathSegments = parsedPdfUrl.pathname
.split('/')
.filter((pathSegment) => {
return pathSegment !== ''
})
if (pathSegments.length !== 4) {
return pdfUrl
}
if (pathSegments[0] !== 'storage' || pathSegments[1] !== 'element-pdfs') {
return pdfUrl
}
const pdfFolder = pathSegments[2]
const fileName = pathSegments[3]
if (!isElementPdfFolder(pdfFolder) || fileName === undefined) {
return pdfUrl
}
const encodedFileName = encodeURIComponent(fileName)
return `${API_BASE_URL}/api/element-pdfs/${pdfFolder}/${encodedFileName}`
}
function isElementPdfFolder(
pdfFolder: string | undefined,
): pdfFolder is ElementPdfFolder {
return pdfFolder === 'short' || pdfFolder === 'long'
}
function getYoutubeEmbedUrl(youtubeUrl: string | null): string | null { function getYoutubeEmbedUrl(youtubeUrl: string | null): string | null {
if (youtubeUrl === null || youtubeUrl === '') { if (youtubeUrl === null || youtubeUrl === '') {
return null return null
@ -266,26 +345,24 @@ function isShortYoutubeHost(hostname: string): boolean {
v-if="element.shortPdfPath !== null || element.longPdfPath !== null" v-if="element.shortPdfPath !== null || element.longPdfPath !== null"
class="element-page__actions" class="element-page__actions"
> >
<a <button
v-if="element.shortPdfPath !== null" v-if="element.shortPdfPath !== null"
:href="element.shortPdfPath" type="button"
class="element-page__pdf-link" class="element-page__pdf-link"
data-cy="element-short-pdf-link" data-cy="element-short-pdf-viewer-button"
target="_blank" @click="openPdfViewer('Short PDF', element.shortPdfPath)"
rel="noreferrer"
> >
View Short PDF View Short PDF
</a> </button>
<a <button
v-if="element.longPdfPath !== null" v-if="element.longPdfPath !== null"
:href="element.longPdfPath" type="button"
class="element-page__pdf-link" class="element-page__pdf-link"
data-cy="element-long-pdf-link" data-cy="element-long-pdf-viewer-button"
target="_blank" @click="openPdfViewer('Long PDF', element.longPdfPath)"
rel="noreferrer"
> >
View Long PDF View Long PDF
</a> </button>
</div> </div>
<nav <nav
@ -326,6 +403,13 @@ function isShortYoutubeHost(hostname: string): boolean {
/> />
</section> </section>
</main> </main>
<PdfViewerModal
:is-open="activePdf !== null"
:open-url="activePdfOpenUrl"
:pdf-title="activePdfTitle"
:pdf-url="activePdfUrl"
@close="closePdfViewer"
/>
</div> </div>
</template> </template>