|
| 1 | +/** |
| 2 | + * Utility functions for SVG dimension extraction |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * Extracts dimensions from SVG content by parsing viewBox or width/height attributes |
| 7 | + * @param svgContent - The SVG content as a string |
| 8 | + * @returns Object containing width and height |
| 9 | + */ |
| 10 | +export function extractSvgDimensions(svgContent: string): { width: number; height: number } { |
| 11 | + // Try to get dimensions from viewBox first |
| 12 | + const viewBoxMatch = svgContent.match(/viewBox=['"]([^'"]*)['"]/); |
| 13 | + if (viewBoxMatch) { |
| 14 | + const [minX, minY, width, height] = viewBoxMatch[1].split(/\s+/).map(Number); |
| 15 | + // Check that both width and height are valid numbers (not NaN and not undefined) |
| 16 | + if (!Number.isNaN(width) && !Number.isNaN(height) && width !== undefined && height !== undefined) { |
| 17 | + return { width, height }; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + // Try to get from width/height attributes |
| 22 | + const widthMatch = svgContent.match(/width=['"]([^'"]*)['"]/); |
| 23 | + const heightMatch = svgContent.match(/height=['"]([^'"]*)['"]/); |
| 24 | + |
| 25 | + const width = widthMatch ? Number.parseInt(widthMatch[1], 10) : 200; |
| 26 | + const height = heightMatch ? Number.parseInt(heightMatch[1], 10) : 100; |
| 27 | + |
| 28 | + return { width, height }; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Creates a wrapped SVG element for a sponsor with positioning and scaling |
| 33 | + * @param sponsor - Sponsor object with name and url |
| 34 | + * @param svgContent - The SVG content to wrap |
| 35 | + * @param svgWidth - Original width of the SVG |
| 36 | + * @param svgHeight - Original height of the SVG |
| 37 | + * @param height - Target height for the scaled SVG |
| 38 | + * @param x - X position for the SVG |
| 39 | + * @param y - Y position for the SVG |
| 40 | + * @returns Wrapped SVG string |
| 41 | + */ |
| 42 | +export function createWrappedSponsorSvg( |
| 43 | + sponsor: { name: string; url: string }, |
| 44 | + svgContent: string, |
| 45 | + svgWidth: number, |
| 46 | + svgHeight: number, |
| 47 | + height: number, |
| 48 | + x: number, |
| 49 | + y: number |
| 50 | +): string { |
| 51 | + const scale = height ? height / svgHeight : 1; |
| 52 | + const scaledWidth = svgWidth * scale; |
| 53 | + const scaledHeight = svgHeight * scale; |
| 54 | + |
| 55 | + return ` |
| 56 | + <a xlink:href="${sponsor.url}" class="contribkit-link" target="_blank" id="${sponsor.name.replaceAll(/\s+/g, '')}"> |
| 57 | + <svg x="${x}" y="${y}" width="${scaledWidth}" height="${scaledHeight}" viewBox="0 0 ${svgWidth} ${svgHeight}"> |
| 58 | + <rect width="${svgWidth}" height="${svgHeight}" fill="transparent" /> |
| 59 | + ${svgContent} |
| 60 | + </svg> |
| 61 | + </a>`; |
| 62 | +} |
0 commit comments