crono-chat-widget
Version:
Widget de chat de Crono AI que puede ser incorporado en cualquier proyecto
3 lines (2 loc) • 11.6 kB
JavaScript
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).CronoChatWidget={},e.jsxRuntime,e.React)}(this,(function(e,r,t){"use strict";var o=function(){return o=Object.assign||function(e){for(var r,t=1,o=arguments.length;t<o;t++)for(var n in r=arguments[t])Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);return e},o.apply(this,arguments)};function n(e,r,t,o){return new(t||(t=Promise))((function(n,a){function c(e){try{i(o.next(e))}catch(e){a(e)}}function s(e){try{i(o.throw(e))}catch(e){a(e)}}function i(e){var r;e.done?n(e.value):(r=e.value,r instanceof t?r:new t((function(e){e(r)}))).then(c,s)}i((o=o.apply(e,r||[])).next())}))}function a(e,r){var t,o,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},c=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return c.next=s(0),c.throw=s(1),c.return=s(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function s(s){return function(i){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;c&&(c=0,s[0]&&(a=0)),a;)try{if(t=1,o&&(n=2&s[0]?o.return:s[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,s[1])).done)return n;switch(o=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,o=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){a.label=s[1];break}if(6===s[0]&&a.label<n[1]){a.label=n[1],n=s;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(s);break}n[2]&&a.ops.pop(),a.trys.pop();continue}s=r.call(e,a)}catch(e){s=[6,e],o=0}finally{t=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,i])}}}function c(e,r,t){if(t||2===arguments.length)for(var o,n=0,a=r.length;n<a;n++)!o&&n in r||(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))}"function"==typeof SuppressedError&&SuppressedError;var s=function(e){var r=t.useState(e.initialMessages||[]),s=r[0],i=r[1],l=t.useState(!1),d=l[0],u=l[1],f=t.useState(null),h=f[0],p=f[1],m=function(e){var r=e.apiUrl,t=e.apiKey,c=o({"Content-Type":"application/json"},t?{Authorization:"Bearer ".concat(t)}:{});return{fetchNewThreadId:function(){return n(void 0,void 0,void 0,(function(){var e,t;return a(this,(function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),[4,fetch("".concat(r,"/new"),{method:"GET",headers:c})];case 1:if(!(e=o.sent()).ok)throw new Error("Error al obtener nuevo thread ID: ".concat(e.status));return[4,e.json()];case 2:return[2,o.sent().ThreadId];case 3:throw t=o.sent(),console.error("Error al obtener nuevo thread ID:",t),t;case 4:return[2]}}))}))},sendMessage:function(e,t){return n(void 0,void 0,void 0,(function(){var o,n,s;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,fetch("".concat(r,"/prompt"),{method:"POST",headers:c,body:JSON.stringify({threadId:e,prompt:t})})];case 1:if(!(o=a.sent()).ok)throw new Error("Error al enviar mensaje: ".concat(o.status));return[4,o.json()];case 2:return(n=a.sent())&&n.Messages&&Array.isArray(n.Messages)?[2,n.Messages.map((function(e){var r=null;if(e.Script)try{var t=document.createElement("script");t.textContent=e.Script,t.textContent&&t.textContent.trim()&&(r=t.textContent)}catch(e){console.error("Error al procesar script:",e)}return{type:"ErrorText"===e.Type?"error":"bot",content:e.Content,isHtml:"Html"===e.Type,script:r||void 0,raw:n.Raw}}))]:(console.error("Respuesta inválida del servidor:",n),[2,[]]);case 3:throw s=a.sent(),console.error("Error al enviar mensaje:",s),s;case 4:return[2]}}))}))}}}(e),g=t.useCallback((function(){return n(void 0,void 0,void 0,(function(){var r,t,o;return a(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,3,4]),u(!0),[4,m.fetchNewThreadId()];case 1:return r=n.sent(),p(r),e.initialMessages||i([]),[3,4];case 2:return t=n.sent(),console.error("Error al inicializar el chat:",t),o=t instanceof Error?t.message:"Error al inicializar el chat",i([{type:"error",content:o,isHtml:!1}]),[3,4];case 3:return u(!1),[7];case 4:return[2]}}))}))}),[e.initialMessages,m]),b=t.useCallback((function(r){return n(void 0,void 0,void 0,(function(){var t,o,n;return a(this,(function(a){switch(a.label){case 0:if(!h||!r.trim())return[2];u(!0),i((function(e){return c(c([],e,!0),[{type:"user",content:r,isHtml:!1}],!1)})),a.label=1;case 1:return a.trys.push([1,3,4,5]),[4,m.sendMessage(h,r)];case 2:return t=a.sent(),i((function(e){return c(c([],e,!0),t,!0)})),[3,5];case 3:return o=a.sent(),console.error("Error al enviar mensaje:",o),n=o instanceof Error?o.message:"Error al enviar mensaje",i((function(r){var t;return c(c([],r,!0),[{type:"error",content:(null===(t=e.labels)||void 0===t?void 0:t.errorDefault)||n,isHtml:!1}],!1)})),[3,5];case 4:return u(!1),[7];case 5:return[2]}}))}))}),[h,m,e.labels]);return{messages:s,isThinking:d,threadId:h,initChat:g,sendMessage:b}},i=function(e){var o=e.message,n=e.showAvatar,a=void 0!==n&&n,c=t.useRef(null);return t.useEffect((function(){if(c.current&&(null==o?void 0:o.isHtml)&&(c.current.scrollTop=0),c.current&&(null==o?void 0:o.script)){var e=document.createElement("script");return e.textContent=o.script,document.body.appendChild(e),function(){document.body.removeChild(e)}}}),[null==o?void 0:o.script,null==o?void 0:o.isHtml]),r.jsx("div",{className:"crono-chat-message-container",children:r.jsxs("div",{className:"crono-chat-message ".concat("user"===o.type?"crono-chat-message-user":"error"===o.type?"crono-chat-message-error":"crono-chat-message-bot"),children:[a&&"bot"===o.type&&r.jsx("div",{className:"crono-chat-avatar",children:r.jsx("span",{children:"AI"})}),r.jsx("div",{className:"crono-chat-message-content",children:(null==o?void 0:o.isHtml)?r.jsx("div",{ref:c,className:"crono-chat-html-content",dangerouslySetInnerHTML:{__html:o.content||""}}):r.jsx("pre",{className:"crono-chat-text-content",children:(null==o?void 0:o.content)||""})})]})})};!function(e,r){void 0===r&&(r={});var t=r.insertAt;if("undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===t&&o.firstChild?o.insertBefore(n,o.firstChild):o.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}('@import "tailwindcss";.crono-chat-widget{background-color:#fff;border-radius:.5rem;box-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -1px rgba(0,0,0,.06);display:flex;flex-direction:column;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif;height:100%;overflow:hidden;width:100%}.crono-chat-messages{display:flex;flex:1;flex-direction:column;gap:1rem;overflow-y:auto;padding:1rem}.crono-chat-message-container{display:flex;width:100%}.crono-chat-message{border-radius:.5rem;max-width:80%;overflow:hidden;padding:.75rem 1rem}.crono-chat-message-user{align-self:flex-end;background-color:#4ade80;border-top-right-radius:0;color:#111827;margin-left:auto}.crono-chat-message-bot{align-self:flex-start;color:#111827;display:flex;gap:.5rem}.crono-chat-message-error{align-self:flex-start;background-color:#fee2e2;border-top-left-radius:0;color:#b91c1c}.crono-chat-avatar{align-items:center;background-color:#002685;border-radius:50%;color:#fff;display:flex;flex-shrink:0;font-size:.75rem;font-weight:700;height:2rem;justify-content:center;width:2rem}.crono-chat-message-content{flex:1;overflow:hidden}.crono-chat-html-content{overflow-x:auto;width:100%}.crono-chat-text-content{font-size:.875rem;margin:0;white-space:pre-wrap;word-break:break-word}.crono-chat-input-container{background-color:#fff;border-top:1px solid #e5e7eb;display:flex;padding:.75rem}.crono-chat-input{border:1px solid #e5e7eb;border-radius:.375rem;flex:1;font-size:.875rem;outline:none;padding:.5rem .75rem;transition:border-color .2s}.crono-chat-input:focus{border-color:#002685}.crono-chat-input:disabled{background-color:#f3f4f6;cursor:not-allowed}.crono-chat-send-button{background-color:#002685;border:none;border-radius:.375rem;color:#fff;cursor:pointer;font-size:.875rem;font-weight:500;margin-left:.5rem;padding:.5rem 1rem;transition:background-color .2s}.crono-chat-send-button:hover:not(:disabled){background-color:#001a5c}.crono-chat-send-button:disabled{cursor:not-allowed;opacity:.5}.crono-chat-thinking{align-items:center;align-self:flex-start;display:flex;gap:.25rem;padding:.5rem}.crono-chat-thinking-dot{animation:thinking 1.4s ease-in-out infinite both;background-color:#9ca3af;border-radius:50%;height:.5rem;width:.5rem}.crono-chat-thinking-dot:first-child{animation-delay:-.32s}.crono-chat-thinking-dot:nth-child(2){animation-delay:-.16s}@keyframes thinking{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}.dark .crono-chat-widget{background-color:#1e293b;color:#fff}.dark .crono-chat-input-container{background-color:#1e293b;border-top-color:#334155}.dark .crono-chat-input{background-color:#334155;border-color:#475569;color:#fff}.dark .crono-chat-input:focus{border-color:#60a5fa}.dark .crono-chat-input:disabled{background-color:#1f2937}.dark .crono-chat-message-user{background-color:#22c55e;color:#fff}.dark .crono-chat-message-bot{color:#fff}.dark .crono-chat-message-error{background-color:#7f1d1d;color:#fecaca}.dark .crono-chat-thinking-dot{background-color:#d1d5db}',{insertAt:"top"});var l=function(e){var o,n,a=e.config,c=e.className,l=void 0===c?"":c,d=s(a),u=d.messages,f=d.isThinking,h=d.sendMessage,p=d.initChat,m=t.useState(""),g=m[0],b=m[1],v=t.useRef(null),y=t.useRef(null);t.useEffect((function(){p()}),[p]),t.useEffect((function(){var e;null===(e=v.current)||void 0===e||e.scrollIntoView({behavior:"smooth"})}),[u]);return r.jsxs("div",{className:"crono-chat-widget ".concat(l),children:[r.jsxs("div",{className:"crono-chat-messages",children:[u.map((function(e,t){var o;return r.jsx(i,{message:e,showAvatar:0===t||(null===(o=u[t-1])||void 0===o?void 0:o.type)!==e.type},"message-".concat(t))})),f&&r.jsxs("div",{className:"crono-chat-thinking",children:[r.jsx("div",{className:"crono-chat-thinking-dot"}),r.jsx("div",{className:"crono-chat-thinking-dot"}),r.jsx("div",{className:"crono-chat-thinking-dot"})]}),r.jsx("div",{ref:v})]}),r.jsxs("form",{onSubmit:function(e){e.preventDefault(),g.trim()&&!f&&(h(g),b(""))},className:"crono-chat-input-container",children:[r.jsx("input",{ref:y,type:"text",value:g,onChange:function(e){return b(e.target.value)},placeholder:(null===(o=a.labels)||void 0===o?void 0:o.inputPlaceholder)||"Escribe un mensaje...",className:"crono-chat-input",disabled:f}),r.jsx("button",{type:"submit",className:"crono-chat-send-button",disabled:!g.trim()||f,children:(null===(n=a.labels)||void 0===n?void 0:n.sendButton)||"Enviar"})]})]})},d=function(e,r){if(e){var t=window.React,o=window.ReactDOM;if(t&&o)if("createRoot"in o)o.createRoot(e).render(t.createElement(l,{config:r}));else o.render(t.createElement(l,{config:r}),e);else console.error("Crono Chat Widget: React y ReactDOM son requeridos. Asegúrate de cargarlos antes de este script.")}else console.error("Crono Chat Widget: El elemento de montaje no es válido")},u={CronoChat:l,mount:d};e.CronoChat=l,e.default=u,e.mount=d,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=index.umd.js.map