Skip to content

Colota - Android GPS Location tracker

fix(map): credit a custom tile server with its own sources (#869)

Max Dietrich7de1669ba4e7
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 253d5995..6f9a8985 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -349,7 +349,7 @@ The app uses [MapLibre GL Native](https://github.com/maplibre/maplibre-react-nat
| Component | Purpose |
| --- | --- |
-| `ColotaMapView` | Shared base map component wrapping MapLibre's `MapView` with OpenFreeMap vector tiles, dark mode style transformation, custom compass, and attribution |
+| `ColotaMapView` | Shared base map wrapping MapLibre's `Map` with the light or dark style URL, a custom compass and the credits dialog. Credits come from each source in the style or its TileJSON; a custom server that publishes none is credited by its host |
| `DashboardMap` | Live tracking map with user marker, accuracy circle, today's track (its visibility is the screen's Route toggle, the map only draws it), geofence polygons with labels, follow-me until the user pans, then a centre button in the disc column. Frames the last known fix, or the zones when there is none |
| `TrackMap` | Location history map: trip-colored track segments over a casing layer, a focused trip drawn wider while the rest dim, 48 dp point hitboxes, fit-to-day and fit-to-trip bounds. Selection and focus are props; it draws no popup or legend |
| `CalendarPicker` | Day, month and year panes inside `DayPickerModal`, dot indicators for days with data, per-day stats spoken by the cell |
diff --git a/apps/docs/docs/guides/tile-server.md b/apps/docs/docs/guides/tile-server.md
index b922eb9c..314b1146 100644
--- a/apps/docs/docs/guides/tile-server.md
+++ b/apps/docs/docs/guides/tile-server.md
@@ -59,7 +59,7 @@ For a light/dark pair, use `bright` or `liberty` for light mode and `fiord` for
:::note[Attribution]
-When using the default server, the map shows **© OpenMapTiles · © OpenStreetMap contributors · © maps.mxd.codes** attribution. When a custom server is configured, attribution is read automatically from the style JSON served by your tile server.
+When using the default server, the map shows **© OpenMapTiles · © OpenStreetMap contributors · © maps.mxd.codes** attribution. With a custom server, the credits come from its style JSON or from the TileJSON a source points to. A server that publishes none is credited with its host name.
:::
diff --git a/apps/mobile/src/components/features/map/ColotaMapView.tsx b/apps/mobile/src/components/features/map/ColotaMapView.tsx
index c20bee21..caae94df 100644
--- a/apps/mobile/src/components/features/map/ColotaMapView.tsx
+++ b/apps/mobile/src/components/features/map/ColotaMapView.tsx
@@ -38,7 +38,7 @@ interface AttributionLink {
label: string
}
-// Used when the style fetch fails or returns no attribution. Must cover
+// 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[] = [
@@ -72,17 +72,17 @@ export function attributionRole(url: string): string | undefined {
return known ? ATTRIBUTION_ROLES[known] : undefined
}
-function parseStyleAttribution(sources: unknown): AttributionLink[] {
- if (!sources || typeof sources !== "object") return []
+function parseAttributionLinks(htmls: string[]): AttributionLink[] {
const seen = new Set<string>()
const links: AttributionLink[] = []
const anchorRe = /<a\s+[^>]*href=["']([^"']+)["'][^>]*>([^<]+)<\/a>/gi
- for (const src of Object.values(sources as Record<string, unknown>)) {
- const html = (src as { attribution?: unknown })?.attribution
- if (typeof html !== "string") continue
+ for (const html of htmls) {
for (const match of html.matchAll(anchorRe)) {
const url = match[1]
- const label = match[2].trim()
+ const label = match[2]
+ .replace(/&copy;/g, "©")
+ .replace(/&amp;/g, "&")
+ .trim()
if (!label || seen.has(url)) continue
seen.add(url)
links.push({ url, label })
@@ -91,6 +91,35 @@ function parseStyleAttribution(sources: unknown): AttributionLink[] {
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
@@ -172,20 +201,22 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
const mapStyle = isDark ? mapStyleDark : mapStyleLight
useEffect(() => {
+ const fallback = fallbackAttribution(mapStyle)
if (!/^https?:/i.test(mapStyle)) {
- setAttributionLinks(FALLBACK_ATTRIBUTION_LINKS)
+ setAttributionLinks(fallback)
return
}
const controller = new AbortController()
fetch(mapStyle, { signal: controller.signal })
.then((r) => r.json())
- .then((loadedStyle: { sources?: unknown }) => {
- const parsed = parseStyleAttribution(loadedStyle?.sources)
- setAttributionLinks(parsed.length > 0 ? parsed : FALLBACK_ATTRIBUTION_LINKS)
+ .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_ATTRIBUTION_LINKS)
+ setAttributionLinks(fallback)
})
return () => controller.abort()
}, [mapStyle])
diff --git a/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx
index 19168ad3..5f976968 100644
--- a/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx
+++ b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx
@@ -1,7 +1,7 @@
import React from "react"
-import { render, fireEvent } from "@testing-library/react-native"
-import { StyleSheet } from "react-native"
-import { HIT_SLOP_SM, size, space, MAX_MAP_ZOOM } from "../../../../constants"
+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"
+import { Linking, StyleSheet } from "react-native"
+import { HIT_SLOP_SM, size, space, MAX_MAP_ZOOM, MAP_STYLE_URL_LIGHT } from "../../../../constants"
const mockSetStop = jest.fn()
const mockCameraProps = jest.fn()
@@ -37,6 +37,7 @@ jest.mock("../../../../services/NativeLocationService", () => ({
import { ColotaMapView, attributionRole } from "../ColotaMapView"
import { MapActionButton, mapActionStyles } from "../MapActionButton"
+import NativeLocationService from "../../../../services/NativeLocationService"
const padding = { top: 40, right: 64, bottom: 200, left: 16 }
const center: [number, number] = [11.5, 48.1]
@@ -228,3 +229,108 @@ describe("attributionRole", () => {
expect(attributionRole("https://[email protected]/")).toBeUndefined()
})
})
+
+describe("ColotaMapView credits from the loaded style", () => {
+ const CUSTOM_STYLE = "https://tiles.example.com/styles/light.json"
+ const TILEJSON = "https://tiles.example.com/planet.json"
+ const getSetting = NativeLocationService.getSetting as jest.Mock
+ const fetchMock = globalThis.fetch as jest.Mock
+
+ function serve(lightStyleUrl: string | null, responses: Record<string, unknown>) {
+ getSetting.mockImplementation((key: string) => Promise.resolve(key === "mapStyleUrlLight" ? lightStyleUrl : null))
+ fetchMock.mockImplementation((url: string) =>
+ url in responses
+ ? Promise.resolve({ json: () => Promise.resolve(responses[url]) })
+ : Promise.reject(new Error("offline"))
+ )
+ }
+
+ function openCredits() {
+ const utils = render(<ColotaMapView initialCenter={center} />)
+ fireEvent.press(utils.getByRole("button", { name: "Show map attribution" }))
+ return utils
+ }
+
+ afterEach(() => {
+ getSetting.mockImplementation(() => Promise.resolve(null))
+ fetchMock.mockImplementation(() => new Promise(() => {}))
+ })
+
+ it("credits a custom server with the names in the TileJSON its source points to, since a style may carry none itself", async () => {
+ serve(CUSTOM_STYLE, {
+ [CUSTOM_STYLE]: { sources: { carto: { type: "vector", url: TILEJSON } }, layers: [] },
+ [TILEJSON]: {
+ attribution:
+ '&copy; <a href="https://carto.com/about-carto/">CARTO</a>, &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
+ }
+ })
+ const { findByText, getAllByRole, queryByText } = openCredits()
+
+ expect(await findByText("CARTO")).toBeTruthy()
+ expect(getAllByRole("link")).toHaveLength(2)
+ expect(queryByText("maps.mxd.codes")).toBeNull()
+ })
+
+ it("prints the copyright sign OpenFreeMap writes as an entity inside its link", async () => {
+ serve(CUSTOM_STYLE, {
+ [CUSTOM_STYLE]: {
+ sources: {
+ planet: {
+ type: "vector",
+ attribution:
+ '<a href="https://www.openmaptiles.org/">&copy; OpenMapTiles</a> <a href="https://tiles.example.com/">Tiles &amp; Styles</a>'
+ }
+ }
+ }
+ })
+ const { findByText, getByText, queryByText } = openCredits()
+
+ expect(await findByText("Tiles & Styles")).toBeTruthy()
+ expect(getByText("© OpenMapTiles")).toBeTruthy()
+ expect(queryByText("&copy; OpenMapTiles")).toBeNull()
+ })
+
+ it.each([
+ [
+ "names no credits",
+ {
+ [CUSTOM_STYLE]: {
+ sources: { planet: { type: "vector", tiles: ["https://tiles.example.com/{z}/{x}/{y}.pbf"] } }
+ }
+ }
+ ],
+ ["cannot be read", {}]
+ ])(
+ "credits a custom server whose style %s by its host, never with the default server's sources",
+ async (_case, responses: Record<string, unknown>) => {
+ serve(CUSTOM_STYLE, responses)
+ const { findByText, getAllByRole, queryByText } = openCredits()
+
+ expect(await findByText("tiles.example.com")).toBeTruthy()
+ expect(getAllByRole("link")).toHaveLength(1)
+ expect(queryByText("© OpenStreetMap contributors")).toBeNull()
+ }
+ )
+
+ it("links a host credit to the server without the credentials its style URL carries", async () => {
+ serve("https://user:[email protected]:8443/style.json", {})
+ const openURL = jest.spyOn(Linking, "openURL").mockResolvedValue(undefined)
+ const { findByText } = openCredits()
+
+ fireEvent.press(await findByText("tiles.example.com"))
+
+ expect(openURL).toHaveBeenCalledWith("https://tiles.example.com:8443")
+ openURL.mockRestore()
+ })
+
+ it("keeps the default server's own credits when its style cannot be read", async () => {
+ serve(null, {})
+ const { getAllByRole, getByText } = openCredits()
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(MAP_STYLE_URL_LIGHT, expect.anything()))
+ await act(() => new Promise<void>((resolve) => setTimeout(() => resolve(), 0)))
+
+ expect(getAllByRole("link")).toHaveLength(4)
+ expect(getByText("OpenFreeMap")).toBeTruthy()
+ })
+})
diff --git a/fastlane/metadata/android/en-US/changelogs/50.txt b/fastlane/metadata/android/en-US/changelogs/50.txt
index 31ea420a..91581418 100644
--- a/fastlane/metadata/android/en-US/changelogs/50.txt
+++ b/fastlane/metadata/android/en-US/changelogs/50.txt
@@ -5,3 +5,4 @@
- GeoJSON exports write one point per recording
- Switching units updates every screen at once
- Offline maps picks up a running download when you come back
+- Map credits show a custom tile server's own sources