[v0.12.0 pre] Planning & Itinerary Overhaul, Recommendation Engine, OIDC Enhancements, and More (#931)

* Fixes [REQUEST] Email-based auto-linking for OIDC
Fixes #921

* Add ClusterMap integration for regions and cities with fit-to-bounds functionality

* Update COUNTRY_REGION_JSON_VERSION to v3.0 and modify state ID generation to use ISO2 code

* fix: handle email verification required case during signup

Updated the signup action to return a specific message when the backend responds with a 401 status, indicating that the signup succeeded but email verification is required. This allows the frontend to display the appropriate message using an i18n key.

* feat: add Advanced Configuration documentation with optional environment variables

* Fixes #511

* fix: update appVersion to v0.11.0-main-121425 and enhance socialProviders handling in settings page

* feat: implement social signup controls and update documentation for new environment variables

* fix: update LocationCard props and enhance restore data functionality

- Changed the user prop to null in LocationCard component on the dashboard page.
- Added isRestoring state to manage loading state during data restoration in settings.
- Updated the restore button to show a loading spinner when a restore operation is in progress.

* fix: update appVersion to v0.12.0-pre-dev-121625

* feat: implement itinerary planning feature with CollectionItineraryPlanner component and related updates

* feat: add overnight lodging indicator and functionality to CollectionItineraryPlanner

* feat: add compact display option to LocationCard and enhance lodging filtering in CollectionItineraryPlanner

* feat(itinerary): add itinerary management features and link modal

- Introduced ItineraryViewSet for managing itinerary items with create and reorder functionalities.
- Added itinerary linking capabilities in CollectionModal and CollectionItineraryPlanner components.
- Implemented new ItineraryLinkModal for linking existing items to specific dates.
- Enhanced the frontend with new modals for creating locations, lodging, transportation, notes, and checklists.
- Updated the backend to handle itinerary item creation and reordering with appropriate permissions.
- Improved data handling for unscheduled items and their association with the itinerary.
- Added new dependencies to the frontend for enhanced functionality.

* feat(itinerary): implement auto-generate functionality for itinerary items based on dated records

* feat(collection): enhance collection sharing logic and improve data handling on invite acceptance

* fix: update appVersion to correct pre-dev version

* feat(wikipedia): implement image selection from Wikipedia with enhanced results display

* Refactor code structure for improved readability and maintainability

* feat: add CollectionRecommendationView component for displaying location recommendations

- Implemented CollectionRecommendationView.svelte to handle location recommendations based on user input and selected categories.
- Added Recommendation and RecommendationResponse types to types.ts for better type safety and structure.
- Updated collections/[id]/+page.svelte to include a new view for recommendations, allowing users to switch between different views seamlessly.

* fix: update appVersion and improve button accessibility in collection views

* feat: add canModify prop to collection components for user permission handling

* feat: add itinerary removal functionality to various cards and update UI components

- Implemented `removeFromItinerary` function in `LodgingCard`, `NoteCard`, and `TransportationCard` to allow users to remove items from their itinerary.
- Replaced the trash icon with a calendar remove icon in `LocationCard`, `LodgingCard`, `NoteCard`, and `TransportationCard` for better visual representation.
- Updated the dropdown menus in `LodgingCard`, `NoteCard`, and `TransportationCard` to include the new remove from itinerary option.
- Enhanced `CollectionItineraryPlanner` to pass itinerary items to the respective cards.
- Removed `PointSelectionModal.svelte` as it is no longer needed.
- Refactored `LocationMedia.svelte` to integrate `ImageManagement` component and clean up unused code related to image handling.

* feat: enhance itinerary management with deduplication and initial visit date handling

* feat: add FullMap component for enhanced map functionality with clustering support

- Introduced FullMap.svelte to handle map rendering, clustering, and marker management.
- Updated map page to utilize FullMap component, replacing direct MapLibre usage.
- Implemented clustering options and marker properties handling in FullMap.
- Added utility functions for resolving theme colors and managing marker states.
- Enhanced user experience with hover popups and improved loading states for location details.
- Updated app version to v0.12.0-pre-dev-122225.

* feat: enhance map interaction for touch devices with custom popup handling

* feat: add progress tracker for folder views to display visited and planned locations

* feat: add map center and zoom state management with URL synchronization

* feat: add status and days until start fields to collections with filtering options

* Component folder structure changes

* feat: add LodgingMedia and LodgingModal components for managing lodging details and media attachments

feat: implement LocationSearchMap component for interactive location searching and mapping functionality

* fix: update contentType in ImageManagement component to 'lodging' for correct media handling

* feat: enhance lodging management with date validation and update messages

* feat: implement lodging detail page with server-side loading and image modal functionality

- Added a new server-side load function to fetch lodging details by ID.
- Created a new Svelte component for the lodging detail page, including image carousel and map integration.
- Implemented a modal for displaying images with navigation.
- Enhanced URL handling in the locations page to only read parameters.

* feat: add Transportation modal component and related routes

- Implemented TransportationModal component for creating and editing transportation entries.
- Added server-side loading for transportation details in the new route [id]/+page.server.ts.
- Created a new Svelte page for displaying transportation details with image and attachment handling.
- Integrated modal for editing transportation in the transportation details page.
- Updated lodging routes to include a modal for editing lodging entries.
- Removed unused delete action from lodging server-side logic.

* feat: add start_code and end_code fields to Transportation model and update related components

* feat: implement date validation for itinerary items and add day picker modal for scheduling

* Reorder town and county checks in geocoding.py

Fix detection if only town exists for a location but county is no city name

* Use address keys only if city is found

* Make sure reverse geocoding uses correct key for cities (#938)

* Reorder town and county checks in geocoding.py

Fix detection if only town exists for a location but county is no city name

* Use address keys only if city is found

* Refactor code structure for improved readability and maintainability

* Enhance collection management with modal updates and item handling

* feat: integrate CollectionMap component in collections page and update map titles in lodging and transportation pages

- Replaced inline map implementation with CollectionMap component in collections/[id]/+page.svelte for better modularity.
- Updated the map title in lodging/[id]/+page.svelte to reflect lodging context.
- Updated the map title in transportations/[id]/+page.svelte to reflect transportation context.
- Added functionality to collect and render GeoJSON data from transportation attachments in transportations/[id]/+page.svelte.

* chore: update copyright year to 2026 in various files

* feat: enhance backup export functionality with itinerary items and export IDs

* fix: improve dropdown close behavior by handling multiple event types

* fix: remove unnecessary cache decorator from globespin function

* feat: add initial visit date support in ChecklistModal and NoteModal, with UI suggestions for prefilled dates

* feat: add details view for checklist and note cards with edit functionality

* feat: add travel duration and GPX distance calculation to Transportation model and UI

* feat: add primary image support to Collection model, serializers, and UI components

* Refactor calendar components and enhance event detail handling

- Replaced direct calendar implementation with a reusable CalendarComponent in the calendar route.
- Introduced EventDetailsModal for displaying event details, improving modularity and readability.
- Added functionality to fetch event details asynchronously when an event is clicked.
- Implemented ICS calendar download functionality with loading state management.
- Enhanced collections page to support calendar view, integrating event handling and timezone management.
- Improved lodging and transportation pages to display local time for stays and trips, including timezone badges.
- Cleaned up unused code and comments for better maintainability.

* feat: enhance hero image handling in collection view by prioritizing primary image

* chore: update .env.example to include account email verification configuration

* feat: enhance LodgingCard and TransportationCard components with expandable details and improved layout

* feat: add price and currency fields to locations, lodging, and transportation components

- Introduced price and price_currency fields in LocationModal, LodgingDetails, LodgingModal, TransportationDetails, and TransportationModal components.
- Implemented MoneyInput and CurrencyDropdown components for handling monetary values and currency selection.
- Updated data structures and types to accommodate new price and currency fields across various models.
- Enhanced cost summary calculations in collections and routes to display total costs by currency.
- Added user preference for default currency in settings, affecting new item forms.
- Updated UI to display price information in relevant components, ensuring consistent formatting and user experience.

* feat: add Development Timeline link to overview and create timeline documentation

* feat: enhance map functionality with search and zoom features

- Updated availableViews in collection page to include map view based on lodging and transportation locations.
- Added search functionality to the map page, allowing users to filter pins by name and category.
- Implemented auto-zoom feature to adjust the map view based on filtered search results.
- Introduced a search bar with a clear button for better user experience.

* feat: enhance ISO code extraction and region matching logic in extractIsoCode function

* feat: enhance extractIsoCode function with normalization for locality matching

* feat: update extractIsoCode function to include additional ISO3166 levels for improved region matching

* feat: enhance extractIsoCode function to handle cases without city information and update CollectionMap to bind user data

* feat: add cron job for syncing visited regions and cities, enhance Docker and supervisord configurations

* feat: add CollectionItineraryDay model and related functionality for itinerary day metadata management

* feat: implement cleanup of out-of-range itinerary items and notify users of potential impacts on itinerary when dates change

* Refactor collection page for improved localization and code clarity

- Removed unused imports and consolidated cost category labels to be reactive.
- Updated cost summary function to accept localized labels.
- Enhanced localization for various UI elements, including buttons, headings, and statistics.
- Improved user feedback messages for better clarity and consistency.
- Ensured all relevant text is translatable using the i18n library.

* feat: add collaborator serialization and display in collections

- Implemented `_build_profile_pic_url` and `_serialize_collaborator` functions for user profile picture URLs and serialization.
- Updated `CollectionSerializer` and `UltraSlimCollectionSerializer` to include collaborators in the serialized output.
- Enhanced `CollectionViewSet` to prefetch shared_with users for optimized queries.
- Modified frontend components to display collaborators in collection details, including profile pictures and initials.
- Added new localization strings for collaborators.
- Refactored map and location components to improve usability and functionality.
- Updated app version to reflect new changes.

* feat: add dynamic lodging icons based on type in CollectionMap component

* feat: add CollectionStats component for detailed trip statistics

- Implemented CollectionStats.svelte to display various statistics related to the collection, including distances, activities, and locations visited.
- Enhanced CollectionMap.svelte to filter activities based on date range using new getActivityDate function.
- Updated LocationSearchMap.svelte to handle airport mode for start and end locations.
- Modified types.ts to include is_global property in CollectionItineraryItem for trip-wide items.
- Updated +page.svelte to integrate the new stats view and manage view state accordingly.

* feat: enhance itinerary management by removing old items on date change for notes and checklists; normalize date handling in CollectionMap

* feat: add functionality to change day and move items to trip-wide itinerary

- Implemented changeDay function in ChecklistCard, LocationCard, LodgingCard, NoteCard, and TransportationCard components to allow users to change the scheduled day of items.
- Added a button to move items to the global (trip-wide) itinerary in the aforementioned components, with appropriate dispatch events.
- Enhanced CollectionItineraryPlanner to handle moving items to the global itinerary and added UI elements for unscheduled items.
- Updated ItineraryDayPickModal to support the deletion of source visits when moving locations.
- Added new translations for "Change Day" and "Move Trip Wide" in the English locale.

* fix: specify full path for python3 in cron job and add shell and path variables

* fix: update appVersion to v0.12.0-pre-dev-010726

* feat: enhance CollectionItineraryPlanner and CollectionStats with dynamic links and transport type normalization

* Add Dev Container + WSL install docs and link in install guide (#944) (#951)

* feat: enhance internationalization support in CollectionMap and CollectionStats components

- Added translation support for various labels and messages in CollectionMap.svelte and CollectionStats.svelte using svelte-i18n.
- Updated English and Chinese locale files to include new translation keys for improved user experience.
- Simplified the rendering of recommendation views in the collections page.

* Refactor itinerary management and UI components

- Updated ItineraryViewSet to handle visit updates and creations more efficiently, preserving visit IDs when moving between days.
- Enhanced ChecklistCard, LodgingCard, TransportationCard, and NoteCard to include a new "Change Day" option in the actions menu.
- Improved user experience in CollectionItineraryPlanner by tracking specific itinerary items being moved and ensuring only the relevant entries are deleted.
- Added new location sharing options in LodgingCard and TransportationCard for Apple Maps, Google Maps, and OpenStreetMap.
- Updated translations in en.json for consistency and clarity.
- Minor UI adjustments for better accessibility and usability across various components.

* feat: implement action menus and close event handling in card components

* feat: refactor Dockerfile and supervisord configuration to remove cron and add periodic sync script

* feat: enhance LocationSearchMap and TransportationDetails components with initialization handling and airport mode logic

* feat: add airport and location search mode labels to localization file

* feat: enhance periodic sync logging and improve airport mode handling in LocationSearchMap

* feat: enhance unscheduled items display with improved card interactions and accessibility

* Add dev compose for hot reload and update WSL dev container docs (#958)

* feat: enhance localization for itinerary linking and transportation components

* Localization: update localization files with new keys and values

* fix: improve error messages for Overpass API responses

* chore: update dependencies in frontend package.json and pnpm-lock.yaml

- Updated @sveltejs/adapter-node from ^5.2.12 to ^5.4.0
- Updated @sveltejs/adapter-vercel from ^5.7.0 to ^6.3.0
- Updated tailwindcss from ^3.4.17 to ^3.4.19
- Updated typescript from ^5.8.3 to ^5.9.3
- Updated vite from ^5.4.19 to ^5.4.21

* chore: update dependencies in pnpm-lock.yaml to latest versions

* Refactor code structure for improved readability and maintainability

* Refactor code structure for improved readability and maintainability

* fix: update package dependencies to resolve compatibility issues

* Add "worldtravel" translations to multiple locale files

- Added "worldtravel" key with translations for Spanish, French, Hungarian, Italian, Japanese, Korean, Dutch, Norwegian, Polish, Brazilian Portuguese, Russian, Slovak, Swedish, Turkish, Ukrainian, and Chinese.
- Updated the navigation section in each locale file to include the new "worldtravel" entry.

* Add new screenshots and update email verification message in locale file

* feat: Implement data restoration functionality with file import

- Added a new action `restoreData` in `+page.server.ts` to handle file uploads for restoring collections.
- Enhanced the UI in `+page.svelte` to include an import button and a modal for import progress.
- Integrated file input handling to trigger form submission upon file selection.
- Removed unused GSAP animations from the login, profile, and signup pages for cleaner code.

* feat: Add modals for creating locations and lodging from recommendations, enhance image import functionality

* fix: Adjust styles to prevent horizontal scroll and enhance floating action button visibility

* feat: Enhance error handling and messaging for Google Maps and OpenStreetMap geocoding functions

* fix: Enhance error messaging for Google Maps access forbidden response

* feat: Add User-Agent header to Google Maps API requests and refine error messaging for access forbidden response

* fix: Update User-Agent header in Google Maps API requests for improved compatibility

* fix: Disable proxy settings in Google Maps API request to prevent connection issues

* fix: Update Trivy security scan configuration and add .trivyignore for known false positives

* fix: Refactor update method to handle is_public cascading for related items

* feat: Integrate django-invitations for user invitation management and update settings

* feat: Add Tailwind CSS and DaisyUI plugin for styling

* feat: Add Tailwind CSS and DaisyUI plugin for styling

* feat: Add "Invite a User" guide and update navigation links

* docs: Update "Invite a User" guide to include email configuration tip

* feat: Update email invitation template for improved styling and clarity

* fix: Remove trailing backslash from installation note in Unraid documentation

* feat: Add export/import messages and user email verification prompts in multiple languages

* Squashed commit of the following:

commit a993a15b93ebb7521ae2e5cc31596b98b29fcd6c
Author: Alex <div@alexe.at>
Date:   Mon Jan 12 20:44:47 2026 +0100

    Translated using Weblate (German)

    Currently translated at 100.0% (1048 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/de/

commit fdc455d9424fbb0f6b72179d9eb1340411700773
Author: Ettore Atalan <atalanttore@googlemail.com>
Date:   Sat Jan 10 23:24:23 2026 +0100

    Translated using Weblate (German)

    Currently translated at 100.0% (1048 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/de/

commit 5942129c55e89dd999a13d4df9c40e6e3189355c
Author: Orhun <orhunavcu@gmail.com>
Date:   Sun Jan 11 13:05:31 2026 +0100

    Translated using Weblate (Turkish)

    Currently translated at 100.0% (1048 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/tr/

commit 8712e43d8ba4a7e7fe163fb454d6577187f9a375
Author: Henrique Fonseca Veloso <henriquefv@tutamail.com>
Date:   Fri Jan 9 22:53:11 2026 +0100

    Translated using Weblate (Portuguese (Brazil))

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/pt_BR/

commit 18ee56653470413afe8d71ecd2b5028f6e4cf118
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:57 2026 +0100

    Translated using Weblate (Dutch)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/nl/

commit 57783c544e583c035c8b57b5c10ca320f25f399e
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:14 2026 +0100

    Translated using Weblate (Arabic)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/ar/

commit fb09edfd85bc85234b1c1ba7dd499f2915093fff
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:26 2026 +0100

    Translated using Weblate (Spanish)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/es/

commit 554a207d8e454a1f7ae826e2a40d389b94be5512
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:21 2026 +0100

    Translated using Weblate (German)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/de/

commit b70b9db27fb8607beefeb288185601c8f5eae28d
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:02 2026 +0100

    Translated using Weblate (Norwegian Bokmål)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/nb_NO/

commit 3b467caa9007c553e4ae7de97f53b6e462161ea3
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:07 2026 +0100

    Translated using Weblate (Polish)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/pl/

commit 30fbbfba3572c8f78ec7c7e1a231e363aca1ef10
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:17 2026 +0100

    Translated using Weblate (Russian)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/ru/

commit 8cecb492cfcac0a1f93ee8919f7b41d978d331ee
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:42 2026 +0100

    Translated using Weblate (Italian)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/it/

commit f0d3d41029c89bfa83d5891ee7af70241f27b7be
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:38 2026 +0100

    Translated using Weblate (Hungarian)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/hu/

commit 102e0f1912d010d38755a1713abb2a7f7564aafb
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:21 2026 +0100

    Translated using Weblate (Slovak)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/sk/

commit 428b8f18cf6195a96b55109e0221413d82415a2f
Author: Максим Горпиніч <gorpinicmaksim0@gmail.com>
Date:   Sat Jan 10 08:55:28 2026 +0100

    Translated using Weblate (Ukrainian)

    Currently translated at 100.0% (1048 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/uk/

commit 1a71aaf279ecab26c0c1fede05025732e6dcfa5e
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:27 2026 +0100

    Translated using Weblate (Swedish)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/sv/

commit 36ec3701f3a1a904e7c42ac4ffbe6a050dc6d1ed
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:53:43 2026 +0100

    Translated using Weblate (Chinese (Simplified Han script))

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/zh_Hans/

commit 65d8b74b340c877cad2028b7142c783a1b568d49
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:48 2026 +0100

    Translated using Weblate (Japanese)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/ja/

commit 4d11d1d31022583657e93aee70301a8ffcde1340
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:52 2026 +0100

    Translated using Weblate (Korean)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/ko/

commit bd1135bcb965ad73cf493771b15081cc97cf513a
Author: Orhun <orhunavcu@gmail.com>
Date:   Fri Jan 9 22:53:33 2026 +0100

    Translated using Weblate (Turkish)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/tr/

commit 2c3d814119f4cf2dabd20933699f5b991f20f3e6
Author: Anonymous <noreply@weblate.org>
Date:   Fri Jan 9 22:52:32 2026 +0100

    Translated using Weblate (French)

    Currently translated at 99.9% (1047 of 1048 strings)

    Translation: AdventureLog/Web App
    Translate-URL: https://hosted.weblate.org/projects/adventurelog/web-app/fr/

* Refactor code structure and remove redundant code blocks for improved readability and maintainability

* fix: Correct appVersion to match the latest pre-release version

* fix: Add missing vulnerability reference for jaraco.context in .trivyignore

---------

Co-authored-by: Lars Lehmann <33843261+larsl-net@users.noreply.github.com>
Co-authored-by: Lars Lehmann <lars@lmail.eu>
Co-authored-by: Nick Petrushin <n.a.petrushin@gmail.com>
This commit is contained in:
Sean Morley
2026-01-14 10:22:14 -05:00
committed by GitHub
parent d954ac057d
commit c39ff2449e
206 changed files with 33830 additions and 14254 deletions

View File

@@ -0,0 +1,251 @@
<script lang="ts">
import type { Activity, Trail, TransportationVisit, Visit } from '$lib/types';
import { t } from 'svelte-i18n';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import RunFastIcon from '~icons/mdi/run-fast';
import FileIcon from '~icons/mdi/file';
import TrashIcon from '~icons/mdi/trash-can';
import SpeedometerIcon from '~icons/mdi/speedometer';
import TrendingUpIcon from '~icons/mdi/trending-up';
import ClockIcon from '~icons/mdi/clock';
import CaloriesIcon from '~icons/mdi/fire';
import LocationIcon from '~icons/mdi/map-marker';
import { formatDateInTimezone } from '$lib/dateUtils';
import { getDistance, getElevation } from '$lib';
export let activity: Activity;
export let trails: Trail[];
export let visit: Visit | TransportationVisit;
export let measurementSystem: 'metric' | 'imperial' = 'metric';
export let readOnly: boolean = false;
$: trail = activity.trail ? trails.find((t) => t.id === activity.trail) : null;
function deleteActivity(visitId: string, activityId: string) {
dispatch('delete', { visitId, activityId });
}
function formatDuration(isoString: string | null): string {
if (!isoString) return '';
// Simple ISO 8601 duration parsing for display
const match = isoString.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
if (!match) return isoString;
const hours = parseInt(match[1] || '0');
const minutes = parseInt(match[2] || '0');
const seconds = parseInt(match[3] || '0');
if (hours > 0) {
return `${hours}h ${minutes}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds}s`;
} else {
return `${seconds}s`;
}
}
function formatSpeed(speed: number | null): string {
if (!speed) return '';
const convertedSpeed = measurementSystem === 'imperial' ? speed * 2.237 : speed * 3.6;
return `${convertedSpeed.toFixed(1)} ${measurementSystem === 'imperial' ? 'mph' : 'km/h'}`;
}
</script>
<div class="bg-base-200/50 p-4 rounded-lg border border-base-300/50">
<div class="flex items-start justify-between mb-3">
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-2">
<RunFastIcon class="w-4 h-4 text-success flex-shrink-0" />
<h5 class="font-semibold text-base truncate">{activity.name}</h5>
<div class="flex gap-1">
{#if activity.sport_type}
<span class="badge badge-outline badge-sm">{activity.sport_type}</span>
{/if}
</div>
</div>
</div>
{#if !readOnly}
<button
class="btn btn-error btn-xs tooltip tooltip-top ml-2"
data-tip="Delete Activity"
on:click={() => deleteActivity(visit.id, activity.id)}
>
<TrashIcon class="w-3 h-3" />
</button>
{/if}
</div>
<!-- Main Stats Grid -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-3">
{#if activity.distance}
<div class="bg-base-100/50 p-2 rounded text-center">
<div class="text-lg font-bold text-primary">
{getDistance(measurementSystem, activity.distance)}
</div>
<div class="text-xs text-base-content/70">
{measurementSystem === 'imperial' ? 'miles' : 'km'}
</div>
</div>
{/if}
{#if activity.moving_time}
<div class="bg-base-100/50 p-2 rounded text-center">
<div class="text-lg font-bold text-secondary">
{formatDuration(activity.moving_time)}
</div>
<div class="text-xs text-base-content/70">{$t('adventures.moving_time')}</div>
</div>
{/if}
{#if activity.elevation_gain}
<div class="bg-base-100/50 p-2 rounded text-center">
<div class="text-lg font-bold text-success">
{getElevation(measurementSystem, activity.elevation_gain)}
</div>
<div class="text-xs text-base-content/70">
{measurementSystem === 'imperial' ? 'ft' : 'm'}
</div>
</div>
{/if}
{#if activity.average_speed}
<div class="bg-base-100/50 p-2 rounded text-center">
<div class="text-lg font-bold text-accent">
{formatSpeed(activity.average_speed)}
</div>
<div class="text-xs text-base-content/70">{$t('adventures.average_speed')}</div>
</div>
{/if}
</div>
<!-- Additional Details -->
<div class="space-y-2 text-xs text-base-content/80">
<!-- Time Details -->
{#if activity.elapsed_time || activity.rest_time}
<div class="flex items-center gap-1">
<ClockIcon class="w-3 h-3" />
<span class="flex gap-4">
{#if activity.elapsed_time}
<span>{$t('adventures.total')}: {formatDuration(activity.elapsed_time)}</span>
{/if}
{#if activity.rest_time}
<span>{$t('adventures.rest')}: {formatDuration(activity.rest_time)}</span>
{/if}
</span>
</div>
{/if}
<!-- Elevation Details -->
{#if activity.elev_high || activity.elev_low || activity.elevation_loss}
<div class="flex items-center gap-1">
<TrendingUpIcon class="w-3 h-3" />
<span class="flex gap-4">
{#if activity.elev_high}
<span
>{$t('adventures.high')}: {getElevation(
measurementSystem,
activity.elev_high
)}{measurementSystem === 'imperial' ? 'ft' : 'm'}</span
>
{/if}
{#if activity.elev_low}
<span
>{$t('adventures.low')}: {getElevation(
measurementSystem,
activity.elev_low
)}{measurementSystem === 'imperial' ? 'ft' : 'm'}</span
>
{/if}
{#if activity.elevation_loss}
<span
>{getElevation(measurementSystem, activity.elevation_loss)}{measurementSystem ===
'imperial'
? 'ft'
: 'm'}</span
>
{/if}
</span>
</div>
{/if}
<!-- Speed Details -->
{#if activity.max_speed}
<div class="flex items-center gap-1">
<SpeedometerIcon class="w-3 h-3" />
<span>{$t('adventures.max_speed')}: {formatSpeed(activity.max_speed)}</span>
</div>
{/if}
<!-- Performance Metrics -->
{#if activity.average_cadence || activity.calories}
<div class="flex items-center gap-4">
{#if activity.average_cadence}
<span>{$t('adventures.cadence')}: {activity.average_cadence} rpm</span>
{/if}
{#if activity.calories}
<span class="flex items-center gap-1">
<CaloriesIcon class="w-3 h-3" />
{activity.calories}
{$t('adventures.calories')}
</span>
{/if}
</div>
{/if}
<!-- Trail Information -->
{#if trail}
<div class="flex items-center gap-1">
<LocationIcon class="w-3 h-3" />
<span>{$t('adventures.trail')}: <span class="font-medium">{trail.name}</span></span>
</div>
{/if}
<!-- Date Information -->
{#if activity.start_date}
<div class="border-t border-base-300/50 pt-2">
<div>
Started: {formatDateInTimezone(
activity.start_date,
activity.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone
)}
</div>
{#if activity.timezone}
<div class="text-xs text-base-content/60">
{$t('adventures.timezone')}: {activity.timezone}
</div>
{/if}
</div>
{/if}
<!-- Location Information -->
{#if activity.start_lat && activity.start_lng}
<div class="flex items-center gap-1">
<LocationIcon class="w-3 h-3" />
<span
>{$t('adventures.start')}: {activity.start_lat.toFixed(4)}, {activity.start_lng.toFixed(
4
)}</span
>
{#if activity.end_lat && activity.end_lng && (activity.end_lat !== activity.start_lat || activity.end_lng !== activity.start_lng)}
<span class="ml-2"
>{$t('adventures.end')}: {activity.end_lat.toFixed(4)}, {activity.end_lng.toFixed(
4
)}</span
>
{/if}
</div>
{/if}
<!-- GPX File -->
{#if activity.gpx_file}
<div class="flex items-center gap-1 pt-2 border-t border-base-300/50">
<FileIcon class="w-3 h-3" />
<a href={activity.gpx_file} target="_blank" class="link link-primary text-xs">
{$t('adventures.view_gpx')}
</a>
</div>
{/if}
</div>
</div>

View File

@@ -0,0 +1,101 @@
<script lang="ts">
import type { Attachment } from '$lib/types';
import { t } from 'svelte-i18n';
export let attachment: Attachment;
export let allowEdit: boolean = false;
import { createEventDispatcher } from 'svelte';
import { addToast } from '$lib/toasts';
const dispatch = createEventDispatcher();
async function deleteAttachment() {
let res = await fetch(`/api/attachments/${attachment.id}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('adventures.attachment_delete_success'));
dispatch('delete', attachment.id);
} else {
console.log('Error deleting attachment');
}
}
// Check if the attachment is an image or not
function getCardBackground() {
const isImage = ['.jpg', '.jpeg', '.png', '.gif', '.webp'].some((ext) =>
attachment.file.endsWith(ext)
);
return isImage ? `url(${attachment.file})` : '';
}
</script>
<div class="relative rounded-lg shadow-lg group hover:shadow-xl transition-shadow overflow-hidden">
<!-- Card Image or Placeholder -->
<!-- svelte-ignore a11y-click-events-have-key-events -->
<div
class="w-full h-48 bg-cover bg-center group-hover:opacity-90 transition-opacity"
style="background-image: {getCardBackground()}"
on:click={() => window.open(attachment.file, '_blank')}
role="button"
tabindex="0"
aria-label={attachment.file.split('/').pop()}
>
{#if !['.jpg', '.jpeg', '.png', '.gif', '.webp'].some((ext) => attachment.file.endsWith(ext))}
<div
class="flex justify-center items-center w-full h-full text-white text-lg font-bold bg-gradient-to-r from-secondary via-base to-primary text-center"
>
<p>
{attachment.name} <br />
{attachment.extension.toUpperCase()}
</p>
</div>
<!-- show the name under the extension -->
{/if}
</div>
<!-- Attachment Label -->
<div
class="absolute top-0 right-0 bg-primary text-white px-3 py-1 text-sm font-medium rounded-bl-lg shadow-md"
>
{$t('adventures.attachment')}
</div>
<div
class="absolute top-0 left-0 bg-secondary text-white px-2 py-1 text-sm font-medium rounded-br-lg shadow-md"
>
{attachment.extension}
</div>
<!-- Action Bar -->
<div
class="absolute bottom-0 w-full bg-gradient-to-t from-black/50 to-transparent p-3 rounded-b-lg flex justify-between items-center"
>
<span class="text-white text-sm font-medium truncate">
{attachment.name}
</span>
<div class="flex space-x-2">
{#if !allowEdit}
<button
class="btn btn-sm btn-secondary btn-outline"
type="button"
on:click={() => window.open(attachment.file, '_blank')}
>
{$t('notes.open')}
</button>
{/if}
{#if allowEdit}
<button
class="btn btn-sm btn-info btn-outline"
type="button"
on:click={() => dispatch('edit', attachment)}
>
{$t('transportation.edit')}
</button>
<button class="btn btn-sm btn-danger btn-outline" type="button" on:click={deleteAttachment}>
{$t('adventures.delete')}
</button>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,466 @@
<script lang="ts">
import { addToast } from '$lib/toasts';
import type { Checklist, Collection, User } from '$lib/types';
import { createEventDispatcher, onMount } from 'svelte';
const dispatch = createEventDispatcher();
import { t } from 'svelte-i18n';
import Launch from '~icons/mdi/launch';
import TrashCan from '~icons/mdi/trash-can';
import Calendar from '~icons/mdi/calendar';
import DeleteWarning from '../DeleteWarning.svelte';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import CheckCircle from '~icons/mdi/check-circle';
import CheckboxBlankCircleOutline from '~icons/mdi/checkbox-blank-circle-outline';
import CalendarRemove from '~icons/mdi/calendar-remove';
import Close from '~icons/mdi/close';
import Globe from '~icons/mdi/globe';
import type { CollectionItineraryItem } from '$lib/types';
let isActionsMenuOpen = false;
let actionsMenuRef: HTMLDivElement | null = null;
const ACTIONS_CLOSE_EVENT = 'card-actions-close';
const handleCloseEvent = () => (isActionsMenuOpen = false);
function handleDocumentClick(event: MouseEvent) {
if (!isActionsMenuOpen) return;
const target = event.target as Node | null;
if (actionsMenuRef && target && !actionsMenuRef.contains(target)) {
isActionsMenuOpen = false;
}
}
function closeAllChecklistMenus() {
window.dispatchEvent(new CustomEvent(ACTIONS_CLOSE_EVENT));
}
onMount(() => {
document.addEventListener('click', handleDocumentClick);
window.addEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
return () => {
document.removeEventListener('click', handleDocumentClick);
window.removeEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
};
});
export let checklist: Checklist;
export let user: User | null = null;
export let collection: Collection;
export let readOnly: boolean = false;
export let itineraryItem: CollectionItineraryItem | null = null;
let isWarningModalOpen: boolean = false;
let isDetailsOpen: boolean = false;
let updatingItemId: string | null = null;
$: canEdit =
!readOnly &&
(checklist.user == user?.uuid ||
(collection && user && collection.shared_with?.includes(user.uuid)));
const normalizeDateForApi = (date: string | Date | null | undefined): string | null => {
if (!date) return null;
if (date instanceof Date && !isNaN(date.getTime())) {
return date.toISOString().slice(0, 10);
}
if (typeof date === 'string') {
const match = date.match(/^\d{4}-\d{2}-\d{2}/);
return match ? match[0] : null;
}
return null;
};
function editChecklist() {
dispatch('edit', checklist);
}
function changeDay() {
dispatch('changeDay', { type: 'checklist', item: checklist, forcePicker: true });
}
async function deleteChecklist() {
const res = await fetch(`/api/checklists/${checklist.id}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('success', $t('checklist.checklist_deleted'));
isWarningModalOpen = false;
dispatch('delete', checklist.id);
} else {
addToast($t('checklist.checklist_delete_error'), 'error');
}
}
async function removeFromItinerary() {
let itineraryItemId = itineraryItem?.id;
let res = await fetch(`/api/itineraries/${itineraryItemId}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('itinerary.item_remove_success'));
dispatch('removeFromItinerary', itineraryItem);
} else {
addToast('error', $t('itinerary.item_remove_error'));
}
}
async function toggleItemStatus(itemId: string) {
if (!canEdit || !itemId) return;
const previousItems = checklist.items.map((item) => ({ ...item }));
const updatedItems = checklist.items.map((item) =>
item.id === itemId ? { ...item, is_checked: !item.is_checked } : item
);
const dateForApi = normalizeDateForApi(checklist.date);
updatingItemId = itemId;
checklist = { ...checklist, items: updatedItems };
try {
const res = await fetch(`/api/checklists/${checklist.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: checklist.name,
date: dateForApi,
items: updatedItems,
collection: checklist.collection,
is_public: checklist.is_public
})
});
if (res.ok) {
const data = await res.json();
if (data) {
checklist = data;
dispatch('update', data);
}
} else {
checklist = { ...checklist, items: previousItems };
addToast('error', 'Unable to update checklist item');
}
} catch (error) {
checklist = { ...checklist, items: previousItems };
addToast('error', 'Unable to update checklist item');
console.error(error);
} finally {
updatingItemId = null;
}
}
</script>
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_checklist')}
button_text="Delete"
description={$t('adventures.checklist_delete_confirm')}
is_warning={false}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteChecklist}
/>
{/if}
{#if isDetailsOpen}
<dialog class="modal modal-open" open>
<div class="modal-box max-w-3xl space-y-4">
<div class="flex items-start justify-between gap-3">
<div class="space-y-2">
<div class="flex items-center gap-2">
<h3 class="text-xl font-semibold leading-tight">{checklist.name}</h3>
<div class="badge badge-primary badge-sm">{$t('adventures.checklist')}</div>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/70">
{#if checklist.date && checklist.date !== ''}
<div class="flex items-center gap-2">
<Calendar class="w-4 h-4 text-primary" />
<span>
{new Date(checklist.date).toLocaleDateString(undefined, { timeZone: 'UTC' })}
</span>
</div>
{/if}
{#if checklist.items.length > 0}
{@const completedCount = checklist.items.filter((item) => item.is_checked).length}
<div class="badge badge-ghost badge-sm">
{completedCount}/{checklist.items.length}
{$t('checklist.completed')}
</div>
{/if}
</div>
</div>
<button
type="button"
class="btn btn-circle btn-ghost btn-sm"
on:click={() => (isDetailsOpen = false)}
aria-label={$t('about.close')}
>
<Close class="w-4 h-4" />
</button>
</div>
{#if checklist.items.length > 0}
<div class="space-y-2 max-h-96 overflow-y-auto pr-1">
{#each checklist.items as item}
{#if canEdit}
<button
type="button"
on:click={() => toggleItemStatus(item.id)}
disabled={updatingItemId === item.id}
class="flex w-full items-center gap-3 rounded-lg bg-base-200/60 p-2 text-left transition-colors hover:bg-base-200 disabled:opacity-70"
>
{#if updatingItemId === item.id}
<span class="loading loading-spinner loading-xs text-primary flex-shrink-0"
></span>
{:else if item.is_checked}
<CheckCircle class="w-5 h-5 text-success flex-shrink-0" />
{:else}
<CheckboxBlankCircleOutline class="w-5 h-5 flex-shrink-0" />
{/if}
<span
class="flex-1 text-sm"
class:line-through={item.is_checked}
class:opacity-60={item.is_checked}
>
{item.name}
</span>
</button>
{:else}
<div class="flex items-center gap-3 rounded-lg bg-base-200/60 p-2">
{#if item.is_checked}
<CheckCircle class="w-5 h-5 text-success flex-shrink-0" />
{:else}
<CheckboxBlankCircleOutline class="w-5 h-5 flex-shrink-0" />
{/if}
<span
class="flex-1 text-sm"
class:line-through={item.is_checked}
class:opacity-60={item.is_checked}
>
{item.name}
</span>
</div>
{/if}
{/each}
</div>
{:else}
<p class="text-sm text-base-content/70">No items added yet.</p>
{/if}
<div class="modal-action">
<button class="btn" on:click={() => (isDetailsOpen = false)}>Close</button>
</div>
</div>
<form method="dialog" class="modal-backdrop">
<button aria-label="close" on:click={() => (isDetailsOpen = false)}>Close</button>
</form>
</dialog>
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
aria-label="checklist-card"
>
<div class="card-body p-4 space-y-3">
<!-- Header -->
<div class="flex items-start justify-between gap-3">
<div class="flex-1 min-w-0">
<h2 class="text-lg font-semibold line-clamp-2">{checklist.name}</h2>
<div class="flex flex-wrap items-center gap-2 mt-2">
<div class="badge badge-primary badge-sm">{$t('adventures.checklist')}</div>
</div>
</div>
<div class="flex items-center gap-2">
<button
class="btn btn-square btn-sm p-1 text-base-content"
on:click={() => (isDetailsOpen = true)}
aria-label={$t('adventures.view')}
type="button"
>
<Launch class="w-5 h-5" />
</button>
{#if canEdit}
<div
class="dropdown dropdown-end relative z-50"
class:dropdown-open={isActionsMenuOpen}
bind:this={actionsMenuRef}
>
<button
type="button"
class="btn btn-square btn-sm p-1 text-base-content"
aria-haspopup="menu"
on:click|stopPropagation={() => {
if (isActionsMenuOpen) {
isActionsMenuOpen = false;
return;
}
closeAllChecklistMenus();
isActionsMenuOpen = true;
}}
>
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
tabindex="-1"
class="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow-lg border border-base-300"
>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
editChecklist();
}}
class="flex items-center gap-2"
>
<FileDocumentEdit class="w-4 h-4" />
{$t('lodging.edit')}
</button>
</li>
{#if itineraryItem && itineraryItem.id}
<div class="divider my-1"></div>
{#if !itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
dispatch('moveToGlobal', { type: 'checklist', id: checklist.id });
}}
class="flex items-center gap-2"
>
<Globe class="w-4 h-4" />
{$t('itinerary.move_to_trip_context') || 'Move to Trip Context'}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
changeDay();
}}
class=" flex items-center gap-2"
>
<Calendar class="w-4 h-4 text" />
{$t('itinerary.change_day')}
</button>
</li>
{/if}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{#if itineraryItem.is_global}
{$t('itinerary.remove_from_trip_context') || 'Remove from Trip Context'}
{:else}
{$t('itinerary.remove_from_itinerary')}
{/if}
</button>
</li>
{/if}
<div class="divider my-1"></div>
<li>
<button
class="text-error flex items-center gap-2"
on:click={() => {
isActionsMenuOpen = false;
isWarningModalOpen = true;
}}
>
<TrashCan class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
</ul>
</div>
{/if}
</div>
</div>
<!-- Checklist Items Preview -->
{#if checklist.items.length > 0}
<div class="space-y-1.5">
{#each checklist.items.slice(0, 3) as item}
{#if canEdit}
<button
type="button"
on:click={() => toggleItemStatus(item.id)}
disabled={updatingItemId === item.id}
class="flex w-full items-center gap-1.5 rounded-lg px-2 py-0.5 text-left text-sm text-base-content/80 transition-colors hover:bg-base-200/80 disabled:opacity-60"
>
{#if updatingItemId === item.id}
<span class="loading loading-spinner loading-xs text-primary"></span>
{:else if item.is_checked}
<CheckCircle class="w-4 h-4 text-success flex-shrink-0" />
{:else}
<CheckboxBlankCircleOutline class="w-4 h-4 flex-shrink-0" />
{/if}
<span
class="truncate"
class:line-through={item.is_checked}
class:opacity-60={item.is_checked}
>
{item.name}
</span>
</button>
{:else}
<div class="flex items-center gap-1.5 text-sm text-base-content/70">
{#if item.is_checked}
<CheckCircle class="w-4 h-4 text-success flex-shrink-0" />
{:else}
<CheckboxBlankCircleOutline class="w-4 h-4 flex-shrink-0" />
{/if}
<span
class="truncate"
class:line-through={item.is_checked}
class:opacity-60={item.is_checked}
>
{item.name}
</span>
</div>
{/if}
{/each}
{#if checklist.items.length > 3}
<div class="text-sm text-base-content/60 pl-6">
+{checklist.items.length - 3}
{$t('checklist.more_items')}
</div>
{/if}
</div>
{/if}
<!-- Inline Stats -->
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/70">
{#if checklist.date && checklist.date !== ''}
<div class="flex items-center gap-1">
<Calendar class="w-4 h-4 text-primary" />
<span>{new Date(checklist.date).toLocaleDateString(undefined, { timeZone: 'UTC' })}</span>
</div>
{/if}
{#if checklist.items.length > 0}
{@const completedCount = checklist.items.filter((item) => item.is_checked).length}
<div class="badge badge-ghost badge-sm">
{completedCount}/{checklist.items.length}
{$t('checklist.completed')}
</div>
{/if}
</div>
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,80 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { addToast } from '$lib/toasts';
import type { City } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { t } from 'svelte-i18n';
export let city: City;
export let visited: boolean;
async function markVisited() {
let res = await fetch(`/api/visitedcity/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ city: city.id })
});
if (res.ok) {
visited = true;
let data = await res.json();
addToast('success', `Visit to ${city.name} marked`);
dispatch('visit', data);
} else {
console.error('Failed to mark city as visited');
addToast('error', `Failed to mark visit to ${city.name}`);
}
}
async function removeVisit() {
let res = await fetch(`/api/visitedcity/${city.id}`, {
method: 'DELETE'
});
if (res.ok) {
visited = false;
addToast('info', `Visit to ${city.name} removed`);
dispatch('remove', city);
} else {
console.error('Failed to remove visit');
addToast('error', `Failed to remove visit to ${city.name}`);
}
}
</script>
<div
class="card w-full max-w-md bg-base-300 text-base-content shadow-2xl hover:shadow-3xl transition-all duration-300 border border-base-300 hover:border-primary/20 group overflow-hidden"
>
<div class="card-body p-6 space-y-4">
<!-- Header -->
<h2 class="text-xl font-bold truncate">{city.name}</h2>
<!-- Metadata Badges -->
<div class="flex flex-wrap gap-2">
<div class="badge badge-primary">
{city.region_name}, {city.country_name}
</div>
<div class="badge badge-neutral-300">Region ID: {city.region}</div>
</div>
<!-- Actions -->
<div class="pt-4 border-t border-base-300 flex justify-end gap-2">
{#if visited === false}
<button class="btn btn-primary btn-sm" on:click={markVisited}>
{$t('adventures.mark_visited')}
</button>
{/if}
{#if visited === true}
<button class="btn btn-warning btn-sm" on:click={removeVisit}>
{$t('adventures.remove')}
</button>
{/if}
</div>
</div>
</div>
<style>
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

View File

@@ -0,0 +1,432 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import Launch from '~icons/mdi/launch';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import ArchiveArrowDown from '~icons/mdi/archive-arrow-down';
import ArchiveArrowUp from '~icons/mdi/archive-arrow-up';
import ShareVariant from '~icons/mdi/share-variant';
import { goto } from '$app/navigation';
import type { Location, Collection, User, SlimCollection, ContentImage } from '$lib/types';
import { addToast } from '$lib/toasts';
import { t } from 'svelte-i18n';
import Plus from '~icons/mdi/plus';
import Minus from '~icons/mdi/minus';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import TrashCan from '~icons/mdi/trashcan';
import DeleteWarning from '../DeleteWarning.svelte';
import ShareModal from '../ShareModal.svelte';
import CardCarousel from '../CardCarousel.svelte';
import ExitRun from '~icons/mdi/exit-run';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import Check from '~icons/mdi/check';
import MapMarker from '~icons/mdi/map-marker-multiple';
import LinkIcon from '~icons/mdi/link';
import DownloadIcon from '~icons/mdi/download';
const dispatch = createEventDispatcher();
export let type: String | undefined | null;
export let linkedCollectionList: string[] | null = null;
export let user: User | null;
let isShareModalOpen: boolean = false;
let copied: boolean = false;
async function copyLink() {
try {
const url = `${location.origin}/collections/${collection.id}`;
await navigator.clipboard.writeText(url);
copied = true;
setTimeout(() => (copied = false), 2000);
} catch (e) {
addToast('error', $t('adventures.copy_failed') || 'Copy failed');
}
}
function editAdventure() {
dispatch('edit', collection);
}
async function exportCollectionZip() {
try {
const res = await fetch(`/api/collections/${collection.id}/export`);
if (!res.ok) {
addToast('error', $t('adventures.export_failed') || 'Export failed');
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `collection-${String(collection.name).replace(/\s+/g, '_')}.zip`;
a.click();
URL.revokeObjectURL(url);
addToast('success', $t('adventures.export_success') || 'Exported collection');
} catch (e) {
addToast('error', $t('adventures.export_failed') || 'Export failed');
}
}
async function archiveCollection(is_archived: boolean) {
console.log(JSON.stringify({ is_archived: is_archived }));
let res = await fetch(`/api/collections/${collection.id}/`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ is_archived: is_archived })
});
if (res.ok) {
if (is_archived) {
addToast('info', $t('adventures.archived_collection_message'));
dispatch('archive', collection.id);
} else {
addToast('info', $t('adventures.unarchived_collection_message'));
dispatch('unarchive', collection.id);
}
} else {
console.log('Error archiving collection');
}
}
export let collection: Collection | SlimCollection;
let location_images: ContentImage[] = [];
$: {
let images: ContentImage[] = [];
if ('location_images' in collection) {
images = collection.location_images;
} else {
images = collection.locations.flatMap((location: Location) => location.images);
}
const primaryImage = 'primary_image' in collection ? collection.primary_image : null;
if (primaryImage) {
const coverImage = { ...primaryImage, is_primary: true };
const remainingImages = images
.filter((img) => img.id !== primaryImage.id)
.map((img) => ({ ...img, is_primary: false }));
location_images = [coverImage, ...remainingImages];
} else {
location_images = images;
}
}
let locationLength: number = 0;
$: locationLength =
'location_count' in collection ? collection.location_count : collection.locations.length;
async function deleteCollection() {
let res = await fetch(`/api/collections/${collection.id}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('adventures.delete_collection_success'));
dispatch('delete', collection.id);
} else {
console.log('Error deleting collection');
}
}
let isWarningModalOpen: boolean = false;
</script>
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_collection')}
button_text={$t('adventures.delete')}
description={$t('adventures.delete_collection_warning')}
is_warning={true}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteCollection}
/>
{/if}
{#if isShareModalOpen}
<ShareModal {collection} on:close={() => (isShareModalOpen = false)} />
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
>
<!-- Image Carousel -->
<div class="relative overflow-hidden rounded-t-2xl">
<CardCarousel images={location_images} name={collection.name} icon="📚" />
<!-- Status Badge Overlay -->
<div class="absolute top-2 left-4 flex items-center gap-2">
{#if collection.status === 'folder'}
<div class="badge badge-sm badge-neutral shadow-sm">
📁 {$t('adventures.folder')}
</div>
{:else if collection.status === 'upcoming'}
<div class="badge badge-sm badge-info shadow-sm">
🚀 {$t('adventures.upcoming')}
</div>
{#if collection.days_until_start !== null}
<div class="badge badge-sm badge-accent shadow-sm">
{collection.days_until_start}
{collection.days_until_start === 1 ? $t('adventures.day') : $t('adventures.days')}
</div>
{/if}
{:else if collection.status === 'in_progress'}
<div class="badge badge-sm badge-success shadow-sm">
🎯 {$t('adventures.in_progress')}
</div>
{:else if collection.status === 'completed'}
<div class="badge badge-sm badge-primary shadow-sm">
<Check class="w-4 h-4" />
{$t('adventures.completed')}
</div>
{/if}
{#if collection.is_archived}
<div class="badge badge-sm badge-warning shadow-sm">
{$t('adventures.archived')}
</div>
{/if}
</div>
<!-- Privacy Indicator -->
<div class="absolute top-2 right-4">
<div
class="tooltip tooltip-left"
data-tip={collection.is_public ? $t('adventures.public') : $t('adventures.private')}
>
<div
class="badge badge-sm {collection.is_public
? 'badge-secondary'
: 'badge-ghost'} shadow-lg"
aria-label={collection.is_public ? $t('adventures.public') : $t('adventures.private')}
>
{#if collection.is_public}
<Eye class="w-4 h-4" />
{:else}
<EyeOff class="w-4 h-4" />
{/if}
</div>
</div>
</div>
</div>
<!-- Content -->
<div class="card-body p-4 space-y-3">
<!-- Title -->
<a
href="/collections/{collection.id}"
class="hover:text-primary transition-colors duration-200 line-clamp-2 text-lg font-semibold"
>{collection.name}</a
>
<!-- Stats -->
<div class="flex flex-wrap items-center gap-2 text-sm text-base-content/70">
<!-- Location Count -->
<div class="flex items-center gap-1">
<MapMarker class="w-4 h-4 text-primary" />
<span>
{locationLength}
{locationLength === 1 ? $t('locations.location') : $t('locations.locations')}
</span>
</div>
<!-- Date Range & Duration -->
{#if collection.start_date && collection.end_date}
<span class="text-base-content/60 px-1"></span>
<div class="flex items-center gap-1">
<span>
{Math.floor(
(new Date(collection.end_date).getTime() -
new Date(collection.start_date).getTime()) /
(1000 * 60 * 60 * 24)
) + 1}
{Math.floor(
(new Date(collection.end_date).getTime() -
new Date(collection.start_date).getTime()) /
(1000 * 60 * 60 * 24)
) +
1 ===
1
? $t('adventures.day')
: $t('adventures.days')}
</span>
</div>
{/if}
</div>
<!-- Date Range (if exists) -->
{#if collection.start_date && collection.end_date}
<div class="text-xs text-base-content/60">
{new Date(collection.start_date).toLocaleDateString(undefined, {
timeZone: 'UTC',
month: 'short',
day: 'numeric',
year: 'numeric'
})} {new Date(collection.end_date).toLocaleDateString(undefined, {
timeZone: 'UTC',
month: 'short',
day: 'numeric',
year: 'numeric'
})}
</div>
{/if}
<!-- Actions -->
<div class="pt-4 border-t border-base-300">
{#if type == 'link'}
{#if linkedCollectionList && linkedCollectionList
.map(String)
.includes(String(collection.id))}
<button
class="btn btn-error btn-block"
on:click={() => dispatch('unlink', collection.id)}
>
<Minus class="w-4 h-4" />
{$t('adventures.remove_from_collection')}
</button>
{:else}
<button
class="btn btn-primary btn-block"
on:click={() => dispatch('link', collection.id)}
>
<Plus class="w-4 h-4" />
{$t('adventures.add_to_collection')}
</button>
{/if}
{:else}
<div class="flex justify-between items-center">
<button
class="btn btn-neutral btn-sm flex-1 mr-2"
on:click={() => goto(`/collections/${collection.id}`)}
>
<Launch class="w-4 h-4" />
{$t('adventures.open_details')}
</button>
{#if user && user.uuid == collection.user}
<div class="dropdown dropdown-end">
<button type="button" class="btn btn-square btn-sm btn-base-300">
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
class="dropdown-content menu bg-base-100 rounded-box z-[1] w-64 p-2 shadow-xl border border-base-300"
>
{#if type != 'viewonly'}
<li>
<button class="flex items-center gap-2" on:click={editAdventure}>
<FileDocumentEdit class="w-4 h-4" />
{$t('adventures.edit_collection')}
</button>
</li>
<li>
<button
class="flex items-center gap-2"
on:click={() => (isShareModalOpen = true)}
>
<ShareVariant class="w-4 h-4" />
{$t('adventures.share')}
</button>
</li>
{#if collection.is_public}
<li>
<button on:click={copyLink} class="flex items-center gap-2">
{#if copied}
<Check class="w-4 h-4 text-success" />
<span>{$t('adventures.link_copied')}</span>
{:else}
<LinkIcon class="w-4 h-4" />
{$t('adventures.copy_link')}
{/if}
</button>
</li>
{/if}
{#if collection.is_archived}
<li>
<button
class="flex items-center gap-2"
on:click={() => archiveCollection(false)}
>
<ArchiveArrowUp class="w-4 h-4" />
{$t('adventures.unarchive')}
</button>
</li>
{:else}
<li>
<button
class="flex items-center gap-2"
on:click={() => archiveCollection(true)}
>
<ArchiveArrowDown class="w-4 h-4" />
{$t('adventures.archive')}
</button>
</li>
{/if}
<li>
<button class="flex items-center gap-2" on:click={exportCollectionZip}>
<DownloadIcon class="w-4 h-4" />
{$t('adventures.export_zip')}
</button>
</li>
<div class="divider my-1"></div>
<li>
<button
id="delete_collection"
data-umami-event="Delete Collection"
class="text-error flex items-center gap-2"
on:click={() => (isWarningModalOpen = true)}
>
<TrashCan class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
{/if}
{#if type == 'viewonly'}
<li>
<button
class="flex items-center gap-2"
on:click={() => goto(`/collections/${collection.id}`)}
>
<Launch class="w-4 h-4" />
{$t('adventures.open_details')}
</button>
</li>
{/if}
</ul>
</div>
{:else if user && collection.shared_with && collection.shared_with.includes(user.uuid)}
<!-- dropdown with leave button -->
<div class="dropdown dropdown-end">
<button type="button" class="btn btn-square btn-sm btn-base-300">
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
class="dropdown-content menu bg-base-100 rounded-box z-[1] w-64 p-2 shadow-xl border border-base-300"
>
<li>
<button
class="text-error flex items-center gap-2"
on:click={() => dispatch('leave', collection.id)}
>
<ExitRun class="w-4 h-4" />
{$t('adventures.leave_collection')}
</button>
</li>
</ul>
</div>
{/if}
</div>
{/if}
</div>
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,74 @@
<script lang="ts">
import { goto } from '$app/navigation';
import type { Country } from '$lib/types';
import { createEventDispatcher } from 'svelte';
import { t } from 'svelte-i18n';
import MapMarkerStar from '~icons/mdi/map-marker-star';
import Launch from '~icons/mdi/launch';
export let country: Country;
async function nav() {
goto(`/worldtravel/${country.country_code}`);
}
</script>
<div
class="card w-full max-w-md bg-base-300 text-base-content shadow-2xl hover:shadow-3xl transition-all duration-300 border border-base-300 hover:border-primary/20 group overflow-hidden"
>
<!-- Flag Image -->
<figure>
<img src={country.flag_url} alt={`Flag of ${country.name}`} class="w-full h-48 object-cover" />
</figure>
<!-- Content -->
<div class="card-body p-6 space-y-4">
<!-- Title -->
<a
href="/worldtravel/{country.country_code}"
class="text-xl font-bold text-left hover:text-primary transition-colors duration-200 line-clamp-2 group-hover:underline block"
>
{country.name}
</a>
<!-- Info Badges -->
<div class="flex flex-wrap gap-2">
{#if country.subregion}
<div class="badge badge-primary">{country.subregion}</div>
{/if}
{#if country.capital}
<div class="badge badge-secondary inline-flex items-center gap-1">
<MapMarkerStar class="w-4 h-4" />
{country.capital}
</div>
{/if}
{#if country.num_visits > 0 && country.num_visits !== country.num_regions}
<div class="badge badge-accent">
Visited {country.num_visits} Region{country.num_visits > 1 ? 's' : ''}
</div>
{:else if country.num_visits > 0 && country.num_visits === country.num_regions}
<div class="badge badge-success">{$t('adventures.visited')}</div>
{:else}
<div class="badge badge-error">{$t('adventures.not_visited')}</div>
{/if}
</div>
<!-- Actions -->
<div class="pt-4 border-t border-base-300 flex justify-end">
<button class="btn btn-primary btn-sm flex items-center gap-1" on:click={nav}>
<Launch class="w-4 h-4" />
{$t('notes.open')}
</button>
</div>
</div>
</div>
<style>
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

View File

@@ -0,0 +1,587 @@
<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte';
import { goto } from '$app/navigation';
import type { Location, Collection, User } from '$lib/types';
const dispatch = createEventDispatcher();
import Launch from '~icons/mdi/launch';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import TrashCan from '~icons/mdi/trash-can-outline';
import Calendar from '~icons/mdi/calendar';
import Clock from '~icons/mdi/clock-outline';
import MapMarker from '~icons/mdi/map-marker';
import LinkIcon from '~icons/mdi/link-variant';
import Check from '~icons/mdi/check';
import { addToast } from '$lib/toasts';
import Link from '~icons/mdi/link-variant';
import LinkVariantRemove from '~icons/mdi/link-variant-remove';
import Plus from '~icons/mdi/plus';
import CollectionLink from '../CollectionLink.svelte';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import DeleteWarning from '../DeleteWarning.svelte';
import CardCarousel from '../CardCarousel.svelte';
import { t } from 'svelte-i18n';
import Star from '~icons/mdi/star';
import StarOutline from '~icons/mdi/star-outline';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import CollectionItineraryPlanner from '../collections/CollectionItineraryPlanner.svelte';
import CalendarRemove from '~icons/mdi/calendar-remove';
import Globe from '~icons/mdi/globe';
import { DEFAULT_CURRENCY, formatMoney, toMoneyValue } from '$lib/money';
export let type: string | null = null;
export let user: User | null;
export let collection: Collection | null = null;
export let readOnly: boolean = false;
export let compact: boolean = false; // For compact grid display in itinerary
export let itineraryItem: CollectionItineraryPlanner | null = null;
let isCollectionModalOpen: boolean = false;
let isWarningModalOpen: boolean = false;
let copied: boolean = false;
let isActionsMenuOpen: boolean = false;
let actionsMenuRef: HTMLDivElement | null = null;
const ACTIONS_CLOSE_EVENT = 'card-actions-close';
const handleCloseEvent = () => (isActionsMenuOpen = false);
function handleDocumentClick(event: MouseEvent) {
if (!isActionsMenuOpen) return;
const target = event.target as Node | null;
if (actionsMenuRef && target && !actionsMenuRef.contains(target)) {
isActionsMenuOpen = false;
}
}
function closeAllLocationMenus() {
window.dispatchEvent(new CustomEvent(ACTIONS_CLOSE_EVENT));
}
onMount(() => {
document.addEventListener('click', handleDocumentClick);
window.addEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
return () => {
document.removeEventListener('click', handleDocumentClick);
window.removeEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
};
});
async function copyLink() {
try {
const url = `${location.origin}/locations/${adventure.id}`;
await navigator.clipboard.writeText(url);
copied = true;
setTimeout(() => (copied = false), 2000);
} catch (e) {
addToast('error', $t('adventures.copy_failed') || 'Copy failed');
}
}
export let adventure: Location;
let displayActivityTypes: string[] = [];
let remainingCount = 0;
// Price formatting
$: adventurePriceLabel = formatMoney(
toMoneyValue(adventure?.price, adventure?.price_currency, DEFAULT_CURRENCY)
);
// Process activity types for display
$: {
if (adventure.tags) {
if (adventure.tags.length <= 3) {
displayActivityTypes = adventure.tags;
remainingCount = 0;
} else {
displayActivityTypes = adventure.tags.slice(0, 3);
remainingCount = adventure.tags.length - 3;
}
}
}
// Creator avatar helpers
$: creatorInitials =
adventure.user?.first_name && adventure.user?.last_name
? `${adventure.user.first_name[0]}${adventure.user.last_name[0]}`
: adventure.user?.first_name?.[0] || adventure.user?.username?.[0] || '?';
$: creatorDisplayName = adventure.user?.first_name
? `${adventure.user.first_name} ${adventure.user.last_name || ''}`.trim()
: adventure.user?.username || 'Unknown User';
// Helper functions for display
function renderStars(rating: number) {
const stars = [];
for (let i = 1; i <= 5; i++) {
stars.push(i <= rating);
}
return stars;
}
function changeDay() {
dispatch('changeDay', { type: 'location', item: adventure, forcePicker: true });
}
async function deleteAdventure() {
let res = await fetch(`/api/locations/${adventure.id}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('adventures.location_delete_success'));
dispatch('delete', adventure.id);
} else {
console.log('Error deleting adventure');
}
}
async function removeFromItinerary() {
let itineraryItemId = itineraryItem?.id;
let res = await fetch(`/api/itineraries/${itineraryItemId}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('itinerary.item_remove_success'));
dispatch('removeFromItinerary', itineraryItem);
} else {
addToast('error', $t('itinerary.item_remove_error'));
}
}
async function linkCollection(event: CustomEvent<string>) {
let collectionId = event.detail;
// Create a copy to avoid modifying the original directly
const updatedCollections = adventure.collections ? [...adventure.collections] : [];
// Add the new collection if not already present
if (!updatedCollections.some((c) => String(c) === String(collectionId))) {
updatedCollections.push(collectionId);
}
let res = await fetch(`/api/locations/${adventure.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ collections: updatedCollections })
});
if (res.ok) {
// Only update the adventure.collections after server confirms success
adventure.collections = updatedCollections;
addToast('info', `${$t('adventures.collection_link_location_success')}`);
} else {
addToast('error', `${$t('adventures.collection_link_location_error')}`);
}
}
async function removeFromCollection(event: CustomEvent<string>) {
let collectionId = event.detail;
if (!collectionId) {
addToast('error', `${$t('adventures.collection_remove_location_error')}`);
return;
}
// Create a copy to avoid modifying the original directly
if (adventure.collections) {
const updatedCollections = adventure.collections.filter(
(c) => String(c) !== String(collectionId)
);
let res = await fetch(`/api/locations/${adventure.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ collections: updatedCollections })
});
if (res.ok) {
// Only update adventure.collections after server confirms success
adventure.collections = updatedCollections;
addToast('info', `${$t('adventures.collection_remove_location_success')}`);
} else {
addToast('error', `${$t('adventures.collection_remove_location_error')}`);
}
}
}
function editAdventure() {
dispatch('edit', adventure);
}
function link() {
dispatch('link', adventure);
}
</script>
{#if isCollectionModalOpen}
<CollectionLink
on:link={(e) => linkCollection(e)}
on:unlink={(e) => removeFromCollection(e)}
on:close={() => (isCollectionModalOpen = false)}
linkedCollectionList={adventure.collections}
/>
{/if}
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_location')}
button_text="Delete"
description={$t('adventures.location_delete_confirm')}
is_warning={false}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteAdventure}
/>
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
aria-label="location-card"
>
<!-- Image Section with Overlay -->
<div class="relative overflow-hidden rounded-t-2xl">
<CardCarousel images={adventure.images} icon={adventure.category?.icon} name={adventure.name} />
<!-- Status Overlay (icon-only) -->
<div class="absolute top-2 left-4 flex items-center gap-3">
<div
class="tooltip tooltip-right"
data-tip={adventure.is_visited ? $t('adventures.visited') : $t('adventures.not_visited')}
>
{#if adventure.is_visited}
<div class="badge badge-sm badge-success p-1 rounded-full shadow-sm">
<Calendar class="w-4 h-4" />
</div>
{:else}
<div class="badge badge-sm badge-warning p-1 rounded-full shadow-sm">
<Clock class="w-4 h-4" />
</div>
{/if}
</div>
</div>
<!-- Privacy Indicator -->
<div class="absolute top-2 right-4">
<div
class="tooltip tooltip-left"
data-tip={adventure.is_public ? $t('adventures.public') : $t('adventures.private')}
>
<div
class="badge badge-sm p-1 rounded-full text-base-content shadow-sm"
role="img"
aria-label={adventure.is_public ? $t('adventures.public') : $t('adventures.private')}
>
{#if adventure.is_public}
<Eye class="w-4 h-4" />
{:else}
<EyeOff class="w-4 h-4" />
{/if}
</div>
</div>
</div>
<!-- Category Badge -->
{#if adventure.category}
<div class="absolute bottom-4 left-4">
<a
href="/locations?types={adventure.category.name}"
class="badge badge-primary shadow-lg font-medium cursor-pointer hover:brightness-110 transition-all"
>
{adventure.category.display_name}
{adventure.category.icon}
</a>
</div>
{/if}
<!-- Creator Avatar -->
{#if adventure.user && collection}
<div class="absolute bottom-4 right-4">
<div class="tooltip tooltip-left" data-tip={creatorDisplayName}>
<div class="avatar">
<div class="w-7 h-7 rounded-full ring-2 ring-white/40 shadow">
{#if adventure.user.profile_pic}
<img
src={adventure.user.profile_pic}
alt={creatorDisplayName}
class="rounded-full object-cover"
/>
{:else}
<div
class="w-7 h-7 bg-gradient-to-br from-primary to-secondary rounded-full flex items-center justify-center text-primary-content font-semibold text-xs"
>
{creatorInitials.toUpperCase()}
</div>
{/if}
</div>
</div>
</div>
</div>
{/if}
</div>
<!-- Content Section -->
<div
class="card-body space-y-2"
class:p-3={compact}
class:p-4={!compact}
class:space-y-2={compact}
class:space-y-3={!compact}
>
<!-- Header: title + compact actions -->
<div class="flex items-start justify-between gap-2">
<a
href="/locations/{adventure.id}"
class="hover:text-primary transition-colors duration-200 line-clamp-2"
class:text-base={compact}
class:text-lg={!compact}
class:font-semibold={!compact}
class:font-medium={compact}
>
{adventure.name}
</a>
<div class="flex items-center gap-2">
<button
class="btn btn-sm p-1 text-base-content"
aria-label="open-details"
on:click={() => goto(`/locations/${adventure.id}`)}
>
<Launch class="w-4 h-4" />
</button>
{#if !readOnly}
{#if (adventure.user && adventure.user.uuid == user?.uuid) || (collection && user && collection.shared_with?.includes(user.uuid)) || (collection && user && collection.user == user.uuid)}
<div
class="dropdown dropdown-end relative z-50"
class:dropdown-open={isActionsMenuOpen}
bind:this={actionsMenuRef}
>
<button
type="button"
class="btn btn-square btn-sm p-1 text-base-content"
aria-haspopup="menu"
aria-label={$t('adventures.location_actions') || 'Location actions'}
on:click|stopPropagation={() => {
if (isActionsMenuOpen) {
isActionsMenuOpen = false;
return;
}
closeAllLocationMenus();
isActionsMenuOpen = true;
}}
>
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
tabindex="-1"
class="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow-lg border border-base-300"
>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
editAdventure();
}}
class="flex items-center gap-2"
>
<FileDocumentEdit class="w-4 h-4" />
{$t('adventures.edit_location')}
</button>
</li>
{#if user?.uuid == adventure.user?.uuid}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
isCollectionModalOpen = true;
}}
class="flex items-center gap-2"
>
<Plus class="w-4 h-4" />
{$t('collection.manage_collections')}
</button>
</li>
{:else if collection && user && collection.user == user.uuid}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromCollection(new CustomEvent('unlink', { detail: collection.id }));
}}
class="flex items-center gap-2"
>
<LinkVariantRemove class="w-4 h-4" />
{$t('adventures.remove_from_collection')}
</button>
</li>
{/if}
{#if adventure.is_public}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
copyLink();
}}
class="flex items-center gap-2"
>
{#if copied}
<Check class="w-4 h-4 text-success" />
<span>{$t('adventures.link_copied')}</span>
{:else}
<LinkIcon class="w-4 h-4" />
{$t('adventures.copy_link')}
{/if}
</button>
</li>
{/if}
{#if itineraryItem && itineraryItem.id}
<div class="divider my-1"></div>
{#if !itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
dispatch('moveToGlobal', { type: 'location', id: adventure.id });
}}
class=" flex items-center gap-2"
>
<Globe class="w-4 h-4" />
{$t('itinerary.move_to_trip_context') || 'Move to Trip Context'}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
changeDay();
}}
class=" flex items-center gap-2"
>
<Calendar class="w-4 h-4" />
{$t('itinerary.change_day')}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{$t('itinerary.remove_from_itinerary')}
</button>
</li>
{/if}
{#if itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{$t('itinerary.remove_from_trip_context')}
</button>
</li>
{/if}
{/if}
{#if user.uuid == adventure.user?.uuid}
<div class="divider my-1"></div>
<li>
<button
id="delete_adventure"
data-umami-event="Delete Adventure"
class="text-error flex items-center gap-2"
on:click={() => {
isActionsMenuOpen = false;
isWarningModalOpen = true;
}}
>
<TrashCan class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
{/if}
</ul>
</div>
{/if}
{/if}
</div>
</div>
<!-- Inline stats: location, rating, visits -->
<div
class="flex flex-wrap items-center text-base-content/70 min-w-0"
class:gap-2={compact}
class:gap-3={!compact}
class:text-xs={compact}
class:text-sm={!compact}
>
{#if adventure.location}
<div class="flex items-center gap-1 min-w-0">
<MapMarker class="w-4 h-4 text-primary" />
<span class="truncate max-w-[18rem]">{adventure.location}</span>
</div>
{/if}
{#if adventure.rating}
<div class="flex items-center gap-1">
<div class="flex -ml-1">
{#each renderStars(adventure.rating) as filled}
{#if filled}
<Star class="w-4 h-4 text-warning fill-current" />
{:else}
<StarOutline class="w-4 h-4 text-base-content/30" />
{/if}
{/each}
</div>
<span class="text-xs text-base-content/60">({adventure.rating}/5)</span>
</div>
{/if}
{#if adventurePriceLabel}
<span class="badge badge-ghost badge-sm whitespace-nowrap">💰 {adventurePriceLabel}</span>
{/if}
</div>
<!-- Tags (compact) -->
{#if displayActivityTypes.length > 0}
<div class="flex flex-wrap gap-2">
{#each displayActivityTypes as tag}
<span class="badge badge-ghost badge-sm">{tag}</span>
{/each}
{#if remainingCount > 0}
<span class="badge badge-ghost badge-sm">+{remainingCount}</span>
{/if}
</div>
{/if}
</div>
{#if !readOnly}
{#if type == 'link'}
<div class="card-body p-4 pt-0">
<button class="btn btn-primary btn-block btn-sm" on:click={link}>
<Link class="w-4 h-4 mr-2" />
Link Adventure
</button>
</div>
{/if}
{/if}
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,504 @@
<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte';
import TrashCanOutline from '~icons/mdi/trash-can-outline';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import type { Collection, Lodging, User } from '$lib/types';
import { addToast } from '$lib/toasts';
import { t } from 'svelte-i18n';
import DeleteWarning from '../DeleteWarning.svelte';
import { LODGING_TYPES_ICONS } from '$lib';
import { formatDateInTimezone } from '$lib/dateUtils';
import { formatAllDayDate } from '$lib/dateUtils';
import { isAllDay } from '$lib';
import { DEFAULT_CURRENCY, formatMoney, toMoneyValue } from '$lib/money';
import CardCarousel from '../CardCarousel.svelte';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import Star from '~icons/mdi/star';
import StarOutline from '~icons/mdi/star-outline';
import MapMarker from '~icons/mdi/map-marker';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import CalendarRemove from '~icons/mdi/calendar-remove';
import Launch from '~icons/mdi/launch';
import Globe from '~icons/mdi/globe';
import { goto } from '$app/navigation';
import Calendar from '~icons/mdi/calendar';
import type { CollectionItineraryItem } from '$lib/types';
let isActionsMenuOpen = false;
let actionsMenuRef: HTMLDivElement | null = null;
const ACTIONS_CLOSE_EVENT = 'card-actions-close';
const handleCloseEvent = () => (isActionsMenuOpen = false);
function handleDocumentClick(event: MouseEvent) {
if (!isActionsMenuOpen) return;
const target = event.target as Node | null;
if (actionsMenuRef && target && !actionsMenuRef.contains(target)) {
isActionsMenuOpen = false;
}
}
function closeAllLodgingMenus() {
window.dispatchEvent(new CustomEvent(ACTIONS_CLOSE_EVENT));
}
onMount(() => {
document.addEventListener('click', handleDocumentClick);
window.addEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
return () => {
document.removeEventListener('click', handleDocumentClick);
window.removeEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
};
});
const dispatch = createEventDispatcher();
function getLodgingIcon(type: string) {
if (type in LODGING_TYPES_ICONS) {
return LODGING_TYPES_ICONS[type as keyof typeof LODGING_TYPES_ICONS];
} else {
return '🏨';
}
}
function renderStars(rating: number) {
const stars = [];
for (let i = 1; i <= 5; i++) {
stars.push(i <= rating);
}
return stars;
}
const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
const getTimezoneLabel = (zone?: string | null) => zone ?? localTimeZone;
const getTimezoneTip = (zone?: string | null) => {
const label = getTimezoneLabel(zone);
return label === localTimeZone
? null
: `${$t('adventures.trip_timezone') ?? 'Trip TZ'}: ${label}. ${
$t('adventures.your_time') ?? 'Your time'
}: ${localTimeZone}.`;
};
const shouldShowTzBadge = (zone?: string | null) => {
if (!zone) return false;
return getTimezoneLabel(zone) !== localTimeZone;
};
const hasTimePortion = (date: string | null) => !!date && !isAllDay(date);
const isTimedStay = (date: string | null) => hasTimePortion(date);
$: lodgingPriceLabel = formatMoney(
toMoneyValue(lodging.price, lodging.price_currency, DEFAULT_CURRENCY)
);
let showMoreDetails = false;
$: hasExpandableDetails = Boolean(
lodging.check_out && (isTimedStay(lodging.check_out) || isTimedStay(lodging.check_in))
);
$: if (!hasExpandableDetails) showMoreDetails = false;
export let lodging: Lodging;
export let user: User | null = null;
export let collection: Collection | null = null;
export let readOnly: boolean = false;
export let itineraryItem: CollectionItineraryItem | null = null;
let isWarningModalOpen: boolean = false;
function editTransportation() {
dispatch('edit', lodging);
}
async function deleteTransportation() {
let res = await fetch(`/api/lodging/${lodging.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
if (!res.ok) {
console.log($t('transportation.transportation_delete_error'));
} else {
addToast('info', $t('transportation.transportation_deleted'));
isWarningModalOpen = false;
dispatch('delete', lodging.id);
}
}
function changeDay() {
dispatch('changeDay', { type: 'lodging', item: lodging, forcePicker: true });
}
async function removeFromItinerary() {
let itineraryItemId = itineraryItem?.id;
let res = await fetch(`/api/itineraries/${itineraryItemId}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('itinerary.item_remove_success'));
dispatch('removeFromItinerary', itineraryItem);
} else {
addToast('error', $t('itinerary.item_remove_error'));
}
}
</script>
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_lodging')}
button_text="Delete"
description={$t('adventures.lodging_delete_confirm')}
is_warning={false}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteTransportation}
/>
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
aria-label="lodging-card"
>
<!-- Image Section with Overlay -->
<div class="relative overflow-hidden rounded-t-2xl">
<CardCarousel images={lodging.images} icon={getLodgingIcon(lodging.type)} name={lodging.name} />
<!-- Privacy Indicator -->
<div class="absolute top-2 right-4">
<div
class="tooltip tooltip-left"
data-tip={lodging.is_public ? $t('adventures.public') : $t('adventures.private')}
>
<div
class="badge badge-sm p-1 rounded-full text-base-content shadow-sm"
role="img"
aria-label={lodging.is_public ? $t('adventures.public') : $t('adventures.private')}
>
{#if lodging.is_public}
<Eye class="w-4 h-4" />
{:else}
<EyeOff class="w-4 h-4" />
{/if}
</div>
</div>
</div>
<!-- Category Badge -->
{#if lodging.type}
<div class="absolute bottom-4 left-4">
<div class="badge badge-primary shadow-lg font-medium">
{$t(`lodging.${lodging.type}`)}
{getLodgingIcon(lodging.type)}
</div>
</div>
{/if}
</div>
<div class="card-body p-4 space-y-3 min-w-0">
<!-- Header -->
<div class="flex items-start justify-between gap-3">
<a
href="/lodging/{lodging.id}"
class="hover:text-primary transition-colors duration-200 line-clamp-2 text-lg font-semibold"
>
{lodging.name}
</a>
<div class="flex items-center gap-2">
<button
class="btn btn-sm p-1 text-base-content"
aria-label="open-details"
on:click={() => goto(`/lodging/${lodging.id}`)}
>
<Launch class="w-4 h-4" />
</button>
{#if !readOnly && (lodging.user == user?.uuid || (collection && user && collection.shared_with?.includes(user.uuid)))}
<div
class="dropdown dropdown-end relative z-50"
class:dropdown-open={isActionsMenuOpen}
bind:this={actionsMenuRef}
>
<button
type="button"
class="btn btn-square btn-sm p-1 text-base-content"
aria-haspopup="menu"
on:click|stopPropagation={() => {
if (isActionsMenuOpen) {
isActionsMenuOpen = false;
return;
}
closeAllLodgingMenus();
isActionsMenuOpen = true;
}}
>
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
tabindex="-1"
class="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow-lg border border-base-300"
>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
editTransportation();
}}
class="flex items-center gap-2"
>
<FileDocumentEdit class="w-4 h-4" />
{$t('transportation.edit')}
</button>
</li>
{#if itineraryItem && itineraryItem.id}
<div class="divider my-1"></div>
{#if !itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
dispatch('moveToGlobal', { type: 'lodging', id: lodging.id });
}}
class="flex items-center gap-2"
>
<Globe class="w-4 h-4" />
{$t('itinerary.move_to_trip_context') || 'Move to Trip Context'}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
changeDay();
}}
class=" flex items-center gap-2"
>
<Calendar class="w-4 h-4 text" />
{$t('itinerary.change_day')}
</button>
</li>
{/if}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{#if itineraryItem.is_global}
{$t('itinerary.remove_from_trip_context') || 'Remove from Trip Context'}
{:else}
{$t('itinerary.remove_from_itinerary')}
{/if}
</button>
</li>
{/if}
<div class="divider my-1"></div>
<li>
<button
class="text-error flex items-center gap-2"
on:click={() => {
isActionsMenuOpen = false;
isWarningModalOpen = true;
}}
>
<TrashCanOutline class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
</ul>
</div>
{/if}
</div>
</div>
<!-- Location -->
{#if lodging.location}
<div class="flex items-center gap-2 text-sm text-base-content/70 min-w-0">
<MapMarker class="w-4 h-4 text-primary flex-shrink-0" />
<span class="truncate">{lodging.location}</span>
</div>
{/if}
<!-- Check-in & Check-out Section -->
{#if lodging.check_in || lodging.check_out}
<div class="flex flex-col gap-1.5">
{#if lodging.check_in && lodging.check_out}
<!-- Both dates present -->
{#if isAllDay(lodging.check_in) && isAllDay(lodging.check_out)}
<!-- All-day dates -->
<div class="flex items-center gap-2 text-sm">
<span class="font-medium text-base-content">{formatAllDayDate(lodging.check_in)}</span
>
<span class="text-primary"></span>
<span class="font-medium text-base-content"
>{formatAllDayDate(lodging.check_out)}</span
>
</div>
{:else}
<!-- Timed dates with tidy mini cards and toggle -->
<div class="flex flex-col gap-2">
<!-- Check-in Card (always shown) -->
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs text-base-content/60">Check-in</span>
<span class="text-sm font-semibold text-base-content">
{#if isAllDay(lodging.check_in)}
{formatAllDayDate(lodging.check_in)}
{:else}
{formatDateInTimezone(lodging.check_in, lodging.timezone)}
{/if}
</span>
</div>
</div>
{#if hasTimePortion(lodging.check_in) && shouldShowTzBadge(lodging.timezone)}
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div class="tooltip" data-tip={getTimezoneTip(lodging.timezone) ?? undefined}>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(lodging.timezone)}
</span>
</div>
</div>
{/if}
</div>
{#if hasExpandableDetails}
<div class="flex justify-end">
<button
class="btn btn-neutral-200 btn-xs"
aria-expanded={showMoreDetails}
on:click={() => (showMoreDetails = !showMoreDetails)}
type="button"
>
{showMoreDetails
? ($t('common.show_less') ?? 'Hide details')
: ($t('common.show_more') ?? 'Show more')}
</button>
</div>
{/if}
{#if showMoreDetails && hasExpandableDetails}
<!-- Check-out Card (expandable) -->
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs text-base-content/60">Check-out</span>
<span class="text-sm font-semibold text-base-content">
{#if isAllDay(lodging.check_out)}
{formatAllDayDate(lodging.check_out)}
{:else}
{formatDateInTimezone(lodging.check_out, lodging.timezone)}
{/if}
</span>
</div>
</div>
{#if hasTimePortion(lodging.check_out) && shouldShowTzBadge(lodging.timezone)}
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div class="tooltip" data-tip={getTimezoneTip(lodging.timezone) ?? undefined}>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(lodging.timezone)}
</span>
</div>
</div>
{/if}
</div>
{/if}
</div>
{/if}
{:else if lodging.check_in}
<!-- Check-in only -->
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5">
<span class="text-xs text-base-content/60">Check-in</span>
<span class="text-sm font-semibold text-base-content">
{#if isAllDay(lodging.check_in)}
{formatAllDayDate(lodging.check_in)}
{:else}
{formatDateInTimezone(lodging.check_in, lodging.timezone)}
{/if}
</span>
</div>
</div>
{#if hasTimePortion(lodging.check_in) && shouldShowTzBadge(lodging.timezone)}
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div class="tooltip" data-tip={getTimezoneTip(lodging.timezone) ?? undefined}>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(lodging.timezone)}
</span>
</div>
</div>
{/if}
</div>
{:else if lodging.check_out}
<!-- Check-out only -->
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5">
<span class="text-xs text-base-content/60">Check-out</span>
<span class="text-sm font-semibold text-base-content">
{#if isAllDay(lodging.check_out)}
{formatAllDayDate(lodging.check_out)}
{:else}
{formatDateInTimezone(lodging.check_out, lodging.timezone)}
{/if}
</span>
</div>
</div>
{#if hasTimePortion(lodging.check_out) && shouldShowTzBadge(lodging.timezone)}
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div class="tooltip" data-tip={getTimezoneTip(lodging.timezone) ?? undefined}>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(lodging.timezone)}
</span>
</div>
</div>
{/if}
</div>
{/if}
</div>
{/if}
<!-- Rating & Info Badges -->
<div class="flex flex-wrap items-center gap-2 text-sm">
{#if lodging.rating}
<div class="flex items-center gap-1">
<div class="flex -ml-1">
{#each renderStars(lodging.rating) as filled}
{#if filled}
<Star class="w-4 h-4 text-warning fill-current" />
{:else}
<StarOutline class="w-4 h-4 text-base-content/30" />
{/if}
{/each}
</div>
<span class="text-xs text-base-content/60">({lodging.rating}/5)</span>
</div>
{/if}
{#if lodging.user == user?.uuid || (collection && user && collection.shared_with?.includes(user.uuid))}
{#if lodging.reservation_number}
<span class="badge badge-primary badge-sm font-medium">
{$t('adventures.reservation')}: {lodging.reservation_number}
</span>
{/if}
{#if lodgingPriceLabel}
<span class="badge badge-ghost badge-sm">💰 {lodgingPriceLabel}</span>
{/if}
{/if}
</div>
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,373 @@
<script lang="ts">
import { t } from 'svelte-i18n';
import { addToast } from '$lib/toasts';
import type { Collection, Note, User } from '$lib/types';
import { createEventDispatcher, onMount } from 'svelte';
const dispatch = createEventDispatcher();
import { marked } from 'marked'; // Import the markdown parser
const renderMarkdown = (markdown: string) => {
return marked(markdown);
};
import TrashCan from '~icons/mdi/trash-can';
import Calendar from '~icons/mdi/calendar';
import DeleteWarning from '../DeleteWarning.svelte';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import LinkVariant from '~icons/mdi/link-variant';
import CalendarRemove from '~icons/mdi/calendar-remove';
import Launch from '~icons/mdi/launch';
import Close from '~icons/mdi/close';
import Globe from '~icons/mdi/globe';
import type { CollectionItineraryItem } from '$lib/types';
let isActionsMenuOpen = false;
let actionsMenuRef: HTMLDivElement | null = null;
const ACTIONS_CLOSE_EVENT = 'card-actions-close';
const handleCloseEvent = () => (isActionsMenuOpen = false);
function handleDocumentClick(event: MouseEvent) {
if (!isActionsMenuOpen) return;
const target = event.target as Node | null;
if (actionsMenuRef && target && !actionsMenuRef.contains(target)) {
isActionsMenuOpen = false;
}
}
function closeAllNoteMenus() {
window.dispatchEvent(new CustomEvent(ACTIONS_CLOSE_EVENT));
}
onMount(() => {
document.addEventListener('click', handleDocumentClick);
window.addEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
return () => {
document.removeEventListener('click', handleDocumentClick);
window.removeEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
};
});
export let note: Note;
export let user: User | null = null;
export let collection: Collection | null = null;
export let readOnly: boolean = false;
export let itineraryItem: CollectionItineraryItem | null = null;
let isWarningModalOpen: boolean = false;
let isDetailsOpen: boolean = false;
$: canEdit =
!readOnly &&
(note.user == user?.uuid ||
(collection && user && collection.shared_with?.includes(user.uuid)));
function editNote() {
dispatch('edit', note);
}
async function deleteNote() {
const res = await fetch(`/api/notes/${note.id}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('success', $t('notes.note_deleted'));
isWarningModalOpen = false;
dispatch('delete', note.id);
} else {
addToast($t('notes.note_delete_error'), 'error');
}
}
function changeDay() {
dispatch('changeDay', { type: 'note', item: note, forcePicker: true });
}
async function removeFromItinerary() {
let itineraryItemId = itineraryItem?.id;
let res = await fetch(`/api/itineraries/${itineraryItemId}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('itinerary.item_remove_success'));
dispatch('removeFromItinerary', itineraryItem);
} else {
addToast('error', $t('itinerary.item_remove_error'));
}
}
</script>
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_note')}
button_text="Delete"
description={$t('adventures.note_delete_confirm')}
is_warning={false}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteNote}
/>
{/if}
{#if isDetailsOpen}
<dialog class="modal modal-open" open>
<div class="modal-box max-w-3xl space-y-4">
<div class="flex items-start justify-between gap-3">
<div class="space-y-2">
<h3 class="text-xl font-semibold leading-tight">{note.name}</h3>
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/70">
<div class="badge badge-primary badge-sm">{$t('adventures.note')}</div>
{#if note.date && note.date !== ''}
<div class="flex items-center gap-2">
<Calendar class="w-4 h-4 text-primary" />
<span>{new Date(note.date).toLocaleDateString(undefined, { timeZone: 'UTC' })}</span
>
</div>
{/if}
{#if note.links && note.links?.length > 0}
<div class="badge badge-ghost badge-sm">
<LinkVariant class="w-3 h-3 mr-1" />
{note.links.length}
{note.links.length > 1 ? $t('adventures.links') : $t('adventures.link')}
</div>
{/if}
</div>
</div>
<button
type="button"
class="btn btn-circle btn-ghost btn-sm"
on:click={() => (isDetailsOpen = false)}
aria-label={$t('about.close')}
>
<Close class="w-4 h-4" />
</button>
</div>
{#if note.content && note.content?.length > 0}
<article class="prose max-w-none text-base-content">
{@html renderMarkdown(note.content || '')}
</article>
{:else}
<p class="text-sm text-base-content/70">No content available.</p>
{/if}
{#if note.links && note.links?.length > 0}
<div class="space-y-2">
<p class="text-sm font-semibold text-base-content">{$t('adventures.links')}</p>
<div class="flex flex-wrap gap-2">
{#each note.links as link}
<a
class="badge badge-outline gap-1"
href={link}
target="_blank"
rel="noopener noreferrer"
>
<LinkVariant class="w-3 h-3" />
<span class="break-all text-left">{link}</span>
</a>
{/each}
</div>
</div>
{/if}
<div class="modal-action">
<button class="btn" on:click={() => (isDetailsOpen = false)}>Close</button>
</div>
</div>
<form method="dialog" class="modal-backdrop">
<button aria-label="close" on:click={() => (isDetailsOpen = false)}>Close</button>
</form>
</dialog>
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
aria-label="note-card"
>
<div class="card-body p-4 space-y-3">
<!-- Header -->
<div class="flex items-start justify-between gap-3">
<div class="flex-1 min-w-0">
<h2 class="text-lg font-semibold line-clamp-2">{note.name}</h2>
<div class="flex flex-wrap items-center gap-2 mt-2">
<div class="badge badge-primary badge-sm">{$t('adventures.note')}</div>
</div>
</div>
<div class="flex items-center gap-2">
<button
class="btn btn-square btn-sm p-1 text-base-content"
on:click={() => (isDetailsOpen = true)}
aria-label={$t('adventures.view')}
type="button"
>
<Launch class="w-5 h-5" />
</button>
{#if canEdit}
<div
class="dropdown dropdown-end relative z-50"
class:dropdown-open={isActionsMenuOpen}
bind:this={actionsMenuRef}
>
<button
type="button"
class="btn btn-square btn-sm p-1 text-base-content"
aria-haspopup="menu"
on:click|stopPropagation={() => {
if (isActionsMenuOpen) {
isActionsMenuOpen = false;
return;
}
closeAllNoteMenus();
isActionsMenuOpen = true;
}}
>
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
tabindex="-1"
class="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow-lg border border-base-300"
>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
editNote();
}}
class="flex items-center gap-2"
>
<FileDocumentEdit class="w-4 h-4" />
{$t('lodging.edit')}
</button>
</li>
{#if itineraryItem && itineraryItem.id}
<div class="divider my-1"></div>
{#if !itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
dispatch('moveToGlobal', { type: 'note', id: note.id });
}}
class=" flex items-center gap-2"
>
<Globe class="w-4 h-4 " />
{$t('itinerary.move_to_trip_context')}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
changeDay();
}}
class=" flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text" />
{$t('itinerary.change_day')}
</button>
</li>
{/if}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{#if itineraryItem.is_global}
{$t('itinerary.remove_from_trip_context') || 'Remove from Trip Context'}
{:else}
{$t('itinerary.remove_from_itinerary')}
{/if}
</button>
</li>
{/if}
<div class="divider my-1"></div>
<li>
<button
class="text-error flex items-center gap-2"
on:click={() => {
isActionsMenuOpen = false;
isWarningModalOpen = true;
}}
>
<TrashCan class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
</ul>
</div>
{/if}
</div>
</div>
<!-- Note Content Preview -->
{#if note.content && note.content?.length > 0}
<article
class="prose prose-sm max-w-none overflow-hidden max-h-32 text-sm text-base-content/70 line-clamp-4"
>
{@html renderMarkdown(note.content || '')}
</article>
{/if}
<!-- Inline Stats -->
<div class="flex flex-wrap items-center gap-3 text-sm text-base-content/70">
{#if note.date && note.date !== ''}
<div class="flex items-center gap-1">
<Calendar class="w-4 h-4 text-primary" />
<span>{new Date(note.date).toLocaleDateString(undefined, { timeZone: 'UTC' })}</span>
</div>
{/if}
{#if note.links && note.links?.length > 0}
<div class="badge badge-ghost badge-sm">
<LinkVariant class="w-3 h-3 mr-1" />
{note.links.length}
{note.links.length > 1 ? $t('adventures.links') : $t('adventures.link')}
</div>
{/if}
</div>
<!-- Links Preview (compact) -->
{#if note.links && note.links?.length > 0}
<div class="flex flex-wrap gap-2">
{#each note.links.slice(0, 2) as link}
<a
class="badge badge-outline badge-sm hover:badge-primary transition-colors"
href={link}
target="_blank"
rel="noopener noreferrer"
>
<LinkVariant class="w-3 h-3 mr-1" />
{link.split('//')[1]?.split('/', 1)[0]}
</a>
{/each}
{#if note.links.length > 2}
<span class="badge badge-ghost badge-sm">+{note.links.length - 2}</span>
{/if}
</div>
{/if}
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.line-clamp-4 {
display: -webkit-box;
-webkit-line-clamp: 4;
line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,101 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { addToast } from '$lib/toasts';
import type { Region, VisitedRegion } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { t } from 'svelte-i18n';
export let region: Region;
export let visited: boolean | undefined;
function goToCity() {
console.log(region);
goto(`/worldtravel/${region.id.split('-')[0]}/${region.id}`);
}
async function markVisited() {
let res = await fetch(`/api/visitedregion/`, {
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: JSON.stringify({ region: region.id })
});
if (res.ok) {
visited = true;
let data = await res.json();
addToast(
'success',
`${$t('worldtravel.visit_to')} ${region.name} ${$t('worldtravel.marked_visited')}`
);
dispatch('visit', data);
} else {
console.error($t('worldtravel.region_failed_visited'));
addToast('error', `${$t('worldtravel.failed_to_mark_visit')} ${region.name}`);
}
}
async function removeVisit() {
let res = await fetch(`/api/visitedregion/${region.id}`, {
headers: { 'Content-Type': 'application/json' },
method: 'DELETE'
});
if (res.ok) {
visited = false;
addToast('info', `${$t('worldtravel.visit_to')} ${region.name} ${$t('worldtravel.removed')}`);
dispatch('remove', region);
} else {
console.error($t('worldtravel.visit_remove_failed'));
addToast('error', `${$t('worldtravel.failed_to_remove_visit')} ${region.name}`);
}
}
</script>
<div
class="card w-full max-w-md bg-base-300 text-base-content shadow-2xl hover:shadow-3xl transition-all duration-300 border border-base-300 hover:border-primary/20 group overflow-hidden"
>
<div class="card-body p-6 space-y-4">
<!-- Header -->
<a
href="/worldtravel/{region.id.split('-')[0]}/{region.id}"
class="text-xl font-bold text-left hover:text-primary transition-colors duration-200 line-clamp-2 group-hover:underline block"
>
{region.name}
</a>
<!-- Metadata Badges -->
<div class="flex flex-wrap gap-2">
<div class="badge badge-primary">{region.country_name}</div>
<div class="badge badge-neutral">
{region.num_cities}
{$t('worldtravel.cities')}
</div>
<div class="badge badge-neutral-300">ID: {region.id}</div>
</div>
<!-- Actions -->
<div class="pt-4 border-t border-base-300 flex flex-wrap gap-2 justify-end">
{#if visited === false}
<button class="btn btn-primary btn-sm" on:click={markVisited}>
{$t('adventures.mark_visited')}
</button>
{/if}
{#if visited === true}
<button class="btn btn-warning btn-sm" on:click={removeVisit}>
{$t('adventures.remove')}
</button>
{/if}
{#if region.num_cities > 0}
<button class="btn btn-neutral btn-sm" on:click={goToCity}>
{$t('worldtravel.view_cities')}
</button>
{/if}
</div>
</div>
</div>
<style>
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

View File

@@ -0,0 +1,153 @@
<script lang="ts">
import type { Trail } from '$lib/types';
import { t } from 'svelte-i18n';
// Icons (only those used)
import Calendar from '~icons/mdi/calendar';
import Camera from '~icons/mdi/camera';
import Clock from '~icons/mdi/clock';
import MapPin from '~icons/mdi/map-marker';
import TrendingUp from '~icons/mdi/trending-up';
import Users from '~icons/mdi/account-supervisor';
export let trail: Trail;
export let measurementSystem: 'metric' | 'imperial' = 'metric';
function getDistance(meters: number) {
return measurementSystem === 'imperial'
? `${(meters * 0.000621371).toFixed(2)} mi`
: `${(meters / 1000).toFixed(2)} km`;
}
function getElevation(meters: number) {
return measurementSystem === 'imperial'
? `${(meters * 3.28084).toFixed(1)} ft`
: `${meters.toFixed(1)} m`;
}
function getDuration(minutes: number) {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
}
function formatDate(date: string | number | Date) {
return new Date(date).toLocaleDateString();
}
</script>
<div class="card bg-base-100 shadow">
<div class="card-body p-4">
<div class="flex items-start justify-between">
<div class="flex-1">
<!-- Trail Name -->
<h2 class="text-xl font-bold leading-tight mb-1">{trail.name}</h2>
<!-- Provider + Created Date -->
<div class="flex items-center gap-2 mb-2">
{#if trail.provider}
<span class="badge badge-outline badge-sm">{trail.provider}</span>
{/if}
<span class="text-sm opacity-70">
{$t('adventures.created')}: {formatDate(trail.created_at)}
</span>
</div>
{#if trail.wanderer_data}
<div class="mb-4 space-y-3">
<!-- Trail Stats -->
<div class="grid grid-cols-2 gap-3">
<div class="flex items-center gap-2 text-sm">
<MapPin class="w-3 h-3 text-base-content/60" />
<span class="text-base-content/80">
{getDistance(trail.wanderer_data.distance)}
</span>
</div>
{#if trail.wanderer_data.duration > 0}
<div class="flex items-center gap-2 text-sm">
<Clock class="w-3 h-3 text-base-content/60" />
<span class="text-base-content/80">
{getDuration(trail.wanderer_data.duration)}
</span>
</div>
{/if}
{#if trail.wanderer_data.elevation_gain > 0}
<div class="flex items-center gap-2 text-sm">
<TrendingUp class="w-3 h-3 text-base-content/60" />
<span class="text-base-content/80">
{getElevation(trail.wanderer_data.elevation_gain)}
{$t('adventures.gain')}
</span>
</div>
{/if}
<div class="flex items-center gap-2 text-sm">
<Calendar class="w-3 h-3 text-base-content/60" />
<span class="text-base-content/80">
{formatDate(trail.wanderer_data.date)}
</span>
</div>
</div>
<!-- Difficulty + Likes -->
{#if trail.wanderer_data.difficulty}
<div class="flex items-center gap-2">
<span
class="badge badge-sm"
class:badge-success={trail.wanderer_data.difficulty === 'easy'}
class:badge-warning={trail.wanderer_data.difficulty === 'moderate'}
class:badge-error={trail.wanderer_data.difficulty === 'hard'}
>
{trail.wanderer_data.difficulty}
</span>
{#if trail.wanderer_data.like_count > 0}
<div class="flex items-center gap-1 text-xs text-base-content/60">
<Users class="w-3 h-3" />
{$t('adventures.likes')}: {trail.wanderer_data.like_count}
</div>
{/if}
</div>
{/if}
<!-- Description -->
{#if trail.wanderer_data.description}
<div class="text-sm text-base-content/70 leading-relaxed">
{@html trail.wanderer_data.description}
</div>
{/if}
<!-- Location -->
{#if trail.wanderer_data.location}
<div class="text-xs text-base-content/60 flex items-center gap-1">
<MapPin class="w-3 h-3" />
{trail.wanderer_data.location}
</div>
{/if}
<!-- Photos -->
{#if trail.wanderer_data.photos?.length > 0}
<div class="flex items-center gap-1 text-xs text-base-content/60">
<Camera class="w-3 h-3" />
{$t('adventures.photos')}: {trail.wanderer_data.photos.length}
</div>
{/if}
</div>
{/if}
</div>
{#if trail.link || trail.wanderer_link}
<a
href={trail.wanderer_link || trail.link}
target="_blank"
rel="noopener noreferrer"
class="btn btn-sm btn-primary"
>
🔗 {$t('adventures.view_trail')}
</a>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,512 @@
<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte';
import TrashCanOutline from '~icons/mdi/trash-can-outline';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import type { Collection, Transportation, User } from '$lib/types';
import { addToast } from '$lib/toasts';
import { t } from 'svelte-i18n';
import DeleteWarning from '../DeleteWarning.svelte';
import { TRANSPORTATION_TYPES_ICONS } from '$lib';
import { formatAllDayDate, formatDateInTimezone } from '$lib/dateUtils';
import { isAllDay } from '$lib';
import { DEFAULT_CURRENCY, formatMoney, toMoneyValue } from '$lib/money';
import CardCarousel from '../CardCarousel.svelte';
import TransportationRoutePreview from './TransportationRoutePreview.svelte';
import Eye from '~icons/mdi/eye';
import EyeOff from '~icons/mdi/eye-off';
import Star from '~icons/mdi/star';
import StarOutline from '~icons/mdi/star-outline';
import Calendar from '~icons/mdi/calendar';
import DotsHorizontal from '~icons/mdi/dots-horizontal';
import CalendarRemove from '~icons/mdi/calendar-remove';
import Launch from '~icons/mdi/launch';
import Globe from '~icons/mdi/globe';
import { goto } from '$app/navigation';
import type { CollectionItineraryItem } from '$lib/types';
let isActionsMenuOpen = false;
let actionsMenuRef: HTMLDivElement | null = null;
const ACTIONS_CLOSE_EVENT = 'card-actions-close';
const handleCloseEvent = () => (isActionsMenuOpen = false);
function handleDocumentClick(event: MouseEvent) {
if (!isActionsMenuOpen) return;
const target = event.target as Node | null;
if (actionsMenuRef && target && !actionsMenuRef.contains(target)) {
isActionsMenuOpen = false;
}
}
function closeAllTransportationMenus() {
window.dispatchEvent(new CustomEvent(ACTIONS_CLOSE_EVENT));
}
onMount(() => {
document.addEventListener('click', handleDocumentClick);
window.addEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
return () => {
document.removeEventListener('click', handleDocumentClick);
window.removeEventListener(ACTIONS_CLOSE_EVENT, handleCloseEvent);
};
});
function getTransportationIcon(type: string) {
if (type in TRANSPORTATION_TYPES_ICONS) {
return TRANSPORTATION_TYPES_ICONS[type as keyof typeof TRANSPORTATION_TYPES_ICONS];
} else {
return '🚗';
}
}
function renderStars(rating: number) {
const stars = [];
for (let i = 1; i <= 5; i++) {
stars.push(i <= rating);
}
return stars;
}
const dispatch = createEventDispatcher();
const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
const getTimezoneLabel = (zone?: string | null) => zone ?? localTimeZone;
const getTimezoneTip = (zone?: string | null) => {
const label = getTimezoneLabel(zone);
return label === localTimeZone
? null
: `${$t('adventures.trip_timezone') ?? 'Trip TZ'}: ${label}. ${
$t('adventures.your_time') ?? 'Your time'
}: ${localTimeZone}.`;
};
export let transportation: Transportation;
export let user: User | null = null;
export let collection: Collection | null = null;
export let readOnly: boolean = false;
export let itineraryItem: CollectionItineraryItem | null = null;
const toMiles = (km: any) => (Number(km) * 0.621371).toFixed(1);
const formatTravelDuration = (minutes: number | null | undefined) => {
if (minutes === null || minutes === undefined || Number.isNaN(minutes)) return null;
const safeMinutes = Math.max(0, Math.floor(minutes));
const hours = Math.floor(safeMinutes / 60);
const mins = safeMinutes % 60;
const parts = [] as string[];
if (hours) parts.push(`${hours}h`);
parts.push(`${mins}m`);
return parts.join(' ');
};
function changeDay() {
dispatch('changeDay', { type: 'transportation', item: transportation, forcePicker: true });
}
let travelDurationLabel: string | null = null;
$: travelDurationLabel = formatTravelDuration(transportation?.travel_duration_minutes ?? null);
let showMoreDetails = false;
$: hasCodePair = Boolean(transportation?.start_code && transportation?.end_code);
$: routeFromLabel = hasCodePair
? transportation.start_code
: (transportation.from_location ?? transportation.start_code ?? null);
$: routeToLabel = hasCodePair
? transportation.end_code
: (transportation.to_location ?? transportation.end_code ?? null);
$: hasExpandableDetails = Boolean(transportation?.end_date || travelDurationLabel);
$: if (!hasExpandableDetails) showMoreDetails = false;
$: transportationPriceLabel = formatMoney(
toMoneyValue(transportation.price, transportation.price_currency, DEFAULT_CURRENCY)
);
$: routeGeojson =
transportation?.attachments?.find((attachment) => attachment?.geojson)?.geojson ?? null;
let isWarningModalOpen: boolean = false;
function editTransportation() {
dispatch('edit', transportation);
}
async function deleteTransportation() {
let res = await fetch(`/api/transportations/${transportation.id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
if (!res.ok) {
console.log($t('transportation.transportation_delete_error'));
} else {
addToast('info', $t('transportation.transportation_deleted'));
isWarningModalOpen = false;
dispatch('delete', transportation.id);
}
}
async function removeFromItinerary() {
let itineraryItemId = itineraryItem?.id;
let res = await fetch(`/api/itineraries/${itineraryItemId}`, {
method: 'DELETE'
});
if (res.ok) {
addToast('info', $t('itinerary.item_remove_success'));
dispatch('removeFromItinerary', itineraryItem);
} else {
addToast('error', $t('itinerary.item_remove_error'));
}
}
</script>
{#if isWarningModalOpen}
<DeleteWarning
title={$t('adventures.delete_transportation')}
button_text="Delete"
description={$t('adventures.transportation_delete_confirm')}
is_warning={false}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteTransportation}
/>
{/if}
<div
class="card w-full max-w-md bg-base-300 shadow hover:shadow-md transition-all duration-200 border border-base-300 group"
aria-label="transportation-card"
>
<!-- Image Section with Overlay -->
<div class="relative overflow-hidden rounded-t-2xl">
{#if routeGeojson}
<TransportationRoutePreview
geojson={routeGeojson}
name={transportation.name}
images={transportation.images}
/>
{:else}
<CardCarousel
images={transportation.images}
icon={getTransportationIcon(transportation.type)}
name={transportation.name}
/>
{/if}
<!-- Privacy Indicator -->
<div class="absolute top-2 right-4">
<div
class="tooltip tooltip-left"
data-tip={transportation.is_public ? $t('adventures.public') : $t('adventures.private')}
>
<div
class="badge badge-sm p-1 rounded-full text-base-content shadow-sm"
role="img"
aria-label={transportation.is_public ? $t('adventures.public') : $t('adventures.private')}
>
{#if transportation.is_public}
<Eye class="w-4 h-4" />
{:else}
<EyeOff class="w-4 h-4" />
{/if}
</div>
</div>
</div>
<!-- Category Badge -->
{#if transportation.type}
<div class="absolute bottom-4 left-4">
<div class="badge badge-primary shadow-lg font-medium">
{$t(`transportation.modes.${transportation.type}`)}
{getTransportationIcon(transportation.type)}
</div>
</div>
{/if}
</div>
<div class="card-body p-4 space-y-3 min-w-0">
<!-- Header -->
<div class="flex items-start justify-between gap-3">
<a
href="/transportations/{transportation.id}"
class="hover:text-primary transition-colors duration-200 line-clamp-2 text-lg font-semibold"
>
{transportation.name}
</a>
<div class="flex items-center gap-2">
<button
class="btn btn-sm p-1 text-base-content"
aria-label="open-details"
on:click={() => goto(`/transportations/${transportation.id}`)}
>
<Launch class="w-4 h-4" />
</button>
{#if !readOnly && (transportation.user === user?.uuid || (collection && user && collection.shared_with?.includes(user.uuid)))}
<div
class="dropdown dropdown-end relative z-50"
class:dropdown-open={isActionsMenuOpen}
bind:this={actionsMenuRef}
>
<button
type="button"
class="btn btn-square btn-sm p-1 text-base-content"
aria-haspopup="menu"
on:click|stopPropagation={() => {
if (isActionsMenuOpen) {
isActionsMenuOpen = false;
return;
}
closeAllTransportationMenus();
isActionsMenuOpen = true;
}}
>
<DotsHorizontal class="w-5 h-5" />
</button>
<ul
tabindex="-1"
class="dropdown-content menu bg-base-100 rounded-box z-[9999] w-52 p-2 shadow-lg border border-base-300"
>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
editTransportation();
}}
class="flex items-center gap-2"
>
<FileDocumentEdit class="w-4 h-4" />
{$t('transportation.edit')}
</button>
</li>
{#if itineraryItem && itineraryItem.id}
<div class="divider my-1"></div>
{#if !itineraryItem.is_global}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
dispatch('moveToGlobal', { type: 'transportation', id: transportation.id });
}}
class=" flex items-center gap-2"
>
<Globe class="w-4 h-4 " />
{$t('itinerary.move_to_trip_context') || 'Move to Trip Context'}
</button>
</li>
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
changeDay();
}}
class=" flex items-center gap-2"
>
<Calendar class="w-4 h-4 text" />
{$t('itinerary.change_day')}
</button>
</li>
{/if}
<li>
<button
on:click={() => {
isActionsMenuOpen = false;
removeFromItinerary();
}}
class="text-error flex items-center gap-2"
>
<CalendarRemove class="w-4 h-4 text-error" />
{#if itineraryItem.is_global}
{$t('itinerary.remove_from_trip_context') || 'Remove from Trip Context'}
{:else}
{$t('itinerary.remove_from_itinerary')}
{/if}
</button>
</li>
{/if}
<div class="divider my-1"></div>
<li>
<button
class="text-error flex items-center gap-2"
on:click={() => {
isActionsMenuOpen = false;
isWarningModalOpen = true;
}}
>
<TrashCanOutline class="w-4 h-4" />
{$t('adventures.delete')}
</button>
</li>
</ul>
</div>
{/if}
</div>
</div>
<!-- Route & Flight Info -->
{#if routeFromLabel || routeToLabel}
<div class="flex items-center gap-2 min-w-0">
{#if routeFromLabel}
<span class="text-base font-semibold text-base-content truncate max-w-[10rem]"
>{routeFromLabel}</span
>
{/if}
{#if routeFromLabel && routeToLabel}
<span class="text-primary text-lg">→</span>
{/if}
{#if routeToLabel}
<span class="text-base font-semibold text-base-content truncate max-w-[10rem]"
>{routeToLabel}</span
>
{/if}
{#if hasCodePair && transportation.type === 'plane' && transportation.flight_number}
<div class="divider divider-horizontal mx-1"></div>
<span class="badge badge-primary badge-sm font-medium"
>{transportation.flight_number}</span
>
{/if}
</div>
{/if}
<!-- Date & Time Section -->
{#if transportation.date}
<div class="flex flex-col gap-1.5">
{#if isAllDay(transportation.date) && (!transportation.end_date || isAllDay(transportation.end_date))}
<!-- All-day event -->
<div class="flex items-center gap-2 text-sm">
<span class="font-medium text-base-content"
>{formatAllDayDate(transportation.date)}</span
>
{#if transportation.end_date && transportation.end_date !== transportation.date}
<span class="text-base-content/40">→</span>
<span class="font-medium text-base-content"
>{formatAllDayDate(transportation.end_date)}</span
>
{/if}
</div>
{:else}
<!-- Compact departure card with tidy layout -->
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs text-base-content/60">Departure</span>
<span class="text-sm font-semibold text-base-content">
{formatDateInTimezone(transportation.date, transportation.start_timezone)}
</span>
</div>
{#if hasCodePair}
<span class="badge badge-outline badge-sm font-medium whitespace-nowrap">
{transportation.start_code} → {transportation.end_code}
</span>
{/if}
</div>
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div
class="tooltip"
data-tip={getTimezoneTip(transportation.start_timezone) ?? undefined}
>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(transportation.start_timezone)}
</span>
</div>
</div>
</div>
{#if hasExpandableDetails}
<div class="flex justify-end">
<button
class="btn btn-neutral-200 btn-xs"
aria-expanded={showMoreDetails}
on:click={() => (showMoreDetails = !showMoreDetails)}
type="button"
>
{showMoreDetails
? ($t('common.show_less') ?? 'Hide details')
: ($t('common.show_more') ?? 'Show more')}
</button>
</div>
{/if}
{#if showMoreDetails && hasExpandableDetails}
<div class="flex flex-col gap-1">
{#if transportation.end_date}
<div class="bg-base-200 rounded-lg px-3 py-2 flex flex-col gap-2">
<div class="flex items-center justify-between gap-2">
<div class="flex flex-col gap-0.5 min-w-0">
<span class="text-xs text-base-content/60">Arrival</span>
<span class="text-sm font-semibold text-base-content">
{formatDateInTimezone(
transportation.end_date,
transportation.end_timezone ?? transportation.start_timezone
)}
</span>
</div>
</div>
<div class="flex items-center gap-2 text-xs text-base-content/70">
<div
class="tooltip"
data-tip={getTimezoneTip(
transportation.end_timezone ?? transportation.start_timezone
) ?? undefined}
>
<span class="badge badge-ghost badge-sm">
{getTimezoneLabel(
transportation.end_timezone ?? transportation.start_timezone
)}
</span>
</div>
</div>
</div>
{/if}
</div>
{/if}
{/if}
</div>
{/if}
<!-- Stats & Rating -->
<div class="flex flex-wrap items-center gap-2 text-sm">
{#if transportationPriceLabel}
<span class="badge badge-ghost badge-sm">💰 {transportationPriceLabel}</span>
{/if}
{#if transportation.distance && !isNaN(+transportation.distance)}
<span class="badge badge-ghost badge-sm">
🌍 {user?.measurement_system === 'imperial'
? `${toMiles(transportation.distance)} mi`
: `${(+transportation.distance).toFixed(1)} km`}
</span>
{/if}
{#if travelDurationLabel}
<span class="badge badge-ghost badge-sm">⏱️ {travelDurationLabel}</span>
{/if}
{#if transportation.rating}
<div class="flex items-center gap-1">
<div class="flex -ml-1">
{#each renderStars(transportation.rating) as filled}
{#if filled}
<Star class="w-4 h-4 text-warning fill-current" />
{:else}
<StarOutline class="w-4 h-4 text-base-content/30" />
{/if}
{/each}
</div>
<span class="text-xs text-base-content/60">({transportation.rating}/5)</span>
</div>
{/if}
</div>
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,183 @@
<script lang="ts">
import ImageDisplayModal from '../ImageDisplayModal.svelte';
import type { ContentImage } from '$lib/types';
export let geojson: any;
export let name: string = '';
export let images: ContentImage[] = [];
export let heightClass: string = 'h-48';
let showImageModal = false;
let modalInitialIndex = 0;
$: sortedImages = [...images]
.filter((img) => !!img?.image)
.sort((a, b) => Number(b?.is_primary) - Number(a?.is_primary));
$: routeCoordinates = extractLineCoords(geojson);
$: normalizedRoute = normalizeCoords(routeCoordinates);
$: pathD = buildPath(normalizedRoute);
$: hasRoute = !!pathD;
$: startPoint = normalizedRoute.length > 0 ? normalizedRoute[0] : null;
$: endPoint =
normalizedRoute.length > 1 ? normalizedRoute[normalizedRoute.length - 1] : startPoint;
function openImageModal(initialIndex: number = 0) {
if (!sortedImages.length) return;
modalInitialIndex = initialIndex;
showImageModal = true;
}
function closeImageModal() {
showImageModal = false;
}
type LonLat = [number, number];
type NormalizedPoint = { x: number; y: number };
function extractLineCoords(data: any): LonLat[] {
if (!data || typeof data !== 'object') return [];
if (data.type === 'FeatureCollection' && Array.isArray(data.features)) {
return data.features.flatMap((feature: any) => extractLineCoords(feature));
}
if (data.type === 'Feature') {
return extractLineCoords(data.geometry);
}
if (data.type === 'GeometryCollection' && Array.isArray(data.geometries)) {
return data.geometries.flatMap((geom: any) => extractLineCoords(geom));
}
if (data.type === 'LineString' && Array.isArray(data.coordinates)) {
return sanitizeCoordinates(data.coordinates);
}
if (data.type === 'MultiLineString' && Array.isArray(data.coordinates)) {
return data.coordinates.flatMap((line: any) => sanitizeCoordinates(line));
}
return [];
}
function sanitizeCoordinates(raw: any): LonLat[] {
if (!Array.isArray(raw)) return [];
const coords: LonLat[] = [];
for (const point of raw) {
if (!Array.isArray(point) || point.length < 2) continue;
const lon = Number(point[0]);
const lat = Number(point[1]);
if (Number.isFinite(lon) && Number.isFinite(lat)) {
coords.push([lon, lat]);
}
}
return coords;
}
function normalizeCoords(coords: LonLat[]): NormalizedPoint[] {
if (!coords.length) return [];
const lons = coords.map(([lon]) => lon);
const lats = coords.map(([, lat]) => lat);
const minLon = Math.min(...lons);
const maxLon = Math.max(...lons);
const minLat = Math.min(...lats);
const maxLat = Math.max(...lats);
const spanLon = maxLon - minLon || 1;
const spanLat = maxLat - minLat || 1;
const padLon = spanLon * 0.05;
const padLat = spanLat * 0.05;
const originLon = minLon - padLon;
const originLat = minLat - padLat;
const scaleX = 100 / (spanLon + padLon * 2);
const scaleY = 100 / (spanLat + padLat * 2);
return coords.map(([lon, lat]) => ({
x: (lon - originLon) * scaleX,
y: 100 - (lat - originLat) * scaleY
}));
}
function buildPath(points: NormalizedPoint[]): string {
if (!points.length) return '';
return points
.map((p, idx) => `${idx === 0 ? 'M' : 'L'} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`)
.join(' ');
}
</script>
{#if showImageModal && sortedImages.length > 0}
<ImageDisplayModal
images={sortedImages}
initialIndex={modalInitialIndex}
on:close={closeImageModal}
{name}
/>
{/if}
<div
class={`relative w-full ${heightClass} rounded-t-2xl bg-gradient-to-r from-success via-base to-primary overflow-hidden`}
aria-label="route-preview"
>
<svg viewBox="0 0 100 100" class="w-full h-full" role="img" aria-label="Route preview">
<!-- No separate bg; rely on parent gradient -->
{#if hasRoute}
<g stroke-linecap="round" stroke-linejoin="round">
<path
d={pathD}
fill="none"
stroke="var(--color-base-content, #111827)"
stroke-width="2.6"
opacity="0.55"
/>
{#if startPoint}
<circle
cx={startPoint.x}
cy={startPoint.y}
r="2.4"
fill="var(--color-base-content, #111827)"
opacity="0.9"
/>
{/if}
{#if endPoint}
<circle
cx={endPoint.x}
cy={endPoint.y}
r="2.8"
fill="var(--color-base-content, #111827)"
opacity="0.9"
/>
{/if}
</g>
{:else}
<text
x="50"
y="50"
text-anchor="middle"
fill="var(--color-base-content, #111827)"
opacity="0.6"
>
Route unavailable
</text>
{/if}
</svg>
<div class="absolute top-3 left-3 badge badge-primary gap-1 shadow">
<span class="text-xs font-semibold">GPX</span>
<span class="text-xs">Route</span>
</div>
{#if sortedImages.length > 0}
<button
type="button"
on:click|stopPropagation={() => openImageModal(0)}
class="btn btn-xs btn-neutral absolute bottom-3 right-3 shadow"
>
View photos ({sortedImages.length})
</button>
{/if}
</div>

View File

@@ -0,0 +1,115 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { continentCodeToString, getFlag } from '$lib';
import type { User } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { t } from 'svelte-i18n';
import Calendar from '~icons/mdi/calendar';
export let sharing: boolean = false;
export let shared_with: string[] | undefined = undefined;
export let user: User & { status?: 'available' | 'pending' };
$: isShared = shared_with?.includes(user.uuid) || false;
$: isPending = user.status === 'pending';
$: isAvailable = user.status === 'available';
function handleShare() {
dispatch('share', user);
}
function handleUnshare() {
dispatch('unshare', user);
}
function handleRevoke() {
dispatch('revoke', user);
}
</script>
<div
class="card w-full max-w-xs bg-base-200 text-base-content shadow-lg border border-base-300 hover:shadow-xl transition-all"
>
<div class="card-body items-center text-center space-y-4">
<!-- Profile Picture -->
<div class="avatar">
<div class="w-24 rounded-full ring ring-primary ring-offset-base-100 ring-offset-2">
{#if user.profile_pic}
<img src={user.profile_pic} alt={user.username} />
{:else}
<div
class="bg-base-300 w-full h-full flex items-center justify-center text-xl font-semibold"
>
{user.first_name?.[0] || user.username?.[0]}{user.last_name?.[0] || user.username?.[1]}
</div>
{/if}
</div>
</div>
<!-- User Info -->
<div>
<h2 class="text-lg font-bold leading-tight">
{user.first_name}
{user.last_name}
</h2>
<p class="text-sm opacity-70">@{user.username}</p>
{#if user.is_staff}
<div class="badge badge-outline badge-primary mt-2">{$t('settings.admin')}</div>
{/if}
<!-- Status Badge for sharing mode -->
{#if sharing}
{#if isPending}
<div class="badge badge-warning badge-sm mt-2">
{$t('share.pending')}
</div>
{:else if isShared}
<div class="badge badge-success badge-sm mt-2">
{$t('share.shared')}
</div>
{:else if isAvailable}
<div class="badge badge-ghost badge-sm mt-2">
{$t('share.available')}
</div>
{/if}
{/if}
</div>
<!-- Join Date -->
<div class="flex items-center gap-2 text-sm text-base-content/70">
<Calendar class="w-4 h-4 text-primary" />
<span>
{user.date_joined
? `${$t('adventures.joined')} ` + new Date(user.date_joined).toLocaleDateString()
: ''}
</span>
</div>
<!-- Actions -->
<div class="card-actions w-full justify-center pt-2">
{#if !sharing}
<button
class="btn btn-sm btn-primary w-full"
on:click={() => goto(`/profile/${user.username}`)}
>
{$t('adventures.view_profile')}
</button>
{:else if isShared}
<button class="btn btn-sm btn-error w-full" on:click={handleUnshare}>
{$t('adventures.remove')}
</button>
{:else if isPending}
<button class="btn btn-sm btn-warning btn-outline w-full" on:click={handleRevoke}>
{$t('share.revoke_invite')}
</button>
{:else if isAvailable}
<button class="btn btn-sm btn-success w-full" on:click={handleShare}>
{$t('share.send_invite')}
</button>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,168 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import { t } from 'svelte-i18n';
const dispatch = createEventDispatcher();
import MountainIcon from '~icons/mdi/mountain';
import MapPinIcon from '~icons/mdi/map-marker';
import CalendarIcon from '~icons/mdi/calendar';
import CameraIcon from '~icons/mdi/camera';
import FileIcon from '~icons/mdi/file';
import LinkIcon from '~icons/mdi/link-variant';
import type { WandererTrail } from '$lib/types';
export let trail: WandererTrail;
// Helper functions
/**
* @param {number} distanceInMeters
*/
function formatDistance(distanceInMeters: number) {
const miles = (distanceInMeters * 0.000621371).toFixed(1);
return `${miles} mi`;
}
/**
* @param {number} elevationInMeters
*/
function formatElevation(elevationInMeters: number) {
const feet = Math.round(elevationInMeters * 3.28084);
return `${feet}ft`;
}
/**
* @param {string} difficulty
*/
function getDifficultyBadgeClass(difficulty: string) {
switch (difficulty?.toLowerCase()) {
case 'easy':
return 'badge-success';
case 'moderate':
return 'badge-warning';
case 'difficult':
return 'badge-error';
default:
return 'badge-outline';
}
}
/**
* @param {string | number | Date} dateString
*/
function formatDate(dateString: string | number | Date) {
if (!dateString) return '';
return new Date(dateString).toLocaleDateString();
}
/**
* @param {string} html
*/
function stripHtml(html: string) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
</script>
<div class="bg-base-200/50 p-4 rounded-lg shadow-sm">
<div class="flex items-start justify-between">
<div class="flex-1 min-w-0">
<!-- Header with trail name and difficulty -->
<div class="flex items-center gap-2 mb-2">
<MountainIcon class="w-4 h-4 text-primary flex-shrink-0" />
<h5 class="font-semibold text-base truncate">{trail.name}</h5>
<span class="badge {getDifficultyBadgeClass(trail.difficulty)} badge-sm">
{trail.difficulty}
</span>
</div>
<!-- Location -->
{#if trail.location}
<div class="flex items-center gap-1 mb-2">
<MapPinIcon class="w-3 h-3 text-base-content/60" />
<span class="text-sm text-base-content/70">{trail.location}</span>
</div>
{/if}
<!-- Trail stats -->
<div class="text-xs text-base-content/70 space-y-1">
{#if trail.distance}
<div class="flex items-center gap-4">
<span>{$t('adventures.distance')}: {formatDistance(trail.distance)}</span>
{#if trail.duration > 0}
<span>{$t('adventures.duration')}: {Math.round(trail.duration / 60)} min</span>
{/if}
</div>
{/if}
{#if trail.elevation_gain > 0 || trail.elevation_loss > 0}
<div class="flex items-center gap-4">
{#if trail.elevation_gain > 0}
<span class="text-success">{formatElevation(trail.elevation_gain)}</span>
{/if}
{#if trail.elevation_loss > 0}
<span class="text-error">{formatElevation(trail.elevation_loss)}</span>
{/if}
</div>
{/if}
{#if trail.waypoints && trail.waypoints.length > 0}
<div>
Waypoints: {trail.waypoints.length}
</div>
{/if}
{#if trail.created}
<div class="flex items-center gap-1">
<CalendarIcon class="w-3 h-3" />
<span>{$t('adventures.created')}: {formatDate(trail.created)}</span>
</div>
{/if}
{#if trail.photos && trail.photos.length > 0}
<div class="flex items-center gap-1">
<CameraIcon class="w-3 h-3" />
<span>{$t('adventures.photos')}: {trail.photos.length}</span>
</div>
{/if}
{#if trail.gpx}
<div class="flex items-center gap-1">
<FileIcon class="w-3 h-3" />
<a href={trail.gpx} target="_blank" class="link link-primary text-xs">
{$t('adventures.view_gpx')}
</a>
</div>
{/if}
</div>
<!-- Description preview -->
{#if trail.description}
<div class="mt-3 pt-2 border-t border-base-300">
<p class="text-xs text-base-content/60 line-clamp-2">
{stripHtml(trail.description).substring(0, 150)}...
</p>
</div>
{/if}
</div>
<!-- button to link trail to activity -->
<div class="flex-shrink-0 ml-4">
<button
class="btn btn-primary btn-xs tooltip tooltip-top"
on:click={() => dispatch('link', trail)}
aria-label="Link Trail to Activity"
>
<LinkIcon class="w-3 h-3" />
</button>
</div>
</div>
</div>
<style>
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>