Spaces:
Running
Running
Download src/utils/chartExport.ts from climateexploer/eurometeo: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/climateexploer/eurometeo/resolve/main/src/utils/chartExport.ts
- Command line
-
hf download hf://spaces/climateexploer/eurometeo/src/utils/chartExport.ts
-
curl -L -o chartExport.ts https://huggingface.co/spaces/climateexploer/eurometeo/resolve/main/src/utils/chartExport.ts
13.6 kB
| /** | |
| * chartExport.ts — Export any dashboard chart card as a self-contained branded PNG image. | |
| * | |
| * Works with both Recharts-generated SVGs and hand-crafted SVGs (e.g. WindRose). | |
| * Composes title, unit, station metadata, UTC date range, inline series legend, | |
| * and attribution footer using only native browser APIs. | |
| */ | |
| import { ChartLegendItem, WIND_ROSE_CLASSES } from "@/utils/chartHelpers"; | |
| /** CSS properties that must be inlined for SVG serialization to look correct */ | |
| const INLINE_STYLE_PROPS: (keyof CSSStyleDeclaration)[] = [ | |
| "fill", | |
| "stroke", | |
| "strokeWidth", | |
| "strokeDasharray", | |
| "strokeOpacity", | |
| "strokeLinecap", | |
| "strokeLinejoin", | |
| "fillOpacity", | |
| "opacity", | |
| "fontFamily", | |
| "fontSize", | |
| "fontWeight", | |
| "fontStyle", | |
| "textAnchor", | |
| "dominantBaseline", | |
| "color", | |
| "letterSpacing", | |
| "textDecoration", | |
| "visibility", | |
| "display", | |
| "clipPath", | |
| "filter", | |
| "transform", | |
| ]; | |
| /** Selectors for interactive Recharts chrome to strip from the export */ | |
| const STRIP_SELECTORS = [ | |
| ".recharts-tooltip-wrapper", | |
| ".recharts-active-dot", | |
| ".recharts-tooltip-cursor", | |
| "[class*='recharts-tooltip']", | |
| ".recharts-brush", | |
| ]; | |
| /** Sanitize a string for use in a filename */ | |
| function toKebab(s: string): string { | |
| return s | |
| .toLowerCase() | |
| .replace(/[^a-z0-9]+/g, "-") | |
| .replace(/^-|-$/g, ""); | |
| } | |
| /** Recursively inline computed CSS styles onto every element in the SVG clone */ | |
| function inlineStyles(original: Element, clone: Element): void { | |
| if (!(original instanceof HTMLElement || original instanceof SVGElement)) return; | |
| if (!(clone instanceof HTMLElement || clone instanceof SVGElement)) return; | |
| const computed = window.getComputedStyle(original); | |
| for (const prop of INLINE_STYLE_PROPS) { | |
| const value = computed[prop]; | |
| if (value && value !== "" && value !== "normal" && value !== "auto" && (value !== "none" || prop === "display")) { | |
| (clone as HTMLElement | SVGElement).style.setProperty(prop as string, value as string); | |
| } | |
| } | |
| const origChildren = original.children; | |
| const cloneChildren = clone.children; | |
| const len = Math.min(origChildren.length, cloneChildren.length); | |
| for (let i = 0; i < len; i++) { | |
| inlineStyles(origChildren[i], cloneChildren[i]); | |
| } | |
| } | |
| export interface ChartExportOptions { | |
| title: string; | |
| unit?: string; | |
| stationName?: string; | |
| stationId?: string; | |
| country?: string; | |
| dateRangeLabel?: string; | |
| legendItems?: ChartLegendItem[]; | |
| } | |
| function layoutLegendRows( | |
| ctx: CanvasRenderingContext2D, | |
| items: ChartLegendItem[], | |
| maxWidth: number | |
| ): ChartLegendItem[][] { | |
| if (items.length === 0) return []; | |
| ctx.font = "600 11px Inter, system-ui, -apple-system, sans-serif"; | |
| const rows: ChartLegendItem[][] = []; | |
| let currentRow: ChartLegendItem[] = []; | |
| let x = 0; | |
| for (const item of items) { | |
| const itemWidth = 18 + ctx.measureText(item.label).width + 16; | |
| if (currentRow.length > 0 && x + itemWidth > maxWidth) { | |
| rows.push(currentRow); | |
| currentRow = [item]; | |
| x = itemWidth; | |
| } else { | |
| currentRow.push(item); | |
| x += itemWidth; | |
| } | |
| } | |
| if (currentRow.length > 0) rows.push(currentRow); | |
| return rows; | |
| } | |
| function drawLegendSwatch( | |
| ctx: CanvasRenderingContext2D, | |
| item: ChartLegendItem, | |
| x: number, | |
| centerY: number | |
| ): void { | |
| ctx.save(); | |
| if (item.variant === "dot") { | |
| ctx.fillStyle = item.color; | |
| ctx.beginPath(); | |
| ctx.arc(x + 6, centerY, 4, 0, Math.PI * 2); | |
| ctx.fill(); | |
| } else if (item.variant === "dashed") { | |
| ctx.strokeStyle = item.color; | |
| ctx.lineWidth = 2; | |
| ctx.setLineDash([4, 3]); | |
| ctx.beginPath(); | |
| ctx.moveTo(x, centerY); | |
| ctx.lineTo(x + 13, centerY); | |
| ctx.stroke(); | |
| } else if (item.variant === "line") { | |
| ctx.fillStyle = item.color; | |
| ctx.fillRect(x, centerY - 1.5, 13, 3); | |
| } else { | |
| ctx.fillStyle = item.color; | |
| ctx.beginPath(); | |
| ctx.roundRect(x + 1, centerY - 5, 10, 10, 2); | |
| ctx.fill(); | |
| } | |
| ctx.restore(); | |
| } | |
| /** | |
| * Export a chart container element as a high-DPI PNG with title, metadata, legend, and branded footer. | |
| * | |
| * @param containerEl — the outer card `<div>` or `<figure>` wrapping the chart SVG | |
| * @param options — title, unit, station metadata, date range, and legend items | |
| */ | |
| export async function exportChartAsPng( | |
| containerEl: HTMLElement, | |
| options: ChartExportOptions | |
| ): Promise<void> { | |
| try { | |
| let svgOriginal: SVGSVGElement | null = | |
| containerEl.querySelector("svg.recharts-surface"); | |
| if (!svgOriginal) { | |
| const allSvgs = containerEl.querySelectorAll("svg"); | |
| let best: SVGSVGElement | null = null; | |
| let bestArea = 0; | |
| allSvgs.forEach((svg) => { | |
| if (svg.closest("button")) return; | |
| const w = svg.clientWidth || svg.width?.baseVal?.value || 0; | |
| const h = svg.clientHeight || svg.height?.baseVal?.value || 0; | |
| const area = w * h; | |
| if (area > bestArea) { | |
| bestArea = area; | |
| best = svg; | |
| } | |
| }); | |
| svgOriginal = best; | |
| } | |
| if (!svgOriginal) return; | |
| const isRecharts = svgOriginal.classList.contains("recharts-surface"); | |
| const vb = svgOriginal.viewBox?.baseVal; | |
| let origW = vb && vb.width > 0 ? vb.width : svgOriginal.width.baseVal.value || svgOriginal.clientWidth || 600; | |
| const origH = vb && vb.height > 0 ? vb.height : svgOriginal.height.baseVal.value || svgOriginal.clientHeight || 300; | |
| // Measure where the interactive Brush begins before removing it from the clone | |
| let plotH = origH; | |
| if (isRecharts) { | |
| const brushEl = svgOriginal.querySelector(".recharts-brush"); | |
| if (brushEl) { | |
| try { | |
| if ("getBBox" in brushEl) { | |
| const bbox = (brushEl as SVGGraphicsElement).getBBox(); | |
| if (Number.isFinite(bbox.y) && bbox.y > 100 && bbox.y < origH) { | |
| plotH = Math.ceil(bbox.y) + 4; | |
| } | |
| } | |
| } catch { | |
| plotH = Math.max(120, origH - 28); | |
| } | |
| } | |
| } | |
| const svgClone = svgOriginal.cloneNode(true) as SVGSVGElement; | |
| for (const sel of STRIP_SELECTORS) { | |
| svgClone.querySelectorAll(sel).forEach((el) => el.remove()); | |
| } | |
| inlineStyles(svgOriginal, svgClone); | |
| // For WindRose (non-Recharts SVG), embed the legend panel directly inside the expanded SVG canvas | |
| if (!isRecharts) { | |
| const fallbackLegend: ChartLegendItem[] = WIND_ROSE_CLASSES.map((c) => ({ | |
| label: c.label, | |
| color: c.color, | |
| variant: "bar", | |
| })); | |
| const roseLegend = options.legendItems && options.legendItems.length > 0 ? options.legendItems : fallbackLegend; | |
| const legendX = origW + 18; | |
| const legendW = 265; | |
| origW = origW + legendW + 24; | |
| svgClone.setAttribute("viewBox", `${vb ? vb.x : 0} ${vb ? vb.y : 0} ${origW} ${origH}`); | |
| svgClone.setAttribute("width", String(origW)); | |
| svgClone.setAttribute("height", String(origH)); | |
| const startY = Math.max(40, Math.round(origH / 2 - (roseLegend.length * 22) / 2)); | |
| const legendTitle = document.createElementNS("http://www.w3.org/2000/svg", "text"); | |
| legendTitle.setAttribute("x", String(legendX)); | |
| legendTitle.setAttribute("y", String(startY - 14)); | |
| legendTitle.setAttribute("font-family", "Inter, system-ui, -apple-system, sans-serif"); | |
| legendTitle.setAttribute("font-size", "10"); | |
| legendTitle.setAttribute("font-weight", "700"); | |
| legendTitle.setAttribute("fill", "#64748b"); | |
| legendTitle.setAttribute("letter-spacing", "0.05em"); | |
| legendTitle.textContent = "BEAUFORT WIND CLASSES"; | |
| svgClone.appendChild(legendTitle); | |
| roseLegend.forEach((item, i) => { | |
| const y = startY + i * 22; | |
| const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); | |
| rect.setAttribute("x", String(legendX)); | |
| rect.setAttribute("y", String(y)); | |
| rect.setAttribute("width", "12"); | |
| rect.setAttribute("height", "12"); | |
| rect.setAttribute("rx", "2"); | |
| rect.setAttribute("fill", item.color); | |
| svgClone.appendChild(rect); | |
| const text = document.createElementNS("http://www.w3.org/2000/svg", "text"); | |
| text.setAttribute("x", String(legendX + 18)); | |
| text.setAttribute("y", String(y + 10)); | |
| text.setAttribute("font-family", "Inter, system-ui, -apple-system, sans-serif"); | |
| text.setAttribute("font-size", "10.5"); | |
| text.setAttribute("font-weight", "500"); | |
| text.setAttribute("fill", "#334155"); | |
| text.textContent = item.label; | |
| svgClone.appendChild(text); | |
| }); | |
| } | |
| const serializer = new XMLSerializer(); | |
| const svgString = serializer.serializeToString(svgClone); | |
| const svgBlob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" }); | |
| const svgUrl = URL.createObjectURL(svgBlob); | |
| const padX = 18; | |
| const minCanvasW = Math.max(origW, 480); | |
| const scale = 2; | |
| const measureCanvas = document.createElement("canvas"); | |
| const measureCtx = measureCanvas.getContext("2d"); | |
| if (!measureCtx) { | |
| URL.revokeObjectURL(svgUrl); | |
| return; | |
| } | |
| const legendRows = isRecharts && options.legendItems && options.legendItems.length > 0 | |
| ? layoutLegendRows(measureCtx, options.legendItems, minCanvasW - padX * 2) | |
| : []; | |
| const locationParts = [ | |
| options.stationName, | |
| options.country, | |
| options.stationId ? `WIGOS ${options.stationId}` : undefined, | |
| ].filter(Boolean); | |
| const subtitleParts: string[] = []; | |
| if (locationParts.length > 0) subtitleParts.push(locationParts.join(", ")); | |
| if (options.dateRangeLabel) subtitleParts.push(options.dateRangeLabel); | |
| const subtitleText = subtitleParts.join(" · "); | |
| const titleH = 28; | |
| const subtitleH = subtitleText ? 18 : 0; | |
| const legendH = legendRows.length > 0 ? legendRows.length * 18 + 8 : 0; | |
| const headerH = 14 + titleH + subtitleH + legendH + 6; | |
| const footerH = 34; | |
| const totalH = headerH + plotH + footerH; | |
| const canvas = document.createElement("canvas"); | |
| canvas.width = minCanvasW * scale; | |
| canvas.height = totalH * scale; | |
| const ctx = canvas.getContext("2d"); | |
| if (!ctx) { | |
| URL.revokeObjectURL(svgUrl); | |
| return; | |
| } | |
| ctx.scale(scale, scale); | |
| ctx.fillStyle = "#ffffff"; | |
| ctx.fillRect(0, 0, minCanvasW, totalH); | |
| // Draw SVG centered horizontally when minCanvasW > origW | |
| const svgOffsetX = Math.max(0, Math.round((minCanvasW - origW) / 2)); | |
| const img = new Image(); | |
| img.crossOrigin = "anonymous"; | |
| await new Promise<void>((resolve, reject) => { | |
| img.onload = () => { | |
| ctx.drawImage(img, svgOffsetX, headerH, origW, origH); | |
| URL.revokeObjectURL(svgUrl); | |
| resolve(); | |
| }; | |
| img.onerror = () => { | |
| URL.revokeObjectURL(svgUrl); | |
| reject(new Error("Image load failed")); | |
| }; | |
| img.src = svgUrl; | |
| }); | |
| // Paint crisp Header Band (overwrites top area cleanly) | |
| ctx.fillStyle = "#ffffff"; | |
| ctx.fillRect(0, 0, minCanvasW, headerH); | |
| const headingText = options.unit | |
| ? `${options.title} (${options.unit})` | |
| : options.title; | |
| ctx.font = "700 15px Inter, system-ui, -apple-system, sans-serif"; | |
| ctx.fillStyle = "#0f172a"; | |
| ctx.textBaseline = "top"; | |
| ctx.fillText(headingText, padX, 14); | |
| let cursorY = 14 + titleH; | |
| if (subtitleText) { | |
| ctx.font = "500 11px Inter, system-ui, -apple-system, sans-serif"; | |
| ctx.fillStyle = "#64748b"; | |
| ctx.fillText(subtitleText, padX, cursorY); | |
| cursorY += subtitleH; | |
| } | |
| if (legendRows.length > 0) { | |
| cursorY += 4; | |
| for (const row of legendRows) { | |
| let cursorX = padX; | |
| const centerY = cursorY + 7; | |
| for (const item of row) { | |
| drawLegendSwatch(ctx, item, cursorX, centerY); | |
| ctx.font = "600 11px Inter, system-ui, -apple-system, sans-serif"; | |
| ctx.fillStyle = "#334155"; | |
| ctx.fillText(item.label, cursorX + 18, cursorY + 1); | |
| cursorX += 18 + ctx.measureText(item.label).width + 16; | |
| } | |
| cursorY += 18; | |
| } | |
| } | |
| ctx.strokeStyle = "#f1f5f9"; | |
| ctx.lineWidth = 1; | |
| ctx.beginPath(); | |
| ctx.moveTo(padX, headerH - 2); | |
| ctx.lineTo(minCanvasW - padX, headerH - 2); | |
| ctx.stroke(); | |
| // Paint opaque Footer Band at headerH + plotH (cleanly covers stripped brush region) | |
| const footerY = headerH + plotH; | |
| ctx.fillStyle = "#f8fafc"; | |
| ctx.fillRect(0, footerY, minCanvasW, footerH); | |
| ctx.strokeStyle = "#e2e8f0"; | |
| ctx.beginPath(); | |
| ctx.moveTo(0, footerY); | |
| ctx.lineTo(minCanvasW, footerY); | |
| ctx.stroke(); | |
| ctx.font = "500 11px Inter, system-ui, -apple-system, sans-serif"; | |
| ctx.fillStyle = "#64748b"; | |
| ctx.textAlign = "center"; | |
| ctx.textBaseline = "middle"; | |
| ctx.fillText( | |
| "Source: WMO / EUMETNET MeteoGate · climateexplorer.app", | |
| minCanvasW / 2, | |
| footerY + footerH / 2 | |
| ); | |
| const stationSlug = options.stationName ? `_${toKebab(options.stationName)}` : ""; | |
| const filename = `${toKebab(options.title)}${stationSlug}.png`; | |
| await new Promise<void>((resolve) => { | |
| canvas.toBlob((blob) => { | |
| if (!blob) { | |
| resolve(); | |
| return; | |
| } | |
| const blobUrl = URL.createObjectURL(blob); | |
| const a = document.createElement("a"); | |
| a.href = blobUrl; | |
| a.download = filename; | |
| document.body.appendChild(a); | |
| a.click(); | |
| document.body.removeChild(a); | |
| URL.revokeObjectURL(blobUrl); | |
| resolve(); | |
| }, "image/png"); | |
| }); | |
| } catch { | |
| // Silent graceful failure — no alerts or errors shown to user | |
| } | |
| } | |