Activities, Trails, Wanderer + Strava Integration, UI Refresh, Devops Improvments, and more (#785)

* Implement code changes to enhance functionality and improve performance

* Update nl.json

Fix Dutch translations.

* feat(security): add Trivy security scans for Docker images and source code

* feat(security): restructure Trivy scans for improved clarity and organization

* fix(dependencies): update Django version to 5.2.2

* style(workflows): standardize quotes and fix typo in frontend-test.yml

* feat(workflows): add job names for clarity in backend and frontend test workflows

* refactor(workflows): remove path filters from pull_request and push triggers in backend and frontend workflows

* feat(workflows): add paths to push and pull_request triggers for backend and frontend workflows

* refactor(workflows): simplify trigger paths for backend and frontend workflows
fix(dependencies): add overrides for esbuild in frontend package.json

* fix(package): add missing pnpm overrides for esbuild in package.json

* fix(workflows): add missing severity parameter for Trivy filesystem scan

* fix(workflows): add missing severity parameter for Docker image scans in Trivy workflow

* fix(workflows): remove MEDIUM severity from Trivy scans in security workflow

* added-fix-image-deletion (#681)

* added-fix-image-deletion

* feat(commands): add image cleanup command to find and delete unused files

* fix(models): ensure associated AdventureImages are deleted and files cleaned up on Adventure deletion

* fix(models): ensure associated Attachment files are deleted and their filesystem cleaned up on Adventure deletion

---------

Co-authored-by: ferdousahmed <taninme@gmail.com>
Co-authored-by: Sean Morley

* Rename Adventures to Locations (#696)

* Refactor user_id to user in adventures and related models, views, and components

- Updated all instances of user_id to user in the adventures app, including models, serializers, views, and frontend components.
- Adjusted queries and filters to reflect the new user field naming convention.
- Ensured consistency across the codebase for user identification in adventures, collections, notes, and transportation entities.
- Modified frontend components to align with the updated data structure, ensuring proper access control and rendering based on user ownership.

* Refactor adventure-related views and components to use "Location" terminology

- Updated GlobalSearchView to replace AdventureSerializer with LocationSerializer.
- Modified IcsCalendarGeneratorViewSet to use LocationSerializer instead of AdventureSerializer.
- Created new LocationImageViewSet for managing location images, including primary image toggling and image deletion.
- Introduced LocationViewSet for managing locations with enhanced filtering, sorting, and sharing capabilities.
- Updated ReverseGeocodeViewSet to utilize LocationSerializer.
- Added ActivityTypesView to retrieve distinct activity types from locations.
- Refactored user views to replace AdventureSerializer with LocationSerializer.
- Updated frontend components to reflect changes from "adventure" to "location", including AdventureCard, AdventureLink, AdventureModal, and others.
- Adjusted API endpoints in frontend routes to align with new location-based structure.
- Ensured all references to adventures are replaced with locations across the codebase.

* refactor: rename adventures to locations across the application

- Updated localization files to replace adventure-related terms with location-related terms.
- Refactored TypeScript types and variables from Adventure to Location in various routes and components.
- Adjusted UI elements and labels to reflect the change from adventures to locations.
- Ensured all references to adventures in the codebase are consistent with the new location terminology.

* Refactor code structure for improved readability and maintainability

* feat: Implement location details page with server-side loading and deletion functionality

- Added +page.server.ts to handle server-side loading of additional location info.
- Created +page.svelte for displaying location details, including images, visits, and maps.
- Integrated GPX file handling and rendering on the map.
- Updated map route to link to locations instead of adventures.
- Refactored profile and search routes to use LocationCard instead of AdventureCard.

* docs: Update terminology from "Adventure" to "Location" and enhance project overview

* docs: Clarify collection examples in usage documentation

* feat: Enable credentials for GPX file fetch and add CORS_ALLOW_CREDENTIALS setting

* Refactor adventure references to locations across the backend and frontend

- Updated CategoryViewSet to reflect location context instead of adventures.
- Modified ChecklistViewSet to include locations in retrieval logic.
- Changed GlobalSearchView to search for locations instead of adventures.
- Adjusted IcsCalendarGeneratorViewSet to handle locations instead of adventures.
- Refactored LocationImageViewSet to remove unused import.
- Updated LocationViewSet to clarify public access for locations.
- Changed LodgingViewSet to reference locations instead of adventures.
- Modified NoteViewSet to prevent listing all locations.
- Updated RecommendationsViewSet to handle locations in parsing and response.
- Adjusted ReverseGeocodeViewSet to search through user locations.
- Updated StatsViewSet to count locations instead of adventures.
- Changed TagsView to reflect activity types for locations.
- Updated TransportationViewSet to reference locations instead of adventures.
- Added new translations for search results related to locations in multiple languages.
- Updated dashboard and profile pages to reflect location counts instead of adventure counts.
- Adjusted search routes to handle locations instead of adventures.

* Update banner image

* style: Update stats component background and border for improved visibility

* refactor: Rename AdventureCard and AdventureModal to LocationCard and LocationModal for consistency

* Import and Export Functionality (#698)

* feat(backup): add BackupViewSet for data export and import functionality

* Fixed frontend returning corrupt binary data

* feat(import): enhance import functionality with confirmation check and improved city/region/country handling

* Potential fix for code scanning alert no. 29: Information exposure through an exception

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* Refactor response handling to use arrayBuffer instead of bytes

* Refactor image cleanup command to use LocationImage model and update import/export view to include backup and restore functionality

* Update backup export versioning and improve data restore warning message

* Enhance image navigation and localization support in modal components

* Refactor location handling in Immich integration components for consistency

* Enhance backup and restore functionality with improved localization and error handling

* Improve accessibility by adding 'for' attribute to backup file input label

---------

Co-authored-by: Christian Zäske <blitzdose@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* refactor(serializers): rename Location to Adventure and update related fields

* refactor(serializers): rename Adventure to Location and update related fields

* chore(requirements): update pillow version to 11.3.0

* Add PT-BR translations (#739)

* Fixed frontend returning corrupt binary data

* fix(adventure): enhance collection ownership validation in AdventureSerializer (#723)

* Add PT-BR translations

Add translation for Brazilian Portuguese to the project;

Signed-off-by: Lucas Zampieri <lzampier@redhat.com>

---------

Signed-off-by: Lucas Zampieri <lzampier@redhat.com>
Co-authored-by: Sean Morley <98704938+seanmorley15@users.noreply.github.com>
Co-authored-by: Christian Zäske <blitzdose@gmail.com>

* fix: update date formatting for adventure items to include timezone

* Image/attachment overhaul, activities, trails and integrations with Strava and Wanderer (#726)

* refactor(models, views, serializers): rename LocationImage and Attachment to ContentImage and ContentAttachment, update related references

* feat: Enhance collection sharing and location management features

- Implemented unsharing functionality in CollectionViewSet, including removal of user-owned locations from collections.
- Refactored ContentImageViewSet to support multiple content types and improved permission checks for image uploads.
- Added user ownership checks in LocationViewSet for delete operations.
- Enhanced collection management in the frontend to display both owned and shared collections separately.
- Updated Immich integration to handle access control based on location visibility and user permissions.
- Improved UI components to show creator information and manage collection links more effectively.
- Added loading states and error handling in collection fetching logic.

* feat: enhance transportation card and modal with image handling

- Added CardCarousel component to TransportationCard for image display.
- Implemented privacy indicator with Eye and EyeOff icons.
- Introduced image upload functionality in TransportationModal, allowing users to upload multiple images.
- Added image management features: remove image and set primary image.
- Updated Transportation and Location types to include images as ContentImage array.
- Enhanced UI for image upload and display in modal, including selected images preview and current images management.

* feat: update CardCarousel component to handle images, name, and icon props across various cards

* feat: add Discord link to AboutModal and update appVersion in config

* feat: add LocationQuickStart and LocationVisits components for enhanced location selection and visit management

- Implemented LocationQuickStart.svelte for searching and selecting locations on a map with reverse geocoding.
- Created LocationVisits.svelte to manage visit dates and notes for locations, including timezone handling and validation.
- Updated types to remove location property from Attachment type.
- Modified locations page to integrate NewLocationModal for creating and editing locations, syncing updates with adventures.

* feat: update button styles and add back and close functionality in location components

* Collection invite system

* feat: update CollectionSerializer to include 'shared_with' as a read-only field; update app version; add new background images and localization strings for invites

* feat: add Strava integration with OAuth flow and activity management

- Implemented IntegrationView for listing integrations including Immich, Google Maps, and Strava.
- Created StravaIntegrationView for handling OAuth authorization and token exchange.
- Added functionality to refresh Strava access tokens when needed.
- Implemented endpoints to fetch user activities from Strava and extract essential information.
- Added Strava logo asset and integrated it into the frontend settings page.
- Updated settings page to display Strava integration status.
- Enhanced location management to include trails with create, edit, and delete functionalities.
- Updated types and localization files to support new features.

* feat: enhance Strava integration with user-specific settings and management options; update localization strings

* feat: update Strava integration settings and add Wanderer logo; enhance user experience with active section management

* Add StravaActivity and Activity types to types.ts

- Introduced StravaActivity type to represent detailed activity data from Strava.
- Added Activity type to encapsulate user activities, including optional trail and GPX file information.
- Updated Location type to include an array of activities associated with each visit.

* feat: streamline location and activity management; enhance Strava import functionality and add activity handling in server actions

* feat: add ActivityCard component and update LocationVisits to use it; modify Activity type to reference trail as string

* feat: add geojson support to ActivitySerializer and ActivityCard; enhance location page with activity summaries and GPS tracks

* feat: add trails property to recommendation object in collection page

* feat: add Wanderer integration with authentication and management features

* feat: implement Wanderer integration with trail management and UI components; enhance settings for reauthentication

* feat: add measurement system field to CustomUser model and update related serializers, migrations, and UI components

* feat: add measurement system support across ActivityCard, StravaActivityCard, NewLocationModal, LocationVisits, and related utility functions

* feat: enhance Wanderer integration with trail data fetching and UI updates; add measurement system support

* feat: add TrailCard component for displaying trail details with measurement system support

* feat: add wanderer link support in TrailSerializer and TrailCard; update measurement system handling in location page

* feat: integrate memcached for caching in Wanderer services; update Docker, settings, and supervisord configurations

* feat: add activity statistics to user profile; include distance, moving time, elevation, and total activities

* feat: enhance import/export functionality to include trails and activities; update UI components and localization

* feat: integrate NewLocationModal across various components; update location handling and state management

* Refactor Location and Visit types: Replace visits structure in Location with Visit type and add location, created_at, and updated_at fields to Visit

* feat: enhance permissions and validation in activity, trail, and visit views; add unique constraint to CollectionInvite model

* feat: sync visits when updating adventures in collection page

* feat: add geojson support for attachments and refactor GPX handling in location page

* chore: remove unused dependencies from pnpm-lock.yaml

* feat: add Strava and Wanderer integration documentation and configuration options

* Add support for Japanese and Arabic languages in localization

* Add new localization strings for Russian, Swedish, and Chinese languages

- Updated translations in ru.json, sv.json, and zh.json to include new phrases related to collections, activities, and integrations.
- Added strings for leaving collections, loading collections, and quick start instructions.
- Included new sections for invites and Strava integration with relevant messages.
- Enhanced Google Maps integration descriptions for clarity.

* Add localization support for activity-related features and update UI labels

- Added new Russian, Swedish, and Chinese translations for activity statistics, achievements, and related terms.
- Updated UI components to use localized strings for activity statistics, distance, moving time, and other relevant fields.
- Enhanced user experience by ensuring all relevant buttons and labels are translated and accessible.

* fix: update appVersion to reflect the latest development version

* feat: add getActivityColor function and integrate activity color coding in map and location pages

* feat: add support for showing activities and visited cities on the map

* feat: update map page to display counts for visited cities and activities

* fix: remove debug print statement from IsOwnerOrSharedWithFullAccess permission class

* feat: add MapStyleSelector component and integrate basemap selection in map page

* feat: enhance basemap functions with 3D terrain support and update XYZ style handling

* feat: add management command to recalculate elevation data from GPX files and update activity view to handle elevation data extraction

* feat: update MapStyleSelector component and enhance basemap options for improved user experience

* feat: refactor activity model and admin to use sport_type, update serializers and components for improved activity handling

* feat: update Activity model string representation to use sport_type instead of type

* feat: update activity handling to use sport_type for color determination in map and location components

* feat: Add attachments support to Transportation and Lodging types

- Updated Transportation and Lodging types to include attachments array.
- Enhanced localization files for multiple languages to include new strings related to attachments, lodging, and transportation.
- Added error and success messages for attachment removal and upload information.
- Included new prompts for creating and updating lodging and transportation details across various languages.

* feat: Enhance activity statistics and breakdown by category in user profile

* feat: Add SPORT_CATEGORIES for better organization of sports types and update StatsViewSet to use it

* feat: Enhance CategoryDropdown for mobile responsiveness and add category creation functionality

* feat: Update inspirational quote in adventure log

* feat: Localize navigation labels in Navbar and add translation to en.json

* feat: Update navigation elements to use anchor tags for better accessibility and add new fields to signup form

* Translate login button text to support internationalization

* feat: Refactor location visit status logic and add utility function for visited locations count

* chore: Upgrade GitHub Actions and remove unused timezone import

* fix: Update Docker image tags in GitHub Actions workflow for consistency

* fix: Update Docker image build process to use BuildKit cache for improved performance

* chore: Remove unused imports from stats_view.py for cleaner code

* Increase background image opacity on login and signup pages for improved visibility

* fix: Add postgresql-client to runtime dependencies in Dockerfile

* fix: Update workflow files to include permissions for GitHub Actions

* fix: Update esbuild version to ^0.25.9 in package.json and pnpm-lock.yaml for compatibility

* chore: improve Chinese translation (#796)

* fix: update adventure log quote and remove unused activity type field

* fix: optimize import process by using get_or_create for visited cities and regions

* fix: update README to reflect changes from adventures to locations and enhance feature descriptions

* fix: update documentation to reflect changes from adventures to locations and enhance feature descriptions

* Update google_maps_integration.md (#743)

* Update google_maps_integration.md

Explain APIs needed for AdventureLogs versions.

Fixes #731 and #727

* Fix a typo google_maps_integration.md

---------

Co-authored-by: Sean Morley <98704938+seanmorley15@users.noreply.github.com>

* fix: update appVersion to reflect the main branch version

* fix: update image source for satellite map in documentation

* Update frontend/src/lib/components/NewLocationModal.svelte

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Add localization updates for multiple languages

- Japanese (ja.json): Added new activity-related phrases and checklist terms.
- Korean (ko.json): Included activity breakdown and checklist enhancements.
- Dutch (nl.json): Updated activity descriptions and added checklist functionalities.
- Norwegian (no.json): Enhanced activity and checklist terminology.
- Polish (pl.json): Added new phrases for activities and checklist management.
- Brazilian Portuguese (pt-br.json): Updated activity-related terms and checklist features.
- Russian (ru.json): Included new phrases for activities and checklist management.
- Swedish (sv.json): Enhanced activity descriptions and checklist functionalities.
- Chinese (zh.json): Added new activity-related phrases and checklist terms.

* fix: enhance image upload handling to support immich_id

* Add "not_enabled" message for Strava integration in multiple languages

- Updated Spanish, French, Italian, Japanese, Korean, Dutch, Norwegian, Polish, Brazilian Portuguese, Russian, Swedish, and Chinese locale files to include a new message indicating that Strava integration is not enabled in the current instance.

---------

Signed-off-by: Lucas Zampieri <lzampier@redhat.com>
Co-authored-by: Ycer0n <37674033+Ycer0n@users.noreply.github.com>
Co-authored-by: taninme <5262715+taninme@users.noreply.github.com>
Co-authored-by: ferdousahmed <taninme@gmail.com>
Co-authored-by: Christian Zäske <blitzdose@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
Co-authored-by: Lucas Zampieri <lcasmz54@gmail.com>
Co-authored-by: pplulee <pplulee@live.cn>
Co-authored-by: Cathelijne Hornstra <github@hornstra.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Sean Morley
2025-08-19 08:50:45 -04:00
committed by GitHub
parent 4e96e529f4
commit a3f0eda63f
220 changed files with 27763 additions and 6653 deletions

View File

@@ -17,8 +17,27 @@
register('ko', () => import('../locales/ko.json'));
register('no', () => import('../locales/no.json'));
register('ru', () => import('../locales/ru.json'));
register('ja', () => import('../locales/ja.json'));
register('ar', () => import('../locales/ar.json'));
register('pt-br', () => import('../locales/pt-br.json'));
let locales = ['en', 'es', 'fr', 'de', 'it', 'zh', 'nl', 'sv', 'pl', 'ko', 'no', 'ru'];
let locales = [
'en',
'es',
'fr',
'de',
'it',
'zh',
'nl',
'sv',
'pl',
'ko',
'no',
'ru',
'ja',
'ar',
'pt-br'
];
if (browser) {
init({

View File

@@ -102,7 +102,7 @@
<div class="flex flex-col sm:flex-row gap-4 pt-4">
{#if data.user}
<button
on:click={() => goto('/adventures')}
on:click={() => goto('/locations')}
class="btn btn-primary btn-lg gap-3 shadow-lg hover:shadow-xl transition-all duration-300 group"
>
<PlayIcon class="w-5 h-5 group-hover:scale-110 transition-transform" />

View File

@@ -8,7 +8,7 @@ export const POST: RequestHandler = async (event) => {
let allActivities: string[] = [];
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await event.fetch(`${endpoint}/api/activity-types/types/`, {
let res = await event.fetch(`${endpoint}/api/tags/types/`, {
headers: {
'X-CSRFToken': csrfToken,
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`

View File

@@ -1,99 +1,5 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure } from '$lib/types';
import type { Actions } from '@sveltejs/kit';
import { fetchCSRFToken } from '$lib/index.server';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
if (!event.locals.user) {
return redirect(302, '/login');
} else {
let count = 0;
let adventures: Adventure[] = [];
let typeString = event.url.searchParams.get('types');
// If no type is specified, default to 'all'
if (!typeString) {
typeString = 'all';
}
const include_collections = event.url.searchParams.get('include_collections') || 'false';
const order_by = event.url.searchParams.get('order_by') || 'updated_at';
const order_direction = event.url.searchParams.get('order_direction') || 'asc';
const page = event.url.searchParams.get('page') || '1';
const is_visited = event.url.searchParams.get('is_visited') || 'all';
let initialFetch = await event.fetch(
`${serverEndpoint}/api/adventures/filtered?types=${typeString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}&page=${page}&is_visited=${is_visited}`,
{
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include'
}
);
if (!initialFetch.ok) {
let error_message = await initialFetch.json();
console.error(error_message);
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let res = await initialFetch.json();
let visited = res.results as Adventure[];
count = res.count;
adventures = [...adventures, ...visited];
}
return {
props: {
adventures,
count
}
};
}
}) satisfies PageServerLoad;
export const actions: Actions = {
image: async (event) => {
let formData = await event.request.formData();
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/images/`, {
method: 'POST',
headers: {
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`,
'X-CSRFToken': csrfToken,
Referer: event.url.origin // Include Referer header
},
body: formData
});
let data = await res.json();
return data;
},
attachment: async (event) => {
let formData = await event.request.formData();
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/attachments/`, {
method: 'POST',
headers: {
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`,
'X-CSRFToken': csrfToken,
Referer: event.url.origin // Include Referer header
},
body: formData
});
let data = await res.json();
console.log(res);
console.log(data);
return data;
}
};
export const load = (async (_event) => {
return redirect(301, '/locations');
}) satisfies import('./$types').PageServerLoad;

View File

@@ -1,76 +1,7 @@
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { AdditionalAdventure, Adventure, Collection } from '$lib/types';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
import { redirect } from '@sveltejs/kit';
export const load = (async (event) => {
const id = event.params as { id: string };
let request = await fetch(`${endpoint}/api/adventures/${id.id}/additional-info/`, {
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include'
});
if (!request.ok) {
console.error('Failed to fetch adventure ' + id.id);
return {
props: {
adventure: null
}
};
} else {
let adventure = (await request.json()) as AdditionalAdventure;
return {
props: {
adventure
}
};
}
return redirect(301, `/locations/${id.id}`);
}) satisfies PageServerLoad;
import { redirect, type Actions } from '@sveltejs/kit';
import { fetchCSRFToken } from '$lib/index.server';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const actions: Actions = {
delete: async (event) => {
const id = event.params as { id: string };
const adventureId = id.id;
if (!event.locals.user) {
return redirect(302, '/login');
}
if (!adventureId) {
return {
status: 400,
error: new Error('Bad request')
};
}
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${serverEndpoint}/api/adventures/${event.params.id}`, {
method: 'DELETE',
headers: {
Referer: event.url.origin, // Include Referer header
Cookie: `sessionid=${event.cookies.get('sessionid')};
csrftoken=${csrfToken}`,
'X-CSRFToken': csrfToken
},
credentials: 'include'
});
console.log(res);
if (!res.ok) {
return {
status: res.status,
error: new Error('Failed to delete adventure')
};
} else {
return {
status: 204
};
}
}
};

View File

@@ -85,7 +85,7 @@ async function handleRequest(
});
}
const responseData = await response.bytes();
const responseData = await response.arrayBuffer();
// Create a new Headers object without the 'set-cookie' header
const cleanHeaders = new Headers(response.headers);
cleanHeaders.delete('set-cookie');

View File

@@ -1,4 +1,4 @@
import type { Adventure } from '$lib/types';
import type { Location } from '$lib/types';
import type { PageServerLoad } from './$types';
import { formatDateInTimezone, formatAllDayDate } from '$lib/dateUtils';
import { isAllDay } from '$lib';
@@ -8,12 +8,12 @@ const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
let sessionId = event.cookies.get('sessionid');
let visitedFetch = await fetch(`${endpoint}/api/adventures/all/?include_collections=true`, {
let visitedFetch = await fetch(`${endpoint}/api/locations/all/?include_collections=true`, {
headers: {
Cookie: `sessionid=${sessionId}`
}
});
let adventures = (await visitedFetch.json()) as Adventure[];
let adventures = (await visitedFetch.json()) as Location[];
// Get user's local timezone as fallback
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

View File

@@ -26,7 +26,7 @@
return marked(markdown);
};
let adventures = data.props.adventures;
let locations = data.props.adventures;
let allDates = data.props.dates;
let filteredDates = [...allDates];
@@ -174,7 +174,7 @@
</script>
<svelte:head>
<title>{$t('adventures.adventure_calendar')} - AdventureLog</title>
<title>{$t('adventures.visit_calendar')} - AdventureLog</title>
</svelte:head>
<div class="min-h-screen bg-gradient-to-br from-base-200 via-base-100 to-base-200">
@@ -196,7 +196,7 @@
</div>
<div>
<h1 class="text-3xl font-bold text-primary bg-clip-text">
{$t('adventures.adventure_calendar')}
{$t('adventures.visit_calendar')}
</h1>
<p class="text-sm text-base-content/60">
{filteredDates.length}
@@ -214,8 +214,8 @@
<div class="stat-value text-lg text-primary">{allDates.length}</div>
</div>
<div class="stat py-2 px-4">
<div class="stat-title text-xs">{$t('navbar.adventures')}</div>
<div class="stat-value text-lg text-secondary">{adventures.length}</div>
<div class="stat-title text-xs">{$t('locations.locations')}</div>
<div class="stat-value text-lg text-secondary">{locations.length}</div>
</div>
</div>
</div>
@@ -229,7 +229,7 @@
/>
<input
type="text"
placeholder="Search adventures or locations..."
placeholder={$t('adventures.search_for_location')}
class="input input-bordered w-full pl-10 pr-10 bg-base-100/80"
bind:value={searchFilter}
/>
@@ -298,8 +298,8 @@
<div class="grid grid-cols-2 gap-4">
<div class="stat p-0">
<div class="stat-title text-xs">{$t('navbar.adventures')}</div>
<div class="stat-value text-lg text-primary">{adventures.length}</div>
<div class="stat-title text-xs">{$t('locations.locations')}</div>
<div class="stat-value text-lg text-primary">{locations.length}</div>
</div>
</div>
@@ -418,7 +418,7 @@
{#if selectedEvent.extendedProps.adventureId}
<a
href={`/adventures/${selectedEvent.extendedProps.adventureId}`}
href={`/locations/${selectedEvent.extendedProps.adventureId}`}
class="btn btn-neutral btn-block mt-4"
>
{$t('map.view_details')}

View File

@@ -1,7 +1,7 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure, Collection } from '$lib/types';
import type { Location, Collection } from '$lib/types';
import type { Actions } from '@sveltejs/kit';
import { fetchCSRFToken } from '$lib/index.server';
@@ -16,7 +16,7 @@ export const load = (async (event) => {
let next = null;
let previous = null;
let count = 0;
let collections: Adventure[] = [];
let collections: Location[] = [];
let sessionId = event.cookies.get('sessionid');
// Get sorting parameters from URL
@@ -38,7 +38,7 @@ export const load = (async (event) => {
return redirect(302, '/login');
} else {
let res = await initialFetch.json();
let visited = res.results as Adventure[];
let visited = res.results as Location[];
next = res.next;
previous = res.previous;
count = res.count;
@@ -67,6 +67,17 @@ export const load = (async (event) => {
}
let archivedCollections = (await archivedRes.json()) as Collection[];
let inviteRes = await fetch(`${serverEndpoint}/api/collections/invites/`, {
headers: {
Cookie: `sessionid=${sessionId}`
}
});
if (!inviteRes.ok) {
console.error('Failed to fetch invites');
return redirect(302, '/login');
}
let invites = await inviteRes.json();
// Calculate current page from URL
const currentPage = parseInt(page);
@@ -80,7 +91,8 @@ export const load = (async (event) => {
currentPage,
order_by,
order_direction,
archivedCollections
archivedCollections,
invites
}
};
}

View File

@@ -5,7 +5,7 @@
import CollectionLink from '$lib/components/CollectionLink.svelte';
import CollectionModal from '$lib/components/CollectionModal.svelte';
import NotFound from '$lib/components/NotFound.svelte';
import type { Collection } from '$lib/types';
import type { Collection, CollectionInvite } from '$lib/types';
import { t } from 'svelte-i18n';
import Plus from '~icons/mdi/plus';
@@ -14,6 +14,11 @@
import Archive from '~icons/mdi/archive';
import Share from '~icons/mdi/share-variant';
import CollectionIcon from '~icons/mdi/folder-multiple';
import MailIcon from '~icons/mdi/email';
import CheckIcon from '~icons/mdi/check';
import CloseIcon from '~icons/mdi/close';
import { addToast } from '$lib/toasts';
import DeleteWarning from '$lib/components/DeleteWarning.svelte';
export let data: any;
console.log('Collections page data:', data);
@@ -25,7 +30,7 @@
let newType: string = '';
let resultsPerPage: number = 25;
let isShowingCollectionModal: boolean = false;
let activeView: 'owned' | 'shared' | 'archived' = 'owned';
let activeView: 'owned' | 'shared' | 'archived' | 'invites' = 'owned';
let next: string | null = data.props.next || null;
let previous: string | null = data.props.previous || null;
@@ -35,6 +40,8 @@
let orderBy = data.props.order_by || 'updated_at';
let orderDirection = data.props.order_direction || 'asc';
let invites: CollectionInvite[] = data.props.invites || [];
let sidebarOpen = false;
let collectionToEdit: Collection | null = null;
@@ -54,7 +61,9 @@
? sharedCollections.length
: activeView === 'archived'
? archivedCollections.length
: 0;
: activeView === 'invites'
? invites.length
: 0;
// Optionally, keep count in sync with collections only for owned view
$: {
@@ -152,6 +161,26 @@
isShowingCollectionModal = true;
}
let isShowingConfirmLeaveModal: boolean = false;
let collectionIdToLeave: string | null = null;
async function leaveCollection() {
let res = await fetch(`/api/collections/${collectionIdToLeave}/leave`, {
method: 'POST'
});
if (res.ok) {
addToast('info', $t('adventures.left_collection_message'));
// Remove from shared collections
sharedCollections = sharedCollections.filter(
(collection) => collection.id !== collectionIdToLeave
);
// Optionally, you can also remove from owned collections if needed
collections = collections.filter((collection) => collection.id !== collectionIdToLeave);
} else {
console.log('Error leaving collection');
}
}
function saveEdit(event: CustomEvent<Collection>) {
collections = collections.map((adventure) => {
if (adventure.id === event.detail.id) {
@@ -166,9 +195,60 @@
sidebarOpen = !sidebarOpen;
}
function switchView(view: 'owned' | 'shared' | 'archived') {
function switchView(view: 'owned' | 'shared' | 'archived' | 'invites') {
activeView = view;
}
// Invite functions
async function acceptInvite(invite: CollectionInvite) {
try {
const res = await fetch(`/api/collections/${invite.collection}/accept-invite/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
// Remove invite from list
invites = invites.filter((i) => i.id !== invite.id);
addToast('success', `${$t('invites.accepted')} "${invite.name}"`);
// Optionally refresh shared collections
await goto(window.location.pathname, { invalidateAll: true });
} else {
const error = await res.json();
addToast('error', error.error || $t('invites.accept_failed'));
}
} catch (error) {
addToast('error', $t('invites.accept_failed'));
}
}
async function declineInvite(invite: CollectionInvite) {
try {
const res = await fetch(`/api/collections/${invite.collection}/decline-invite/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
// Remove invite from list
invites = invites.filter((i) => i.id !== invite.id);
addToast('success', `${$t('invites.declined')} "${invite.name}"`);
} else {
const error = await res.json();
addToast('error', error.error || $t('invites.decline_failed'));
}
} catch (error) {
addToast('error', $t('invites.decline_failed'));
}
}
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString();
}
</script>
<svelte:head>
@@ -176,6 +256,17 @@
<meta name="description" content="View your adventure collections." />
</svelte:head>
{#if isShowingConfirmLeaveModal}
<DeleteWarning
title={$t('adventures.leave_collection')}
button_text={$t('adventures.leave')}
description={$t('adventures.leave_collection_warning')}
is_warning={true}
on:close={() => (isShowingConfirmLeaveModal = false)}
on:confirm={leaveCollection}
/>
{/if}
{#if isShowingCollectionModal}
<CollectionModal
{collectionToEdit}
@@ -204,7 +295,9 @@
</div>
<div>
<h1 class="text-3xl font-bold bg-clip-text text-primary">
{$t(`adventures.my_collections`)}
{activeView === 'invites'
? $t('invites.title')
: $t(`adventures.my_collections`)}
</h1>
<p class="text-sm text-base-content/60">
{currentCount}
@@ -212,7 +305,9 @@
? $t('navbar.collections')
: activeView === 'shared'
? $t('collection.shared_collections')
: $t('adventures.archived_collections')}
: activeView === 'archived'
? $t('adventures.archived_collections')
: $t('invites.pending_invites')}
</p>
</div>
</div>
@@ -258,6 +353,27 @@
{archivedCollections.length}
</div>
</button>
<button
class="tab gap-2 {activeView === 'invites' ? 'tab-active' : ''}"
on:click={() => switchView('invites')}
>
<div class="indicator">
<MailIcon class="w-4 h-4" />
{#if invites.length > 0}
<span class="indicator-item badge badge-xs badge-error"></span>
{/if}
</div>
<span class="hidden sm:inline">{$t('invites.title')}</span>
<div
class="badge badge-sm {activeView === 'invites'
? 'badge-primary'
: invites.length > 0
? 'badge-error'
: 'badge-ghost'}"
>
{invites.length}
</div>
</button>
</div>
</div>
</div>
@@ -265,7 +381,72 @@
<!-- Main Content -->
<div class="container mx-auto px-6 py-8">
{#if currentCollections.length === 0}
{#if activeView === 'invites'}
<!-- Invites Content -->
{#if invites.length === 0}
<div class="flex flex-col items-center justify-center py-16">
<div class="p-6 bg-base-200/50 rounded-2xl mb-6">
<MailIcon class="w-16 h-16 text-base-content/30" />
</div>
<h3 class="text-xl font-semibold text-base-content/70 mb-2">
{$t('invites.no_invites')}
</h3>
<p class="text-base-content/50 text-center max-w-md">
{$t('invites.no_invites_desc')}
</p>
</div>
{:else}
<div class="space-y-4">
{#each invites as invite}
<div
class="card bg-base-100 shadow-lg border border-base-300 hover:shadow-xl transition-shadow"
>
<div class="card-body p-6">
<div class="flex items-start justify-between">
<div class="flex-1">
<div class="flex items-center gap-3 mb-2">
<div class="p-2 bg-primary/10 rounded-lg">
<CollectionIcon class="w-5 h-5 text-primary" />
</div>
<div>
<h3 class="font-semibold text-lg">
{invite.name}
</h3>
<p class="text-xs text-base-content/50">
{$t('invites.invited_on')}
{formatDate(invite.created_at)}
{$t('invites.by')}
{invite.collection_owner_username || ''}
({invite.collection_user_first_name || ''}
{invite.collection_user_last_name || ''})
</p>
</div>
</div>
</div>
<div class="flex gap-2 ml-4">
<button
class="btn btn-success btn-sm gap-2"
on:click={() => acceptInvite(invite)}
>
<CheckIcon class="w-4 h-4" />
{$t('invites.accept')}
</button>
<button
class="btn btn-error btn-sm btn-outline gap-2"
on:click={() => declineInvite(invite)}
>
<CloseIcon class="w-4 h-4" />
{$t('invites.decline')}
</button>
</div>
</div>
</div>
</div>
{/each}
</div>
{/if}
{:else if currentCollections.length === 0}
<!-- Empty State for Collections -->
<div class="flex flex-col items-center justify-center py-16">
<div class="p-6 bg-base-200/50 rounded-2xl mb-6">
{#if activeView === 'owned'}
@@ -318,6 +499,10 @@
on:archive={archiveCollection}
on:unarchive={unarchiveCollection}
user={data.user}
on:leave={(e) => {
collectionIdToLeave = e.detail;
isShowingConfirmLeaveModal = true;
}}
/>
{/each}
</div>
@@ -356,79 +541,82 @@
<h2 class="text-xl font-bold">{$t('adventures.filters_and_sort')}</h2>
</div>
<!-- Sort Form - Updated to use URL navigation -->
<div class="card bg-base-200/50 p-4">
<h3 class="font-semibold text-lg mb-4 flex items-center gap-2">
<Sort class="w-5 h-5" />
{$t(`adventures.sort`)}
</h3>
<!-- Only show sort options for collection views, not invites -->
{#if activeView !== 'invites'}
<!-- Sort Form - Updated to use URL navigation -->
<div class="card bg-base-200/50 p-4">
<h3 class="font-semibold text-lg mb-4 flex items-center gap-2">
<Sort class="w-5 h-5" />
{$t(`adventures.sort`)}
</h3>
<div class="space-y-4">
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t(`adventures.order_direction`)}</span>
</label>
<div class="join w-full">
<button
class="join-item btn btn-sm flex-1 {orderDirection === 'asc'
? 'btn-active'
: ''}"
on:click={() => updateSort(orderBy, 'asc')}
>
{$t(`adventures.ascending`)}
</button>
<button
class="join-item btn btn-sm flex-1 {orderDirection === 'desc'
? 'btn-active'
: ''}"
on:click={() => updateSort(orderBy, 'desc')}
>
{$t(`adventures.descending`)}
</button>
<div class="space-y-4">
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t(`adventures.order_direction`)}</span>
</label>
<div class="join w-full">
<button
class="join-item btn btn-sm flex-1 {orderDirection === 'asc'
? 'btn-active'
: ''}"
on:click={() => updateSort(orderBy, 'asc')}
>
{$t(`adventures.ascending`)}
</button>
<button
class="join-item btn btn-sm flex-1 {orderDirection === 'desc'
? 'btn-active'
: ''}"
on:click={() => updateSort(orderBy, 'desc')}
>
{$t(`adventures.descending`)}
</button>
</div>
</div>
</div>
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t('adventures.order_by')}</span>
</label>
<div class="space-y-2">
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'updated_at'}
on:change={() => updateSort('updated_at', orderDirection)}
/>
<span class="label-text">{$t('adventures.updated')}</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'start_date'}
on:change={() => updateSort('start_date', orderDirection)}
/>
<span class="label-text">{$t('adventures.start_date')}</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'name'}
on:change={() => updateSort('name', orderDirection)}
/>
<span class="label-text">{$t('adventures.name')}</span>
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t('adventures.order_by')}</span>
</label>
<div class="space-y-2">
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'updated_at'}
on:change={() => updateSort('updated_at', orderDirection)}
/>
<span class="label-text">{$t('adventures.updated')}</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'start_date'}
on:change={() => updateSort('start_date', orderDirection)}
/>
<span class="label-text">{$t('adventures.start_date')}</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="radio"
name="order_by_radio"
class="radio radio-primary radio-sm"
checked={orderBy === 'name'}
on:change={() => updateSort('name', orderDirection)}
/>
<span class="label-text">{$t('adventures.name')}</span>
</label>
</div>
</div>
</div>
</div>
</div>
{/if}
</div>
</div>
</div>

View File

@@ -1,7 +1,7 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure, Collection } from '$lib/types';
import type { Location, Collection } from '$lib/types';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import type { Adventure, Checklist, Collection, Lodging, Note, Transportation } from '$lib/types';
import type { Location, Checklist, Collection, Lodging, Note, Transportation } from '$lib/types';
import { onMount, onDestroy } from 'svelte';
import type { PageData } from './$types';
import { marked } from 'marked'; // Import the markdown parser
@@ -15,8 +15,8 @@
import DayGrid from '@event-calendar/day-grid';
import Plus from '~icons/mdi/plus';
import AdventureCard from '$lib/components/AdventureCard.svelte';
import AdventureLink from '$lib/components/AdventureLink.svelte';
import LocationCard from '$lib/components/LocationCard.svelte';
import AdventureLink from '$lib/components/LocationLink.svelte';
import { MapLibre, Marker, Popup, LineLayer, GeoJSON } from 'svelte-maplibre';
import TransportationCard from '$lib/components/TransportationCard.svelte';
import NoteCard from '$lib/components/NoteCard.svelte';
@@ -25,7 +25,7 @@
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
import {
groupAdventuresByDate,
groupLocationsByDate,
groupNotesByDate,
groupTransportationsByDate,
groupChecklistsByDate,
@@ -39,13 +39,13 @@
import ChecklistCard from '$lib/components/ChecklistCard.svelte';
import ChecklistModal from '$lib/components/ChecklistModal.svelte';
import AdventureModal from '$lib/components/AdventureModal.svelte';
import TransportationModal from '$lib/components/TransportationModal.svelte';
import CardCarousel from '$lib/components/CardCarousel.svelte';
import { goto } from '$app/navigation';
import LodgingModal from '$lib/components/LodgingModal.svelte';
import LodgingCard from '$lib/components/LodgingCard.svelte';
import CollectionAllView from '$lib/components/CollectionAllView.svelte';
import NewLocationModal from '$lib/components/NewLocationModal.svelte';
export let data: PageData;
console.log(data);
@@ -242,14 +242,14 @@
let currentView: string = 'itinerary';
let currentItineraryView: string = 'date';
let adventures: Adventure[] = [];
let adventures: Location[] = [];
$: lineData = createLineData(orderedItems);
// Function to create GeoJSON line data from ordered items
function createLineData(
items: Array<{
item: Adventure | Transportation | Lodging | Note | Checklist;
item: Location | Transportation | Lodging | Note | Checklist;
start: string;
end: string;
}>
@@ -333,7 +333,7 @@
}
let orderedItems: Array<{
item: Adventure | Transportation | Lodging;
item: Location | Transportation | Lodging;
type: 'adventure' | 'transportation' | 'lodging';
start: string; // ISO date string
end: string; // ISO date string
@@ -417,7 +417,7 @@
onMount(() => {
if (data.props.adventure) {
collection = data.props.adventure;
adventures = collection.adventures as Adventure[];
adventures = collection.locations as Location[];
} else {
notFound = true;
}
@@ -461,7 +461,7 @@
adventures = adventures.filter((a) => a.id !== event.detail);
}
async function addAdventure(event: CustomEvent<Adventure>) {
async function addAdventure(event: CustomEvent<Location>) {
console.log(event.detail);
if (adventures.find((a) => a.id === event.detail.id)) {
return;
@@ -477,7 +477,7 @@
}
}
let res = await fetch(`/api/adventures/${adventure.id}/`, {
let res = await fetch(`/api/locations/${adventure.id}/`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
@@ -498,7 +498,7 @@
function recomendationToAdventure(recomendation: any) {
adventureToEdit = {
id: '',
user_id: null,
user: null,
name: recomendation.name,
latitude: recomendation.latitude,
longitude: recomendation.longitude,
@@ -513,27 +513,50 @@
icon: osmTagToEmoji(recomendation.tag),
id: '',
name: recomendation.tag,
user_id: ''
user: ''
},
attachments: []
attachments: [],
trails: []
};
isAdventureModalOpen = true;
isLocationModalOpen = true;
}
let adventureToEdit: Adventure | null = null;
let adventureToEdit: Location | null = null;
let transportationToEdit: Transportation | null = null;
let isShowingLodgingModal: boolean = false;
let lodgingToEdit: Lodging | null = null;
let isAdventureModalOpen: boolean = false;
let isLocationModalOpen: boolean = false;
let isNoteModalOpen: boolean = false;
let noteToEdit: Note | null;
let checklistToEdit: Checklist | null;
let newType: string;
let locationBeingUpdated: Location | undefined = undefined;
function editAdventure(event: CustomEvent<Adventure>) {
// Sync the locationBeingUpdated with the adventures array
$: {
if (locationBeingUpdated && locationBeingUpdated.id) {
const index = adventures.findIndex((adventure) => adventure.id === locationBeingUpdated?.id);
if (index !== -1) {
// Ensure visits are properly synced
adventures[index] = {
...adventures[index],
...locationBeingUpdated,
visits: locationBeingUpdated.visits || adventures[index].visits || []
};
adventures = adventures; // Trigger reactivity
} else {
adventures = [{ ...locationBeingUpdated }, ...adventures];
if (data.props.adventure) {
data.props.adventure.locations = adventures;
}
}
}
}
function editAdventure(event: CustomEvent<Location>) {
adventureToEdit = event.detail;
isAdventureModalOpen = true;
isLocationModalOpen = true;
}
function editTransportation(event: CustomEvent<Transportation>) {
@@ -546,7 +569,7 @@
isShowingLodgingModal = true;
}
function saveOrCreateAdventure(event: CustomEvent<Adventure>) {
function saveOrCreateAdventure(event: CustomEvent<Location>) {
if (adventures.find((adventure) => adventure.id === event.detail.id)) {
adventures = adventures.map((adventure) => {
if (adventure.id === event.detail.id) {
@@ -557,7 +580,7 @@
} else {
adventures = [event.detail, ...adventures];
}
isAdventureModalOpen = false;
isLocationModalOpen = false;
}
let isPopupOpen = false;
@@ -585,7 +608,7 @@
console.log(filteredRecomendations);
console.log(selectedRecomendationTag);
}
async function getRecomendations(adventure: Adventure) {
async function getRecomendations(adventure: Location) {
recomendationsData = null;
selectedRecomendationTag = '';
loadingRecomendations = true;
@@ -688,11 +711,12 @@
/>
{/if}
{#if isAdventureModalOpen}
<AdventureModal
{adventureToEdit}
on:close={() => (isAdventureModalOpen = false)}
on:save={saveOrCreateAdventure}
{#if isLocationModalOpen}
<NewLocationModal
on:close={() => (isLocationModalOpen = false)}
user={data.user}
locationToEdit={adventureToEdit}
bind:location={locationBeingUpdated}
{collection}
/>
{/if}
@@ -748,7 +772,7 @@
</div>
{/if}
{#if collection && collection.id}
{#if data.user && data.user.uuid && (data.user.uuid == collection.user_id || (collection.shared_with && collection.shared_with.includes(data.user.uuid))) && !collection.is_archived}
{#if data.user && data.user.uuid && (data.user.uuid == collection.user || (collection.shared_with && collection.shared_with.includes(data.user.uuid))) && !collection.is_archived}
<div class="fixed bottom-4 right-4 z-[999]">
<div class="flex flex-row items-center justify-center gap-4">
<div class="dropdown dropdown-top dropdown-end z-[999]">
@@ -760,7 +784,7 @@
tabindex="0"
class="dropdown-content z-[1] menu p-4 shadow bg-base-300 text-base-content rounded-box w-52 gap-4"
>
{#if collection.user_id === data.user.uuid}
{#if collection.user === data.user.uuid || (collection.shared_with && collection.shared_with.includes(data.user.uuid))}
<p class="text-center font-bold text-lg">{$t('adventures.link_new')}</p>
<button
class="btn btn-primary"
@@ -768,18 +792,18 @@
isShowingLinkModal = true;
}}
>
{$t('adventures.adventure')}</button
{$t('locations.location')}</button
>
{/if}
<p class="text-center font-bold text-lg">{$t('adventures.add_new')}</p>
<button
class="btn btn-primary"
on:click={() => {
isAdventureModalOpen = true;
isLocationModalOpen = true;
adventureToEdit = null;
}}
>
{$t('adventures.adventure')}</button
{$t('locations.location')}</button
>
<button
@@ -788,7 +812,6 @@
// Reset the transportation object for creating a new one
transportationToEdit = null;
isShowingTransportationModal = true;
newType = '';
}}
>
{$t('adventures.transportation')}</button
@@ -797,7 +820,7 @@
class="btn btn-primary"
on:click={() => {
isNoteModalOpen = true;
newType = '';
noteToEdit = null;
}}
>
@@ -807,7 +830,7 @@
class="btn btn-primary"
on:click={() => {
isShowingChecklistModal = true;
newType = '';
checklistToEdit = null;
}}
>
@@ -817,7 +840,7 @@
class="btn btn-primary"
on:click={() => {
isShowingLodgingModal = true;
newType = '';
lodgingToEdit = null;
}}
>
@@ -1032,7 +1055,7 @@
{@const dateString = adjustedDate.toISOString().split('T')[0]}
{@const dayAdventures =
groupAdventuresByDate(adventures, new Date(collection.start_date), numberOfDays + 1)[
groupLocationsByDate(adventures, new Date(collection.start_date), numberOfDays + 1)[
dateString
] || []}
{@const dayTransportations =
@@ -1069,7 +1092,7 @@
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{#if dayAdventures.length > 0}
{#each dayAdventures as adventure}
<AdventureCard
<LocationCard
user={data.user}
on:edit={editAdventure}
on:delete={deleteAdventure}
@@ -1177,11 +1200,8 @@
<div class="flex justify-between items-center mb-4">
<span class="badge badge-lg">{$t(`adventures.${orderedItem.type}`)}</span>
<div class="text-sm opacity-80 text-right">
{new Date(orderedItem.start).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric'
})}
{#if orderedItem.start !== orderedItem.end}
{new Date(orderedItem.start).toLocaleDateString(undefined, {})}
<div>
{new Date(orderedItem.start).toLocaleTimeString(undefined, {
hour: '2-digit',
@@ -1219,12 +1239,17 @@
)}m
</div>
{:else}
<p>{$t('adventures.all_day')} ⏱️</p>
<div>
{new Date(orderedItem.start).toLocaleDateString(undefined, {
timeZone: 'UTC'
})}
</div>
<div>{$t('adventures.all_day')} ⏱️</div>
{/if}
</div>
</div>
{#if orderedItem.type === 'adventure' && orderedItem.item && 'images' in orderedItem.item}
<AdventureCard
{#if orderedItem.type === 'adventure' && orderedItem.item && 'visits' in orderedItem.item}
<LocationCard
user={data.user}
on:edit={editAdventure}
on:delete={deleteAdventure}
@@ -1292,7 +1317,11 @@
{#if isPopupOpen}
<Popup openOn="click" offset={[0, -10]} on:close={() => (isPopupOpen = false)}>
{#if adventure.images && adventure.images.length > 0}
<CardCarousel adventures={[adventure]} />
<CardCarousel
images={adventure.images}
name={adventure.name}
icon={adventure?.category?.icon}
/>
{/if}
<div class="text-lg text-black font-bold">{adventure.name}</div>
<p class="font-semibold text-black text-md">
@@ -1323,7 +1352,7 @@
{/if}
<button
class="btn btn-neutral btn-wide btn-sm mt-4"
on:click={() => goto(`/adventures/${adventure.id}`)}
on:click={() => goto(`/locations/${adventure.id}`)}
>{$t('map.view_details')}</button
>
</Popup>
@@ -1418,7 +1447,7 @@
<div class="card bg-base-200 shadow-xl my-8 mx-auto w-10/12">
<div class="card-body">
<h2 class="card-title text-3xl justify-center mb-4">
{$t('adventures.adventure_calendar')}
{$t('adventures.visit_calendar')}
</h2>
<Calendar {plugins} {options} />
</div>
@@ -1428,7 +1457,7 @@
<div class="card bg-base-200 shadow-xl my-8 mx-auto w-10/12">
<div class="card-body">
<h2 class="card-title text-3xl justify-center mb-4">
{$t('recomendations.adventure_recommendations')}
{$t('recomendations.location_recommendations')}
</h2>
{#each adventures as adventure}
{#if adventure.longitude && adventure.latitude}
@@ -1439,7 +1468,7 @@
{/each}
{#if adventures.length == 0}
<div class="alert alert-info">
<p class="text-center text-lg">{$t('adventures.no_adventures_to_recommendations')}</p>
<p class="text-center text-lg">{$t('adventures.no_locations_to_recommendations')}</p>
</div>
{/if}
<div class="mt-4">
@@ -1526,7 +1555,7 @@
<button
class="btn btn-neutral btn-wide btn-sm mt-4"
on:click={() => recomendationToAdventure(recomendation)}
>{$t('adventures.create_adventure')}</button
>{$t('adventures.create_location')}</button
>
</Popup>
{/if}
@@ -1558,7 +1587,7 @@
class="btn btn-primary"
on:click={() => recomendationToAdventure(recomendation)}
>
{$t('adventures.create_adventure')}
{$t('adventures.create_location')}
</button>
</div>
</div>
@@ -1587,8 +1616,8 @@
<div class="hero-content text-center">
<div class="max-w-md">
<img src={Lost} alt="Lost" class="w-64 mx-auto mb-8 opacity-80" />
<h1 class="text-5xl font-bold text-primary mb-4">{$t('adventures.not_found')}</h1>
<p class="text-lg opacity-70 mb-8">{$t('adventures.not_found_desc')}</p>
<h1 class="text-5xl font-bold text-primary mb-4">{$t('adventures.location_not_found')}</h1>
<p class="text-lg opacity-70 mb-8">{$t('adventures.location_not_found_desc')}</p>
<button class="btn btn-primary btn-lg" on:click={() => goto('/')}>
{$t('adventures.homepage')}
</button>

View File

@@ -1,7 +1,7 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure } from '$lib/types';
import type { Location } from '$lib/types';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
@@ -9,9 +9,9 @@ export const load = (async (event) => {
if (!event.locals.user) {
return redirect(302, '/login');
} else {
let adventures: Adventure[] = [];
let adventures: Location[] = [];
let initialFetch = await event.fetch(`${serverEndpoint}/api/adventures/`, {
let initialFetch = await event.fetch(`${serverEndpoint}/api/locations/`, {
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
@@ -41,7 +41,7 @@ export const load = (async (event) => {
return redirect(302, '/login');
} else {
let res = await initialFetch.json();
let visited = res.results as Adventure[];
let visited = res.results as Location[];
// only get the first 3 adventures or less if there are less than 3
adventures = visited.slice(0, 3);
}

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import AdventureCard from '$lib/components/AdventureCard.svelte';
import LocationCard from '$lib/components/LocationCard.svelte';
import type { PageData } from './$types';
import { t } from 'svelte-i18n';
import { onMount } from 'svelte';
@@ -51,9 +51,9 @@
: user?.username}!
</h1>
<p class="text-lg text-base-content/60 mt-2">
{#if stats.adventure_count > 0}
{#if stats.location_count > 0}
{$t('dashboard.welcome_text_1')}
<span class="font-semibold text-primary">{stats.adventure_count}</span>
<span class="font-semibold text-primary">{stats.location_count}</span>
{$t('dashboard.welcome_text_2')}
{:else}
{$t('dashboard.welcome_text_3')}
@@ -66,11 +66,11 @@
<!-- Quick Action -->
<div class="flex flex-col sm:flex-row gap-3">
<a
href="/adventures"
href="/locations"
class="btn btn-primary btn-lg gap-2 shadow-lg hover:shadow-xl transition-all duration-300"
>
<Plus class="w-5 h-5" />
{$t('map.add_adventure')}
{$t('map.add_location')}
</a>
<a href="/worldtravel" class="btn btn-outline btn-lg gap-2">
<FlagCheckeredVariantIcon class="w-5 h-5" />
@@ -169,16 +169,16 @@
<p class="text-base-content/60">{$t('home.latest_travel_experiences')}</p>
</div>
</div>
<a href="/adventures" class="btn btn-ghost gap-2">
<a href="/locations" class="btn btn-ghost gap-2">
{$t('dashboard.view_all')}
<span class="badge badge-primary">{stats.adventure_count}</span>
<span class="badge badge-primary">{stats.location_count}</span>
</a>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
{#each recentAdventures as adventure}
<div class="adventure-card">
<AdventureCard {adventure} user={data.user} readOnly />
<LocationCard {adventure} user={data.user} readOnly />
</div>
{/each}
</div>
@@ -208,11 +208,11 @@
<div class="flex flex-col sm:flex-row gap-4 justify-center">
<a
href="/adventures"
href="/locations"
class="btn btn-primary btn-lg gap-2 shadow-lg hover:shadow-xl transition-all duration-300"
>
<Plus class="w-5 h-5" />
{$t('map.add_adventure')}
{$t('map.add_location')}
</a>
<a href="/worldtravel" class="btn btn-outline btn-lg gap-2">
<FlagCheckeredVariantIcon class="w-5 h-5" />

View File

@@ -1,22 +0,0 @@
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
/** @type {import('./$types').RequestHandler} */
export async function GET(event) {
let sessionid = event.cookies.get('sessionid');
let fileName = event.params.file;
let res = await fetch(`${endpoint}/media/attachments/${fileName}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Cookie: `sessionid=${sessionid}`
}
});
let data = await res.text();
return new Response(data, {
status: res.status,
headers: {
'Content-Type': 'application/xml'
}
});
}

View File

@@ -0,0 +1,23 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import type { CollectionInvite } from '$lib/types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
if (!event.locals.user) {
redirect(302, '/login');
}
let res = await event.fetch(`${serverEndpoint}/api/collections/invites/`, {
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include'
});
if (!res.ok) {
return { status: res.status, error: new Error('Failed to fetch invites') };
}
const invites = (await res.json()) as CollectionInvite[];
return { invites };
}) satisfies PageServerLoad;

View File

@@ -0,0 +1,147 @@
<script lang="ts">
import { onMount } from 'svelte';
import { addToast } from '$lib/toasts';
import { t } from 'svelte-i18n';
interface CollectionInvite {
id: string;
collection: string; // UUID of the collection
name: string; // Name of the collection
created_at: string; // ISO 8601 date string
}
let invites: CollectionInvite[] = [];
let loading = true;
async function fetchInvites() {
try {
const res = await fetch('/api/collections/invites/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
invites = await res.json();
} else {
addToast('error', $t('invites.fetch_failed'));
}
} catch (error) {
addToast('error', $t('invites.fetch_failed'));
} finally {
loading = false;
}
}
async function acceptInvite(invite: CollectionInvite) {
try {
const res = await fetch(`/api/collections/${invite.collection}/accept-invite/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
// Remove invite from list
invites = invites.filter((i) => i.id !== invite.id);
addToast('success', `${$t('invites.accepted')} "${invite.name}"`);
} else {
const error = await res.json();
addToast('error', error.error || $t('invites.accept_failed'));
}
} catch (error) {
addToast('error', $t('invites.accept_failed'));
}
}
async function declineInvite(invite: CollectionInvite) {
try {
const res = await fetch(`/api/collections/${invite.collection}/decline-invite/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
// Remove invite from list
invites = invites.filter((i) => i.id !== invite.id);
addToast('success', `${$t('invites.declined')} "${invite.name}"`);
} else {
const error = await res.json();
addToast('error', error.error || $t('invites.decline_failed'));
}
} catch (error) {
addToast('error', $t('invites.decline_failed'));
}
}
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString();
}
onMount(() => {
fetchInvites();
});
</script>
<div class="space-y-4">
<div class="flex items-center justify-between">
<h2 class="text-2xl font-bold">{$t('invites.title')}</h2>
<button class="btn btn-sm btn-ghost" on:click={fetchInvites} disabled={loading}>
{#if loading}
<span class="loading loading-spinner loading-sm"></span>
{:else}
{$t('common.refresh')}
{/if}
</button>
</div>
{#if loading}
<div class="flex justify-center py-8">
<span class="loading loading-spinner loading-lg"></span>
</div>
{:else if invites.length === 0}
<div class="text-center py-8">
<div class="text-base-content/60 mb-2">
{$t('invites.no_invites')}
</div>
<p class="text-sm text-base-content/40">
{$t('invites.no_invites_desc')}
</p>
</div>
{:else}
<div class="space-y-3">
{#each invites as invite}
<div class="card bg-base-100 shadow-sm border border-base-300">
<div class="card-body p-4">
<div class="flex items-start justify-between">
<div class="flex-1">
<h3 class="font-semibold text-lg mb-1">
{invite.name}
</h3>
<p class="text-xs text-base-content/50">
{$t('invites.invited_on')}
{formatDate(invite.created_at)}
</p>
</div>
<div class="flex gap-2 ml-4">
<button class="btn btn-success btn-sm" on:click={() => acceptInvite(invite)}>
{$t('invites.accept')}
</button>
<button
class="btn btn-error btn-sm btn-outline"
on:click={() => declineInvite(invite)}
>
{$t('invites.decline')}
</button>
</div>
</div>
</div>
</div>
{/each}
</div>
{/if}
</div>

View File

@@ -0,0 +1,115 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Location } from '$lib/types';
import type { Actions } from '@sveltejs/kit';
import { fetchCSRFToken } from '$lib/index.server';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
if (!event.locals.user) {
return redirect(302, '/login');
} else {
let count = 0;
let adventures: Location[] = [];
let typeString = event.url.searchParams.get('types');
// If no type is specified, default to 'all'
if (!typeString) {
typeString = 'all';
}
const include_collections = event.url.searchParams.get('include_collections') || 'false';
const order_by = event.url.searchParams.get('order_by') || 'updated_at';
const order_direction = event.url.searchParams.get('order_direction') || 'asc';
const page = event.url.searchParams.get('page') || '1';
const is_visited = event.url.searchParams.get('is_visited') || 'all';
let initialFetch = await event.fetch(
`${serverEndpoint}/api/locations/filtered?types=${typeString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}&page=${page}&is_visited=${is_visited}`,
{
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include'
}
);
if (!initialFetch.ok) {
let error_message = await initialFetch.json();
console.error(error_message);
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let res = await initialFetch.json();
let visited = res.results as Location[];
count = res.count;
adventures = [...adventures, ...visited];
}
return {
props: {
adventures,
count
}
};
}
}) satisfies PageServerLoad;
export const actions: Actions = {
image: async (event) => {
let formData = await event.request.formData();
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/images/`, {
method: 'POST',
headers: {
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`,
'X-CSRFToken': csrfToken,
Referer: event.url.origin // Include Referer header
},
body: formData
});
let data = await res.json();
return data;
},
activity: async (event) => {
let formData = await event.request.formData();
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/activities/`, {
method: 'POST',
headers: {
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`,
'X-CSRFToken': csrfToken,
Referer: event.url.origin // Include Referer header
},
body: formData
});
let data = await res.json();
return data;
},
attachment: async (event) => {
let formData = await event.request.formData();
let csrfToken = await fetchCSRFToken();
let sessionId = event.cookies.get('sessionid');
let res = await fetch(`${serverEndpoint}/api/attachments/`, {
method: 'POST',
headers: {
Cookie: `csrftoken=${csrfToken}; sessionid=${sessionId}`,
'X-CSRFToken': csrfToken,
Referer: event.url.origin // Include Referer header
},
body: formData
});
let data = await res.json();
console.log(res);
console.log(data);
return data;
}
};

View File

@@ -1,13 +1,10 @@
<script lang="ts">
import { enhance, deserialize } from '$app/forms';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import AdventureCard from '$lib/components/AdventureCard.svelte';
import AdventureModal from '$lib/components/AdventureModal.svelte';
import LocationCard from '$lib/components/LocationCard.svelte';
import CategoryFilterDropdown from '$lib/components/CategoryFilterDropdown.svelte';
import CategoryModal from '$lib/components/CategoryModal.svelte';
import NotFound from '$lib/components/NotFound.svelte';
import type { Adventure, Category } from '$lib/types';
import type { Location } from '$lib/types';
import { t } from 'svelte-i18n';
import Plus from '~icons/mdi/plus';
@@ -15,15 +12,14 @@
import Sort from '~icons/mdi/sort';
import MapMarker from '~icons/mdi/map-marker';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import Calendar from '~icons/mdi/calendar';
import Star from '~icons/mdi/star';
import Tag from '~icons/mdi/tag';
import Compass from '~icons/mdi/compass';
import NewLocationModal from '$lib/components/NewLocationModal.svelte';
export let data: any;
let adventures: Adventure[] = data.props.adventures || [];
let adventures: Location[] = data.props.adventures || [];
let currentSort = {
order_by: '',
@@ -34,6 +30,23 @@
is_visited: 'all'
};
let locationBeingUpdated: Location | undefined = undefined;
// Sync the locationBeingUpdated with the adventures array
$: {
if (locationBeingUpdated && locationBeingUpdated.id) {
const index = adventures.findIndex((adventure) => adventure.id === locationBeingUpdated?.id);
if (index !== -1) {
adventures[index] = { ...locationBeingUpdated };
adventures = adventures; // Trigger reactivity
} else {
adventures = [{ ...locationBeingUpdated }, ...adventures];
data.props.adventures = adventures; // Update data.props.adventures as well
}
}
}
let resultsPerPage: number = 25;
let count = data.props.count || 0;
let totalPages = Math.ceil(count / resultsPerPage);
@@ -41,8 +54,8 @@
let is_category_modal_open: boolean = false;
let typeString: string = '';
let adventureToEdit: Adventure | null = null;
let isAdventureModalOpen: boolean = false;
let adventureToEdit: Location | null = null;
let isLocationModalOpen: boolean = false;
let sidebarOpen = false;
// Reactive statements
@@ -130,23 +143,9 @@
adventures = adventures.filter((adventure) => adventure.id !== event.detail);
}
function saveOrCreate(event: CustomEvent<Adventure>) {
if (adventures.find((adventure) => adventure.id === event.detail.id)) {
adventures = adventures.map((adventure) => {
if (adventure.id === event.detail.id) {
return event.detail;
}
return adventure;
});
} else {
adventures = [event.detail, ...adventures];
}
isAdventureModalOpen = false;
}
function editAdventure(event: CustomEvent<Adventure>) {
function editAdventure(event: CustomEvent<Location>) {
adventureToEdit = event.detail;
isAdventureModalOpen = true;
isLocationModalOpen = true;
}
function toggleSidebar() {
@@ -163,15 +162,16 @@
</script>
<svelte:head>
<title>{$t('navbar.adventures')}</title>
<title>{$t('locations.locations')}</title>
<meta name="description" content="View your completed and planned adventures." />
</svelte:head>
{#if isAdventureModalOpen}
<AdventureModal
{adventureToEdit}
on:close={() => (isAdventureModalOpen = false)}
on:save={saveOrCreate}
{#if isLocationModalOpen}
<NewLocationModal
on:close={() => (isLocationModalOpen = false)}
user={data.user}
locationToEdit={adventureToEdit}
bind:location={locationBeingUpdated}
/>
{/if}
@@ -198,11 +198,11 @@
</div>
<div>
<h1 class="text-3xl font-bold bg-clip-text text-primary">
{$t('navbar.my_adventures')}
{$t('locations.my_locations')}
</h1>
<p class="text-sm text-base-content/60">
{count}
{$t('navbar.adventures')}{getVisitedCount()}
{$t('locations.locations')}{getVisitedCount()}
{$t('adventures.visited')}{getPlannedCount()}
{$t('adventures.planned')}
</p>
@@ -241,7 +241,7 @@
<Compass class="w-16 h-16 text-base-content/30" />
</div>
<h3 class="text-xl font-semibold text-base-content/70 mb-2">
{$t('adventures.no_adventures_found')}
{$t('adventures.no_locations_found')}
</h3>
<p class="text-base-content/50 text-center max-w-md">
{$t('adventures.no_adventures_message')}
@@ -250,11 +250,11 @@
class="btn btn-primary btn-wide mt-6 gap-2"
on:click={() => {
adventureToEdit = null;
isAdventureModalOpen = true;
isLocationModalOpen = true;
}}
>
<Plus class="w-5 h-5" />
{$t('adventures.create_adventure')}
{$t('adventures.create_location')}
</button>
</div>
{:else}
@@ -263,7 +263,7 @@
class="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-6"
>
{#each adventures as adventure}
<AdventureCard
<LocationCard
user={data.user}
{adventure}
on:delete={deleteAdventure}
@@ -470,7 +470,7 @@
class="checkbox checkbox-primary"
checked={currentSort.includeCollections}
/>
<span class="label-text">{$t('adventures.collection_adventures')}</span>
<span class="label-text">{$t('adventures.collection_locations')}</span>
</label>
</div>
@@ -503,12 +503,12 @@
<button
class="btn btn-primary gap-2 w-full"
on:click={() => {
isAdventureModalOpen = true;
isLocationModalOpen = true;
adventureToEdit = null;
}}
>
<Compass class="w-5 h-5" />
{$t('adventures.adventure')}
{$t('locations.location')}
</button>
</ul>
</div>

View File

@@ -0,0 +1,76 @@
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { AdditionalLocation, Location, Collection } from '$lib/types';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
const id = event.params as { id: string };
let request = await fetch(`${endpoint}/api/locations/${id.id}/additional-info/`, {
headers: {
Cookie: `sessionid=${event.cookies.get('sessionid')}`
},
credentials: 'include'
});
if (!request.ok) {
console.error('Failed to fetch adventure ' + id.id);
return {
props: {
adventure: null
}
};
} else {
let adventure = (await request.json()) as AdditionalLocation;
return {
props: {
adventure
}
};
}
}) satisfies PageServerLoad;
import { redirect, type Actions } from '@sveltejs/kit';
import { fetchCSRFToken } from '$lib/index.server';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const actions: Actions = {
delete: async (event) => {
const id = event.params as { id: string };
const adventureId = id.id;
if (!event.locals.user) {
return redirect(302, '/login');
}
if (!adventureId) {
return {
status: 400,
error: new Error('Bad request')
};
}
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${serverEndpoint}/api/locations/${event.params.id}`, {
method: 'DELETE',
headers: {
Referer: event.url.origin, // Include Referer header
Cookie: `sessionid=${event.cookies.get('sessionid')};
csrftoken=${csrfToken}`,
'X-CSRFToken': csrfToken
},
credentials: 'include'
});
console.log(res);
if (!res.ok) {
return {
status: res.status,
error: new Error('Failed to delete adventure')
};
} else {
return {
status: 204
};
}
}
};

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import type { AdditionalAdventure } from '$lib/types';
import type { AdditionalLocation } from '$lib/types';
import { onMount } from 'svelte';
import type { PageData } from './$types';
import { goto } from '$app/navigation';
@@ -9,17 +9,17 @@
import { marked } from 'marked';
import DOMPurify from 'dompurify';
// @ts-ignore
import toGeoJSON from '@mapbox/togeojson';
// @ts-ignore
import { DateTime } from 'luxon';
import LightbulbOn from '~icons/mdi/lightbulb-on';
import WeatherSunset from '~icons/mdi/weather-sunset';
import ClipboardList from '~icons/mdi/clipboard-list';
import AdventureModal from '$lib/components/AdventureModal.svelte';
import ImageDisplayModal from '$lib/components/ImageDisplayModal.svelte';
import AttachmentCard from '$lib/components/AttachmentCard.svelte';
import { getBasemapUrl, isAllDay } from '$lib';
import { getActivityColor, getBasemapUrl, isAllDay } from '$lib';
import ActivityCard from '$lib/components/ActivityCard.svelte';
import TrailCard from '$lib/components/TrailCard.svelte';
import NewLocationModal from '$lib/components/NewLocationModal.svelte';
let geojson: any;
@@ -27,57 +27,11 @@
return marked(markdown) as string;
};
async function getGpxFiles() {
let gpxfiles: string[] = [];
if (adventure.attachments && adventure.attachments.length > 0) {
gpxfiles = adventure.attachments
.filter((attachment) => attachment.extension === 'gpx')
.map((attachment) => attachment.file);
}
geojson = {
type: 'FeatureCollection',
features: []
};
if (gpxfiles.length > 0) {
const promises = gpxfiles.map(async (gpxfile) => {
try {
const gpxFileName = gpxfile.split('/').pop();
const res = await fetch('/gpx/' + gpxFileName);
if (!res.ok) {
console.error(`Failed to fetch GPX file: ${gpxFileName}`);
return [];
}
const gpxData = await res.text();
const parser = new DOMParser();
const gpx = parser.parseFromString(gpxData, 'text/xml');
const convertedGeoJSON = toGeoJSON.gpx(gpx);
return convertedGeoJSON.features || [];
} catch (error) {
console.error(`Error processing GPX file ${gpxfile}:`, error);
return [];
}
});
const results = await Promise.allSettled(promises);
results.forEach((result) => {
if (result.status === 'fulfilled' && result.value.length > 0) {
geojson.features.push(...result.value);
}
});
}
}
export let data: PageData;
let measurementSystem = data.user?.measurement_system || 'metric';
console.log(data);
let adventure: AdditionalAdventure;
let adventure: AdditionalLocation;
let currentSlide = 0;
function goToSlide(index: number) {
@@ -86,7 +40,9 @@
let notFound: boolean = false;
let isEditModalOpen: boolean = false;
let image_url: string | null = null;
let adventure_images: { image: string; adventure: AdditionalLocation | null }[] = [];
let modalInitialIndex: number = 0;
let isImageModalOpen: boolean = false;
onMount(async () => {
if (data.props.adventure) {
@@ -103,14 +59,63 @@
} else {
notFound = true;
}
await getGpxFiles();
});
async function saveEdit(event: CustomEvent<AdditionalAdventure>) {
adventure = event.detail;
isEditModalOpen = false;
geojson = null;
await getGpxFiles();
function hasActivityGeojson(adventure: AdditionalLocation) {
return adventure.visits.some((visit) => visit.activities.some((activity) => activity.geojson));
}
function hasAttachmentGeojson(adventure: AdditionalLocation) {
return adventure.attachments.some((attachment) => attachment.geojson);
}
function getTotalActivities(adventure: AdditionalLocation) {
return adventure.visits.reduce(
(total, visit) => total + (visit.activities ? visit.activities.length : 0),
0
);
}
function getTotalDistance(adventure: AdditionalLocation) {
const totalMeters = adventure.visits.reduce(
(total, visit) =>
total +
(visit.activities
? visit.activities.reduce((sum, activity) => sum + (activity.distance || 0), 0)
: 0),
0
);
// Convert meters to km, then to miles if using imperial system
const totalKm = totalMeters / 1000;
return measurementSystem === 'imperial' ? totalKm * 0.621371 : totalKm;
}
function getTotalElevationGain(adventure: AdditionalLocation) {
const totalMeters = adventure.visits.reduce(
(total, visit) =>
total +
(visit.activities
? visit.activities.reduce((sum, activity) => sum + (activity.elevation_gain || 0), 0)
: 0),
0
);
// Convert to feet if using imperial system
return measurementSystem === 'imperial' ? totalMeters * 3.28084 : totalMeters;
}
function closeImageModal() {
isImageModalOpen = false;
}
function openImageModal(imageIndex: number) {
adventure_images = adventure.images.map((img) => ({
image: img.image,
adventure: adventure
}));
modalInitialIndex = imageIndex;
isImageModalOpen = true;
}
</script>
@@ -119,8 +124,8 @@
<div class="hero-content text-center">
<div class="max-w-md">
<img src={Lost} alt="Lost" class="w-64 mx-auto mb-8 opacity-80" />
<h1 class="text-5xl font-bold text-primary mb-4">{$t('adventures.not_found')}</h1>
<p class="text-lg opacity-70 mb-8">{$t('adventures.not_found_desc')}</p>
<h1 class="text-5xl font-bold text-primary mb-4">{$t('adventures.location_not_found')}</h1>
<p class="text-lg opacity-70 mb-8">{$t('adventures.location_not_found_desc')}</p>
<button class="btn btn-primary btn-lg" on:click={() => goto('/')}>
{$t('adventures.homepage')}
</button>
@@ -130,15 +135,20 @@
{/if}
{#if isEditModalOpen}
<AdventureModal
adventureToEdit={adventure}
<NewLocationModal
on:close={() => (isEditModalOpen = false)}
on:save={saveEdit}
user={data.user}
locationToEdit={adventure}
bind:location={adventure}
/>
{/if}
{#if image_url}
<ImageDisplayModal image={image_url} on:close={() => (image_url = null)} {adventure} />
{#if isImageModalOpen}
<ImageDisplayModal
images={adventure.images}
initialIndex={modalInitialIndex}
on:close={closeImageModal}
/>
{/if}
{#if !adventure && !notFound}
@@ -150,7 +160,7 @@
{/if}
{#if adventure}
{#if data.user && data.user.uuid == adventure.user_id}
{#if data.user?.uuid && adventure.user?.uuid && data.user.uuid === adventure.user.uuid}
<div class="fixed bottom-6 right-6 z-50">
<button
class="btn btn-primary btn-circle w-16 h-16 shadow-xl hover:shadow-2xl transition-all duration-300 hover:scale-110"
@@ -174,7 +184,7 @@
>
<button
class="w-full h-full p-0 bg-transparent border-0"
on:click={() => (image_url = image.image)}
on:click={() => openImageModal(i)}
aria-label={`View full image of ${adventure.name}`}
>
<img src={image.image} class="w-full h-full object-cover" alt={adventure.name} />
@@ -220,6 +230,11 @@
{adventure.visits.length === 1 ? $t('adventures.visit') : $t('adventures.visits')}
</div>
{/if}
{#if adventure.trails && adventure.trails.length > 0}
<div class="badge badge-lg badge-info font-semibold px-4 py-3">
🥾 {adventure.trails.length} Trail{adventure.trails.length === 1 ? '' : 's'}
</div>
{/if}
</div>
<!-- Image Navigation -->
@@ -231,7 +246,7 @@
on:click={() =>
goToSlide(currentSlide > 0 ? currentSlide - 1 : adventure.images.length - 1)}
class="btn btn-circle btn-sm btn-primary"
aria-label="Previous image"
aria-label={$t('adventures.previous_image')}
>
</button>
@@ -244,7 +259,7 @@
on:click={() =>
goToSlide(currentSlide < adventure.images.length - 1 ? currentSlide + 1 : 0)}
class="btn btn-circle btn-sm btn-primary"
aria-label="Next image"
aria-label={$t('adventures.next_image')}
>
</button>
@@ -360,13 +375,6 @@
? `🌍 ${$t('adventures.public')}`
: `🔒 ${$t('adventures.private')}`}
</div>
<!-- {#if data.props.collection}
<div class="badge badge-sm badge-outline">
📚 <a href="/collections/{data.props.collection.id}" class="link"
>{data.props.collection.name}</a
>
</div>
{/if} -->
{#if adventure.collections && adventure.collections.length > 0}
<div class="badge badge-sm badge-outline">
📚
@@ -392,6 +400,23 @@
</div>
{/if}
<!-- Trails Section -->
{#if adventure.trails && adventure.trails.length > 0}
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h2 class="card-title text-2xl mb-6">🥾 {$t('adventures.trails')}</h2>
<div class="grid gap-4">
{#each adventure.trails as trail}
<TrailCard
{trail}
measurementSystem={data.user?.measurement_system || 'metric'}
/>
{/each}
</div>
</div>
</div>
{/if}
<!-- Visits Timeline -->
{#if adventure.visits.length > 0}
<div class="card bg-base-200 shadow-xl">
@@ -407,7 +432,7 @@
{/if}
</div>
<div class="flex-1 pb-4">
<div class="card bg-base-200 shadow">
<div class="card bg-base-100 shadow">
<div class="card-body p-4">
{#if isAllDay(visit.start_date)}
<div class="flex items-center gap-2 mb-2">
@@ -454,6 +479,26 @@
<p class="text-sm italic">"{visit.notes}"</p>
</div>
{/if}
<!-- Activities Section -->
{#if visit.activities && visit.activities.length > 0}
<div class="mt-4">
<h4 class="font-semibold mb-3 flex items-center gap-2">
🏃‍♂️ Activities ({visit.activities.length})
</h4>
<div class="space-y-3">
{#each visit.activities as activity}
<ActivityCard
{activity}
readOnly={true}
trails={adventure.trails}
{visit}
measurementSystem={data.user?.measurement_system || 'metric'}
/>
{/each}
</div>
</div>
{/if}
</div>
</div>
</div>
@@ -465,7 +510,7 @@
{/if}
<!-- Map Section -->
{#if (adventure.longitude && adventure.latitude) || geojson}
{#if (adventure.longitude && adventure.latitude) || hasAttachmentGeojson(adventure) || hasActivityGeojson(adventure)}
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h2 class="card-title text-2xl mb-4">🗺️ {$t('adventures.location')}</h2>
@@ -539,7 +584,16 @@
class="btn btn-xs btn-outline hover:btn-success"
on:click={() => goto(`/worldtravel/${adventure.country?.country_code}`)}
>
🌎 {adventure.country.name}
{#if adventure.country.flag_url}
<img
src={adventure.country.flag_url}
alt={adventure.country.name}
class="w-4 h-3 rounded"
/>
{:else}
🌎
{/if}
{adventure.country.name}
</button>
{/if}
</div>
@@ -617,6 +671,37 @@
</GeoJSON>
{/if}
<!-- Activity GPS tracks -->
{#each adventure.visits as visit}
{#each visit.activities as activity}
{#if activity.geojson}
<GeoJSON data={activity.geojson}>
<LineLayer
paint={{
'line-color': getActivityColor(activity.sport_type),
'line-width': 3,
'line-opacity': 0.8
}}
/>
</GeoJSON>
{/if}
{/each}
{/each}
{#each adventure.attachments as attachment}
{#if attachment.geojson}
<GeoJSON data={attachment.geojson}>
<LineLayer
paint={{
'line-color': '#00FF00',
'line-width': 2,
'line-opacity': 0.6
}}
/>
</GeoJSON>
{/if}
{/each}
{#if adventure.longitude && adventure.latitude}
<DefaultMarker lngLat={{ lng: adventure.longitude, lat: adventure.latitude }}>
<Popup openOn="click" offset={[0, -10]}>
@@ -649,11 +734,11 @@
<div class="card-body">
<h3 class="card-title text-lg mb-4"> {$t('adventures.basic_information')}</h3>
<div class="space-y-3">
{#if adventure.activity_types && adventure.activity_types?.length > 0}
{#if adventure.tags && adventure.tags?.length > 0}
<div>
<div class="text-sm opacity-70 mb-1">{$t('adventures.tags')}</div>
<div class="flex flex-wrap gap-1">
{#each adventure.activity_types as activity}
{#each adventure.tags as activity}
<span class="badge badge-sm badge-outline">{activity}</span>
{/each}
</div>
@@ -677,6 +762,41 @@
</div>
</div>
<!-- Activity Summary -->
{#if getTotalActivities(adventure) > 0}
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h3 class="card-title text-lg mb-4">🏃‍♂️ Activity Summary</h3>
<div class="space-y-2">
<div class="stat">
<div class="stat-title">Total Activities</div>
<div class="stat-value text-2xl">{getTotalActivities(adventure)}</div>
</div>
{#if getTotalDistance(adventure) > 0}
<div class="stat">
<div class="stat-title">Total Distance</div>
<div class="stat-value text-xl">
{getTotalDistance(adventure).toFixed(1)}
{#if measurementSystem === 'imperial'}mi
{:else}km{/if}
</div>
</div>
{/if}
{#if getTotalElevationGain(adventure) > 0}
<div class="stat">
<div class="stat-title">Total Elevation</div>
<div class="stat-value text-xl">
{getTotalElevationGain(adventure).toFixed(0)}
{#if measurementSystem === 'imperial'}ft
{:else}m{/if}
</div>
</div>
{/if}
</div>
</div>
</div>
{/if}
<!-- Sunrise/Sunset -->
{#if adventure.sun_times && adventure.sun_times.length > 0}
<div class="card bg-base-200 shadow-xl">
@@ -726,13 +846,13 @@
<div class="card-body">
<h3 class="card-title text-lg mb-4">🖼️ {$t('adventures.images')}</h3>
<div class="grid grid-cols-2 sm:grid-cols-3 gap-2">
{#each adventure.images as image}
{#each adventure.images as image, index}
<div class="relative group">
<div
class="aspect-square bg-cover bg-center rounded-lg cursor-pointer transition-transform duration-200 group-hover:scale-105"
style="background-image: url({image.image})"
on:click={() => (image_url = image.image)}
on:keydown={(e) => e.key === 'Enter' && (image_url = image.image)}
on:click={() => openImageModal(index)}
on:keydown={(e) => e.key === 'Enter' && openImageModal(index)}
role="button"
tabindex="0"
></div>

View File

@@ -1,5 +1,6 @@
<script lang="ts">
import { enhance } from '$app/forms';
let isSubmitting: boolean = false;
export let data;
console.log(data);
@@ -15,35 +16,36 @@
import OpenIdConnect from '~icons/mdi/openid';
import { page } from '$app/stores';
import { gsap } from 'gsap'; // Import GSAP
import { gsap } from 'gsap';
import { onMount } from 'svelte';
function handleEnhanceSubmit() {
isSubmitting = true;
// If the form is aborted or done, reset the state
return async ({ update, result }: { update: any; result: any }) => {
if (result.type === 'success') {
// Keep isSubmitting as true for success to show loading state
await update(result);
} else {
isSubmitting = false;
await update(result);
}
};
}
onMount(() => {
gsap.from('.card', {
opacity: 0,
y: 50,
duration: 1,
ease: 'power3.out'
});
gsap.from('.text-center', {
opacity: 0,
x: -50,
duration: 1,
ease: 'power2.out'
});
gsap.from('.input', {
opacity: 0,
y: 30,
duration: 1,
ease: 'power2.out'
});
// Minimal fade-in only
gsap.fromTo(
'.main-container',
{ opacity: 0 },
{ opacity: 1, duration: 0.6, ease: 'power2.out' }
);
});
import ImageInfoModal from '$lib/components/ImageInfoModal.svelte';
import type { Background } from '$lib/types.js';
let quote: { quote: string; author: string } = data.props?.quote ?? { quote: '', author: '' };
let background: Background = data.props?.background ?? { url: '' };
</script>
@@ -51,97 +53,170 @@
<ImageInfoModal {background} on:close={() => (isImageInfoModalOpen = false)} />
{/if}
<div
class="min-h-screen bg-no-repeat bg-cover flex items-center justify-center"
style="background-image: url('{background.url}')"
>
<div
class="card card-compact m-12 w-full max-w-4xl bg-base-100 shadow-xl p-6 flex flex-col md:flex-row"
>
<div class="flex-1">
<h3 class="text-center">AdventureLog</h3>
<article class="text-center text-4xl mb-4 font-extrabold">
<h1>{$t('auth.login')}</h1>
</article>
<div class="min-h-screen bg-base-200">
<!-- Background image if provided -->
{#if background.url}
<div
class="fixed inset-0 bg-cover bg-center bg-no-repeat opacity-90"
style="background-image: url('{background.url}')"
></div>
{/if}
<div class="flex justify-center">
<form method="post" use:enhance class="w-full max-w-xs">
<label for="username">{$t('auth.username')}</label>
<input
name="username"
id="username"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="password">{$t('auth.password')}</label>
<input
type="password"
name="password"
id="password"
class="block input input-bordered w-full max-w-xs"
/><br />
{#if $page.form?.mfa_required}
<label for="totp">TOTP</label>
<input
type="text"
name="totp"
id="totp"
inputmode="numeric"
pattern="[0-9]*"
autocomplete="one-time-code"
class="block input input-bordered w-full max-w-xs"
/><br />
{/if}
<button class="py-2 px-4 btn btn-primary mr-2">{$t('auth.login')}</button>
<div class="main-container relative z-10 min-h-screen flex items-center justify-center p-4">
<div class="w-full max-w-5xl">
<div class="card bg-base-100 shadow-2xl">
<div class="card-body p-0">
<div class="grid lg:grid-cols-2 min-h-[600px]">
<!-- Login Section -->
<div class="p-8 lg:p-12 flex flex-col justify-center">
<!-- Header -->
<div class="text-center mb-8">
<div class="mb-4">
<h1 class="text-3xl font-bold text-primary mb-1">AdventureLog</h1>
<div class="w-12 h-1 bg-primary mx-auto rounded"></div>
</div>
<h2 class="text-4xl font-bold text-base-content mb-2">{$t('auth.login')}</h2>
</div>
{#if socialProviders.length > 0}
<div class="divider text-center text-sm my-4">{$t('auth.or_3rd_party')}</div>
<div class="flex justify-center">
{#each socialProviders as provider}
<a href={provider.url} class="btn btn-primary mr-2 flex items-center">
{#if provider.provider === 'github'}
<GitHub class="w-4 h-4 mr-2" />
{:else if provider.provider === 'openid_connect'}
<OpenIdConnect class="w-4 h-4 mr-2" />
<!-- Form -->
<div class="max-w-sm mx-auto w-full">
<form method="post" use:enhance={handleEnhanceSubmit} class="space-y-4">
<!-- Username -->
<div class="form-control">
<label class="label" for="username">
<span class="label-text font-medium">{$t('auth.username')}</span>
</label>
<input
name="username"
id="username"
type="text"
class="input input-bordered w-full focus:input-primary"
placeholder={$t('auth.enter_username')}
autocomplete="username"
/>
</div>
<!-- Password -->
<div class="form-control">
<label class="label" for="password">
<span class="label-text font-medium">{$t('auth.password')}</span>
</label>
<input
type="password"
name="password"
id="password"
class="input input-bordered w-full focus:input-primary"
placeholder={$t('auth.enter_password')}
autocomplete="current-password"
/>
</div>
<!-- TOTP -->
{#if $page.form?.mfa_required}
<div class="form-control">
<label class="label" for="totp">
<span class="label-text font-medium">{$t('auth.totp')}</span>
</label>
<input
type="text"
name="totp"
id="totp"
inputmode="numeric"
pattern="[0-9]*"
autocomplete="one-time-code"
class="input input-bordered w-full focus:input-primary"
placeholder="000000"
maxlength="6"
/>
</div>
{/if}
{provider.name}
</a>
{/each}
<!-- Submit Button -->
<div class="form-control mt-6">
<button type="submit" class="btn btn-primary w-full" disabled={isSubmitting}>
{#if isSubmitting}
<span class="loading loading-spinner"></span>
<span class="ml-2">{$t('auth.logging_in')}...</span>
{:else}
{$t('auth.login')}
{/if}
</button>
</div>
<!-- Error Message -->
{#if ($page.form?.message && $page.form?.message.length > 1) || $page.form?.type === 'error'}
<div class="alert alert-error mt-4">
<span>{$t($page.form.message) || $t('auth.login_error')}</span>
</div>
{/if}
<!-- Social Login -->
{#if socialProviders.length > 0}
<div class="divider text-sm">{$t('auth.or_3rd_party')}</div>
<div class="space-y-2">
{#each socialProviders as provider}
<a
href={provider.url}
class="btn btn-outline w-full flex items-center gap-2"
>
{#if provider.provider === 'github'}
<GitHub class="w-4 h-4" />
{:else if provider.provider === 'openid_connect'}
<OpenIdConnect class="w-4 h-4" />
{/if}
Continue with {provider.name}
</a>
{/each}
</div>
{/if}
<!-- Footer Links -->
<div class="flex justify-between text-sm mt-6 pt-4 border-t border-base-300">
<a href="/signup" class="link link-primary">
{$t('auth.signup')}
</a>
<a href="/user/reset-password" class="link link-primary">
{$t('auth.forgot_password')}
</a>
</div>
</form>
</div>
</div>
{/if}
<div class="flex justify-between mt-4">
<p><a href="/signup" class="underline">{$t('auth.signup')}</a></p>
<p>
<a href="/user/reset-password" class="underline">{$t('auth.forgot_password')}</a>
</p>
<!-- Quote/Info Section -->
<div
class="bg-primary/5 p-8 lg:p-12 flex items-center justify-center border-l border-base-300"
>
<div class="text-center max-w-md">
{#if quote && quote.quote}
<div class="space-y-4">
<div class="text-6xl text-primary/30 mb-2">"</div>
<blockquote class="text-lg font-medium text-base-content leading-relaxed">
{quote.quote}
</blockquote>
<footer class="text-base-content/70 font-medium">
{quote.author}
</footer>
</div>
{/if}
</div>
</div>
</div>
</form>
</div>
{#if ($page.form?.message && $page.form?.message.length > 1) || $page.form?.type === 'error'}
<div class="text-center text-error mt-4">
{$t($page.form.message) || $t('auth.login_error')}
</div>
{/if}
</div>
<div class="flex-1 flex justify-center items-center mt-12 md:mt-0 md:ml-6">
<blockquote class="w-80 text-center text-2xl font-semibold break-words">
{#if quote != null}
{quote.quote}
{/if}
<footer class="text-sm mt-1">{quote.author}</footer>
</blockquote>
</div>
</div>
</div>
</div>
<div class="fixed bottom-4 right-4 z-[999]">
<div class="dropdown dropdown-left dropdown-end">
<button class="btn m-1 btn-circle btn-md" on:click={() => (isImageInfoModalOpen = true)}>
<!-- Image Info Button -->
{#if background.url}
<button
class="btn btn-circle btn-sm fixed bottom-4 right-4 bg-base-100/80 border-base-300 z-20"
on:click={() => (isImageInfoModalOpen = true)}
>
<FileImageBox class="w-4 h-4" />
</button>
</div>
{/if}
</div>
<svelte:head>
@@ -151,3 +226,10 @@
content="Login to your AdventureLog account to start logging your adventures!"
/>
</svelte:head>
<style>
.input:focus {
outline: 2px solid hsl(var(--p));
outline-offset: 2px;
}
</style>

View File

@@ -1,7 +1,7 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure, VisitedRegion } from '$lib/types';
import type { Location, VisitedRegion } from '$lib/types';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => {
@@ -9,7 +9,7 @@ export const load = (async (event) => {
return redirect(302, '/login');
} else {
let sessionId = event.cookies.get('sessionid');
let visitedFetch = await fetch(`${endpoint}/api/adventures/all/?include_collections=true`, {
let visitedFetch = await fetch(`${endpoint}/api/locations/all/?include_collections=true`, {
headers: {
Cookie: `sessionid=${sessionId}`
}
@@ -22,7 +22,7 @@ export const load = (async (event) => {
});
let visitedRegions = (await visitedRegionsFetch.json()) as VisitedRegion[];
let adventures = (await visitedFetch.json()) as Adventure[];
let adventures = (await visitedFetch.json()) as Location[];
if (!visitedRegionsFetch.ok) {
console.error('Failed to fetch visited regions');

View File

@@ -1,11 +1,18 @@
<script lang="ts">
import AdventureModal from '$lib/components/AdventureModal.svelte';
import { DefaultMarker, MapEvents, MapLibre, Popup, Marker } from 'svelte-maplibre';
import {
DefaultMarker,
MapEvents,
MapLibre,
Popup,
Marker,
GeoJSON,
LineLayer
} from 'svelte-maplibre';
import { t } from 'svelte-i18n';
import type { Adventure, VisitedRegion } from '$lib/types.js';
import type { Activity, Location, VisitedCity, VisitedRegion } from '$lib/types.js';
import CardCarousel from '$lib/components/CardCarousel.svelte';
import { goto } from '$app/navigation';
import { getBasemapUrl } from '$lib';
import { basemapOptions, getActivityColor, getBasemapLabel, getBasemapUrl } from '$lib';
// Icons
import MapIcon from '~icons/mdi/map';
@@ -13,22 +20,30 @@
import Plus from '~icons/mdi/plus';
import Clear from '~icons/mdi/close';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import Pin from '~icons/mdi/map-marker';
import Calendar from '~icons/mdi/calendar';
import Category from '~icons/mdi/shape';
import Location from '~icons/mdi/crosshairs-gps';
import LocationIcon from '~icons/mdi/crosshairs-gps';
import NewLocationModal from '$lib/components/NewLocationModal.svelte';
import ActivityIcon from '~icons/mdi/run-fast';
import MapStyleSelector from '$lib/components/MapStyleSelector.svelte';
export let data;
let createModalOpen: boolean = false;
let showGeo: boolean = false;
let sidebarOpen = false;
let showRegions: boolean = false;
let showActivities: boolean = false;
let showCities: boolean = false;
let sidebarOpen: boolean = false;
let basemapType: string = 'default'; // default
export let initialLatLng: { lat: number; lng: number } | null = null;
let visitedRegions: VisitedRegion[] = data.props.visitedRegions;
let adventures: Adventure[] = data.props.adventures;
let visitedCities: VisitedCity[] = [];
let adventures: Location[] = data.props.adventures;
let activities: Activity[] = [];
let filteredAdventures = adventures;
@@ -39,7 +54,6 @@
let newLongitude: number | null = null;
let newLatitude: number | null = null;
let openPopupId: string | null = null;
let isPopupOpen = false;
// Statistics
@@ -68,6 +82,48 @@
}
}
let locationBeingUpdated: Location | undefined = undefined;
// Sync the locationBeingUpdated with the adventures array
$: {
if (locationBeingUpdated && locationBeingUpdated.id) {
const index = adventures.findIndex((adventure) => adventure.id === locationBeingUpdated?.id);
if (index !== -1) {
adventures[index] = { ...locationBeingUpdated };
adventures = adventures; // Trigger reactivity
} else {
adventures = [{ ...locationBeingUpdated }, ...adventures];
if (data.props.adventures) {
data.props.adventures = adventures; // Update data.props.adventure.locations as well
}
}
}
}
$: {
// if show activities is true, fetch all activities
if (showActivities && activities.length === 0) {
fetchAllActivities();
}
}
async function fetchAllActivities() {
const response = await fetch('/api/activities');
activities = await response.json();
}
$: {
if (showCities && visitedCities.length === 0) {
fetchVisitedCities();
}
}
async function fetchVisitedCities() {
const response = await fetch('/api/visitedcity');
visitedCities = await response.json();
}
function addMarker(e: { detail: { lngLat: { lng: any; lat: any } } }) {
newMarker = null;
newMarker = { lngLat: e.detail.lngLat };
@@ -123,13 +179,13 @@
</div>
<div>
<h1 class="text-3xl font-bold bg-clip-text text-primary">
{$t('map.adventure_map')}
{$t('map.location_map')}
</h1>
<p class="text-sm text-base-content/60">
{filteredAdventures.length}
{$t('worldtravel.of')}
{totalAdventures}
{$t('map.adventures_shown')}
{$t('map.locations_shown')}
</p>
</div>
</div>
@@ -137,7 +193,7 @@
<!-- Quick Stats -->
<div class="hidden md:flex items-center gap-2">
<div class="stats stats-horizontal bg-base-100 shadow-lg">
<div class="stats stats-horizontal bg-base-200/50 border border-base-300/50">
<div class="stat py-2 px-4">
<div class="stat-title text-xs">{$t('adventures.visited')}</div>
<div class="stat-value text-lg text-success">{visitedAdventures}</div>
@@ -157,7 +213,7 @@
{#if newMarker}
<button type="button" class="btn btn-primary btn-sm gap-2" on:click={newAdventure}>
<Plus class="w-4 h-4" />
{$t('map.add_adventure_at_marker')}
{$t('map.add_location_at_marker')}
</button>
<button type="button" class="btn btn-ghost btn-sm gap-2" on:click={clearMarker}>
<Clear class="w-4 h-4" />
@@ -170,7 +226,7 @@
on:click={() => (createModalOpen = true)}
>
<Plus class="w-4 h-4" />
{$t('map.add_adventure')}
{$t('map.add_location')}
</button>
{/if}
</div>
@@ -180,10 +236,19 @@
<!-- Map Section -->
<div class="container mx-auto px-6 py-4 flex-1">
<div class="card bg-base-100 shadow-xl h-full">
<div class="card-body p-4 h-full">
<div class="card bg-base-100 shadow-xl h-full relative">
<!-- Integrated Map Type Selector -->
<div
class="absolute top-4 right-4 z-10 bg-base-200 backdrop-blur-sm rounded-lg shadow-lg"
>
<div class="p-2">
<MapStyleSelector bind:basemapType />
</div>
</div>
<div class="card-body p-0 h-full">
<MapLibre
style={getBasemapUrl()}
style={getBasemapUrl(basemapType)}
class="w-full h-full min-h-[70vh] rounded-lg"
standardControls
>
@@ -191,7 +256,7 @@
{#if adventure.latitude && adventure.longitude}
<Marker
lngLat={[adventure.longitude, adventure.latitude]}
class="grid h-8 w-8 place-items-center rounded-full border border-gray-200 shadow-lg cursor-pointer hover:scale-110 {adventure.is_visited
class="grid h-8 w-8 place-items-center rounded-full border border-gray-200 shadow-lg cursor-pointer hover:scale-110 transition-transform {adventure.is_visited
? 'bg-red-300 hover:bg-red-400'
: 'bg-blue-300 hover:bg-blue-400'} text-black focus:outline-6 focus:outline-black"
on:click={togglePopup}
@@ -208,7 +273,11 @@
<div class="min-w-64 max-w-sm">
{#if adventure.images && adventure.images.length > 0}
<div class="mb-3">
<CardCarousel adventures={[adventure]} />
<CardCarousel
images={adventure.images}
name={adventure.name}
icon={adventure?.category?.icon}
/>
</div>
{/if}
<div class="space-y-2">
@@ -262,13 +331,13 @@
target="_blank"
rel="noopener noreferrer"
>
<Location class="w-4 h-4" />
<LocationIcon class="w-4 h-4" />
{$t('adventures.open_in_maps')}
</a>
{/if}
<button
class="btn btn-primary btn-sm gap-2"
on:click={() => goto(`/adventures/${adventure.id}`)}
on:click={() => goto(`/locations/${adventure.id}`)}
>
<Eye class="w-4 h-4" />
{$t('map.view_details')}
@@ -288,12 +357,12 @@
{/if}
{#each visitedRegions as region}
{#if showGeo}
{#if showRegions}
<Marker
lngLat={[region.longitude, region.latitude]}
class="grid h-8 w-8 place-items-center rounded-full border border-gray-200 bg-green-300 hover:bg-green-400 text-black shadow-lg cursor-pointer transition-transform hover:scale-110"
>
<Location class="w-5 h-5 text-green-700" />
<LocationIcon class="w-5 h-5 text-green-700" />
<Popup openOn="click" offset={[0, -10]}>
<div class="space-y-2">
<div class="text-lg text-black font-bold">{region.name}</div>
@@ -303,6 +372,39 @@
</Marker>
{/if}
{/each}
{#if showCities}
{#each visitedCities as city}
<Marker
lngLat={[city.longitude, city.latitude]}
class="grid h-8 w-8 place-items-center rounded-full border border-gray-200 bg-blue-300 hover:bg-blue-400 text-black shadow-lg cursor-pointer transition-transform hover:scale-110"
>
<LocationIcon class="w-5 h-5 text-blue-700" />
<Popup openOn="click" offset={[0, -10]}>
<div class="space-y-2">
<div class="text-lg text-black font-bold">{city.name}</div>
<div class="badge badge-success badge-sm">{city.id}</div>
</div>
</Popup>
</Marker>
{/each}
{/if}
{#if showActivities}
{#each activities as activity}
{#if activity.geojson}
<GeoJSON data={activity.geojson}>
<LineLayer
paint={{
'line-color': getActivityColor(activity.sport_type),
'line-width': 3,
'line-opacity': 0.8
}}
/>
</GeoJSON>
{/if}
{/each}
{/if}
</MapLibre>
</div>
</div>
@@ -401,22 +503,49 @@
<label class="label cursor-pointer justify-start gap-3">
<input
type="checkbox"
bind:checked={showGeo}
bind:checked={showRegions}
class="checkbox checkbox-accent checkbox-sm"
/>
<span class="label-text flex items-center gap-2">
<Location class="w-4 h-4" />
{$t('map.show_visited_regions')} ({totalRegions})
<LocationIcon class="w-4 h-4" />
{$t('profile.visited_regions')} ({totalRegions})
</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="checkbox"
bind:checked={showCities}
class="checkbox checkbox-warning checkbox-sm"
/>
<span class="label-text flex items-center gap-2">
<LocationIcon class="w-4 h-4" />
{$t('map.show_visited_cities')}
{visitedCities.length > 0 ? ` (${visitedCities.length})` : ''}
</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input
type="checkbox"
bind:checked={showActivities}
class="checkbox checkbox-error checkbox-sm"
/>
<span class="label-text flex items-center gap-2">
<ActivityIcon class="w-4 h-4" />
{$t('settings.activities')}{activities.length > 0
? ` (${activities.length})`
: ''}
</span>
</label>
</div>
</div>
<!-- New Adventure Section -->
<!-- New Location Section -->
<div class="card bg-base-200/50 p-4">
<h3 class="font-semibold text-lg mb-4 flex items-center gap-2">
<Plus class="w-5 h-5" />
Add Adventure
{$t('adventures.new_location')}
</h3>
{#if newMarker}
@@ -427,7 +556,7 @@
</div>
<button type="button" class="btn btn-primary w-full gap-2" on:click={newAdventure}>
<Plus class="w-4 h-4" />
{$t('map.add_adventure_at_marker')}
{$t('map.add_location_at_marker')}
</button>
<button type="button" class="btn btn-ghost w-full gap-2" on:click={clearMarker}>
<Clear class="w-4 h-4" />
@@ -437,7 +566,7 @@
{:else}
<div class="space-y-3">
<p class="text-sm text-base-content/60">
{$t('map.place_marker_desc')}
{$t('map.place_marker_desc_location')}
</p>
<button
type="button"
@@ -445,7 +574,7 @@
on:click={() => (createModalOpen = true)}
>
<Plus class="w-4 h-4" />
{$t('map.add_adventure')}
{$t('map.add_location')}
</button>
</div>
{/if}
@@ -457,10 +586,12 @@
</div>
{#if createModalOpen}
<AdventureModal
<NewLocationModal
on:close={() => (createModalOpen = false)}
on:save={createNewAdventure}
{initialLatLng}
user={data.user}
bind:location={locationBeingUpdated}
/>
{/if}

View File

@@ -1,8 +1,8 @@
<script lang="ts">
export let data;
import AdventureCard from '$lib/components/AdventureCard.svelte';
import LocationCard from '$lib/components/LocationCard.svelte';
import CollectionCard from '$lib/components/CollectionCard.svelte';
import type { Adventure, Collection, User } from '$lib/types.js';
import type { Location, Collection, User } from '$lib/types.js';
import { t } from 'svelte-i18n';
import { onMount } from 'svelte';
import { gsap } from 'gsap';
@@ -18,23 +18,206 @@
import TrendingUp from '~icons/mdi/trending-up';
import Share from '~icons/mdi/share-variant';
import Award from '~icons/mdi/award';
import Run from '~icons/mdi/run';
import Timer from '~icons/mdi/timer-outline';
import TrendingUpOutline from '~icons/mdi/trending-up';
import Mountain from '~icons/mdi/mountain';
import Walk from '~icons/mdi/walk';
import Bike from '~icons/mdi/bike';
import Snowflake from '~icons/mdi/snowflake';
import WaterOutline from '~icons/mdi/water-outline';
import Dumbbell from '~icons/mdi/dumbbell';
import TennisOutline from '~icons/mdi/tennis';
import RockClimbing from '~icons/mdi/image-filter-hdr';
import Soccer from '~icons/mdi/soccer';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import Fire from '~icons/mdi/fire';
import ChevronDown from '~icons/mdi/chevron-down';
import ChevronUp from '~icons/mdi/chevron-up';
let measurementSystem = data.user?.measurement_system || 'metric';
let expandedCategories = new Set();
let stats: {
visited_country_count: number;
total_regions: number;
trips_count: number;
adventure_count: number;
location_count: number;
visited_region_count: number;
total_countries: number;
visited_city_count: number;
total_cities: number;
activities_overall: {
total_count: number;
total_distance: number;
total_moving_time: number;
total_elevation_gain: number;
total_elevation_loss: number;
total_calories: number;
};
activities_by_category: Record<
string,
{
count: number;
total_distance: number;
total_moving_time: number;
total_elevation_gain: number;
total_elevation_loss: number;
avg_distance: number;
max_distance: number;
avg_elevation_gain: number;
max_elevation_gain: number;
avg_speed: number;
max_speed: number;
total_calories: number;
sports: Record<
string,
{
count: number;
total_distance: number;
total_elevation_gain: number;
}
>;
}
>;
// Legacy fields
activity_count: number;
activity_distance: number;
activity_moving_time: number;
activity_elevation: number;
} | null;
const user: User = data.user;
const adventures: Adventure[] = data.adventures;
const adventures: Location[] = data.adventures;
const collections: Collection[] = data.collections;
stats = data.stats || null;
// Activity category configurations
const categoryConfig: Record<
string,
{
name: string;
icon: any;
color: string;
bgGradient: string;
borderColor: string;
}
> = {
running: {
name: 'Running',
icon: Run,
color: 'error',
bgGradient: 'from-error/10 to-error/5',
borderColor: 'border-error/20'
},
walking_hiking: {
name: 'Walking & Hiking',
icon: Walk,
color: 'success',
bgGradient: 'from-success/10 to-success/5',
borderColor: 'border-success/20'
},
cycling: {
name: 'Cycling',
icon: Bike,
color: 'info',
bgGradient: 'from-info/10 to-info/5',
borderColor: 'border-info/20'
},
winter_sports: {
name: 'Winter Sports',
icon: Snowflake,
color: 'primary',
bgGradient: 'from-primary/10 to-primary/5',
borderColor: 'border-primary/20'
},
water_sports: {
name: 'Water Sports',
icon: WaterOutline,
color: 'accent',
bgGradient: 'from-accent/10 to-accent/5',
borderColor: 'border-accent/20'
},
fitness_gym: {
name: 'Fitness & Gym',
icon: Dumbbell,
color: 'warning',
bgGradient: 'from-warning/10 to-warning/5',
borderColor: 'border-warning/20'
},
racket_sports: {
name: 'Racket Sports',
icon: TennisOutline,
color: 'secondary',
bgGradient: 'from-secondary/10 to-secondary/5',
borderColor: 'border-secondary/20'
},
climbing_adventure: {
name: 'Climbing & Adventure',
icon: RockClimbing,
color: 'orange-500',
bgGradient: 'from-orange-500/10 to-orange-500/5',
borderColor: 'border-orange-500/20'
},
team_sports: {
name: 'Team Sports',
icon: Soccer,
color: 'green-500',
bgGradient: 'from-green-500/10 to-green-500/5',
borderColor: 'border-green-500/20'
},
other_sports: {
name: 'Other Sports',
icon: DotsHorizontal,
color: 'purple-500',
bgGradient: 'from-purple-500/10 to-purple-500/5',
borderColor: 'border-purple-500/20'
}
};
function toggleCategory(category: string) {
if (expandedCategories.has(category)) {
expandedCategories.delete(category);
} else {
expandedCategories.add(category);
}
expandedCategories = expandedCategories; // Trigger reactivity
}
// function to take in meters for distance and return it in either kilometers or miles
function getDistance(meters: number): string {
return measurementSystem === 'imperial'
? `${(meters * 0.000621371).toFixed(2)} mi`
: `${(meters / 1000).toFixed(2)} km`;
}
function getElevation(meters: number): string {
return measurementSystem === 'imperial'
? `${(meters * 3.28084).toFixed(1)} ft`
: `${meters.toFixed(1)} m`;
}
// Function to format time from seconds to readable format
function formatTime(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
}
function getSpeed(ms: number): string {
if (measurementSystem === 'imperial') {
const mph = ms * 2.237;
return `${mph.toFixed(1)} mph`;
} else {
const kmh = ms * 3.6;
return `${kmh.toFixed(1)} km/h`;
}
}
// Calculate achievements
$: worldExplorationPercentage = stats
? Math.round((stats.visited_country_count / stats.total_countries) * 100)
@@ -48,34 +231,34 @@
// Achievement levels
$: achievementLevel =
(stats?.adventure_count ?? 0) >= 100
(stats?.location_count ?? 0) >= 100
? 'Legendary Explorer'
: (stats?.adventure_count ?? 0) >= 75
: (stats?.location_count ?? 0) >= 75
? 'World Wanderer'
: (stats?.adventure_count ?? 0) >= 50
: (stats?.location_count ?? 0) >= 50
? 'Explorer Master'
: (stats?.adventure_count ?? 0) >= 35
: (stats?.location_count ?? 0) >= 35
? 'Globetrotter'
: (stats?.adventure_count ?? 0) >= 25
: (stats?.location_count ?? 0) >= 25
? 'Seasoned Traveler'
: (stats?.adventure_count ?? 0) >= 15
: (stats?.location_count ?? 0) >= 15
? 'Adventure Seeker'
: (stats?.adventure_count ?? 0) >= 10
: (stats?.location_count ?? 0) >= 10
? 'Trailblazer'
: (stats?.adventure_count ?? 0) >= 5
: (stats?.location_count ?? 0) >= 5
? 'Journey Starter'
: (stats?.adventure_count ?? 0) >= 1
: (stats?.location_count ?? 0) >= 1
? 'Travel Enthusiast'
: 'New Explorer';
$: achievementColor =
(stats?.adventure_count ?? 0) >= 50
(stats?.location_count ?? 0) >= 50
? 'text-warning'
: (stats?.adventure_count ?? 0) >= 25
: (stats?.location_count ?? 0) >= 25
? 'text-success'
: (stats?.adventure_count ?? 0) >= 10
: (stats?.location_count ?? 0) >= 10
? 'text-info'
: (stats?.adventure_count ?? 0) >= 5
: (stats?.location_count ?? 0) >= 5
? 'text-secondary'
: 'text-primary';
</script>
@@ -159,7 +342,7 @@
{/if}
<!-- User rank achievement -->
{#if stats && stats.adventure_count > 0}
{#if stats && stats.location_count > 0}
<div class="flex items-center justify-center gap-2 text-base-content/70">
<Award class="w-5 h-5" />
<span class={`text-lg ${achievementColor}`}>{achievementLevel}</span>
@@ -189,9 +372,9 @@
<div class="flex items-center justify-between">
<div>
<div class="text-primary/70 font-medium text-sm uppercase tracking-wide">
{$t('navbar.adventures')}
{$t('locations.locations')}
</div>
<div class="text-4xl font-bold text-primary">{stats.adventure_count}</div>
<div class="text-4xl font-bold text-primary">{stats.location_count}</div>
<div class="text-primary/60 mt-2 flex items-center gap-1">
<TrendingUp class="w-4 h-4" />
{achievementLevel}
@@ -258,7 +441,7 @@
</div>
<!-- Secondary Stats -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
<!-- Regions -->
<div
class="stat-card card bg-gradient-to-br from-info/10 to-info/5 shadow-xl border border-info/20 hover:shadow-2xl transition-all duration-300"
@@ -320,6 +503,256 @@
</div>
</div>
</div>
<!-- Enhanced Activity Stats Section -->
{#if stats.activities_overall && stats.activities_overall.total_count > 0}
<div class="mb-8">
<div class="text-center mb-6">
<h3 class="text-2xl font-bold mb-2">{$t('adventures.activity_statistics')}</h3>
<p class="text-base-content/60">{$t('adventures.activity_statistics_description')}</p>
</div>
<!-- Overall Activity Summary -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<!-- Total Activities -->
<div
class="stat-card card bg-gradient-to-br from-accent/10 to-accent/5 shadow-xl border border-accent/20 hover:shadow-2xl transition-all duration-300"
>
<div class="card-body p-6">
<div class="flex items-center justify-between">
<div>
<div class="text-accent/70 font-medium text-sm uppercase tracking-wide">
{$t('adventures.total_activities')}
</div>
<div class="text-3xl font-bold text-accent">
{stats.activities_overall.total_count}
</div>
<div class="text-accent/60 mt-2">{$t('adventures.recorded_sessions')}</div>
</div>
<div class="p-3 bg-accent/20 rounded-2xl">
<Run class="w-6 h-6 text-accent" />
</div>
</div>
</div>
</div>
<!-- Total Distance -->
<div
class="stat-card card bg-gradient-to-br from-error/10 to-error/5 shadow-xl border border-error/20 hover:shadow-2xl transition-all duration-300"
>
<div class="card-body p-6">
<div class="flex items-center justify-between">
<div>
<div class="text-error/70 font-medium text-sm uppercase tracking-wide">
{$t('adventures.total_distance')}
</div>
<div class="text-3xl font-bold text-error">
{getDistance(stats.activities_overall.total_distance)}
</div>
<div class="text-error/60 mt-2">{$t('adventures.distance_covered')}</div>
</div>
<div class="p-3 bg-error/20 rounded-2xl">
<TrendingUpOutline class="w-6 h-6 text-error" />
</div>
</div>
</div>
</div>
<!-- Moving Time -->
<div
class="stat-card card bg-gradient-to-br from-purple-500/10 to-purple-500/5 shadow-xl border border-purple-500/20 hover:shadow-2xl transition-all duration-300"
>
<div class="card-body p-6">
<div class="flex items-center justify-between">
<div>
<div class="text-purple-500/70 font-medium text-sm uppercase tracking-wide">
{$t('adventures.moving_time')}
</div>
<div class="text-3xl font-bold text-purple-500">
{formatTime(stats.activities_overall.total_moving_time)}
</div>
<div class="text-purple-500/60 mt-2">{$t('adventures.active_duration')}</div>
</div>
<div class="p-3 bg-purple-500/20 rounded-2xl">
<Timer class="w-6 h-6 text-purple-500" />
</div>
</div>
</div>
</div>
<!-- Elevation Gain -->
<div
class="stat-card card bg-gradient-to-br from-orange-500/10 to-orange-500/5 shadow-xl border border-orange-500/20 hover:shadow-2xl transition-all duration-300"
>
<div class="card-body p-6">
<div class="flex items-center justify-between">
<div>
<div class="text-orange-500/70 font-medium text-sm uppercase tracking-wide">
{$t('adventures.elevation_gain')}
</div>
<div class="text-3xl font-bold text-orange-500">
{getElevation(stats.activities_overall.total_elevation_gain)}
</div>
<div class="text-orange-500/60 mt-2">{$t('adventures.total_climbed')}</div>
</div>
<div class="p-3 bg-orange-500/20 rounded-2xl">
<Mountain class="w-6 h-6 text-orange-500" />
</div>
</div>
</div>
</div>
</div>
<!-- Activity Categories -->
<div class="space-y-4">
<h4 class="text-xl font-bold text-center mb-6">
{$t('adventures.activity_breakdown_by_category')}
</h4>
{#each Object.entries(stats.activities_by_category) as [categoryKey, categoryData]}
{@const config = categoryConfig[categoryKey]}
{@const isExpanded = expandedCategories.has(categoryKey)}
<div
class="card bg-gradient-to-br {config.bgGradient} shadow-xl border {config.borderColor} hover:shadow-2xl transition-all duration-300"
>
<div class="card-body p-6">
<!-- Category Header -->
<div
class="flex items-center justify-between cursor-pointer"
role="button"
tabindex="0"
on:click={() => toggleCategory(categoryKey)}
on:keydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleCategory(categoryKey);
}
}}
>
<div class="flex items-center gap-4">
<div class="p-3 bg-{config.color}/20 rounded-2xl">
<svelte:component
this={config.icon}
class="w-6 h-6 text-{config.color}"
/>
</div>
<div>
<h5 class="text-xl font-bold text-{config.color}">{config.name}</h5>
<p class="text-{config.color}/60">
{categoryData.count}
{$t('adventures.activities_text')}
</p>
</div>
</div>
<div class="flex items-center gap-4">
<div class="text-right">
<div class="text-2xl font-bold text-{config.color}">
{getDistance(categoryData.total_distance)}
</div>
<div class="text-{config.color}/60 text-sm">
{getElevation(categoryData.total_elevation_gain)}
{$t('adventures.elevation')}
</div>
</div>
<svelte:component
this={isExpanded ? ChevronUp : ChevronDown}
class="w-5 h-5 text-{config.color}/60"
/>
</div>
</div>
<!-- Expanded Details -->
{#if isExpanded}
<div class="mt-6 space-y-6">
<!-- Quick Stats Grid -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div
class="bg-{config.color}/5 rounded-lg p-4 border {config.borderColor}"
>
<div class="text-{config.color}/70 text-xs uppercase font-medium">
Time
</div>
<div class="text-lg font-bold text-{config.color}">
{formatTime(categoryData.total_moving_time)}
</div>
</div>
<div
class="bg-{config.color}/5 rounded-lg p-4 border {config.borderColor}"
>
<div class="text-{config.color}/70 text-xs uppercase font-medium">
Avg Speed
</div>
<div class="text-lg font-bold text-{config.color}">
{getSpeed(categoryData.avg_speed)}
</div>
</div>
<div
class="bg-{config.color}/5 rounded-lg p-4 border {config.borderColor}"
>
<div class="text-{config.color}/70 text-xs uppercase font-medium">
Max Distance
</div>
<div class="text-lg font-bold text-{config.color}">
{getDistance(categoryData.max_distance)}
</div>
</div>
{#if categoryData.total_calories > 0}
<div
class="bg-{config.color}/5 rounded-lg p-4 border {config.borderColor}"
>
<div class="text-{config.color}/70 text-xs uppercase font-medium">
{$t('adventures.calories')}
</div>
<div
class="text-lg font-bold text-{config.color} flex items-center gap-1"
>
<Fire class="w-4 h-4" />
{Math.round(categoryData.total_calories)}
</div>
</div>
{/if}
</div>
<!-- Individual Sports Breakdown -->
{#if Object.keys(categoryData.sports).length > 1}
<div>
<h6 class="font-semibold text-{config.color} mb-3">Sport Types</h6>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
{#each Object.entries(categoryData.sports) as [sportType, sportData]}
<div
class="bg-{config.color}/5 rounded-lg p-4 border {config.borderColor}"
>
<div class="flex justify-between items-start">
<div>
<div class="font-medium text-{config.color}">{sportType}</div>
<div class="text-{config.color}/60 text-sm">
{sportData.count}
{$t('adventures.activities_text')}
</div>
</div>
<div class="text-right">
<div class="font-bold text-{config.color}">
{getDistance(sportData.total_distance)}
</div>
<div class="text-{config.color}/60 text-xs">
{getElevation(sportData.total_elevation_gain)} elev
</div>
</div>
</div>
</div>
{/each}
</div>
</div>
{/if}
</div>
{/if}
</div>
</div>
{/each}
</div>
</div>
{/if}
</div>
{/if}
@@ -331,14 +764,14 @@
<Airplane class="w-6 h-6 text-primary" />
</div>
<div>
<h2 class="text-3xl font-bold">{$t('auth.user_adventures')}</h2>
<p class="text-base-content/60">{$t('profile.public_adventure_experiences')}</p>
<h2 class="text-3xl font-bold">{$t('auth.user_locations')}</h2>
<p class="text-base-content/60">{$t('profile.public_location_experiences')}</p>
</div>
</div>
{#if adventures && adventures.length > 0}
<div class="badge badge-primary badge-lg">
{adventures.length}
{adventures.length === 1 ? $t('adventures.adventure') : $t('navbar.adventures')}
{adventures.length === 1 ? $t('locations.location') : $t('locations.locations')}
</div>
{/if}
</div>
@@ -350,7 +783,7 @@
<Airplane class="w-16 h-16 text-base-content/30" />
</div>
<h3 class="text-xl font-bold text-base-content/70 mb-2">
{$t('auth.no_public_adventures')}
{$t('auth.no_public_locations')}
</h3>
<p class="text-base-content/50">{$t('profile.no_shared_adventures')}</p>
</div>
@@ -359,7 +792,7 @@
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
{#each adventures as adventure}
<div class="adventure-card">
<AdventureCard {adventure} user={null} />
<LocationCard {adventure} user={null} />
</div>
{/each}
</div>
@@ -410,3 +843,15 @@
</div>
</div>
</div>
<style>
.stat-card:hover {
transform: translateY(-2px);
}
.adventure-card:hover,
.collection-card:hover {
transform: translateY(-4px);
transition: all 0.3s ease;
}
</style>

View File

@@ -33,7 +33,7 @@ export const load = (async (event) => {
let data = await res.json();
return {
adventures: data.adventures,
locations: data.locations,
collections: data.collections,
users: data.users,
countries: data.countries,

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import AdventureCard from '$lib/components/AdventureCard.svelte';
import LocationCard from '$lib/components/LocationCard.svelte';
import RegionCard from '$lib/components/RegionCard.svelte';
import CityCard from '$lib/components/CityCard.svelte';
import CountryCard from '$lib/components/CountryCard.svelte';
@@ -9,7 +9,7 @@
import type { PageData } from './$types';
import { t } from 'svelte-i18n';
import type {
Adventure,
Location,
Collection,
User,
Country,
@@ -27,7 +27,7 @@
$: query = $page.url.searchParams.get('query') ?? '';
// Assign updated results from data, so when data changes, the displayed items update:
$: adventures = data.adventures as Adventure[];
$: locations = data.locations as Location[];
$: collections = data.collections as Collection[];
$: users = data.users as User[];
$: countries = data.countries as Country[];
@@ -38,7 +38,7 @@
// new stats
$: totalResults =
adventures.length +
locations.length +
collections.length +
users.length +
countries.length +
@@ -64,11 +64,13 @@
<h1
class="text-3xl font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent"
>
Search{query ? `: ${query}` : ''}
{$t('navbar.search')}{query ? `: ${query}` : ''}
</h1>
{#if hasResults}
<p class="text-sm text-base-content/60">
{totalResults} result{totalResults !== 1 ? 's' : ''} found
{totalResults}
{totalResults !== 1 ? $t('search.results') : $t('search.result')}
{$t('search.found')}
</p>
{/if}
</div>
@@ -87,22 +89,22 @@
{$t('adventures.no_results')}
</h3>
<p class="text-base-content/50 text-center max-w-md">
Try searching for adventures, collections, countries, regions, cities, or users.
{$t('search.try_searching_desc')}
</p>
</div>
{:else}
{#if adventures.length > 0}
{#if locations.length > 0}
<div class="mb-12">
<div class="flex items-center gap-3 mb-6">
<div class="p-2 bg-primary/10 rounded-lg">
<SearchIcon class="w-6 h-6 text-primary" />
</div>
<h2 class="text-2xl font-bold">Adventures</h2>
<div class="badge badge-primary">{adventures.length}</div>
<h2 class="text-2xl font-bold">{$t('locations.locations')}</h2>
<div class="badge badge-primary">{locations.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
{#each adventures as adventure}
<AdventureCard {adventure} user={null} />
{#each locations as adventure}
<LocationCard {adventure} user={null} />
{/each}
</div>
</div>
@@ -115,7 +117,7 @@
<!-- you can replace with a CollectionIcon -->
<SearchIcon class="w-6 h-6 text-secondary" />
</div>
<h2 class="text-2xl font-bold">Collections</h2>
<h2 class="text-2xl font-bold">{$t('navbar.collections')}</h2>
<div class="badge badge-secondary">{collections.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
@@ -133,7 +135,7 @@
<!-- you can replace with a GlobeIcon -->
<SearchIcon class="w-6 h-6 text-accent" />
</div>
<h2 class="text-2xl font-bold">Countries</h2>
<h2 class="text-2xl font-bold">{$t('search.countries')}</h2>
<div class="badge badge-accent">{countries.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
@@ -151,7 +153,7 @@
<!-- MapIcon -->
<SearchIcon class="w-6 h-6 text-info" />
</div>
<h2 class="text-2xl font-bold">Regions</h2>
<h2 class="text-2xl font-bold">{$t('map.regions')}</h2>
<div class="badge badge-info">{regions.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
@@ -172,7 +174,7 @@
<!-- CityIcon -->
<SearchIcon class="w-6 h-6 text-warning" />
</div>
<h2 class="text-2xl font-bold">Cities</h2>
<h2 class="text-2xl font-bold">{$t('search.cities')}</h2>
<div class="badge badge-warning">{cities.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
@@ -190,7 +192,7 @@
<!-- UserIcon -->
<SearchIcon class="w-6 h-6 text-success" />
</div>
<h2 class="text-2xl font-bold">Users</h2>
<h2 class="text-2xl font-bold">{$t('navbar.users')}</h2>
<div class="badge badge-success">{users.length}</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">

View File

@@ -80,6 +80,10 @@ export const load: PageServerLoad = async (event) => {
}
let integrations = await integrationsFetch.json();
let googleMapsEnabled = integrations.google_maps as boolean;
let stravaGlobalEnabled = integrations.strava.global as boolean;
let stravaUserEnabled = integrations.strava.user as boolean;
let wandererEnabled = integrations.wanderer.exists as boolean;
let wandererExpired = integrations.wanderer.expired as boolean;
let publicUrlFetch = await fetch(`${endpoint}/public-url/`);
let publicUrl = '';
@@ -98,7 +102,11 @@ export const load: PageServerLoad = async (event) => {
immichIntegration,
publicUrl,
socialProviders,
googleMapsEnabled
googleMapsEnabled,
stravaGlobalEnabled,
stravaUserEnabled,
wandererEnabled,
wandererExpired
}
};
};
@@ -121,6 +129,7 @@ export const actions: Actions = {
let last_name = formData.get('last_name') as string | null | undefined;
let profile_pic = formData.get('profile_pic') as File | null | undefined;
let public_profile = formData.get('public_profile') as string | null | undefined | boolean;
let measurement_system = formData.get('measurement_system') as string | null | undefined;
const resCurrent = await fetch(`${endpoint}/auth/user-metadata/`, {
headers: {
@@ -140,6 +149,13 @@ export const actions: Actions = {
public_profile = false;
}
// Gets the boolean value of the measurement_system input checked means imperial
if (measurement_system === 'on') {
measurement_system = 'imperial';
} else {
measurement_system = 'metric';
}
let currentUser = (await resCurrent.json()) as User;
if (username === currentUser.username || !username) {
@@ -170,6 +186,7 @@ export const actions: Actions = {
formDataToSend.append('profile_pic', profile_pic);
}
formDataToSend.append('public_profile', public_profile.toString());
formDataToSend.append('measurement_system', measurement_system.toString());
let csrfToken = await fetchCSRFToken();
@@ -262,7 +279,7 @@ export const actions: Actions = {
return { success: true };
}
},
changeEmail: async (event) => {
restoreData: async (event) => {
if (!event.locals.user) {
return redirect(302, '/');
}
@@ -270,28 +287,51 @@ export const actions: Actions = {
if (!sessionId) {
return redirect(302, '/');
}
const formData = await event.request.formData();
const new_email = formData.get('new_email') as string | null | undefined;
if (!new_email) {
return fail(400, { message: 'auth.email_required' });
} else {
try {
const formData = await event.request.formData();
const file = formData.get('file') as File | null | undefined;
const confirm = formData.get('confirm') as string | null | undefined;
if (!file || file.size === 0) {
return fail(400, { message: 'settings.no_file_selected' });
}
if (confirm !== 'yes') {
return fail(400, { message: 'settings.confirmation_required' });
}
let csrfToken = await fetchCSRFToken();
let res = await fetch(`${endpoint}/auth/change-email/`, {
// Create FormData for the API request
const apiFormData = new FormData();
apiFormData.append('file', file);
apiFormData.append('confirm', 'yes');
let res = await fetch(`${endpoint}/api/backup/import/`, {
method: 'POST',
headers: {
Referer: event.url.origin, // Include Referer header
Referer: event.url.origin,
Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify({
new_email
})
body: apiFormData
});
if (!res.ok) {
return fail(res.status, await res.json());
const errorData = await res.json();
return fail(res.status, {
message: errorData.code
? `settings.restore_error_${errorData.code}`
: 'settings.generic_error',
details: errorData
});
}
return { success: true };
} catch (error) {
console.error('Restore error:', error);
return fail(500, { message: 'settings.generic_error' });
}
}
};

View File

@@ -10,6 +10,8 @@
import { appTitle, appVersion, copyrightYear } from '$lib/config.js';
import ImmichLogo from '$lib/assets/immich.svg';
import GoogleMapsLogo from '$lib/assets/google_maps.svg';
import StravaLogo from '$lib/assets/strava.svg';
import WandererLogo from '$lib/assets/wanderer.svg';
export let data;
console.log(data);
@@ -20,13 +22,34 @@
emails = data.props.emails;
}
let new_password_disable_setting: boolean = false;
let new_email: string = '';
let public_url: string = data.props.publicUrl;
let immichIntegration = data.props.immichIntegration;
let googleMapsEnabled = data.props.googleMapsEnabled;
let stravaGlobalEnabled = data.props.stravaGlobalEnabled;
let stravaUserEnabled = data.props.stravaUserEnabled;
let wandererEnabled = data.props.wandererEnabled;
let wandererExpired = data.props.wandererExpired;
let activeSection: string = 'profile';
// Initialize activeSection from URL on mount
onMount(() => {
if (browser && $page.url.searchParams.has('tab')) {
activeSection = $page.url.searchParams.get('tab') || 'profile';
}
});
function setActiveSection(sectionId: string) {
activeSection = sectionId;
if (browser) {
const url = new URL($page.url);
url.searchParams.set('tab', sectionId);
history.replaceState({}, '', url);
}
}
let acknowledgeRestoreOverride: boolean = false;
let newImmichIntegration: ImmichIntegration = {
server_url: '',
api_key: '',
@@ -34,6 +57,12 @@
copy_locally: true
};
let newWandererIntegration = {
server_url: '',
username: '',
password: ''
};
let isMFAModalOpen: boolean = false;
const sections = [
@@ -41,6 +70,7 @@
{ id: 'security', icon: '🔒', label: () => $t('settings.security') },
{ id: 'emails', icon: '📧', label: () => $t('settings.emails') },
{ id: 'integrations', icon: '🔗', label: () => $t('settings.integrations') },
{ id: 'import_export', icon: '📦', label: () => $t('settings.backup_restore') },
{ id: 'admin', icon: '⚙️', label: () => $t('settings.admin') },
{ id: 'advanced', icon: '🛠️', label: () => $t('settings.advanced') }
];
@@ -269,6 +299,91 @@
addToast('error', $t('settings.generic_error'));
}
}
async function stravaAuthorizeRedirect() {
const res = await fetch('/api/integrations/strava/authorize/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
const data = await res.json();
window.location.href = data.auth_url;
} else {
addToast('error', $t('strava.authorization_error'));
}
}
async function stravaDisconnect() {
const res = await fetch('/api/integrations/strava/disable/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
addToast('success', $t('strava.disconnected'));
stravaUserEnabled = false;
} else {
addToast('error', $t('strava.disconnect_error'));
}
}
async function wandererDisconnect() {
const res = await fetch('/api/integrations/wanderer/disable/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.ok) {
addToast('success', $t('wanderer.disconnected'));
wandererEnabled = false;
} else {
addToast('error', $t('wanderer.disconnect_error'));
}
}
async function wandererConnect() {
const res = await fetch('/api/integrations/wanderer/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newWandererIntegration)
});
if (res.ok) {
addToast('success', $t('wanderer.connected'));
wandererEnabled = true;
newWandererIntegration = { server_url: '', username: '', password: '' };
} else {
const data = await res.json();
addToast('error', $t('wanderer.connection_error'));
}
}
async function wandererRefresh() {
if (wandererEnabled) {
const res = await fetch(`/api/integrations/wanderer/refresh/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
password: newWandererIntegration.password
})
});
if (res.ok) {
addToast('success', $t('wanderer.refreshed'));
newWandererIntegration.password = '';
wandererExpired = false;
} else {
addToast('error', $t('wanderer.refresh_error'));
}
newWandererIntegration.password = '';
}
}
</script>
{#if isMFAModalOpen}
@@ -309,7 +424,7 @@
section.id
? 'bg-primary text-primary-content shadow-lg'
: 'hover:bg-base-200'}"
on:click={() => (activeSection = section.id)}
on:click={() => setActiveSection(section.id)}
>
<span class="text-xl">{section.icon}</span>
<span class="font-medium">{section.label()}</span>
@@ -400,23 +515,44 @@
accept="image/*"
/>
</div>
</div>
<div class="form-control">
<label class="label cursor-pointer justify-start gap-4">
<input
type="checkbox"
bind:checked={user.public_profile}
name="public_profile"
class="toggle toggle-primary"
/>
<div>
<span class="label-text font-medium">{$t('auth.public_profile')}</span>
<p class="text-sm text-base-content/60">
{$t('settings.public_profile_desc')}
</p>
</div>
</label>
<div class="form-control">
<label class="label cursor-pointer justify-start gap-4">
<input
type="checkbox"
bind:checked={user.public_profile}
name="public_profile"
class="toggle toggle-primary"
/>
<div>
<span class="label-text font-medium">{$t('auth.public_profile')}</span>
<p class="text-sm text-base-content/60">
{$t('settings.public_profile_desc')}
</p>
</div>
</label>
</div>
<!-- metric or imperal toggle -->
<div class="form-control">
<label class="label cursor-pointer justify-start gap-4">
<input
type="checkbox"
checked={user.measurement_system === 'imperial'}
name="measurement_system"
class="toggle toggle-primary"
on:change={() =>
(user.measurement_system =
user.measurement_system === 'metric' ? 'imperial' : 'metric')}
/>
<div>
<span class="label-text font-medium">{$t('settings.use_imperial')}</span>
<p class="text-sm text-base-content/60">
{$t('settings.use_imperial_desc')}
</p>
</div>
</label>
</div>
</div>
<button class="btn btn-primary btn-wide">
@@ -895,7 +1031,7 @@
</div>
<!-- Google maps integration - displayt only if its connected -->
<div class="p-6 bg-base-200 rounded-xl">
<div class="p-6 bg-base-200 rounded-xl mb-4">
<div class="flex items-center gap-4 mb-4">
<img src={GoogleMapsLogo} alt="Google Maps" class="w-8 h-8" />
<div>
@@ -910,15 +1046,403 @@
<div class="badge badge-error ml-auto">{$t('settings.disconnected')}</div>
{/if}
</div>
<div class="mt-4 p-4 bg-info/10 rounded-lg">
<p class="text-sm">
📖 {$t('immich.need_help')}
<a
class="link link-primary"
href="https://adventurelog.app/docs/configuration/google_maps_integration.html"
target="_blank">{$t('navbar.documentation')}</a
>
{#if user.is_staff || !googleMapsEnabled}
<div class="mt-4 p-4 bg-info/10 rounded-lg">
{#if user.is_staff}
<p class="text-sm">
📖 {$t('immich.need_help')}
<a
class="link link-primary"
href="https://adventurelog.app/docs/configuration/google_maps_integration.html"
target="_blank">{$t('navbar.documentation')}</a
>
</p>
{:else if !googleMapsEnabled}
<p class="text-sm">
{$t('google_maps.google_maps_integration_desc_no_staff')}
</p>
{/if}
</div>
{/if}
</div>
<!-- Strava Integration Section -->
<div class="p-6 bg-base-200 rounded-xl mb-4">
<div class="flex items-center gap-4 mb-4">
<img src={StravaLogo} alt="Strava" class="w-8 h-8 rounded-md" />
<div>
<h3 class="text-xl font-bold">Strava</h3>
<p class="text-sm text-base-content/70">
{$t('strava.strava_integration_desc')}
</p>
</div>
{#if stravaGlobalEnabled && stravaUserEnabled}
<div class="badge badge-success ml-auto">{$t('settings.connected')}</div>
{:else}
<div class="badge badge-error ml-auto">{$t('settings.disconnected')}</div>
{/if}
</div>
<!-- Content based on integration status -->
{#if !stravaGlobalEnabled}
<!-- Strava not enabled globally -->
<div class="text-center">
<p class="text-base-content/70 mb-4">
{$t('strava.not_enabled') ||
'Strava integration is not enabled on this instance.'}
</p>
</div>
{:else if !stravaUserEnabled && stravaGlobalEnabled}
<!-- Globally enabled but user not connected -->
<div class="text-center">
<button class="btn btn-primary" on:click={stravaAuthorizeRedirect}>
🔗 {$t('strava.connect_account')}
</button>
</div>
{:else if stravaGlobalEnabled && stravaUserEnabled}
<!-- User connected - show management options -->
<div class="text-center">
<button class="btn btn-error" on:click={stravaDisconnect}>
❌ {$t('strava.disconnect')}
</button>
</div>
{/if}
<!-- Help documentation link -->
{#if user.is_staff || !stravaGlobalEnabled}
<div class="mt-4 p-4 bg-info/10 rounded-lg">
{#if user.is_staff}
<p class="text-sm">
📖 {$t('immich.need_help')}
<a
class="link link-primary"
href="https://adventurelog.app/docs/configuration/strava_integration.html"
target="_blank">{$t('navbar.documentation')}</a
>
</p>
{:else if !stravaGlobalEnabled}
<p class="text-sm">
{$t('google_maps.google_maps_integration_desc_no_staff')}
</p>
{/if}
</div>
{/if}
</div>
<div class="p-6 bg-base-200 rounded-xl">
<div class="flex items-center gap-4 mb-4">
<div
class="w-8 h-8 rounded-md bg-base-content"
style="mask: url({WandererLogo}) no-repeat center; mask-size: contain; -webkit-mask: url({WandererLogo}) no-repeat center; -webkit-mask-size: contain;"
></div>
<div>
<h3 class="text-xl font-bold">Wanderer</h3>
<p class="text-sm text-base-content/70">
{$t('wanderer.wanderer_integration_desc')}
</p>
</div>
{#if wandererEnabled}
<div class="badge badge-success ml-auto">{$t('settings.connected')}</div>
{:else}
<div class="badge badge-error ml-auto">{$t('settings.disconnected')}</div>
{/if}
</div>
{#if wandererEnabled && wandererExpired}
<div class="space-y-4 mb-4">
<div class="form-control">
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">Password</span>
</label>
<input
type="password"
class="input input-bordered input-primary focus:input-primary"
placeholder="Enter your password"
bind:value={newWandererIntegration.password}
/>
</div>
<button class="btn btn-primary w-full" on:click={wandererRefresh}>
🔗 Wanderer Reauth
</button>
</div>
{/if}
<!-- Content based on integration status -->
{#if !wandererEnabled}
<!-- login form with server url username and password -->
<div class="space-y-4">
<div class="form-control">
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">Server URL</span>
</label>
<input
type="url"
class="input input-bordered input-primary focus:input-primary"
placeholder="https://wanderer.example.com"
bind:value={newWandererIntegration.server_url}
/>
</div>
<div class="form-control">
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t('auth.username')}</span>
</label>
<input
type="text"
class="input input-bordered input-primary focus:input-primary"
placeholder="Enter your username"
bind:value={newWandererIntegration.username}
/>
</div>
<div class="form-control">
<!-- svelte-ignore a11y-label-has-associated-control -->
<label class="label">
<span class="label-text font-medium">{$t('auth.password')}</span>
</label>
<input
type="password"
class="input input-bordered input-primary focus:input-primary"
placeholder="Enter your password"
bind:value={newWandererIntegration.password}
/>
</div>
<button class="btn btn-primary w-full" on:click={wandererConnect}>
🔗 {$t('adventures.connect_to_wanderer')}
</button>
</div>
{:else}
<!-- User connected - show management options -->
<div class="text-center">
<button class="btn btn-error" on:click={wandererDisconnect}>
❌ {$t('strava.disconnect')}
</button>
</div>
{/if}
<!-- Help documentation link -->
{#if user.is_staff || !stravaGlobalEnabled}
<div class="mt-4 p-4 bg-info/10 rounded-lg">
{#if user.is_staff}
<p class="text-sm">
📖 {$t('immich.need_help')}
<a
class="link link-primary"
href="https://adventurelog.app/docs/configuration/wanderer_integration.html"
target="_blank">{$t('navbar.documentation')}</a
>
</p>
{:else if !stravaGlobalEnabled}
<p class="text-sm">
{$t('google_maps.google_maps_integration_desc_no_staff')}
</p>
{/if}
</div>
{/if}
</div>
</div>
{/if}
<!-- import export -->
{#if activeSection === 'import_export'}
<div class="bg-base-100 rounded-2xl shadow-xl p-8">
<div class="flex items-center gap-4 mb-6">
<div class="p-3 bg-accent/10 rounded-xl">
<span class="text-2xl">📦</span>
</div>
<div>
<div>
<h2 class="text-2xl font-bold">{$t('settings.backup_restore')}</h2>
<p class="text-base-content/70">
{$t('settings.backup_restore_desc')}
</p>
</div>
</div>
</div>
<!-- Backup Coverage -->
<div class="bg-base-200 rounded-xl p-4 mb-6">
<h4 class="text-sm font-semibold mb-3 text-base-content/70">
{$t('settings.whats_included')}
</h4>
<div class="grid grid-cols-2 gap-4 text-sm">
<!-- Backed Up -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<span>📍 {$t('locations.locations')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>🚶 {$t('adventures.visits')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>📚 {$t('navbar.collections')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>🖼️ {$t('settings.media')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>🥾 {$t('settings.trails')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>⏱️ {$t('settings.activities')}</span>
<span>✅</span>
</div>
<div class="flex items-center justify-between">
<span>🌍 {$t('settings.world_travel_visits')}</span>
<span>✅</span>
</div>
</div>
<!-- Not Backed Up -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<span>⚙️ {$t('navbar.settings')}</span>
<span>❌</span>
</div>
<div class="flex items-center justify-between">
<span>👤 {$t('navbar.profile')}</span>
<span>❌</span>
</div>
<div class="flex items-center justify-between">
<span>🔗 {$t('settings.integrations_settings')}</span>
<span>❌</span>
</div>
<div class="flex items-center justify-between opacity-30">
<span></span>
<span></span>
</div>
</div>
</div>
</div>
<div class="space-y-6">
<!-- Backup Data -->
<div class="p-6 bg-base-200 rounded-xl">
<h3 class="text-lg font-semibold mb-4">📤 {$t('settings.backup_your_data')}</h3>
<p class="text-base-content/70 mb-4">
{$t('settings.backup_your_data_desc')}
</p>
<div class="flex gap-4">
<a class="btn btn-primary" href="/api/backup/export">
💾 {$t('settings_download_backup')}
</a>
</div>
</div>
<!-- Restore Data -->
<div class="p-6 bg-base-200 rounded-xl">
<h3 class="text-lg font-semibold mb-4">📥 {$t('settings.restore_data')}</h3>
<p class="text-base-content/70 mb-4">
{$t('settings.restore_data_desc')}
</p>
<!-- Warning Alert -->
<div class="alert alert-warning mb-4">
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
/>
</svg>
<div>
<h4 class="font-bold">⚠️ {$t('settings.data_override_warning')}</h4>
<p class="text-sm">
{$t('settings.data_override_warning_desc')}
</p>
</div>
</div>
<!-- File Upload Form -->
<form
method="post"
action="?/restoreData"
use:enhance
enctype="multipart/form-data"
class="space-y-4"
>
<div class="form-control">
<label class="label" for="backup-file">
<span class="label-text font-medium"
>{$t('settings.select_backup_file')}</span
>
</label>
<input
type="file"
name="file"
id="backup-file"
class="file-input file-input-bordered file-input-primary w-full"
accept=".zip"
required
/>
</div>
<!-- Acknowledgment Checkbox -->
<div class="form-control">
<label class="label cursor-pointer justify-start gap-4">
<input
type="checkbox"
name="confirm"
value="yes"
class="checkbox checkbox-warning"
required
bind:checked={acknowledgeRestoreOverride}
/>
<div>
<span class="label-text font-medium text-warning"
>{$t('settings.data_override_acknowledge')}</span
>
<p class="text-xs text-base-content/60 mt-1">
{$t('settings.data_override_acknowledge_desc')}
</p>
</div>
</label>
</div>
{#if $page.form?.message && $page.form?.message.includes('restore')}
<div class="alert alert-error">
<svg
xmlns="http://www.w3.org/2000/svg"
class="stroke-current shrink-0 h-6 w-6"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
<span>{$t($page.form?.message)}</span>
</div>
{/if}
<div class="flex gap-4">
<button
type="submit"
class="btn btn-warning"
disabled={!acknowledgeRestoreOverride}
>
🚀 {$t('settings.restore_data')}
</button>
</div>
</form>
</div>
</div>
</div>

View File

@@ -4,28 +4,16 @@
export let data;
console.log(data);
import { gsap } from 'gsap'; // Import GSAP
import { gsap } from 'gsap';
import { onMount } from 'svelte';
onMount(() => {
gsap.from('.card', {
opacity: 0,
y: 50,
duration: 1,
ease: 'power3.out'
});
gsap.from('.text-center', {
opacity: 0,
x: -50,
duration: 1,
ease: 'power2.out'
});
gsap.from('.input', {
opacity: 0,
y: 30,
duration: 1,
ease: 'power2.out'
});
// Minimal fade-in only
gsap.fromTo(
'.main-container',
{ opacity: 0 },
{ opacity: 1, duration: 0.6, ease: 'power2.out' }
);
});
import FileImageBox from '~icons/mdi/file-image-box';
@@ -47,155 +35,238 @@
<ImageInfoModal {background} on:close={() => (isImageInfoModalOpen = false)} />
{/if}
<div
class="min-h-screen bg-no-repeat bg-cover flex items-center justify-center"
style="background-image: url('{background.url}')"
>
<div
class="card card-compact m-12 w-full max-w-4xl bg-base-100 shadow-xl p-6 flex flex-col md:flex-row"
>
<div class="flex-1">
{#if !is_disabled}
<h3 class="text-center">AdventureLog</h3>
<article class="text-center text-4xl mb-4 font-extrabold">
<h1>{$t('auth.signup')}</h1>
</article>
<div class="min-h-screen bg-base-200">
<!-- Background image if provided -->
{#if background.url}
<div
class="fixed inset-0 bg-cover bg-center bg-no-repeat opacity-90"
style="background-image: url('{background.url}')"
></div>
{/if}
<div class="flex justify-center">
<form method="post" use:enhance class="w-full max-w-xs">
<label for="username">{$t('auth.username')}</label>
<input
name="username"
id="username"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="email">{$t('auth.email')}</label>
<input
name="email"
id="email"
type="email"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="first_name">{$t('auth.first_name')}</label>
<input
name="first_name"
id="first_name"
type="text"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="last_name">{$t('auth.last_name')}</label>
<input
name="last_name"
id="last_name"
type="text"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="password">{$t('auth.password')}</label>
<input
type="password"
name="password1"
id="password"
class="block input input-bordered w-full max-w-xs"
/><br />
<label for="password">{$t('auth.confirm_password')}</label>
<input
type="password"
name="password2"
id="password2"
class="block input input-bordered w-full max-w-xs"
/><br />
<div class="main-container relative z-10 min-h-screen flex items-center justify-center p-4">
<div class="w-full max-w-5xl">
<div class="card bg-base-100 shadow-2xl">
<div class="card-body p-0">
<div class="grid lg:grid-cols-2 min-h-[700px]">
<!-- Signup Section -->
<div class="p-8 lg:p-12 flex flex-col justify-center">
{#if !is_disabled}
<!-- Header -->
<div class="text-center mb-8">
<div class="mb-4">
<h1 class="text-3xl font-bold text-primary mb-1">AdventureLog</h1>
<div class="w-12 h-1 bg-primary mx-auto rounded"></div>
</div>
<h2 class="text-4xl font-bold text-base-content mb-2">{$t('auth.signup')}</h2>
</div>
<button class="py-2 px-4 btn btn-primary mr-2">{$t('auth.signup')}</button>
<!-- Form -->
<div class="max-w-sm mx-auto w-full">
<form method="post" use:enhance class="space-y-4">
<!-- Username -->
<div class="form-control">
<label class="label" for="username">
<span class="label-text font-medium">{$t('auth.username')}</span>
</label>
<input
name="username"
id="username"
type="text"
class="input input-bordered w-full focus:input-primary"
placeholder="Choose a username"
autocomplete="username"
required
/>
</div>
<div class="flex justify-between mt-4">
<p><a href="/login" class="underline">{$t('auth.login')}</a></p>
<p>
<a href="/user/reset-password" class="underline">{$t('auth.forgot_password')}</a>
</p>
<!-- Email -->
<div class="form-control">
<label class="label" for="email">
<span class="label-text font-medium">{$t('auth.email')}</span>
</label>
<input
name="email"
id="email"
type="email"
class="input input-bordered w-full focus:input-primary"
placeholder="Enter your email"
autocomplete="email"
required
/>
</div>
<!-- Name Fields Row -->
<div class="grid grid-cols-2 gap-3">
<div class="form-control">
<label class="label" for="first_name">
<span class="label-text font-medium">{$t('auth.first_name')}</span>
</label>
<input
name="first_name"
id="first_name"
type="text"
class="input input-bordered w-full focus:input-primary"
placeholder="First name"
autocomplete="given-name"
required
/>
</div>
<div class="form-control">
<label class="label" for="last_name">
<span class="label-text font-medium">{$t('auth.last_name')}</span>
</label>
<input
name="last_name"
id="last_name"
type="text"
class="input input-bordered w-full focus:input-primary"
placeholder="Last name"
autocomplete="family-name"
required
/>
</div>
</div>
<!-- Password -->
<div class="form-control">
<label class="label" for="password">
<span class="label-text font-medium">{$t('auth.password')}</span>
</label>
<input
type="password"
name="password1"
id="password"
class="input input-bordered w-full focus:input-primary"
placeholder="Create a password"
autocomplete="new-password"
required
/>
</div>
<!-- Confirm Password -->
<div class="form-control">
<label class="label" for="password2">
<span class="label-text font-medium">{$t('auth.confirm_password')}</span>
</label>
<input
type="password"
name="password2"
id="password2"
class="input input-bordered w-full focus:input-primary"
placeholder="Confirm your password"
autocomplete="new-password"
required
/>
</div>
<!-- Submit Button -->
<div class="form-control mt-6">
<button type="submit" class="btn btn-primary w-full">
{$t('auth.signup')}
</button>
</div>
<!-- Error Message -->
{#if $page.form?.message}
<div class="alert alert-error mt-4">
<span>{$t($page.form.message)}</span>
</div>
{/if}
<!-- Footer Links -->
<div class="flex justify-between text-sm mt-6 pt-4 border-t border-base-300">
<a href="/login" class="link link-primary">
{$t('auth.login')}
</a>
<a href="/user/reset-password" class="link link-primary">
{$t('auth.forgot_password')}
</a>
</div>
</form>
</div>
{:else}
<!-- Registration Disabled -->
<div class="text-center">
<div class="mb-6">
<div
class="w-16 h-16 mx-auto bg-warning/10 rounded-full flex items-center justify-center mb-4"
>
<svg
class="w-8 h-8 text-warning"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
/>
</svg>
</div>
<h1 class="text-4xl font-bold text-base-content mb-4">
{$t('auth.registration_disabled')}
</h1>
<p class="text-lg text-base-content/70 max-w-md mx-auto">
{is_disabled_message}
</p>
</div>
<div class="mt-8">
<a href="/login" class="btn btn-primary"> Go to Login </a>
</div>
</div>
{/if}
</div>
</form>
</div>
{#if $page.form?.message}
<div class="text-center text-error mt-4">{$t($page.form?.message)}</div>
{/if}
{:else}
<div class="flex justify-center">
<div class="text-center mb-4">
<h1 class="text-4xl font-extrabold">{$t('auth.registration_disabled')}</h1>
<p class="text-lg mt-4">{is_disabled_message}</p>
<!-- Info Section -->
<div
class="bg-primary/5 p-8 lg:p-12 flex items-center justify-center border-l border-base-300"
>
<div class="text-center max-w-md">
{#if quote && quote.quote}
<div class="space-y-4">
<div class="text-6xl text-primary/30 mb-2">"</div>
<blockquote class="text-lg font-medium text-base-content leading-relaxed">
{quote.quote}
</blockquote>
<footer class="text-base-content/70 font-medium">
{quote.author}
</footer>
</div>
{/if}
</div>
</div>
</div>
</div>
{/if}
</div>
<div class="flex-1 flex justify-center items-center mt-12 md:mt-0 md:ml-6">
<blockquote class="w-80 text-center text-2xl font-semibold break-words">
{#if quote != null}
{quote.quote}
{/if}
<footer class="text-sm mt-1">{quote.author}</footer>
</blockquote>
</div>
</div>
</div>
</div>
<div class="fixed bottom-4 right-4 z-[999]">
<div class="dropdown dropdown-left dropdown-end">
<button class="btn m-1 btn-circle btn-md" on:click={() => (isImageInfoModalOpen = true)}>
<!-- Image Info Button -->
{#if background.url}
<button
class="btn btn-circle btn-sm fixed bottom-4 right-4 bg-base-100/80 border-base-300 z-20"
on:click={() => (isImageInfoModalOpen = true)}
>
<FileImageBox class="w-4 h-4" />
</button>
</div>
{/if}
</div>
<svelte:head>
<title>Signup</title>
<meta name="description" content="Signup for AdventureLog to explore the world!" />
<title>Sign Up | AdventureLog</title>
<meta
name="description"
content="Sign up for AdventureLog to explore the world and document your adventures!"
/>
</svelte:head>
<!-- <form method="post" use:enhance class="w-full max-w-xs">
<label for="username">Username</label>
<input
name="username"
id="username"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br />
<label for="first_name">Email</label>
<input
name="email"
id="email"
type="email"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br />
<label for="first_name">First Name</label>
<input
name="first_name"
id="first_name"
type="text"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br />
<label for="first_name">Last Name</label>
<input
name="last_name"
id="last_name"
type="text"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br />
<label for="password">Password</label>
<input
type="password"
name="password1"
id="password1"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br /><label for="password">Confirm Password</label>
<input
type="password"
name="password2"
id="password2"
class="block mb-2 input input-bordered w-full max-w-xs"
/><br />
<button class="py-2 px-4 btn btn-primary">Signup</button>
{#if $page.form?.message}
<div class="text-center text-error mt-4">{$page.form?.message}</div>
{/if}
</form> -->
<style>
.input:focus {
outline: 2px solid hsl(var(--p));
outline-offset: 2px;
}
</style>