crono-chat-widget
Version:
Widget de chat de Crono AI que puede ser incorporado en cualquier proyecto
3 lines (2 loc) • 11.2 kB
JavaScript
import{jsx as e,jsxs as r}from"react/jsx-runtime";import{useState as t,useCallback as o,useRef as n,useEffect as a}from"react";var c=function(){return c=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},c.apply(this,arguments)};function i(e,r,t,o){return new(t||(t=Promise))((function(n,a){function c(e){try{s(o.next(e))}catch(e){a(e)}}function i(e){try{s(o.throw(e))}catch(e){a(e)}}function s(e){var r;e.done?n(e.value):(r=e.value,r instanceof t?r:new t((function(e){e(r)}))).then(c,i)}s((o=o.apply(e,r||[])).next())}))}function s(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=i(0),c.throw=i(1),c.return=i(2),"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function i(i){return function(s){return function(i){if(t)throw new TypeError("Generator is already executing.");for(;c&&(c=0,i[0]&&(a=0)),a;)try{if(t=1,o&&(n=2&i[0]?o.return:i[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,i[1])).done)return n;switch(o=0,n&&(i=[2&i[0],n.value]),i[0]){case 0:case 1:n=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!n||i[1]>n[0]&&i[1]<n[3])){a.label=i[1];break}if(6===i[0]&&a.label<n[1]){a.label=n[1],n=i;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(i);break}n[2]&&a.ops.pop(),a.trys.pop();continue}i=r.call(e,a)}catch(e){i=[6,e],o=0}finally{t=n=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function l(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 d=function(e){var r=t(e.initialMessages||[]),n=r[0],a=r[1],d=t(!1),u=d[0],h=d[1],f=t(null),m=f[0],p=f[1],g=function(e){var r=e.apiUrl,t=e.apiKey,o=c({"Content-Type":"application/json"},t?{Authorization:"Bearer ".concat(t)}:{});return{fetchNewThreadId:function(){return i(void 0,void 0,void 0,(function(){var e,t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,fetch("".concat(r,"/new"),{method:"GET",headers:o})];case 1:if(!(e=n.sent()).ok)throw new Error("Error al obtener nuevo thread ID: ".concat(e.status));return[4,e.json()];case 2:return[2,n.sent().ThreadId];case 3:throw t=n.sent(),console.error("Error al obtener nuevo thread ID:",t),t;case 4:return[2]}}))}))},sendMessage:function(e,t){return i(void 0,void 0,void 0,(function(){var n,a,c;return s(this,(function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,fetch("".concat(r,"/prompt"),{method:"POST",headers:o,body:JSON.stringify({threadId:e,prompt:t})})];case 1:if(!(n=i.sent()).ok)throw new Error("Error al enviar mensaje: ".concat(n.status));return[4,n.json()];case 2:return(a=i.sent())&&a.Messages&&Array.isArray(a.Messages)?[2,a.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:a.Raw}}))]:(console.error("Respuesta inválida del servidor:",a),[2,[]]);case 3:throw c=i.sent(),console.error("Error al enviar mensaje:",c),c;case 4:return[2]}}))}))}}}(e),v=o((function(){return i(void 0,void 0,void 0,(function(){var r,t,o;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,3,4]),h(!0),[4,g.fetchNewThreadId()];case 1:return r=n.sent(),p(r),e.initialMessages||a([]),[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",a([{type:"error",content:o,isHtml:!1}]),[3,4];case 3:return h(!1),[7];case 4:return[2]}}))}))}),[e.initialMessages,g]),b=o((function(r){return i(void 0,void 0,void 0,(function(){var t,o,n;return s(this,(function(c){switch(c.label){case 0:if(!m||!r.trim())return[2];h(!0),a((function(e){return l(l([],e,!0),[{type:"user",content:r,isHtml:!1}],!1)})),c.label=1;case 1:return c.trys.push([1,3,4,5]),[4,g.sendMessage(m,r)];case 2:return t=c.sent(),a((function(e){return l(l([],e,!0),t,!0)})),[3,5];case 3:return o=c.sent(),console.error("Error al enviar mensaje:",o),n=o instanceof Error?o.message:"Error al enviar mensaje",a((function(r){var t;return l(l([],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 h(!1),[7];case 5:return[2]}}))}))}),[m,g,e.labels]);return{messages:n,isThinking:u,threadId:m,initChat:v,sendMessage:b}},u=function(t){var o=t.message,c=t.showAvatar,i=void 0!==c&&c,s=n(null);return a((function(){if(s.current&&(null==o?void 0:o.isHtml)&&(s.current.scrollTop=0),s.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]),e("div",{className:"crono-chat-message-container",children:r("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:[i&&"bot"===o.type&&e("div",{className:"crono-chat-avatar",children:e("span",{children:"AI"})}),e("div",{className:"crono-chat-message-content",children:(null==o?void 0:o.isHtml)?e("div",{ref:s,className:"crono-chat-html-content",dangerouslySetInnerHTML:{__html:o.content||""}}):e("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 h=function(o){var c,i,s=o.config,l=o.className,h=void 0===l?"":l,f=d(s),m=f.messages,p=f.isThinking,g=f.sendMessage,v=f.initChat,b=t(""),y=b[0],w=b[1],k=n(null),x=n(null);a((function(){v()}),[v]),a((function(){var e;null===(e=k.current)||void 0===e||e.scrollIntoView({behavior:"smooth"})}),[m]);return r("div",{className:"crono-chat-widget ".concat(h),children:[r("div",{className:"crono-chat-messages",children:[m.map((function(r,t){var o;return e(u,{message:r,showAvatar:0===t||(null===(o=m[t-1])||void 0===o?void 0:o.type)!==r.type},"message-".concat(t))})),p&&r("div",{className:"crono-chat-thinking",children:[e("div",{className:"crono-chat-thinking-dot"}),e("div",{className:"crono-chat-thinking-dot"}),e("div",{className:"crono-chat-thinking-dot"})]}),e("div",{ref:k})]}),r("form",{onSubmit:function(e){e.preventDefault(),y.trim()&&!p&&(g(y),w(""))},className:"crono-chat-input-container",children:[e("input",{ref:x,type:"text",value:y,onChange:function(e){return w(e.target.value)},placeholder:(null===(c=s.labels)||void 0===c?void 0:c.inputPlaceholder)||"Escribe un mensaje...",className:"crono-chat-input",disabled:p}),e("button",{type:"submit",className:"crono-chat-send-button",disabled:!y.trim()||p,children:(null===(i=s.labels)||void 0===i?void 0:i.sendButton)||"Enviar"})]})]})},f=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(h,{config:r}));else o.render(t.createElement(h,{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")},m={CronoChat:h,mount:f};export{h as CronoChat,m as default,f as mount};
//# sourceMappingURL=index.esm.js.map