mirror of
https://github.com/seanmorley15/AdventureLog.git
synced 2025-07-22 22:39:36 +02:00
Refactor adventure category handling: update type definitions, enhance category management in UI components, and implement user-specific category deletion logic in the backend
This commit is contained in:
parent
736ede2417
commit
8e5a20ec62
12 changed files with 324 additions and 93 deletions
|
@ -21,18 +21,28 @@ class AdventureImageSerializer(CustomModelSerializer):
|
||||||
representation['image'] = f"{public_url}/media/{instance.image.name}"
|
representation['image'] = f"{public_url}/media/{instance.image.name}"
|
||||||
return representation
|
return representation
|
||||||
|
|
||||||
class CategorySerializer(CustomModelSerializer):
|
class CategorySerializer(serializers.ModelSerializer):
|
||||||
num_adventures = serializers.SerializerMethodField()
|
num_adventures = serializers.SerializerMethodField()
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Category
|
model = Category
|
||||||
fields = ['id', 'name', 'display_name', 'icon', 'user_id', 'num_adventures']
|
fields = ['id', 'name', 'display_name', 'icon', 'num_adventures']
|
||||||
read_only_fields = ['id', 'user_id', 'num_adventures']
|
read_only_fields = ['id', 'num_adventures']
|
||||||
|
|
||||||
def validate_name(self, value):
|
def validate_name(self, value):
|
||||||
if Category.objects.filter(name=value).exists():
|
return value.lower()
|
||||||
raise serializers.ValidationError('Category with this name already exists.')
|
|
||||||
|
|
||||||
return value
|
def create(self, validated_data):
|
||||||
|
user = self.context['request'].user
|
||||||
|
validated_data['name'] = validated_data['name'].lower()
|
||||||
|
return Category.objects.create(user_id=user, **validated_data)
|
||||||
|
|
||||||
|
def update(self, instance, validated_data):
|
||||||
|
for attr, value in validated_data.items():
|
||||||
|
setattr(instance, attr, value)
|
||||||
|
if 'name' in validated_data:
|
||||||
|
instance.name = validated_data['name'].lower()
|
||||||
|
instance.save()
|
||||||
|
return instance
|
||||||
|
|
||||||
def get_num_adventures(self, obj):
|
def get_num_adventures(self, obj):
|
||||||
return Adventure.objects.filter(category=obj, user_id=obj.user_id).count()
|
return Adventure.objects.filter(category=obj, user_id=obj.user_id).count()
|
||||||
|
@ -46,13 +56,8 @@ class VisitSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class AdventureSerializer(CustomModelSerializer):
|
class AdventureSerializer(CustomModelSerializer):
|
||||||
images = AdventureImageSerializer(many=True, read_only=True)
|
images = AdventureImageSerializer(many=True, read_only=True)
|
||||||
visits = VisitSerializer(many=True, read_only=False)
|
visits = VisitSerializer(many=True, read_only=False, required=False)
|
||||||
category = serializers.PrimaryKeyRelatedField(
|
category = CategorySerializer(read_only=False, required=False)
|
||||||
queryset=Category.objects.all(),
|
|
||||||
write_only=True,
|
|
||||||
required=False
|
|
||||||
)
|
|
||||||
category_object = CategorySerializer(source='category', read_only=True)
|
|
||||||
is_visited = serializers.SerializerMethodField()
|
is_visited = serializers.SerializerMethodField()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
@ -60,19 +65,45 @@ class AdventureSerializer(CustomModelSerializer):
|
||||||
fields = [
|
fields = [
|
||||||
'id', 'user_id', 'name', 'description', 'rating', 'activity_types', 'location',
|
'id', 'user_id', 'name', 'description', 'rating', 'activity_types', 'location',
|
||||||
'is_public', 'collection', 'created_at', 'updated_at', 'images', 'link', 'longitude',
|
'is_public', 'collection', 'created_at', 'updated_at', 'images', 'link', 'longitude',
|
||||||
'latitude', 'visits', 'is_visited', 'category', 'category_object'
|
'latitude', 'visits', 'is_visited', 'category'
|
||||||
]
|
]
|
||||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'is_visited']
|
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'is_visited']
|
||||||
|
|
||||||
def to_representation(self, instance):
|
def validate_category(self, category_data):
|
||||||
representation = super().to_representation(instance)
|
if isinstance(category_data, Category):
|
||||||
representation['category'] = representation.pop('category_object')
|
return category_data
|
||||||
return representation
|
if category_data:
|
||||||
|
user = self.context['request'].user
|
||||||
|
name = category_data.get('name', '').lower()
|
||||||
|
existing_category = Category.objects.filter(user_id=user, name=name).first()
|
||||||
|
if existing_category:
|
||||||
|
return existing_category
|
||||||
|
category_data['name'] = name
|
||||||
|
return category_data
|
||||||
|
|
||||||
def validate_category(self, category):
|
def get_or_create_category(self, category_data):
|
||||||
# Check that the category belongs to the same user
|
user = self.context['request'].user
|
||||||
if category.user_id != self.context['request'].user:
|
|
||||||
raise serializers.ValidationError('Category does not belong to the user.')
|
if isinstance(category_data, Category):
|
||||||
|
return category_data
|
||||||
|
|
||||||
|
if isinstance(category_data, dict):
|
||||||
|
name = category_data.get('name', '').lower()
|
||||||
|
display_name = category_data.get('display_name', name)
|
||||||
|
icon = category_data.get('icon', '🌎')
|
||||||
|
else:
|
||||||
|
name = category_data.name.lower()
|
||||||
|
display_name = category_data.display_name
|
||||||
|
icon = category_data.icon
|
||||||
|
|
||||||
|
category, created = Category.objects.get_or_create(
|
||||||
|
user_id=user,
|
||||||
|
name=name,
|
||||||
|
defaults={
|
||||||
|
'display_name': display_name,
|
||||||
|
'icon': icon
|
||||||
|
}
|
||||||
|
)
|
||||||
return category
|
return category
|
||||||
|
|
||||||
def get_is_visited(self, obj):
|
def get_is_visited(self, obj):
|
||||||
|
@ -86,16 +117,28 @@ class AdventureSerializer(CustomModelSerializer):
|
||||||
|
|
||||||
def create(self, validated_data):
|
def create(self, validated_data):
|
||||||
visits_data = validated_data.pop('visits', [])
|
visits_data = validated_data.pop('visits', [])
|
||||||
|
category_data = validated_data.pop('category', None)
|
||||||
adventure = Adventure.objects.create(**validated_data)
|
adventure = Adventure.objects.create(**validated_data)
|
||||||
for visit_data in visits_data:
|
for visit_data in visits_data:
|
||||||
Visit.objects.create(adventure=adventure, **visit_data)
|
Visit.objects.create(adventure=adventure, **visit_data)
|
||||||
|
|
||||||
|
if category_data:
|
||||||
|
category = self.get_or_create_category(category_data)
|
||||||
|
adventure.category = category
|
||||||
|
adventure.save()
|
||||||
|
|
||||||
return adventure
|
return adventure
|
||||||
|
|
||||||
def update(self, instance, validated_data):
|
def update(self, instance, validated_data):
|
||||||
visits_data = validated_data.pop('visits', [])
|
visits_data = validated_data.pop('visits', [])
|
||||||
|
category_data = validated_data.pop('category', None)
|
||||||
|
|
||||||
for attr, value in validated_data.items():
|
for attr, value in validated_data.items():
|
||||||
setattr(instance, attr, value)
|
setattr(instance, attr, value)
|
||||||
|
|
||||||
|
if category_data:
|
||||||
|
category = self.get_or_create_category(category_data)
|
||||||
|
instance.category = category
|
||||||
instance.save()
|
instance.save()
|
||||||
|
|
||||||
current_visits = instance.visits.all()
|
current_visits = instance.visits.all()
|
||||||
|
|
|
@ -614,24 +614,43 @@ class ActivityTypesView(viewsets.ViewSet):
|
||||||
|
|
||||||
return Response(allTypes)
|
return Response(allTypes)
|
||||||
|
|
||||||
class CategoryViewSet(viewsets.ViewSet):
|
class CategoryViewSet(viewsets.ModelViewSet):
|
||||||
|
queryset = Category.objects.all()
|
||||||
|
serializer_class = CategorySerializer
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
return Category.objects.filter(user_id=self.request.user)
|
||||||
|
|
||||||
@action(detail=False, methods=['get'])
|
@action(detail=False, methods=['get'])
|
||||||
def categories(self, request):
|
def categories(self, request):
|
||||||
"""
|
"""
|
||||||
Retrieve a list of distinct categories for adventures associated with the current user.
|
Retrieve a list of distinct categories for adventures associated with the current user.
|
||||||
|
|
||||||
Args:
|
|
||||||
request (HttpRequest): The HTTP request object.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Response: A response containing a list of distinct categories.
|
|
||||||
"""
|
"""
|
||||||
categories = Category.objects.filter(user_id=request.user.id).distinct()
|
categories = self.get_queryset().distinct()
|
||||||
serializer = CategorySerializer(categories, many=True)
|
serializer = self.get_serializer(categories, many=True)
|
||||||
return Response(serializer.data)
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
def destroy(self, request, *args, **kwargs):
|
||||||
|
instance = self.get_object()
|
||||||
|
if instance.user_id != request.user:
|
||||||
|
return Response({"error": "User does not own this category"}, status
|
||||||
|
=400)
|
||||||
|
|
||||||
|
if instance.name == 'general':
|
||||||
|
return Response({"error": "Cannot delete the general category"}, status=400)
|
||||||
|
|
||||||
|
# set any adventures with this category to a default category called general before deleting the category, if general does not exist create it for the user
|
||||||
|
general_category = Category.objects.filter(user_id=request.user, name='general').first()
|
||||||
|
|
||||||
|
if not general_category:
|
||||||
|
general_category = Category.objects.create(user_id=request.user, name='general', icon='🌎', display_name='General')
|
||||||
|
|
||||||
|
Adventure.objects.filter(category=instance).update(category=general_category)
|
||||||
|
|
||||||
|
return super().destroy(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
class TransportationViewSet(viewsets.ModelViewSet):
|
class TransportationViewSet(viewsets.ModelViewSet):
|
||||||
queryset = Transportation.objects.all()
|
queryset = Transportation.objects.all()
|
||||||
serializer_class = TransportationSerializer
|
serializer_class = TransportationSerializer
|
||||||
|
@ -1129,11 +1148,12 @@ class ReverseGeocodeViewSet(viewsets.ViewSet):
|
||||||
print(iso_code)
|
print(iso_code)
|
||||||
country_code = iso_code[:2]
|
country_code = iso_code[:2]
|
||||||
|
|
||||||
|
if region:
|
||||||
if city:
|
if city:
|
||||||
display_name = f"{city}, {region.name}, {country_code}"
|
display_name = f"{city}, {region.name}, {country_code}"
|
||||||
elif town and region.name:
|
elif town:
|
||||||
display_name = f"{town}, {region.name}, {country_code}"
|
display_name = f"{town}, {region.name}, {country_code}"
|
||||||
elif county and region.name:
|
elif county:
|
||||||
display_name = f"{county}, {region.name}, {country_code}"
|
display_name = f"{county}, {region.name}, {country_code}"
|
||||||
|
|
||||||
if visited_region:
|
if visited_region:
|
||||||
|
|
|
@ -31,6 +31,7 @@
|
||||||
import ActivityComplete from './ActivityComplete.svelte';
|
import ActivityComplete from './ActivityComplete.svelte';
|
||||||
import { appVersion } from '$lib/config';
|
import { appVersion } from '$lib/config';
|
||||||
import CategoryDropdown from './CategoryDropdown.svelte';
|
import CategoryDropdown from './CategoryDropdown.svelte';
|
||||||
|
import { findFirstValue } from '$lib';
|
||||||
|
|
||||||
let wikiError: string = '';
|
let wikiError: string = '';
|
||||||
|
|
||||||
|
@ -56,7 +57,13 @@
|
||||||
images: [],
|
images: [],
|
||||||
user_id: null,
|
user_id: null,
|
||||||
collection: collection?.id || null,
|
collection: collection?.id || null,
|
||||||
category: ''
|
category: {
|
||||||
|
id: '',
|
||||||
|
name: '',
|
||||||
|
display_name: '',
|
||||||
|
icon: '',
|
||||||
|
user_id: ''
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export let adventureToEdit: Adventure | null = null;
|
export let adventureToEdit: Adventure | null = null;
|
||||||
|
@ -78,7 +85,13 @@
|
||||||
collection: adventureToEdit?.collection || collection?.id || null,
|
collection: adventureToEdit?.collection || collection?.id || null,
|
||||||
visits: adventureToEdit?.visits || [],
|
visits: adventureToEdit?.visits || [],
|
||||||
is_visited: adventureToEdit?.is_visited || false,
|
is_visited: adventureToEdit?.is_visited || false,
|
||||||
category: adventureToEdit?.category || ''
|
category: adventureToEdit?.category || {
|
||||||
|
id: '',
|
||||||
|
name: '',
|
||||||
|
display_name: '',
|
||||||
|
icon: '',
|
||||||
|
user_id: ''
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let markers: Point[] = [];
|
let markers: Point[] = [];
|
||||||
|
@ -405,7 +418,8 @@
|
||||||
warningMessage = '';
|
warningMessage = '';
|
||||||
addToast('success', $t('adventures.adventure_created'));
|
addToast('success', $t('adventures.adventure_created'));
|
||||||
} else {
|
} else {
|
||||||
warningMessage = Object.values(data)[0] as string;
|
warningMessage = findFirstValue(data) as string;
|
||||||
|
console.error(data);
|
||||||
addToast('error', $t('adventures.adventure_create_error'));
|
addToast('error', $t('adventures.adventure_create_error'));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -450,7 +464,8 @@
|
||||||
</div>
|
</div>
|
||||||
<div class="collapse-content">
|
<div class="collapse-content">
|
||||||
<div>
|
<div>
|
||||||
<label for="name">{$t('adventures.name')}</label><br />
|
<label for="name">{$t('adventures.name')}<span class="text-red-500">*</span></label
|
||||||
|
><br />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="name"
|
id="name"
|
||||||
|
@ -461,9 +476,11 @@
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="link">{$t('adventures.category')}</label><br />
|
<label for="link"
|
||||||
|
>{$t('adventures.category')}<span class="text-red-500">*</span></label
|
||||||
|
><br />
|
||||||
|
|
||||||
<CategoryDropdown bind:categories bind:category_id={adventure.category} />
|
<CategoryDropdown bind:categories bind:selected_category={adventure.category} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="rating">{$t('adventures.rating')}</label><br />
|
<label for="rating">{$t('adventures.rating')}</label><br />
|
||||||
|
|
|
@ -4,17 +4,16 @@
|
||||||
import { t } from 'svelte-i18n';
|
import { t } from 'svelte-i18n';
|
||||||
|
|
||||||
export let categories: Category[] = [];
|
export let categories: Category[] = [];
|
||||||
let selected_category: Category | null = null;
|
export let selected_category: Category | null = null;
|
||||||
|
let new_category: Category = {
|
||||||
|
name: '',
|
||||||
|
display_name: '',
|
||||||
|
icon: '',
|
||||||
|
id: '',
|
||||||
|
user_id: '',
|
||||||
|
num_adventures: 0
|
||||||
|
};
|
||||||
|
|
||||||
export let category_id:
|
|
||||||
| {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
display_name: string;
|
|
||||||
icon: string;
|
|
||||||
user_id: string;
|
|
||||||
}
|
|
||||||
| string;
|
|
||||||
let isOpen = false;
|
let isOpen = false;
|
||||||
|
|
||||||
function toggleDropdown() {
|
function toggleDropdown() {
|
||||||
|
@ -22,25 +21,28 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectCategory(category: Category) {
|
function selectCategory(category: Category) {
|
||||||
|
console.log('category', category);
|
||||||
selected_category = category;
|
selected_category = category;
|
||||||
category_id = category.id;
|
|
||||||
isOpen = false;
|
isOpen = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeCategory(categoryName: string) {
|
function custom_category() {
|
||||||
categories = categories.filter((category) => category.name !== categoryName);
|
new_category.name = new_category.display_name.toLowerCase().replace(/ /g, '_');
|
||||||
if (selected_category && selected_category.name === categoryName) {
|
selectCategory(new_category);
|
||||||
selected_category = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// function removeCategory(categoryName: string) {
|
||||||
|
// categories = categories.filter((category) => category.name !== categoryName);
|
||||||
|
// if (selected_category && selected_category.name === categoryName) {
|
||||||
|
// selected_category = null;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
// Close dropdown when clicking outside
|
// Close dropdown when clicking outside
|
||||||
let dropdownRef: HTMLDivElement;
|
let dropdownRef: HTMLDivElement;
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
if (category_id) {
|
categories = categories.sort((a, b) => (b.num_adventures || 0) - (a.num_adventures || 0));
|
||||||
// when category_id is passed, it will be the full object not just the id that is why we can use it directly as selected_category
|
|
||||||
selected_category = category_id as Category;
|
|
||||||
}
|
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
if (dropdownRef && !dropdownRef.contains(event.target as Node)) {
|
if (dropdownRef && !dropdownRef.contains(event.target as Node)) {
|
||||||
isOpen = false;
|
isOpen = false;
|
||||||
|
@ -55,28 +57,52 @@
|
||||||
|
|
||||||
<div class="mt-2 relative" bind:this={dropdownRef}>
|
<div class="mt-2 relative" bind:this={dropdownRef}>
|
||||||
<button type="button" class="btn btn-outline w-full text-left" on:click={toggleDropdown}>
|
<button type="button" class="btn btn-outline w-full text-left" on:click={toggleDropdown}>
|
||||||
{selected_category
|
{selected_category && selected_category.name
|
||||||
? selected_category.display_name + ' ' + selected_category.icon
|
? selected_category.display_name + ' ' + selected_category.icon
|
||||||
: 'Select Category'}
|
: 'Select Category'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{#if isOpen}
|
{#if isOpen}
|
||||||
<div class="absolute z-10 w-full mt-1 bg-base-300 rounded shadow-lg p-2 flex flex-wrap gap-2">
|
<div class="absolute z-10 w-full mt-1 bg-base-300 rounded shadow-lg p-2">
|
||||||
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
|
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Category Name"
|
||||||
|
class="input input-bordered w-full max-w-xs"
|
||||||
|
bind:value={new_category.display_name}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Icon"
|
||||||
|
class="input input-bordered w-full max-w-xs"
|
||||||
|
bind:value={new_category.icon}
|
||||||
|
/>
|
||||||
|
<button on:click={custom_category} type="button" class="btn btn-primary"
|
||||||
|
>{$t('adventures.add')}</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-2 mt-2">
|
||||||
|
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||||
{#each categories as category}
|
{#each categories as category}
|
||||||
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
|
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||||
<div
|
<div
|
||||||
class="btn btn-neutral flex items-center space-x-2"
|
class="btn btn-neutral flex items-center space-x-2"
|
||||||
on:click={() => selectCategory(category)}
|
on:click={() => selectCategory(category)}
|
||||||
>
|
>
|
||||||
<span>{category.display_name} {category.icon}</span>
|
<span>{category.display_name} {category.icon} ({category.num_adventures})</span>
|
||||||
<button
|
<!-- <button
|
||||||
type="button"
|
type="button"
|
||||||
class="btn btn-xs btn-error"
|
class="btn btn-xs btn-error"
|
||||||
on:click|stopPropagation={() => removeCategory(category.name)}
|
on:click|stopPropagation={() => removeCategory(category.name)}
|
||||||
>
|
>
|
||||||
{$t('adventures.remove')}
|
{$t('adventures.remove')}
|
||||||
</button>
|
</button> -->
|
||||||
</div>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
107
frontend/src/lib/components/CategoryModal.svelte
Normal file
107
frontend/src/lib/components/CategoryModal.svelte
Normal file
|
@ -0,0 +1,107 @@
|
||||||
|
<script lang="ts">
|
||||||
|
import type { Category } from '$lib/types';
|
||||||
|
import { createEventDispatcher } from 'svelte';
|
||||||
|
const dispatch = createEventDispatcher();
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
let modal: HTMLDialogElement;
|
||||||
|
import { t } from 'svelte-i18n';
|
||||||
|
|
||||||
|
export let categories: Category[] = [];
|
||||||
|
|
||||||
|
let category_to_edit: Category | null = null;
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
|
||||||
|
if (modal) {
|
||||||
|
modal.showModal();
|
||||||
|
}
|
||||||
|
let category_fetch = await fetch('/api/categories/categories');
|
||||||
|
categories = await category_fetch.json();
|
||||||
|
// remove the general category if it exists
|
||||||
|
categories = categories.filter((c) => c.name !== 'general');
|
||||||
|
});
|
||||||
|
|
||||||
|
async function saveCategory() {
|
||||||
|
if (category_to_edit) {
|
||||||
|
let edit_fetch = await fetch(`/api/categories/${category_to_edit.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(category_to_edit)
|
||||||
|
});
|
||||||
|
if (edit_fetch.ok) {
|
||||||
|
category_to_edit = null;
|
||||||
|
let the_category = (await edit_fetch.json()) as Category;
|
||||||
|
categories = categories.map((c) => {
|
||||||
|
if (c.id === the_category.id) {
|
||||||
|
return the_category;
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
dispatch('close');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeydown(event: KeyboardEvent) {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
dispatch('close');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeCategory(category: Category) {
|
||||||
|
return async () => {
|
||||||
|
let response = await fetch(`/api/categories/${category.id}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
if (response.ok) {
|
||||||
|
categories = categories.filter((c) => c.id !== category.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog id="my_modal_1" class="modal">
|
||||||
|
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
|
||||||
|
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
|
||||||
|
<div class="modal-box" role="dialog" on:keydown={handleKeydown} tabindex="0">
|
||||||
|
<h3 class="font-bold text-lg">Manage Categories</h3>
|
||||||
|
|
||||||
|
{#each categories as category}
|
||||||
|
<div class="flex justify-between items-center mt-2">
|
||||||
|
<span>{category.display_name} {category.icon}</span>
|
||||||
|
<div class="flex space-x-2">
|
||||||
|
<button on:click={() => (category_to_edit = category)} class="btn btn-primary btn-sm"
|
||||||
|
>Edit</button
|
||||||
|
>
|
||||||
|
<button on:click={removeCategory(category)} class="btn btn-warning btn-sm">Remove</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if categories.length === 0}
|
||||||
|
<p>No categories found.</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if category_to_edit}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Name"
|
||||||
|
bind:value={category_to_edit.display_name}
|
||||||
|
class="input input-bordered w-full max-w-xs"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Icon"
|
||||||
|
bind:value={category_to_edit.icon}
|
||||||
|
class="input input-bordered w-full max-w-xs"
|
||||||
|
/>
|
||||||
|
<button class="btn btn-primary" on:click={saveCategory}>Save</button>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<button class="btn btn-primary mt-4" on:click={close}>{$t('about.close')}</button>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
|
@ -6,6 +6,7 @@
|
||||||
import FileDocumentEdit from '~icons/mdi/file-document-edit';
|
import FileDocumentEdit from '~icons/mdi/file-document-edit';
|
||||||
import ArchiveArrowDown from '~icons/mdi/archive-arrow-down';
|
import ArchiveArrowDown from '~icons/mdi/archive-arrow-down';
|
||||||
import ArchiveArrowUp from '~icons/mdi/archive-arrow-up';
|
import ArchiveArrowUp from '~icons/mdi/archive-arrow-up';
|
||||||
|
import ShareVariant from '~icons/mdi/share-variant';
|
||||||
|
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import type { Adventure, Collection } from '$lib/types';
|
import type { Adventure, Collection } from '$lib/types';
|
||||||
|
@ -149,7 +150,7 @@
|
||||||
<FileDocumentEdit class="w-6 h-6" />{$t('adventures.edit_collection')}
|
<FileDocumentEdit class="w-6 h-6" />{$t('adventures.edit_collection')}
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-neutral mb-2" on:click={() => (isShareModalOpen = true)}>
|
<button class="btn btn-neutral mb-2" on:click={() => (isShareModalOpen = true)}>
|
||||||
<FileDocumentEdit class="w-6 h-6" />{$t('adventures.share')}
|
<ShareVariant class="w-6 h-6" />{$t('adventures.share')}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if collection.is_archived}
|
{#if collection.is_archived}
|
||||||
|
|
|
@ -219,8 +219,7 @@
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
class="btn btn-sm mt-2"
|
class="btn btn-sm mt-2"
|
||||||
on:click={() => (window.location.href = 'https://discord.gg/wRbQ9Egr8C')}
|
on:click={() => (window.location.href = 'https://discord.gg/wRbQ9Egr8C')}>Discord</button
|
||||||
>{$t('navbar.discord')}</button
|
|
||||||
>
|
>
|
||||||
<p class="font-bold m-4 text-lg text-center">{$t('navbar.theme_selection')}</p>
|
<p class="font-bold m-4 text-lg text-center">{$t('navbar.theme_selection')}</p>
|
||||||
<form method="POST" use:enhance={submitUpdateTheme}>
|
<form method="POST" use:enhance={submitUpdateTheme}>
|
||||||
|
|
|
@ -292,3 +292,16 @@ export function getRandomBackground() {
|
||||||
const randomIndex = Math.floor(Math.random() * randomBackgrounds.backgrounds.length);
|
const randomIndex = Math.floor(Math.random() * randomBackgrounds.backgrounds.length);
|
||||||
return randomBackgrounds.backgrounds[randomIndex] as Background;
|
return randomBackgrounds.backgrounds[randomIndex] as Background;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function findFirstValue(obj: any): any {
|
||||||
|
for (const key in obj) {
|
||||||
|
if (typeof obj[key] === 'object' && obj[key] !== null) {
|
||||||
|
const value = findFirstValue(obj[key]);
|
||||||
|
if (value !== undefined) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return obj[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -38,15 +38,7 @@ export type Adventure = {
|
||||||
created_at?: string | null;
|
created_at?: string | null;
|
||||||
updated_at?: string | null;
|
updated_at?: string | null;
|
||||||
is_visited?: boolean;
|
is_visited?: boolean;
|
||||||
category:
|
category: Category | null;
|
||||||
| {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
display_name: string;
|
|
||||||
icon: string;
|
|
||||||
user_id: string;
|
|
||||||
}
|
|
||||||
| string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Country = {
|
export type Country = {
|
||||||
|
@ -196,5 +188,5 @@ export type Category = {
|
||||||
display_name: string;
|
display_name: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
user_id: string;
|
user_id: string;
|
||||||
num_adventures: number;
|
num_adventures?: number | null;
|
||||||
};
|
};
|
||||||
|
|
|
@ -5,6 +5,7 @@
|
||||||
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
||||||
import AdventureModal from '$lib/components/AdventureModal.svelte';
|
import AdventureModal from '$lib/components/AdventureModal.svelte';
|
||||||
import CategoryFilterDropdown from '$lib/components/CategoryFilterDropdown.svelte';
|
import CategoryFilterDropdown from '$lib/components/CategoryFilterDropdown.svelte';
|
||||||
|
import CategoryModal from '$lib/components/CategoryModal.svelte';
|
||||||
import NotFound from '$lib/components/NotFound.svelte';
|
import NotFound from '$lib/components/NotFound.svelte';
|
||||||
import type { Adventure, Category } from '$lib/types';
|
import type { Adventure, Category } from '$lib/types';
|
||||||
import { t } from 'svelte-i18n';
|
import { t } from 'svelte-i18n';
|
||||||
|
@ -32,6 +33,8 @@
|
||||||
let totalPages = Math.ceil(count / resultsPerPage);
|
let totalPages = Math.ceil(count / resultsPerPage);
|
||||||
let currentPage: number = 1;
|
let currentPage: number = 1;
|
||||||
|
|
||||||
|
let is_category_modal_open: boolean = false;
|
||||||
|
|
||||||
let typeString: string = '';
|
let typeString: string = '';
|
||||||
|
|
||||||
$: {
|
$: {
|
||||||
|
@ -167,6 +170,10 @@
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if is_category_modal_open}
|
||||||
|
<CategoryModal on:close={() => (is_category_modal_open = false)} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
<div class="fixed bottom-4 right-4 z-[999]">
|
<div class="fixed bottom-4 right-4 z-[999]">
|
||||||
<div class="flex flex-row items-center justify-center gap-4">
|
<div class="flex flex-row items-center justify-center gap-4">
|
||||||
<div class="dropdown dropdown-top dropdown-end">
|
<div class="dropdown dropdown-top dropdown-end">
|
||||||
|
@ -253,6 +260,10 @@
|
||||||
<!-- <h3 class="text-center font-bold text-lg mb-4">Adventure Types</h3> -->
|
<!-- <h3 class="text-center font-bold text-lg mb-4">Adventure Types</h3> -->
|
||||||
<form method="get">
|
<form method="get">
|
||||||
<CategoryFilterDropdown bind:types={typeString} />
|
<CategoryFilterDropdown bind:types={typeString} />
|
||||||
|
<button
|
||||||
|
on:click={() => (is_category_modal_open = true)}
|
||||||
|
class="btn btn-neutral btn-sm min-w-full">Manage Categories</button
|
||||||
|
>
|
||||||
<div class="divider"></div>
|
<div class="divider"></div>
|
||||||
<h3 class="text-center font-bold text-lg mb-4">{$t('adventures.sort')}</h3>
|
<h3 class="text-center font-bold text-lg mb-4">{$t('adventures.sort')}</h3>
|
||||||
<p class="text-lg font-semibold mb-2">{$t('adventures.order_direction')}</p>
|
<p class="text-lg font-semibold mb-2">{$t('adventures.order_direction')}</p>
|
||||||
|
|
|
@ -265,7 +265,9 @@
|
||||||
<div>
|
<div>
|
||||||
<p class="text-sm text-muted-foreground">{$t('adventures.adventure_type')}</p>
|
<p class="text-sm text-muted-foreground">{$t('adventures.adventure_type')}</p>
|
||||||
<p class="text-base font-medium">
|
<p class="text-base font-medium">
|
||||||
{`${adventure.category.display_name} ${adventure.category.icon}`}
|
{typeof adventure.category === 'object'
|
||||||
|
? `${adventure.category.display_name} ${adventure.category.icon}`
|
||||||
|
: ''}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{#if data.props.collection}
|
{#if data.props.collection}
|
||||||
|
@ -337,8 +339,8 @@
|
||||||
<Popup openOn="click" offset={[0, -10]}>
|
<Popup openOn="click" offset={[0, -10]}>
|
||||||
<div class="text-lg text-black font-bold">{adventure.name}</div>
|
<div class="text-lg text-black font-bold">{adventure.name}</div>
|
||||||
<p class="font-semibold text-black text-md">
|
<p class="font-semibold text-black text-md">
|
||||||
{adventure.category.display_name}
|
{typeof adventure.category === 'object' && adventure.category.display_name}
|
||||||
{adventure.category.icon}
|
{typeof adventure.category === 'object' && adventure.category.icon}
|
||||||
</p>
|
</p>
|
||||||
{#if adventure.visits.length > 0}
|
{#if adventure.visits.length > 0}
|
||||||
<p class="text-black text-sm">
|
<p class="text-black text-sm">
|
||||||
|
|
|
@ -126,7 +126,7 @@
|
||||||
on:click={togglePopup}
|
on:click={togglePopup}
|
||||||
>
|
>
|
||||||
<span class="text-xl">
|
<span class="text-xl">
|
||||||
{getAdventureTypeLabel(adventure.type)}
|
{typeof adventure.category === 'object' ? adventure.category.icon : adventure.category}
|
||||||
</span>
|
</span>
|
||||||
{#if isPopupOpen}
|
{#if isPopupOpen}
|
||||||
<Popup openOn="click" offset={[0, -10]} on:close={() => (isPopupOpen = false)}>
|
<Popup openOn="click" offset={[0, -10]} on:close={() => (isPopupOpen = false)}>
|
||||||
|
@ -138,7 +138,7 @@
|
||||||
{adventure.is_visited ? $t('adventures.visited') : $t('adventures.planned')}
|
{adventure.is_visited ? $t('adventures.visited') : $t('adventures.planned')}
|
||||||
</p>
|
</p>
|
||||||
<p class="font-semibold text-black text-md">
|
<p class="font-semibold text-black text-md">
|
||||||
{$t(`adventures.activities.${adventure.type}`)}
|
{adventure.category.display_name + ' ' + adventure.category.icon}
|
||||||
</p>
|
</p>
|
||||||
{#if adventure.visits && adventure.visits.length > 0}
|
{#if adventure.visits && adventure.visits.length > 0}
|
||||||
<p class="text-black text-sm">
|
<p class="text-black text-sm">
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue