Skip to content

Colota - Android GPS Location tracker

11.9 KB
Raw Blame
/**
 * Copyright (C) 2026 Max Dietrich
 * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
 */

import React, { useRef, useImperativeHandle, forwardRef, useState, useEffect, useCallback } from "react"
import { StyleProp, ViewStyle, View, StyleSheet, Linking } from "react-native"
import { Map, Camera } from "@maplibre/maplibre-react-native"
import type {
  MapRef,
  CameraRef,
  ViewStateChangeEvent,
  LngLatBounds,
  ViewPadding
} from "@maplibre/maplibre-react-native"
import type { NativeSyntheticEvent } from "react-native"
import { Compass, ExternalLink, Info } from "lucide-react-native"
import { useIsFocused } from "@react-navigation/native"
import { useTheme } from "../../../hooks/useTheme"
import {
  DEFAULT_MAP_ZOOM,
  MAP_STYLE_URL_DARK,
  MAP_STYLE_URL_LIGHT,
  MAX_MAP_ZOOM,
  size,
  space
} from "../../../constants"
import NativeLocationService from "../../../services/NativeLocationService"
import { MapActionButton, mapActionStyles } from "./MapActionButton"
import { DialogShell } from "../../ui/DialogShell"
import { Divider } from "../../ui/Divider"
import { ListItem } from "../../ui/ListItem"
import { Button } from "../../ui/Button"
import { logger } from "../../../utils/logger"
import { t } from "../../../i18n/t"
import { useTranslation } from "../../../i18n/useTranslation"
import type { TranslationKey } from "../../../i18n/options"

interface AttributionLink {
  url: string
  label: string
}

// Used for the default server when its style fetch fails or returns no attribution. Must cover
// anything legally required for the default tile sources (OSM ODbL,
// OpenMapTiles CC-BY) so attribution is never silently hidden.
const FALLBACK_ATTRIBUTION_LINKS: AttributionLink[] = [
  { url: "https://www.openstreetmap.org/copyright", label: "© OpenStreetMap contributors" },
  { url: "https://openmaptiles.org", label: "© OpenMapTiles" },
  { url: "https://openfreemap.org", label: "OpenFreeMap" },
  { url: "https://maps.mxd.codes", label: "maps.mxd.codes" }
]

/** What each known source contributes; a custom tile server's own credits show without a role. */
const ATTRIBUTION_ROLES: Record<string, TranslationKey> = {
  "openstreetmap.org": "map.role.osm",
  "openmaptiles.org": "map.role.omt",
  "openfreemap.org": "map.role.ofm",
  "maps.mxd.codes": "map.role.mxd"
}

