import { addPropertyControls, ControlType, RenderTarget } from "framer"
import { useState, useEffect } from "react"
import { SettingsMessage } from "<https://framer.com/m/Utils-QTIc.js@PVRWqcAS5FromVQ03eYl>"
export default function MarketoForm(props) {
const { embed, style } = props
const [isEmbedValid, setIsEmbedValid] = useState(false)
const [formId, setFormId] = useState(null)
const [script, setScript] = useState(null)
const [isLoading, setIsLoading] = useState(true)
if (!embed || embed.length === 0) {
return (
<SettingsMessage
title="Marketo Embed Component"
description="Enter the Marketo Embed Code here"
containerStyle={style}
/>
)
}
useEffect(() => {
setIsLoading(true)
const embedRegex =
/MktoForms2\\.loadForm\\("(.+?)", "(.+?)", (\\d+)(?:, .+?)?\\);/
const embedMatch = embed.match(embedRegex)
const [, link, value, id] = embedMatch || []
setFormId(`mktoForm_${id}`)
const embedFirstLine = `<script src="${link}/js/forms2/js/forms2.min.js"></script>`
const isValidEmbed =
embed.startsWith(embedFirstLine) && value && id && link
setIsEmbedValid(isValidEmbed)
if (isValidEmbed) {
const newScript = document.createElement("script")
newScript.src = `${link}/js/forms2/js/forms2.min.js`
newScript.async = true
const handleError = (error, message) => {
setIsEmbedValid(false)
setIsLoading(false)
console.error(message, error)
}
const handleScriptLoad = () => {
try {
if (window.MktoForms2) {
window.MktoForms2.loadForm(link, value, id)
}
} catch (error) {
handleError(error, "Error loading form:")
}
}
newScript.onload = handleScriptLoad
document.body.appendChild(newScript)
setScript(newScript)
try {
document.body.appendChild(newScript)
setScript(newScript)
} catch (error) {
handleError(error, "Error appending script:")
}
}
setIsLoading(false)
return () => {
if (script) {
try {
document.body.removeChild(script)
} catch (error) {
setIsEmbedValid(false)
console.error("Error removing script:", error)
}
}
}
}, [embed])
return (
<>
{isLoading ? (
<></>
) : isEmbedValid ? (
<>
<style>{customCSS}</style>
<form id={formId} />
</>
) : (
<SettingsMessage
title="Your embed code is incorrect!"
description="Update the Marketo embed form in the component property."
containerStyle={style}
icon={"🚨"}
/>
)}
</>
)
}
const customCSS = `
.mktoLabel {
width: auto !important;
float: none !important;
display: block !important;
}
`
MarketoForm.displayName = "Marketo Form"
addPropertyControls(MarketoForm, {
embed: {
title: "Embed Code",
type: ControlType.String,
displayTextArea: true,
description:
"[Where to find my Marketo embed form](<https://experienceleague.adobe.com/en/docs/marketo/using/product-docs/demand-generation/forms/form-actions/embed-a-form-on-your-website>).",
},
})