Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Bug] Preserve custom basemap style attributions (#3515) (#3543)
Hafiz Hussain0d0673b60617
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 257f050bf..e74c1ba8c 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -50,6 +50,7 @@ import {isStyleUsingMapboxTiles,isStyleUsingOpenStreetMapTiles,mapHasOpenStreetMapAttribution,+ getBaseMapAttributions,getBaseMapLibrary,BaseMapLibraryConfig,transformRequest,@@ -252,14 +253,76 @@ const DatasetAttributions = ({type AttributionProps = {showBaseMapLibLogo: boolean;showOsmBasemapAttribution: boolean;+ basemapAttributions?: string[];datasetAttributions: DatasetAttribution[];baseMapLibraryConfig: BaseMapLibraryConfig;globeAttributions?: GlobeAttribution[];};+const ATTRIBUTION_ANCHOR_REGEX = /<a\b[^>]*?href=["']([^"']*)["'][^>]*?>(.*?)<\/a>/gi;+const ATTRIBUTION_SAFE_HREF_REGEX = /^(https?:|mailto:)/i;++// Decode the handful of HTML entities that commonly appear in basemap+// attribution strings, so they render as text rather than raw entities.+function decodeAttributionEntities(text: string): string {+ return text+ .replace(/©/gi, '©')+ .replace(/ /gi, ' ')+ .replace(/&/gi, '&')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/"/gi, '"')+ .replace(/�*39;/gi, "'");+}++function attributionTextNode(raw: string, key: string): React.ReactNode {+ // strip any residual markup, then decode entities+ const text = decodeAttributionEntities(raw.replace(/<[^>]*>/g, ''));+ return text ? <React.Fragment key={key}>{text}</React.Fragment> : null;+}++/**+ * Parse a basemap attribution HTML string into safe React nodes. Only anchor+ * tags with http(s)/mailto hrefs become links; everything else is rendered as+ * plain text. This avoids dangerouslySetInnerHTML while preserving the links+ * custom basemap styles (e.g. OpenFreeMap) declare in their attribution.+ */+export function renderBasemapAttribution(html: string, keyPrefix: string): React.ReactNode[] {+ const nodes: React.ReactNode[] = [];+ let lastIndex = 0;+ let match: RegExpExecArray | null;+ let index = 0;+ // regex has global flag; reset before use+ ATTRIBUTION_ANCHOR_REGEX.lastIndex = 0;+ while ((match = ATTRIBUTION_ANCHOR_REGEX.exec(html)) !== null) {+ const [full, href, label] = match;+ if (match.index > lastIndex) {+ nodes.push(attributionTextNode(html.slice(lastIndex, match.index), `${keyPrefix}-t${index}`));+ }+ const text = decodeAttributionEntities(label.replace(/<[^>]*>/g, ''));+ if (ATTRIBUTION_SAFE_HREF_REGEX.test(href) && text) {+ nodes.push(+ <a key={`${keyPrefix}-a${index}`} href={href} target="_blank" rel="noopener noreferrer">+ {text}+ </a>+ );+ } else if (text) {+ // drop unsafe hrefs (e.g. javascript:) but keep the link text+ nodes.push(<React.Fragment key={`${keyPrefix}-a${index}`}>{text}</React.Fragment>);+ }+ lastIndex = match.index + full.length;+ index++;+ }+ if (lastIndex < html.length) {+ nodes.push(attributionTextNode(html.slice(lastIndex), `${keyPrefix}-t${index}`));+ }+ return nodes.filter(Boolean);+}+export const Attribution: React.FC<AttributionProps> = ({showBaseMapLibLogo = true,showOsmBasemapAttribution = false,+ basemapAttributions = [],datasetAttributions,baseMapLibraryConfig,globeAttributions = []@@ -267,6 +330,22 @@ export const Attribution: React.FC<AttributionProps> = ({const isPalm = hasMobileWidth(breakPointValues);const memoizedComponents = useMemo(() => {+ // attributions declared by custom basemap styles, rendered as safe links+ const basemapAttributionNodes = basemapAttributions.length ? (+ <>+ {basemapAttributions.map((attribution, idx) => (+ <React.Fragment key={`basemap-attr-${idx}`}>+ <span className="pipe-separator">|</span>+ {renderBasemapAttribution(attribution, `basemap-attr-${idx}`)}+ </React.Fragment>+ ))}+ </>+ ) : null;++ // fall back to the generic OSM link only when no explicit attribution was+ // collected from the resolved sources (avoids double-rendering)+ const showOsmFallback = showOsmBasemapAttribution && !basemapAttributions.length;+const globeAttributionNodes = globeAttributions.length ? (<>{globeAttributions.map(attr => (@@ -296,6 +375,7 @@ export const Attribution: React.FC<AttributionProps> = ({<a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">© kepler.gl</a>+ {basemapAttributionNodes}{globeAttributionNodes}{globeAttributions.length ? <span className="pipe-separator">|</span> : null}{globeAttributions.length && !isPalm ? (@@ -320,7 +400,8 @@ export const Attribution: React.FC<AttributionProps> = ({<a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">© kepler.gl</a>- {showOsmBasemapAttribution ? (+ {basemapAttributionNodes}+ {showOsmFallback ? (<><span className="pipe-separator">|</span><a@@ -342,6 +423,7 @@ export const Attribution: React.FC<AttributionProps> = ({}, [showBaseMapLibLogo,showOsmBasemapAttribution,+ basemapAttributions,datasetAttributions,isPalm,baseMapLibraryConfig,@@ -498,7 +580,9 @@ export default function MapContainerFactory(state = {showBaseMapAttribution: true,- showOsmAttribution: false+ showOsmAttribution: false,+ // attribution strings declared by custom basemap styles (e.g. OpenFreeMap)+ basemapAttributions: [] as string[]};componentDidMount() {@@ -526,7 +610,8 @@ export default function MapContainerFactory(if (this.props.mapStyle.styleType === NO_MAP_ID) {this.setState({showBaseMapAttribution: false,- showOsmAttribution: false+ showOsmAttribution: false,+ basemapAttributions: []});} else {this._updateAttribution();@@ -747,16 +832,19 @@ export default function MapContainerFactory(}const usesMapbox = styleObj ? isStyleUsingMapboxTiles(styleObj) : false;const usesOsm = styleObj ? isStyleUsingOpenStreetMapTiles(styleObj) : false;+ const basemapAttributions = getBaseMapAttributions(this._map);- if (usesMapbox || usesOsm) {+ if (usesMapbox || usesOsm || basemapAttributions.length) {this.setState({showBaseMapAttribution: true,- showOsmAttribution: usesOsm+ showOsmAttribution: usesOsm,+ basemapAttributions});} else {this.setState({showBaseMapAttribution: false,- showOsmAttribution: false+ showOsmAttribution: false,+ basemapAttributions});this._checkOsmAttributionOnSourceLoad();}@@ -777,11 +865,16 @@ export default function MapContainerFactory(const onSourceData = (e: any) => {if (!e?.isSourceLoaded) return;attempts++;- if (mapHasOpenStreetMapAttribution(this._map)) {+ // TileJSON resolves asynchronously; re-collect attributions once a+ // source is loaded so custom basemap attributions are not lost.+ const basemapAttributions = getBaseMapAttributions(this._map);+ const usesOsm = mapHasOpenStreetMapAttribution(this._map);+ if (basemapAttributions.length || usesOsm) {this._removeOsmSourceDataListener();this.setState({showBaseMapAttribution: true,- showOsmAttribution: true+ showOsmAttribution: usesOsm,+ basemapAttributions});} else if (attempts >= MAX_ATTEMPTS) {this._removeOsmSourceDataListener();@@ -1639,6 +1732,7 @@ export default function MapContainerFactory(<AttributionshowBaseMapLibLogo={this.state.showBaseMapAttribution}showOsmBasemapAttribution={this.state.showOsmAttribution}+ basemapAttributions={this.state.basemapAttributions}datasetAttributions={datasetAttributions}baseMapLibraryConfig={baseMapLibraryConfig}globeAttributions={getGlobeBasemapAttributions({diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 0b84e0972..25751b6fd 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -118,6 +118,7 @@ export {isStyleUsingMapboxTiles,isStyleUsingOpenStreetMapTiles,mapHasOpenStreetMapAttribution,+ getBaseMapAttributions,getBaseMapLibrary,transformRequest} from './map-style-utils/mapbox-utils';diff --git a/src/utils/src/map-style-utils/mapbox-utils.ts b/src/utils/src/map-style-utils/mapbox-utils.tsindex fc5a5ac1f..5df87a1a8 100644--- a/src/utils/src/map-style-utils/mapbox-utils.ts+++ b/src/utils/src/map-style-utils/mapbox-utils.ts@@ -62,6 +62,37 @@ export function mapHasOpenStreetMapAttribution(map: any): boolean {}}+/**+ * Collects the attribution strings declared by the resolved map sources.+ * Custom basemap styles (e.g. OpenFreeMap, OpenMapTiles) declare their own+ * attribution in the source's TileJSON, which only becomes available after+ * MapLibre resolves it. Unlike {@link mapHasOpenStreetMapAttribution}, this+ * preserves the full attribution text instead of collapsing it to a boolean,+ * so custom attributions are not lost.+ * @param map the resolved MapLibre/Mapbox map instance+ * @returns de-duplicated list of attribution HTML strings, order preserved+ */+export function getBaseMapAttributions(map: any): string[] {+ try {+ const style = map?.getStyle?.();+ if (!style?.sources) return [];+ const seen = new Set<string>();+ Object.keys(style.sources).forEach(sourceId => {+ const source = map.getSource?.(sourceId);+ const attribution = source?.attribution;+ if (typeof attribution === 'string') {+ const trimmed = attribution.trim();+ if (trimmed) {+ seen.add(trimmed);+ }+ }+ });+ return [...seen];+ } catch {+ return [];+ }+}+/*** Transform mapbox protocol so can be used with maplibre* @param mapboxKey mapbox api keydiff --git a/test/node/utils/mapbox-utils-test.js b/test/node/utils/mapbox-utils-test.jsindex 859171e2e..56a4461d7 100644--- a/test/node/utils/mapbox-utils-test.js+++ b/test/node/utils/mapbox-utils-test.js@@ -2,7 +2,16 @@// Copyright contributors to the kepler.gl projectimport test from 'tape';-import {isStyleUsingMapboxTiles} from '@kepler.gl/utils';+import {isStyleUsingMapboxTiles, getBaseMapAttributions} from '@kepler.gl/utils';++// Build a minimal mock of a resolved MapLibre/Mapbox map instance where each+// source id resolves to an object exposing an `attribution` string.+function mockMap(sources) {+ return {+ getStyle: () => ({sources}),+ getSource: id => sources[id]+ };+}test('mapbox-utils -> isStyleUsingMapboxTiles', t => {t.notOk(isStyleUsingMapboxTiles({}), 'Empty style does not reference Mapbox');@@ -34,3 +43,56 @@ test('mapbox-utils -> isStyleUsingMapboxTiles', t => {);t.end();});++test('mapbox-utils -> getBaseMapAttributions', t => {+ t.deepEqual(getBaseMapAttributions(undefined), [], 'No map returns empty list');+ t.deepEqual(getBaseMapAttributions({}), [], 'Map without getStyle returns empty list');+ t.deepEqual(getBaseMapAttributions(mockMap({})), [], 'No sources returns empty list');++ t.deepEqual(+ getBaseMapAttributions(+ mockMap({+ a: {attribution: '<a href="https://openfreemap.org">OpenFreeMap</a>'},+ b: {attribution: '<a href="https://www.openmaptiles.org/">© OpenMapTiles</a>'}+ })+ ),+ [+ '<a href="https://openfreemap.org">OpenFreeMap</a>',+ '<a href="https://www.openmaptiles.org/">© OpenMapTiles</a>'+ ],+ 'Collects attribution strings from each resolved source'+ );++ t.deepEqual(+ getBaseMapAttributions(+ mockMap({+ a: {attribution: '© OpenStreetMap'},+ b: {attribution: '© OpenStreetMap'},+ c: {attribution: ' © OpenStreetMap '}+ })+ ),+ ['© OpenStreetMap'],+ 'De-duplicates and trims identical attributions'+ );++ t.deepEqual(+ getBaseMapAttributions(+ mockMap({+ a: {attribution: ''},+ b: {},+ c: {attribution: 42}+ })+ ),+ [],+ 'Ignores empty, missing, and non-string attributions'+ );++ const throwingMap = {+ getStyle: () => {+ throw new Error('style not ready');+ }+ };+ t.deepEqual(getBaseMapAttributions(throwingMap), [], 'Swallows errors and returns empty list');++ t.end();+});