map speed improvements

This commit is contained in:
Christian Beutel
2025-02-10 18:10:14 +01:00
parent 3173be8d79
commit 550e3daa43
10 changed files with 207 additions and 94 deletions

View File

@@ -55,7 +55,7 @@
<div
class="relative w-full basis-full max-h-48 overflow-hidden rounded-t-2xl"
>
<img class="h-full w-full" id="header-img" src={thumbnail} alt="" />
<img loading="lazy" class="w-full h-full" id="header-img" src={thumbnail} alt="" />
</div>
{#if (trail.public || trailIsShared) && pb.authStore.model}
<div
@@ -73,7 +73,9 @@
</span>
{/if}
{#if trail.expand?.trail_share_via_trail?.length}
<ShareInfo type="trail" subject={trail}></ShareInfo>
<span class="tooltip" data-title={$_("shared")}>
<i class="fa fa-share-nodes"></i>
</span>
{/if}
</div>
{/if}

View File

@@ -214,8 +214,8 @@
<div
class="flex absolute justify-between items-end w-full bottom-8 left-0 px-8 gap-y-4"
>
<div class="text-white">
<h4 class="text-4xl font-bold">
<div class="text-white overflow-hidden">
<h4 title={trail.name} class="text-4xl font-bold line-clamp-3">
{trail.name}
</h4>
{#if trail.date}
@@ -370,7 +370,7 @@
<EmptyStateDescription></EmptyStateDescription>
{/if}
<h4 class="text-2xl font-semibold mb-6 mt-12">
{$_("route", { values: { n: 2 } })}
{$_("route", { values: { n: 1 } })}
</h4>
{#if mode === "overview"}
<div

View File

@@ -68,7 +68,7 @@
<div class="p-4">
<h5 class="text-xl font-semibold">{wp.name}</h5>
<span class="text-sm text-gray-500"
>{wp.lat.toFixed(5)}, {wp.lon.toFixed(5)}</span
><i class="fa fa-location-dot mr-1"></i> {wp.lat.toFixed(5)}, {wp.lon.toFixed(5)}</span
>
<p class="whitespace-pre-line">
{wp.description}

View File

@@ -27,10 +27,10 @@ class Trail {
summit_logs: string[];
expand?: {
category?: Category;
waypoints: Waypoint[]
summit_logs: SummitLog[]
waypoints?: Waypoint[]
summit_logs?: SummitLog[]
author?: UserAnonymous
comments_via_trail: Comment[]
comments_via_trail?: Comment[]
gpx_data?: string
trail_share_via_trail?: TrailShare[]
}
@@ -142,6 +142,35 @@ interface TrailBoundingBox {
min_lon: number,
}
interface TrailSearchResult {
id: string;
author: string;
author_name: string;
author_avatar: string;
name: string;
description: string;
location: string;
distance: number;
elevation_gain: number;
elevation_loss: number;
duration: number;
difficulty: "easy" | "moderate" | "difficult";
category: string;
completed: boolean;
date: number;
created: number;
public: boolean;
thumbnail: string;
shares?: string[];
gpx: string;
_geo: {
lat: number,
lng: number
};
}
export { Trail };
export type { TrailBoundingBox, TrailFilter, TrailFilterValues };
export type { TrailBoundingBox, TrailFilter, TrailFilterValues, TrailSearchResult };

View File

@@ -1,12 +1,12 @@
import type { SummitLog } from "$lib/models/summit_log";
import { Trail, type TrailFilter, type TrailFilterValues } from "$lib/models/trail";
import { Trail, type TrailFilter, type TrailFilterValues, type TrailSearchResult } from "$lib/models/trail";
import type { Waypoint } from "$lib/models/waypoint";
import { pb } from "$lib/pocketbase";
import { deepEqual } from "$lib/util/deep_util";
import { getFileURL } from "$lib/util/file_util";
import * as M from "maplibre-gl";
import type { Hits } from "meilisearch";
import { type ListResult } from "pocketbase";
import { type ListResult, type RecordModel } from "pocketbase";
import { writable, type Writable } from "svelte/store";
import { summit_logs_create, summit_logs_delete, summit_logs_update } from "./summit_log_store";
import { waypoints_create, waypoints_delete, waypoints_update } from "./waypoint_store";
@@ -59,7 +59,15 @@ export async function trails_search_filter(filter: TrailFilter, page: number = 1
let r = await f("/api/v1/search/trails", {
method: "POST",
body: JSON.stringify({ q: filter.q, options: { filter: filterText, sort: [`${filter.sort}:${filter.sortOrder == "+" ? "asc" : "desc"}`], hitsPerPage: 12, page: page } }),
body: JSON.stringify({
q: filter.q,
options: {
filter: filterText,
sort: [`${filter.sort}:${filter.sortOrder == "+" ? "asc" : "desc"}`],
hitsPerPage: 12,
page: page
}
}),
});
if (!r.ok) {
@@ -67,35 +75,19 @@ export async function trails_search_filter(filter: TrailFilter, page: number = 1
throw new APIError(r.status, response.message, response.detail)
}
const result: { page: number, totalPages: number, hits: Hits<Record<string, any>> } = await r.json();
const result: { page: number, totalPages: number, hits: Hits<TrailSearchResult> } = await r.json();
const trailIds = result.hits.map((h: Record<string, any>) => h.id);
if (trailIds.length == 0) {
if (result.hits.length == 0) {
return { items: [], ...result };
}
r = await f('/api/v1/trail?' + new URLSearchParams({
expand: "category,waypoints,summit_logs,trail_share_via_trail",
filter: `'${trailIds.join(',')}'~id`,
sort: `${filter.sortOrder}${filter.sort}`
}), {
method: 'GET',
})
const resultTrails: Trail[] = await searchResultToTrailList(result.hits)
if (!r.ok) {
const response = await r.json();
throw new APIError(r.status, response.message, response.detail)
}
const response: ListResult<Trail> = await r.json()
return { items: response.items, ...result };
return { items: resultTrails, ...result };
}
export async function trails_search_bounding_box(northEast: M.LngLat, southWest: M.LngLat, filter?: TrailFilter, loadGPX: boolean = true) {
export async function trails_search_bounding_box(northEast: M.LngLat, southWest: M.LngLat, filter?: TrailFilter, page: number = 1, loadGPX: boolean = true) {
let filterText: string = "";
@@ -106,57 +98,29 @@ export async function trails_search_bounding_box(northEast: M.LngLat, southWest:
let r = await fetch("/api/v1/search/trails", {
method: "POST",
body: JSON.stringify({
q: "", options: {
limit: 100,
q: "",
options: {
filter: [
`_geoBoundingBox([${northEast.lat}, ${northEast.lng}], [${southWest.lat}, ${southWest.lng}])`,
filterText
],
hitsPerPage: 500,
page: page
}
}),
});
const result = await r.json();
const result: { page: number, totalPages: number, hits: Hits<TrailSearchResult> } = await r.json();
const trailIds = result.hits?.map((h: Record<string, any>) => h.id) ?? [];
if (trailIds.length == 0) {
const currentTrails: Trail[] = trails;
const comparison = compareObjectArrays<Trail>(currentTrails, []);
if (result.hits.length == 0) {
trails = [];
return { trails: [], ...comparison }
return { trails: [], ...result }
}
r = await fetch('/api/v1/trail?' + new URLSearchParams({
"perPage": "-1",
filter: `'${trailIds.join(',')}'~id`,
expand: "category,waypoints,summit_logs",
sort: `+name`,
}), {
method: 'GET',
})
const resultTrails: Trail[] = await searchResultToTrailList(result.hits, loadGPX)
if (!r.ok) {
const response = await r.json();
throw new APIError(r.status, response.message, response.detail)
}
trails = page > 1 ? trails.concat(resultTrails) : resultTrails
const response = await r.json()
if (loadGPX) {
for (const trail of response.items) {
const gpxData: string = await fetchGPX(trail);
if (!trail.expand) {
trail.expand = {};
}
trail.expand.gpx_data = gpxData;
}
}
const comparison = compareObjectArrays<Trail>(trails, response.items)
trails = response.items;
return { trails: response.items, ...comparison };
return { trails, ...result };
}
@@ -269,7 +233,7 @@ export async function trails_update(oldTrail: Trail, newTrail: Trail, photos?: F
}
for (const updatedWaypoint of waypointUpdates.updated) {
const oldWaypoint = oldTrail.expand?.waypoints.find(w => w.id == updatedWaypoint.id);
const oldWaypoint = oldTrail.expand?.waypoints?.find(w => w.id == updatedWaypoint.id);
const model = await waypoints_update(oldWaypoint!, {
...updatedWaypoint,
marker: undefined,
@@ -288,7 +252,7 @@ export async function trails_update(oldTrail: Trail, newTrail: Trail, photos?: F
}
for (const updatedSummitLog of summitLogUpdates.updated) {
const oldSummitLog = oldTrail.expand?.summit_logs.find(w => w.id == updatedSummitLog.id);
const oldSummitLog = oldTrail.expand?.summit_logs?.find(w => w.id == updatedSummitLog.id);
const model = await summit_logs_update(oldSummitLog!, updatedSummitLog);
}
@@ -448,6 +412,60 @@ export async function fetchGPX(trail: { gpx?: string } & Record<string, any>, f:
return gpxData
}
async function searchResultToTrailList(hits: Hits<TrailSearchResult>, loadGPX: boolean = false): Promise<Trail[]> {
const trails: Trail[] = []
for (const h of hits) {
const t: Trail & RecordModel = {
collectionId: "trails",
collectionName: "trails",
updated: new Date(h.created * 1000).toISOString(),
author: h.author,
name: h.name,
photos: h.thumbnail ? [h.thumbnail] : [],
public: h.public,
summit_logs: [],
waypoints: [],
category: h.category,
created: new Date(h.created * 1000).toISOString(),
date: new Date(h.date * 1000).toISOString(),
description: h.description,
difficulty: h.difficulty,
distance: h.distance,
duration: h.duration,
elevation_gain: h.elevation_gain,
elevation_loss: h.elevation_loss,
id: h.id,
lat: h._geo.lat,
lon: h._geo.lng,
location: h.location,
gpx: h.gpx,
thumbnail: 0,
expand: {
author: {
collectionId: "users",
private: false,
id: h.author,
avatar: h.author_avatar,
username: h.author_name
} as any,
trail_share_via_trail: h.shares?.map(s => ({
permission: "view",
trail: h.id,
user: s,
})),
}
}
if (loadGPX) {
const gpxData: string = await fetchGPX(t);
t.expand!.gpx_data = gpxData;
}
trails.push(t)
}
return trails
}
function buildFilterText(filter: TrailFilter, includeGeo: boolean): string {
let filterText: string = "";

View File

@@ -158,7 +158,7 @@ export function createPopupFromTrail(trail: Trail) {
// Create the image element
const img = document.createElement("img");
img.className = "h-full w-28 object-cover";
img.className = "h-full w-20 object-cover";
img.src = thumbnail; // Set image source safely
img.alt = ""; // Always include a safe alt attribute
imageContainer.appendChild(img);

View File

@@ -15,7 +15,8 @@ export async function GET(event: RequestEvent) {
if (!t.expand) {
t.expand = {} as any
}
t.expand!.author = await pb.collection("users_anonymous").getOne(t.author);
// t.expand!.author = await pb.collection("users_anonymous").getOne(t.author);
t.expand?.waypoints?.sort((a, b) => (a.distance_from_start ?? 0) - (b.distance_from_start ?? 0))
}
return json(r)

View File

@@ -46,8 +46,12 @@
const MIN_ZOOM = 6;
let loading: boolean = $state(true);
let loadingNextPage: boolean = false;
onMount(async () => {});
let pagination = {
page: 1,
totalPages: 1,
};
async function search(q: string) {
const r = await searchMulti({
@@ -103,15 +107,24 @@
}
}
async function searchTrails(northEast: M.LngLat, southWest: M.LngLat) {
loading = true;
const changes = await trails_search_bounding_box(
async function searchTrails(
northEast: M.LngLat,
southWest: M.LngLat,
reset: boolean = true,
) {
if (reset) {
pagination.page = 1;
loading = true;
}
const trailsInBox = await trails_search_bounding_box(
northEast,
southWest,
filter,
pagination.page,
(map?.getZoom() ?? 0) > MIN_ZOOM,
);
trails = changes.trails;
pagination.totalPages = trailsInBox.totalPages;
trails = trailsInBox.trails;
loading = false;
}
@@ -147,7 +160,6 @@
bounds.getNorthEast().lat,
),
};
await searchTrails(
normalizedBounds.northEast,
normalizedBounds.southWest,
@@ -214,6 +226,32 @@
);
}
}
async function onListScroll(e: Event) {
const container = e.target as HTMLDivElement;
const scrollTop = container.scrollTop;
const scrollHeight = container.scrollHeight;
const clientHeight = container.clientHeight;
if (
scrollTop + clientHeight >= scrollHeight * 0.8 &&
pagination.page !== pagination.totalPages &&
!loadingNextPage
) {
loadingNextPage = true;
await loadNextPage();
loadingNextPage = false;
}
}
async function loadNextPage() {
if (!map) {
return;
}
pagination.page += 1;
const bounds = map.getBounds();
await searchTrails(bounds.getNorthEast(), bounds.getSouthWest(), false);
}
</script>
<svelte:head>
@@ -223,6 +261,7 @@
<div
id="trail-list"
class="flex flex-col items-stretch gap-4 px-3 md:px-8 overflow-y-scroll"
onscroll={onListScroll}
>
<div class="sticky top-0 z-10 bg-background pb-4 space-y-4">
<div class="flex items-center gap-2 md:gap-4">
@@ -276,6 +315,7 @@
<a href="map/trail/{trail.id}">
<TrailCard
{trail}
fullWidth={true}
onmouseenter={() =>
handleTrailCardMouseEnter(trail)}
onmouseleave={() =>