import { forwardRef, useEffect, useRef, useState } from "react"; import { BadgeType } from "@/types/badge"; import { FONT_FAMILY } from "@/components/font-family/font-family.constants"; import { RATIONAL_BADGE_WIDTH } from "../badge-editor.constants"; import { Icons } from "@/components/svg/icons"; import { IconItem } from "@/types/editor"; import { BADGE_COMPONENTS } from "@/components/svg/badges"; import classNames from "classnames"; import { ShineEffect } from "./shine_effect"; export const Badge = forwardRef( ( { badge, size = "medium", }: { badge: BadgeType; size?: "medium" | "small"; }, ref ) => { const textRef = useRef(null); const svgRef = useRef(null); const badgeContentRef = useRef(null); const [viewBox, setViewBox] = useState("0 0 24 24"); useEffect(() => { if (!textRef.current) return; if (!badgeContentRef.current) return; const textWidth = textRef.current.getBoundingClientRect().width; let newBadgeWidth = RATIONAL_BADGE_WIDTH; if (textWidth > RATIONAL_BADGE_WIDTH) { newBadgeWidth = Math.ceil(textWidth / 32) * 32; } if ( (findShape?.autoResize || badge.type === "circle") && newBadgeWidth - textWidth < (badge.type === "circle" ? 6 : 3) ) newBadgeWidth += 32; badgeContentRef.current.style.width = `${newBadgeWidth}px`; }, [ badge.text, badge.fontFamily, badge.letterSpacing, badge.fontWeight, badge.type, badge?.icon?.component, badge?.icon?.enabled, badge?.icon?.position, ]); const fontFamily = FONT_FAMILY?.find((f) => f.label === badge?.fontFamily); const defaultStyle = { letterSpacing: badge?.letterSpacing, fontWeight: badge?.fontWeight, }; const findIcon = Icons?.find( (i: IconItem) => badge?.icon?.component === i.name ); const findShape = BADGE_COMPONENTS?.find( (b: any) => b.name === badge?.type ); useEffect(() => { return setViewBox( svgRef?.current?.getAttribute("viewBox") ?? "0 0 200 200" ); }, [badge?.icon]); const IconComponent = findIcon?.component as any; const ShapeComponent = findShape?.component as any; return (
{findShape?.component && ( )} {badge?.shinyEffect && ( <> )}
{badge?.icon?.enabled && badge?.icon?.position?.includes("left") && findIcon?.component && badge?.icon?.component && ( )} {badge?.text?.value && (

{badge?.text?.value}

)} {badge?.icon?.enabled && badge?.icon?.position?.includes("right") && findIcon?.component && badge?.icon?.component && ( )}
{findShape?.component && ( )}
); } );