@burdenoff/microfe-bigconsole 2026.613.4 → 2026.613.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"MapWidget.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/map-widget/MapWidget.tsx"],"sourcesContent":["/**\n * MapWidget Component\n *\n * Interactive geographic map (Leaflet + OpenStreetMap tiles) with data-bound\n * markers. Leaflet's stylesheet is loaded from a CDN at runtime (with SRI) because\n * the build-time MFE library bundle does not ship a component's CSS to the host\n * shell — consistent with the map being an inherently online feature (tiles).\n */\n\nimport { type FC, memo, useEffect, useMemo, useRef, useState } from 'react';\nimport L from 'leaflet';\nimport type { Widget } from '../../../types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MapWidgetProps {\n widget: Widget;\n data?: MapData;\n onClick?: (marker: MapMarker) => void;\n /** Drilldown handler - receives selected marker data */\n onDrilldown?: (selectedData: Record<string, unknown>) => void;\n}\n\nexport interface MapMarker {\n name: string;\n lat: number;\n lng: number;\n value?: number;\n popup?: string;\n color?: string;\n}\n\n/** Minimal GeoJSON FeatureCollection shape (we only read geometry + properties). */\nexport interface GeoJsonFeatureCollection {\n type: 'FeatureCollection';\n features: Array<{\n type: 'Feature';\n id?: string | number;\n properties?: Record<string, unknown> | null;\n geometry: unknown;\n }>;\n}\n\n/** A region value used to shade a choropleth (joined to a GeoJSON feature). */\nexport interface MapRegionValue {\n /** Join key — matched against the feature's id field. */\n id: string;\n /** Numeric value driving the fill intensity. */\n value: number;\n /** Optional display name for the popup. */\n name?: string;\n}\n\nexport interface MapData {\n center?: { lat: number; lng: number };\n zoom?: number;\n markers?: MapMarker[];\n /** GeoJSON regions for choropleth mode. */\n geoJson?: GeoJsonFeatureCollection;\n /** Per-region values joined to GeoJSON features for choropleth shading. */\n regions?: MapRegionValue[];\n}\n\n// ============================================================================\n// Leaflet CSS (runtime CDN injection)\n// ============================================================================\n\nconst LEAFLET_CSS = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';\n// SRI for leaflet@1.9.4/dist/leaflet.css (immutable versioned URL) — guards against a CDN compromise.\nconst LEAFLET_CSS_SRI = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';\n\nlet leafletCssRequested = false;\n\nfunction ensureLeafletCss(): void {\n // Module-level guard in addition to the DOM check so two MapWidgets mounting in\n // the same tick can't both append the <link> before either lands in the DOM.\n if (leafletCssRequested || document.getElementById('leaflet-css')) return;\n leafletCssRequested = true;\n const link = document.createElement('link');\n link.id = 'leaflet-css';\n link.rel = 'stylesheet';\n link.href = LEAFLET_CSS;\n link.integrity = LEAFLET_CSS_SRI;\n link.crossOrigin = 'anonymous';\n // Don't leak the current path (workspace/dashboard IDs) to the CDN.\n link.referrerPolicy = 'no-referrer';\n // Leaflet needs its stylesheet for correct tile/marker positioning. If the CDN\n // is unreachable or the SRI check fails the load is otherwise silent, so warn and\n // clear the guard/element to allow a later mount to retry.\n link.onerror = () => {\n console.warn('[bigconsole] Leaflet CSS failed to load; map styling may be broken.');\n leafletCssRequested = false;\n link.remove();\n };\n document.head.appendChild(link);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nconst DEFAULT_MARKER_COLOR = 'var(--color-chart-1, #3b82f6)';\n\n/**\n * Marker colours come from widget data and are interpolated into an inline\n * `style` attribute, so restrict them to a safe character set (hex / rgb() /\n * hsl() / css var() / named colours). Anything outside that — or containing\n * style-breaking characters — falls back to the default token colour.\n */\nfunction safeColor(color: unknown): string {\n // Marker data is untrusted: a parser can emit a non-string colour (e.g. a numeric\n // status code) that slips past the lat/lng filter, so guard the type before trim().\n if (typeof color !== 'string') return DEFAULT_MARKER_COLOR;\n const trimmed = color.trim();\n if (trimmed.length > 64) return DEFAULT_MARKER_COLOR;\n if (/[;{}<>\"'\\\\]/.test(trimmed)) return DEFAULT_MARKER_COLOR;\n // Block `url()` so a marker colour can't smuggle an exfiltration beacon\n // (e.g. `url(//evil.com/pixel)`) through the otherwise-permissive char set.\n if (/\\burl\\s*\\(/i.test(trimmed)) return DEFAULT_MARKER_COLOR;\n // Allow `_` (custom-property names) and `/` (modern `rgb(r g b / a)` syntax);\n // the dangerous-char guard above still blocks anything that could break out of\n // the inline style.\n if (!/^[#a-zA-Z0-9(),.%/_\\s-]+$/.test(trimmed)) return DEFAULT_MARKER_COLOR;\n return trimmed;\n}\n\nfunction isFiniteNumber(v: unknown): v is number {\n return typeof v === 'number' && Number.isFinite(v);\n}\n\n/**\n * Normalize the bound widget data into markers + optional center/zoom. Accepts\n * the documented `{ markers, center, zoom }` shape, or a bare array of markers\n * (parser output), and drops any entry without valid coordinates.\n */\ninterface NormalizedMapData {\n markers: MapMarker[];\n /** Center explicitly supplied by the data payload — wins over markers. */\n center?: { lat: number; lng: number };\n /** Zoom explicitly supplied by the data payload. */\n zoom?: number;\n /** Center from widget config — a static fallback used only when there are no markers. */\n fallbackCenter?: { lat: number; lng: number };\n /** Zoom from widget config — fallback for the no-marker case. */\n fallbackZoom?: number;\n /** GeoJSON for choropleth mode. */\n geoJson?: GeoJsonFeatureCollection;\n /** region id → { value, name } map for choropleth shading. */\n regionValues: Map<string, { value: number; name?: string }>;\n}\n\nfunction asLatLng(v: unknown): { lat: number; lng: number } | undefined {\n const c = v as { lat?: unknown; lng?: unknown } | undefined;\n return c && isFiniteNumber(c.lat) && isFiniteNumber(c.lng) ? { lat: c.lat, lng: c.lng } : undefined;\n}\n\nfunction normalizeMapData(data: MapData | MapMarker[] | undefined, config: Record<string, unknown>): NormalizedMapData {\n // The widget may be handed either the documented { markers, center, zoom } shape\n // or a bare marker array (parser output); narrow once so the rest is type-safe.\n const payload: MapData | undefined = Array.isArray(data) ? undefined : data;\n const rawMarkers: unknown = Array.isArray(data) ? data : data?.markers;\n const markers: MapMarker[] = Array.isArray(rawMarkers)\n ? (rawMarkers as MapMarker[]).filter((m) => m && isFiniteNumber(m.lat) && isFiniteNumber(m.lng))\n : [];\n\n // Choropleth inputs: GeoJSON (from data payload or config) + a region→value join.\n const geoJson = (payload?.geoJson ?? (config.geoJson as GeoJsonFeatureCollection | undefined)) || undefined;\n const regionIdField = (config.regionIdField as string) || 'id';\n const regionValues = new Map<string, { value: number; name?: string }>();\n const rawRegions: unknown = payload?.regions ?? config.regions;\n if (Array.isArray(rawRegions)) {\n for (const r of rawRegions as Array<Record<string, unknown>>) {\n if (!r) continue;\n const id = r[regionIdField] ?? r.id ?? r.region ?? r.code;\n const value = r.value ?? r.count ?? r.total;\n if (id != null && isFiniteNumber(value)) {\n regionValues.set(String(id), { value, name: typeof r.name === 'string' ? r.name : undefined });\n }\n }\n }\n\n // Data-payload center/zoom are an explicit intent and win over markers. Config\n // center/zoom (e.g. the WidgetRegistry default of {0,0}/2) are only a static\n // fallback for marker-less maps — otherwise that default would pin every marker\n // dataset to the world view instead of framing the markers.\n return {\n markers,\n center: asLatLng(payload?.center),\n zoom: isFiniteNumber(payload?.zoom) ? payload?.zoom : undefined,\n fallbackCenter: asLatLng(config.center),\n fallbackZoom: isFiniteNumber(config.zoom) ? (config.zoom as number) : undefined,\n geoJson: geoJson && Array.isArray(geoJson.features) ? geoJson : undefined,\n regionValues,\n };\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const MapWidget: FC<MapWidgetProps> = memo(function MapWidget({ widget, data, onClick, onDrilldown }) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n // Signature of the last view we auto-framed to; lets us re-render markers on\n // every data change without snapping the viewport back when the framing\n // inputs (coords/center/zoom) are unchanged — e.g. a refetch of identical data.\n const lastFrameSigRef = useRef<string | null>(null);\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n\n const config = useMemo(() => (widget?.config ?? {}) as Record<string, unknown>, [widget?.config]);\n const showMarkers = config.showMarkers !== false;\n const regionIdField = (config.regionIdField as string) || 'id';\n const { markers, center, zoom, fallbackCenter, fallbackZoom, geoJson, regionValues } = useMemo(\n () => normalizeMapData(data, config),\n [data, config]\n );\n const hasChoropleth = Boolean(geoJson && regionValues.size > 0);\n\n // Keep the latest click handler in a ref so marker bindings don't need rebinding.\n // Assign in an effect (not during render) per the React 19 useRef guidance.\n const clickRef = useRef<(marker: MapMarker) => void>(() => undefined);\n useEffect(() => {\n clickRef.current = (marker: MapMarker) => {\n if (onDrilldown) onDrilldown(marker as unknown as Record<string, unknown>);\n else if (onClick) onClick(marker);\n };\n }, [onClick, onDrilldown]);\n\n // Initialise the map once.\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n\n let map: L.Map;\n try {\n map = L.map(el, { center: [20, 0], zoom: 2, scrollWheelZoom: true, attributionControl: true });\n const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenStreetMap contributors',\n maxZoom: 18,\n });\n // Leaflet reports tile failures asynchronously, so addTo() won't throw when\n // tiles are blocked/offline. Surface the error overlay only if a tile errors\n // before any tile has loaded (true offline/blocked), tolerating the odd\n // transient miss once the base map is up.\n let anyTileLoaded = false;\n tiles.on('tileload', () => {\n anyTileLoaded = true;\n // Recover if an early tile miss had shown the offline overlay — a flaky\n // connection that later succeeds shouldn't stay hidden behind it.\n setStatus((s) => (s === 'error' ? 'ready' : s));\n });\n tiles.on('tileerror', () => {\n if (!anyTileLoaded) setStatus('error');\n });\n tiles.addTo(map);\n mapRef.current = map;\n // Fresh map ⇒ force the next marker effect to (re)frame it. Without this the\n // frame-signature ref would survive a remount (e.g. React StrictMode's\n // double-invoke) and the new map would stay stuck at this init view.\n lastFrameSigRef.current = null;\n setStatus('ready');\n } catch {\n setStatus('error');\n return undefined;\n }\n\n // Widgets live in a resizable grid; keep tiles correct as the box changes.\n const ro =\n typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => mapRef.current?.invalidateSize()) : undefined;\n ro?.observe(el);\n const t = window.setTimeout(() => map.invalidateSize(), 80);\n\n return () => {\n window.clearTimeout(t);\n ro?.disconnect();\n map.remove();\n mapRef.current = null;\n };\n }, []);\n\n // Render markers + frame the view whenever the data changes.\n useEffect(() => {\n const map = mapRef.current;\n if (!map) return undefined;\n\n const layer = L.layerGroup();\n\n // Choropleth: shade GeoJSON regions by a single-hue intensity ramp (the\n // semantic `info` token at varying opacity) joined on the region id field.\n let geoLayer: L.GeoJSON | null = null;\n if (geoJson && regionValues.size > 0) {\n const vals = Array.from(regionValues.values()).map((v) => v.value);\n const min = Math.min(...vals);\n const max = Math.max(...vals);\n const span = max - min || 1;\n const FILL = 'var(--color-status-info, #3b82f6)';\n\n const lookup = (feature: { id?: string | number; properties?: Record<string, unknown> | null }) => {\n const props = feature.properties ?? {};\n const joinId = feature.id ?? props[regionIdField] ?? props.id ?? props.code;\n return joinId != null ? regionValues.get(String(joinId)) : undefined;\n };\n\n geoLayer = L.geoJSON(geoJson as unknown as Parameters<typeof L.geoJSON>[0], {\n style: (feature) => {\n const hit = feature ? lookup(feature) : undefined;\n const norm = hit ? (hit.value - min) / span : 0;\n return {\n fillColor: FILL,\n fillOpacity: hit ? 0.2 + norm * 0.65 : 0.05,\n color: 'var(--color-border-default, #cbd5e1)',\n weight: 1,\n };\n },\n onEachFeature: (feature, lyr) => {\n const hit = lookup(feature);\n const name =\n hit?.name ??\n (typeof feature.properties?.name === 'string' ? (feature.properties.name as string) : undefined) ??\n String(feature.id ?? '');\n const popupEl = document.createElement('div');\n const title = document.createElement('div');\n title.style.fontWeight = '600';\n title.textContent = name || 'Region';\n popupEl.appendChild(title);\n if (hit) {\n const val = document.createElement('div');\n val.textContent = hit.value.toLocaleString();\n popupEl.appendChild(val);\n }\n lyr.bindPopup(popupEl);\n lyr.on('click', () => clickRef.current({ name, lat: NaN, lng: NaN, value: hit?.value } as MapMarker));\n },\n });\n geoLayer.addTo(layer);\n }\n\n if (showMarkers) {\n for (const marker of markers) {\n // Build the pin as a DOM element (not an HTML string) so the marker colour\n // is assigned via the style API and can never be interpreted as markup —\n // defense-in-depth alongside safeColor().\n const pin = document.createElement('div');\n Object.assign(pin.style, {\n width: '14px',\n height: '14px',\n borderRadius: '50% 50% 50% 0',\n transform: 'rotate(-45deg)',\n background: safeColor(marker.color),\n border: '2px solid #fff',\n boxShadow: '0 1px 4px rgba(0,0,0,.4)',\n });\n const icon = L.divIcon({\n className: 'bc-map-marker',\n html: pin,\n iconSize: [14, 14],\n iconAnchor: [7, 14],\n });\n const m = L.marker([marker.lat, marker.lng], { icon }).addTo(layer);\n\n // bindPopup treats a string as HTML; build a text node so marker-supplied\n // text can never be interpreted as markup (defense-in-depth).\n const popupEl = document.createElement('div');\n const title = document.createElement('div');\n title.style.fontWeight = '600';\n title.textContent = marker.popup || marker.name || 'Location';\n popupEl.appendChild(title);\n if (isFiniteNumber(marker.value)) {\n const val = document.createElement('div');\n val.textContent = marker.value.toLocaleString();\n popupEl.appendChild(val);\n }\n m.bindPopup(popupEl);\n m.on('click', () => clickRef.current(marker));\n }\n }\n layer.addTo(map);\n\n // Only (re)frame the view when the framing inputs actually change — otherwise\n // a data-prop reference change (e.g. a refetch returning identical markers)\n // would discard the user's current pan/zoom.\n const frameSig = JSON.stringify({\n m: markers.map((mk) => [mk.lat, mk.lng]),\n c: center ? [center.lat, center.lng] : null,\n z: zoom ?? null,\n fc: fallbackCenter ? [fallbackCenter.lat, fallbackCenter.lng] : null,\n fz: fallbackZoom ?? null,\n g: geoJson ? regionValues.size : 0,\n });\n if (frameSig !== lastFrameSigRef.current) {\n lastFrameSigRef.current = frameSig;\n // Framing priority: data-payload center → frame the markers → frame the\n // choropleth regions → config fallback center → zoom only → world view.\n // Markers/regions win over the config default so a palette-created map frames\n // its data instead of {0,0}.\n if (center) {\n map.setView([center.lat, center.lng], zoom ?? map.getZoom());\n } else if (!markers.length && geoLayer) {\n const b = geoLayer.getBounds();\n if (b.isValid()) map.fitBounds(b, { padding: [24, 24], maxZoom: 12 });\n } else if (markers.length === 1) {\n map.setView([markers[0].lat, markers[0].lng], zoom ?? 8);\n } else if (markers.length > 1) {\n const bounds = L.latLngBounds(markers.map((m) => [m.lat, m.lng] as [number, number]));\n map.fitBounds(bounds, { padding: [32, 32], maxZoom: 12 });\n } else if (fallbackCenter) {\n map.setView([fallbackCenter.lat, fallbackCenter.lng], zoom ?? fallbackZoom ?? map.getZoom());\n } else if (isFiniteNumber(zoom ?? fallbackZoom)) {\n map.setZoom((zoom ?? fallbackZoom) as number);\n }\n }\n\n const resize = window.setTimeout(() => map.invalidateSize(), 0);\n\n return () => {\n window.clearTimeout(resize);\n layer.remove();\n };\n }, [markers, center, zoom, fallbackCenter, fallbackZoom, showMarkers, geoJson, regionValues, regionIdField]);\n\n return (\n <div className=\"relative h-full w-full overflow-hidden rounded-lg bg-bg-muted\">\n <div ref={containerRef} className=\"h-full w-full\" />\n\n {status !== 'error' && markers.length === 0 && !hasChoropleth && (\n <div className=\"pointer-events-none absolute inset-0 z-[500] flex items-center justify-center bg-bg-muted/70 text-sm text-text-secondary\">\n <div className=\"text-center\">\n <svg\n className=\"mx-auto mb-2 h-12 w-12 text-text-tertiary\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z\"\n />\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M15 11a3 3 0 11-6 0 3 3 0 016 0z\"\n />\n </svg>\n <p>No map data</p>\n </div>\n </div>\n )}\n\n {status === 'error' && (\n <div className=\"absolute inset-0 z-[500] flex items-center justify-center bg-bg-muted px-4 text-center text-sm text-text-secondary\">\n The map needs an internet connection and couldn’t load.\n </div>\n )}\n </div>\n );\n});\n\nexport default MapWidget;\n"],"mappings":";;;;AAqEA,IAAM,IAAc,oDAEd,IAAkB,uDAEpB,IAA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../../../src/bigconsole/components/widgets/map-widget/MapWidget.tsx"],"sourcesContent":["/**\n * MapWidget Component\n *\n * Interactive geographic map (Leaflet + OpenStreetMap tiles) with data-bound\n * markers. Leaflet's stylesheet is loaded from a CDN at runtime (with SRI) because\n * the build-time MFE library bundle does not ship a component's CSS to the host\n * shell — consistent with the map being an inherently online feature (tiles).\n */\n\nimport { type FC, memo, useEffect, useMemo, useRef, useState } from 'react';\nimport L from 'leaflet';\nimport type { Widget } from '../../../types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MapWidgetProps {\n widget: Widget;\n data?: MapData;\n onClick?: (marker: MapMarker) => void;\n /** Drilldown handler - receives selected marker data */\n onDrilldown?: (selectedData: Record<string, unknown>) => void;\n}\n\nexport interface MapMarker {\n name: string;\n lat: number;\n lng: number;\n value?: number;\n popup?: string;\n color?: string;\n}\n\n/** Minimal GeoJSON FeatureCollection shape (we only read geometry + properties). */\nexport interface GeoJsonFeatureCollection {\n type: 'FeatureCollection';\n features: Array<{\n type: 'Feature';\n id?: string | number;\n properties?: Record<string, unknown> | null;\n geometry: unknown;\n }>;\n}\n\n/** A region value used to shade a choropleth (joined to a GeoJSON feature). */\nexport interface MapRegionValue {\n /** Join key — matched against the feature's id field. */\n id: string;\n /** Numeric value driving the fill intensity. */\n value: number;\n /** Optional display name for the popup. */\n name?: string;\n}\n\nexport interface MapData {\n center?: { lat: number; lng: number };\n zoom?: number;\n markers?: MapMarker[];\n /** GeoJSON regions for choropleth mode. */\n geoJson?: GeoJsonFeatureCollection;\n /** Per-region values joined to GeoJSON features for choropleth shading. */\n regions?: MapRegionValue[];\n}\n\n// ============================================================================\n// Leaflet CSS (runtime CDN injection)\n// ============================================================================\n\nconst LEAFLET_CSS = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';\n// SRI for leaflet@1.9.4/dist/leaflet.css (immutable versioned URL) — guards against a CDN compromise.\nconst LEAFLET_CSS_SRI = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';\n\nlet leafletCssRequested = false;\n\nfunction ensureLeafletCss(): void {\n // Module-level guard in addition to the DOM check so two MapWidgets mounting in\n // the same tick can't both append the <link> before either lands in the DOM.\n if (leafletCssRequested || document.getElementById('leaflet-css')) return;\n leafletCssRequested = true;\n const link = document.createElement('link');\n link.id = 'leaflet-css';\n link.rel = 'stylesheet';\n link.href = LEAFLET_CSS;\n link.integrity = LEAFLET_CSS_SRI;\n link.crossOrigin = 'anonymous';\n // Don't leak the current path (workspace/dashboard IDs) to the CDN.\n link.referrerPolicy = 'no-referrer';\n // Leaflet needs its stylesheet for correct tile/marker positioning. If the CDN\n // is unreachable or the SRI check fails the load is otherwise silent, so warn and\n // clear the guard/element to allow a later mount to retry.\n link.onerror = () => {\n console.warn('[bigconsole] Leaflet CSS failed to load; map styling may be broken.');\n leafletCssRequested = false;\n link.remove();\n };\n document.head.appendChild(link);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nconst DEFAULT_MARKER_COLOR = 'var(--color-chart-1, #3b82f6)';\n\n/**\n * Marker colours come from widget data and are interpolated into an inline\n * `style` attribute, so restrict them to a safe character set (hex / rgb() /\n * hsl() / css var() / named colours). Anything outside that — or containing\n * style-breaking characters — falls back to the default token colour.\n */\nfunction safeColor(color: unknown): string {\n // Marker data is untrusted: a parser can emit a non-string colour (e.g. a numeric\n // status code) that slips past the lat/lng filter, so guard the type before trim().\n if (typeof color !== 'string') return DEFAULT_MARKER_COLOR;\n const trimmed = color.trim();\n if (trimmed.length > 64) return DEFAULT_MARKER_COLOR;\n if (/[;{}<>\"'\\\\]/.test(trimmed)) return DEFAULT_MARKER_COLOR;\n // Block `url()` so a marker colour can't smuggle an exfiltration beacon\n // (e.g. `url(//evil.com/pixel)`) through the otherwise-permissive char set.\n if (/\\burl\\s*\\(/i.test(trimmed)) return DEFAULT_MARKER_COLOR;\n // Allow `_` (custom-property names) and `/` (modern `rgb(r g b / a)` syntax);\n // the dangerous-char guard above still blocks anything that could break out of\n // the inline style.\n if (!/^[#a-zA-Z0-9(),.%/_\\s-]+$/.test(trimmed)) return DEFAULT_MARKER_COLOR;\n return trimmed;\n}\n\nfunction isFiniteNumber(v: unknown): v is number {\n return typeof v === 'number' && Number.isFinite(v);\n}\n\n/**\n * Theme-safe cold→hot ramp for the heat-point layer: normalized intensity\n * (0–1) → info → warning → error status tokens, returned as `var()` refs.\n *\n * We deliberately pass the `var()` reference (not a resolved color): the map\n * uses Leaflet's default SVG renderer, where `fill` participates in the CSS\n * cascade, so the tokens resolve correctly AND stay live across theme toggles\n * (a resolved concrete color would go stale until the next data refresh). This\n * also matches the choropleth layer and avoids any per-marker `getComputedStyle`\n * lookup. (If the map ever opts into `preferCanvas`, pre-resolve these instead.)\n */\nfunction heatColor(norm: number): string {\n if (norm >= 0.66) return 'var(--color-status-error)';\n if (norm >= 0.33) return 'var(--color-status-warning)';\n return 'var(--color-status-info)';\n}\n\n/**\n * Build a marker/region popup as DOM (a bold title + optional formatted value).\n * Uses textContent — never an HTML string — so marker-supplied text can't be\n * interpreted as markup. Shared by the pin and heat-point branches.\n */\nfunction buildMarkerPopup(marker: MapMarker): HTMLDivElement {\n const popupEl = document.createElement('div');\n const title = document.createElement('div');\n title.style.fontWeight = '600';\n title.textContent = marker.popup || marker.name || 'Location';\n popupEl.appendChild(title);\n if (isFiniteNumber(marker.value)) {\n const val = document.createElement('div');\n val.textContent = marker.value.toLocaleString();\n popupEl.appendChild(val);\n }\n return popupEl;\n}\n\n/**\n * Normalize the bound widget data into markers + optional center/zoom. Accepts\n * the documented `{ markers, center, zoom }` shape, or a bare array of markers\n * (parser output), and drops any entry without valid coordinates.\n */\ninterface NormalizedMapData {\n markers: MapMarker[];\n /** Center explicitly supplied by the data payload — wins over markers. */\n center?: { lat: number; lng: number };\n /** Zoom explicitly supplied by the data payload. */\n zoom?: number;\n /** Center from widget config — a static fallback used only when there are no markers. */\n fallbackCenter?: { lat: number; lng: number };\n /** Zoom from widget config — fallback for the no-marker case. */\n fallbackZoom?: number;\n /** GeoJSON for choropleth mode. */\n geoJson?: GeoJsonFeatureCollection;\n /** region id → { value, name } map for choropleth shading. */\n regionValues: Map<string, { value: number; name?: string }>;\n}\n\nfunction asLatLng(v: unknown): { lat: number; lng: number } | undefined {\n const c = v as { lat?: unknown; lng?: unknown } | undefined;\n return c && isFiniteNumber(c.lat) && isFiniteNumber(c.lng) ? { lat: c.lat, lng: c.lng } : undefined;\n}\n\nfunction normalizeMapData(data: MapData | MapMarker[] | undefined, config: Record<string, unknown>): NormalizedMapData {\n // The widget may be handed either the documented { markers, center, zoom } shape\n // or a bare marker array (parser output); narrow once so the rest is type-safe.\n const payload: MapData | undefined = Array.isArray(data) ? undefined : data;\n const rawMarkers: unknown = Array.isArray(data) ? data : data?.markers;\n const markers: MapMarker[] = Array.isArray(rawMarkers)\n ? (rawMarkers as MapMarker[]).filter((m) => m && isFiniteNumber(m.lat) && isFiniteNumber(m.lng))\n : [];\n\n // Choropleth inputs: GeoJSON (from data payload or config) + a region→value join.\n const geoJson = (payload?.geoJson ?? (config.geoJson as GeoJsonFeatureCollection | undefined)) || undefined;\n const regionIdField = (config.regionIdField as string) || 'id';\n const regionValues = new Map<string, { value: number; name?: string }>();\n const rawRegions: unknown = payload?.regions ?? config.regions;\n if (Array.isArray(rawRegions)) {\n for (const r of rawRegions as Array<Record<string, unknown>>) {\n if (!r) continue;\n const id = r[regionIdField] ?? r.id ?? r.region ?? r.code;\n const value = r.value ?? r.count ?? r.total;\n if (id != null && isFiniteNumber(value)) {\n regionValues.set(String(id), { value, name: typeof r.name === 'string' ? r.name : undefined });\n }\n }\n }\n\n // Data-payload center/zoom are an explicit intent and win over markers. Config\n // center/zoom (e.g. the WidgetRegistry default of {0,0}/2) are only a static\n // fallback for marker-less maps — otherwise that default would pin every marker\n // dataset to the world view instead of framing the markers.\n return {\n markers,\n center: asLatLng(payload?.center),\n zoom: isFiniteNumber(payload?.zoom) ? payload?.zoom : undefined,\n fallbackCenter: asLatLng(config.center),\n fallbackZoom: isFiniteNumber(config.zoom) ? (config.zoom as number) : undefined,\n geoJson: geoJson && Array.isArray(geoJson.features) ? geoJson : undefined,\n regionValues,\n };\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const MapWidget: FC<MapWidgetProps> = memo(function MapWidget({ widget, data, onClick, onDrilldown }) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<L.Map | null>(null);\n // Signature of the last view we auto-framed to; lets us re-render markers on\n // every data change without snapping the viewport back when the framing\n // inputs (coords/center/zoom) are unchanged — e.g. a refetch of identical data.\n const lastFrameSigRef = useRef<string | null>(null);\n const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');\n\n const config = useMemo(() => (widget?.config ?? {}) as Record<string, unknown>, [widget?.config]);\n const showMarkers = config.showMarkers !== false;\n // Heat-point density mode: render weighted, translucent circles whose overlap\n // accumulates into a heat-like surface (dependency-free — no leaflet.heat).\n const heatMode = config.mapMode === 'heat';\n const regionIdField = (config.regionIdField as string) || 'id';\n const { markers, center, zoom, fallbackCenter, fallbackZoom, geoJson, regionValues } = useMemo(\n () => normalizeMapData(data, config),\n [data, config]\n );\n const hasChoropleth = Boolean(geoJson && regionValues.size > 0);\n\n // Keep the latest click handler in a ref so marker bindings don't need rebinding.\n // Assign in an effect (not during render) per the React 19 useRef guidance.\n const clickRef = useRef<(marker: MapMarker) => void>(() => undefined);\n useEffect(() => {\n clickRef.current = (marker: MapMarker) => {\n if (onDrilldown) onDrilldown(marker as unknown as Record<string, unknown>);\n else if (onClick) onClick(marker);\n };\n }, [onClick, onDrilldown]);\n\n // Initialise the map once.\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return undefined;\n ensureLeafletCss();\n\n let map: L.Map;\n try {\n map = L.map(el, { center: [20, 0], zoom: 2, scrollWheelZoom: true, attributionControl: true });\n const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: '© OpenStreetMap contributors',\n maxZoom: 18,\n });\n // Leaflet reports tile failures asynchronously, so addTo() won't throw when\n // tiles are blocked/offline. Surface the error overlay only if a tile errors\n // before any tile has loaded (true offline/blocked), tolerating the odd\n // transient miss once the base map is up.\n let anyTileLoaded = false;\n tiles.on('tileload', () => {\n anyTileLoaded = true;\n // Recover if an early tile miss had shown the offline overlay — a flaky\n // connection that later succeeds shouldn't stay hidden behind it.\n setStatus((s) => (s === 'error' ? 'ready' : s));\n });\n tiles.on('tileerror', () => {\n if (!anyTileLoaded) setStatus('error');\n });\n tiles.addTo(map);\n mapRef.current = map;\n // Fresh map ⇒ force the next marker effect to (re)frame it. Without this the\n // frame-signature ref would survive a remount (e.g. React StrictMode's\n // double-invoke) and the new map would stay stuck at this init view.\n lastFrameSigRef.current = null;\n setStatus('ready');\n } catch {\n setStatus('error');\n return undefined;\n }\n\n // Widgets live in a resizable grid; keep tiles correct as the box changes.\n const ro =\n typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => mapRef.current?.invalidateSize()) : undefined;\n ro?.observe(el);\n const t = window.setTimeout(() => map.invalidateSize(), 80);\n\n return () => {\n window.clearTimeout(t);\n ro?.disconnect();\n map.remove();\n mapRef.current = null;\n };\n }, []);\n\n // Render markers + frame the view whenever the data changes.\n useEffect(() => {\n const map = mapRef.current;\n if (!map) return undefined;\n\n const layer = L.layerGroup();\n\n // Choropleth: shade GeoJSON regions by a single-hue intensity ramp (the\n // semantic `info` token at varying opacity) joined on the region id field.\n let geoLayer: L.GeoJSON | null = null;\n if (geoJson && regionValues.size > 0) {\n const vals = Array.from(regionValues.values()).map((v) => v.value);\n const min = Math.min(...vals);\n const max = Math.max(...vals);\n const span = max - min || 1;\n const FILL = 'var(--color-status-info, #3b82f6)';\n\n const lookup = (feature: { id?: string | number; properties?: Record<string, unknown> | null }) => {\n const props = feature.properties ?? {};\n const joinId = feature.id ?? props[regionIdField] ?? props.id ?? props.code;\n return joinId != null ? regionValues.get(String(joinId)) : undefined;\n };\n\n geoLayer = L.geoJSON(geoJson as unknown as Parameters<typeof L.geoJSON>[0], {\n style: (feature) => {\n const hit = feature ? lookup(feature) : undefined;\n const norm = hit ? (hit.value - min) / span : 0;\n return {\n fillColor: FILL,\n fillOpacity: hit ? 0.2 + norm * 0.65 : 0.05,\n color: 'var(--color-border-default, #cbd5e1)',\n weight: 1,\n };\n },\n onEachFeature: (feature, lyr) => {\n const hit = lookup(feature);\n const name =\n hit?.name ??\n (typeof feature.properties?.name === 'string' ? (feature.properties.name as string) : undefined) ??\n String(feature.id ?? '');\n const popupEl = document.createElement('div');\n const title = document.createElement('div');\n title.style.fontWeight = '600';\n title.textContent = name || 'Region';\n popupEl.appendChild(title);\n if (hit) {\n const val = document.createElement('div');\n val.textContent = hit.value.toLocaleString();\n popupEl.appendChild(val);\n }\n lyr.bindPopup(popupEl);\n lyr.on('click', () => clickRef.current({ name, lat: NaN, lng: NaN, value: hit?.value } as MapMarker));\n },\n });\n geoLayer.addTo(layer);\n }\n\n if (showMarkers && heatMode) {\n // Heat-point layer: translucent weighted circles, sized + colored by value.\n const weights = markers.map((mk) => (isFiniteNumber(mk.value) ? mk.value : 1));\n // reduce, not Math.min(...spread) — spreading a large array as args can\n // blow the call-stack (RangeError) for big datasets.\n const minW = weights.reduce((a, b) => Math.min(a, b), Infinity);\n const maxW = weights.reduce((a, b) => Math.max(a, b), -Infinity);\n const spanW = maxW - minW || 1;\n markers.forEach((marker, i) => {\n const norm = (weights[i] - minW) / spanW;\n const circle = L.circleMarker([marker.lat, marker.lng], {\n radius: 10 + norm * 22,\n fillColor: heatColor(norm),\n // Both radius and opacity ramp with intensity for a truer density look.\n fillOpacity: 0.25 + norm * 0.35,\n stroke: false,\n }).addTo(layer);\n circle.bindPopup(buildMarkerPopup(marker));\n circle.on('click', () => clickRef.current(marker));\n });\n } else if (showMarkers) {\n for (const marker of markers) {\n // Build the pin as a DOM element (not an HTML string) so the marker colour\n // is assigned via the style API and can never be interpreted as markup —\n // defense-in-depth alongside safeColor().\n const pin = document.createElement('div');\n Object.assign(pin.style, {\n width: '14px',\n height: '14px',\n borderRadius: '50% 50% 50% 0',\n transform: 'rotate(-45deg)',\n background: safeColor(marker.color),\n border: '2px solid #fff',\n boxShadow: '0 1px 4px rgba(0,0,0,.4)',\n });\n const icon = L.divIcon({\n className: 'bc-map-marker',\n html: pin,\n iconSize: [14, 14],\n iconAnchor: [7, 14],\n });\n const m = L.marker([marker.lat, marker.lng], { icon }).addTo(layer);\n m.bindPopup(buildMarkerPopup(marker));\n m.on('click', () => clickRef.current(marker));\n }\n }\n layer.addTo(map);\n\n // Only (re)frame the view when the framing inputs actually change — otherwise\n // a data-prop reference change (e.g. a refetch returning identical markers)\n // would discard the user's current pan/zoom.\n const frameSig = JSON.stringify({\n m: markers.map((mk) => [mk.lat, mk.lng]),\n c: center ? [center.lat, center.lng] : null,\n z: zoom ?? null,\n fc: fallbackCenter ? [fallbackCenter.lat, fallbackCenter.lng] : null,\n fz: fallbackZoom ?? null,\n g: geoJson ? regionValues.size : 0,\n });\n if (frameSig !== lastFrameSigRef.current) {\n lastFrameSigRef.current = frameSig;\n // Framing priority: data-payload center → frame the markers → frame the\n // choropleth regions → config fallback center → zoom only → world view.\n // Markers/regions win over the config default so a palette-created map frames\n // its data instead of {0,0}.\n if (center) {\n map.setView([center.lat, center.lng], zoom ?? map.getZoom());\n } else if (!markers.length && geoLayer) {\n const b = geoLayer.getBounds();\n if (b.isValid()) map.fitBounds(b, { padding: [24, 24], maxZoom: 12 });\n } else if (markers.length === 1) {\n map.setView([markers[0].lat, markers[0].lng], zoom ?? 8);\n } else if (markers.length > 1) {\n const bounds = L.latLngBounds(markers.map((m) => [m.lat, m.lng] as [number, number]));\n map.fitBounds(bounds, { padding: [32, 32], maxZoom: 12 });\n } else if (fallbackCenter) {\n map.setView([fallbackCenter.lat, fallbackCenter.lng], zoom ?? fallbackZoom ?? map.getZoom());\n } else if (isFiniteNumber(zoom ?? fallbackZoom)) {\n map.setZoom((zoom ?? fallbackZoom) as number);\n }\n }\n\n const resize = window.setTimeout(() => map.invalidateSize(), 0);\n\n return () => {\n window.clearTimeout(resize);\n layer.remove();\n };\n }, [\n markers,\n center,\n zoom,\n fallbackCenter,\n fallbackZoom,\n showMarkers,\n heatMode,\n geoJson,\n regionValues,\n regionIdField,\n ]);\n\n return (\n <div className=\"relative h-full w-full overflow-hidden rounded-lg bg-bg-muted\">\n <div ref={containerRef} className=\"h-full w-full\" />\n\n {status !== 'error' && markers.length === 0 && !hasChoropleth && (\n <div className=\"pointer-events-none absolute inset-0 z-[500] flex items-center justify-center bg-bg-muted/70 text-sm text-text-secondary\">\n <div className=\"text-center\">\n <svg\n className=\"mx-auto mb-2 h-12 w-12 text-text-tertiary\"\n fill=\"none\"\n stroke=\"currentColor\"\n viewBox=\"0 0 24 24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z\"\n />\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M15 11a3 3 0 11-6 0 3 3 0 016 0z\"\n />\n </svg>\n <p>No map data</p>\n </div>\n </div>\n )}\n\n {status === 'error' && (\n <div className=\"absolute inset-0 z-[500] flex items-center justify-center bg-bg-muted px-4 text-center text-sm text-text-secondary\">\n The map needs an internet connection and couldn’t load.\n </div>\n )}\n </div>\n );\n});\n\nexport default MapWidget;\n"],"mappings":";;;;AAqEA,IAAM,IAAc,oDAEd,IAAkB,uDAEpB,IAAsB;AAE1B,SAAS,IAAyB;AAGhC,KAAI,KAAuB,SAAS,eAAe,cAAc,CAAE;AACnE,KAAsB;CACtB,IAAM,IAAO,SAAS,cAAc,OAAO;AAgB3C,CAfA,EAAK,KAAK,eACV,EAAK,MAAM,cACX,EAAK,OAAO,GACZ,EAAK,YAAY,GACjB,EAAK,cAAc,aAEnB,EAAK,iBAAiB,eAItB,EAA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U;IAAkB,CAAA;GAEnD,MAAW,WAAW,EAAQ,WAAW,KAAK,CAAC,KAC9C,kBAAC,OAAD;IAAK,WAAU;cACb,kBAAC,OAAD;KAAK,WAAU;eAAf,CACE,kBAAC,OAAD;MACE,WAAU;MACV,MAAK;MACL,QAAO;MACP,SAAQ;gBAJV,CAME,kBAAC,QAAD;OACE,eAAc;OACd,gBAAe;OACf,aAAa;OACb,GAAE;OACF,CAAA,EACF,kBAAC,QAAD;OACE,eAAc;OACd,gBAAe;OACf,aAAa;OACb,GAAE;OACF,CAAA,CACE;SACN,kBAAC,KAAD,EAAA,UAAG,eAAe,CAAA,CACd;;IACF,CAAA;GAGP,MAAW,WACV,kBAAC,OAAD;IAAK,WAAU;cAAqH;IAE9H,CAAA;GAEJ;;EAER"}
@@ -1,9 +1,16 @@
1
1
  import { CONDITIONAL_ICON_PATHS as e, conditionalStyleToClassName as t, intentToCssVar as n, resolveConditionalStyle as r } from "../utils/conditionalFormat.js";
