Skip to content

Commit

Permalink
chore: improve types on map store + use store subscriber instead of w…
Browse files Browse the repository at this point in the history
…atcher #362
  • Loading branch information
wazolab committed Sep 23, 2024
1 parent 3f035ca commit a4943dc
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 84 deletions.
38 changes: 33 additions & 5 deletions components/Home/Embedded.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { flattenFeatures } from '~/utils/utilities'
const props = defineProps<{
boundaryArea?: Polygon | MultiPolygon
initialCategoryIds?: number[]
initialPoi?: string
}>()
//
Expand All @@ -32,6 +33,7 @@ const { isModeExplorer, mode, selectedFeature } = storeToRefs(mapStore)
const menuStore = useMenuStore()
const { apiMenuCategory, features, selectedCategoryIds, menuItems } = storeToRefs(menuStore)
const { config, settings } = useSiteStore()
const { API_ENDPOINT, API_PROJECT, API_THEME } = config!
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
Expand Down Expand Up @@ -116,13 +118,16 @@ const poiFilters = computed(() => {
)
})
// Store Subscribers
mapStore.$onAction(({ name, after }) => {
if (name === 'setSelectedFeature') {
after(() => routerPushUrl())
}
})
//
// Watchers
//
watch(selectedFeature, () => {
routerPushUrl()
})
watch(selectedCategoryIds, (a, b) => {
if (a !== b) {
routerPushUrl()
Expand Down Expand Up @@ -152,6 +157,7 @@ function routerPushUrl() {
const id = selectedFeature.value?.properties?.metadata?.id?.toString()
|| selectedFeature.value?.id?.toString()
|| null
router.push({
path: `/embedded${categoryIds ? `/${categoryIds}/` : '/'}${id ? `${id}` : ''}`,
query: router.currentRoute.value.query,
Expand All @@ -168,6 +174,28 @@ function toggleExploreAroundSelectedPoi() {
mode.value = Mode.BROWSER
}
}
// Fetch inital POI
const { data, error } = await useFetch<ApiPoi>(
() => `${API_ENDPOINT}/${API_PROJECT}/${API_THEME}/poi/${props.initialPoi}.geojson`,
{
query: {
geometry_as: 'bbox',
short_description: false,
},
immediate: !!props.initialPoi,
},
)
if (props.initialPoi) {
if (error.value)
throw createError(error.value)
if (!data.value)
throw createError({ statusCode: 404, message: 'Initial POI not found !' })
mapStore.setSelectedFeature(data.value)
}
</script>

<template>
Expand All @@ -180,7 +208,7 @@ function toggleExploreAroundSelectedPoi() {
<UIButton
:label="t('ui.close')"
icon="times"
@click="mapStore.setSelectedFeature(null)"
@click="mapStore.setSelectedFeature()"
/>
</div>
<PoiCardContent
Expand Down
74 changes: 51 additions & 23 deletions components/Home/Home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type { ApiAddrSearchResult, ApiSearchResult } from '~/lib/apiSearch'
const props = defineProps<{
boundaryArea?: Polygon | MultiPolygon
initialCategoryIds?: number[]
initialPoi?: string
}>()
//
Expand All @@ -48,6 +49,7 @@ const { apiMenuCategory, features, selectedCategoryIds } = storeToRefs(menuStore
const favoriteStore = useFavoriteStore()
const { favoritesIds, favoriteAddresses, favoriteFeatures, favoriteCount } = storeToRefs(favoriteStore)
const { config, settings, contents } = useSiteStore()
const { API_ENDPOINT, API_PROJECT, API_THEME } = config!
const { $tracking } = useNuxtApp()
const route = useRoute()
const router = useRouter()
Expand Down Expand Up @@ -220,28 +222,33 @@ const siteName = computed(() => {
return settings!.themes[0]?.title.fr || ''
})
// Store Subscribers
mapStore.$onAction(({ name, after }) => {
if (name === 'setSelectedFeature') {
after((feature) => {
isPoiCardShown.value = !!feature
if (process.client) {
routerPushUrl()
if (feature) {
$tracking({
type: 'popup',
poiId: feature.properties.metadata.id || feature.properties?.id,
title: feature.properties?.name,
location: window.location.href,
path: route.path,
categoryIds: feature.properties?.metadata?.category_ids || [],
})
}
}
})
}
})
//
// Watchers
//
watch(selectedFeature, (newFeature) => {
isPoiCardShown.value = !!newFeature
if (process.client) {
routerPushUrl()
if (newFeature) {
$tracking({
type: 'popup',
poiId: newFeature.properties.metadata.id || newFeature.properties?.id,
title: newFeature.properties?.name,
location: window.location.href,
path: route.path,
categoryIds: newFeature.properties?.metadata?.category_ids || [],
})
}
}
}, { immediate: true })
watch(selectedCategoryIds, (a, b) => {
if (a !== b) {
routerPushUrl()
Expand Down Expand Up @@ -349,7 +356,7 @@ function onBottomMenuButtonClick() {
function onQuitExplorerFavoriteMode() {
mode.value = Mode.BROWSER
mapStore.setSelectedFeature(null)
mapStore.setSelectedFeature()
}
function toggleFavoriteMode() {
Expand Down Expand Up @@ -396,8 +403,7 @@ function routerPushUrl(hashUpdate: { [key: string]: string | null } = {}) {
}
function toggleExploreAroundSelectedPoi(feature?: ApiPoi) {
if (feature)
mapStore.setSelectedFeature(feature)
mapStore.setSelectedFeature(feature)
if (!isModeExplorer.value) {
mode.value = Mode.EXPLORER
Expand Down Expand Up @@ -440,7 +446,29 @@ function scrollTop() {
}
function handlePoiCardClose() {
mapStore.setSelectedFeature(null)
mapStore.setSelectedFeature()
}
// Fetch inital POI
const { data, error } = await useFetch<ApiPoi>(
() => `${API_ENDPOINT}/${API_PROJECT}/${API_THEME}/poi/${props.initialPoi}.geojson`,
{
query: {
geometry_as: 'bbox',
short_description: true,
},
immediate: !!props.initialPoi,
},
)
if (props.initialPoi) {
if (error.value)
throw createError(error.value)
if (!data.value)
throw createError({ statusCode: 404, message: 'Initial POI not found !' })
mapStore.setSelectedFeature(data.value)
}
</script>

Expand Down
17 changes: 8 additions & 9 deletions components/MainMap/MapFeatures.vue
Original file line number Diff line number Diff line change
Expand Up @@ -288,11 +288,11 @@ export default defineNuxtComponent({
this.showSelectedFeature()
}
else {
this.updateSelectedFeature(null, undefined)
this.updateSelectedFeature()
}
},
updateSelectedFeature(feature: ApiPoi | null, marker?: Marker, fetch = false) {
updateSelectedFeature(feature?: ApiPoi, marker?: Marker, fetch = false) {
if (this.selectedFeature !== feature) {
this.mapStore.setSelectedFeature(feature)
this.setSelectedFeatureMarker(marker)
Expand Down Expand Up @@ -343,12 +343,11 @@ export default defineNuxtComponent({
zoom
= this.categories.find(
category =>
category.id === this.selectedFeature?.properties.vido_cat,
category.id === this.selectedFeature!.properties.vido_cat,
)?.category.zoom || 17
}
this.map.flyTo({
center: this.selectedFeature.geometry
.coordinates as unknown as LatLng,
center: this.selectedFeature.geometry.coordinates as unknown as LatLng,
zoom: zoom === undefined ? Math.max(this.map.getZoom(), 17) : zoom,
})
}
Expand Down Expand Up @@ -411,13 +410,13 @@ export default defineNuxtComponent({
if (
this.selectedFeature
&& (this.selectedFeature.properties?.metadata?.id
|| this.selectedFeature?.id
|| this.selectedFeature?.properties?.id)
|| this.selectedFeature.id
|| this.selectedFeature.properties?.id)
) {
filterRouteByPoiIds(this.map as Map, [
this.selectedFeature.properties?.metadata?.id
|| this.selectedFeature?.id
|| this.selectedFeature?.properties?.id,
|| this.selectedFeature.id
|| this.selectedFeature.properties?.id,
])
}
else {
Expand Down
17 changes: 1 addition & 16 deletions pages/embedded.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,14 @@
import type { GeoJSON, MultiPolygon, Polygon } from 'geojson'
import { storeToRefs } from 'pinia'
import Embedded from '~/components/Home/Embedded.vue'
import type { ApiPoi } from '~/lib/apiPois'
import { siteStore as useSiteStore } from '~/stores/site'
import { mapStore as useMapStore } from '~/stores/map'
//
// Composables
//
const { params, query, path } = useRoute()
const siteStore = useSiteStore()
const mapStore = useMapStore()
const { config, settings } = storeToRefs(siteStore)
const { API_ENDPOINT, API_PROJECT, API_THEME } = config.value!
const { $trackingInit } = useNuxtApp()
//
Expand Down Expand Up @@ -66,24 +62,13 @@ else {
}
categoryIds.value = categoryIdsJoin.value?.split(',').map(id => Number.parseInt(id))
const { data, error } = await useFetch<ApiPoi>(`${API_ENDPOINT}/${API_PROJECT}/${API_THEME}/poi/${poiId.value}.geojson?geometry_as=bbox&short_description=false`)
if (categoryIds.value && poiId.value) {
if (error.value)
throw createError(error.value)
if (!data.value)
throw createError({ statusCode: 404, message: 'Initial POI not found !' })
mapStore.setSelectedFeature(data.value!)
}
</script>

<template>
<Embedded
:boundary-area="boundaryGeojson"
:initial-category-ids="categoryIds"
:initial-poi="poiId"
/>
</template>

Expand Down
18 changes: 1 addition & 17 deletions pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,14 @@
import type { GeoJSON, MultiPolygon, Polygon } from 'geojson'
import { storeToRefs } from 'pinia'
import Home from '~/components/Home/Home.vue'
import type { ApiPoi } from '~/lib/apiPois'
import { siteStore as useSiteStore } from '~/stores/site'
import { mapStore as useMapStore } from '~/stores/map'
//
// Composables
//
const { params, query, path } = useRoute()
const siteStore = useSiteStore()
const mapStore = useMapStore()
const { config, settings } = storeToRefs(siteStore)
const { API_ENDPOINT, API_PROJECT, API_THEME } = config.value!
const { $trackingInit } = useNuxtApp()
//
Expand Down Expand Up @@ -66,25 +62,13 @@ else {
}
categoryIds.value = categoryIdsJoin.value?.split(',').map(id => Number.parseInt(id))
// Fetch inital POI
const { data, error } = await useFetch<ApiPoi>(`${API_ENDPOINT}/${API_PROJECT}/${API_THEME}/poi/${poiId.value}.geojson?geometry_as=bbox&short_description=true`)
if (categoryIds.value && poiId.value) {
if (error.value)
throw createError(error.value)
if (!data.value)
throw createError({ statusCode: 404, message: 'Initial POI not found !' })
mapStore.setSelectedFeature(data.value!)
}
</script>

<template>
<Home
:boundary-area="boundaryGeojson"
:initial-category-ids="categoryIds"
:initial-poi="poiId"
/>
</template>

Expand Down
29 changes: 15 additions & 14 deletions stores/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,21 @@ interface State {
selectedFeature: ApiPoi | null
}

function isJsonObject(item: string): boolean {
let value = false
try {
value = JSON.parse(item)
}
catch (e) {
return false
}

return typeof value === 'object' && value !== null
}

export const mapStore = defineStore('map', {
state: (): State => ({
center: { lng: 0, lat: 0 },
center: { lng: 0, lat: 0 } as LatLng,
mode: Mode.BROWSER,
pitch: 0,
selectedFeature: null,
Expand All @@ -26,25 +38,13 @@ export const mapStore = defineStore('map', {
},

actions: {
setSelectedFeature(feature: ApiPoi | null) {
setSelectedFeature(feature?: ApiPoi) {
if (!feature) {
this.selectedFeature = null
}
else {
const goodFeature = feature

function isJsonObject(item: string): boolean {
let value = false
try {
value = JSON.parse(item)
}
catch (e) {
return false
}

return typeof value === 'object' && value !== null
}

if (feature?.properties) {
const cleanProperties: ApiPoiProperties = {} as ApiPoiProperties

Expand All @@ -58,6 +58,7 @@ export const mapStore = defineStore('map', {
}

this.selectedFeature = goodFeature
return this.selectedFeature
}
},
},
Expand Down

0 comments on commit a4943dc

Please sign in to comment.