Skip to content

Commit

Permalink
Use new point type
Browse files Browse the repository at this point in the history
  • Loading branch information
mauriciabad committed Aug 8, 2024
1 parent 87b5bbb commit 298624e
Show file tree
Hide file tree
Showing 25 changed files with 83 additions and 148 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export const PlaceDetails: FC<{
features={place.features}
externalLinks={place.externalLinks}
googleMapsId={place.googleMapsId}
geoUri={`geo:${place.location.lat},${place.location.lng}`}
geoUri={`geo:${place.location.x},${place.location.y}`}
className="mt-4"
/>

Expand Down
3 changes: 2 additions & 1 deletion src/app/[locale]/(app)/explore/places/[placeId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { unstable_setRequestLocale } from 'next-intl/server'
import { notFound } from 'next/navigation'
import { type FC } from 'react'
import { makeImageUrl } from '~/helpers/images'
import { toLatLng } from '~/helpers/spatial-data/point'
import {
LocaleRouteParams,
locales,
Expand Down Expand Up @@ -98,7 +99,7 @@ const PlacePage: FC<LocaleRouteParams> = async ({ params }) => {
return (
<>
<OverrideMainMap
center={place.location}
center={toLatLng(place.location)}
zoom={18}
veryEmphasizedMarkers={veryEmphasizedMarkers}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export const PlacePreviewModal: FC<
const t = useTranslations('missions')
const isFar =
place &&
(place.location.lng < 3.170467 ||
place.location.lng > 3.24022 ||
place.location.lat < 41.920697 ||
place.location.lat > 41.984129)
(place.location.x < 3.170467 ||
place.location.x > 3.24022 ||
place.location.y < 41.920697 ||
place.location.y > 41.984129)

return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>
Expand Down Expand Up @@ -70,8 +70,8 @@ export const PlacePreviewModal: FC<
markers={[
{
placeId: place.id,
lat: place.location.lat,
lng: place.location.lng,
lat: place.location.y,
lng: place.location.x,
icon: place.mainCategory.icon,
color: 'red',
size: 'sm',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import { useDisclosure } from '@nextui-org/use-disclosure'
import { IconDiscountCheckFilled } from '@tabler/icons-react'
import { useTranslations } from 'next-intl'
import { FC } from 'react'
import type { MapPoint } from '~/helpers/spatial-data/point'
import { VerificationRequirements } from '~/server/db/constants/verifications'
import {
OnVerificate,
VerificatePlaceVisitModal,
} from './verificate-place-visit-modal'

export type VerificateButtonProps = {
expectedLocation: MapPoint
expectedLocation: { x: number; y: number }
placeId: number
isAlreadyVisited: boolean
isAlreadyVerified: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import { AlertBox } from '~/components/generic/alert-box'
import { DividerWithText } from '~/components/generic/divider-with-text'
import { ExplanationCard } from '~/components/generic/explanation-card'
import { LinkButton } from '~/components/links/link-button'
import type { MapPoint } from '~/helpers/spatial-data/point'
import { useRouter } from '~/navigation'
import {
VerificationRequirements,
Expand All @@ -39,15 +38,15 @@ import { useLocationValidator } from '../_hooks/useLocationValidator'
export type OnVerificate = (
hasBeenVerified: boolean,
verificationData: {
location: MapPoint | null
location: { x: number; y: number } | null
accuracy: number | null
}
) => Promise<void> | void

export const VerificatePlaceVisitModal: FC<
Omit<ModalProps, 'children'> & {
onVerificate?: OnVerificate
expectedLocation: MapPoint
expectedLocation: { x: number; y: number }
placeId: number
isAlreadyVisited: boolean
verificationRequirements: VerificationRequirements | null
Expand Down
21 changes: 12 additions & 9 deletions src/app/[locale]/(app)/missions/_hooks/useLocationValidator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import haversine from 'haversine-distance'
import { useCallback, useEffect, useState } from 'react'
import type { MapPoint } from '~/helpers/spatial-data/point'
import { toLatLng } from '~/helpers/spatial-data/point'
import { useDevicePermissions } from '~/helpers/useDevicePermissions'

/** In meters */
Expand All @@ -19,7 +19,7 @@ type ErrorCodes =
| 'permission-not-granted-yet'

export function useLocationValidator(
expectedLocation: MapPoint,
expectedLocation: { x: number; y: number },
maxLocationDistance?: number | null
) {
const [deviceLocationError, setDeviceLocationError] =
Expand All @@ -46,18 +46,21 @@ export function useLocationValidator(
}, [locationPermission])

const validateLocation = useCallback<
() => Promise<{ location: MapPoint; accuracy: number } | null>
() => Promise<{
location: { x: number; y: number }
accuracy: number
} | null>
>(async () => {
setLoadingDeviceLocation(true)

const { error, data } = await new Promise<
| {
error: null
data: { location: MapPoint; accuracy: number }
data: { location: { x: number; y: number }; accuracy: number }
}
| {
error: ErrorCodes
data: { location: MapPoint; accuracy: number } | null
data: { location: { x: number; y: number }; accuracy: number } | null
}
>((resolve) => {
if (!('geolocation' in navigator)) {
Expand All @@ -71,15 +74,15 @@ export function useLocationValidator(
(position) => {
const deviceGeolocation = {
location: {
lat: position.coords.latitude,
lng: position.coords.longitude,
x: position.coords.latitude,
y: position.coords.longitude,
},
accuracy: position.coords.accuracy,
} as const

const distance = haversine(
deviceGeolocation.location,
expectedLocation
toLatLng(deviceGeolocation.location),
toLatLng(expectedLocation)
)
if (distance > (maxLocationDistance ?? MAX_DISTANCE_TO_PLACE)) {
return resolve({
Expand Down
2 changes: 1 addition & 1 deletion src/app/[locale]/admin/places/_components/place-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const PlaceForm: FC<{
description: place.description ?? undefined,
mainCategory: place.mainCategory.id,
categories: place.categories.map((c) => c.category.id).join(','),
location: `${place.location.lat}, ${place.location.lng}`,
location: `${place.location.x}, ${place.location.y}`,
importance: place.importance,
mainImageId: place.mainImage?.id ?? undefined,
content: place.content ?? undefined,
Expand Down
2 changes: 1 addition & 1 deletion src/components/features/features-block.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export const FeaturesBlock: FC<{
}}
/>
)}
{geoUri && (
{!!geoUri && (
<LinkFeatureItem
link={{
url: geoUri,
Expand Down
5 changes: 2 additions & 3 deletions src/components/map/map-elements/map-marker.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import moize from 'moize'
import { FC, memo, useMemo, useState } from 'react'
import { useMap, useMapEvent } from 'react-leaflet'
import { MapPoint } from '~/helpers/spatial-data/point'
import { useRouter } from '~/navigation'
import { NextMarker } from '../leaflet-components/next-js-ready/marker'
import {
Expand All @@ -16,8 +15,8 @@ type MapMarkerSize =
| 'not-emphasized'
export type MapMarkerInvariable = {
placeId: number
lat: MapPoint['lat']
lng: MapPoint['lng']
lat: number
lng: number
url?: string
icon: PlaceMarkerLeafletIconProps['icon']
color: PlaceMarkerLeafletIconProps['color']
Expand Down
4 changes: 2 additions & 2 deletions src/components/map/map-elements/map-point-selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const MapPointSelector: FC<{
value={value}
label={label}
className="shadow-lg"
placeholder="Lat, Lng"
placeholder="Lng, Lat"
/>
{reset && (
<Button
Expand All @@ -67,7 +67,7 @@ export const MapPointSelector: FC<{
className="h-full w-full rounded-md"
onValueChange={(newValue) => {
const newValueString = newValue
? `${newValue.lat}, ${newValue.lng}`
? `${newValue.lng}, ${newValue.lat}`
: undefined

onChange({ target: { value: newValueString } })
Expand Down
4 changes: 2 additions & 2 deletions src/components/providers/main-map-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export const MainMapProvider: FC<PropsWithChildren> = memo(({ children }) => {
const { data: places } = trpc.map.getAllPlaces.useQuery()
const markers = places?.map((place) => ({
placeId: place.id,
lat: place.location.lat,
lng: place.location.lng,
lat: place.location.y,
lng: place.location.x,
icon: place.mainCategory.icon,
color: place.mainCategory.color,
url: `/explore/places/${place.id}`,
Expand Down
14 changes: 2 additions & 12 deletions src/helpers/spatial-data/point.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,6 @@ export function getPoint(
return null
}

export function calculateLocation<
L extends PointString | null | undefined,
P extends { location: L },
>(place: P) {
return {
...place,
location: getPoint(place.location),
}
}

export function pointToString(value: MapPoint): PointString {
return `POINT(${value.lng} ${value.lat})`
export function toLatLng(point: { x: number; y: number }) {
return { lat: point.y, lng: point.x }
}
8 changes: 4 additions & 4 deletions src/schemas/places.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ export const createPlaceSchema = z.object({
.string()
.min(3, 'Required')
.transform((value) => {
const [lat, lng] = value.split(',')
return { lat: Number(lat), lng: Number(lng) }
const [x, y] = value.split(',')
return { x: Number(x), y: Number(y) }
})
.pipe(
z.object({
lat: z.number(),
lng: z.number(),
x: z.number(),
y: z.number(),
})
),
importance: z.coerce.number().gt(0).lt(MAX_IMPORTANCE).optional().nullable(),
Expand Down
4 changes: 2 additions & 2 deletions src/schemas/verifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ export const verificateVisitSchema = z.object({
placeId: numericIdSchema,
deviceLocation: z
.object({
lat: z.number(),
lng: z.number(),
x: z.number(),
y: z.number(),
})
.nullable(),
deviceLocationAccuracy: z.number().nullable(),
Expand Down
13 changes: 5 additions & 8 deletions src/server/api/router/admin/places.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'server-only'

import { and, asc, eq, isNull, like, or, sql } from 'drizzle-orm'
import { calculateLocation, pointToString } from '~/helpers/spatial-data/point'
import {
createPlaceSchema,
editPlaceSchema,
Expand All @@ -18,7 +17,6 @@ import {
placesToPlaceCategories,
} from '~/server/db/schema'
import { ascNullsEnd } from '~/server/helpers/order-by'
import { selectPoint } from '~/server/helpers/spatial-data/point'
import {
flattenTranslationsOnExecute,
withTranslations,
Expand Down Expand Up @@ -143,9 +141,7 @@ const getPlace = flattenTranslationsOnExecute(
content: true,
importance: true,
googleMapsId: true,
},
extras: {
location: selectPoint('location', places.location),
location: true,
},
where: (place, { eq }) =>
eq(place.id, sql`${sql.placeholder('id')}::integer`),
Expand Down Expand Up @@ -207,7 +203,8 @@ export const placesAdminRouter = router({
locale: input.locale,
id: input.id,
})
return result ? calculateLocation(result) : undefined
if (!result) return undefined
return result
}),
listCategories: adminProcedure
.input(listCategoriesSchema)
Expand All @@ -234,7 +231,7 @@ export const placesAdminRouter = router({
googleMapsId: input.googleMapsId,
mainCategoryId: input.mainCategory,
mainImageId: input.mainImageId,
location: pointToString(input.location),
location: input.location,
importance: input.importance,
content: input.content,
verificationRequirementsId: 1,
Expand Down Expand Up @@ -293,7 +290,7 @@ export const placesAdminRouter = router({
googleMapsId: input.googleMapsId,
mainCategoryId: input.mainCategory,
mainImageId: input.mainImageId,
location: pointToString(input.location),
location: input.location,
importance: input.importance,
content: input.content,
featuresId: featuresId,
Expand Down
10 changes: 3 additions & 7 deletions src/server/api/router/map.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import 'server-only'

import { calculatePath } from '~/helpers/spatial-data/multi-line'
import { calculateLocation } from '~/helpers/spatial-data/point'
import { db } from '~/server/db/db'
import { places, routes } from '~/server/db/schema'
import { routes } from '~/server/db/schema'
import { selectMultiLine } from '~/server/helpers/spatial-data/multi-line'
import { selectPoint } from '~/server/helpers/spatial-data/point'
import { publicProcedure, router } from '~/server/trpc'

const getAllPlacesForMap = db.query.places
Expand All @@ -14,9 +12,7 @@ const getAllPlacesForMap = db.query.places
id: true,
name: true,
importance: true,
},
extras: {
location: selectPoint('location', places.location),
location: true,
},
with: {
mainCategory: {
Expand Down Expand Up @@ -54,7 +50,7 @@ const getAllRoutesForMap = db.query.routes

export const mapRouter = router({
getAllPlaces: publicProcedure.query(async () => {
return (await getAllPlacesForMap.execute()).map(calculateLocation)
return await getAllPlacesForMap.execute()
}),
getAllRoutes: publicProcedure.query(async () => {
return (await getAllRoutesForMap.execute()).map(calculatePath)
Expand Down
Loading

0 comments on commit 298624e

Please sign in to comment.