github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/ui/dashboard/src/components/dashboards/Image/index.tsx (about) 1 import get from "lodash/get"; 2 import Img from "react-cool-img"; 3 import { 4 BasePrimitiveProps, 5 ExecutablePrimitiveProps, 6 LeafNodeData, 7 } from "../common"; 8 import { getComponent, registerComponent } from "../index"; 9 import { PanelDefinition } from "../../../types"; 10 import { useEffect, useState } from "react"; 11 const Table = getComponent("table"); 12 13 type ImageType = "image" | "table" | null; 14 15 type ImageDataFormat = "simple" | "formal"; 16 17 type ImageState = { 18 src: string | null; 19 alt: string | null; 20 }; 21 22 export type ImageProps = PanelDefinition & 23 BasePrimitiveProps & 24 ExecutablePrimitiveProps & { 25 display_type?: ImageType; 26 properties: { 27 src: string; 28 alt: string; 29 }; 30 }; 31 32 const getDataFormat = (data: LeafNodeData): ImageDataFormat => { 33 if (data.columns.length > 1) { 34 return "formal"; 35 } 36 return "simple"; 37 }; 38 39 const useImageState = ({ data, properties }: ImageProps) => { 40 const [calculatedProperties, setCalculatedProperties] = useState<ImageState>({ 41 src: properties.src || null, 42 alt: properties.alt || null, 43 }); 44 45 useEffect(() => { 46 if (!data) { 47 return; 48 } 49 50 if ( 51 !data.columns || 52 !data.rows || 53 data.columns.length === 0 || 54 data.rows.length === 0 55 ) { 56 setCalculatedProperties({ 57 src: null, 58 alt: null, 59 }); 60 return; 61 } 62 63 const dataFormat = getDataFormat(data); 64 65 if (dataFormat === "simple") { 66 const firstCol = data.columns[0]; 67 const row = data.rows[0]; 68 setCalculatedProperties({ 69 src: row[firstCol.name], 70 alt: firstCol.name, 71 }); 72 } else { 73 const src = get(data, `rows[0].src`, null); 74 const alt = get(data, `rows[0].alt`, null); 75 76 setCalculatedProperties({ 77 src, 78 alt, 79 }); 80 } 81 }, [data, properties]); 82 83 return calculatedProperties; 84 }; 85 86 const Image = (props: ImageProps) => { 87 const state = useImageState(props); 88 return <Img src={state.src} alt={state.alt} />; 89 }; 90 91 const ImageWrapper = (props: ImageProps) => { 92 if (props.display_type === "table") { 93 // @ts-ignore 94 return <Table {...props} />; 95 } 96 return <Image {...props} />; 97 }; 98 99 registerComponent("image", ImageWrapper); 100 101 export default ImageWrapper;