@topthink/chat 1.0.19 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as e from"react";import{useCallback as r,useState as t,useImperativeHandle as o,memo as n,useMemo as i,useRef as a,createContext as s,useContext as l,Fragment as c,useEffect as d}from"react";import{useImmer as m,request as h,isRequestError as p,Lightbox as u,styled as g,Clipboard as f,css as b,formatSize as v,Tooltip as x,useAsync as y,isImageUrl as k}from"@topthink/components";import{jsx as w,jsxs as j,Fragment as N}from"react/jsx-runtime";import z from"react-markdown";import"katex/dist/katex.min.css";import $ from"remark-math";import M from"remark-breaks";import E from"remark-gfm";import q from"rehype-katex";import C from"rehype-highlight";import{Spinner as F}from"react-bootstrap";import*as R from"path";import _ from"path";import O from"react-textarea-autosize";import T from"use-resize-observer";function D(e){if((e=e.filter((e=>!!e.trim()))).length>3){const r=[...e];let t=e.length-3;for(;t--;){let e=Math.floor(Math.random()*r.length);r.splice(e,1)}e=r}return e}function A(e){let{url:n,transformRequest:i,onboarding:a,onSuccess:s,ref:l,...c}=e;const d=r((e=>{const r=[];if(a&&!1!==a.enable&&a.prologue){const e=D(a.questions);r.push({chunks:[{content:[a.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}]})}return e?r.concat(e.messages):r}),[a]),[u,g]=m((()=>d(c.conversation))),[f,b]=t(!1),[v,x]=t(c.conversation?.id),y=r((async function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(e||r.length>0){b(!0),g((t=>{t.push({query:e,files:r,chunks:[],loading:!0})}));try{await h({method:"post",url:n,data:{query:e,files:r,conversation:v},transformRequest:i,onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const r=JSON.parse(e.data);r.conversation?x(r.conversation):g((e=>{const t=e[e.length-1];if(t.chunks)if(r.chunks){const e=r.chunks.index;if(t.chunks[e]||(t.chunks[e]={content:"",tools:[]}),r.chunks.error)t.chunks[e].error=r.chunks.error;else if(r.chunks.tools){const o=r.chunks.tools.index;"response"in r.chunks.tools?(t.chunks[e].tools[o].response=r.chunks.tools.response,t.chunks[e].tools[o].error=r.chunks.tools.error,t.chunks[e].tools[o].content=r.chunks.tools.content):t.chunks[e].tools[o]={name:r.chunks.tools.name,title:r.chunks.tools.title,arguments:r.chunks.tools.arguments}}else r.chunks.content&&(t.chunks[e].content+=r.chunks.content)}else r.stats&&(t.stats=r.stats)}))}catch(e){console.error(e)}else g((e=>{e[e.length-1].loading=!1}))}})}catch(e){let r="未知错误";p(e)&&(r=401==e.response?.status?"未授权或授权已过期,请刷新页面后重试":"string"==typeof e.errors?e.errors:Object.values(e.errors).join("\n")),g((e=>{const t=e[e.length-1];t.chunks&&(0===t.chunks.length?t.chunks=[{content:`[${r}]`,tools:[]}]:t.chunks[t.chunks.length-1].content=`[${r}]`),t.loading=!1}))}b(!1),s?.()}}),[i,v]),k=r((e=>{f||(x(e?.id),g(d(e)))}),[f,d]);return o(l,(()=>({reset:k,send:y}))),{messages:u,loading:f,send:y,reset:k}}const L=u.Image,P={pre:e=>{let{children:r}=e;const t=a(null);return j(H,{ref:t,children:[w(I,{tooltip:!1,content:()=>{const e=t.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),r]})},a:e=>{let{node:r,href:t,...o}=e;const n=t?.startsWith("http")?"_blank":"_self";return w("a",{...o,href:t,target:n})},img:e=>{let{node:r,...t}=e;return w(L,{...t})}},S=[[$,{singleDollarTextMath:!1}],E,M],B=[q,[C,{detect:!1,ignoreMissing:!0}]],U=n((e=>{let{content:r,components:t}=e;return r=r.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$"),w(K,{remarkPlugins:S,rehypePlugins:B,components:i((()=>({...P,...t})),[t]),children:r})})),I=g(f)`
1
+ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandle as o,memo as n,useMemo as i,useRef as a,createContext as s,useContext as l,Fragment as c,useEffect as d}from"react";import{useImmer as m,request as h,isRequestError as p,Lightbox as u,styled as g,Clipboard as f,css as b,formatSize as v,Tooltip as x,useAsync as y,isImageUrl as k}from"@topthink/components";import{jsx as w,jsxs as j,Fragment as N}from"react/jsx-runtime";import z from"react-markdown";import"katex/dist/katex.min.css";import $ from"remark-math";import M from"remark-breaks";import E from"remark-gfm";import q from"rehype-katex";import C from"rehype-highlight";import{Spinner as F}from"react-bootstrap";import*as R from"path";import _ from"path";import L from"react-textarea-autosize";import O from"use-resize-observer";function T(e){if((e=e.filter((e=>!!e.trim()))).length>3){const r=[...e];let t=e.length-3;for(;t--;){let e=Math.floor(Math.random()*r.length);r.splice(e,1)}e=r}return e}function D(e){return e.map((e=>({query:e.query,files:e.files||void 0,chunks:e.chunks.map((e=>{let{content:r="",error:t,tools:o=[]}=e;return{content:r,error:t,tools:o}})),stats:{usage:e.usage,latency:e.latency}})))}function A(e){let{url:n,onboarding:i,onSuccess:a,ref:s,transformRequest:l,...c}=e;const d=r((e=>{const r=[];if(i&&!1!==i.enable&&i.prologue){const e=T(i.questions);r.push({chunks:[{content:[i.prologue,...e.map((e=>`[${e}](#!question)`))].join("\n"),tools:[]}]})}return e?r.concat(D(e.messages||[])):r}),[i]),[u,g]=m((()=>d(c.conversation))),[f,b]=t(!1),[v,x]=t(c.conversation?.id),y=r((async function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(e||r.length>0){b(!0),g((t=>{t.push({query:e,files:r,chunks:[],loading:!0})}));try{let t={method:"post",url:n,data:{query:e,files:r,conversation:v},onMessage:e=>{if(e.data)if("[DONE]"!=e.data)try{const r=JSON.parse(e.data);r.conversation?x(r.conversation):g((e=>{const t=e[e.length-1];if(t.chunks)if(r.chunks){const e=r.chunks.index;if(t.chunks[e]||(t.chunks[e]={content:"",tools:[]}),r.chunks.error)t.chunks[e].error=r.chunks.error;else if(r.chunks.tools){const o=r.chunks.tools.index;"response"in r.chunks.tools?(t.chunks[e].tools[o].response=r.chunks.tools.response,t.chunks[e].tools[o].error=r.chunks.tools.error,t.chunks[e].tools[o].content=r.chunks.tools.content):t.chunks[e].tools[o]={name:r.chunks.tools.name,title:r.chunks.tools.title,arguments:r.chunks.tools.arguments}}else r.chunks.content&&(t.chunks[e].content+=r.chunks.content)}else r.stats&&(t.stats=r.stats)}))}catch(e){console.error(e)}else g((e=>{e[e.length-1].loading=!1}))}};l&&(t=l("chat",t)),await h(t)}catch(e){let r="未知错误";p(e)&&(r=401==e.response?.status?"未授权或授权已过期,请刷新页面后重试":"string"==typeof e.errors?e.errors:Object.values(e.errors).join("\n")),g((e=>{const t=e[e.length-1];t.chunks&&(0===t.chunks.length?t.chunks=[{content:`[${r}]`,tools:[]}]:t.chunks[t.chunks.length-1].content=`[${r}]`),t.loading=!1}))}b(!1),a?.()}}),[l,v]),k=r((e=>{f||(x(e?.id),g(d(e)))}),[f,d]);return o(s,(()=>({reset:k,send:y}))),{messages:u,loading:f,send:y,reset:k}}const P=u.Image,S={pre:e=>{let{children:r}=e;const t=a(null);return j(K,{ref:t,children:[w(H,{tooltip:!1,content:()=>{const e=t.current?.getElementsByTagName("code");return e?.[0]?.innerText||""}}),r]})},a:e=>{let{node:r,href:t,...o}=e;const n=t?.startsWith("http")?"_blank":"_self";return w("a",{...o,href:t,target:n})},img:e=>{let{node:r,...t}=e;return w(P,{...t})}},B=[[$,{singleDollarTextMath:!1}],E,M],U=[q,[C,{detect:!1,ignoreMissing:!0}]],I=n((e=>{let{content:r,components:t}=e;return r=r.replace(/\\\(\s(.+?)\s\\\)/g,"$$$$ $1 $$$$"),w(X,{remarkPlugins:B,rehypePlugins:U,components:i((()=>({...S,...t})),[t]),children:r})})),H=g(f)`
2
2
  position: absolute;
3
3
  right: 10px;
4
4
  top: 1em;
@@ -18,17 +18,17 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
18
18
  &:hover {
19
19
  opacity: 1;
20
20
  }
21
- `,H=g.pre`
21
+ `,K=g.pre`
22
22
  position: relative;
23
23
 
24
24
  &:hover {
25
- ${I} {
25
+ ${H} {
26
26
  pointer-events: all;
27
27
  transform: translateX(0px);
28
28
  opacity: 0.5;
29
29
  }
30
30
  }
31
- `,K=g(z)`
31
+ `,X=g(z)`
32
32
  -ms-text-size-adjust: 100%;
33
33
  -webkit-text-size-adjust: 100%;
34
34
  line-height: 1.8;
@@ -298,7 +298,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
298
298
  .hljs-strong {
299
299
  font-weight: 700;
300
300
  }
301
- `,X=s(null);function J(){const e=l(X);if(!e)throw new Error("useContext must be used within a Provider");return e}function W(e){let{children:r,...t}=e;return w(X.Provider,{value:t,children:r})}const G=u.Image;function Q(e){let{src:r,...t}=e;const{imageResolver:o}=J();return o&&r&&(r=o(r)),w(V,{children:w(G,{src:r,...t})})}const V=g.div`
301
+ `,J=s(null);function W(){const e=l(J);if(!e)throw new Error("useContext must be used within a Provider");return e}function G(e){let{children:r,...t}=e;return w(J.Provider,{value:t,children:r})}const Q=u.Image;function V(e){let{src:r,...t}=e;const{imageResolver:o}=W();return o&&r&&(r=o(r)),w(Y,{children:w(Q,{src:r,...t})})}const Y=g.div`
302
302
  margin-bottom: .5rem;
303
303
  margin-top: .5rem;
304
304
  border: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
@@ -323,9 +323,9 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
323
323
  max-height: 100%;
324
324
  max-width: 100%;
325
325
  }
326
- `;function Y(e){let{tool:r}=e;const[o,n]=t(!1),{logLevel:i="none"}=J();let a=null;r.content&&("string"==typeof r.content?a=w(U,{content:r.content}):"image"===r.content.type&&(a=w(Q,{src:r.content.image})));const s="response"in r;return j(c,{children:["stats"==i&&w("div",{className:"mb-2",children:j("div",{role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}):w(F,{animation:"border",variant:"primary",size:"sm"}),w("span",{className:"text-muted",children:s?"已使用":"正在使用"}),w("span",{children:r.title})]})}),"all"==i&&w("div",{className:"mb-2",children:j("div",o&&s?{className:"shadow-sm rounded bg-white fs-7",children:[j("div",{onClick:()=>n(!1),role:"button",className:"d-flex align-items-center p-1 px-2 gap-2",children:[r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}),w("span",{className:"text-muted",children:"已使用"}),w("span",{children:r.title}),w("i",{className:"bi bi-caret-up-fill text-muted"})]}),j("div",{className:"border-top p-2 d-flex flex-column gap-2",children:[j("div",{className:"border rounded bg-light",children:[w("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:w("span",{className:"text-muted",children:"参数"})}),w("div",{className:"border-top p-2 overflow-hidden",children:r.arguments})]}),j("div",{className:"border rounded bg-light",children:[w("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:w("span",{className:"text-muted",children:"响应"})}),w(Z,{className:"border-top p-2 overflow-hidden",children:r.response||"None"})]})]})]}:{onClick:()=>n(s),role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}):w(F,{animation:"border",variant:"primary",size:"sm"}),w("span",{className:"text-muted",children:s?"已使用":"正在使用"}),w("span",{children:r.title}),s&&w("i",{className:"bi bi-caret-down-fill text-muted"})]})}),a]})}const Z=g.div`
326
+ `;function Z(e){let{tool:r}=e;const[o,n]=t(!1),{logLevel:i="none"}=W();let a=null;r.content&&("string"==typeof r.content?a=w(I,{content:r.content}):"image"===r.content.type&&(a=w(V,{src:r.content.image})));const s="response"in r;return j(c,{children:["stats"==i&&w("div",{className:"mb-2",children:j("div",{role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}):w(F,{animation:"border",variant:"primary",size:"sm"}),w("span",{className:"text-muted",children:s?"已使用":"正在使用"}),w("span",{children:r.title})]})}),"all"==i&&w("div",{className:"mb-2",children:j("div",o&&s?{className:"shadow-sm rounded bg-white fs-7",children:[j("div",{onClick:()=>n(!1),role:"button",className:"d-flex align-items-center p-1 px-2 gap-2",children:[r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}),w("span",{className:"text-muted",children:"已使用"}),w("span",{children:r.title}),w("i",{className:"bi bi-caret-up-fill text-muted"})]}),j("div",{className:"border-top p-2 d-flex flex-column gap-2",children:[j("div",{className:"border rounded bg-light",children:[w("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:w("span",{className:"text-muted",children:"参数"})}),w("div",{className:"border-top p-2 overflow-hidden",children:r.arguments})]}),j("div",{className:"border rounded bg-light",children:[w("div",{className:"d-flex align-items-center p-1 px-2 fs-7 gap-2",children:w("span",{className:"text-muted",children:"响应"})}),w(ee,{className:"border-top p-2 overflow-hidden",children:r.response||"None"})]})]})]}:{onClick:()=>n(s),role:"button",className:"d-inline-flex align-items-center shadow-sm rounded bg-white p-1 px-2 fs-7 gap-2",children:[s?r.error?w("i",{className:"bi bi-x-circle-fill text-danger"}):w("i",{className:"bi bi-check-circle-fill text-success"}):w(F,{animation:"border",variant:"primary",size:"sm"}),w("span",{className:"text-muted",children:s?"已使用":"正在使用"}),w("span",{children:r.title}),s&&w("i",{className:"bi bi-caret-down-fill text-muted"})]})}),a]})}const ee=g.div`
327
327
  white-space: pre-wrap;
328
- `;var ee,re,te;function oe(){return oe=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},oe.apply(this,arguments)}const ne=r=>e.createElement("svg",oe({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},r),ee||(ee=e.createElement("circle",{cx:15,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))),re||(re=e.createElement("circle",{cx:60,cy:15,r:9,fill:"#3c60ff",fillOpacity:.3},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:9,repeatCount:"indefinite",to:9,values:"9;15;9"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:.5,repeatCount:"indefinite",to:.5,values:".5;1;.5"}))),te||(te=e.createElement("circle",{cx:105,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))));const ie=function(e){let{ext:r}=e;const{result:t}=y((async e=>(await function(e){switch(e){case"../../images/file/docx.svg":return import("./docx-nWXnlyT_.js");case"../../images/file/jpg.svg":return import("./jpg-6tBxSzWk.js");case"../../images/file/md.svg":return import("./md-GZ3HJPcw.js");case"../../images/file/pdf.svg":return import("./pdf-pVX1_E6T.js");case"../../images/file/png.svg":return import("./png-u0o1NMqQ.js");case"../../images/file/pptx.svg":return import("./pptx-Hprz0cON.js");case"../../images/file/txt.svg":return import("./txt-eHeCpvNO.js");case"../../images/file/xlsx.svg":return import("./xlsx-uOft-SV2.js");default:return new Promise((function(r,t){("function"==typeof queueMicrotask?queueMicrotask:setTimeout)(t.bind(null,new Error("Unknown variable dynamic import: "+e)))}))}}(`../../images/file/${e}.svg`)).default),[r]);return t?w("img",{width:30,height:30,src:t}):null};function ae(e){let{className:r,name:t,size:o,loading:n,error:i,onRemove:a}=e;const s=_.extname(t).substring(1),l=j(de,{className:r,$error:!!i,children:[j(ce,{children:[w(ie,{ext:s}),n&&w(F,{variant:"primary"})]}),j(le,{children:[w("h4",{children:t}),w("p",{children:v(o,1)})]}),a&&w(se,{onClick:e=>{e.preventDefault(),a()},children:w("i",{className:"bi bi-trash3"})})]});return i?w(x,{placement:"top",tooltip:i,children:l}):l}const se=g.div`
328
+ `;var re,te,oe;function ne(){return ne=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},ne.apply(this,arguments)}const ie=r=>e.createElement("svg",ne({xmlns:"http://www.w3.org/2000/svg",width:20,height:10,fill:"#fff",viewBox:"0 0 120 30"},r),re||(re=e.createElement("circle",{cx:15,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))),te||(te=e.createElement("circle",{cx:60,cy:15,r:9,fill:"#3c60ff",fillOpacity:.3},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:9,repeatCount:"indefinite",to:9,values:"9;15;9"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:.5,repeatCount:"indefinite",to:.5,values:".5;1;.5"}))),oe||(oe=e.createElement("circle",{cx:105,cy:15,r:15,fill:"#3c60ff"},e.createElement("animate",{attributeName:"r",begin:"0s",calcMode:"linear",dur:"0.8s",from:15,repeatCount:"indefinite",to:15,values:"15;9;15"}),e.createElement("animate",{attributeName:"fill-opacity",begin:"0s",calcMode:"linear",dur:"0.8s",from:1,repeatCount:"indefinite",to:1,values:"1;.5;1"}))));const ae=function(e){let{ext:r}=e;const{result:t}=y((async e=>(await function(e){switch(e){case"../../images/file/docx.svg":return import("./docx-nWXnlyT_.js");case"../../images/file/jpg.svg":return import("./jpg-6tBxSzWk.js");case"../../images/file/md.svg":return import("./md-GZ3HJPcw.js");case"../../images/file/pdf.svg":return import("./pdf-pVX1_E6T.js");case"../../images/file/png.svg":return import("./png-u0o1NMqQ.js");case"../../images/file/pptx.svg":return import("./pptx-Hprz0cON.js");case"../../images/file/txt.svg":return import("./txt-eHeCpvNO.js");case"../../images/file/xlsx.svg":return import("./xlsx-uOft-SV2.js");default:return new Promise((function(r,t){("function"==typeof queueMicrotask?queueMicrotask:setTimeout)(t.bind(null,new Error("Unknown variable dynamic import: "+e)))}))}}(`../../images/file/${e}.svg`)).default),[r]);return t?w("img",{width:30,height:30,src:t}):null};function se(e){let{className:r,name:t,size:o,loading:n,error:i,onRemove:a}=e;const s=_.extname(t).substring(1),l=j(me,{className:r,$error:!!i,children:[j(de,{children:[w(ae,{ext:s}),n&&w(F,{variant:"primary"})]}),j(ce,{children:[w("h4",{children:t}),w("p",{children:v(o,1)})]}),a&&w(le,{onClick:e=>{e.preventDefault(),a()},children:w("i",{className:"bi bi-trash3"})})]});return i?w(x,{placement:"top",tooltip:i,children:l}):l}const le=g.div`
329
329
  width: 1.75rem;
330
330
  height: 1.75rem;
331
331
  align-items: center;
@@ -340,7 +340,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
340
340
  color: var(--bs-danger);
341
341
  background-color: var(--bs-danger-bg-subtle);
342
342
  }
343
- `,le=g.div`
343
+ `,ce=g.div`
344
344
  flex: 1;
345
345
  overflow: hidden;
346
346
 
@@ -361,7 +361,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
361
361
  line-height: 20px;
362
362
  margin-bottom: 0;
363
363
  }
364
- `,ce=g.div`
364
+ `,de=g.div`
365
365
  position: relative;
366
366
  width: 3rem;
367
367
  height: 3rem;
@@ -375,7 +375,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
375
375
  position: absolute;
376
376
  }
377
377
 
378
- `,de=g.div`
378
+ `,me=g.div`
379
379
  display: flex;
380
380
  gap: .5rem;
381
381
  padding: .5rem;
@@ -391,7 +391,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
391
391
  ${e=>e.$error&&b`
392
392
  border-color: var(--bs-danger) !important;
393
393
  `}
394
- `,me=n((e=>{let{message:r}=e;const{query:t,files:o=[],chunks:n}=r,{user:i,bot:a,logLevel:s="none"}=J();return j(N,{children:[(t||o.length>0)&&j(ve,{$reverse:!0,children:[i&&w(fe,{children:w("img",{src:i.avatar})}),j(be,{children:[t&&w(U,{content:t}),o.length>0&&o.map(((e,r)=>{let{name:t,size:o,path:n}=e;return k(n)?w(Q,{src:`/uploads/${n}`},r):w(he,{children:w(ae,{name:t,size:o})},r)}))]})]}),n&&j(ve,{children:[w(fe,{children:w("img",{src:a.avatar})}),j(be,{children:[r.query&&w(ue,{children:w(f,{placement:"top",content:n.reduce((function(e,r){return e+r.content+"\n"+r.tools.reduce(((e,r)=>r.content&&"string"==typeof r.content?e+r.content+"\n":e),"")}),""),as:pe})}),w(ge,{children:["stats","all"].includes(s)&&r.stats&&j(N,{children:[j("span",{children:["耗时 ",r.stats.latency/1e3," 秒"]}),j("span",{children:["花费 Token ",r.stats.usage]})]})}),n.length>0&&n.map(((e,r)=>j(c,{children:[e.content&&w(U,{content:e.content}),e.tools.map(((e,r)=>w(Y,{tool:e},r))),e.error&&w(U,{content:`[${e.error}]`})]},r))),r.loading&&w(ne,{})]})]})]})})),he=g.div`
394
+ `,he=n((e=>{let{message:r}=e;const{query:t,files:o=[],chunks:n}=r,{user:i,bot:a,logLevel:s="none"}=W();return j(N,{children:[(t||o.length>0)&&j(xe,{$reverse:!0,children:[i&&w(be,{children:w("img",{src:i.avatar})}),j(ve,{children:[t&&w(I,{content:t}),o.length>0&&o.map(((e,r)=>{let{name:t,size:o,path:n}=e;return k(n)?w(V,{src:`/uploads/${n}`},r):w(pe,{children:w(se,{name:t,size:o})},r)}))]})]}),n&&j(xe,{children:[w(be,{children:w("img",{src:a.avatar})}),j(ve,{children:[r.query&&w(ge,{children:w(f,{placement:"top",content:n.reduce((function(e,r){return e+r.content+"\n"+r.tools.reduce(((e,r)=>r.content&&"string"==typeof r.content?e+r.content+"\n":e),"")}),""),as:ue})}),w(fe,{children:["stats","all"].includes(s)&&r.stats&&j(N,{children:[j("span",{children:["耗时 ",r.stats.latency/1e3," 秒"]}),j("span",{children:["花费 Token ",r.stats.usage]})]})}),n.length>0&&n.map(((e,r)=>j(c,{children:[e.content&&w(I,{content:e.content}),e.tools.map(((e,r)=>w(Z,{tool:e},r))),e.error&&w(I,{content:`[${e.error}]`})]},r))),r.loading&&w(ie,{})]})]})]})})),pe=g.div`
395
395
  width: 100%;
396
396
  margin-bottom: .5rem;
397
397
  margin-top: .5rem;
@@ -403,7 +403,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
403
403
  &:last-child {
404
404
  margin-bottom: 0;
405
405
  }
406
- `,pe=g.div`
406
+ `,ue=g.div`
407
407
  align-items: center;
408
408
  justify-content: center;
409
409
  border-radius: .375rem;
@@ -427,7 +427,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
427
427
  background-color: var(--bs-gray-200);
428
428
  }
429
429
  }
430
- `,ue=g.div`
430
+ `,ge=g.div`
431
431
  position: absolute;
432
432
  top: -1.1rem;
433
433
  right: 0;
@@ -435,7 +435,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
435
435
  gap: .25rem;
436
436
  opacity: 0;
437
437
  z-index: 1;
438
- `,ge=g.div`
438
+ `,fe=g.div`
439
439
  position: absolute;
440
440
  bottom: -1.4rem;
441
441
  left: 0;
@@ -448,7 +448,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
448
448
  display: flex;
449
449
  opacity: 0;
450
450
  z-index: 1;
451
- `,fe=g.div`
451
+ `,be=g.div`
452
452
  width: 35px;
453
453
  height: 35px;
454
454
  border-radius: 50%;
@@ -458,7 +458,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
458
458
  width: 100%;
459
459
  height: 100%;
460
460
  }
461
- `,be=g.div`
461
+ `,ve=g.div`
462
462
  padding: .875rem;
463
463
  background-color: rgb(243, 243, 243);
464
464
  border-radius: var(--bs-border-radius-lg);
@@ -478,18 +478,18 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
478
478
  }
479
479
 
480
480
  &:hover {
481
- ${ge}, ${ue} {
481
+ ${fe}, ${ge} {
482
482
  opacity: 1;
483
483
  }
484
484
  }
485
- `,ve=g.div`
485
+ `,xe=g.div`
486
486
  display: flex;
487
487
  justify-content: flex-start;
488
488
  padding: 1rem 0 1rem 0;
489
489
  ${e=>e.$reverse&&b`
490
490
  flex-direction: row-reverse;
491
491
 
492
- ${be} {
492
+ ${ve} {
493
493
  background: rgba(var(--bs-primary-rgb), 0.1);
494
494
  margin-right: 10px;
495
495
  margin-left: 0;
@@ -504,15 +504,15 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
504
504
  }
505
505
  }
506
506
  `};
507
- `,xe=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function ye(e){let{chat:o,fileTypes:n,scrollRef:i,onMessages:s,minRows:l,toolbar:c,disabled:u}=e;const g=a(null),f=a(null),[b,v]=t(""),[y,k]=m([]),[N,z]=t(!1),$=n&&n.length>0?n:xe,{loading:M,messages:E,send:q}=A({...o,onSuccess(){requestAnimationFrame((()=>{g.current?.focus()})),o.onSuccess?.()}});d((()=>{s(E)}),[E]),d((()=>{!n&&y.length>0&&k([])}),[n]),d((()=>{const e=i.current;if(e&&q){const r=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),q(e.target.text))};return e.addEventListener("click",r),()=>{e.removeEventListener("click",r)}}}),[i,q]);const C=r((e=>{let{target:r}=e;if(r.files){const e=Array.from(r.files).filter((e=>!!$.includes(R.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-y.length);k((r=>{r.push(...e.map((e=>({file:e}))))})),e.forEach((async e=>{try{const r=new FormData;r.set("file",e);const t=await h({method:"POST",url:`${o.url}/upload`,transformRequest:o.transformRequest,data:r});k((r=>{const o=r.find((r=>r.file===e));o&&(o.path=t.path)}))}catch(r){const t=p(r)?r.message:"unknown error";k((r=>{const o=r.find((r=>r.file===e));o&&(o.error=t)}))}}))}r.value=""}),[y,$]),F=y.flatMap((e=>{let{file:r,path:t}=e;return t?[{name:r.name,size:r.size,path:t}]:[]})),_=()=>{(b||F.length>0)&&(q(b,F),v(""),k([]))};return j($e,{children:[c,j(ze,{$focused:N&&!M,children:[y.length>0&&w(we,{children:y.map(((e,r)=>{let{file:t,error:o,path:n}=e;const i=void 0===o&&void 0===n;return w(ke,{name:t.name,size:t.size,error:o,loading:i,onRemove:()=>{k((e=>{const r=e.findIndex((e=>e.file===t));-1!==r&&e.splice(r,1)}))}},r)}))}),j(Ne,{children:[w(O,{disabled:M||u,ref:g,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:l,maxRows:5,value:b,onChange:e=>v(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),_())},onFocus:()=>z(!0),onBlur:()=>z(!1)}),n&&w(x,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:j(je,{disabled:y.length>=6,onClick:()=>f.current?.click(),children:[w("input",{onChange:C,multiple:!0,accept:$.join(","),ref:f,type:"file",hidden:!0}),w("i",{className:"bi bi-file-earmark-arrow-up"})]})}),w(je,{className:"text-primary",disabled:!b&&0===F.length,onClick:e=>{e.preventDefault(),_()},children:w("i",{className:"bi bi-send-fill"})})]})]})]})}const ke=g(ae)`
507
+ `,ye=[".txt",".md",".pdf",".docx",".xlsx",".pptx",".png",".jpg"];function ke(e){let{chat:o,fileTypes:n,scrollRef:i,onMessages:s,minRows:l,toolbar:c,disabled:u,onLoading:g}=e;const f=a(null),b=a(null),[v,y]=t(""),[k,N]=m([]),[z,$]=t(!1),M=n&&n.length>0?n:ye,{loading:E,messages:q,send:C}=A({...o,onSuccess(){requestAnimationFrame((()=>{f.current?.focus()})),o.onSuccess?.()}});d((()=>{s(q)}),[q]),d((()=>{g?.(E)}),[E]),d((()=>{!n&&k.length>0&&N([])}),[n]),d((()=>{const e=i.current;if(e&&C){const r=e=>{e.target instanceof HTMLAnchorElement&&"#!question"===e.target.hash&&(e.preventDefault(),C(e.target.text))};return e.addEventListener("click",r),()=>{e.removeEventListener("click",r)}}}),[i,C]);const F=r((e=>{let{target:r}=e;if(r.files){const e=Array.from(r.files).filter((e=>!!M.includes(R.extname(e.name))&&(!(e.size>20971520)&&e))).slice(0,6-k.length);N((r=>{r.push(...e.map((e=>({file:e}))))})),e.forEach((async e=>{try{const r=new FormData;r.set("file",e);let t={method:"POST",url:`${o.url}/upload`,data:r};o.transformRequest&&(t=o.transformRequest("upload",t));const n=await h(t);N((r=>{const t=r.find((r=>r.file===e));t&&(t.path=n.path)}))}catch(r){const t=p(r)?r.message:"unknown error";N((r=>{const o=r.find((r=>r.file===e));o&&(o.error=t)}))}}))}r.value=""}),[k,M]),_=k.flatMap((e=>{let{file:r,path:t}=e;return t?[{name:r.name,size:r.size,path:t}]:[]})),O=()=>{(v||_.length>0)&&(C(v,_),y(""),N([]))};return j(Me,{children:[c,j($e,{$focused:z&&!E,children:[k.length>0&&w(je,{children:k.map(((e,r)=>{let{file:t,error:o,path:n}=e;const i=void 0===o&&void 0===n;return w(we,{name:t.name,size:t.size,error:o,loading:i,onRemove:()=>{N((e=>{const r=e.findIndex((e=>e.file===t));-1!==r&&e.splice(r,1)}))}},r)}))}),j(ze,{children:[w(L,{disabled:E||u,ref:f,placeholder:"请输入你的问题, Enter+Shift换行, Enter发送",minRows:l,maxRows:5,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),O())},onFocus:()=>$(!0),onBlur:()=>$(!1)}),n&&w(x,{tooltip:"可上传不超过6个小于20MB的文件",placement:"top",children:j(Ne,{disabled:k.length>=6,onClick:()=>b.current?.click(),children:[w("input",{onChange:F,multiple:!0,accept:M.join(","),ref:b,type:"file",hidden:!0}),w("i",{className:"bi bi-file-earmark-arrow-up"})]})}),w(Ne,{className:"text-primary",disabled:!v&&0===_.length,onClick:e=>{e.preventDefault(),O()},children:w("i",{className:"bi bi-send-fill"})})]})]})]})}const we=g(se)`
508
508
  width: calc((100% - .75rem) / 2);
509
- `,we=g.div`
509
+ `,je=g.div`
510
510
  display: flex;
511
511
  flex-wrap: wrap;
512
512
  padding: .75rem;
513
513
  gap: .75rem;
514
514
  border-bottom: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
515
- `,je=g.button`
515
+ `,Ne=g.button`
516
516
  color: var(--bs-secondary);
517
517
  cursor: pointer;
518
518
  display: flex;
@@ -534,7 +534,7 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
534
534
  background-color: var(--bs-gray-200);
535
535
  }
536
536
 
537
- `,Ne=g.div`
537
+ `,ze=g.div`
538
538
  display: flex;
539
539
  padding: .5rem .5rem .5rem 1rem;
540
540
  gap: .25rem;
@@ -551,26 +551,26 @@ import*as e from"react";import{useCallback as r,useState as t,useImperativeHandl
551
551
  color: rgba(54, 54, 54, .3);
552
552
  }
553
553
  }
554
- `,ze=g.div`
554
+ `,$e=g.div`
555
555
  background: #FFF;
556
556
  border: var(--bs-border-width) var(--bs-border-style) ${e=>e.$focused?"var(--bs-primary)":"var(--bs-border-color)"};
557
557
  border-radius: var(--bs-border-radius-lg);
558
558
  box-shadow: 0.125rem 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
559
- `,$e=g.div`
559
+ `,Me=g.div`
560
560
  margin: 0 1rem 1rem;
561
- `;function Me(e){let{className:o,bot:n,user:i,input:s,logLevel:l,imageResolver:c,placeholder:m,...h}=e;const[p,g]=t(h.messages||[]),f=a(null),b=r((()=>{const e=f.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:v,height:x}=T();return d((()=>{b()}),[x]),w(W,{bot:n,user:i,logLevel:l,imageResolver:c,children:w(Ce,{className:o,children:j(u,{children:[w(Ee,{ref:f,children:j(qe,{ref:v,children:[0===p.length&&m,p.map(((e,r)=>w(me,{message:e},r)))]})}),s&&w(ye,{onMessages:g,scrollRef:f,...s})]})})})}const Ee=g.div`
561
+ `;function Ee(e){let{className:o,bot:n,user:i,input:s,logLevel:l,imageResolver:c,placeholder:m,...h}=e;const[p,g]=t((()=>D(h.messages||[]))),[f,b]=t(!1),v=a(!s),x=a(null),y=r((()=>{const e=x.current;e&&requestAnimationFrame((()=>{e.scrollTo({top:e.scrollHeight})}))}),[]),{ref:k,height:N}=O();return d((()=>{!f&&v.current||(f&&(v.current=!0),y())}),[N,f,v]),w(G,{bot:n,user:i,logLevel:l,imageResolver:c,children:w(Fe,{className:o,children:j(u,{children:[w(qe,{ref:x,children:j(Ce,{ref:k,children:[0===p.length&&m,p.map(((e,r)=>w(he,{message:e},r)))]})}),s&&w(ke,{onMessages:g,scrollRef:x,onLoading:b,...s})]})})})}const qe=g.div`
562
562
  display: flex;
563
563
  flex-direction: column;
564
564
  flex: 1;
565
565
  overflow-y: auto;
566
566
  padding: 0 1rem;
567
567
  margin-bottom: .5rem;
568
- `,qe=g.div`
568
+ `,Ce=g.div`
569
569
  display: flex;
570
570
  flex-direction: column;
571
571
  flex: 1;
572
- `,Ce=g.div`
572
+ `,Fe=g.div`
573
573
  display: flex;
574
574
  flex-direction: column;
575
575
  height: 100%;
576
- `;export{Me as MessageBox,D as pickQuestions,A as useChat};
576
+ `;export{Ee as MessageBox,T as pickQuestions,A as useChat};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@topthink/chat",
3
- "version": "1.0.19",
3
+ "version": "1.0.20",
4
4
  "scripts": {
5
5
  "prebuild": "rimraf es types",
6
6
  "build": "rollup -c --environment NODE_ENV:production",
@@ -56,5 +56,5 @@
56
56
  },
57
57
  "author": "yunwuxin <tzzhangyajun@qq.com> (https://github.com/yunwuxin)",
58
58
  "license": "MIT",
59
- "gitHead": "470b6d29bbebf5e813ed0384be448ec30aa3ea92"
59
+ "gitHead": "c7b420302fcaf4f83e893be80f0a9751e6de846a"
60
60
  }
@@ -1,5 +1,5 @@
1
1
  import { ReactNode } from 'react';
2
- import { LogLevel, Message } from '../../types';
2
+ import { ConversationMessage, LogLevel } from '../../types';
3
3
  import { ChatOptions } from '../../hooks/use-chat';
4
4
  interface Props {
5
5
  className?: string;
@@ -11,7 +11,7 @@ interface Props {
11
11
  name: string;
12
12
  avatar: string;
13
13
  };
14
- messages?: Message[];
14
+ messages?: ConversationMessage[];
15
15
  placeholder?: ReactNode;
16
16
  logLevel?: LogLevel;
17
17
  imageResolver?: (url: string) => string;
@@ -9,6 +9,7 @@ interface Props {
9
9
  onMessages: (messages: Message[]) => void;
10
10
  toolbar?: ReactNode;
11
11
  disabled?: boolean;
12
+ onLoading?: (loading: boolean) => void;
12
13
  }
13
- export default function ({ chat, fileTypes, scrollRef, onMessages, minRows, toolbar, disabled }: Props): JSX.Element;
14
+ export default function ({ chat, fileTypes, scrollRef, onMessages, minRows, toolbar, disabled, onLoading }: Props): JSX.Element;
14
15
  export {};
@@ -3,7 +3,7 @@ import { Chat, Conversation, Message } from '../types';
3
3
  import { RequestConfig } from '@topthink/components';
4
4
  export interface ChatOptions {
5
5
  url: string;
6
- transformRequest?: Exclude<RequestConfig, string>['transformRequest'];
6
+ transformRequest?: (scene: 'chat' | 'upload', config: RequestConfig) => RequestConfig;
7
7
  onSuccess?: () => void;
8
8
  onboarding?: {
9
9
  enable?: boolean;
@@ -13,7 +13,7 @@ export interface ChatOptions {
13
13
  conversation?: Conversation;
14
14
  ref?: MutableRefObject<Chat | null>;
15
15
  }
16
- export default function useChat({ url, transformRequest, onboarding, onSuccess, ref, ...props }: ChatOptions): {
16
+ export default function useChat({ url, onboarding, onSuccess, ref, transformRequest, ...props }: ChatOptions): {
17
17
  messages: Message[];
18
18
  loading: boolean;
19
19
  send: (query: string, files?: Message['files']) => Promise<void>;
package/types/types.d.ts CHANGED
@@ -13,6 +13,7 @@ export interface ToolMessage {
13
13
  image: string;
14
14
  };
15
15
  }
16
+ export type LogLevel = 'stats' | 'all' | 'none';
16
17
  export interface Message {
17
18
  query?: string;
18
19
  files?: {
@@ -31,8 +32,18 @@ export interface Message {
31
32
  };
32
33
  loading?: boolean;
33
34
  }
34
- export type LogLevel = 'stats' | 'all' | 'none';
35
35
  export interface Conversation {
36
36
  id: string;
37
- messages: Message[];
37
+ messages?: ConversationMessage[];
38
+ }
39
+ export interface ConversationMessage {
40
+ query: string;
41
+ files: [];
42
+ chunks: {
43
+ content?: '';
44
+ error?: string;
45
+ tools?: ToolMessage[];
46
+ }[];
47
+ usage: number;
48
+ latency: number;
38
49
  }
@@ -0,0 +1,2 @@
1
+ import { ConversationMessage, Message } from '../types';
2
+ export default function transformMessages(messages: ConversationMessage[]): Message[];