/** The credits come from the style JSON, so key on the host itself and not on a link that names one. */
function attributionHost(url: string): string {
  return url
    .replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")
    .split(/[/?#]/)[0]
    .replace(/^[^@]*@/, "")
    .split(":")[0]
    .toLowerCase()
}

export function attributionRole(url: string): string | undefined {
  const host = attributionHost(url)
  const known = Object.keys(ATTRIBUTION_ROLES).find((name) => host === name || host.endsWith(`.${name}`))
  return known ? t(ATTRIBUTION_ROLES[known]) : undefined
}

function parseAttributionLinks(htmls: string[]): AttributionLink[] {
  const seen = new Set<string>()
  const links: AttributionLink[] = []
  const anchorRe = /<a\s+[^>]*href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/gi
  for (const html of htmls) {
    for (const match of html.matchAll(anchorRe)) {
      const url = match[1]
      const label = match[2]
        .replace(/&copy;/g, "©")
        .replace(/&amp;/g, "&")
        .trim()
      if (!label || seen.has(url)) continue
      seen.add(url)
      links.push({ url, label })
    }
  }
  return links
}

/** MapLibre reads a source's credits from the style first, then from the TileJSON its url names. */
async function sourceAttributions(sources: unknown, signal: AbortSignal): Promise<string[]> {
  if (!sources || typeof sources !== "object") return []
  const found = await Promise.all(
    Object.values(sources as Record<string, { attribution?: unknown; url?: unknown }>).map(async (src) => {
      if (typeof src?.attribution === "string") return src.attribution
      if (typeof src?.url !== "string" || !/^https?:/i.test(src.url)) return null
      const tileJson = await fetch(src.url, { signal })
        .then((r) => r.json())
        .catch((err) => {
          if (err?.name === "AbortError") throw err
          return null
        })
      return typeof tileJson?.attribution === "string" ? tileJson.attribution : null
    })
  )
  return found.filter((html): html is string => html !== null)
}

/** The default list names the default server's sources, so a custom server is credited by its own host. */
function fallbackAttribution(styleUrl: string): AttributionLink[] {
  if (styleUrl === MAP_STYLE_URL_LIGHT || styleUrl === MAP_STYLE_URL_DARK) return FALLBACK_ATTRIBUTION_LINKS
  const scheme = styleUrl.match(/^https?:\/\//i)?.[0]
  if (!scheme) return []
  const authority = styleUrl.slice(scheme.length).split(/[/?#]/)[0]
  const host = authority.slice(authority.lastIndexOf("@") + 1)
  return host ? [{ url: scheme + host, label: attributionHost(host) }] : []
}

export interface ColotaMapRef {
  camera: CameraRef | null
  mapView: MapRef | null
}

export interface RegionChangePayload {
  heading: number
  isUserInteraction: boolean
  bounds: LngLatBounds
}

interface Props {
  initialCenter: [number, number] // [lon, lat]
  initialZoom?: number
  onPress?: (coords: { latitude: number; longitude: number }) => void
  onRegionDidChange?: (payload: RegionChangePayload) => void
  onMapReady?: () => void
  cameraPadding?: ViewPadding
  controlsBottom?: number
  controlsEnd?: number
  style?: StyleProp<ViewStyle>
  children?: React.ReactNode
}

export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapViewInner(
  {
    initialCenter,
    initialZoom = DEFAULT_MAP_ZOOM,
    onPress,
    onRegionDidChange,
    onMapReady,
    cameraPadding,
    controlsBottom,
    controlsEnd,
    style,
    children
  },
  ref
) {
  const cameraRef = useRef<CameraRef>(null)
  const mapViewRef = useRef<MapRef>(null)
  const { colors, mode } = useTheme()
  useTranslation()
  const isDark = mode === "dark"

  const [mapStyleLight, setMapStyleLight] = useState(MAP_STYLE_URL_LIGHT)
  const [mapStyleDark, setMapStyleDark] = useState(MAP_STYLE_URL_DARK)
  const [heading, setHeading] = useState(0)
  const [attributionLinks, setAttributionLinks] = useState<AttributionLink[]>(FALLBACK_ATTRIBUTION_LINKS)
  const [attributionOpen, setAttributionOpen] = useState(false)

  const isFocused = useIsFocused()

  useEffect(() => {
    if (!isFocused) return
    Promise.all([
      NativeLocationService.getSetting("mapStyleUrlLight"),
      NativeLocationService.getSetting("mapStyleUrlDark")
    ])
      .then(([light, dark]) => {
        setMapStyleLight(light || MAP_STYLE_URL_LIGHT)
        setMapStyleDark(dark || MAP_STYLE_URL_DARK)
      })
      .catch(() => {})
  }, [isFocused])

  useImperativeHandle(
    ref,
    () => ({
      get camera() {
        return cameraRef.current
      },
      get mapView() {
        return mapViewRef.current
      }
    }),
    []
  )

  const mapStyle = isDark ? mapStyleDark : mapStyleLight

  useEffect(() => {
    const fallback = fallbackAttribution(mapStyle)
    if (!/^https?:/i.test(mapStyle)) {
      setAttributionLinks(fallback)
      return
    }
    const controller = new AbortController()
    fetch(mapStyle, { signal: controller.signal })
      .then((r) => r.json())
      .then(async (loadedStyle: { sources?: unknown }) => {
        const links = parseAttributionLinks(await sourceAttributions(loadedStyle?.sources, controller.signal))
        if (controller.signal.aborted) return
        setAttributionLinks(links.length > 0 ? links : fallback)
      })
      .catch((err) => {
        if (err?.name === "AbortError") return
        setAttributionLinks(fallback)
      })
    return () => controller.abort()
  }, [mapStyle])

  const hasPadding = cameraPadding !== undefined
  const { top, right, bottom, left } = cameraPadding ?? {}
  useEffect(() => {
    if (!hasPadding) return
    cameraRef.current?.setStop({ padding: { top, right, bottom, left }, duration: 0 })
  }, [hasPadding, top, right, bottom, left])

  const handleRegionDidChange = useCallback(
    (event: NativeSyntheticEvent<ViewStateChangeEvent>) => {
      const { bearing, userInteraction, bounds } = event.nativeEvent
      setHeading(bearing ?? 0)
      if (onRegionDidChange) {
        onRegionDidChange({ heading: bearing ?? 0, isUserInteraction: userInteraction, bounds })
      }
    },
    [onRegionDidChange]
  )

  const handleCompassPress = useCallback(() => {
    if (cameraRef.current) {
      cameraRef.current.setStop({
        bearing: 0,
        duration: 300,
        easing: "ease"
      })
    }
  }, [])

  const handlePress = useCallback(
    (event: NativeSyntheticEvent<{ lngLat: [number, number] }>) => {
      if (onPress) {
        const [lon, lat] = event.nativeEvent.lngLat
        onPress({ latitude: lat, longitude: lon })
      }
    },
    [onPress]
  )

  const showCompass = Math.abs(heading) > 3
  const columnEnd = controlsEnd !== undefined && { right: controlsEnd }
  const attributionStyle = [
    mapActionStyles.right,
    controlsBottom !== undefined && { bottom: controlsBottom },
    columnEnd
  ]
  const compassStyle = [
    mapActionStyles.right,
    controlsBottom === undefined
      ? styles.compassPosition
      : { bottom: controlsBottom + 2 * (size.iconColumn + space.lg) },
    columnEnd
  ]

  return (
    <View style={[styles.container, style]}>
      <Map
        ref={mapViewRef}
        style={styles.map}
        mapStyle={mapStyle}
        androidView="texture"
        attribution={false}
        logo={false}
        compass={false}
        onDidFinishLoadingMap={onMapReady}
        onDidFailLoadingMap={() => logger.error("[ColotaMapView] Map style failed to load")}
        onPress={onPress ? handlePress : undefined}
        onRegionDidChange={handleRegionDidChange}
      >
        <Camera
          ref={cameraRef}
          maxZoom={MAX_MAP_ZOOM}
          initialViewState={{
            center: initialCenter,
            zoom: initialZoom,
            ...(cameraPadding && { padding: cameraPadding })
          }}
        />

        {children}
      </Map>

      {/* Custom compass button */}
      {showCompass && (
        <MapActionButton
          onPress={handleCompassPress}
          style={compassStyle}
          accessibilityRole="button"
          accessibilityLabel={t("map.north")}
        >
          <View style={{ transform: [{ rotate: `${-heading}deg` }] }}>
            <Compass size={size.icon.md} color={colors.textLight} />
          </View>
        </MapActionButton>
      )}

      {attributionLinks.length > 0 && (
        <>
          <MapActionButton
            onPress={() => setAttributionOpen(true)}
            style={attributionStyle}
            accessibilityRole="button"
            accessibilityLabel={t("map.showAttribution")}
          >
            <Info size={size.icon.md} color={colors.textLight} />
          </MapActionButton>

          <DialogShell
            visible={attributionOpen}
            title={t("map.credits")}
            onRequestClose={() => setAttributionOpen(false)}
            footer={<Button title={t("common.close")} variant="ghost" onPress={() => setAttributionOpen(false)} />}
          >
            <View style={styles.attributionRows}>
              {attributionLinks.map((link, i) => (
                <React.Fragment key={link.url}>
                  {i > 0 && <Divider tight />}
                  <ListItem
                    label={link.label}
                    sub={attributionRole(link.url)}
                    trailingIcon={ExternalLink}
                    accessibilityRole="link"
                    onPress={() => Linking.openURL(link.url)}
                  />
                </React.Fragment>
              ))}
            </View>
          </DialogShell>
        </>
      )}
    </View>
  )
})

const styles = StyleSheet.create({
  container: { flex: 1 },
  map: { flex: 1 },
  compassPosition: { bottom: space.xxl + 2 * (size.iconColumn + space.lg) },
  // A row cancels a card's lg inset; the dialog pads xl, so the rows step out the remaining sm to reach its edge.
  attributionRows: {
    marginHorizontal: -space.sm
  }
})