import { Fragment, useRef, useState } from "react"; import { useMount, useUpdateEffect } from "react-use"; import { motion } from "framer-motion"; import saveAsPng from "save-svg-as-png"; import { EditorType, IconItem } from "types/editor"; import Shapes from "@/components/svg/shapes"; import { Icons } from "components/svg/icons"; import { Null } from "components/svg/shapes/null"; export const Icon = ({ editor, size = 200, id, onChange, onChangeTab, }: { editor: EditorType; id?: string; size?: number; onChange?: (e: EditorType) => void; onChangeTab?: (e: number) => void; }) => { const shapeRef = useRef(null); const ComponentShape = Shapes[editor.shape?.component as keyof typeof Shapes] ?? Null; return ( {editor?.icons?.map((icon, k) => { const findIcon = Icons?.find( (i: IconItem) => icon.component === i.name ); const customText = icon?.custom_text?.enabled; const customImage = icon?.image; const GradientType = icon?.gradient?.type === "radialGradient" ? "radialGradient" : "linearGradient"; if (!findIcon && !customText && !customImage) return null; return ( {icon?.gradient?.enabled ? ( <> {icon?.gradient?.colours?.map((color, c) => ( ))} ) : ( )} <_IconComponent component={findIcon?.component} shapeRef={shapeRef} shape={editor?.shape?.component} key={k} index={k} icon={icon} onChange={(e: any) => onChange && onChange({ ...editor, icons: editor.icons.map((i: any, index: number) => index === k ? e : i ), }) } onClick={onChangeTab ? () => onChangeTab(2) : undefined} /> ); })} ); }; const _IconComponent = ({ shapeRef, component, icon, shape, index, onChange, ...props }: any) => { const iconRef = useRef(null); const [position, setPosition] = useState(null); useUpdateEffect(() => { const position = setIconPosition(iconRef, shapeRef); setPosition(position); const svg = document.getElementById("discotools-selected-svg"); saveAsPng.svgAsPngUri(svg).then(() => {}); }, [shapeRef.current, icon.component, icon?.image]); useMount(() => { const position = setIconPosition(iconRef, shapeRef); setPosition(position); }); useUpdateEffect(() => { onChange({ ...icon, position, }); }, [position]); const IconComponent = component as any; return ( {icon?.custom_text?.enabled ? ( {icon?.custom_text?.text} ) : icon?.image ? ( ) : ( )} ); }; const setIconPosition = (iconRef: any, shapeRef: any) => { if (iconRef?.current) { const shapeBoxW = shapeRef?.current?.getAttribute("viewBox")?.split(" ")[2]; const shapeBoxH = shapeRef?.current?.getAttribute("viewBox")?.split(" ")[3]; const iconBoxW = iconRef?.current?.getAttribute("viewBox")?.split(" ")[2]; const iconBoxH = iconRef?.current?.getAttribute("viewBox")?.split(" ")[3]; const position = { x: shapeBoxW / 2 - iconBoxW / 2, y: shapeBoxH / 2 - iconBoxH / 2, xPath: Number(shapeBoxW - iconBoxW), yPath: Number(shapeBoxH - iconBoxH), }; return position; } };