Source: feedback/CharacterLoadScript.js

import { useVariables } from "../../_core";
import { useEffect } from "react";
import { useState } from "react";

/**
 * Componente que hace load de los scripts necesarios para ejecutar Character de SitePal
 * @name Reactor.Components.Feedback.CharacterLoadScript
 * @param {string} variable 
 *  variable donde se va a colocar el status de la carga de los scripts
 *  {loaded: [boolean], error: [boolean]}
 * @param {string} [context = "global"] Contexto donde se encuentra la variable
 * @class
 * @example
<style>
  div.sitepal-wrapper{
    height: 500px;
    width:300px;
  }
</style>
<div style="height: 500px;min-width:300px;width: 100%;display: flex;flex-direction: column;align-items: center;">
  <character_load_script variable="loader" context="gpt">
    <if variable="loader.loaded" context="gpt" type="boolean">
      <condition value="true" type="boolean">
        <character 
          embed='3432155,500,300,"",1,1,2722664,0,1,1,"WSGmJ3ScqO8d4Zop1cuILz7q4In5k6q2",0,1' 
          variable="character" 
          context="gpt" 
        ></character>
        <a href="EjemplosCharacter" data='{"action": "say1"}' target="operation">Hablar</a>
      </condition>  
      <condition value="false" type="boolean">
        <p>Cargando...</p>
      </condition>  
    </if>
    <if variable="loader.error" context="gpt" type="boolean">
      <condition value="true" type="boolean">
        <p>Ops, ocurrió un error</p>
      </condition>  
    </if>
  </character_load_script>
</div>
 */

export const CharacterLoadScript = ({variable, context, children}) => {

  const [ loaded, setLoaded ] = useState(false);
  const [ error, setError ] = useState(false);
  const variables = useVariables({variable, context});

  useEffect(()=>{
    variables.setData({loaded, error});
  }, [loaded, error])

  useEffect(() => {
    const scripts = document.head.getElementsByTagName('script');
    if (scripts.length > 0) {
      for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src.includes("vhost_embed_functions_v4.php")) {
          setLoaded(true);
          return;
        }
      }
    }
    loadEmbedFile()
      .then(() => {
        setLoaded(true);
      })
      .catch(() => {
        setError(true);
      });
  }, []);

  return (
    <>
      {children}
    </>
  )
}

const loadEmbedFile = () => new Promise((resolve, reject) => {
  var sc = document.createElement('script');
  sc.type = "text/javascript";
  sc.src = "//vhss-d.oddcast.com/vhost_embed_functions_v4.php?acc=5626448&js=1";
  sc.onload = function () {
    resolve();
  }
  sc.onerror = function () {
    reject();
  }
  document.head.appendChild(sc);
})