|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { ReactNode, useEffect, useRef, useState } from "react"; |
| 4 | +import embed from "vega-embed"; |
| 5 | +import type { VisualizationSpec } from "vega-embed"; |
| 6 | +import { VegaEmbedContainer } from "./vegaEmbed.styles"; |
| 7 | + |
| 8 | +export interface VegaEmbedProps { |
| 9 | + caption?: ReactNode; |
| 10 | + spec: string | VisualizationSpec; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Extract genome_pos extent from a single dataset array. |
| 15 | + * @param dataset - Array of data points. |
| 16 | + * @returns The min and max values found in this dataset. |
| 17 | + */ |
| 18 | +function getDatasetExtent(dataset: unknown[]): { |
| 19 | + max: number; |
| 20 | + min: number; |
| 21 | +} { |
| 22 | + let min = Infinity; |
| 23 | + let max = -Infinity; |
| 24 | + |
| 25 | + for (const dataPoint of dataset) { |
| 26 | + const point = dataPoint as Record<string, unknown>; |
| 27 | + if ( |
| 28 | + point.genome_pos !== undefined && |
| 29 | + typeof point.genome_pos === "number" |
| 30 | + ) { |
| 31 | + min = Math.min(min, point.genome_pos); |
| 32 | + max = Math.max(max, point.genome_pos); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return { max, min }; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Calculate the data extent for genome_pos field in datasets. |
| 41 | + * @param vegaSpec - The Vega specification. |
| 42 | + * @returns The min and max values, or null if no data found. |
| 43 | + */ |
| 44 | +function calculateGenomePosExtent( |
| 45 | + vegaSpec: VisualizationSpec |
| 46 | +): [number, number] | null { |
| 47 | + let xMin = Infinity; |
| 48 | + let xMax = -Infinity; |
| 49 | + |
| 50 | + if (vegaSpec.datasets) { |
| 51 | + const datasets = Object.values( |
| 52 | + vegaSpec.datasets as Record<string, unknown> |
| 53 | + ); |
| 54 | + for (const dataset of datasets) { |
| 55 | + if (Array.isArray(dataset)) { |
| 56 | + const { max, min } = getDatasetExtent(dataset); |
| 57 | + xMin = Math.min(xMin, min); |
| 58 | + xMax = Math.max(xMax, max); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return xMin !== Infinity && xMax !== -Infinity ? [xMin, xMax] : null; |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Set explicit x-axis domain on a Vega spec to ensure proper centering. |
| 68 | + * @param vegaSpec - The Vega specification to modify. |
| 69 | + * @param domain - The domain to set [min, max]. |
| 70 | + */ |
| 71 | +function setXAxisDomain( |
| 72 | + vegaSpec: VisualizationSpec, |
| 73 | + domain: [number, number] |
| 74 | +): void { |
| 75 | + const spec = vegaSpec as Record<string, unknown>; |
| 76 | + |
| 77 | + if (spec.vconcat && Array.isArray(spec.vconcat)) { |
| 78 | + for (const view of spec.vconcat) { |
| 79 | + const v = view as Record<string, unknown>; |
| 80 | + const encoding = v.encoding as Record<string, unknown> | undefined; |
| 81 | + if (encoding?.x) { |
| 82 | + const x = encoding.x as Record<string, unknown>; |
| 83 | + encoding.x = { |
| 84 | + ...x, |
| 85 | + scale: { |
| 86 | + ...(x.scale as Record<string, unknown> | undefined), |
| 87 | + domain, |
| 88 | + nice: false, |
| 89 | + }, |
| 90 | + }; |
| 91 | + } |
| 92 | + } |
| 93 | + } else if (spec.encoding) { |
| 94 | + const encoding = spec.encoding as Record<string, unknown>; |
| 95 | + if (encoding.x) { |
| 96 | + const x = encoding.x as Record<string, unknown>; |
| 97 | + encoding.x = { |
| 98 | + ...x, |
| 99 | + scale: { |
| 100 | + ...(x.scale as Record<string, unknown> | undefined), |
| 101 | + domain, |
| 102 | + nice: false, |
| 103 | + }, |
| 104 | + }; |
| 105 | + } |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * VegaEmbed component for rendering Vega-Lite visualizations. |
| 111 | + * @param props - Component props. |
| 112 | + * @param props.caption - Optional caption to display below the visualization. |
| 113 | + * @param props.spec - URL to a JSON spec or a Vega-Lite specification object. |
| 114 | + * @returns JSX element containing the Vega-Lite visualization. |
| 115 | + */ |
| 116 | +export const VegaEmbed = ({ caption, spec }: VegaEmbedProps): JSX.Element => { |
| 117 | + const containerRef = useRef<HTMLDivElement>(null); |
| 118 | + const [error, setError] = useState<string | null>(null); |
| 119 | + |
| 120 | + useEffect(() => { |
| 121 | + let result: Awaited<ReturnType<typeof embed>> | null = null; |
| 122 | + |
| 123 | + const loadSpec = async (): Promise<void> => { |
| 124 | + if (!containerRef.current) return; |
| 125 | + |
| 126 | + try { |
| 127 | + let vegaSpec: VisualizationSpec; |
| 128 | + |
| 129 | + // If spec is a string (URL), fetch it |
| 130 | + if (typeof spec === "string") { |
| 131 | + const response = await fetch(spec); |
| 132 | + if (!response.ok) { |
| 133 | + throw new Error(`Failed to fetch spec: ${response.statusText}`); |
| 134 | + } |
| 135 | + vegaSpec = await response.json(); |
| 136 | + } else { |
| 137 | + vegaSpec = spec; |
| 138 | + } |
| 139 | + |
| 140 | + // Calculate and set x-axis domain for proper centering |
| 141 | + const extent = calculateGenomePosExtent(vegaSpec); |
| 142 | + if (extent) { |
| 143 | + const [min, max] = extent; |
| 144 | + const range = max - min; |
| 145 | + const padding = range * 0.05; |
| 146 | + const paddedExtent: [number, number] = [min - padding, max + padding]; |
| 147 | + setXAxisDomain(vegaSpec, paddedExtent); |
| 148 | + } |
| 149 | + |
| 150 | + // Embed the visualization with responsive sizing |
| 151 | + result = await embed(containerRef.current, vegaSpec, { |
| 152 | + actions: { |
| 153 | + compiled: false, |
| 154 | + editor: false, |
| 155 | + export: true, |
| 156 | + source: false, |
| 157 | + }, |
| 158 | + config: { |
| 159 | + autosize: { |
| 160 | + resize: true, |
| 161 | + type: "fit-x", |
| 162 | + }, |
| 163 | + scale: { |
| 164 | + nice: false, |
| 165 | + }, |
| 166 | + }, |
| 167 | + }); |
| 168 | + setError(null); |
| 169 | + } catch (err) { |
| 170 | + const errorMessage = |
| 171 | + err instanceof Error ? err.message : "Unknown error"; |
| 172 | + setError(errorMessage); |
| 173 | + console.error("Error loading Vega-Lite spec:", err); |
| 174 | + } |
| 175 | + }; |
| 176 | + |
| 177 | + loadSpec(); |
| 178 | + |
| 179 | + return (): void => { |
| 180 | + if (result) { |
| 181 | + result.finalize(); |
| 182 | + } |
| 183 | + }; |
| 184 | + }, [spec]); |
| 185 | + |
| 186 | + return ( |
| 187 | + <VegaEmbedContainer> |
| 188 | + {error && ( |
| 189 | + <div className="error">Error loading visualization: {error}</div> |
| 190 | + )} |
| 191 | + <div ref={containerRef} className="vega-container" /> |
| 192 | + {caption && <figcaption>{caption}</figcaption>} |
| 193 | + </VegaEmbedContainer> |
| 194 | + ); |
| 195 | +}; |
0 commit comments