File size: 13,629 Bytes
ce3be46
2be44dc
ce3be46
 
2be44dc
 
ce3be46
 
2be44dc
 
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be44dc
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f390ea
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
2be44dc
ce3be46
2be44dc
ce3be46
2be44dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce3be46
 
 
2be44dc
ce3be46
2be44dc
 
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
 
2be44dc
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
2be44dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce3be46
 
 
 
 
 
 
 
2be44dc
ce3be46
2be44dc
 
 
 
 
 
 
 
 
 
ce3be46
 
 
 
2be44dc
ce3be46
 
2be44dc
ce3be46
 
 
2be44dc
ce3be46
2be44dc
ce3be46
 
2be44dc
 
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
2be44dc
ce3be46
2be44dc
ce3be46
 
 
 
 
 
 
 
 
 
2be44dc
 
ce3be46
2be44dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce3be46
2be44dc
 
ce3be46
2be44dc
 
 
 
ce3be46
2be44dc
ce3be46
2be44dc
 
 
 
ce3be46
 
 
 
 
 
2be44dc
ce3be46
 
 
 
 
 
 
 
 
 
2be44dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce3be46
 
 
 
 
2be44dc
 
 
 
ce3be46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/**
 * 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
  }
}