Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: attribution fixes and refactoring (#3550)
Igor Dykhtae3c200c0d3c8
diff --git a/src/components/src/common/styled-components.tsx b/src/components/src/common/styled-components.tsxindex a66fa5146..4fbfbb363 100644--- a/src/components/src/common/styled-components.tsx+++ b/src/components/src/common/styled-components.tsx@@ -583,6 +583,29 @@ export const StyledAttribution = styled.divcolor: ${props => props.theme.labelColor};}+ .basemap-attribution {+ display: inline-block;+ max-width: 220px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ vertical-align: bottom;+ margin-right: 2px;+ font-size: 10px;+ line-height: normal;+ color: ${props => props.theme.labelColor};++ &:hover {+ max-width: none;+ white-space: normal;+ }+ }++ .basemap-attribution a {+ font-size: 10px;+ color: ${props => props.theme.labelColor};+ }+.pipe-separator {text-decoration: none;}@@ -614,6 +637,10 @@ export const StyledAttribution = styled.div.attrition-link {line-height: 1em;}++ .basemap-attribution {+ max-width: 140px;+ }`};`;diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex b8536bed5..9a7ce8001 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -55,7 +55,12 @@ export {geoCoderPanelSelector} from './kepler-gl';export {default as LayerAnimationControllerFactory} from './layer-animation-controller';-export {Attribution, default as MapContainerFactory} from './map-container';+export {+ Attribution,+ renderBasemapAttribution,+ dedupeBasemapAttributions,+ default as MapContainerFactory+} from './map-container';export {default as MapsLayoutFactory} from './maps-layout';export {default as LayoutSplitter, LayoutSplitterMode} from './common/layout-splitter';export {default as ModalContainerFactory} from './modal-container';@@ -101,7 +106,6 @@ export {default as SingleColorPalette} from './side-panel/layer-panel/single-colexport {default as TextLabelPanelFactory} from './side-panel/layer-panel/text-label-panel';export {default as ScenegraphModelSelectorFactory} from './side-panel/layer-panel/scenegraph-model-selector';-export {default as AddLayerButtonFactory} from './side-panel/layer-panel/add-layer-button';export * from './side-panel/layer-panel/channel-by-value-selector';export * from './side-panel/layer-panel/color-breaks-panel';diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex e74c1ba8c..c8873dfaa 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -2,8 +2,8 @@// Copyright contributors to the kepler.gl project// libraries-import React, {Component, createRef, useMemo} from 'react';-import styled, {withTheme, useTheme} from 'styled-components';+import React, {Component, createRef} from 'react';+import styled, {withTheme} from 'styled-components';import {Map as MapboxLegacyMap, MapRef} from 'react-map-gl/mapbox-legacy';import {Map as MaplibreMap} from '@vis.gl/react-maplibre';import {PickingInfo, MapView} from '@deck.gl/core';@@ -17,11 +17,13 @@ import {VisStateActions, MapStateActions, UIStateActions} from '@kepler.gl/actio// componentsimport MapPopoverFactory from './map/map-popover';import MapControlFactory from './map/map-control';+import {StyledMapContainer} from './common/styled-components';import {- StyledMapContainer,- StyledAttribution,- EndHorizontalFlexbox-} from './common/styled-components';+ Attribution,+ AttributionLogos,+ renderBasemapAttribution,+ dedupeBasemapAttributions+} from './map/attribution';import EditorFactory from './editor/editor';import {AnnotationOverlay} from './annotations';@@ -49,14 +51,11 @@ import {errorNotification,isStyleUsingMapboxTiles,isStyleUsingOpenStreetMapTiles,- mapHasOpenStreetMapAttribution,getBaseMapAttributions,getBaseMapLibrary,- BaseMapLibraryConfig,transformRequest,observeDimensions,unobserveDimensions,- hasMobileWidth,getMapLayersFromSplitMaps,onViewPortChange,getViewportFromMapState,@@ -68,7 +67,6 @@ import {getLayerBlendingParameters,patchDeckRendererForPostProcessing} from '@kepler.gl/utils';-import {breakPointValues} from '@kepler.gl/styles';// default-settingsimport {@@ -93,7 +91,6 @@ import {getStarsBackgroundImage,KeplerGlobeView} from '@kepler.gl/deckgl-layers';-import type {GlobeAttribution} from '@kepler.gl/deckgl-layers';import {DROPPABLE_MAP_CONTAINER_TYPE} from './common/dnd-layer-items';// Contexts@@ -161,23 +158,13 @@ const StyledMap = styled(StyledMapContainer)<StyledMapContainerProps>(const MAPBOXGL_STYLE_UPDATE = 'style.load';const MAPBOXGL_RENDER = 'render';-type MapLibLogoProps = {- baseMapLibraryConfig: BaseMapLibraryConfig;-};--const MapLibLogo = ({baseMapLibraryConfig}: MapLibLogoProps) => (- <div className="attrition-logo">- Basemap by:- <a- style={{marginLeft: '5px'}}- className={`${baseMapLibraryConfig.mapLibCssClass}-ctrl-logo`}- target="_blank"- rel="noopener noreferrer"- href={baseMapLibraryConfig.mapLibUrl}- aria-label={`${baseMapLibraryConfig.mapLibName} logo`}- />- </div>-);+// Canonical OpenStreetMap attribution, injected into the collected list when a+// style is detected to use OSM tiles but the resolved sources haven't yielded+// an attribution string of their own (e.g. raw style declares OSM but the+// TileJSON hasn't exposed it). Rendered through the same safe link parser as+// every other collected attribution.+const OSM_ATTRIBUTION_HTML =+ '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';interface StyledDroppableProps {$isOver: boolean;@@ -205,287 +192,9 @@ export const Droppable = ({containerId}) => {return <StyledDroppable ref={setNodeRef} $isOver={isOver} />;};-interface StyledDatasetAttributionsContainerProps {- isPalm: boolean;-}--const StyledDatasetAttributionsContainer = styled.div<StyledDatasetAttributionsContainerProps>`- max-width: ${props => (props.isPalm ? '200px' : '300px')};- text-overflow: ellipsis;- white-space: nowrap;- overflow: hidden;- color: ${props => props.theme.labelColor};- margin-right: 2px;- margin-bottom: 1px;- line-height: ${props => (props.isPalm ? '1em' : '1.4em')};-- &:hover {- white-space: inherit;- }-`;--const DatasetAttributions = ({- datasetAttributions,- isPalm-}: {- datasetAttributions: DatasetAttribution[];- isPalm: boolean;-}) => (- <>- {datasetAttributions?.length ? (- <StyledDatasetAttributionsContainer isPalm={isPalm}>- {datasetAttributions.map((ds, idx) => (- <a- {...(ds.url ? {href: ds.url} : null)}- target="_blank"- rel="noopener noreferrer"- key={`${ds.title}_${idx}`}- >- {ds.title}- {idx !== datasetAttributions.length - 1 ? ', ' : null}- </a>- ))}- </StyledDatasetAttributionsContainer>- ) : null}- </>-);--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 = []-}: 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 => (- <React.Fragment key={attr.label}>- <span className="pipe-separator">|</span>- <a href={attr.href} target="_blank" rel="noopener noreferrer">- {attr.label}- </a>- </React.Fragment>- ))}- </>- ) : null;-- if (!showBaseMapLibLogo) {- return (- <StyledAttribution- mapLibCssClass={baseMapLibraryConfig.mapLibCssClass}- mapLibAttributionCssClass={baseMapLibraryConfig.mapLibAttributionCssClass}- >- <EndHorizontalFlexbox>- <DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />- <div className="attrition-link">- {datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}- {globeAttributions.length && isPalm ? (- <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />- ) : null}- <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 ? (- <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />- ) : null}- </div>- </EndHorizontalFlexbox>- </StyledAttribution>- );- }-- return (- <StyledAttribution- mapLibCssClass={baseMapLibraryConfig.mapLibCssClass}- mapLibAttributionCssClass={baseMapLibraryConfig.mapLibAttributionCssClass}- >- <EndHorizontalFlexbox>- <DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />- <div className="attrition-link">- {datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}- {isPalm ? <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} /> : null}- <a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">- © kepler.gl- </a>- {basemapAttributionNodes}- {showOsmFallback ? (- <>- <span className="pipe-separator">|</span>- <a- href="https://www.openstreetmap.org/copyright"- target="_blank"- rel="noopener noreferrer"- >- © OpenStreetMap- </a>- </>- ) : null}- {globeAttributionNodes}- <span className="pipe-separator">|</span>- {!isPalm ? <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} /> : null}- </div>- </EndHorizontalFlexbox>- </StyledAttribution>- );- }, [- showBaseMapLibLogo,- showOsmBasemapAttribution,- basemapAttributions,- datasetAttributions,- isPalm,- baseMapLibraryConfig,- globeAttributions- ]);-- return memoizedComponents;-};--const StyledAttributionLogoContainer = styled.div<{$left: number}>`- position: absolute;- bottom: ${props => props.theme.sidePanel.margin.left}px;- left: ${props => props.$left}px;- z-index: 1;- display: flex;- align-items: flex-end;- gap: 4px;- pointer-events: auto;- transition: left 250ms ease-in-out;-`;--const StyledLogoLink = styled.a<{$enabled: boolean}>`- cursor: ${props => (props.$enabled ? 'pointer' : 'default')};- display: flex;- align-items: flex-end;-`;--type AttributionLogosProps = {- logos: AttributionWithStyle[];- activeSidePanel?: boolean;- sidePanelWidth?: number;-};--const LOGO_LEFT_ADJUSTMENT = 3;--export const AttributionLogos: React.FC<AttributionLogosProps> = ({- logos,- activeSidePanel,- sidePanelWidth-}) => {- const theme = useTheme() as any;- const left =- (activeSidePanel ? (sidePanelWidth || 0) + LOGO_LEFT_ADJUSTMENT : 0) +- theme.sidePanel.margin.left;-- if (!logos?.length) return null;- return (- <StyledAttributionLogoContainer $left={left}>- {logos.map((logo, idx) => (- <StyledLogoLink- key={logo.logoUrl || idx}- href={logo.url || undefined}- {...(logo.url ? {target: '_blank', rel: 'noopener noreferrer'} : {})}- $enabled={Boolean(logo.url)}- style={logo.bottom ? {marginBottom: logo.bottom} : undefined}- >- <img src={logo.logoUrl} style={{height: logo.height || 12}} alt={logo.title} />- </StyledLogoLink>- ))}- </StyledAttributionLogoContainer>- );-};+// Attribution UI (parser + components) lives in ./map/attribution and is+// re-exported here to preserve the public import path (@kepler.gl/components).+export {Attribution, AttributionLogos, renderBasemapAttribution, dedupeBasemapAttributions};MapContainerFactory.deps = [MapPopoverFactory, MapControlFactory, EditorFactory];@@ -580,7 +289,6 @@ export default function MapContainerFactory(state = {showBaseMapAttribution: true,- showOsmAttribution: false,// attribution strings declared by custom basemap styles (e.g. OpenFreeMap)basemapAttributions: [] as string[]};@@ -610,7 +318,6 @@ export default function MapContainerFactory(if (this.props.mapStyle.styleType === NO_MAP_ID) {this.setState({showBaseMapAttribution: false,- showOsmAttribution: false,basemapAttributions: []});} else {@@ -833,17 +540,21 @@ export default function MapContainerFactory(const usesMapbox = styleObj ? isStyleUsingMapboxTiles(styleObj) : false;const usesOsm = styleObj ? isStyleUsingOpenStreetMapTiles(styleObj) : false;const basemapAttributions = getBaseMapAttributions(this._map);+ // if OSM tiles are detected but no source-level attribution string was+ // collected, fold in the canonical OSM attribution so the render path+ // stays uniform (no separate hardcoded fallback link)+ if (usesOsm && !basemapAttributions.length) {+ basemapAttributions.push(OSM_ATTRIBUTION_HTML);+ }if (usesMapbox || usesOsm || basemapAttributions.length) {this.setState({showBaseMapAttribution: true,- showOsmAttribution: usesOsm,basemapAttributions});} else {this.setState({showBaseMapAttribution: false,- showOsmAttribution: false,basemapAttributions});this._checkOsmAttributionOnSourceLoad();@@ -861,19 +572,22 @@ export default function MapContainerFactory(if (!this._map) return;this._removeOsmSourceDataListener();let attempts = 0;+ // Cap retries so a style that never yields attributions doesn't leave a+ // permanent sourcedata listener attached.const MAX_ATTEMPTS = 50;const onSourceData = (e: any) => {if (!e?.isSourceLoaded) return;attempts++;// TileJSON resolves asynchronously; re-collect attributions once a// source is loaded so custom basemap attributions are not lost.+ // (Unlike the sync path, OSM detection here reads the same resolved+ // sources as getBaseMapAttributions, so a separate OSM fold-in is+ // unreachable — any OSM string would already be in the collected list.)const basemapAttributions = getBaseMapAttributions(this._map);- const usesOsm = mapHasOpenStreetMapAttribution(this._map);- if (basemapAttributions.length || usesOsm) {+ if (basemapAttributions.length) {this._removeOsmSourceDataListener();this.setState({showBaseMapAttribution: true,- showOsmAttribution: usesOsm,basemapAttributions});} else if (attempts >= MAX_ATTEMPTS) {@@ -1731,7 +1445,6 @@ export default function MapContainerFactory({this.props.primary ? (<AttributionshowBaseMapLibLogo={this.state.showBaseMapAttribution}- showOsmBasemapAttribution={this.state.showOsmAttribution}basemapAttributions={this.state.basemapAttributions}datasetAttributions={datasetAttributions}baseMapLibraryConfig={baseMapLibraryConfig}diff --git a/src/components/src/map/attribution.tsx b/src/components/src/map/attribution.tsxnew file mode 100644index 000000000..cd67fcb9b--- /dev/null+++ b/src/components/src/map/attribution.tsx@@ -0,0 +1,466 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useMemo} from 'react';+import styled, {useTheme} from 'styled-components';++import {AttributionWithStyle, DatasetAttribution} from '@kepler.gl/types';+import {BaseMapLibraryConfig, hasMobileWidth} from '@kepler.gl/utils';+import {breakPointValues} from '@kepler.gl/styles';+import type {GlobeAttribution} from '@kepler.gl/deckgl-layers';++import {StyledAttribution, EndHorizontalFlexbox} from '../common/styled-components';++type MapLibLogoProps = {+ baseMapLibraryConfig: BaseMapLibraryConfig;+};++export const MapLibLogo = ({baseMapLibraryConfig}: MapLibLogoProps) => (+ <div className="attrition-logo">+ Basemap by:+ <a+ style={{marginLeft: '5px'}}+ className={`${baseMapLibraryConfig.mapLibCssClass}-ctrl-logo`}+ target="_blank"+ rel="noopener noreferrer"+ href={baseMapLibraryConfig.mapLibUrl}+ aria-label={`${baseMapLibraryConfig.mapLibName} logo`}+ />+ </div>+);++interface StyledDatasetAttributionsContainerProps {+ isPalm: boolean;+}++const StyledDatasetAttributionsContainer = styled.div<StyledDatasetAttributionsContainerProps>`+ max-width: ${props => (props.isPalm ? '200px' : '300px')};+ text-overflow: ellipsis;+ white-space: nowrap;+ overflow: hidden;+ color: ${props => props.theme.labelColor};+ margin-right: 2px;+ margin-bottom: 1px;+ line-height: ${props => (props.isPalm ? '1em' : '1.4em')};++ &:hover {+ white-space: inherit;+ }+`;++export const DatasetAttributions = ({+ datasetAttributions,+ isPalm+}: {+ datasetAttributions: DatasetAttribution[];+ isPalm: boolean;+}) => (+ <>+ {datasetAttributions?.length ? (+ <StyledDatasetAttributionsContainer isPalm={isPalm}>+ {datasetAttributions.map((ds, idx) => (+ <a+ {...(ds.url ? {href: ds.url} : null)}+ target="_blank"+ rel="noopener noreferrer"+ key={`${ds.title}_${idx}`}+ >+ {ds.title}+ {idx !== datasetAttributions.length - 1 ? ', ' : null}+ </a>+ ))}+ </StyledDatasetAttributionsContainer>+ ) : null}+ </>+);++type AttributionProps = {+ showBaseMapLibLogo: boolean;+ basemapAttributions?: string[];+ datasetAttributions: DatasetAttribution[];+ baseMapLibraryConfig: BaseMapLibraryConfig;+ globeAttributions?: GlobeAttribution[];+};++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. Only+ * needed on the SSR / no-DOM fallback path; in the browser DOMParser decodes+ * entities for us.+ */+function decodeAttributionEntities(text: string): string {+ return text+ .replace(/©/gi, '©')+ .replace(/ /gi, ' ')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/"/gi, '"')+ .replace(/�*39;/gi, "'")+ .replace(/&/gi, '&');+}++/**+ * Strip all markup from a string as a fallback for environments without a DOM+ * (e.g. SSR), then decode common HTML entities. Uses a non-greedy tag matcher;+ * only used when DOMParser is unavailable, so it never has to be perfectly+ * correct.+ */+function stripTags(html: string): string {+ return decodeAttributionEntities(html.replace(/<[^>]*>/g, '')).trim();+}++/**+ * Recursively convert parsed DOM nodes into safe React nodes. Only anchor+ * elements with http(s)/mailto hrefs become links; every other element is+ * flattened to its text content. Text nodes are emitted with internal+ * whitespace collapsed to single spaces (matching HTML rendering), so the+ * meaningful single space between adjacent links is preserved while we avoid+ * emitting large whitespace blobs.+ *+ * Anchors are collapsed to their `textContent`, so any markup nested inside an+ * anchor (including an invalid nested `<a>`) becomes plain text — a link can+ * never contain another link.+ */+function domNodesToReact(+ nodes: NodeListOf<ChildNode> | ChildNode[],+ keyPrefix: string,+ counter: {i: number}+): React.ReactNode[] {+ const result: React.ReactNode[] = [];+ nodes.forEach(node => {+ if (node.nodeType === 3 /* TEXT_NODE */) {+ // collapse whitespace runs to a single space (HTML-like), keeping a+ // meaningful separating space between adjacent inline links+ const text = (node.textContent || '').replace(/\s+/g, ' ');+ if (text) {+ result.push(<React.Fragment key={`${keyPrefix}-t${counter.i++}`}>{text}</React.Fragment>);+ }+ return;+ }+ if (node.nodeType !== 1 /* ELEMENT_NODE */) {+ return;+ }+ const el = node as Element;+ const tag = el.tagName.toLowerCase();+ // never surface the source of script/style/template elements as text+ if (tag === 'script' || tag === 'style' || tag === 'template' || tag === 'noscript') {+ return;+ }+ if (tag === 'a') {+ const href = el.getAttribute('href') || '';+ // textContent flattens any nested markup (incl. a nested <a>) to text, so+ // the rendered link can never contain another link+ const text = el.textContent || '';+ if (!text.trim()) return;+ if (ATTRIBUTION_SAFE_HREF_REGEX.test(href)) {+ result.push(+ <a+ key={`${keyPrefix}-a${counter.i++}`}+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ >+ {text}+ </a>+ );+ } else {+ // drop unsafe hrefs (e.g. javascript:) but keep the link text+ result.push(<React.Fragment key={`${keyPrefix}-a${counter.i++}`}>{text}</React.Fragment>);+ }+ return;+ }+ // any other element: keep its (recursively resolved) children+ result.push(...domNodesToReact(el.childNodes, keyPrefix, counter));+ });+ return result;+}++function resolveDOMParser(): {new (): DOMParser} | null {+ return (+ (typeof window !== 'undefined' && (window as any).DOMParser) ||+ (typeof globalThis !== 'undefined' && (globalThis as any).DOMParser) ||+ 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.+ *+ * Uses the browser's DOMParser (inert: scripts don't run and no resources are+ * fetched) so nested tags, `>` inside attributes, unusual quoting, and HTML+ * entities are all handled correctly. Falls back to plain text where no DOM is+ * available (e.g. SSR).+ */+export function renderBasemapAttribution(html: string, keyPrefix: string): React.ReactNode[] {+ const DOMParserCtor = resolveDOMParser();+ if (!DOMParserCtor) {+ const text = stripTags(html);+ return text ? [<React.Fragment key={`${keyPrefix}-t0`}>{text}</React.Fragment>] : [];+ }+ try {+ const doc = new DOMParserCtor().parseFromString(html, 'text/html');+ return domNodesToReact(doc.body.childNodes, keyPrefix, {i: 0}).filter(Boolean);+ } catch {+ const text = stripTags(html);+ return text ? [<React.Fragment key={`${keyPrefix}-t0`}>{text}</React.Fragment>] : [];+ }+}++/**+ * Build a set of "signature" tokens for an attribution string: the hostname of+ * each safe link plus the normalized plain text (lowercased, punctuation and+ * the boilerplate word "contributors" removed). Two attributions that point at+ * the same providers therefore produce overlapping signatures even when their+ * wording differs (e.g. "© OpenStreetMap" vs "© OpenStreetMap contributors").+ */+function attributionSignature(html: string): Set<string> {+ const tokens = new Set<string>();+ const DOMParserCtor = resolveDOMParser();+ let text = html;+ if (DOMParserCtor) {+ try {+ const doc = new DOMParserCtor().parseFromString(html, 'text/html');+ doc.body.querySelectorAll('a').forEach(a => {+ const href = a.getAttribute('href') || '';+ if (ATTRIBUTION_SAFE_HREF_REGEX.test(href)) {+ try {+ tokens.add(`href:${new URL(href).hostname.replace(/^www\./, '').toLowerCase()}`);+ } catch {+ tokens.add(`href:${href.toLowerCase()}`);+ }+ }+ });+ text = doc.body.textContent || '';+ } catch {+ text = stripTags(html);+ }+ } else {+ text = stripTags(html);+ }+ const normalized = text+ .toLowerCase()+ .replace(/©|©/g, '')+ .replace(/\bcontributors?\b/g, '')+ .replace(/[^a-z0-9]+/g, ' ')+ .trim();+ if (normalized) {+ // emit per-word tokens so a shorter attribution's words can be subsumed by+ // a longer one that mentions the same providers (e.g. "openstreetmap" is+ // covered by a CARTO string mentioning both "carto" and "openstreetmap")+ normalized.split(' ').forEach(word => {+ if (word) tokens.add(`text:${word}`);+ });+ }+ return tokens;+}++/**+ * Drop attributions whose providers are already fully represented by a single+ * earlier (kept) attribution. Order is preserved, and the longer/more complete+ * strings tend to come first from the sources so they survive. This collapses+ * near-duplicates such as a standalone "© OpenStreetMap" when a CARTO string+ * that already links OpenStreetMap is present.+ *+ * Subsumption is checked against each kept attribution *individually* (never a+ * merged union), so an entry is only dropped when some single earlier entry+ * fully covers it. This avoids false positives where two unrelated providers'+ * tokens together happen to cover a distinct third provider.+ */+export function dedupeBasemapAttributions(attributions: string[]): string[] {+ const kept: string[] = [];+ const keptTokens: Set<string>[] = [];+ attributions.forEach(attribution => {+ const sig = attributionSignature(attribution);+ if (sig.size === 0) {+ // nothing to compare on; keep as-is (exact dedup already done upstream)+ if (!kept.includes(attribution)) {+ kept.push(attribution);+ keptTokens.push(sig);+ }+ return;+ }+ // subsumed only if some single kept attribution's tokens are a superset+ const isSubsumed = keptTokens.some(+ tokens => tokens.size > 0 && [...sig].every(t => tokens.has(t))+ );+ if (!isSubsumed) {+ kept.push(attribution);+ keptTokens.push(sig);+ }+ });+ return kept;+}++/**+ * Render a list of items as `| item | item ...` fragments, each preceded by a+ * pipe separator. Keys are index-based (safe even when item content collides,+ * e.g. two globe attributions sharing a label). Returns null when empty so+ * callers can `{group}` inline.+ */+function renderSeparatedLinks<T>(+ items: T[],+ keyPrefix: string,+ renderItem: (item: T, index: number) => React.ReactNode+): React.ReactNode {+ if (!items.length) return null;+ return (+ <>+ {items.map((item, idx) => (+ <React.Fragment key={`${keyPrefix}-${idx}`}>+ <span className="pipe-separator">|</span>+ {renderItem(item, idx)}+ </React.Fragment>+ ))}+ </>+ );+}++export const Attribution: React.FC<AttributionProps> = ({+ showBaseMapLibLogo = true,+ basemapAttributions = [],+ datasetAttributions,+ baseMapLibraryConfig,+ globeAttributions = []+}: AttributionProps) => {+ const isPalm = hasMobileWidth(breakPointValues);++ const memoizedComponents = useMemo(() => {+ // collapse near-duplicate attributions (e.g. a standalone OSM link when a+ // CARTO string already links OSM) before rendering+ const dedupedBasemapAttributions = dedupeBasemapAttributions(basemapAttributions);+ // attributions declared by custom basemap styles, rendered as safe links+ const basemapAttributionNodes = renderSeparatedLinks(+ dedupedBasemapAttributions,+ 'basemap-attr',+ (attribution, idx) => (+ <span className="basemap-attribution">+ {renderBasemapAttribution(attribution, `basemap-attr-${idx}`)}+ </span>+ )+ );++ const globeAttributionNodes = renderSeparatedLinks(globeAttributions, 'globe-attr', attr => (+ <a href={attr.href} target="_blank" rel="noopener noreferrer">+ {attr.label}+ </a>+ ));++ if (!showBaseMapLibLogo) {+ return (+ <StyledAttribution+ mapLibCssClass={baseMapLibraryConfig.mapLibCssClass}+ mapLibAttributionCssClass={baseMapLibraryConfig.mapLibAttributionCssClass}+ >+ <EndHorizontalFlexbox>+ <DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />+ <div className="attrition-link">+ {datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}+ {globeAttributions.length && isPalm ? (+ <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />+ ) : null}+ <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 ? (+ <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />+ ) : null}+ </div>+ </EndHorizontalFlexbox>+ </StyledAttribution>+ );+ }++ return (+ <StyledAttribution+ mapLibCssClass={baseMapLibraryConfig.mapLibCssClass}+ mapLibAttributionCssClass={baseMapLibraryConfig.mapLibAttributionCssClass}+ >+ <EndHorizontalFlexbox>+ <DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} />+ <div className="attrition-link">+ {datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}+ {isPalm ? <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} /> : null}+ <a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">+ © kepler.gl+ </a>+ {basemapAttributionNodes}+ {globeAttributionNodes}+ <span className="pipe-separator">|</span>+ {!isPalm ? <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} /> : null}+ </div>+ </EndHorizontalFlexbox>+ </StyledAttribution>+ );+ }, [+ showBaseMapLibLogo,+ basemapAttributions,+ datasetAttributions,+ isPalm,+ baseMapLibraryConfig,+ globeAttributions+ ]);++ return memoizedComponents;+};++const StyledAttributionLogoContainer = styled.div<{$left: number}>`+ position: absolute;+ bottom: ${props => props.theme.sidePanel.margin.left}px;+ left: ${props => props.$left}px;+ z-index: 1;+ display: flex;+ align-items: flex-end;+ gap: 4px;+ pointer-events: auto;+ transition: left 250ms ease-in-out;+`;++const StyledLogoLink = styled.a<{$enabled: boolean}>`+ cursor: ${props => (props.$enabled ? 'pointer' : 'default')};+ display: flex;+ align-items: flex-end;+`;++type AttributionLogosProps = {+ logos: AttributionWithStyle[];+ activeSidePanel?: boolean;+ sidePanelWidth?: number;+};++const LOGO_LEFT_ADJUSTMENT = 3;++export const AttributionLogos: React.FC<AttributionLogosProps> = ({+ logos,+ activeSidePanel,+ sidePanelWidth+}) => {+ const theme = useTheme() as any;+ const left =+ (activeSidePanel ? (sidePanelWidth || 0) + LOGO_LEFT_ADJUSTMENT : 0) ++ theme.sidePanel.margin.left;++ if (!logos?.length) return null;+ return (+ <StyledAttributionLogoContainer $left={left}>+ {logos.map((logo, idx) => (+ <StyledLogoLink+ key={logo.logoUrl || idx}+ href={logo.url || undefined}+ {...(logo.url ? {target: '_blank', rel: 'noopener noreferrer'} : {})}+ $enabled={Boolean(logo.url)}+ style={logo.bottom ? {marginBottom: logo.bottom} : undefined}+ >+ <img src={logo.logoUrl} style={{height: logo.height || 12}} alt={logo.title} />+ </StyledLogoLink>+ ))}+ </StyledAttributionLogoContainer>+ );+};diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 25751b6fd..44b5fa7ea 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -122,6 +122,7 @@ export {getBaseMapLibrary,transformRequest} from './map-style-utils/mapbox-utils';+export type {AttributionMapLike} from './map-style-utils/mapbox-utils';// Mapexport * from './map-utils';diff --git a/src/utils/src/map-style-utils/mapbox-utils.ts b/src/utils/src/map-style-utils/mapbox-utils.tsindex 5df87a1a8..e2fe162de 100644--- a/src/utils/src/map-style-utils/mapbox-utils.ts+++ b/src/utils/src/map-style-utils/mapbox-utils.ts@@ -39,18 +39,35 @@ export function isStyleUsingOpenStreetMapTiles(mapStyle: any) {});}+/**+ * Minimal structural contract for the MapLibre/Mapbox map instance used by the+ * attribution helpers below. Only the members actually read are declared;+ * everything is optional because these helpers may be called before the map is+ * fully initialized (guarded by optional chaining + try/catch at runtime).+ *+ * `getSource` returns `any` on purpose: the concrete MapLibre/Mapbox source+ * union (GeoJSONSource, VectorSource, …) is not structurally assignable to a+ * `{attribution?}` shape, and we only ever read an optional `attribution`+ * string off it. Declaring the two getters still catches passing a non-map.+ */+export interface AttributionMapLike {+ getStyle?: () => {sources?: Record<string, unknown>} | undefined | null;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getSource?: (id: string) => any;+}+/*** Checks resolved map sources for OpenStreetMap attribution.* CARTO basemaps don't have attribution in the raw style JSON;* it only appears after MapLibre resolves the TileJSON.* Uses map.getSource() to access the resolved source with TileJSON metadata.*/-export function mapHasOpenStreetMapAttribution(map: any): boolean {+export function mapHasOpenStreetMapAttribution(map?: AttributionMapLike | null): boolean {try {const style = map?.getStyle?.();if (!style?.sources) return false;return Object.keys(style.sources).some(sourceId => {- const source = map.getSource?.(sourceId);+ const source = map?.getSource?.(sourceId);const attribution = source?.attribution;if (typeof attribution === 'string') {return attribution.toLowerCase().includes('openstreetmap');@@ -72,13 +89,13 @@ export function mapHasOpenStreetMapAttribution(map: any): boolean {* @param map the resolved MapLibre/Mapbox map instance* @returns de-duplicated list of attribution HTML strings, order preserved*/-export function getBaseMapAttributions(map: any): string[] {+export function getBaseMapAttributions(map?: AttributionMapLike | null): 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 source = map?.getSource?.(sourceId);const attribution = source?.attribution;if (typeof attribution === 'string') {const trimmed = attribution.trim();diff --git a/test/browser/components/attribution-test.js b/test/browser/components/attribution-test.jsnew file mode 100644index 000000000..675e25284--- /dev/null+++ b/test/browser/components/attribution-test.js@@ -0,0 +1,441 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import test from 'tape';+import {mountWithTheme} from 'test/helpers/component-utils';+import {renderBasemapAttribution, dedupeBasemapAttributions} from '@kepler.gl/components';++// Helper: mount the parsed nodes and return the enzyme wrapper.+function mountAttribution(html) {+ return mountWithTheme(<div>{renderBasemapAttribution(html, 'k')}</div>);+}++test('renderBasemapAttribution -> plain text', t => {+ const wrapper = mountAttribution('© OpenStreetMap contributors');+ t.equal(wrapper.find('a').length, 0, 'No anchors for plain text');+ t.equal(wrapper.text(), '© OpenStreetMap contributors', 'Text preserved verbatim');+ t.end();+});++test('renderBasemapAttribution -> single safe anchor', t => {+ const wrapper = mountAttribution('© <a href="https://carto.com/attributions">CARTO</a>');+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'One anchor rendered');+ t.equal(anchors.at(0).prop('href'), 'https://carto.com/attributions', 'href preserved');+ t.equal(anchors.at(0).prop('target'), '_blank', 'opens in new tab');+ t.equal(anchors.at(0).prop('rel'), 'noopener noreferrer', 'safe rel');+ t.equal(anchors.at(0).text(), 'CARTO', 'anchor text preserved');+ t.ok(wrapper.text().startsWith('©'), 'leading text preserved');+ t.end();+});++test('renderBasemapAttribution -> OpenFreeMap style (multiple links + entities)', t => {+ const html =+ '<a href="https://openfreemap.org" target="_blank">OpenFreeMap</a> ' ++ '<a href="https://www.openmaptiles.org/" target="_blank">© OpenMapTiles</a> ' ++ 'Data from <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>';+ const wrapper = mountAttribution(html);+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 3, 'All three links preserved');+ t.deepEqual(+ anchors.map(a => a.prop('href')),+ [+ 'https://openfreemap.org',+ 'https://www.openmaptiles.org/',+ 'https://www.openstreetmap.org/copyright'+ ],+ 'All hrefs preserved in order'+ );+ t.ok(wrapper.text().includes('© OpenMapTiles'), 'HTML entity (©) decoded');+ t.end();+});++test('renderBasemapAttribution -> drops unsafe javascript: href, keeps text', t => {+ const wrapper = mountAttribution(+ // eslint-disable-next-line no-script-url+ '<a href="javascript:alert(1)">Bad</a> and <a href="https://ok.com">Good</a>'+ );+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'Only the safe anchor becomes a link');+ t.equal(anchors.at(0).prop('href'), 'https://ok.com', 'safe href kept');+ t.ok(wrapper.text().includes('Bad'), 'unsafe link text still rendered as plain text');+ const unsafeCount = anchors.reduce(+ (n, a) => n + ((a.prop('href') || '').startsWith('javascript:') ? 1 : 0),+ 0+ );+ t.equal(unsafeCount, 0, 'no javascript: href rendered');+ t.end();+});++test('renderBasemapAttribution -> mailto is allowed', t => {+ const wrapper = mountAttribution('<a href="mailto:[email protected]">Contact</a>');+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'mailto anchor is a link');+ t.equal(anchors.at(0).prop('href'), 'mailto:[email protected]', 'mailto href preserved');+ t.end();+});++test('renderBasemapAttribution -> nested tags and > inside attribute (regex-breaking cases)', t => {+ // A '>' inside an attribute value and nested markup would break the old+ // regex-based parser; the DOM parser handles both.+ const html = '<a href="https://x.com" data-tip="a > b"><b>Bold</b> Link</a> tail';+ const wrapper = mountAttribution(html);+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'One anchor despite > inside attribute');+ t.equal(anchors.at(0).prop('href'), 'https://x.com', 'href parsed correctly');+ t.equal(anchors.at(0).text(), 'Bold Link', 'nested tag content flattened to text');+ t.ok(wrapper.text().includes('tail'), 'trailing text preserved');+ t.end();+});++test('renderBasemapAttribution -> empty / whitespace', t => {+ t.deepEqual(renderBasemapAttribution('', 'k'), [], 'empty string yields no nodes');+ const wrapper = mountAttribution(' ');+ t.equal(wrapper.find('a').length, 0, 'whitespace yields no anchors');+ t.end();+});++test('renderBasemapAttribution -> single space preserved between adjacent links', t => {+ // whitespace between two links must collapse to a single space (not be+ // dropped), so links don't run together (e.g. OpenFreeMap-style strings)+ const html = '<a href="https://a.com">A</a> <a href="https://b.com">B</a>';+ const wrapper = mountAttribution(html);+ t.equal(wrapper.find('a').length, 2, 'both links rendered');+ t.equal(wrapper.text(), 'A B', 'a single separating space is preserved');+ t.end();+});++test('renderBasemapAttribution -> collapses whitespace runs but keeps inter-link spacing', t => {+ const html =+ '<a href="https://openfreemap.org">OpenFreeMap</a> ' ++ '<a href="https://www.openmaptiles.org/">© OpenMapTiles</a> ' ++ 'Data from <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';+ const wrapper = mountAttribution(html);+ t.equal(+ wrapper.text(),+ 'OpenFreeMap © OpenMapTiles Data from OpenStreetMap',+ 'links stay separated by single spaces'+ );+ t.end();+});++test('renderBasemapAttribution -> nested <a> inside <a> does not produce link-in-link', t => {+ // invalid markup: an anchor nested inside another anchor. Browsers (and+ // JSDOM) auto-close the outer <a>, yielding sibling anchors; the parser must+ // never emit an anchor that contains another anchor.+ const html = '<a href="https://outer.com">outer <a href="https://inner.com">inner</a></a>';+ const wrapper = mountAttribution(html);+ const container = wrapper.getDOMNode();+ const anchorEls = container.querySelectorAll('a');+ anchorEls.forEach(a => {+ t.equal(a.querySelectorAll('a').length, 0, 'no anchor nested inside another anchor');+ });+ t.ok(wrapper.text().includes('inner'), 'inner link text preserved');+ t.ok(wrapper.text().includes('outer'), 'outer link text preserved');+ t.end();+});++test('renderBasemapAttribution -> script/style/template/noscript content is not rendered', t => {+ const cases = [+ 'before<script>alert(1)</script>after',+ 'a<style>.x{color:red}</style>b',+ 'c<template><span>hidden</span></template>d',+ 'e<noscript>noscript-text</noscript>f'+ ];+ cases.forEach(html => {+ const wrapper = mountAttribution(html);+ t.equal(wrapper.find('script').length, 0, `no script element rendered: ${html}`);+ t.equal(wrapper.find('style').length, 0, `no style element rendered: ${html}`);+ t.notOk(wrapper.text().includes('alert(1)'), 'script source not surfaced as text');+ t.notOk(wrapper.text().includes('color:red'), 'style source not surfaced as text');+ t.notOk(wrapper.text().includes('hidden'), 'template content not surfaced as text');+ t.notOk(wrapper.text().includes('noscript-text'), 'noscript content not surfaced as text');+ });+ t.end();+});++test('renderBasemapAttribution -> unsafe/non-allowlisted schemes are dropped, text kept', t => {+ const cases = [+ {href: '//evil.com', label: 'protocol-relative'},+ {href: '/relative/path', label: 'relative'},+ {href: 'tel:12345', label: 'tel'},+ {href: 'ftp://host/file', label: 'ftp'},+ {href: 'data:text/html,<b>x</b>', label: 'data'},+ // eslint-disable-next-line no-script-url+ {href: ' javascript:alert(1)', label: 'js with leading space'},+ // eslint-disable-next-line no-script-url+ {href: 'JAVASCRIPT:alert(1)', label: 'uppercase js'},+ {href: 'vbscript:msgbox(1)', label: 'vbscript'}+ ];+ cases.forEach(({href, label}) => {+ const wrapper = mountAttribution(`<a href="${href}">click ${label}</a>`);+ t.equal(wrapper.find('a').length, 0, `no link rendered for ${label}`);+ t.ok(wrapper.text().includes(`click ${label}`), `text preserved for ${label}`);+ });+ t.end();+});++test('renderBasemapAttribution -> allowlisted schemes are kept (incl. uppercase, http)', t => {+ const cases = [+ 'http://plain.com',+ 'https://secure.com',+ 'HTTPS://UPPER.COM',+ 'mailto:[email protected]',+ 'MAILTO:[email protected]'+ ];+ cases.forEach(href => {+ const wrapper = mountAttribution(`<a href="${href}">x</a>`);+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, `link rendered for ${href}`);+ t.equal(anchors.at(0).prop('href'), href, `href preserved for ${href}`);+ t.equal(anchors.at(0).prop('rel'), 'noopener noreferrer', `safe rel for ${href}`);+ t.equal(anchors.at(0).prop('target'), '_blank', `target _blank for ${href}`);+ });+ t.end();+});++test('renderBasemapAttribution -> empty and whitespace-only anchors are dropped', t => {+ const empty = mountAttribution('<a href="https://x.com"></a>tail');+ t.equal(empty.find('a').length, 0, 'empty anchor is not rendered as a link');+ t.ok(empty.text().includes('tail'), 'surrounding text kept');++ const wsOnly = mountAttribution('<a href="https://x.com"> </a>keep');+ t.equal(wsOnly.find('a').length, 0, 'whitespace-only anchor is not rendered as a link');+ t.ok(wsOnly.text().includes('keep'), 'surrounding text kept');+ t.end();+});++test('renderBasemapAttribution -> event-handler attributes are never carried to output', t => {+ // even for a safe href, only href/target/rel are set; inline handlers dropped+ const wrapper = mountAttribution(+ '<a href="https://x.com" onclick="alert(1)" onmouseover="x()" style="color:red">y</a>'+ );+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'safe anchor rendered');+ t.notOk(anchors.at(0).prop('onClick'), 'no onClick handler');+ t.notOk(anchors.at(0).prop('onclick'), 'no onclick attribute');+ t.notOk(anchors.at(0).prop('style'), 'no inline style carried over');+ t.end();+});++test('renderBasemapAttribution -> img/onerror payload does not render an image or execute', t => {+ const wrapper = mountAttribution('<img src="x" onerror="alert(1)">visible');+ t.equal(wrapper.find('img').length, 0, 'no img element rendered');+ t.equal(wrapper.text(), 'visible', 'only surrounding text is rendered');+ t.end();+});++test('renderBasemapAttribution -> deeply nested non-anchor markup flattens to text', t => {+ const html =+ '<div><span><b>Deep</b> <i>text</i></span> and <a href="https://x.com">link</a></div>';+ const wrapper = mountAttribution(html);+ const anchors = wrapper.find('a');+ t.equal(anchors.length, 1, 'the single link is preserved');+ t.equal(anchors.at(0).prop('href'), 'https://x.com', 'href preserved through nesting');+ t.ok(wrapper.text().includes('Deep text'), 'nested formatting flattened to text');+ t.end();+});++test('renderBasemapAttribution -> always returns an array, never throws', t => {+ const inputs = [+ '',+ ' ',+ 'plain',+ '<a>no href</a>',+ '<a href="">empty href</a>',+ '<<<malformed>>>',+ '<a href="https://x.com">unclosed',+ '© & < > entities'+ ];+ inputs.forEach(html => {+ const out = renderBasemapAttribution(html, 'k');+ t.ok(Array.isArray(out), `array returned for ${JSON.stringify(html)}`);+ });+ t.end();+});++test('renderBasemapAttribution -> keys are unique across produced nodes', t => {+ const html =+ 'a <a href="https://one.com">one</a> b <a href="https://two.com">two</a> c ' ++ '<a href="https://three.com">three</a>';+ const nodes = renderBasemapAttribution(html, 'k');+ const keys = nodes.map(n => n.key);+ t.equal(new Set(keys).size, keys.length, 'no duplicate React keys');+ t.ok(keys.every(Boolean), 'every node has a key');+ t.end();+});++test('dedupeBasemapAttributions -> exact duplicates', t => {+ t.deepEqual(+ dedupeBasemapAttributions(['© OpenStreetMap', '© OpenStreetMap']),+ ['© OpenStreetMap'],+ 'collapses exact duplicates'+ );+ t.end();+});++test('dedupeBasemapAttributions -> wording variants collapse (OSM vs OSM contributors)', t => {+ t.deepEqual(+ dedupeBasemapAttributions(['© OpenStreetMap contributors', '© OpenStreetMap']),+ ['© OpenStreetMap contributors'],+ 'the standalone OSM string is subsumed by the fuller one'+ );+ t.end();+});++test('dedupeBasemapAttributions -> standalone OSM link subsumed by CARTO string that links OSM', t => {+ const carto =+ '© <a href="https://carto.com/attributions">CARTO</a>, © ' ++ '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';+ const osm = '<a href="https://www.openstreetmap.org/copyright">© OpenStreetMap</a>';+ t.deepEqual(+ dedupeBasemapAttributions([carto, osm]),+ [carto],+ 'OSM-only entry dropped because CARTO already links OSM and the text overlaps'+ );+ t.end();+});++test('dedupeBasemapAttributions -> distinct providers are all kept', t => {+ const ofm = '<a href="https://openfreemap.org">OpenFreeMap</a>';+ const omt = '<a href="https://www.openmaptiles.org/">© OpenMapTiles</a>';+ const osm = '<a href="https://www.openstreetmap.org/copyright">© OpenStreetMap</a>';+ t.deepEqual(+ dedupeBasemapAttributions([ofm, omt, osm]),+ [ofm, omt, osm],+ 'independent providers are preserved'+ );+ t.end();+});++test('dedupeBasemapAttributions -> distinct provider not dropped by token cross-contamination', t => {+ // "Map Co" is a distinct provider; its tokens (map, co) each appear in a+ // *different* earlier entry, but no single earlier entry covers both, so it+ // must be kept (guards against union-based false positives)+ const a = '© Map Data';+ const b = '© Data Co';+ const c = '© Map Co';+ t.deepEqual(+ dedupeBasemapAttributions([a, b, c]),+ [a, b, c],+ 'entry whose tokens span two different kept entries is not subsumed'+ );+ t.end();+});++test('dedupeBasemapAttributions -> www prefix and casing normalized', t => {+ const a = '<a href="https://www.OpenStreetMap.org/copyright">OpenStreetMap</a>';+ const b = '<a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>';+ t.deepEqual(+ dedupeBasemapAttributions([a, b]),+ [a],+ 'same host regardless of www/casing collapses'+ );+ t.end();+});++test('dedupeBasemapAttributions -> synthesized OSM entry is subsumed by CARTO', t => {+ // mirrors the runtime fold-in: a synthesized canonical OSM link should not+ // double-render when a CARTO string already links OSM+ const carto =+ '© <a href="https://carto.com/attributions">CARTO</a>, © ' ++ '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';+ const synthesizedOsm = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';+ t.deepEqual(+ dedupeBasemapAttributions([carto, synthesizedOsm]),+ [carto],+ 'canonical OSM entry dropped when CARTO already links OSM'+ );+ t.end();+});++test('dedupeBasemapAttributions -> empty and single-entry inputs', t => {+ t.deepEqual(dedupeBasemapAttributions([]), [], 'empty input yields empty output');+ t.deepEqual(dedupeBasemapAttributions(['© Solo']), ['© Solo'], 'single entry is kept');+ t.end();+});++test('dedupeBasemapAttributions -> order is preserved', t => {+ const a = '<a href="https://a.com">Alpha</a>';+ const b = '<a href="https://b.com">Beta</a>';+ const c = '<a href="https://c.com">Gamma</a>';+ t.deepEqual(dedupeBasemapAttributions([c, a, b]), [c, a, b], 'input order preserved');+ t.end();+});++test('dedupeBasemapAttributions -> shorter-first: fuller variant adds no new tokens, collapses', t => {+ // "© OpenStreetMap" comes first and is kept; the fuller "... contributors"+ // normalizes to the same token set ("contributors" is boilerplate), so it is+ // subsumed and the shorter (first) entry wins+ const osm = '© OpenStreetMap';+ const osmFull = '© OpenStreetMap contributors';+ t.deepEqual(+ dedupeBasemapAttributions([osm, osmFull]),+ [osm],+ 'fuller variant with only boilerplate difference collapses to the first'+ );+ t.end();+});++test('dedupeBasemapAttributions -> fuller entry with new tokens after a shorter one is kept', t => {+ // shorter first; the later entry introduces a genuinely new token (carto), so+ // it is NOT subsumed and both are kept+ const osm = '© OpenStreetMap';+ const both = '© CARTO, © OpenStreetMap';+ t.deepEqual(+ dedupeBasemapAttributions([osm, both]),+ [osm, both],+ 'later entry with an additional provider is preserved'+ );+ t.end();+});++test('dedupeBasemapAttributions -> is idempotent', t => {+ const carto =+ '© <a href="https://carto.com/attributions">CARTO</a>, © ' ++ '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';+ const osm = '<a href="https://www.openstreetmap.org/copyright">© OpenStreetMap</a>';+ const once = dedupeBasemapAttributions([carto, osm]);+ const twice = dedupeBasemapAttributions(once);+ t.deepEqual(twice, once, 'running dedupe again changes nothing');+ t.end();+});++test('dedupeBasemapAttributions -> does not mutate its input array', t => {+ const input = ['© OpenStreetMap contributors', '© OpenStreetMap'];+ const snapshot = [...input];+ dedupeBasemapAttributions(input);+ t.deepEqual(input, snapshot, 'input array is unchanged');+ t.end();+});++test('dedupeBasemapAttributions -> different link hosts are not merged', t => {+ const a = '<a href="https://openstreetmap.org">Map</a>';+ const b = '<a href="https://openmaptiles.org">Map</a>';+ // same visible text "Map" but different hosts -> both kept (host token differs)+ t.deepEqual(+ dedupeBasemapAttributions([a, b]),+ [a, b],+ 'same text but distinct hosts are preserved'+ );+ t.end();+});++test('dedupeBasemapAttributions -> punctuation/casing/whitespace normalized in text', t => {+ const a = '© OpenStreetMap Contributors';+ const b = '© openstreetmap, contributors';+ t.deepEqual(+ dedupeBasemapAttributions([a, b]),+ [a],+ 'text normalized (case, punctuation, whitespace, "contributors") collapses'+ );+ t.end();+});++test('dedupeBasemapAttributions -> whitespace-only entries are dropped as empty signatures', t => {+ // exact-dup path keeps the first; a second identical whitespace entry is a+ // duplicate string so it is removed+ t.deepEqual(dedupeBasemapAttributions([' ', ' ']), [' '], 'duplicate blank collapses');+ t.end();+});diff --git a/test/browser/components/index.js b/test/browser/components/index.jsindex 1ffe2b356..235ba39bf 100644--- a/test/browser/components/index.js+++ b/test/browser/components/index.js@@ -14,6 +14,7 @@ import './editor';import './filters';import './geocoder-panel-test';import './tooltip-config-test';+import './attribution-test';import './bottom-widget-test';import './plot-container-test';import './effects';