feat:finds on homepage

This commit is contained in:
2025-10-13 12:24:20 +02:00
parent 1d858e40e1
commit b95c7dad7b
7 changed files with 855 additions and 8 deletions

View File

@@ -1,13 +1,155 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { db } from '$lib/server/db';
import { find, findMedia, user } from '$lib/server/db/schema';
import { eq, and, sql, desc } from 'drizzle-orm';
import { getSignedR2Url } from '$lib/server/r2';
export const load: PageServerLoad = async (event) => {
if (!event.locals.user) {
// if not logged in, redirect to login page
return redirect(302, '/login');
export const load: PageServerLoad = async ({ locals, url }) => {
if (!locals.user) {
return redirect(302, '/login');
}
return {
user: event.locals.user
};
// Get query parameters for location-based filtering
const lat = url.searchParams.get('lat');
const lng = url.searchParams.get('lng');
const radius = url.searchParams.get('radius') || '50'; // Default 50km radius
try {
// Build where conditions
const baseCondition = sql`(${find.isPublic} = 1 OR ${find.userId} = ${locals.user.id})`;
let whereConditions = baseCondition;
// Add location filtering if coordinates provided
if (lat && lng) {
const radiusKm = parseFloat(radius);
// Simple bounding box query for MVP (can upgrade to proper distance calculation later)
const latOffset = radiusKm / 111; // Approximate degrees per km for latitude
const lngOffset = radiusKm / (111 * Math.cos((parseFloat(lat) * Math.PI) / 180));
const locationConditions = and(
baseCondition,
sql`${find.latitude} BETWEEN ${parseFloat(lat) - latOffset} AND ${
parseFloat(lat) + latOffset
}`,
sql`${find.longitude} BETWEEN ${parseFloat(lng) - lngOffset} AND ${
parseFloat(lng) + lngOffset
}`
);
if (locationConditions) {
whereConditions = locationConditions;
}
}
// Get all finds with filtering
const finds = await db
.select({
id: find.id,
title: find.title,
description: find.description,
latitude: find.latitude,
longitude: find.longitude,
locationName: find.locationName,
category: find.category,
isPublic: find.isPublic,
createdAt: find.createdAt,
userId: find.userId,
username: user.username
})
.from(find)
.innerJoin(user, eq(find.userId, user.id))
.where(whereConditions)
.orderBy(desc(find.createdAt))
.limit(100);
// Get media for all finds
const findIds = finds.map((f) => f.id);
let media: Array<{
id: string;
findId: string;
type: string;
url: string;
thumbnailUrl: string | null;
orderIndex: number | null;
}> = [];
if (findIds.length > 0) {
media = await db
.select({
id: findMedia.id,
findId: findMedia.findId,
type: findMedia.type,
url: findMedia.url,
thumbnailUrl: findMedia.thumbnailUrl,
orderIndex: findMedia.orderIndex
})
.from(findMedia)
.where(
sql`${findMedia.findId} IN (${sql.join(
findIds.map((id) => sql`${id}`),
sql`, `
)})`
)
.orderBy(findMedia.orderIndex);
}
// Group media by find
const mediaByFind = media.reduce(
(acc, item) => {
if (!acc[item.findId]) {
acc[item.findId] = [];
}
acc[item.findId].push(item);
return acc;
},
{} as Record<string, typeof media>
);
// Combine finds with their media and generate signed URLs
const findsWithMedia = await Promise.all(
finds.map(async (findItem) => {
const findMedia = mediaByFind[findItem.id] || [];
// Generate signed URLs for all media items
const mediaWithSignedUrls = await Promise.all(
findMedia.map(async (mediaItem) => {
// Extract path from URL if it's still a full URL, otherwise use as-is
const path = mediaItem.url.startsWith('https://')
? mediaItem.url.split('/').slice(3).join('/')
: mediaItem.url;
const thumbnailPath = mediaItem.thumbnailUrl?.startsWith('https://')
? mediaItem.thumbnailUrl.split('/').slice(3).join('/')
: mediaItem.thumbnailUrl;
const [signedUrl, signedThumbnailUrl] = await Promise.all([
getSignedR2Url(path, 24 * 60 * 60), // 24 hours
thumbnailPath ? getSignedR2Url(thumbnailPath, 24 * 60 * 60) : Promise.resolve(null)
]);
return {
...mediaItem,
url: signedUrl,
thumbnailUrl: signedThumbnailUrl
};
})
);
return {
...findItem,
media: mediaWithSignedUrls
};
})
);
return {
finds: findsWithMedia
};
} catch (err) {
console.error('Error loading finds:', err);
return {
finds: []
};
}
};

View File

@@ -1,5 +1,149 @@
<script lang="ts">
import { Map } from '$lib';
import FindsList from '$lib/components/FindsList.svelte';
import CreateFindModal from '$lib/components/CreateFindModal.svelte';
import FindPreview from '$lib/components/FindPreview.svelte';
import type { PageData } from './$types';
import { coordinates } from '$lib/stores/location';
import { Button } from '$lib/components/button';
// Server response type
interface ServerFind {
id: string;
title: string;
description?: string;
latitude: string;
longitude: string;
locationName?: string;
category?: string;
isPublic: number;
createdAt: Date;
userId: string;
username: string;
media: Array<{
id: string;
findId: string;
type: string;
url: string;
thumbnailUrl: string | null;
orderIndex: number | null;
}>;
}
// Map component type
interface MapFind {
id: string;
title: string;
description?: string;
latitude: string;
longitude: string;
locationName?: string;
category?: string;
isPublic: number;
createdAt: Date;
userId: string;
user: {
id: string;
username: string;
};
media?: Array<{
type: string;
url: string;
thumbnailUrl: string;
}>;
}
// Interface for FindPreview component
interface FindPreviewData {
id: string;
title: string;
description?: string;
latitude: string;
longitude: string;
locationName?: string;
category?: string;
createdAt: string;
user: {
id: string;
username: string;
};
media?: Array<{
type: string;
url: string;
thumbnailUrl: string;
}>;
}
let { data }: { data: PageData & { finds?: ServerFind[] } } = $props();
let showCreateModal = $state(false);
let selectedFind: FindPreviewData | null = $state(null);
// Reactive finds list - convert server format to component format
let finds = $derived(
(data.finds || ([] as ServerFind[])).map((serverFind: ServerFind) => ({
...serverFind,
user: {
id: serverFind.userId,
username: serverFind.username
},
media: serverFind.media?.map(
(m: { type: string; url: string; thumbnailUrl: string | null }) => ({
type: m.type,
url: m.url,
thumbnailUrl: m.thumbnailUrl || m.url
})
)
})) as MapFind[]
);
function handleFindCreated(event: CustomEvent) {
// For now, just close modal and refresh page as in original implementation
showCreateModal = false;
if (event.detail?.reload) {
window.location.reload();
}
}
function handleFindClick(find: MapFind) {
// Convert MapFind to FindPreviewData format
selectedFind = {
id: find.id,
title: find.title,
description: find.description,
latitude: find.latitude,
longitude: find.longitude,
locationName: find.locationName,
category: find.category,
createdAt: find.createdAt.toISOString(),
user: find.user,
media: find.media?.map((m) => ({
type: m.type,
url: m.url,
thumbnailUrl: m.thumbnailUrl || m.url
}))
};
}
function handleFindExplore(id: string) {
// Find the specific find and show preview
const find = finds.find((f) => f.id === id);
if (find) {
handleFindClick(find);
}
}
function closeFindPreview() {
selectedFind = null;
}
function openCreateModal() {
showCreateModal = true;
}
function closeCreateModal() {
showCreateModal = false;
}
</script>
<svelte:head>
@@ -25,14 +169,55 @@
<div class="home-container">
<main class="main-content">
<div class="map-section">
<Map showLocationButton={true} autoCenter={true} />
<Map
showLocationButton={true}
autoCenter={true}
center={[$coordinates?.longitude || 0, $coordinates?.latitude || 51.505]}
{finds}
onFindClick={handleFindClick}
/>
</div>
<div class="finds-section">
<div class="finds-header">
<FindsList {finds} onFindExplore={handleFindExplore} />
<Button onclick={openCreateModal} class="create-find-button">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" class="mr-2">
<line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" stroke-width="2" />
<line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2" />
</svg>
Create Find
</Button>
</div>
</div>
</main>
<!-- Floating action button for mobile -->
<button class="fab" onclick={openCreateModal} aria-label="Create new find">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" stroke-width="2" />
<line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2" />
</svg>
</button>
</div>
<!-- Modals -->
{#if showCreateModal}
<CreateFindModal
isOpen={showCreateModal}
onClose={closeCreateModal}
onFindCreated={handleFindCreated}
/>
{/if}
{#if selectedFind}
<FindPreview find={selectedFind} onClose={closeFindPreview} />
{/if}
<style>
.home-container {
background-color: #f8f8f8;
min-height: 100vh;
}
.main-content {
@@ -56,16 +241,79 @@
border-radius: 0;
}
.finds-section {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
position: relative;
}
.finds-header {
position: relative;
}
:global(.create-find-button) {
position: absolute;
top: 0;
right: 0;
z-index: 10;
}
.fab {
position: fixed;
bottom: 2rem;
right: 2rem;
width: 56px;
height: 56px;
background: hsl(var(--primary));
color: hsl(var(--primary-foreground));
border: none;
border-radius: 50%;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
transition: all 0.2s;
z-index: 100;
}
.fab:hover {
transform: scale(1.1);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}
@media (max-width: 768px) {
.main-content {
padding: 16px;
gap: 16px;
}
.finds-section {
padding: 16px;
}
:global(.create-find-button) {
display: none;
}
.fab {
display: flex;
}
.map-section :global(.map-container) {
height: 300px;
}
}
@media (max-width: 480px) {
.main-content {
padding: 12px;
}
.finds-section {
padding: 12px;
}
}
</style>