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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 21x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 4x 4x 4x 4x 4x 7x 7x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 14x 5x 5x 5x 5x 5x 4x 7x 4x 4x 7x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 4x 4x 4x 3x 9x 3x 1x 4x 3x 3x 3x 3x | import { Location } from '@angular/common';
import { Component, Input, NgZone, OnChanges, OnDestroy, SimpleChanges, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router } from '@angular/router';
import {
ControlComponent,
MapComponent as MglComponent,
NavigationControlDirective,
ScaleControlDirective
} from '@maplibre/ngx-maplibre-gl';
import { provideMaplibreWorker } from '@maplibre/ngx-maplibre-gl/config';
import type { FeatureCollection } from 'geojson';
import type { GeoJSONSource, MapMouseEvent } from 'maplibre-gl';
import { LngLatBounds, Map, Marker } from 'maplibre-gl';
import { BehaviorSubject, catchError, filter, forkJoin, map as rxMap, of, Subject, switchMap } from 'rxjs';
import { HasChanges } from '../../guard/pending-changes.guard';
import { Ext } from '../../model/ext';
import { Page } from '../../model/page';
import { Ref } from '../../model/ref';
import { features, mapTemplate } from '../../mods/map';
import { RootConfig } from '../../mods/root';
import { isInlineSvg } from '../../pipe/thumbnail.pipe';
import { AdminService } from '../../service/admin.service';
import { ProxyService } from '../../service/api/proxy.service';
import { RefService } from '../../service/api/ref.service';
import { AuthzService } from '../../service/authz.service';
import { GeocodeService } from '../../service/geocode.service';
import { Store } from '../../store/store';
import { getAddTags } from '../../util/add-tags';
import { getTitle } from '../../util/format';
import { formatMapView, geoFeatures, hasLocation, MapView, minimalLngInterval, parseMapView } from '../../util/geo';
import { addGeoLayers } from '../../util/geo-style';
import { GeocoderPosition, isConfigured } from '../../util/geocode';
import { memo, MemoCache } from '../../util/memo';
import { hasPrefix, hasTag, repost } from '../../util/tag';
import { LoadingComponent } from '../loading/loading.component';
import { addGeocoder } from './geocoder';
import { preventSelectionDrag } from './selection-drag';
import { DOUBLE_CLICK_DELAY, isRepeatClick, onSingleClick } from './single-click';
import { PageControlsComponent } from '../page-controls/page-controls.component';
import { ResizeHandleDirective } from "../../directive/resize-handle.directive";
export { formatMapView, minimalLngInterval, parseMapView };
export type { MapView };
type MapEntry = [ref: Ref, bareRepost?: Ref];
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss'],
encapsulation: ViewEncapsulation.None,
host: { 'class': 'map ext' },
providers: [provideMaplibreWorker('assets/maplibre-gl-worker.mjs')],
changeDetection: ChangeDetectionStrategy.Eager,
imports: [
MglComponent,
ControlComponent,
NavigationControlDirective,
ScaleControlDirective,
LoadingComponent,
PageControlsComponent,
ResizeHandleDirective,
]
})
export class MapComponent implements OnChanges, OnDestroy, HasChanges {
@Input()
tag = '';
@Input()
ext?: Ext;
@Input()
pageControls = true;
/**
* Fit the map to this bounding box [west, south, east, north].
* If empty, fits to the features on the map when fitFeatures is set.
*/
@Input()
bbox?: number[];
@Input()
fitFeatures = false;
/**
* Save the map center and zoom in the URL, replacing the current history
* entry so pressing back returns to the same spot on the map.
*/
@Input()
set saveView(value: boolean) {
this._saveView = value;
this.view = value ? parseMapView(this.store.view.mapView) : undefined;
}
get saveView() {
return this._saveView;
}
private _page?: Page<Ref>;
private map?: Map;
private geocoderMap?: Map;
private markers: Marker[] = [];
private mapDataUpdates$ = new Subject<Ref[]>();
private ext$ = new BehaviorSubject<Ext | undefined>(undefined);
mapData: MapEntry[] = [];
private geocoding = false;
private geocoderPosition?: GeocoderPosition;
private removeGeocoder?: () => void;
private removeGeoLayers?: () => void;
private searchMarker?: Marker;
private searchActivation?: ReturnType<typeof setTimeout>;
private reverseGeocode?: AbortController;
private removeClick?: () => void;
private _saveView = false;
/**
* View the map is created with, restored from the URL.
*/
view?: MapView;
constructor(
private router: Router,
private location: Location,
private admin: AdminService,
private proxy: ProxyService,
private refs: RefService,
private store: Store,
private geocoder: GeocodeService,
private auth: AuthzService,
private zone: NgZone,
) {
this.ext$.pipe(
switchMap(ext => geocoder.configFor$(ext)),
takeUntilDestroyed(),
).subscribe(config => {
this.geocoding = isConfigured(config);
Eif (this.geocoderPosition !== config.geocoderPosition) {
this.removeGeocoder?.();
this.removeGeocoder = undefined;
}
this.geocoderPosition = config.geocoderPosition;
this.updateGeocoder();
});
this.mapDataUpdates$.pipe(
switchMap(content => {
if (!content.some(ref => this.isBareRepost(ref))) return of(content.map(ref => [ref] as MapEntry));
return forkJoin(content.map(ref => this.getBareRepost(ref)));
}),
takeUntilDestroyed(),
).subscribe(mapData => {
this.mapData = mapData;
MemoCache.clear(this);
this.updateMapData();
Iif (this.fitFeatures) this.fit();
});
router.events.pipe(
filter(e => e instanceof NavigationEnd),
takeUntilDestroyed(),
).subscribe(() => this.restoreView());
}
/**
* Back and forward within the same page move the map to the saved view.
*/
private restoreView() {
if (!this.saveView || !this.map) return;
const view = parseMapView(this.store.view.mapView);
if (!view) {
this.writeView();
} else if (formatMapView(view) !== formatMapView(this.currentView)) {
this.map.jumpTo(view);
}
}
private get currentView(): MapView | undefined {
if (!this.map) return undefined;
const { lng, lat } = this.map.getCenter().wrap();
return { center: [lng, lat], zoom: this.map.getZoom() };
}
private writeView = () => {
if (!this.saveView) return;
const view = this.currentView;
if (!view) return;
const url = this.router.parseUrl(this.location.path());
const value = formatMapView(view);
this.store.view.setLiveMapView(value);
if (url.queryParams['map'] === value) return;
url.queryParams = { ...url.queryParams, map: value };
this.location.replaceState(this.router.serializeUrl(url), '', this.location.getState());
};
@memo
get mapStyle() {
return {
...this.ext?.config?.mapStyle || this.admin.getTemplate('map')?.defaults?.mapStyle || mapTemplate.defaults?.mapStyle || {},
...this.admin.getTemplate('map')?.config?.mapStyle || {},
};
}
private updateGeocoder() {
Iif (this.geocoding && this.geocoderMap && !this.removeGeocoder) {
this.removeGeocoder = addGeocoder(this.geocoderMap, this.geocoder, this.geocoderPosition,
(location, name) => this.showSearchResult(location, name),
() => this.clearSearchResult(),
() => this.ext);
I} else if (!this.geocoding && this.removeGeocoder) {
this.removeGeocoder();
this.removeGeocoder = undefined;
this.clearSearchResult();
}
}
/**
* Mark an address search result. Clicking the marker submits a new Ref there.
* Returns a function to update the marker's title.
*/
private showSearchResult(location: [number, number], name = '') {
if (!this.map) return undefined;
this.clearSearchResult();
const marker = new Marker({ color: '#e5a50a', className: 'geocode-marker' })
.setLngLat(location);
const el = marker.getElement();
const setName = (value: string) => {
name = value;
const label = name || $localize`Submit a Ref here`;
el.title = label;
el.setAttribute('aria-label', label);
};
setName(name);
el.setAttribute('role', 'button');
el.tabIndex = 0;
const activate = () => {
// Marker events run outside Angular
this.zone.run(() => {
this.clearSearchResult();
this.router.navigate(['/submit/text'], {
queryParams: {
tag: [...this.addTags.filter(t => t !== 'plugin/geo/point'), 'plugin/geo/point'],
location: location.join(','),
...name ? { title: name } : {},
},
});
});
};
el.addEventListener('click', e => {
e.stopPropagation();
this.cancelSearchActivation();
// Double clicking zooms in
if (isRepeatClick(e)) return;
this.searchActivation = setTimeout(() => {
this.searchActivation = undefined;
activate();
}, DOUBLE_CLICK_DELAY);
});
el.addEventListener('dblclick', () => this.cancelSearchActivation());
el.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.stopPropagation();
this.cancelSearchActivation();
activate();
}
});
marker.addTo(this.map);
this.searchMarker = marker;
return setName;
}
/**
* Tags added to a Ref submitted from the map, the same as the sidebar
* Submit button.
*/
get addTags(): string[] {
const tag = this.tag || undefined;
const plugin = tag ? this.admin.getPlugin(tag) : undefined;
const root = this.admin.getTemplate('');
const home = tag === 'config/home' || (!tag && this.store.view.current === 'home');
const submitExt = home ? this.store.view.homeExt : this.ext;
const rootConfig = root
? (submitExt?.config || (tag && this.admin.getTemplate(tag)?.defaults) || root.defaults) as RootConfig
: undefined;
return getAddTags(tag, plugin, rootConfig, home).filter(t => this.auth.canAddTag(t));
}
private cancelSearchActivation() {
clearTimeout(this.searchActivation);
this.searchActivation = undefined;
}
private clearSearchResult() {
this.cancelSearchActivation();
this.reverseGeocode?.abort();
this.reverseGeocode = undefined;
this.searchMarker?.remove();
this.searchMarker = undefined;
}
/**
* Clicking the map marks that point, titled with its reverse geocoded address.
*/
private mapClick = (e: MapMouseEvent) => {
if ((e.originalEvent?.target as Element | null)?.closest?.('.maplibregl-marker')) return;
const { lng, lat } = e.lngLat.wrap();
const location: [number, number] = [round(lng), round(lat)];
const setName = this.showSearchResult(location);
if (!setName || !this.geocoding) return;
const controller = this.reverseGeocode = new AbortController();
this.geocoder.reverse(location, controller.signal, this.ext)
.then(result => {
if (!controller.signal.aborted && result?.name) setName(result.name);
})
.catch(err => {
if (!controller.signal.aborted) console.error('Reverse geocoding error:', err);
});
};
saveChanges() {
return true;
}
ngOnChanges(changes: SimpleChanges) {
if (changes['ext']) {
MemoCache.clear(this);
if (this.ext$.value !== this.ext) this.ext$.next(this.ext);
}
if (changes['bbox'] && !changes['bbox'].firstChange) {
MemoCache.clear(this);
this.fit();
}
}
ngOnDestroy() {
this.mapDataUpdates$.complete();
this.ext$.complete();
this.clearMarkers();
this.clearSearchResult();
this.removeClick?.();
this.removeClick = undefined;
this.map?.off('moveend', this.writeView);
Iif (this.saveView) this.store.view.setLiveMapView();
this.removeGeocoder?.();
this.removeGeocoder = undefined;
this.geocoderMap = undefined;
this.removeGeoLayers?.();
this.removeGeoLayers = undefined;
try {
this.map?.remove();
} catch (ignored) { }
this.map = undefined;
}
get page(): Page<Ref> | undefined {
return this._page;
}
@Input()
set page(value: Page<Ref> | undefined) {
MemoCache.clear(this);
this._page = value;
this.mapDataUpdates$.next(value?.content || []);
Eif (this._page) {
Iif (this._page.page.number > 0 && this._page.page.number >= this._page.page.totalPages) {
this.router.navigate([], {
queryParams: {
pageNumber: this._page.page.totalPages - 1
},
queryParamsHandling: 'merge',
});
}
}
}
@memo
get geoData(): FeatureCollection {
return {
type: 'FeatureCollection',
// Geo points are shown as markers
features: this.mapData.flatMap(([ref]) => features(ref, 'plugin/geo/point'))
.filter(f => f?.type === 'Feature')
.flatMap(f => geoFeatures(f, f.geometry?.type === 'Point' ? hasLocation : undefined)),
};
}
onMapError(event: any) {
console.error('MapLibre Engine Error:', event.error);
}
/**
* Add the address search as soon as the style is ready, without waiting for the tiles to load.
*/
styleLoaded(map: Map) {
if (this.geocoderMap === map) return;
this.removeGeocoder?.();
this.removeGeocoder = undefined;
this.geocoderMap = map;
this.updateGeocoder();
}
mapLoaded(map: Map) {
this.removeGeoLayers?.();
this.removeGeoLayers = undefined;
this.clearSearchResult();
this.removeClick?.();
this.map?.off('moveend', this.writeView);
this.map = map;
this.styleLoaded(map);
this.removeClick = onSingleClick(map, this.mapClick);
preventSelectionDrag(map);
map.addSource('geo-features', { type: 'geojson', data: this.geoData });
this.removeGeoLayers = this.zone.runOutsideAngular(() => addGeoLayers(map, 'geo-features', 'geo', 8));
this.updateMapData();
if (!this.view) this.fit();
map.on('moveend', this.writeView);
this.writeView();
}
private fit() {
if (!this.map) return;
const bounds = this.bounds;
if (!bounds) return;
this.map.fitBounds(bounds, { ...this.fitBoundsOptions, animate: false });
}
readonly fitBoundsOptions = { padding: 40, maxZoom: 14 };
/**
* Bounds the map is created with, so it doesn't render the style's
* default center first and then jump to the features.
*/
@memo
get bounds(): LngLatBounds | undefined {
const bbox = this.bbox;
if (bbox && (bbox.length === 4 || bbox.length === 6) && bbox.every(n => typeof n === 'number' && isFinite(n))) {
const east = bbox.length === 6 ? bbox[3] : bbox[2];
const north = bbox.length === 6 ? bbox[4] : bbox[3];
if (Math.abs(bbox[1]) <= 90 && Math.abs(north) <= 90) {
return new LngLatBounds([bbox[0], bbox[1]], [east, north]);
}
}
if (!this.fitFeatures) return undefined;
const lngs: number[] = [];
let south = Infinity;
let north = -Infinity;
const extend = (c: any): void => {
if (!Array.isArray(c)) return;
if (typeof c[0] === 'number' && typeof c[1] === 'number') {
if (isFinite(c[0]) && isFinite(c[1])) {
lngs.push(((c[0] + 180) % 360 + 360) % 360 - 180);
south = Math.min(south, c[1]);
north = Math.max(north, c[1]);
}
} else {
c.forEach(extend);
}
};
(this.mapData.length
? this.mapData.map(([ref]) => ref)
: (this.page?.content || []).filter(ref => hasTag('plugin/geo', ref)))
.flatMap(ref => features(ref))
.flatMap(f => geoFeatures(f, hasLocation))
.forEach(f => extend((f.geometry as any).coordinates));
if (!lngs.length) return undefined;
const [west, east] = minimalLngInterval(lngs);
return new LngLatBounds([west, south], [east, north]);
}
private updateMapData() {
Eif (!this.map) return;
const source = this.map.getSource('geo-features') as GeoJSONSource | undefined;
if (source) {
source.setData(this.geoData);
}
this.clearMarkers();
this.addMarkers(this.map);
}
private clearMarkers() {
this.markers.forEach(m => m.remove());
this.markers = [];
}
private addMarkers(map: Map) {
this.mapData.forEach(entry => {
const [ref] = entry;
const pointFeature = ref.plugins?.['plugin/geo/point'];
if (pointFeature?.geometry?.type === 'Point' && hasLocation(pointFeature.geometry?.coordinates)) {
const el = this.createMarkerElement(ref);
const marker = el ? new Marker({ element: el }) : new Marker();
marker.addClassName('map-thumbnail');
const title = getTitle(ref);
const markerElement = marker.getElement();
markerElement.title = title;
markerElement.setAttribute('aria-label', title);
markerElement.setAttribute('role', 'link');
markerElement.tabIndex = 0;
marker.setLngLat(pointFeature.geometry.coordinates).addTo(map);
const openRef = () => this.zone.run(() => this.router.navigate(['/ref', ref.url]));
marker.on('click', openRef);
markerElement.addEventListener('keydown', event => {
if (event.key === 'Enter') {
event.preventDefault();
openRef();
}
});
this.markers.push(marker);
}
});
}
private createMarkerElement(ref: Ref): HTMLElement | undefined {
Iif (!this.admin.getPlugin('plugin/thumbnail')) return undefined;
const thumbnailPlugin = ref.plugins?.['plugin/thumbnail'];
Iif (!thumbnailPlugin) return undefined;
const el = document.createElement('div');
el.className = 'thumbnail';
Iif (thumbnailPlugin.color) el.style.backgroundColor = thumbnailPlugin.color;
Iif (thumbnailPlugin.radius) el.style.borderRadius = thumbnailPlugin.radius + 'px';
Iif (thumbnailPlugin.emoji) el.textContent = thumbnailPlugin.emoji;
if (thumbnailPlugin.url && (this.admin.getPlugin('plugin/image') || isInlineSvg(thumbnailPlugin.url))) {
const isProxy = this.admin.getPlugin('plugin/thumbnail')?.config?.proxy;
const url = isProxy && !isInlineSvg(thumbnailPlugin.url)
? this.proxy.getFetch(thumbnailPlugin.url, ref.origin, 'thumbnail', true)
: thumbnailPlugin.url;
el.style.backgroundImage = `url(${url})`;
el.style.backgroundSize = thumbnailPlugin.radius ? 'cover' : 'contain';
}
return el;
}
private getBareRepost(ref: Ref) {
Iif (!this.isBareRepost(ref)) return of([ref] as MapEntry);
const source = repost(ref);
return (this.store.view.top?.url === source
? of(this.store.view.top)
: this.refs.getCurrent(source)
).pipe(
rxMap(sourceRef => [this.withRepostGeo(ref, sourceRef), ref] as MapEntry),
catchError(() => of([ref] as MapEntry)),
);
}
private isBareRepost(ref: Ref) {
return !!ref.sources?.[0] && hasTag('plugin/repost', ref) && !ref.title && !ref.comment;
}
private withRepostGeo(repostRef: Ref, sourceRef: Ref) {
if (!hasTag('plugin/geo', repostRef)) return { ...sourceRef, url: repostRef.url };
const tags = [
...(sourceRef.tags || []).filter(tag => !hasPrefix(tag, 'plugin/geo')),
...(repostRef.tags || []).filter(tag => hasPrefix(tag, 'plugin/geo')),
];
const plugins = {
...this.filterPlugins(sourceRef.plugins, false),
...this.filterPlugins(repostRef.plugins, true),
};
return {
...sourceRef,
url: repostRef.url,
tags: [...new Set(tags)],
plugins: Object.keys(plugins).length ? plugins : undefined,
};
}
private filterPlugins(plugins: Ref['plugins'], geo: boolean) {
return Object.fromEntries(Object.entries(plugins || {}).filter(([key]) => key.startsWith('plugin/geo/') === geo));
}
}
function round(n: number) {
return Math.round(n * 1e6) / 1e6;
}
|