All files / src/components GeoLocationField.vue

88.88% Statements 48/54
87.23% Branches 41/47
92.3% Functions 12/13
91.83% Lines 45/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194  16x                                     9x 9x 9x                     1x     9x                     1x       9x                                                                     1x   9x                           13x 2x     13x 13x                                 13x 13x   13x 13x 13x 13x   13x 3x 3x       13x 5x 5x 3x 2x     13x 9x 9x 9x       2x 2x 2x   2x             2x       1x       2x 1x 1x     1x 1x   1x 1x                          
<template>
  <div :class="{ 'geo-location-field': !props.noWrapper }">
    <!-- Display mode -->
    <div v-if="!isEditing">
      <div v-if="modelValue" class="d-flex align-items-center gap-2">
        <font-awesome-icon icon="fa-solid fa-location-dot" class="text-muted" />
        <span>{{ formattedCoordinates }}</span>
        <a :href="mapLink" target="_blank" rel="noopener" class="small">
          {{ t('field.viewOnMap') }}
          <font-awesome-icon icon="fa-solid fa-up-right-from-square" class="ms-1" />
        </a>
      </div>
      <div v-else class="text-muted small">{{ t('field.noLocation') }}</div>
      <!-- A preview of the place (the item cards) -->
      <div v-if="withMap && markers.length" class="mt-2" data-testid="geo-location-preview">
        <MapView :markers="markers" :interactive="false" :lang="uiLanguage" height="160px" />
      </div>
    </div>
 
    <!-- Edit mode -->
    <div v-else class="geo-location-edit">
      <div class="row g-2">
        <div class="col-6">
          <label class="form-label small mb-1" :for="latInputId">{{ t('field.latitude') }}</label>
          <input
            :id="latInputId"
            :value="modelValue?.lat ?? ''"
            type="number"
            step="any"
            min="-90"
            max="90"
            class="form-control form-control-sm"
            :placeholder="t('field.latitude')"
            @input="updateCoordinate('lat', $event)"
          />
        </div>
        <div class="col-6">
          <label class="form-label small mb-1" :for="lngInputId">{{ t('field.longitude') }}</label>
          <input
            :id="lngInputId"
            :value="modelValue?.lng ?? ''"
            type="number"
            step="any"
            min="-180"
            max="180"
            class="form-control form-control-sm"
            :placeholder="t('field.longitude')"
            @input="updateCoordinate('lng', $event)"
          />
        </div>
      </div>
      <div class="d-flex align-items-center gap-2 mt-2">
        <button
          type="button"
          class="btn btn-sm btn-outline-secondary"
          :disabled="locating"
          @click="useCurrentLocation"
        >
          <font-awesome-icon
            :icon="locating ? 'fa-solid fa-spinner' : 'fa-solid fa-location-crosshairs'"
            :spin="locating"
            class="me-1"
          />
          {{ t('field.useMyLocation') }}
        </button>
        <button
          v-if="modelValue"
          type="button"
          class="btn btn-sm btn-outline-danger"
          @click="clearLocation"
        >
          <font-awesome-icon icon="fa-solid fa-times" class="me-1" />
          {{ t('common.clear') }}
        </button>
        <a v-if="modelValue" :href="mapLink" target="_blank" rel="noopener" class="small ms-auto">
          {{ t('field.viewOnMap') }}
          <font-awesome-icon icon="fa-solid fa-up-right-from-square" class="ms-1" />
        </a>
      </div>
      <!-- Picking the place on a map (UC-ENTITY-028.2) -->
      <div v-if="withMap" class="mt-2" data-testid="geo-location-map">
        <MapView
          :markers="markers"
          pickable
          :lang="uiLanguage"
          height="220px"
          @pick="emit('update:modelValue', $event)"
        />
        <div class="form-text">{{ t('field.pickOnMap') }}</div>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-028.1, UC-ENTITY-028.2
import { computed, defineAsyncComponent, ref } from 'vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useToastStore } from '@/stores/toast'
import type { GeoLocationValue } from '@/stores/entities'
 
// MapLibre (about 310 KB compressed) only loads where a map shows
const MapView = defineAsyncComponent(() =>
  import('@/components/MapView.vue').then((module) => module.default)
)
 
const { t, uiLanguage } = useUILanguage()
const toastStore = useToastStore()
 
interface Props {
  modelValue: GeoLocationValue | null | undefined
  isEditing: boolean
  noWrapper?: boolean
  /**
   * A map of the place: while editing, clicking it sets the place (the item
   * sidebar); else a preview (the item cards)
   */
  withMap?: boolean
}
 
interface Emits {
  (e: 'update:modelValue', value: GeoLocationValue | null): void
}
 
const props = withDefaults(defineProps<Props>(), { noWrapper: false, withMap: false })
const emit = defineEmits<Emits>()
 
const locating = ref(false)
const uid = Math.random().toString(36).substring(2, 9)
const latInputId = `geo-lat-${uid}`
const lngInputId = `geo-lng-${uid}`
 
const formattedCoordinates = computed(() => {
  Iif (!props.modelValue) return ''
  return `${props.modelValue.lat.toFixed(5)}, ${props.modelValue.lng.toFixed(5)}`
})
 
/** The place on the map, once both coordinates are valid */
const markers = computed(() => {
  const value = props.modelValue
  if (!value || !Number.isFinite(value.lat) || !Number.isFinite(value.lng)) return []
  if (Math.abs(value.lat) > 90 || Math.abs(value.lng) > 180) return []
  return [{ id: 'place', lat: value.lat, lng: value.lng }]
})
 
const mapLink = computed(() => {
  Iif (!props.modelValue) return ''
  const { lat, lng } = props.modelValue
  return `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=15/${lat}/${lng}`
})
 
function updateCoordinate(axis: 'lat' | 'lng', event: Event) {
  const raw = (event.target as HTMLInputElement).value
  const value = raw === '' ? NaN : Number(raw)
  const current = props.modelValue ?? { lat: 0, lng: 0 }
 
  Iif (Number.isNaN(value)) {
    // Clearing one field with the other still set keeps the field editable
    // rather than snapping back to a stale value.
    emit('update:modelValue', { ...current, [axis]: 0 })
    return
  }
 
  emit('update:modelValue', { ...current, [axis]: value })
}
 
function clearLocation() {
  emit('update:modelValue', null)
}
 
function useCurrentLocation() {
  if (typeof navigator === 'undefined' || !navigator.geolocation) {
    toastStore.error(t('field.geolocationUnsupported'))
    return
  }
 
  locating.value = true
  navigator.geolocation.getCurrentPosition(
    (position) => {
      locating.value = false
      emit('update:modelValue', {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      })
    },
    () => {
      locating.value = false
      toastStore.error(t('field.geolocationDenied'))
    },
    { timeout: 10000 }
  )
}
</script>