Files
contentstack-imagevault/rte/components/ImageElement.tsx
2025-06-23 09:29:26 +00:00

140 lines
3.6 KiB
TypeScript

import { Icon, Tooltip, cbModal } from "@contentstack/venus-components"
import React, { PropsWithChildren, useCallback } from "react"
import EmbedBtn from "./EmbedBtn"
import ImageEditModal from "./ImageEditModal"
import type {
IRteElementType,
IRteParam,
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
type ImageElementProps = PropsWithChildren & {
element: IRteElementType & { attrs: InsertResponse }
rte: IRteParam
}
export function ImageElement({ children, element, rte }: ImageElementProps) {
const assetUrl = element.attrs.MediaConversions[0].Url
const isSelected = rte?.selection?.isSelected()
const isFocused = rte?.selection?.isFocused()
const isHighlight = isFocused && isSelected
const handleEdit = useCallback(() => {
cbModal({
// @ts-expect-error: Component is badly typed
component: (compProps) =>
ImageEditModal({
element,
rte,
path: rte.getPath(element),
...compProps,
}),
modalProps: {
size: "max",
style: {
content: {
maxHeight: "90dvh",
maxWidth: "90dvw",
width: "auto",
},
overlay: {},
},
},
})
}, [element, rte])
const ToolTipButtons = () => {
return (
<div contentEditable={false} className="embed--btn-group">
<EmbedBtn title="edit" content="Edit" onClick={handleEdit}>
<Icon icon="Rename" />
</EmbedBtn>
<EmbedBtn
title="remove"
content={"Remove"}
onClick={() => rte?.removeNode(element)}
>
<Icon icon="Trash" />
</EmbedBtn>
</div>
)
}
let alignmentStyles = {}
const marginAlignment: Record<string, { [key: string]: string }> = {
center: { margin: "auto" },
left: { marginRight: "auto" },
right: { marginLeft: "auto" },
}
if (typeof element.attrs.position === "string") {
alignmentStyles = marginAlignment[element.attrs.position]
}
return (
<div
style={{
...alignmentStyles,
...element.attrs.style,
}}
>
<Tooltip
zIndex={909}
className="p-0"
style={{ marginBottom: "10px" }}
position="top"
variantType="light"
offset={[0, -15]}
content={<ToolTipButtons />}
>
<span
data-type="asset"
contentEditable={false}
style={element.attrs?.style}
>
<div
contentEditable={false}
style={{
width: "280px",
height: "auto",
...(isHighlight ? { border: "1px solid #6c5ce7" } : {}),
}}
>
<img
src={assetUrl}
onError={(event) => {
event.currentTarget.src = "https://placehold.co/600x400"
}}
style={{
width: "100%",
height: "auto",
aspectRatio: element.attrs.MediaConversions[0].AspectRatio,
borderRadius: "8px",
}}
alt={element.attrs.altText}
title={element.attrs?.Name}
/>
<div
style={{
position: "absolute",
bottom: 0,
right: 0,
background: "#fff",
color: "#000",
height: "25px",
padding: "3px",
borderRadius: "4px",
}}
>
<Icon icon="Embed" />
</div>
</div>
{children}
</span>
</Tooltip>
</div>
)
}