Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

All uploading images to event descriptions (#512)

Dave Earley7020a641a9b3
diff --git a/backend/app/DomainObjects/Enums/ImageTypes.php b/backend/app/DomainObjects/Enums/ImageTypes.php
new file mode 100644
index 000000000..41cbc622f
--- /dev/null
+++ b/backend/app/DomainObjects/Enums/ImageTypes.php
@@ -0,0 +1,10 @@
+<?php
+
+namespace HiEvents\DomainObjects\Enums;
+
+enum ImageTypes
+{
+ use BaseEnum;
+
+ case GENERIC;
+}
diff --git a/backend/app/Http/Actions/Images/CreateImageAction.php b/backend/app/Http/Actions/Images/CreateImageAction.php
new file mode 100644
index 000000000..79a687e7d
--- /dev/null
+++ b/backend/app/Http/Actions/Images/CreateImageAction.php
@@ -0,0 +1,33 @@
+<?php
+
+namespace HiEvents\Http\Actions\Images;
+
+use HiEvents\Http\Actions\BaseAction;
+use HiEvents\Http\Request\Image\CreateImageRequest;
+use HiEvents\Resources\Image\ImageResource;
+use HiEvents\Services\Application\Handlers\Images\CreateImageHandler;
+use HiEvents\Services\Application\Handlers\Images\DTO\CreateImageDTO;
+use HiEvents\Services\Infrastructure\Image\Exception\CouldNotUploadImageException;
+use Illuminate\Http\JsonResponse;
+
+class CreateImageAction extends BaseAction
+{
+ public function __construct(
+ public readonly CreateImageHandler $createImageHandler,
+ )
+ {
+ }
+
+ /**
+ * @throws CouldNotUploadImageException
+ */
+ public function __invoke(CreateImageRequest $request): JsonResponse
+ {
+ $image = $this->createImageHandler->handle(new CreateImageDTO(
+ userId: $this->getAuthenticatedUser()->getId(),
+ image: $request->file('image'),
+ ));
+
+ return $this->resourceResponse(ImageResource::class, $image);
+ }
+}
diff --git a/backend/app/Http/Request/Event/CreateEventImageRequest.php b/backend/app/Http/Request/Event/CreateEventImageRequest.php
index 4150d221b..0a03567d6 100644
--- a/backend/app/Http/Request/Event/CreateEventImageRequest.php
+++ b/backend/app/Http/Request/Event/CreateEventImageRequest.php
@@ -3,6 +3,7 @@
namespace HiEvents\Http\Request\Event;
use HiEvents\DomainObjects\Enums\EventImageType;
+use HiEvents\Validators\Rules\RulesHelper;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -11,14 +12,15 @@ class CreateEventImageRequest extends FormRequest
public function rules(): array
{
return [
- 'image' => [
- 'required',
- 'image',
- 'max:8192', //8mb
- 'dimensions:min_width=600,min_height=50,max_width=4000,max_height=4000',
- 'mimes:jpeg,png,jpg,webp',
- ],
+ 'image' => RulesHelper::IMAGE_RULES,
'type' => Rule::in(EventImageType::valuesArray()),
];
}
+
+ public function messages(): array
+ {
+ return [
+ 'image.dimensions' => __('The image must be at least 600 pixels wide and 50 pixels tall, and no more than 4000 pixels wide and 4000 pixels tall.'),
+ ];
+ }
}
diff --git a/backend/app/Http/Request/Image/CreateImageRequest.php b/backend/app/Http/Request/Image/CreateImageRequest.php
new file mode 100644
index 000000000..b1225f718
--- /dev/null
+++ b/backend/app/Http/Request/Image/CreateImageRequest.php
@@ -0,0 +1,23 @@
+<?php
+
+namespace HiEvents\Http\Request\Image;
+
+use HiEvents\Validators\Rules\RulesHelper;
+use Illuminate\Foundation\Http\FormRequest;
+
+class CreateImageRequest extends FormRequest
+{
+ public function rules(): array
+ {
+ return [
+ 'image' => RulesHelper::IMAGE_RULES,
+ ];
+ }
+
+ public function messages(): array
+ {
+ return [
+ 'image.dimensions' => __('The image must be at least 600 pixels wide and 50 pixels tall, and no more than 4000 pixels wide and 4000 pixels tall.'),
+ ];
+ }
+}
diff --git a/backend/app/Services/Application/Handlers/Event/CreateEventImageHandler.php b/backend/app/Services/Application/Handlers/Event/CreateEventImageHandler.php
index fbfd83255..b96c82359 100644
--- a/backend/app/Services/Application/Handlers/Event/CreateEventImageHandler.php
+++ b/backend/app/Services/Application/Handlers/Event/CreateEventImageHandler.php
@@ -23,7 +23,7 @@ class CreateEventImageHandler
return $this->createEventImageService->createImage(
eventId: $imageData->event_id,
image: $imageData->image,
- type: $imageData->type,
+ imageType: $imageData->imageType,
);
}
}
diff --git a/backend/app/Services/Application/Handlers/Event/DTO/CreateEventImageDTO.php b/backend/app/Services/Application/Handlers/Event/DTO/CreateEventImageDTO.php
index 943d2f63d..5ac03f4a4 100644
--- a/backend/app/Services/Application/Handlers/Event/DTO/CreateEventImageDTO.php
+++ b/backend/app/Services/Application/Handlers/Event/DTO/CreateEventImageDTO.php
@@ -11,7 +11,7 @@ class CreateEventImageDTO extends BaseDTO
public function __construct(
public readonly int $event_id,
public readonly UploadedFile $image,
- public readonly EventImageType $type,
+ public readonly EventImageType $imageType,
)
{
}
diff --git a/backend/app/Services/Application/Handlers/Images/CreateImageHandler.php b/backend/app/Services/Application/Handlers/Images/CreateImageHandler.php
new file mode 100644
index 000000000..530ffeff0
--- /dev/null
+++ b/backend/app/Services/Application/Handlers/Images/CreateImageHandler.php
@@ -0,0 +1,33 @@
+<?php
+
+namespace HiEvents\Services\Application\Handlers\Images;
+
+use HiEvents\DomainObjects\Enums\ImageTypes;
+use HiEvents\DomainObjects\ImageDomainObject;
+use HiEvents\DomainObjects\UserDomainObject;
+use HiEvents\Services\Application\Handlers\Images\DTO\CreateImageDTO;
+use HiEvents\Services\Domain\Image\ImageUploadService;
+use HiEvents\Services\Infrastructure\Image\Exception\CouldNotUploadImageException;
+
+class CreateImageHandler
+{
+ public function __construct(
+ private readonly ImageUploadService $imageUploadService,
+ )
+ {
+ }
+
+ /**
+ * @throws CouldNotUploadImageException
+ */
+ public function handle(CreateImageDTO $imageData): ImageDomainObject
+ {
+ // For generic images, we associate them with the user
+ return $this->imageUploadService->upload(
+ image: $imageData->image,
+ entityId: $imageData->userId,
+ entityType: UserDomainObject::class,
+ imageType: ImageTypes::GENERIC->name,
+ );
+ }
+}
diff --git a/backend/app/Services/Application/Handlers/Images/DTO/CreateImageDTO.php b/backend/app/Services/Application/Handlers/Images/DTO/CreateImageDTO.php
new file mode 100644
index 000000000..fd2b98516
--- /dev/null
+++ b/backend/app/Services/Application/Handlers/Images/DTO/CreateImageDTO.php
@@ -0,0 +1,15 @@
+<?php
+
+namespace HiEvents\Services\Application\Handlers\Images\DTO;
+
+use Illuminate\Http\UploadedFile;
+
+class CreateImageDTO
+{
+ public function __construct(
+ public readonly int $userId,
+ public readonly UploadedFile $image,
+ )
+ {
+ }
+}
diff --git a/backend/app/Services/Application/Handlers/Organizer/CreateOrganizerHandler.php b/backend/app/Services/Application/Handlers/Organizer/CreateOrganizerHandler.php
index 765dd9e38..e920a3f17 100644
--- a/backend/app/Services/Application/Handlers/Organizer/CreateOrganizerHandler.php
+++ b/backend/app/Services/Application/Handlers/Organizer/CreateOrganizerHandler.php
@@ -49,7 +49,7 @@ readonly class CreateOrganizerHandler
image: $organizerData->logo,
entityId: $organizer->getId(),
entityType: OrganizerDomainObject::class,
- imageType: OrganizerImageType::LOGO->name,
+ imageType: OrganizerImageType::LOGO,
);
}
diff --git a/backend/app/Services/Domain/Event/CreateEventImageService.php b/backend/app/Services/Domain/Event/CreateEventImageService.php
index 7c9f85574..10a1d75c3 100644
--- a/backend/app/Services/Domain/Event/CreateEventImageService.php
+++ b/backend/app/Services/Domain/Event/CreateEventImageService.php
@@ -27,11 +27,11 @@ class CreateEventImageService
public function createImage(
int $eventId,
UploadedFile $image,
- EventImageType $type,
+ EventImageType $imageType,
): ImageDomainObject
{
- return $this->databaseManager->transaction(function () use ($image, $eventId, $type) {
- if ($type === EventImageType::EVENT_COVER) {
+ return $this->databaseManager->transaction(function () use ($entityType, $image, $eventId, $imageType) {
+ if ($imageType === EventImageType::EVENT_COVER) {
$this->imageRepository->deleteWhere([
'entity_id' => $eventId,
'entity_type' => EventDomainObject::class,
@@ -43,7 +43,7 @@ class CreateEventImageService
image: $image,
entityId: $eventId,
entityType: EventDomainObject::class,
- imageType: $type->name,
+ imageType: $imageType->name,
);
});
}
diff --git a/backend/app/Services/Domain/Image/ImageUploadService.php b/backend/app/Services/Domain/Image/ImageUploadService.php
index c7c950e01..0a2b004b2 100644
--- a/backend/app/Services/Domain/Image/ImageUploadService.php
+++ b/backend/app/Services/Domain/Image/ImageUploadService.php
@@ -8,11 +8,11 @@ use HiEvents\Services\Infrastructure\Image\Exception\CouldNotUploadImageExceptio
use HiEvents\Services\Infrastructure\Image\ImageStorageService;
use Illuminate\Http\UploadedFile;
-readonly class ImageUploadService
+class ImageUploadService
{
public function __construct(
- private ImageStorageService $imageStorageService,
- private ImageRepositoryInterface $imageRepository
+ private readonly ImageStorageService $imageStorageService,
+ private readonly ImageRepositoryInterface $imageRepository
)
{
}
diff --git a/backend/app/Services/Infrastructure/Image/ImageStorageService.php b/backend/app/Services/Infrastructure/Image/ImageStorageService.php
index db97807a0..c2d962c01 100644
--- a/backend/app/Services/Infrastructure/Image/ImageStorageService.php
+++ b/backend/app/Services/Infrastructure/Image/ImageStorageService.php
@@ -10,12 +10,12 @@ use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Psr\Log\LoggerInterface;
-readonly class ImageStorageService
+class ImageStorageService
{
public function __construct(
- private FilesystemManager $filesystemManager,
- private Repository $config,
- private LoggerInterface $logger,
+ private readonly FilesystemManager $filesystemManager,
+ private readonly Repository $config,
+ private readonly LoggerInterface $logger,
)
{
}
diff --git a/backend/app/Validators/Rules/RulesHelper.php b/backend/app/Validators/Rules/RulesHelper.php
index a68729c2d..cc21970c5 100644
--- a/backend/app/Validators/Rules/RulesHelper.php
+++ b/backend/app/Validators/Rules/RulesHelper.php
@@ -17,4 +17,12 @@ class RulesHelper
public const REQUIRED_EMAIL = ['email' , 'required', 'max:100'];
public const OPTIONAL_TEXT_MEDIUM_LENGTH = ['string', 'max:2000', 'nullable'];
+
+ public const IMAGE_RULES = [
+ 'required',
+ 'image',
+ 'max:8192', //8mb
+ 'dimensions:min_width=600,min_height=50,max_width=4000,max_height=4000',
+ 'mimes:jpeg,png,jpg,webp',
+ ];
}
diff --git a/backend/routes/api.php b/backend/routes/api.php
index b684be9e5..3260df5cc 100644
--- a/backend/routes/api.php
+++ b/backend/routes/api.php
@@ -53,6 +53,7 @@ use HiEvents\Http\Actions\Events\UpdateEventStatusAction;
use HiEvents\Http\Actions\EventSettings\EditEventSettingsAction;
use HiEvents\Http\Actions\EventSettings\GetEventSettingsAction;
use HiEvents\Http\Actions\EventSettings\PartialEditEventSettingsAction;
+use HiEvents\Http\Actions\Images\CreateImageAction;
use HiEvents\Http\Actions\Messages\GetMessagesAction;
use HiEvents\Http\Actions\Messages\SendMessageAction;
use HiEvents\Http\Actions\Orders\CancelOrderAction;
@@ -297,6 +298,9 @@ $router->middleware(['auth:api'])->group(
// Reports
$router->get('/events/{event_id}/reports/{report_type}', GetReportAction::class);
+
+ // Images
+ $router->post('/images', CreateImageAction::class);
}
);
diff --git a/backend/tests/Unit/Services/Application/Handlers/Images/CreateImageHandlerTest.php b/backend/tests/Unit/Services/Application/Handlers/Images/CreateImageHandlerTest.php
new file mode 100644
index 000000000..27e0d70b8
--- /dev/null
+++ b/backend/tests/Unit/Services/Application/Handlers/Images/CreateImageHandlerTest.php
@@ -0,0 +1,56 @@
+<?php
+
+namespace Tests\Unit\Services\Application\Handlers\Images;
+
+use HiEvents\DomainObjects\Enums\ImageTypes;
+use HiEvents\DomainObjects\ImageDomainObject;
+use HiEvents\DomainObjects\UserDomainObject;
+use HiEvents\Services\Application\Handlers\Images\CreateImageHandler;
+use HiEvents\Services\Application\Handlers\Images\DTO\CreateImageDTO;
+use HiEvents\Services\Domain\Image\ImageUploadService;
+use Illuminate\Http\UploadedFile;
+use Mockery as m;
+use PHPUnit\Framework\TestCase;
+
+class CreateImageHandlerTest extends TestCase
+{
+ private ImageUploadService $imageUploadService;
+ private CreateImageHandler $handler;
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $this->imageUploadService = m::mock(ImageUploadService::class);
+
+ $this->handler = new CreateImageHandler(
+ $this->imageUploadService
+ );
+ }
+
+ public function testHandleSuccessfullyCreatesImage(): void
+ {
+ $uploadedFile = m::mock(UploadedFile::class);
+ $imageDomainObject = m::mock(ImageDomainObject::class);
+
+ $dto = new CreateImageDTO(
+ userId: 42,
+ image: $uploadedFile
+ );
+
+ $this->imageUploadService
+ ->shouldReceive('upload')
+ ->once()
+ ->withArgs([
+ $uploadedFile,
+ 42,
+ UserDomainObject::class,
+ ImageTypes::GENERIC->name,
+ ])
+ ->andReturn($imageDomainObject);
+
+ $result = $this->handler->handle($dto);
+
+ $this->assertSame($imageDomainObject, $result);
+ }
+}
diff --git a/backend/tests/Unit/Services/Domain/Image/ImageUploadServiceTest.php b/backend/tests/Unit/Services/Domain/Image/ImageUploadServiceTest.php
new file mode 100644
index 000000000..0e1b666e3
--- /dev/null
+++ b/backend/tests/Unit/Services/Domain/Image/ImageUploadServiceTest.php
@@ -0,0 +1,92 @@
+<?php
+
+namespace Tests\Unit\Services\Domain\Image;
+
+use HiEvents\DomainObjects\ImageDomainObject;
+use HiEvents\Repository\Interfaces\ImageRepositoryInterface;
+use HiEvents\Services\Domain\Image\ImageUploadService;
+use HiEvents\Services\Infrastructure\Image\DTO\ImageStorageResponseDTO;
+use HiEvents\Services\Infrastructure\Image\Exception\CouldNotUploadImageException;
+use HiEvents\Services\Infrastructure\Image\ImageStorageService;
+use Illuminate\Http\UploadedFile;
+use Mockery as m;
+use PHPUnit\Framework\TestCase;
+
+class ImageUploadServiceTest extends TestCase
+{
+ private ImageStorageService $imageStorageService;
+ private ImageRepositoryInterface $imageRepository;
+ private ImageUploadService $service;
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $this->imageStorageService = m::mock(ImageStorageService::class);
+ $this->imageRepository = m::mock(ImageRepositoryInterface::class);
+
+ $this->service = new ImageUploadService(
+ $this->imageStorageService,
+ $this->imageRepository
+ );
+ }
+
+ public function testUploadSuccessfullyCreatesImageRecord(): void
+ {
+ $uploadedFile = m::mock(UploadedFile::class);
+ $storedImage = new ImageStorageResponseDTO(
+ filename: 'foo.jpg',
+ disk: 'public',
+ path: 'images/foo.jpg',
+ size: 123456,
+ mime_type: 'image/jpeg'
+ );
+ $imageDomainObject = m::mock(ImageDomainObject::class);
+
+ $this->imageStorageService
+ ->shouldReceive('store')
+ ->once()
+ ->with($uploadedFile, 'profile')
+ ->andReturn($storedImage);
+
+ $this->imageRepository
+ ->shouldReceive('create')
+ ->once()
+ ->with([
+ 'entity_id' => 1,
+ 'entity_type' => 'user',
+ 'type' => 'profile',
+ 'filename' => 'foo.jpg',
+ 'disk' => 'public',
+ 'path' => 'images/foo.jpg',
+ 'size' => 123456,
+ 'mime_type' => 'image/jpeg',
+ ])
+ ->andReturn($imageDomainObject);
+
+ $result = $this->service->upload($uploadedFile, 1, 'user', 'profile');
+
+ $this->assertSame($imageDomainObject, $result);
+ }
+
+ public function testUploadThrowsExceptionIfStorageFails(): void
+ {
+ $this->expectException(CouldNotUploadImageException::class);
+
+ $uploadedFile = m::mock(UploadedFile::class);
+
+ $this->imageStorageService
+ ->shouldReceive('store')
+ ->once()
+ ->with($uploadedFile, 'profile')
+ ->andThrow(new CouldNotUploadImageException('Failed to store image'));
+
+ $this->service->upload($uploadedFile, 1, 'user', 'profile');
+ }
+
+ protected function tearDown(): void
+ {
+ m::close();
+ parent::tearDown();
+ }
+}
diff --git a/frontend/src/api/event.client.ts b/frontend/src/api/event.client.ts
index 4d7ad46c5..c4777626c 100644
--- a/frontend/src/api/event.client.ts
+++ b/frontend/src/api/event.client.ts
@@ -1,12 +1,14 @@
import {api} from "./client";
import {
CheckInStats,
- Event, EventDuplicatePayload,
+ Event,
+ EventDuplicatePayload,
EventStats,
GenericDataResponse,
GenericPaginatedResponse,
IdParam,
Image,
+ ImageType,
QueryFilters,
} from "../types";
import {publicApi} from "./public-client.ts";
@@ -50,10 +52,10 @@ export const eventsClient = {
return response.data;
},
- uploadEventImage: async (eventId: IdParam, image: File) => {
+ uploadEventImage: async (eventId: IdParam, image: File, type: ImageType = 'EVENT_COVER') => {
const formData = new FormData();
formData.append('image', image);
- formData.append('type', 'EVENT_COVER');
+ formData.append('type', type);
const response = await api.post<GenericDataResponse<Image>>('events/' + eventId + '/images', formData, {
headers: {
'Content-Type': 'multipart/form-data'
diff --git a/frontend/src/api/image.client.ts b/frontend/src/api/image.client.ts
new file mode 100644
index 000000000..66a7ceb2a
--- /dev/null
+++ b/frontend/src/api/image.client.ts
@@ -0,0 +1,15 @@
+import {GenericDataResponse, Image} from "../types.ts";
+import {api} from "./client.ts";
+
+export const imageClient = {
+ uploadImage: async (image: File) => {
+ const formData = new FormData();
+ formData.append('image', image);
+ const response = await api.post<GenericDataResponse<Image>>('images', formData, {
+ headers: {
+ 'Content-Type': 'multipart/form-data'
+ }
+ });
+ return response.data;
+ },
+}
diff --git a/frontend/src/components/common/Editor/Controls/InsertImageControl/index.tsx b/frontend/src/components/common/Editor/Controls/InsertImageControl/index.tsx
index 9ca1c1696..78cd3563c 100644
--- a/frontend/src/components/common/Editor/Controls/InsertImageControl/index.tsx
+++ b/frontend/src/components/common/Editor/Controls/InsertImageControl/index.tsx
@@ -1,49 +1,91 @@
import {RichTextEditor, useRichTextEditorContext} from "@mantine/tiptap";
-import {useCallback, useState} from "react";
+import {useState} from "react";
import {t} from "@lingui/macro";
import {IconPhotoPlus} from "@tabler/icons-react";
-import {Button, Group, Modal, Portal, TextInput} from "@mantine/core";
+import {Button, FileButton, Group, Image, Modal, Portal, Stack, Tabs, Text, TextInput} from "@mantine/core";
+import {useUploadImage} from "../../../../../mutations/useUploadImage.ts";
export const InsertImageControl = () => {
const editor = useRichTextEditorContext();
const [isModalOpen, setModalOpen] = useState(false);
+ const [tab, setTab] = useState<string>('url');
const [imageUrl, setImageUrl] = useState('');
- const [imageError, setImageError] = useState<string | null>(null);
+ const [uploadedImageUrl, setUploadedImageUrl] = useState('');
+ const [urlError, setUrlError] = useState<string | null>(null);
+ const [uploadError, setUploadError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
- // Function to validate if the URL is an actual image
+ const uploadMutation = useUploadImage();
+
const checkImageExists = (url: string) => {
return new Promise((resolve, reject) => {
- const img = new Image();
+ const img = document.createElement('img') as HTMLImageElement;
img.onload = () => resolve(true);
img.onerror = () => reject(false);
img.src = url;
});
};
- const handleImageInsert = useCallback(async () => {
+ const handleImageInsert = async () => {
setLoading(true);
try {
- await checkImageExists(imageUrl);
+ const finalUrl = uploadedImageUrl || imageUrl;
+ if (!finalUrl) {
+ setUrlError(t`Please provide an image.`);
+ return;
+ }
+ await checkImageExists(finalUrl);
if (editor) {
- editor.editor!.commands.setImage({src: imageUrl});
+ editor.editor!.commands.setImage({src: finalUrl});
}
setModalOpen(false);
- setImageError(null);
- setImageUrl('');
+ resetState();
+ } catch (error) {
+ console.log(error)
+ setUrlError(t`Please enter a valid image URL that points to an image.`);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleFileUpload = async (file: File) => {
+ if (!file) {
+ setUploadError(t`Please select an image.`);
+ return;
+ }
+ setLoading(true);
+ try {
+ uploadMutation.mutate({image: file}, {
+ onSuccess: ({data}) => {
+ setUploadedImageUrl(data.url);
+ setUploadError(null);
+ },
+ onError: (error: any) => {
+ const message = error?.response?.data?.message ?? t`Failed to upload image.`;
+ setUploadError(message);
+ }
+ });
} catch {
- setImageError(t`Please enter a valid image URL that points to an image.`);
+ setUploadError(t`Failed to upload image.`);
} finally {
setLoading(false);
}
- }, [editor, imageUrl]);
+ };
+
+ const resetState = () => {
+ setTab('url');
+ setImageUrl('');
+ setUploadedImageUrl('');
+ setUrlError(null);
+ setUploadError(null);
+ };
return (
<>
<RichTextEditor.Control
onClick={() => setModalOpen(true)}
- aria-label="Insert star emoji"
- title="Insert star emoji"
+ aria-label="Insert image"
+ title="Insert image"
>
<IconPhotoPlus stroke={1.5} size="1rem"/>
</RichTextEditor.Control>
@@ -51,21 +93,76 @@ export const InsertImageControl = () => {
<Portal>
<Modal
opened={isModalOpen}
- onClose={() => setModalOpen(false)}
+ onClose={() => {
+ setModalOpen(false);
+ resetState();
+ }}
title={t`Insert Image`}
>
- <TextInput
- label={t`Image URL`}
- placeholder="https://example.com/image.jpg"
- value={imageUrl}
- onChange={(event) => setImageUrl(event.currentTarget.value)}
- error={imageError}
- />
- <Group mt="md">
- <Button onClick={handleImageInsert} loading={loading}>
- {t`Insert Image`}
- </Button>
- </Group>
+ <Tabs value={tab} onChange={setTab} variant="outline">
+ <Tabs.List grow>
+ <Tabs.Tab value="url">{t`Paste URL`}</Tabs.Tab>
+ <Tabs.Tab value="upload">{t`Upload Image`}</Tabs.Tab>
+ </Tabs.List>
+
+ <Tabs.Panel value="url" pt="md">
+ <Stack>
+ <TextInput
+ label={t`Image URL`}
+ placeholder="https://example.com/image.jpg"
+ value={imageUrl}
+ onChange={(event) => {
+ setImageUrl(event.currentTarget.value);
+ setUrlError(null);
+ }}
+ error={urlError}
+ />
+ <Button onClick={handleImageInsert} loading={loading}>
+ {t`Insert Image`}
+ </Button>
+ </Stack>
+ </Tabs.Panel>
+
+ <Tabs.Panel value="upload" pt="md">
+ <Stack>
+ {uploadedImageUrl ? (
+ <>
+ <Image
+ src={uploadedImageUrl}
+ alt="Uploaded preview"
+ radius="md"
+ />
+ <Group grow>
+ <Button onClick={handleImageInsert} loading={loading}>
+ {t`Insert Image`}
+ </Button>
+ <Button variant="outline" color="red" onClick={resetState}>
+ {t`Remove`}
+ </Button>
+ </Group>
+ </>
+ ) : (
+ <>
+ <FileButton onChange={(file: File | null) => {
+ setUploadError(null);
+ file && handleFileUpload(file);
+ }} accept="image/*">
+ {(props) => (
+ <Button {...props} variant="outline" loading={loading}>
+ {t`Upload Image`}
+ </Button>
+ )}
+ </FileButton>
+ {uploadError && (
+ <Text c="red" size="sm">
+ {uploadError}
+ </Text>
+ )}
+ </>
+ )}
+ </Stack>
+ </Tabs.Panel>
+ </Tabs>
</Modal>
</Portal>
</>
diff --git a/frontend/src/components/common/Editor/Extensions/ImageResizeExtension/index.tsx b/frontend/src/components/common/Editor/Extensions/ImageResizeExtension/index.tsx
index bce68406c..7ea99c63d 100644
--- a/frontend/src/components/common/Editor/Extensions/ImageResizeExtension/index.tsx
+++ b/frontend/src/components/common/Editor/Extensions/ImageResizeExtension/index.tsx
@@ -1,5 +1,5 @@
-import {NodeViewProps} from '@tiptap/core';
import Image from '@tiptap/extension-image';
+import { NodeViewProps } from '@tiptap/react';
/**
* Adapted from https://github.com/bae-sh/tiptap-extension-resize-image/blob/main/lib/imageResize.ts
@@ -7,12 +7,7 @@ import Image from '@tiptap/extension-image';
export const ImageResize = Image.extend({
addAttributes() {
return {
- src: {
- default: null,
- },
- alt: {
- default: null,
- },
+ ...this.parent?.(),
style: {
default: 'width: 100%; height: auto; cursor: pointer;',
parseHTML: (element: HTMLElement) => {
@@ -22,213 +17,110 @@ export const ImageResize = Image.extend({
: `${element.style.cssText}`;
},
},
- title: {
- default: null,
- },
- loading: {
- default: null,
- },
- srcset: {
- default: null,
- },
- sizes: {
- default: null,
- },
- crossorigin: {
- default: null,
- },
- usemap: {
- default: null,
- },
- ismap: {
- default: null,
- },
- width: {
- default: null,
- },
- height: {
- default: null,
- },
- referrerpolicy: {
- default: null,
- },
- longdesc: {
- default: null,
- },
- decoding: {
- default: null,
- },
- class: {
- default: null,
- },
- id: {
- default: null,
- },
- name: {
- default: null,
- },
- draggable: {
- default: true,
- },
- tabindex: {
- default: null,
- },
- 'aria-label': {
- default: null,
- },
- 'aria-labelledby': {
- default: null,
- },
- 'aria-describedby': {
- default: null,
- },
};
},
+
addNodeView() {
- return ({node, editor, getPos}: NodeViewProps) => {
+ return ({ node, editor, getPos }: NodeViewProps) => {
const {
view,
- options: {editable},
+ options: { editable },
} = editor;
- const {style} = node.attrs;
- const $wrapper: HTMLDivElement = document.createElement('div');
- const $container: HTMLDivElement = document.createElement('div');
- const $img: HTMLImageElement = document.createElement('img');
- const iconStyle = 'width: 24px; height: 24px; cursor: pointer; margin-bottom: 0;';
-
- const dispatchNodeView = () => {
- if (typeof getPos === 'function') {
- const newAttrs = {
- ...node.attrs,
- style: `${$img.style.cssText}`,
- };
- view.dispatch(view.state.tr.setNodeMarkup(getPos(), null, newAttrs));
- }
- };
-
- const paintPositionController = () => {
- const $positionController: HTMLDivElement = document.createElement('div');
-
- const $leftController: HTMLImageElement = document.createElement('img');
- const $centerController: HTMLImageElement = document.createElement('img');
- const $rightController: HTMLImageElement = document.createElement('img');
-
- const controllerMouseOver = (e: MouseEvent) => {
- (e.target as HTMLElement).style.opacity = '0.3';
- };
-
- const controllerMouseOut = (e: MouseEvent) => {
- (e.target as HTMLElement).style.opacity = '1';
- };
-
- $positionController.setAttribute(
- 'style',
- 'position: absolute; top: 0%; left: 50%; width: 100px; height: 25px; z-index: 999; background-color: rgba(255, 255, 255, 0.7); border-radius: 4px; border: 2px solid #6C6C6C; cursor: pointer; transform: translate(-50%, -50%); display: flex; justify-content: space-between; align-items: center; padding: 0 10px;',
- );
- $leftController.setAttribute(
- 'src',
- 'https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/format_align_left/default/20px.svg',
- );
- $leftController.setAttribute('style', iconStyle);
- $leftController.addEventListener('mouseover', controllerMouseOver);
- $leftController.addEventListener('mouseout', controllerMouseOut);
+ const { style } = node.attrs;
- $centerController.setAttribute(
- 'src',
- 'https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/format_align_center/default/20px.svg',
- );
- $centerController.setAttribute('style', iconStyle);
- $centerController.addEventListener('mouseover', controllerMouseOver);
- $centerController.addEventListener('mouseout', controllerMouseOut);
+ const $wrapper = document.createElement('div');
+ $wrapper.setAttribute('style', 'display: flex; align-items: center;');
- $rightController.setAttribute(
- 'src',
- 'https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/format_align_right/default/20px.svg',
- );
- $rightController.setAttribute('style', iconStyle);
- $rightController.addEventListener('mouseover', controllerMouseOver);
- $rightController.addEventListener('mouseout', controllerMouseOut);
-
- $leftController.addEventListener('click', () => {
- $img.setAttribute('style', `${$img.style.cssText} margin: 0 auto 0 0;`);
- dispatchNodeView();
- });
- $centerController.addEventListener('click', () => {
- $img.setAttribute('style', `${$img.style.cssText} margin: 0 auto;`);
- dispatchNodeView();
- });
- $rightController.addEventListener('click', () => {
- $img.setAttribute('style', `${$img.style.cssText} margin: 0 0 0 auto;`);
- dispatchNodeView();
- });
-
- $positionController.appendChild($leftController);
- $positionController.appendChild($centerController);
- $positionController.appendChild($rightController);
-
- $container.appendChild($positionController);
- };
-
- $wrapper.setAttribute('style', `display: flex;`);
- $wrapper.appendChild($container);
-
- $container.setAttribute('style', `${style}`);
- $container.appendChild($img);
+ const $resizeWrapper = document.createElement('div');
+ $resizeWrapper.setAttribute('style', `${style}; position: relative;`);
+ const $img = document.createElement('img');
Object.entries(node.attrs).forEach(([key, value]) => {
- if (value === undefined || value === null) return;
- $img.setAttribute(key, value as string);
+ if (value !== undefined && value !== null) {
+ $img.setAttribute(key, value);
+ }
});
- if (!editable) return {dom: $img};
+ $img.style.marginBottom = '0px';
+ $img.style.display = 'block';
+ $resizeWrapper.appendChild($img);
+ $wrapper.appendChild($resizeWrapper);
+
+ if (!editable) return { dom: $wrapper };
+
+ const isMobile = document.documentElement.clientWidth < 768;
+ const dotPosition = isMobile ? '-8px' : '-4px';
const dotsPosition = [
- 'top: -4px; left: -4px; cursor: nwse-resize;',
- 'top: -4px; right: -4px; cursor: nesw-resize;',
- 'bottom: -4px; left: -4px; cursor: nesw-resize;',
- 'bottom: -4px; right: -4px; cursor: nwse-resize;',
+ `top: ${dotPosition}; left: ${dotPosition}; cursor: nwse-resize;`,
+ `top: ${dotPosition}; right: ${dotPosition}; cursor: nesw-resize;`,
+ `bottom: ${dotPosition}; left: ${dotPosition}; cursor: nesw-resize;`,
+ `bottom: ${dotPosition}; right: ${dotPosition}; cursor: nwse-resize;`,
];
let isResizing = false;
let startX: number, startWidth: number;
- $container.addEventListener('click', () => {
- // Remove remaining dots and position controller
- if ($container.childElementCount > 3) {
- for (let i = 0; i < 5; i++) {
- $container.removeChild($container.lastChild as Node);
- }
- }
+ const $sizeIndicator = document.createElement('div');
+ $sizeIndicator.setAttribute('style', `
+ position: absolute;
+ bottom: -24px;
+ left: 0;
+ background: rgba(0,0,0,0.7);
+ color: white;
+ font-size: 11px;
+ padding: 2px 4px;
+ border-radius: 4px;
+ pointer-events: none;
+ display: none;
+ `);
+ $resizeWrapper.appendChild($sizeIndicator);
+
+ const updateSizeIndicator = () => {
+ $sizeIndicator.innerText = `${$img.width}px × ${$img.height}px`;
+ $sizeIndicator.style.display = 'block';
+ };
- // Disable positioning for the time being as it's not working properly
- //paintPositionController();
+ const hideSizeIndicator = () => {
+ $sizeIndicator.style.display = 'none';
+ };
- $container.setAttribute(
- 'style',
- `position: relative; border: 1px dashed #6C6C6C; ${style} cursor: pointer;`,
- );
+ const dispatchNodeView = () => {
+ if (typeof getPos === 'function') {
+ const newAttrs = {
+ ...node.attrs,
+ style: `${$img.style.cssText}`,
+ };
+ view.dispatch(view.state.tr.setNodeMarkup(getPos(), null, newAttrs));
+ }
+ };
- Array.from({length: 4}, (_, index) => {
- const $dot: HTMLDivElement = document.createElement('div');
+ const addResizeDots = () => {
+ removeResizeDots();
+ $resizeWrapper.style.border = '1px dashed #6C6C6C';
+ updateSizeIndicator();
+
+ dotsPosition.forEach((pos, index) => {
+ const $dot = document.createElement('div');
$dot.setAttribute(
'style',
- `position: absolute; width: 9px; height: 9px; border: 1.5px solid #6C6C6C; border-radius: 50%; ${dotsPosition[index]}`,
+ `position: absolute; width: ${isMobile ? 16 : 9}px; height: ${isMobile ? 16 : 9}px; border: 1.5px solid #6C6C6C; border-radius: 50%; background: white; ${pos}`
);
$dot.addEventListener('mousedown', (e: MouseEvent) => {
e.preventDefault();
isResizing = true;
startX = e.clientX;
- startWidth = $container.offsetWidth;
+ startWidth = $resizeWrapper.offsetWidth;
const onMouseMove = (e: MouseEvent) => {
if (!isResizing) return;
const deltaX = index % 2 === 0 ? -(e.clientX - startX) : e.clientX - startX;
const newWidth = startWidth + deltaX;
-
- $container.style.width = newWidth + 'px';
+ $resizeWrapper.style.width = newWidth + 'px';
$img.style.width = newWidth + 'px';
+ updateSizeIndicator();
};
const onMouseUp = () => {
@@ -236,7 +128,6 @@ export const ImageResize = Image.extend({
isResizing = false;
}
dispatchNodeView();
-
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
@@ -244,29 +135,37 @@ export const ImageResize = Image.extend({
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
- $container.appendChild($dot);
- });
- });
- document.addEventListener('click', (e: MouseEvent) => {
- const $target = e.target as HTMLElement;
- const isClickInside = $container.contains($target) || $target.style.cssText === iconStyle;
+ $resizeWrapper.appendChild($dot);
+ });
+ };
- if (!isClickInside) {
- const containerStyle = $container.getAttribute('style');
- const newStyle = containerStyle?.replace('border: 1px dashed #6C6C6C;', '');
- $container.setAttribute('style', newStyle as string);
+ const removeResizeDots = () => {
+ $resizeWrapper.style.border = '';
+ Array.from($resizeWrapper.querySelectorAll('div')).forEach(dot => {
+ if (dot !== $sizeIndicator) dot.remove();
+ });
+ hideSizeIndicator();
+ };
- if ($container.childElementCount > 3) {
- for (let i = 0; i < 5; i++) {
- $container.removeChild($container.lastChild as Node);
- }
- }
+ const outsideClickHandler = (e: MouseEvent) => {
+ if (!$resizeWrapper.contains(e.target as Node)) {
+ removeResizeDots();
}
+ };
+
+ $resizeWrapper.addEventListener('click', (e) => {
+ e.stopPropagation();
+ addResizeDots();
});
+ document.addEventListener('click', outsideClickHandler);
+
return {
dom: $wrapper,
+ destroy() {
+ document.removeEventListener('click', outsideClickHandler);
+ },
};
};
},
diff --git a/frontend/src/mutations/useUploadEventImage.ts b/frontend/src/mutations/useUploadEventImage.ts
index 568e8f654..dba1f94d8 100644
--- a/frontend/src/mutations/useUploadEventImage.ts
+++ b/frontend/src/mutations/useUploadEventImage.ts
@@ -1,25 +1,26 @@
import {useMutation, useQueryClient} from "@tanstack/react-query";
-import {IdParam} from "../types.ts";
+import {IdParam, ImageType} from "../types.ts";
import {eventsClient} from "../api/event.client.ts";
import {GET_EVENT_IMAGES_QUERY_KEY} from "../queries/useGetEventImages.ts";
import {GET_EVENT_PUBLIC_QUERY_KEY} from "../queries/useGetEventPublic.ts";
-export const useUploadEventImage = () => {
+export const useUploadEventImage = (type: ImageType = 'EVENT_COVER') => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({eventId, image}: {
image: File,
eventId: IdParam,
- }) => eventsClient.uploadEventImage(eventId, image),
+ }) => eventsClient.uploadEventImage(eventId, image, type as ImageType),
- onSuccess: (_, variables) => {
- queryClient.invalidateQueries({
- queryKey: [GET_EVENT_IMAGES_QUERY_KEY, variables.eventId]
- });
- queryClient.invalidateQueries({
- queryKey: [GET_EVENT_PUBLIC_QUERY_KEY, variables.eventId]
- });
- }
+ onSuccess: (_, variables) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: [GET_EVENT_IMAGES_QUERY_KEY, variables.eventId]
+ }),
+ queryClient.invalidateQueries({
+ queryKey: [GET_EVENT_PUBLIC_QUERY_KEY, variables.eventId]
+ })
+ ])
});
}
diff --git a/frontend/src/mutations/useUploadImage.ts b/frontend/src/mutations/useUploadImage.ts
new file mode 100644
index 000000000..2cc1f37ab
--- /dev/null
+++ b/frontend/src/mutations/useUploadImage.ts
@@ -0,0 +1,10 @@
+import {useMutation} from "@tanstack/react-query";
+import {imageClient} from "../api/image.client.ts";
+
+export const useUploadImage = () => {
+ return useMutation({
+ mutationFn: ({image}: {
+ image: File,
+ }) => imageClient.uploadImage(image),
+ });
+}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 9ed8652cf..98bb7b85f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -100,9 +100,11 @@ export interface Image {
url: string;
size: number;
mime_type: string;
- type: string;
+ type: ImageType;
}
+export type ImageType = 'EVENT_COVER' | 'EDITOR_IMAGE';
+
export type PaymentProvider = 'STRIPE' | 'OFFLINE';
export interface EventSettings {