2
- import { memo as i } from "react";
3
- import { jsx as a, jsxs as o } from "react/jsx-runtime";
2
+ import i from "../metric-card/SparklineChart.js";
3
+ import { memo as a } from "react";
4
+ import { jsx as o, jsxs as s } from "react/jsx-runtime";
4
5
  //#region src/bigconsole/components/widgets/table/TableCell.tsx
5
- function s(e, t) {
6
- if (e == null) return /* @__PURE__ */ a("span", {
6
+ function c(e) {
7
+ if (!Array.isArray(e) || e.length === 0) return null;
8
+ let t = [];
9
+ for (let n of e) typeof n == "number" && Number.isFinite(n) ? t.push(n) : n && typeof n == "object" && typeof n.value == "number" && Number.isFinite(n.value) && t.push(n.value);
10
+ return t.length ? t : null;
11
+ }
12
+ function l(e, t) {
13
+ if (e == null) return /* @__PURE__ */ o("span", {
7
14
  className: "text-text-secondary",
8
15
  children: "—"
9
16
  });
@@ -23,7 +30,7 @@ function s(e, t) {
23
30
  return String(e);
24
31
  case "badge": {
25
32
  let n = String(e);
26
- return /* @__PURE__ */ a("span", {
33
+ return /* @__PURE__ */ o("span", {
27
34
  className: `
28
35
  inline-flex items-center
29
36
  px-2 py-0.5
@@ -34,61 +41,74 @@ function s(e, t) {
34
41
  children: n
35
42
  });
36
43
  }
37
- case "link": return /* @__PURE__ */ a("span", {
44
+ case "link": return /* @__PURE__ */ o("span", {
38
45
  className: "text-action-primary-bg hover:underline cursor-pointer",
39
46
  children: String(e)
40
47
  });
41
48
  default: return String(e);
42
49
  }
43
50
  }
44
- var c = i(function({ value: i, column: c, format: l, rowData: u, conditionalRules: d, dataBarMax: f, stickyLeft: p, onClick: m }) {
45
- let h = r(i, d, u), g = t(h), _ = p != null, v = h?.dataBar && typeof i == "number" && f && f > 0 ? Math.max(0, Math.min(100, Math.abs(i) / f * 100)) : null;
46
- return /* @__PURE__ */ o("td", {
51
+ var u = a(function({ value: a, column: u, format: d, rowData: f, conditionalRules: p, dataBarMax: m, stickyLeft: h, cellChart: g, onClick: _ }) {
52
+ let v = r(a, p, f), y = t(v), b = h != null, x = g === "sparkline" ? c(a) : null, S = x ? x.reduce((e, t) => Math.min(e, t), Infinity) : 0, C = x ? x.reduce((e, t) => Math.max(e, t), -Infinity) : 0, w = v?.dataBar && typeof a == "number" && m && m > 0 ? Math.max(0, Math.min(100, Math.abs(a) / m * 100)) : null;
53
+ return /* @__PURE__ */ s("td", {
47
54
  className: `
48
55
  relative px-4 py-3
49
56
  text-sm text-text-primary
50
57
  border-b border-border-default
51
- ${c.align === "center" ? "text-center" : ""}
52
- ${c.align === "right" ? "text-right" : "text-left"}
53
- ${m ? "cursor-pointer hover:text-action-primary-bg" : ""}
54
- ${_ ? "sticky z-10 bg-bg-surface" : ""}
55
- ${g}
58
+ ${u.align === "center" ? "text-center" : ""}
59
+ ${u.align === "right" ? "text-right" : "text-left"}
60
+ ${_ ? "cursor-pointer hover:text-action-primary-bg" : ""}
61
+ ${b ? "sticky z-10 bg-bg-surface" : ""}
62
+ ${y}
56
63
  `,
57
- style: _ ? {
58
- left: p,
59
- width: c.width
64
+ style: b ? {
65
+ left: h,
66
+ width: u.width
60
67
  } : void 0,
61
- onClick: m,
62
- role: m ? "button" : void 0,
63
- tabIndex: m ? 0 : void 0,
68
+ onClick: _,
69
+ role: _ ? "button" : void 0,
70
+ tabIndex: _ ? 0 : void 0,
64
71
  onKeyDown: (e) => {
65
- m && (e.key === "Enter" || e.key === " ") && (e.preventDefault(), m());
72
+ _ && (e.key === "Enter" || e.key === " ") && (e.preventDefault(), _());
66
73
  },
67
- children: [v != null && /* @__PURE__ */ a("span", {
74
+ children: [w != null && /* @__PURE__ */ o("span", {
68
75
  "aria-hidden": "true",
69
76
  className: "absolute inset-y-1 left-1 rounded-sm opacity-20 pointer-events-none",
70
77
  style: {
71
- width: `calc(${v}% - 0.5rem)`,
72
- backgroundColor: n(h?.dataBarColor ?? "info")
78
+ width: `calc(${w}% - 0.5rem)`,
79
+ backgroundColor: n(v?.dataBarColor ?? "info")
73
80
  }
74
- }), /* @__PURE__ */ o("span", {
81
+ }), x && x.length >= 2 ? /* @__PURE__ */ o("span", {
82
+ className: "relative inline-flex items-center",
83
+ role: "img",
84
+ "aria-label": `Sparkline, ${x.length} points, ${S.toLocaleString()} to ${C.toLocaleString()}`,
85
+ children: /* @__PURE__ */ o(i, {
86
+ data: x.map((e) => ({ value: e })),
87
+ width: 96,
88
+ height: 28,
89
+ color: "primary"
90
+ })
91
+ }) : x && x.length === 1 ? /* @__PURE__ */ o("span", {
92
+ className: "relative inline-flex items-center",
93
+ children: l(x[0], d)
94
+ }) : /* @__PURE__ */ s("span", {
75
95
  className: "relative inline-flex items-center gap-1.5",
76
- children: [h?.icon && /* @__PURE__ */ a("svg", {
96
+ children: [v?.icon && /* @__PURE__ */ o("svg", {
77
97
  className: "w-3.5 h-3.5 shrink-0",
78
98
  fill: "none",
79
99
  stroke: "currentColor",
80
100
  viewBox: "0 0 24 24",
81
- children: /* @__PURE__ */ a("path", {
101
+ children: /* @__PURE__ */ o("path", {
82
102
  strokeLinecap: "round",
83
103
  strokeLinejoin: "round",
84
104
  strokeWidth: 2,
85
- d: e[h.icon]
105
+ d: e[v.icon]
86
106
  })
87
- }), s(i, l)]
107
+ }), l(a, d)]
88
108
  })]
89
109
  });
90
110
  });
91
111
  //#endregion
92
- export { c as default };
112
+ export { u as default };
93
113
 
94
114
  //# sourceMappingURL=TableCell.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"TableCell.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/table/TableCell.tsx"],"sourcesContent":["/**\n * TableCell Component\n *\n * Table cell with formatting and rendering options.\n */\n\nimport { type FC, memo, type ReactNode } from 'react';\nimport type { ColumnDefinition } from './TableHeader';\nimport {\n type ConditionalRule,\n resolveConditionalStyle,\n conditionalStyleToClassName,\n intentToCssVar,\n CONDITIONAL_ICON_PATHS,\n} from '../utils/conditionalFormat';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type CellFormat = 'text' | 'number' | 'currency' | 'percentage' | 'date' | 'badge' | 'link';\n\nexport interface CellFormatConfig {\n /** Format type */\n type: CellFormat;\n /** Currency code for currency format */\n currency?: string;\n /** Date format options */\n dateOptions?: Intl.DateTimeFormatOptions;\n /** Badge color mapping (value -> color) */\n badgeColors?: Record<string, string>;\n /** Link URL pattern (use {value} as placeholder) */\n linkPattern?: string;\n}\n\nexport interface TableCellProps {\n /** Cell value */\n value: unknown;\n /** Column definition */\n column: ColumnDefinition;\n /** Format configuration */\n format?: CellFormatConfig;\n /** Row data for link patterns and conditional rule field lookups */\n rowData?: Record<string, unknown>;\n /** Conditional formatting rules to evaluate against this cell */\n conditionalRules?: ConditionalRule[];\n /** Max absolute value in this column, used to scale in-cell data bars */\n dataBarMax?: number;\n /** When set, freeze this cell sticky-left at the given px offset */\n stickyLeft?: number;\n /** Click handler */\n onClick?: () => void;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction formatValue(value: unknown, format?: CellFormatConfig): ReactNode {\n if (value === null || value === undefined) {\n return <span className=\"text-text-secondary\">—</span>;\n }\n\n const formatType = format?.type || 'text';\n\n switch (formatType) {\n case 'number':\n return typeof value === 'number' ? new Intl.NumberFormat('en-US').format(value) : String(value);\n\n case 'currency':\n return typeof value === 'number'\n ? new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: format?.currency || 'USD',\n }).format(value)\n : String(value);\n\n case 'percentage':\n return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : String(value);\n\n case 'date':\n if (value instanceof Date) {\n return new Intl.DateTimeFormat('en-US', format?.dateOptions || { dateStyle: 'medium' }).format(value);\n }\n if (typeof value === 'string' || typeof value === 'number') {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return new Intl.DateTimeFormat('en-US', format?.dateOptions || { dateStyle: 'medium' }).format(date);\n }\n }\n return String(value);\n\n case 'badge': {\n const stringValue = String(value);\n const badgeColor = format?.badgeColors?.[stringValue] || 'bg-bg-muted text-text-primary';\n return (\n <span\n className={`\n inline-flex items-center\n px-2 py-0.5\n text-xs font-medium\n rounded-full\n ${badgeColor}\n `}\n >\n {stringValue}\n </span>\n );\n }\n\n case 'link':\n return <span className=\"text-action-primary-bg hover:underline cursor-pointer\">{String(value)}</span>;\n\n case 'text':\n default:\n return String(value);\n }\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const TableCell: FC<TableCellProps> = memo(function TableCell({\n value,\n column,\n format,\n rowData,\n conditionalRules,\n dataBarMax,\n stickyLeft,\n onClick,\n}) {\n const cf = resolveConditionalStyle(value, conditionalRules, rowData);\n const cfClass = conditionalStyleToClassName(cf);\n const isFrozen = stickyLeft != null;\n\n // In-cell data bar width (0–100%) scaled against the column max.\n const dataBarWidth =\n cf?.dataBar && typeof value === 'number' && dataBarMax && dataBarMax > 0\n ? Math.max(0, Math.min(100, (Math.abs(value) / dataBarMax) * 100))\n : null;\n\n return (\n <td\n className={`\n relative px-4 py-3\n text-sm text-text-primary\n border-b border-border-default\n ${column.align === 'center' ? 'text-center' : ''}\n ${column.align === 'right' ? 'text-right' : 'text-left'}\n ${onClick ? 'cursor-pointer hover:text-action-primary-bg' : ''}\n ${isFrozen ? 'sticky z-10 bg-bg-surface' : ''}\n ${cfClass}\n `}\n style={isFrozen ? { left: stickyLeft, width: column.width } : undefined}\n onClick={onClick}\n role={onClick ? 'button' : undefined}\n tabIndex={onClick ? 0 : undefined}\n onKeyDown={(e) => {\n if (onClick && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n onClick();\n }\n }}\n >\n {dataBarWidth != null && (\n <span\n aria-hidden=\"true\"\n className=\"absolute inset-y-1 left-1 rounded-sm opacity-20 pointer-events-none\"\n style={{\n width: `calc(${dataBarWidth}% - 0.5rem)`,\n backgroundColor: intentToCssVar(cf?.dataBarColor ?? 'info'),\n }}\n />\n )}\n <span className=\"relative inline-flex items-center gap-1.5\">\n {cf?.icon && (\n <svg className=\"w-3.5 h-3.5 shrink-0\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d={CONDITIONAL_ICON_PATHS[cf.icon]} />\n </svg>\n )}\n {formatValue(value, format)}\n </span>\n </td>\n );\n});\n\nexport default TableCell;\n"],"mappings":";;;;AA0DA,SAAS,EAAY,GAAgB,GAAsC;AACzE,KAAI,KAAU,KACZ,QAAO,kBAAC,QAAD;EAAM,WAAU;YAAsB;EAAQ,CAAA;AAKvD,SAFmB,GAAQ,QAAQ,QAEnC;EACE,KAAK,SACH,QAAO,OAAO,KAAU,WAAW,IAAI,KAAK,aAAa,QAAQ,CAAC,OAAO,EAAM,GAAG,OAAO,EAAM;EAEjG,KAAK,WACH,QAAO,OAAO,KAAU,WACpB,IAAI,KAAK,aAAa,SAAS;GAC7B,OAAO;GACP,UAAU,GAAQ,YAAY;GAC/B,CAAC,CAAC,OAAO,EAAM,GAChB,OAAO,EAAM;EAEnB,KAAK,aACH,QAAO,OAAO,KAAU,WAAW,IAAI,IAAQ,KAAK,QAAQ,EAAE,CAAC,KAAK,OAAO,EAAM;EAEnF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AAU,IAAU,IAAI,KAAA;EACxB,YAAY,MAAM;AAChB,GAAI,MAAY,EAAE,QAAQ,WAAW,EAAE,QAAQ,SAC7C,EAAE,gBAAgB,EAClB,GAAS;;YAlBf,CAsBG,KAAgB,QACf,kBAAC,QAAD;GACE,eAAY;GACZ,WAAU;GACV,OAAO;IACL,OAAO,QAAQ,EAAa;IAC5B,iBAAiB,EAAe,GAAI,gBAAgB,OAAO;IAC5D;GACD,CAAA,EAEJ,kBAAC,QAAD;GAAM,WAAU;aAAhB,CACG,GAAI,QACH,kBAAC,OAAD;IAAK,WAAU;IAAuB,MAAK;IAAO,QAAO;IAAe,SAAQ;cAC9E,kBAAC,QAAD;KAAM,eAAc;KAAQ,gBAAe;KAAQ,aAAa;KAAG,GAAG,EAAuB,EAAG;KAAS,CAAA;IACrG,CAAA,EAEP,EAAY,GAAO,EAAO,CACtB;KACJ;;EAEP"}
1
+ {"version":3,"file":"TableCell.js","names":[],"sources":["../../../../../src/bigconsole/components/widgets/table/TableCell.tsx"],"sourcesContent":["/**\n * TableCell Component\n *\n * Table cell with formatting and rendering options.\n */\n\nimport { type FC, memo, type ReactNode } from 'react';\nimport type { ColumnDefinition } from './TableHeader';\nimport {\n type ConditionalRule,\n resolveConditionalStyle,\n conditionalStyleToClassName,\n intentToCssVar,\n CONDITIONAL_ICON_PATHS,\n} from '../utils/conditionalFormat';\nimport { SparklineChart } from '../metric-card/SparklineChart';\n\n/** In-cell mini-chart kinds. */\nexport type CellChart = 'sparkline';\n\n/**\n * Extract finite numeric values from a sparkline cell value (an array of raw\n * numbers or `{value}` objects). Non-finite values (NaN/Infinity) are rejected\n * in both forms. Returns null when the value isn't a usable numeric array — so\n * the caller can decide how to render: a chart (≥2 points), a single value\n * (1 point), or fall through to the default renderer.\n */\nfunction extractSparklineValues(value: unknown): number[] | null {\n if (!Array.isArray(value) || value.length === 0) return null;\n const nums: number[] = [];\n for (const item of value) {\n if (typeof item === 'number' && Number.isFinite(item)) {\n nums.push(item);\n } else if (\n item &&\n typeof item === 'object' &&\n typeof (item as { value?: unknown }).value === 'number' &&\n Number.isFinite((item as { value: number }).value)\n ) {\n nums.push((item as { value: number }).value);\n }\n }\n return nums.length ? nums : null;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type CellFormat = 'text' | 'number' | 'currency' | 'percentage' | 'date' | 'badge' | 'link';\n\nexport interface CellFormatConfig {\n /** Format type */\n type: CellFormat;\n /** Currency code for currency format */\n currency?: string;\n /** Date format options */\n dateOptions?: Intl.DateTimeFormatOptions;\n /** Badge color mapping (value -> color) */\n badgeColors?: Record<string, string>;\n /** Link URL pattern (use {value} as placeholder) */\n linkPattern?: string;\n}\n\nexport interface TableCellProps {\n /** Cell value */\n value: unknown;\n /** Column definition */\n column: ColumnDefinition;\n /** Format configuration */\n format?: CellFormatConfig;\n /** Row data for link patterns and conditional rule field lookups */\n rowData?: Record<string, unknown>;\n /** Conditional formatting rules to evaluate against this cell */\n conditionalRules?: ConditionalRule[];\n /** Max absolute value in this column, used to scale in-cell data bars */\n dataBarMax?: number;\n /** When set, freeze this cell sticky-left at the given px offset */\n stickyLeft?: number;\n /** Render the cell as an in-cell mini chart (e.g. sparkline) instead of a value */\n cellChart?: CellChart;\n /** Click handler */\n onClick?: () => void;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction formatValue(value: unknown, format?: CellFormatConfig): ReactNode {\n if (value === null || value === undefined) {\n return <span className=\"text-text-secondary\">—</span>;\n }\n\n const formatType = format?.type || 'text';\n\n switch (formatType) {\n case 'number':\n return typeof value === 'number' ? new Intl.NumberFormat('en-US').format(value) : String(value);\n\n case 'currency':\n return typeof value === 'number'\n ? new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: format?.currency || 'USD',\n }).format(value)\n : String(value);\n\n case 'percentage':\n return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : String(value);\n\n case 'date':\n if (value instanceof Date) {\n return new Intl.DateTimeFormat('en-US', format?.dateOptions || { dateStyle: 'medium' }).format(value);\n }\n if (typeof value === 'string' || typeof value === 'number') {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return new Intl.DateTimeFormat('en-US', format?.dateOptions || { dateStyle: 'medium' }).format(date);\n }\n }\n return String(value);\n\n case 'badge': {\n const stringValue = String(value);\n const badgeColor = format?.badgeColors?.[stringValue] || 'bg-bg-muted text-text-primary';\n return (\n <span\n className={`\n inline-flex items-center\n px-2 py-0.5\n text-xs font-medium\n rounded-full\n ${badgeColor}\n `}\n >\n {stringValue}\n </span>\n );\n }\n\n case 'link':\n return <span className=\"text-action-primary-bg hover:underline cursor-pointer\">{String(value)}</span>;\n\n case 'text':\n default:\n return String(value);\n }\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nexport const TableCell: FC<TableCellProps> = memo(function TableCell({\n value,\n column,\n format,\n rowData,\n conditionalRules,\n dataBarMax,\n stickyLeft,\n cellChart,\n onClick,\n}) {\n const cf = resolveConditionalStyle(value, conditionalRules, rowData);\n const cfClass = conditionalStyleToClassName(cf);\n const isFrozen = stickyLeft != null;\n // In-cell sparkline: only when the column opts in and the value is numeric.\n const sparkValues = cellChart === 'sparkline' ? extractSparklineValues(value) : null;\n // Range for the sparkline's accessible label (reduce, not spread → no call-stack risk).\n const sparkMin = sparkValues ? sparkValues.reduce((a, b) => Math.min(a, b), Infinity) : 0;\n const sparkMax = sparkValues ? sparkValues.reduce((a, b) => Math.max(a, b), -Infinity) : 0;\n\n // In-cell data bar width (0–100%) scaled against the column max.\n const dataBarWidth =\n cf?.dataBar && typeof value === 'number' && dataBarMax && dataBarMax > 0\n ? Math.max(0, Math.min(100, (Math.abs(value) / dataBarMax) * 100))\n : null;\n\n return (\n <td\n className={`\n relative px-4 py-3\n text-sm text-text-primary\n border-b border-border-default\n ${column.align === 'center' ? 'text-center' : ''}\n ${column.align === 'right' ? 'text-right' : 'text-left'}\n ${onClick ? 'cursor-pointer hover:text-action-primary-bg' : ''}\n ${isFrozen ? 'sticky z-10 bg-bg-surface' : ''}\n ${cfClass}\n `}\n style={isFrozen ? { left: stickyLeft, width: column.width } : undefined}\n onClick={onClick}\n role={onClick ? 'button' : undefined}\n tabIndex={onClick ? 0 : undefined}\n onKeyDown={(e) => {\n if (onClick && (e.key === 'Enter' || e.key === ' ')) {\n e.preventDefault();\n onClick();\n }\n }}\n >\n {dataBarWidth != null && (\n <span\n aria-hidden=\"true\"\n className=\"absolute inset-y-1 left-1 rounded-sm opacity-20 pointer-events-none\"\n style={{\n width: `calc(${dataBarWidth}% - 0.5rem)`,\n backgroundColor: intentToCssVar(cf?.dataBarColor ?? 'info'),\n }}\n />\n )}\n {sparkValues && sparkValues.length >= 2 ? (\n // ≥2 points → draw the sparkline (SparklineChart needs >1 to avoid a\n // divide-by-zero). Labelled for screen readers since the SVG is decorative.\n <span\n className=\"relative inline-flex items-center\"\n role=\"img\"\n aria-label={`Sparkline, ${sparkValues.length} points, ${sparkMin.toLocaleString()} to ${sparkMax.toLocaleString()}`}\n >\n <SparklineChart data={sparkValues.map((v) => ({ value: v }))} width={96} height={28} color=\"primary\" />\n </span>\n ) : sparkValues && sparkValues.length === 1 ? (\n // A single numeric point can't be charted — render the value itself\n // (not the raw array, which would stringify to \"[object Object]\").\n <span className=\"relative inline-flex items-center\">{formatValue(sparkValues[0], format)}</span>\n ) : (\n <span className=\"relative inline-flex items-center gap-1.5\">\n {cf?.icon && (\n <svg className=\"w-3.5 h-3.5 shrink-0\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d={CONDITIONAL_ICON_PATHS[cf.icon]} />\n </svg>\n )}\n {formatValue(value, format)}\n </span>\n )}\n </td>\n );\n});\n\nexport default TableCell;\n"],"mappings":";;;;;AA2BA,SAAS,EAAuB,GAAiC;AAC/D,KAAI,CAAC,MAAM,QAAQ,EAAM,IAAI,EAAM,WAAW,EAAG,QAAO;CACxD,IAAM,IAAiB,EAAE;AACzB,MA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