All files / app/formly location.type.ts

6% Statements 6/100
11.53% Branches 6/52
0% Functions 0/29
6.17% Lines 5/81

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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 22511x       11x   11x 11x                                                                                                                                                                                                                       11x                                                                                                                                                                                                                          
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FieldType, FieldTypeConfig, FormlyAttributes, FormlyConfig } from '@ngx-formly/core';
import { Subscription } from 'rxjs';
import { getErrorMessage } from './errors';
import { LocationMapComponent } from './location-map.component';
import { parseLocation } from '../util/geo';
import { LocationPicker, locationPicker } from './location-picker';
 
@Component({
  selector: 'formly-field-location',
  host: { 'class': 'field location-field' },
  template: `
    <div class="location-input">
      @if (showMap) {
        @defer {
          <app-location-map [picker]="picker"></app-location-map>
        }
      }
      <div class="form-array">
        <input type="number"
               class="grow"
               placeholder="Longitude"
               i18n-placeholder
               min="-180"
               max="180"
               step="any"
               aria-label="Longitude"
               i18n-aria-label
               [value]="lng"
               [disabled]="formControl.disabled"
               (input)="setLng($any($event.target).value)"
               (paste)="paste($event)"
               (blur)="blur($any($event.target))"
               [formlyAttributes]="field"
               [class.is-invalid]="showError">
        <input type="number"
               class="grow"
               placeholder="Latitude"
               i18n-placeholder
               min="-90"
               max="90"
               step="any"
               [id]="field.id + '-lat'"
               [name]="(field.name || field.id) + '-lat'"
               aria-label="Latitude"
               i18n-aria-label
               [value]="lat"
               [disabled]="formControl.disabled"
               (input)="setLat($any($event.target).value)"
               (paste)="paste($event)"
               (blur)="blur($any($event.target))"
               [class.is-invalid]="showError">
        <button type="button"
                class="location-detect"
                title="Use current location"
                i18n-title
                aria-label="Use current location"
                i18n-aria-label
                [disabled]="formControl.disabled"
                (click)="detectLocation()"
                i18n>📍️</button>
        <button type="button"
                class="location-map-toggle"
                title="Pick location on map"
                i18n-title
                aria-label="Pick location on map"
                i18n-aria-label
                [class.toggled]="showMap"
                [attr.aria-pressed]="showMap"
                [disabled]="formControl.disabled"
                (click)="toggleMap()"
                i18n>🗺️</button>
      </div>
    </div>
  `,
  styles: `
    .location-input {
      display: flex;
      flex-direction: column;
      flex-grow: 1;
      min-width: 0;
    }
    @media (max-width: 740px) {
      .location-input {
        container-type: inline-size;
      }
    }
    .location-input input {
      min-width: 0;
      width: 120px;
    }
    @container (max-width: 240px) {
      .location-input .form-array {
        display: grid;
        grid-template-columns: minmax(0, 1fr) auto;
        grid-template-rows: auto auto;
        grid-auto-flow: column;
        gap: 4px;
      }
      .location-input .form-array > * {
        margin-right: 0;
      }
      .location-input input {
        width: auto;
      }
    }
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ReactiveFormsModule,
    FormlyAttributes,
    LocationMapComponent,
  ],
})
export class FormlyFieldLocationI extends FieldType<FieldTypeConfig> implements OnInit, OnDestroy {
 
  picker!: LocationPicker;
 
  private showedError = false;
  private subs = new Subscription();
 
  constructor(
    private config: FormlyConfig,
    private cd: ChangeDetectorRef,
  ) {
    super();
  }
 
  ngOnInit() {
    this.picker = locationPicker(this.field);
    this.subs.add(this.picker.changes.subscribe(() => this.cd.markForCheck()));
    this.subs.add(this.formControl.valueChanges.subscribe(() => this.cd.markForCheck()));
    if (this.picker.open && !this.hasLocation) {
      // New point added while the map is open: select it so it can be placed by clicking the map
      queueMicrotask(() => this.picker.select(this.formControl));
    }
  }
 
  ngOnDestroy() {
    this.subs.unsubscribe();
    this.picker?.removed(this.formControl);
  }
 
  get showMap() {
    return this.picker.owner === this.formControl;
  }
 
  get lng(): number {
    return this.formControl.value?.[0] ?? 0;
  }
 
  get lat(): number {
    return this.formControl.value?.[1] ?? 0;
  }
 
  get hasLocation() {
    const v = this.formControl.value;
    return Array.isArray(v) && typeof v[0] === 'number' && typeof v[1] === 'number' && (v[0] !== 0 || v[1] !== 0);
  }
 
  setLng(value: string) {
    const lng = parseFloat(value);
    if (!isNaN(lng)) {
      this.setLocation([lng, this.lat]);
    }
  }
 
  setLat(value: string) {
    const lat = parseFloat(value);
    if (!isNaN(lat)) {
      this.setLocation([this.lng, lat]);
    }
  }
 
  /**
   * Pasting "lng, lat" fills in both inputs.
   */
  paste(event: ClipboardEvent) {
    const location = parseLocation(event.clipboardData?.getData('text') || '');
    if (!location) return;
    event.preventDefault();
    this.setLocation(location);
  }
 
  setLocation(value: [number, number]) {
    this.formControl.setValue(value);
    this.formControl.markAsDirty();
    this.cd.markForCheck();
  }
 
  detectLocation(onlyIfUnset = false) {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        pos => {
          if (onlyIfUnset && (!this.showMap || this.hasLocation)) return;
          this.setLocation([pos.coords.longitude, pos.coords.latitude]);
        },
        err => console.error('Geolocation error:', err.message),
      );
    }
  }
 
  toggleMap() {
    this.picker.toggle(this.formControl);
    if (this.showMap && !this.hasLocation) this.detectLocation(true);
  }
 
  validate(input: HTMLInputElement) {
    if (this.showError) {
      input.setCustomValidity(getErrorMessage(this.field, this.config));
      input.reportValidity();
    }
  }
 
  blur(input: HTMLInputElement) {
    if (this.showError && !this.showedError) {
      this.showedError = true;
      this.validate(input);
    } else {
      this.showedError = false;
    }
  }
}