Commit f43ec02b by 李伟康

chore(project): 初始化项目配置文件

- 添加 .dockerignore 文件用于忽略 Docker 构建时的特定文件和目录
- 添加 .editorconfig 文件统一代码编辑器配置,包括换行符、缩进等设置
- 添加 .env.example 文件作为环境变量配置模板
- 添加 .eslintrc.json 文件配置 ESLint 规则继承
- 添加 .gitignore 文件忽略版本控制中的临时文件和依赖目录
- 添加 .prettierrc 文件配置 Prettier 代码格式化规则
- 添加 .stylelintrc.json 文件配置 Stylelint 样式检查规则
- 添加 .unimportedrc.json 文件配置未使用依赖检查规则
0 parents
Showing 1000 changed files with 4842 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

.env
.env.*
# Logs
logs
*.log*
# node
node_modules
.husky
.next
# vscode
.vscode
# webstorm
.idea
*.iml
*.iws
*.ipr
# Jetbrains
.idea
\ No newline at end of file \ No newline at end of file
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,tsx}]
charset = utf-8
indent_style = space
indent_size = 2
# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2
# For production release, change this to PRODUCTION
# NEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT
# # The deployment edition, SELF_HOSTED
# NEXT_PUBLIC_EDITION=SELF_HOSTED
# # The base URL of console application, refers to the Console base URL of WEB service if console domain is
# # different from api or web app domain.
# # example: http://cloud.dify.ai/console/api
# NEXT_PUBLIC_API_PREFIX=http://192.168.3.241/console/api
# # The URL for Web APP, refers to the Web App base URL of WEB service if web app domain is different from
# # console or api domain.
# # example: http://udify.app/api
# NEXT_PUBLIC_PUBLIC_API_PREFIX=http://192.168.3.241/v1
# # The API PREFIX for MARKETPLACE
# NEXT_PUBLIC_MARKETPLACE_API_PREFIX=https://marketplace.dify.ai/api/v1
# # The URL for MARKETPLACE
# NEXT_PUBLIC_MARKETPLACE_URL_PREFIX=https://marketplace.dify.ai
# SENTRY
# NEXT_PUBLIC_SENTRY_DSN=https://90ddfaad2eac44f3b25cd4298ae7af14@sentry.glsx.com.cn/45
# Disable Next.js Telemetry (https://nextjs.org/telemetry)
# NEXT_TELEMETRY_DISABLED=1
# # Disable Upload Image as WebApp icon default is false
# NEXT_PUBLIC_UPLOAD_IMAGE_AS_ICON=false
# # The timeout for the text generation in millisecond
# NEXT_PUBLIC_TEXT_GENERATION_TIMEOUT_MS=60000
# # CSP https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
# NEXT_PUBLIC_CSP_WHITELIST=
# # Github Access Token, used for invoking Github API
# NEXT_PUBLIC_GITHUB_ACCESS_TOKEN=
# # The maximum number of top-k value for RAG.
# NEXT_PUBLIC_TOP_K_MAX_VALUE=10
# # The maximum number of tokens for segmentation
# NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH=4000
# # Maximum loop count in the workflow
# NEXT_PUBLIC_LOOP_NODE_MAX_COUNT=100
# # Maximum number of tools in the agent/workflow
# NEXT_PUBLIC_MAX_TOOLS_NUM=10
# # Maximum number of Parallelism branches in the workflow
# NEXT_PUBLIC_MAX_PARALLEL_LIMIT=10
# # The maximum number of iterations for agent setting
# NEXT_PUBLIC_MAX_ITERATIONS_NUM=5
{
"extends":["next/core-web-vitals","eslint:recommended","plugin:react/recommended", "prettier"]
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
/.history
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# npm
package-lock.json
# yarn
.pnp.cjs
.pnp.loader.mjs
.yarn/
.favorites.json
# storybook
/storybook-static
*storybook.log
# mise
mise.toml
#!/bin/sh
# get the list of modified files
files=$(git diff --cached --name-only)
# check if api or web directory is modified
api_modified=false
web_modified=false
for file in $files
do
# Use POSIX compliant pattern matching
case "$file" in
api/*.py)
# set api_modified flag to true
api_modified=true
;;
web/*)
# set web_modified flag to true
web_modified=true
;;
esac
done
# run linters based on the modified modules
if $api_modified; then
echo "Running Ruff linter on api module"
# python style checks rely on `ruff` in path
if ! command -v ruff > /dev/null 2>&1; then
echo "Installing linting tools (Ruff, dotenv-linter ...) ..."
poetry install -C api --only lint
fi
# run Ruff linter auto-fixing
ruff check --fix ./api
# run Ruff linter checks
ruff check ./api || status=$?
status=${status:-0}
if [ $status -ne 0 ]; then
echo "Ruff linter on api module error, exit code: $status"
echo "Please run 'dev/reformat' to fix the fixable linting errors."
exit 1
fi
fi
if $web_modified; then
echo "Running ESLint on web module"
cd ./web || exit 1
lint-staged
echo "Running unit tests check"
modified_files=$(git diff --cached --name-only -- utils | grep -v '\.spec\.ts$' || true)
if [ -n "$modified_files" ]; then
for file in $modified_files; do
test_file="${file%.*}.spec.ts"
echo "Checking for test file: $test_file"
# check if the test file exists
if [ -f "../$test_file" ]; then
echo "Detected changes in $file, running corresponding unit tests..."
pnpm run test "../$test_file"
if [ $? -ne 0 ]; then
echo "Unit tests failed. Please fix the errors before committing."
exit 1
fi
echo "Unit tests for $file passed."
else
echo "Warning: $file does not have a corresponding test file."
fi
done
echo "All unit tests for modified web/utils files have passed."
fi
cd ../
fi
{
"printWidth": 120,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "all",
"semi": false,
"wrap_line_length": 120,
"wrap_attributes": "auto",
"proseWrap": "always",
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"jsxBracketSameLine": true,
"files.insertFinalNewline": true,
"prettier.ignorePath": ".prettierignore",
"useTabs": false,
"eslintIntegration": false,
"overrides": [
{
"files": ".prettierrc",
"options": {
"parser": "json"
}
}
],
"endOfLine": "auto"
}
import type { StorybookConfig } from '@storybook/nextjs'
const config: StorybookConfig = {
// stories: ['../stories/**/*.mdx', '../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
stories: ['../app/components/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [
'@storybook/addon-onboarding',
'@storybook/addon-links',
'@storybook/addon-essentials',
'@chromatic-com/storybook',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/nextjs',
options: {},
},
staticDirs: ['../public'],
}
export default config
import React from 'react'
import type { Preview } from '@storybook/react'
import { withThemeByDataAttribute } from '@storybook/addon-themes'
import I18nServer from '../app/components/i18n-server'
import '../app/styles/globals.css'
import '../app/styles/markdown.scss'
import './storybook.css'
export const decorators = [
withThemeByDataAttribute({
themes: {
light: 'light',
dark: 'dark',
},
defaultTheme: 'light',
attributeName: 'data-theme',
}),
(Story) => {
return <I18nServer>
<Story />
</I18nServer>
},
]
const preview: Preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
}
export default preview
html,
body {
max-width: unset;
overflow: auto;
user-select: text;
}
{
"extends": "stylelint-config-standard-scss"
}
This diff could not be displayed because it is too large.
{
"recommendations": [
"bradlc.vscode-tailwindcss",
"firsttris.vscode-jest-runner"
]
}
{
"prettier.enable": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.format.enable": true,
"[python]": {
"editor.formatOnType": true
},
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
"[javascriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"npm.packageManager": "pnpm"
}
# base image
FROM node:20-alpine3.20 AS base
LABEL maintainer="yangming@didihu.com.cn"
# if you located in China, you can use aliyun mirror to speed up
# RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk add --no-cache tzdata
RUN npm install -g pnpm@10.11.1
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
# install packages
FROM base AS packages
WORKDIR /app/web
COPY package.json .
COPY pnpm-lock.yaml .
# if you located in China, you can use taobao registry to speed up
# RUN pnpm install --frozen-lockfile --registry https://registry.npmmirror.com/
RUN pnpm install --frozen-lockfile --registry https://registry.npmmirror.com/
# build resources
FROM base AS builder
WORKDIR /app/web
COPY --from=packages /app/web/ .
COPY . .
ENV NODE_OPTIONS="--max-old-space-size=4096"
RUN pnpm build
# production stage
FROM base AS production
ENV NODE_ENV=production
ENV EDITION=SELF_HOSTED
ENV DEPLOY_ENV=PRODUCTION
#ENV CONSOLE_API_URL=http://127.0.0.1:5001
#ENV APP_API_URL=http://127.0.0.1:5001
#ENV MARKETPLACE_API_URL=http://127.0.0.1:5001
#ENV MARKETPLACE_URL=http://127.0.0.1:5001
ENV CONSOLE_API_URL=http://192.168.3.241
ENV APP_API_URL=http://192.168.3.241
ENV MARKETPLACE_API_URL=http://192.168.3.241
ENV MARKETPLACE_URL=http://192.168.3.241
ENV PORT=3000
ENV NEXT_TELEMETRY_DISABLED=1
ENV PM2_INSTANCES=2
# set timezone
#ENV TZ=UTC
ENV TZ=Asia/Shanghai
RUN ln -s /usr/share/zoneinfo/${TZ} /etc/localtime \
&& echo ${TZ} > /etc/timezone
WORKDIR /app/web
COPY --from=builder /app/web/public ./public
COPY --from=builder /app/web/.next/standalone ./
COPY --from=builder /app/web/.next/static ./.next/static
COPY docker/entrypoint.sh ./entrypoint.sh
# global runtime packages
RUN pnpm add -g pm2 --registry https://registry.npmmirror.com/\
&& mkdir /.pm2 \
&& chown -R 1001:0 /.pm2 /app/web \
&& chmod -R g=u /.pm2 /app/web
ARG COMMIT_SHA
ENV COMMIT_SHA=${COMMIT_SHA}
USER 1001
EXPOSE 3000
ENTRYPOINT ["/bin/sh", "./entrypoint.sh"]
# Dify Frontend
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
### Run by source code
To start the web frontend service, you will need [Node.js v18.x (LTS)](https://nodejs.org/en) and [pnpm version 9.12.2](https://pnpm.io).
First, install the dependencies:
```bash
pnpm install
```
Then, configure the environment variables. Create a file named `.env.local` in the current directory and copy the contents from `.env.example`. Modify the values of these environment variables according to your requirements:
```bash
cp .env.example .env.local
```
```
# For production release, change this to PRODUCTION
NEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT
# The deployment edition, SELF_HOSTED
NEXT_PUBLIC_EDITION=SELF_HOSTED
# The base URL of console application, refers to the Console base URL of WEB service if console domain is
# different from api or web app domain.
# example: http://cloud.dify.ai/console/api
NEXT_PUBLIC_API_PREFIX=http://localhost:5001/console/api
# The URL for Web APP, refers to the Web App base URL of WEB service if web app domain is different from
# console or api domain.
# example: http://udify.app/api
NEXT_PUBLIC_PUBLIC_API_PREFIX=http://localhost:5001/api
# SENTRY
NEXT_PUBLIC_SENTRY_DSN=
```
Finally, run the development server:
```bash
pnpm run dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the file under folder `app`. The page auto-updates as you edit the file.
## Deploy
### Deploy on server
First, build the app for production:
```bash
pnpm run build
```
Then, start the server:
```bash
pnpm run start
```
If you want to customize the host and port:
```bash
pnpm run start --port=3001 --host=0.0.0.0
```
If you want to customize the number of instances launched by PM2, you can configure `PM2_INSTANCES` in `docker-compose.yaml` or `Dockerfile`.
## Storybook
This project uses [Storybook](https://storybook.js.org/) for UI component development.
To start the storybook server, run:
```bash
pnpm storybook
```
Open [http://localhost:6006](http://localhost:6006) with your browser to see the result.
## Lint Code
If your IDE is VSCode, rename `web/.vscode/settings.example.json` to `web/.vscode/settings.json` for lint code setting.
## Test
We start to use [Jest](https://jestjs.io/) and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) for Unit Testing.
You can create a test file with a suffix of `.spec` beside the file that to be tested. For example, if you want to test a file named `util.ts`. The test file name should be `util.spec.ts`.
Run test:
```bash
pnpm run test
```
If you are not familiar with writing tests, here is some code to refer to:
* [classnames.spec.ts](./utils/classnames.spec.ts)
* [index.spec.tsx](./app/components/base/button/index.spec.tsx)
## Documentation
Visit <https://docs.dify.ai/getting-started/readme> to view the full documentation.
## Community
The Dify community can be found on [Discord community](https://discord.gg/5AEfbxcd9k), where you can ask questions, voice ideas, and share your projects.
File mode changed
'use client'
import React from 'react'
import ChatWithHistoryWrap from '@/app/components/base/chat/chat-with-history'
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
export function useAuthGuard(options?: { allowPublic?: boolean }) {
const router = useRouter()
useEffect(() => {
const checkIsWorkWeChat = () => {
const ua = navigator.userAgent.toLowerCase()
const isWxWork = ua.includes('wxwork')
// if(!isWxWork) router.push('/not-work-wechat')
}
checkIsWorkWeChat()
}, [router, options])
}
const Chat = () => {
useAuthGuard()
return <ChatWithHistoryWrap />
}
export default Chat
'use client'
import React from 'react'
import EmbeddedChatbot from '@/app/components/base/chat/embedded-chatbot'
const Chatbot = () => {
return (
<EmbeddedChatbot />
)
}
export default React.memo(Chatbot)
import React from 'react'
import type { FC } from 'react'
import type { Metadata } from 'next'
export const metadata: Metadata = {
icons: 'data:,', // prevent browser from using default favicon
}
const Layout: FC<{
children: React.ReactNode
}> = ({ children }) => {
return (
<div className="h-full min-w-[300px] pb-[env(safe-area-inset-bottom)] layout-bg">
{children}
</div>
)
}
export default Layout
.container{
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
padding: 0 60px;
height: 100vh;
}
.icon{
width: 160px;
height: 160px;
margin: auto;
}
.title {
color: #0A3479;
text-align: center;
font-size: 14px;
margin-bottom: 4px;
}
.description {
color: rgba(10, 52, 121, 0.60);
text-align: center;
font-size: 13px;
}
\ No newline at end of file \ No newline at end of file
'use client'
import React from 'react'
import cn from 'classnames'
import s from './index.module.scss'
const NotWorkWeChatPage = () => {
return (
<div className={cn(s['container'],'layout-bg')}>
<div className="max-w-md w-full text-center">
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/not-ww.png" alt="Not Work WeChat" className={cn(s['icon'],)} />
{/* 标题文字 */}
<h1 className={cn(s['title'],)}>
请在企业微信中打开
</h1>
{/* 描述文字 */}
<p className={cn(s['description'],)}>
「AI 智能问数」功能仅支持在企业微信客户端中使用,请在企业微信中重新打开。
</p>
</div>
</div>
)
}
export default NotWorkWeChatPage
\ No newline at end of file \ No newline at end of file
'use client'
import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import Loading from '@/app/components/base/loading'
export default function SettingPage() {
const searchParams = useSearchParams()
const [url, setUrl] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
const settingUrl = searchParams.get('settingUrl')
const sessionId = searchParams.get('sessionId')
const corpId = searchParams.get('corpId')
if (settingUrl) {
let fullUrl = decodeURIComponent(settingUrl)
if (sessionId || corpId) {
const separator = fullUrl.includes('?') ? '&' : '?'
const params = []
if (sessionId) params.push(`sessionId=${sessionId}`)
if (corpId) params.push(`corpId=${corpId}`)
fullUrl = `${fullUrl}${separator}${params.join('&')}`
}
setUrl(fullUrl)
setLoading(false)
} else {
setLoading(false)
}
}, [searchParams])
if (loading) {
return (
<div className="flex h-screen w-full items-center justify-center">
<Loading type="app" />
</div>
)
}
if (!url) {
return (
<div className="flex h-screen w-full items-center justify-center">
<div className="text-text-secondary">无效的请求</div>
</div>
)
}
return (
<div className="h-screen w-full">
<iframe
src={url}
className="h-full w-full border-0"
title="设置页面"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
/>
</div>
)
}
\ No newline at end of file \ No newline at end of file
import { create } from 'zustand'
import type { App, AppSSO } from '@/types/app'
import type { IChatItem } from '@/app/components/base/chat/chat/type'
type State = {
appDetail?: App & Partial<AppSSO>
appSidebarExpand: string
currentLogItem?: IChatItem
currentLogModalActiveTab: string
showPromptLogModal: boolean
showAgentLogModal: boolean
showMessageLogModal: boolean
showAppConfigureFeaturesModal: boolean
globalConfig: any
reviewPassed: boolean // Review 是否通过
scenarioSummaryIndex?: number // 场景摘要索引
scenarioSummaryLength?: number // 场景摘要长度
customerOriginal?: string // 自定义开场白
scenarioSummary?: string // 场景摘要
scenarioType?: string // 场景类型
}
type Action = {
setAppDetail: (appDetail?: App & Partial<AppSSO>) => void
setAppSiderbarExpand: (state: string) => void
setCurrentLogItem: (item?: IChatItem) => void
setCurrentLogModalActiveTab: (tab: string) => void
setShowPromptLogModal: (showPromptLogModal: boolean) => void
setShowAgentLogModal: (showAgentLogModal: boolean) => void
setShowMessageLogModal: (showMessageLogModal: boolean) => void
setShowAppConfigureFeaturesModal: (showAppConfigureFeaturesModal: boolean) => void
setGlobalConfig: (globalConfig: any) => void
setReviewPassed: (reviewPassed: boolean) => void // 设置 Review 通过状态
setScenarioSummaryIndex: (scenarioSummaryIndex?: number) => void // 设置场景摘要索引
setScenarioSummaryLength: (scenarioSummaryLength?: number) => void // 设置场景摘要长度
setCustomerOriginal: (customerOriginal?: string) => void // 设置自定义开场白
setScenarioSummary: (scenarioSummary?: string) => void // 设置场景摘要
setScenarioType: (scenarioType?: string) => void // 设置场景类型
}
export const useStore = create<State & Action>(set => ({
appDetail: undefined,
setAppDetail: appDetail => set(() => ({ appDetail })),
appSidebarExpand: '',
setAppSiderbarExpand: appSidebarExpand => set(() => ({ appSidebarExpand })),
currentLogItem: undefined,
currentLogModalActiveTab: 'DETAIL',
setCurrentLogItem: currentLogItem => set(() => ({ currentLogItem })),
setCurrentLogModalActiveTab: currentLogModalActiveTab => set(() => ({ currentLogModalActiveTab })),
showPromptLogModal: false,
setShowPromptLogModal: showPromptLogModal => set(() => ({ showPromptLogModal })),
showAgentLogModal: false,
setShowAgentLogModal: showAgentLogModal => set(() => ({ showAgentLogModal })),
showMessageLogModal: false,
setShowMessageLogModal: showMessageLogModal =>
set(() => {
if (showMessageLogModal) {
return { showMessageLogModal }
} else {
return {
showMessageLogModal,
currentLogModalActiveTab: 'DETAIL',
}
}
}),
showAppConfigureFeaturesModal: false,
setShowAppConfigureFeaturesModal: showAppConfigureFeaturesModal => set(() => ({ showAppConfigureFeaturesModal })),
globalConfig: undefined,
setGlobalConfig: globalConfig => set(() => ({ globalConfig })),
reviewPassed: false,
setReviewPassed: reviewPassed => set(() => ({ reviewPassed })),
scenarioSummaryIndex: 0,
setScenarioSummaryIndex: scenarioSummaryIndex => set(() => ({ scenarioSummaryIndex })),
scenarioSummaryLength: 0,
setScenarioSummaryLength: scenarioSummaryLength => set(() => ({ scenarioSummaryLength })),
customerOriginal: undefined,
setCustomerOriginal: customerOriginal => set(() => ({ customerOriginal })),
scenarioSummary: undefined,
setScenarioSummary: scenarioSummary => set(() => ({ scenarioSummary })),
scenarioType: undefined,
setScenarioType: scenarioType => set(() => ({ scenarioType })),
}))
@tailwind components;
@layer components {
.action-btn {
@apply inline-flex justify-center items-center cursor-pointer text-text-tertiary hover:text-text-secondary hover:bg-state-base-hover
}
.action-btn-hover {
@apply bg-state-base-hover
}
.action-btn-disabled {
@apply cursor-not-allowed
}
.action-btn-xl {
@apply p-2 w-9 h-9 rounded-lg
}
.action-btn-l {
@apply p-1.5 w-8 h-8 rounded-lg
}
/* m is for the regular button */
.action-btn-m {
@apply p-0.5 w-6 h-6 rounded-lg
}
.action-btn-xs {
@apply p-0 w-4 h-4 rounded
}
.action-btn.action-btn-active {
@apply text-text-accent bg-state-accent-active hover:bg-state-accent-active-alt
}
.action-btn.action-btn-disabled {
@apply text-text-disabled
}
.action-btn.action-btn-destructive {
@apply text-text-destructive bg-state-destructive-hover
}
}
\ No newline at end of file \ No newline at end of file
import type { CSSProperties } from 'react'
import React from 'react'
import { type VariantProps, cva } from 'class-variance-authority'
import classNames from '@/utils/classnames'
enum ActionButtonState {
Destructive = 'destructive',
Active = 'active',
Disabled = 'disabled',
Default = '',
Hover = 'hover',
}
const actionButtonVariants = cva(
'action-btn',
{
variants: {
size: {
xs: 'action-btn-xs',
m: 'action-btn-m',
l: 'action-btn-l',
xl: 'action-btn-xl',
},
},
defaultVariants: {
size: 'm',
},
},
)
export type ActionButtonProps = {
size?: 'xs' | 's' | 'm' | 'l' | 'xl'
state?: ActionButtonState
styleCss?: CSSProperties
} & React.ButtonHTMLAttributes<HTMLButtonElement> & VariantProps<typeof actionButtonVariants>
function getActionButtonState(state: ActionButtonState) {
switch (state) {
case ActionButtonState.Destructive:
return 'action-btn-destructive'
case ActionButtonState.Active:
return 'action-btn-active'
case ActionButtonState.Disabled:
return 'action-btn-disabled'
case ActionButtonState.Hover:
return 'action-btn-hover'
default:
return ''
}
}
const ActionButton = React.forwardRef<HTMLButtonElement, ActionButtonProps>(
({ className, size, state = ActionButtonState.Default, styleCss, children, ...props }, ref) => {
return (
<button
type='button'
className={classNames(
actionButtonVariants({ className, size }),
getActionButtonState(state),
)}
ref={ref}
style={styleCss}
{...props}
>
{children}
</button>
)
},
)
ActionButton.displayName = 'ActionButton'
export default ActionButton
export { ActionButton, ActionButtonState, actionButtonVariants }
/*
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: limin
* @LastEditTime: 2025-07-14 19:42:31
* @FilePath: \ai-assistant\app\components\base\answer-icon\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
'use client'
import { memo, type FC } from 'react'
import { init } from 'emoji-mart'
import data from '@emoji-mart/data'
import classNames from '@/utils/classnames'
import type { AppIconType } from '@/types/app'
import { AVATAR_AI_URL } from '@/app/components/base/chat/constants'
init({ data })
export type AnswerIconProps = {
iconType?: AppIconType | null
icon?: string | null
background?: string | null
imageUrl?: string
}
const AnswerIcon: FC<AnswerIconProps> = ({ iconType, background, imageUrl }) => {
const wrapperClassName = classNames('flex', 'items-center', 'justify-center', 'w-full', 'h-full', 'rounded-full', 'text-xl')
return (
<div className={wrapperClassName}>
<img src={imageUrl||AVATAR_AI_URL} className="h-full w-full rounded-full" alt="answer icon" />
</div>
)
}
const meAnswerIcon = memo(AnswerIcon, (prev, next) => prev.imageUrl === next.imageUrl)
export default meAnswerIcon
'use client'
import type { ChangeEvent, FC } from 'react'
import { createRef, useEffect, useState } from 'react'
import Cropper, { type Area, type CropperProps } from 'react-easy-crop'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
import { ImagePlus } from '../icons/src/vender/line/images'
import { useDraggableUploader } from './hooks'
import { checkIsAnimatedImage } from './utils'
import { ALLOW_FILE_EXTENSIONS } from '@/types/app'
export type OnImageInput = {
(isCropped: true, tempUrl: string, croppedAreaPixels: Area, fileName: string): void
(isCropped: false, file: File): void
}
type UploaderProps = {
className?: string
cropShape?: CropperProps['cropShape']
onImageInput?: OnImageInput
}
const ImageInput: FC<UploaderProps> = ({
className,
cropShape,
onImageInput,
}) => {
const { t } = useTranslation()
const [inputImage, setInputImage] = useState<{ file: File; url: string }>()
const [isAnimatedImage, setIsAnimatedImage] = useState<boolean>(false)
useEffect(() => {
return () => {
if (inputImage)
URL.revokeObjectURL(inputImage.url)
}
}, [inputImage])
const [crop, setCrop] = useState({ x: 0, y: 0 })
const [zoom, setZoom] = useState(1)
const onCropComplete = async (_: Area, croppedAreaPixels: Area) => {
if (!inputImage)
return
onImageInput?.(true, inputImage.url, croppedAreaPixels, inputImage.file.name)
}
const handleLocalFileInput = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
setInputImage({ file, url: URL.createObjectURL(file) })
checkIsAnimatedImage(file).then((isAnimatedImage) => {
setIsAnimatedImage(!!isAnimatedImage)
if (isAnimatedImage)
onImageInput?.(false, file)
})
}
}
const {
isDragActive,
handleDragEnter,
handleDragOver,
handleDragLeave,
handleDrop,
} = useDraggableUploader((file: File) => setInputImage({ file, url: URL.createObjectURL(file) }))
const inputRef = createRef<HTMLInputElement>()
const handleShowImage = () => {
if (isAnimatedImage) {
return (
<img src={inputImage?.url} alt='' />
)
}
return (
<Cropper
image={inputImage?.url}
crop={crop}
zoom={zoom}
aspect={1}
cropShape={cropShape}
onCropChange={setCrop}
onCropComplete={onCropComplete}
onZoomChange={setZoom}
/>
)
}
return (
<div className={classNames(className, 'w-full px-3 py-1.5')}>
<div
className={classNames(
isDragActive && 'border-primary-600',
'relative aspect-square bg-gray-50 border-[1.5px] border-gray-200 border-dashed rounded-lg flex flex-col justify-center items-center text-gray-500')}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{
!inputImage
? <>
<ImagePlus className="pointer-events-none mb-3 h-[30px] w-[30px]" />
<div className="mb-[2px] text-sm font-medium">
<span className="pointer-events-none">{t('common.imageInput.dropImageHere')}&nbsp;</span>
<button className="text-components-button-primary-bg" onClick={() => inputRef.current?.click()}>{t('common.imageInput.browse')}</button>
<input
ref={inputRef} type="file" className="hidden"
onClick={e => ((e.target as HTMLInputElement).value = '')}
accept={ALLOW_FILE_EXTENSIONS.map(ext => `.${ext}`).join(',')}
onChange={handleLocalFileInput}
/>
</div>
<div className="pointer-events-none">{t('common.imageInput.supportedFormats')}</div>
</>
: handleShowImage()
}
</div>
</div>
)
}
export default ImageInput
import { useCallback, useState } from 'react'
export const useDraggableUploader = <T extends HTMLElement>(setImageFn: (file: File) => void) => {
const [isDragActive, setIsDragActive] = useState(false)
const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
e.preventDefault()
e.stopPropagation()
setIsDragActive(true)
}, [])
const handleDragOver = useCallback((e: React.DragEvent<T>) => {
e.preventDefault()
e.stopPropagation()
}, [])
const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
e.preventDefault()
e.stopPropagation()
setIsDragActive(false)
}, [])
const handleDrop = useCallback((e: React.DragEvent<T>) => {
e.preventDefault()
e.stopPropagation()
setIsDragActive(false)
const file = e.dataTransfer.files[0]
if (!file)
return
setImageFn(file)
}, [setImageFn])
return {
handleDragEnter,
handleDragOver,
handleDragLeave,
handleDrop,
isDragActive,
}
}
import type { FC } from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { Area } from 'react-easy-crop'
import Modal from '../modal'
import Divider from '../divider'
import Button from '../button'
import { ImagePlus } from '../icons/src/vender/line/images'
import { useLocalFileUploader } from '../image-uploader/hooks'
import EmojiPickerInner from '../emoji-picker/Inner'
import type { OnImageInput } from './ImageInput'
import ImageInput from './ImageInput'
import s from './style.module.css'
import getCroppedImg from './utils'
import type { AppIconType, ImageFile } from '@/types/app'
import cn from '@/utils/classnames'
import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
import { noop } from 'lodash-es'
export type AppIconEmojiSelection = {
type: 'emoji'
icon: string
background: string
}
export type AppIconImageSelection = {
type: 'image'
fileId: string
url: string
}
export type AppIconSelection = AppIconEmojiSelection | AppIconImageSelection
type AppIconPickerProps = {
onSelect?: (payload: AppIconSelection) => void
onClose?: () => void
className?: string
}
const AppIconPicker: FC<AppIconPickerProps> = ({
onSelect,
onClose,
className,
}) => {
const { t } = useTranslation()
const tabs = [
{ key: 'emoji', label: t('app.iconPicker.emoji'), icon: <span className="text-lg">🤖</span> },
{ key: 'image', label: t('app.iconPicker.image'), icon: <ImagePlus /> },
]
const [activeTab, setActiveTab] = useState<AppIconType>('emoji')
const [emoji, setEmoji] = useState<{ emoji: string; background: string }>()
const handleSelectEmoji = useCallback((emoji: string, background: string) => {
setEmoji({ emoji, background })
}, [setEmoji])
const [uploading, setUploading] = useState<boolean>()
const { handleLocalFileUpload } = useLocalFileUploader({
limit: 3,
disabled: false,
onUpload: (imageFile: ImageFile) => {
if (imageFile.fileId) {
setUploading(false)
onSelect?.({
type: 'image',
fileId: imageFile.fileId,
url: imageFile.url,
})
}
},
})
type InputImageInfo = { file: File } | { tempUrl: string; croppedAreaPixels: Area; fileName: string }
const [inputImageInfo, setInputImageInfo] = useState<InputImageInfo>()
const handleImageInput: OnImageInput = async (isCropped: boolean, fileOrTempUrl: string | File, croppedAreaPixels?: Area, fileName?: string) => {
setInputImageInfo(
isCropped
? { tempUrl: fileOrTempUrl as string, croppedAreaPixels: croppedAreaPixels!, fileName: fileName! }
: { file: fileOrTempUrl as File },
)
}
const handleSelect = async () => {
if (activeTab === 'emoji') {
if (emoji) {
onSelect?.({
type: 'emoji',
icon: emoji.emoji,
background: emoji.background,
})
}
}
else {
if (!inputImageInfo)
return
setUploading(true)
if ('file' in inputImageInfo) {
handleLocalFileUpload(inputImageInfo.file)
return
}
const blob = await getCroppedImg(inputImageInfo.tempUrl, inputImageInfo.croppedAreaPixels, inputImageInfo.fileName)
const file = new File([blob], inputImageInfo.fileName, { type: blob.type })
handleLocalFileUpload(file)
}
}
return <Modal
onClose={noop}
isShow
closable={false}
wrapperClassName={className}
className={cn(s.container, '!w-[362px] !p-0')}
>
{!DISABLE_UPLOAD_IMAGE_AS_ICON && <div className="w-full p-2 pb-0">
<div className='flex items-center justify-center gap-2 rounded-xl bg-background-body p-1'>
{tabs.map(tab => (
<button
key={tab.key}
className={`
flex h-8 flex-1 shrink-0 items-center justify-center rounded-xl p-2 text-sm font-medium
${activeTab === tab.key && 'bg-components-main-nav-nav-button-bg-active shadow-md'}
`}
onClick={() => setActiveTab(tab.key as AppIconType)}
>
{tab.icon} &nbsp; {tab.label}
</button>
))}
</div>
</div>}
<EmojiPickerInner className={cn(activeTab === 'emoji' ? 'block' : 'hidden', 'pt-2')} onSelect={handleSelectEmoji} />
<ImageInput className={activeTab === 'image' ? 'block' : 'hidden'} onImageInput={handleImageInput} />
<Divider className='m-0' />
<div className='flex w-full items-center justify-center gap-2 p-3'>
<Button className='w-full' onClick={() => onClose?.()}>
{t('app.iconPicker.cancel')}
</Button>
<Button variant="primary" className='w-full' disabled={uploading} loading={uploading} onClick={handleSelect}>
{t('app.iconPicker.ok')}
</Button>
</div>
</Modal>
}
export default AppIconPicker
.container {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 362px;
max-height: 552px;
border: 0.5px solid #EAECF0;
box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
border-radius: 12px;
background: #fff;
}
export const createImage = (url: string) =>
new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image()
image.addEventListener('load', () => resolve(image))
image.addEventListener('error', error => reject(error))
image.setAttribute('crossOrigin', 'anonymous') // needed to avoid cross-origin issues on CodeSandbox
image.src = url
})
export function getRadianAngle(degreeValue: number) {
return (degreeValue * Math.PI) / 180
}
export function getMimeType(fileName: string): string {
const extension = fileName.split('.').pop()?.toLowerCase()
switch (extension) {
case 'png':
return 'image/png'
case 'jpg':
case 'jpeg':
return 'image/jpeg'
case 'gif':
return 'image/gif'
case 'webp':
return 'image/webp'
default:
return 'image/jpeg'
}
}
/**
* Returns the new bounding area of a rotated rectangle.
*/
export function rotateSize(width: number, height: number, rotation: number) {
const rotRad = getRadianAngle(rotation)
return {
width:
Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
height:
Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height),
}
}
/**
* This function was adapted from the one in the ReadMe of https://github.com/DominicTobias/react-image-crop
*/
export default async function getCroppedImg(
imageSrc: string,
pixelCrop: { x: number; y: number; width: number; height: number },
fileName: string,
rotation = 0,
flip = { horizontal: false, vertical: false },
): Promise<Blob> {
const image = await createImage(imageSrc)
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const mimeType = getMimeType(fileName)
if (!ctx)
throw new Error('Could not create a canvas context')
const rotRad = getRadianAngle(rotation)
// calculate bounding box of the rotated image
const { width: bBoxWidth, height: bBoxHeight } = rotateSize(
image.width,
image.height,
rotation,
)
// set canvas size to match the bounding box
canvas.width = bBoxWidth
canvas.height = bBoxHeight
// translate canvas context to a central location to allow rotating and flipping around the center
ctx.translate(bBoxWidth / 2, bBoxHeight / 2)
ctx.rotate(rotRad)
ctx.scale(flip.horizontal ? -1 : 1, flip.vertical ? -1 : 1)
ctx.translate(-image.width / 2, -image.height / 2)
// draw rotated image
ctx.drawImage(image, 0, 0)
const croppedCanvas = document.createElement('canvas')
const croppedCtx = croppedCanvas.getContext('2d')
if (!croppedCtx)
throw new Error('Could not create a canvas context')
// Set the size of the cropped canvas
croppedCanvas.width = pixelCrop.width
croppedCanvas.height = pixelCrop.height
// Draw the cropped image onto the new canvas
croppedCtx.drawImage(
canvas,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
0,
0,
pixelCrop.width,
pixelCrop.height,
)
return new Promise((resolve, reject) => {
croppedCanvas.toBlob((file) => {
if (file)
resolve(file)
else
reject(new Error('Could not create a blob'))
}, mimeType)
})
}
export function checkIsAnimatedImage(file: File): Promise<boolean> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = function (e) {
const arr = new Uint8Array(e.target?.result as ArrayBuffer)
// Check file extension
const fileName = file.name.toLowerCase()
if (fileName.endsWith('.gif')) {
// If file is a GIF, assume it's animated
resolve(true)
}
// Check for WebP signature (RIFF and WEBP)
else if (isWebP(arr)) {
resolve(checkWebPAnimation(arr)) // Check if it's animated
}
else {
resolve(false) // Not a GIF or WebP
}
}
fileReader.onerror = function (err) {
reject(err) // Reject the promise on error
}
// Read the file as an array buffer
fileReader.readAsArrayBuffer(file)
})
}
// Function to check for WebP signature
function isWebP(arr: Uint8Array) {
return (
arr[0] === 0x52 && arr[1] === 0x49 && arr[2] === 0x46 && arr[3] === 0x46
&& arr[8] === 0x57 && arr[9] === 0x45 && arr[10] === 0x42 && arr[11] === 0x50
) // "WEBP"
}
// Function to check if the WebP is animated (contains ANIM chunk)
function checkWebPAnimation(arr: Uint8Array) {
// Search for the ANIM chunk in WebP to determine if it's animated
for (let i = 12; i < arr.length - 4; i++) {
if (arr[i] === 0x41 && arr[i + 1] === 0x4E && arr[i + 2] === 0x49 && arr[i + 3] === 0x4D)
return true // Found animation
}
return false // No animation chunk found
}
'use client'
import type { FC } from 'react'
import { init } from 'emoji-mart'
import data from '@emoji-mart/data'
import { cva } from 'class-variance-authority'
import type { AppIconType } from '@/types/app'
import classNames from '@/utils/classnames'
init({ data })
export type AppIconProps = {
size?: 'xs' | 'tiny' | 'small' | 'medium' | 'large' | 'xl' | 'xxl'
rounded?: boolean
iconType?: AppIconType | null
icon?: string
background?: string | null
imageUrl?: string | null
className?: string
innerIcon?: React.ReactNode
onClick?: () => void
}
const appIconVariants = cva(
'flex items-center justify-center relative text-lg rounded-lg grow-0 shrink-0 overflow-hidden leading-none',
{
variants: {
size: {
xs: 'w-4 h-4 text-xs',
tiny: 'w-6 h-6 text-base',
small: 'w-8 h-8 text-xl',
medium: 'w-9 h-9 text-[22px]',
large: 'w-10 h-10 text-[24px]',
xl: 'w-12 h-12 text-[28px]',
xxl: 'w-14 h-14 text-[32px]',
},
rounded: {
true: 'rounded-full',
},
},
defaultVariants: {
size: 'medium',
rounded: false,
},
})
const AppIcon: FC<AppIconProps> = ({
size = 'medium',
rounded = false,
iconType,
icon,
background,
imageUrl,
className,
innerIcon,
onClick,
}) => {
const isValidImageIcon = iconType === 'image' && imageUrl
return <span
className={classNames(appIconVariants({ size, rounded }), className)}
style={{ background: isValidImageIcon ? undefined : (background || '#FFEAD5') }}
onClick={onClick}
>
{isValidImageIcon
? <img src={imageUrl} className="h-full w-full" alt="app icon" />
: (innerIcon || ((icon && icon !== '') ? <em-emoji id={icon} /> : <em-emoji id='🤖' />))
}
</span>
}
export default AppIcon
.appIcon {
@apply flex items-center justify-center relative w-9 h-9 text-lg rounded-lg grow-0 shrink-0;
}
.appIcon.large {
@apply w-10 h-10;
}
.appIcon.small {
@apply w-8 h-8;
}
.appIcon.tiny {
@apply w-6 h-6 text-base;
}
.appIcon.xs {
@apply w-5 h-5 text-base;
}
.appIcon.rounded {
@apply rounded-full;
}
\ No newline at end of file \ No newline at end of file
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
type IAppUnavailableProps = {
code?: number
isUnknownReason?: boolean
unknownReason?: string
}
const AppUnavailable: FC<IAppUnavailableProps> = ({ code = 404, isUnknownReason, unknownReason }) => {
const { t } = useTranslation()
return (
<div className="flex h-screen w-screen items-center justify-center">
<h1
className="mr-5 h-[50px] pr-5 text-[24px] font-medium leading-[50px]"
style={{
borderRight: '1px solid rgba(0,0,0,.3)',
}}>
{code}
</h1>
<div className="text-sm">{unknownReason || (isUnknownReason ? t('share.common.appUnknownError') : t('share.common.appUnavailable'))}</div>
</div>
)
}
export default React.memo(AppUnavailable)
import AudioPlayer from '@/app/components/base/audio-btn/audio'
declare global {
// eslint-disable-next-line ts/consistent-type-definitions
interface AudioPlayerManager {
instance: AudioPlayerManager
}
}
export class AudioPlayerManager {
private static instance: AudioPlayerManager
private audioPlayers: AudioPlayer | null = null
private msgId: string | undefined
private constructor() {
}
public static getInstance(): AudioPlayerManager {
if (!AudioPlayerManager.instance) {
AudioPlayerManager.instance = new AudioPlayerManager()
this.instance = AudioPlayerManager.instance
}
return AudioPlayerManager.instance
}
public getAudioPlayer(url: string, isPublic: boolean, id: string | undefined, msgContent: string | null | undefined, voice: string | undefined, callback: ((event: string) => {}) | null): AudioPlayer {
if (this.msgId && this.msgId === id && this.audioPlayers) {
this.audioPlayers.setCallback(callback)
return this.audioPlayers
}
else {
if (this.audioPlayers) {
try {
this.audioPlayers.pauseAudio()
this.audioPlayers.cacheBuffers = []
this.audioPlayers.sourceBuffer?.abort()
}
catch (e) {
}
}
this.msgId = id
this.audioPlayers = new AudioPlayer(url, isPublic, id, msgContent, voice, callback)
return this.audioPlayers
}
}
public resetMsgId(msgId: string) {
this.msgId = msgId
this.audioPlayers?.resetMsgId(msgId)
}
}
import Toast from '@/app/components/base/toast'
import { textToAudioStream } from '@/service/share'
declare global {
// eslint-disable-next-line ts/consistent-type-definitions
interface Window {
ManagedMediaSource: any
}
}
export default class AudioPlayer {
mediaSource: MediaSource | null
audio: HTMLAudioElement
audioContext: AudioContext
sourceBuffer?: any
cacheBuffers: ArrayBuffer[] = []
pauseTimer: number | null = null
msgId: string | undefined
msgContent: string | null | undefined = null
voice: string | undefined = undefined
isLoadData = false
url: string
isPublic: boolean
callback: ((event: string) => {}) | null
constructor(streamUrl: string, isPublic: boolean, msgId: string | undefined, msgContent: string | null | undefined, voice: string | undefined, callback: ((event: string) => {}) | null) {
this.audioContext = new AudioContext()
this.msgId = msgId
this.msgContent = msgContent
this.url = streamUrl
this.isPublic = isPublic
this.voice = voice
this.callback = callback
// Compatible with iphone ios17 ManagedMediaSource
const MediaSource = window.ManagedMediaSource || window.MediaSource
if (!MediaSource) {
Toast.notify({
message: 'Your browser does not support audio streaming, if you are using an iPhone, please update to iOS 17.1 or later.',
type: 'error',
})
}
this.mediaSource = MediaSource ? new MediaSource() : null
this.audio = new Audio()
this.setCallback(callback)
if (!window.MediaSource) { // if use ManagedMediaSource
this.audio.disableRemotePlayback = true
this.audio.controls = true
}
this.audio.src = this.mediaSource ? URL.createObjectURL(this.mediaSource) : ''
this.audio.autoplay = true
const source = this.audioContext.createMediaElementSource(this.audio)
source.connect(this.audioContext.destination)
this.listenMediaSource('audio/mpeg')
}
public resetMsgId(msgId: string) {
this.msgId = msgId
}
private listenMediaSource(contentType: string) {
this.mediaSource?.addEventListener('sourceopen', () => {
if (this.sourceBuffer)
return
this.sourceBuffer = this.mediaSource?.addSourceBuffer(contentType)
})
}
public setCallback(callback: ((event: string) => {}) | null) {
this.callback = callback
if (callback) {
this.audio.addEventListener('ended', () => {
callback('ended')
}, false)
this.audio.addEventListener('paused', () => {
callback('paused')
}, true)
this.audio.addEventListener('loaded', () => {
callback('loaded')
}, true)
this.audio.addEventListener('play', () => {
callback('play')
}, true)
this.audio.addEventListener('timeupdate', () => {
callback('timeupdate')
}, true)
this.audio.addEventListener('loadeddate', () => {
callback('loadeddate')
}, true)
this.audio.addEventListener('canplay', () => {
callback('canplay')
}, true)
this.audio.addEventListener('error', () => {
callback('error')
}, true)
}
}
private async loadAudio() {
try {
const audioResponse: any = await textToAudioStream(this.url, this.isPublic, { content_type: 'audio/mpeg' }, {
message_id: this.msgId,
streaming: true,
voice: this.voice,
text: this.msgContent,
})
if (audioResponse.status !== 200) {
this.isLoadData = false
if (this.callback)
this.callback('error')
}
const reader = audioResponse.body.getReader()
while (true) {
const { value, done } = await reader.read()
if (done) {
this.receiveAudioData(value)
break
}
this.receiveAudioData(value)
}
}
catch (error) {
this.isLoadData = false
this.callback && this.callback('error')
}
}
// play audio
public playAudio() {
if (this.isLoadData) {
if (this.audioContext.state === 'suspended') {
this.audioContext.resume().then((_) => {
this.audio.play()
this.callback && this.callback('play')
})
}
else if (this.audio.ended) {
this.audio.play()
this.callback && this.callback('play')
}
if (this.callback)
this.callback('play')
}
else {
this.isLoadData = true
this.loadAudio()
}
}
private theEndOfStream() {
const endTimer = setInterval(() => {
if (!this.sourceBuffer?.updating) {
this.mediaSource?.endOfStream()
clearInterval(endTimer)
}
}, 10)
}
private finishStream() {
const timer = setInterval(() => {
if (!this.cacheBuffers.length) {
this.theEndOfStream()
clearInterval(timer)
}
if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
const arrayBuffer = this.cacheBuffers.shift()!
this.sourceBuffer?.appendBuffer(arrayBuffer)
}
}, 10)
}
public async playAudioWithAudio(audio: string, play = true) {
if (!audio || !audio.length) {
this.finishStream()
return
}
const audioContent = Buffer.from(audio, 'base64')
this.receiveAudioData(new Uint8Array(audioContent))
if (play) {
this.isLoadData = true
if (this.audio.paused) {
this.audioContext.resume().then((_) => {
this.audio.play()
this.callback && this.callback('play')
})
}
else if (this.audio.ended) {
this.audio.play()
this.callback && this.callback('play')
}
else if (this.audio.played) { /* empty */ }
else {
this.audio.play()
this.callback && this.callback('play')
}
}
}
public pauseAudio() {
this.callback && this.callback('paused')
this.audio.pause()
this.audioContext.suspend()
}
private cancer() {
}
private receiveAudioData(unit8Array: Uint8Array) {
if (!unit8Array) {
this.finishStream()
return
}
const audioData = this.byteArrayToArrayBuffer(unit8Array)
if (!audioData.byteLength) {
if (this.mediaSource?.readyState === 'open')
this.finishStream()
return
}
if (this.sourceBuffer?.updating) {
this.cacheBuffers.push(audioData)
}
else {
if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {
this.cacheBuffers.push(audioData)
const cacheBuffer = this.cacheBuffers.shift()!
this.sourceBuffer?.appendBuffer(cacheBuffer)
}
else {
this.sourceBuffer?.appendBuffer(audioData)
}
}
}
private byteArrayToArrayBuffer(byteArray: Uint8Array): ArrayBuffer {
const arrayBuffer = new ArrayBuffer(byteArray.length)
const uint8Array = new Uint8Array(arrayBuffer)
uint8Array.set(byteArray)
return arrayBuffer
}
}
'use client'
import { useState } from 'react'
import { t } from 'i18next'
import { useParams, usePathname } from 'next/navigation'
import s from './style.module.css'
import Tooltip from '@/app/components/base/tooltip'
import Loading from '@/app/components/base/loading'
import { AudioPlayerManager } from '@/app/components/base/audio-btn/audio.player.manager'
type AudioBtnProps = {
id?: string
voice?: string
value?: string
className?: string
isAudition?: boolean
noCache?: boolean
}
type AudioState = 'initial' | 'loading' | 'playing' | 'paused' | 'ended'
const AudioBtn = ({
id,
voice,
value,
className,
isAudition,
}: AudioBtnProps) => {
const [audioState, setAudioState] = useState<AudioState>('initial')
const params = useParams()
const pathname = usePathname()
const audio_finished_call = (event: string): any => {
switch (event) {
case 'ended':
setAudioState('ended')
break
case 'paused':
setAudioState('ended')
break
case 'loaded':
setAudioState('loading')
break
case 'play':
setAudioState('playing')
break
case 'error':
setAudioState('ended')
break
}
}
let url = ''
let isPublic = false
if (params.token) {
url = '/text-to-audio'
isPublic = true
}
else if (params.appId) {
if (pathname.search('explore/installed') > -1)
url = `/installed-apps/${params.appId}/text-to-audio`
else
url = `/apps/${params.appId}/text-to-audio`
}
const handleToggle = async () => {
if (audioState === 'playing' || audioState === 'loading') {
setTimeout(() => setAudioState('paused'), 1)
AudioPlayerManager.getInstance().getAudioPlayer(url, isPublic, id, value, voice, audio_finished_call).pauseAudio()
}
else {
setTimeout(() => setAudioState('loading'), 1)
AudioPlayerManager.getInstance().getAudioPlayer(url, isPublic, id, value, voice, audio_finished_call).playAudio()
}
}
const tooltipContent = {
initial: t('appApi.play'),
ended: t('appApi.play'),
paused: t('appApi.pause'),
playing: t('appApi.playing'),
loading: t('appApi.loading'),
}[audioState]
return (
<div className={`inline-flex items-center justify-center ${(audioState === 'loading' || audioState === 'playing') ? 'mr-1' : className}`}>
<Tooltip
popupContent={tooltipContent}
>
<button
disabled={audioState === 'loading'}
className={`box-border flex h-6 w-6 cursor-pointer items-center justify-center ${isAudition ? 'p-0.5' : 'rounded-md bg-white p-0'}`}
onClick={handleToggle}
>
{audioState === 'loading'
? (
<div className='flex h-full w-full items-center justify-center rounded-md'>
<Loading />
</div>
)
: (
<div className={`flex h-full w-full items-center justify-center rounded-md ${!isAudition ? 'hover:bg-gray-50' : 'hover:bg-gray-50'}`}>
<div className={`h-4 w-4 ${(audioState === 'playing') ? s.pauseIcon : s.playIcon}`}></div>
</div>
)}
</button>
</Tooltip>
</div>
)
}
export default AudioBtn
.playIcon {
background-image: url(~@/app/components/develop/secret-key/assets/play.svg);
background-position: center;
background-repeat: no-repeat;
}
.pauseIcon {
background-image: url(~@/app/components/develop/secret-key/assets/pause.svg);
background-position: center;
background-repeat: no-repeat;
}
\ No newline at end of file \ No newline at end of file
import React from 'react'
import AudioPlayer from './AudioPlayer'
type Props = {
srcs: string[]
}
const AudioGallery: React.FC<Props> = ({ srcs }) => {
return (<><br/>{srcs.map((src, index) => (<AudioPlayer key={`audio_${index}`} src={src}/>))}</>)
}
export default React.memo(AudioGallery)
import { useEffect, useRef } from 'react'
import cn from '@/utils/classnames'
type AutoHeightTextareaProps =
& React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>
& { outerClassName?: string }
const AutoHeightTextarea = (
{
ref: outRef,
outerClassName,
value,
className,
placeholder,
autoFocus,
disabled,
...rest
}: AutoHeightTextareaProps & {
ref: React.RefObject<HTMLTextAreaElement>;
},
) => {
const innerRef = useRef<HTMLTextAreaElement>(null)
const ref = outRef || innerRef
useEffect(() => {
if (autoFocus && !disabled && value) {
if (typeof ref !== 'function') {
ref.current?.setSelectionRange(`${value}`.length, `${value}`.length)
ref.current?.focus()
}
}
}, [autoFocus, disabled, ref])
return (
(<div className={outerClassName}>
<div className='relative'>
<div className={cn(className, 'invisible whitespace-pre-wrap break-all')}>
{!value ? placeholder : `${value}`.replace(/\n$/, '\n ')}
</div>
<textarea
ref={ref}
placeholder={placeholder}
className={cn(className, 'absolute inset-0 h-full w-full resize-none appearance-none border-none outline-none disabled:bg-transparent')}
value={value}
disabled={disabled}
{...rest}
/>
</div>
</div>)
)
}
AutoHeightTextarea.displayName = 'AutoHeightTextarea'
export default AutoHeightTextarea
import { useEffect, useRef } from 'react'
import cn from '@/utils/classnames'
import { sleep } from '@/utils'
type IProps = {
placeholder?: string
value: string
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
className?: string
wrapperClassName?: string
minHeight?: number
maxHeight?: number
autoFocus?: boolean
controlFocus?: number
onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
}
const AutoHeightTextarea = (
{
ref: outerRef,
value,
onChange,
placeholder,
className,
wrapperClassName,
minHeight = 36,
maxHeight = 96,
autoFocus,
controlFocus,
onKeyDown,
onKeyUp,
}: IProps & {
ref: React.RefObject<unknown>;
},
) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const ref = outerRef || useRef<HTMLTextAreaElement>(null)
const doFocus = () => {
if (ref.current) {
ref.current.setSelectionRange(value.length, value.length)
ref.current.focus()
return true
}
return false
}
const focus = async () => {
if (!doFocus()) {
let hasFocus = false
await sleep(100)
hasFocus = doFocus()
if (!hasFocus)
focus()
}
}
useEffect(() => {
if (autoFocus)
focus()
}, [])
useEffect(() => {
if (controlFocus)
focus()
}, [controlFocus])
return (
(<div className={`relative ${wrapperClassName}`}>
<div className={cn(className, 'invisible overflow-y-auto whitespace-pre-wrap break-all')} style={{
minHeight,
maxHeight,
paddingRight: (value && value.trim().length > 10000) ? 140 : 130,
}}>
{!value ? placeholder : value.replace(/\n$/, '\n ')}
</div>
<textarea
ref={ref}
autoFocus={autoFocus}
className={cn(className, 'absolute inset-0 resize-none overflow-auto')}
style={{
paddingRight: (value && value.trim().length > 10000) ? 140 : 130,
}}
placeholder={placeholder}
onChange={onChange}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
value={value}
/>
</div>)
)
}
AutoHeightTextarea.displayName = 'AutoHeightTextarea'
export default AutoHeightTextarea
'use client'
import { useState } from 'react'
import cn from '@/utils/classnames'
export type AvatarProps = {
name: string
avatar: string | null
size?: number
className?: string
textClassName?: string
}
const Avatar = ({
name,
avatar,
size = 30,
className,
textClassName,
}: AvatarProps) => {
const avatarClassName = 'shrink-0 flex items-center rounded-full bg-primary-600'
const style = { width: `${size}px`, height: `${size}px`, fontSize: `${size}px`, lineHeight: `${size}px` }
const [imgError, setImgError] = useState(false)
const handleError = () => {
setImgError(true)
}
if (avatar && !imgError) {
return (
<img
className={cn(avatarClassName, className)}
style={style}
alt={name}
src={avatar}
onError={handleError}
/>
)
}
return (
<div
className={cn(avatarClassName, className)}
style={style}
>
<div
className={cn(textClassName, 'scale-[0.4] text-center text-white')}
style={style}
>
{name[0].toLocaleUpperCase()}
</div>
</div>
)
}
export default Avatar
import type { ReactNode } from 'react'
import { memo } from 'react'
import cn from '@/utils/classnames'
type BadgeProps = {
className?: string
text?: ReactNode
children?: ReactNode
uppercase?: boolean
hasRedCornerMark?: boolean
}
const Badge = ({ className, text, children, uppercase = true, hasRedCornerMark }: BadgeProps) => {
return (
<div className={cn('relative inline-flex h-5 items-center rounded-[5px] border border-divider-deep px-[5px] leading-3 text-text-tertiary', uppercase ? 'system-2xs-medium-uppercase' : 'system-xs-medium', className)}>
{hasRedCornerMark && <div className="absolute right-[-2px] top-[-2px] h-1.5 w-1.5 rounded-[2px] border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm"></div>}
{children || text}
</div>
)
}
export default memo(Badge)
@tailwind components;
@layer components {
.badge {
@apply inline-flex justify-center items-center text-text-tertiary border border-divider-deep
}
.badge-l {
@apply rounded-md gap-1 min-w-6
}
/* m is for the regular button */
.badge-m {
@apply rounded-md gap-[3px] min-w-5
}
.badge-s {
@apply rounded-[5px] gap-0.5 min-w-[18px]
}
.badge.badge-warning {
@apply text-text-warning border border-text-warning
}
.badge.badge-accent {
@apply text-text-accent-secondary border border-text-accent-secondary
}
}
\ No newline at end of file \ No newline at end of file
import type { CSSProperties, ReactNode } from 'react'
import React from 'react'
import { type VariantProps, cva } from 'class-variance-authority'
import classNames from '@/utils/classnames'
import './index.css'
enum BadgeState {
Warning = 'warning',
Accent = 'accent',
Default = '',
}
const BadgeVariants = cva(
'badge',
{
variants: {
size: {
s: 'badge-s',
m: 'badge-m',
l: 'badge-l',
},
},
defaultVariants: {
size: 'm',
},
},
)
type BadgeProps = {
size?: 's' | 'm' | 'l'
iconOnly?: boolean
uppercase?: boolean
state?: BadgeState
styleCss?: CSSProperties
children?: ReactNode
} & React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof BadgeVariants>
function getBadgeState(state: BadgeState) {
switch (state) {
case BadgeState.Warning:
return 'badge-warning'
case BadgeState.Accent:
return 'badge-accent'
default:
return ''
}
}
const Badge: React.FC<BadgeProps> = ({
className,
size,
state = BadgeState.Default,
iconOnly = false,
uppercase = false,
styleCss,
children,
...props
}) => {
return (
<div
className={classNames(
BadgeVariants({ size, className }),
getBadgeState(state),
size === 's'
? (iconOnly ? 'p-[3px]' : 'px-[5px] py-[3px]')
: size === 'l'
? (iconOnly ? 'p-1.5' : 'px-2 py-1')
: (iconOnly ? 'p-1' : 'px-[5px] py-[2px]'),
uppercase ? 'system-2xs-medium-uppercase' : 'system-2xs-medium',
)}
style={styleCss}
{...props}
>
{children}
</div>
)
}
Badge.displayName = 'Badge'
export default Badge
export { Badge, BadgeState, BadgeVariants }
'use client'
import type { ChangeEvent, FC } from 'react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { varHighlightHTML } from '../../app/configuration/base/var-highlight'
import Toast from '../toast'
import classNames from '@/utils/classnames'
import { checkKeys } from '@/utils/var'
// regex to match the {{}} and replace it with a span
const regex = /\{\{([^}]+)\}\}/g
export const getInputKeys = (value: string) => {
const keys = value.match(regex)?.map((item) => {
return item.replace('{{', '').replace('}}', '')
}) || []
const keyObj: Record<string, boolean> = {}
// remove duplicate keys
const res: string[] = []
keys.forEach((key) => {
if (keyObj[key])
return
keyObj[key] = true
res.push(key)
})
return res
}
export type IBlockInputProps = {
value: string
className?: string // wrapper class
highLightClassName?: string // class for the highlighted text default is text-blue-500
readonly?: boolean
onConfirm?: (value: string, keys: string[]) => void
}
const BlockInput: FC<IBlockInputProps> = ({
value = '',
className,
readonly = false,
onConfirm,
}) => {
const { t } = useTranslation()
// current is used to store the current value of the contentEditable element
const [currentValue, setCurrentValue] = useState<string>(value)
useEffect(() => {
setCurrentValue(value)
}, [value])
const contentEditableRef = useRef<HTMLTextAreaElement>(null)
const [isEditing, setIsEditing] = useState<boolean>(false)
useEffect(() => {
if (isEditing && contentEditableRef.current) {
// TODO: Focus at the click position
if (currentValue)
contentEditableRef.current.setSelectionRange(currentValue.length, currentValue.length)
contentEditableRef.current.focus()
}
}, [isEditing])
const style = classNames({
'block px-4 py-2 w-full h-full text-sm text-gray-900 outline-0 border-0 break-all': true,
'block-input--editing': isEditing,
})
const coloredContent = (currentValue || '')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(regex, varHighlightHTML({ name: '$1' })) // `<span class="${highLightClassName}">{{$1}}</span>`
.replace(/\n/g, '<br />')
// Not use useCallback. That will cause out callback get old data.
const handleSubmit = (value: string) => {
if (onConfirm) {
const keys = getInputKeys(value)
const { isValid, errorKey, errorMessageKey } = checkKeys(keys)
if (!isValid) {
Toast.notify({
type: 'error',
message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
})
return
}
onConfirm(value, keys)
}
}
const onValueChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value
setCurrentValue(value)
handleSubmit(value)
}, [])
// Prevent rerendering caused cursor to jump to the start of the contentEditable element
const TextAreaContentView = () => {
return <div
className={classNames(style, className)}
dangerouslySetInnerHTML={{ __html: coloredContent }}
suppressContentEditableWarning={true}
/>
}
const placeholder = ''
const editAreaClassName = 'focus:outline-none bg-transparent text-sm'
const textAreaContent = (
<div className={classNames(readonly ? 'max-h-[180px] pb-5' : 'h-[180px]', ' overflow-y-auto')} onClick={() => !readonly && setIsEditing(true)}>
{isEditing
? <div className='h-full px-4 py-2'>
<textarea
ref={contentEditableRef}
className={classNames(editAreaClassName, 'block w-full h-full resize-none')}
placeholder={placeholder}
onChange={onValueChange}
value={currentValue}
onBlur={() => {
blur()
setIsEditing(false)
// click confirm also make blur. Then outer value is change. So below code has problem.
// setTimeout(() => {
// handleCancel()
// }, 1000)
}}
/>
</div>
: <TextAreaContentView />}
</div>)
return (
<div className={classNames('block-input w-full overflow-y-auto bg-white border-none rounded-xl')}>
{textAreaContent}
{/* footer */}
{!readonly && (
<div className='flex pb-2 pl-4'>
<div className="h-[18px] rounded-md bg-gray-100 px-1 text-xs leading-[18px] text-gray-500">{currentValue?.length}</div>
</div>
)}
</div>
)
}
export default React.memo(BlockInput)
'use client'
import type { FC } from 'react'
import React from 'react'
import { RiAddLine } from '@remixicon/react'
import cn from '@/utils/classnames'
type Props = {
className?: string
onClick: () => void
}
const AddButton: FC<Props> = ({
className,
onClick,
}) => {
return (
<div className={cn(className, 'cursor-pointer select-none rounded-md p-1 hover:bg-state-base-hover')} onClick={onClick}>
<RiAddLine className='h-4 w-4 text-text-tertiary' />
</div>
)
}
export default React.memo(AddButton)
@tailwind components;
@layer components {
.btn {
@apply inline-flex justify-center items-center cursor-pointer whitespace-nowrap;
}
.btn-disabled {
@apply cursor-not-allowed;
}
.btn-small {
@apply px-2 h-6 rounded-md text-xs font-medium;
}
.btn-medium {
@apply px-3.5 h-8 rounded-lg text-[13px] leading-4 font-medium;
}
.btn-large {
@apply px-4 h-9 rounded-[10px] text-sm font-semibold;
}
.btn-primary {
@apply
shadow
bg-components-button-primary-bg
border-components-button-primary-border
hover:bg-components-button-primary-bg-hover
hover:border-components-button-primary-border-hover
text-components-button-primary-text;
}
.btn-primary.btn-destructive {
@apply
bg-components-button-destructive-primary-bg
border-components-button-destructive-primary-border
hover:bg-components-button-destructive-primary-bg-hover
hover:border-components-button-destructive-primary-border-hover
text-components-button-destructive-primary-text;
}
.btn-primary.btn-disabled {
@apply
shadow-none
bg-components-button-primary-bg-disabled
border-components-button-primary-border-disabled
text-components-button-primary-text-disabled;
}
.btn-primary.btn-destructive.btn-disabled {
@apply
shadow-none
bg-components-button-destructive-primary-bg-disabled
border-components-button-destructive-primary-border-disabled
text-components-button-destructive-primary-text-disabled;
}
.btn-secondary {
@apply
border-[0.5px]
shadow-xs
bg-components-button-secondary-bg
border-components-button-secondary-border
hover:bg-components-button-secondary-bg-hover
hover:border-components-button-secondary-border-hover
text-components-button-secondary-text;
}
.btn-secondary.btn-disabled {
@apply
bg-components-button-secondary-bg-disabled
border-components-button-secondary-border-disabled
text-components-button-secondary-text-disabled;
}
.btn-secondary.btn-destructive {
@apply
bg-components-button-destructive-secondary-bg
border-components-button-destructive-secondary-border
hover:bg-components-button-destructive-secondary-bg-hover
hover:border-components-button-destructive-secondary-border-hover
text-components-button-destructive-secondary-text;
}
.btn-secondary.btn-destructive.btn-disabled {
@apply
bg-components-button-destructive-secondary-bg-disabled
border-components-button-destructive-secondary-border-disabled
text-components-button-destructive-secondary-text-disabled;
}
.btn-secondary-accent {
@apply
border-[0px]
hover:border-components-button-secondary-border-hover
text-components-button-secondary-accent-text;
background: #f5f8fc;
color: #383A3D;
}
.btn-secondary-accent.btn-disabled {
@apply
bg-components-button-secondary-bg-disabled
border-components-button-secondary-border-disabled
text-components-button-secondary-accent-text-disabled;
}
.btn-warning {
@apply
bg-components-button-destructive-primary-bg
border-components-button-destructive-primary-border
hover:bg-components-button-destructive-primary-bg-hover
hover:border-components-button-destructive-primary-border-hover
text-components-button-destructive-primary-text;
}
.btn-warning.btn-disabled {
@apply
bg-components-button-destructive-primary-bg-disabled
border-components-button-destructive-primary-border-disabled
text-components-button-destructive-primary-text-disabled;
}
.btn-tertiary {
@apply
bg-components-button-tertiary-bg
hover:bg-components-button-tertiary-bg-hover
text-components-button-tertiary-text;
}
.btn-tertiary.btn-disabled {
@apply
bg-components-button-tertiary-bg-disabled
text-components-button-tertiary-text-disabled;
}
.btn-tertiary.btn-destructive {
@apply
bg-components-button-destructive-tertiary-bg
hover:bg-components-button-destructive-tertiary-bg-hover
text-components-button-destructive-tertiary-text;
}
.btn-tertiary.btn-destructive.btn-disabled {
@apply
bg-components-button-destructive-tertiary-bg-disabled
text-components-button-destructive-tertiary-text-disabled;
}
.btn-ghost {
@apply
hover:bg-components-button-ghost-bg-hover
text-components-button-ghost-text;
}
.btn-ghost.btn-disabled {
@apply
text-components-button-ghost-text-disabled;
}
.btn-ghost.btn-destructive {
@apply
hover:bg-components-button-destructive-ghost-bg-hover
text-components-button-destructive-ghost-text;
}
.btn-ghost.btn-destructive.btn-disabled {
@apply
text-components-button-destructive-ghost-text-disabled;
}
.btn-ghost-accent {
@apply
hover:bg-state-accent-hover
text-components-button-secondary-accent-text;
}
.btn-ghost-accent.btn-disabled {
@apply
text-components-button-secondary-accent-text-disabled;
}
.arrow-icon {
display: inline-block;
margin-left: 10px;
width: 8px;
height: 8px;
border-top: 1.5px solid #969BA3;
border-right: 1.5px solid #969BA3;
transform: rotate(45deg);
}
}
.btn-block{
@apply w-full;
@apply h-full;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
font-size: 15px;
color: #13336866;
}
.btn-primary.btn-block {
color: #133368;
}
import React from 'react'
import { cleanup, fireEvent, render } from '@testing-library/react'
import Button from './index'
afterEach(cleanup)
// https://testing-library.com/docs/queries/about
describe('Button', () => {
describe('Button text', () => {
test('Button text should be same as children', async () => {
const { getByRole, container } = render(<Button>Click me</Button>)
expect(getByRole('button').textContent).toBe('Click me')
expect(container.querySelector('button')?.textContent).toBe('Click me')
})
})
describe('Button loading', () => {
test('Loading button text should include same as children', async () => {
const { getByRole } = render(<Button loading>Click me</Button>)
expect(getByRole('button').textContent?.includes('Loading')).toBe(true)
})
test('Not loading button text should include same as children', async () => {
const { getByRole } = render(<Button loading={false}>Click me</Button>)
expect(getByRole('button').textContent?.includes('Loading')).toBe(false)
})
test('Loading button should have loading classname', async () => {
const animClassName = 'anim-breath'
const { getByRole } = render(<Button loading spinnerClassName={animClassName}>Click me</Button>)
expect(getByRole('button').getElementsByClassName('animate-spin')[0]?.className).toContain(animClassName)
})
})
describe('Button style', () => {
test('Button should have default variant', async () => {
const { getByRole } = render(<Button>Click me</Button>)
expect(getByRole('button').className).toContain('btn-secondary')
})
test('Button should have primary variant', async () => {
const { getByRole } = render(<Button variant='primary'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-primary')
})
test('Button should have warning variant', async () => {
const { getByRole } = render(<Button variant='warning'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-warning')
})
test('Button should have secondary variant', async () => {
const { getByRole } = render(<Button variant='secondary'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-secondary')
})
test('Button should have secondary-accent variant', async () => {
const { getByRole } = render(<Button variant='secondary-accent'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-secondary-accent')
})
test('Button should have ghost variant', async () => {
const { getByRole } = render(<Button variant='ghost'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-ghost')
})
test('Button should have ghost-accent variant', async () => {
const { getByRole } = render(<Button variant='ghost-accent'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-ghost-accent')
})
test('Button disabled should have disabled variant', async () => {
const { getByRole } = render(<Button disabled>Click me</Button>)
expect(getByRole('button').className).toContain('btn-disabled')
})
})
describe('Button size', () => {
test('Button should have default size', async () => {
const { getByRole } = render(<Button>Click me</Button>)
expect(getByRole('button').className).toContain('btn-medium')
})
test('Button should have small size', async () => {
const { getByRole } = render(<Button size='small'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-small')
})
test('Button should have medium size', async () => {
const { getByRole } = render(<Button size='medium'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-medium')
})
test('Button should have large size', async () => {
const { getByRole } = render(<Button size='large'>Click me</Button>)
expect(getByRole('button').className).toContain('btn-large')
})
})
describe('Button destructive', () => {
test('Button should have destructive classname', async () => {
const { getByRole } = render(<Button destructive>Click me</Button>)
expect(getByRole('button').className).toContain('btn-destructive')
})
})
describe('Button events', () => {
test('onClick should been call after clicked', async () => {
const onClick = jest.fn()
const { getByRole } = render(<Button onClick={onClick}>Click me</Button>)
fireEvent.click(getByRole('button'))
expect(onClick).toHaveBeenCalled()
})
})
})
import type { Meta, StoryObj } from '@storybook/react'
import { fn } from '@storybook/test'
import { RocketLaunchIcon } from '@heroicons/react/20/solid'
import { Button } from '.'
const meta = {
title: 'Base/Button',
component: Button,
parameters: {
layout: 'centered',
},
tags: ['autodocs'],
argTypes: {
loading: { control: 'boolean' },
variant: {
control: 'select',
options: ['primary', 'warning', 'secondary', 'secondary-accent', 'ghost', 'ghost-accent', 'tertiary'],
},
},
args: {
variant: 'ghost',
onClick: fn(),
children: 'adsf',
},
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: {
variant: 'primary',
loading: false,
children: 'Primary Button',
},
}
export const Secondary: Story = {
args: {
variant: 'secondary',
children: 'Secondary Button',
},
}
export const SecondaryAccent: Story = {
args: {
variant: 'secondary-accent',
children: 'Secondary Accent Button',
},
}
export const Ghost: Story = {
args: {
variant: 'ghost',
children: 'Ghost Button',
},
}
export const GhostAccent: Story = {
args: {
variant: 'ghost-accent',
children: 'Ghost Accent Button',
},
}
export const Tertiary: Story = {
args: {
variant: 'tertiary',
children: 'Tertiary Button',
},
}
export const Warning: Story = {
args: {
variant: 'warning',
children: 'Warning Button',
},
}
export const Disabled: Story = {
args: {
variant: 'primary',
disabled: true,
children: 'Disabled Button',
},
}
export const Loading: Story = {
args: {
variant: 'primary',
loading: true,
children: 'Loading Button',
},
}
export const WithIcon: Story = {
args: {
variant: 'primary',
children: (
<>
<RocketLaunchIcon className="mr-1.5 h-4 w-4 stroke-[1.8px]" />
Launch
</>
),
},
}
/*
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: yangming@didihu.com.cn yangming@didihu.com.cn
* @LastEditTime: 2025-05-02 12:03:38
* @FilePath: \glsk-ai-assistant\app\components\base\button\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { CSSProperties } from "react";
import React from "react";
import { type VariantProps, cva } from "class-variance-authority";
import Spinner from "../spinner";
import classNames from "@/utils/classnames";
const buttonVariants = cva("btn disabled:btn-disabled", {
variants: {
variant: {
primary: "btn-primary",
warning: "btn-warning",
secondary: "btn-secondary",
"secondary-accent": "btn-secondary-accent",
ghost: "btn-ghost",
"ghost-accent": "btn-ghost-accent",
tertiary: "btn-tertiary",
},
size: {
small: "btn-small",
medium: "btn-medium",
large: "btn-large",
},
},
defaultVariants: {
variant: "secondary",
size: "medium",
},
});
export type ButtonProps = {
destructive?: boolean;
loading?: boolean;
styleCss?: CSSProperties;
showArrow?: boolean;
spinnerClassName?: string;
isBlock?: boolean;
} & React.ButtonHTMLAttributes<HTMLButtonElement> &
VariantProps<typeof buttonVariants>;
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
(
{
className,
variant,
size,
destructive,
loading,
styleCss,
showArrow,
children,
spinnerClassName,
isBlock,
...props
},
ref
) => {
return (
<button
type="button"
className={classNames(
buttonVariants({ variant, size, className }),
destructive && "btn-destructive",
isBlock && "btn-block"
)}
ref={ref}
style={styleCss}
{...props}
>
{children}
{loading && (
<Spinner
loading={loading}
className={classNames(
"!text-white !h-3 !w-3 !border-2 !ml-1",
spinnerClassName
)}
/>
)}
{showArrow && <span className="arrow-icon"></span>}
</button>
);
}
);
Button.displayName = "Button";
export default Button;
export { Button, buttonVariants };
/*
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-29 16:57:03
* @LastEditors: yangming@didihu.com.cn yangming@didihu.com.cn
* @LastEditTime: 2025-05-15 16:46:26
* @FilePath: \glsk-ai-assistant\app\components\base\button\next-button.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { CSSProperties } from 'react'
import React from 'react'
import { type VariantProps, cva } from 'class-variance-authority'
import Spinner from '../spinner'
import classNames from '@/utils/classnames'
const buttonVariants = cva('btn disabled:btn-disabled', {
variants: {
variant: {
primary: 'btn-primary',
warning: 'btn-warning',
secondary: 'btn-secondary',
'secondary-accent': 'btn-secondary-accent',
ghost: 'btn-ghost',
'ghost-accent': 'btn-ghost-accent',
tertiary: 'btn-tertiary',
},
size: {
small: 'btn-small',
medium: 'btn-medium',
large: 'btn-large',
},
},
defaultVariants: {
variant: 'secondary',
size: 'medium',
},
})
export type ButtonProps = {
text: string
onClick?: () => void
}
const Button = ({ text, onClick }: ButtonProps) => {
return (
<div onClick={onClick} className="flex items-center bg-[#f5f8fc] rounded-[8px] cursor-pointer justify-between p-2 mr-1 mt-3 max-w-full shrink-0 last:mr-0">
<div className="text-[#383A3D]">{text}</div>
<div className="w-6">
<div className="arrow-icon"></div>
</div>
</div>
)
}
export default Button
export { Button, buttonVariants }
[
{
"id": "question-1",
"isAnswer": false,
"parentMessageId": null
},
{
"id": "1",
"isAnswer": true,
"parentMessageId": "question-1"
},
{
"id": "question-2",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "2",
"isAnswer": true,
"parentMessageId": "question-2"
},
{
"id": "question-3",
"isAnswer": false,
"parentMessageId": "2"
},
{
"id": "3",
"isAnswer": true,
"parentMessageId": "question-3"
},
{
"id": "question-4",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "4",
"isAnswer": true,
"parentMessageId": "question-4"
}
]
[
{
"id": "question-1",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "1",
"isAnswer": true,
"parentMessageId": "question-1"
},
{
"id": "question-2",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "2",
"isAnswer": true,
"parentMessageId": "question-2"
},
{
"id": "question-3",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "3",
"isAnswer": true,
"parentMessageId": "question-3"
},
{
"id": "question-4",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "4",
"isAnswer": true,
"parentMessageId": "question-4"
}
]
[
{
"id": "question-1",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "1",
"isAnswer": true,
"parentMessageId": "question-1"
},
{
"id": "question-2",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "2",
"isAnswer": true,
"parentMessageId": "question-2"
},
{
"id": "question-3",
"isAnswer": false,
"parentMessageId": "2"
},
{
"id": "3",
"isAnswer": true,
"parentMessageId": "question-3"
},
{
"id": "question-4",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "4",
"isAnswer": true,
"parentMessageId": "question-4"
}
]
[
{
"id": "question-1",
"isAnswer": false,
"parentMessageId": null
},
{
"id": "1",
"isAnswer": true,
"parentMessageId": "question-1"
},
{
"id": "question-2",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "2",
"isAnswer": true,
"parentMessageId": "question-2"
},
{
"id": "question-3",
"isAnswer": false,
"parentMessageId": "2"
},
{
"id": "3",
"isAnswer": true,
"parentMessageId": "question-3"
},
{
"id": "question-4",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "4",
"isAnswer": true,
"parentMessageId": "question-4"
},
{
"id": "question-5",
"isAnswer": false,
"parentMessageId": null
},
{
"id": "5",
"isAnswer": true,
"parentMessageId": "question-5"
}
]
[
{
"id": "question-1",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "1",
"isAnswer": true,
"parentMessageId": "question-1"
},
{
"id": "question-2",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "2",
"isAnswer": true,
"parentMessageId": "question-2"
},
{
"id": "question-3",
"isAnswer": false,
"parentMessageId": "00000000-0000-0000-0000-000000000000"
},
{
"id": "3",
"isAnswer": true,
"parentMessageId": "question-3"
},
{
"id": "question-4",
"isAnswer": false,
"parentMessageId": "1"
},
{
"id": "4",
"isAnswer": true,
"parentMessageId": "question-4"
},
{
"id": "question-5",
"isAnswer": false,
"parentMessageId": null
},
{
"id": "5",
"isAnswer": true,
"parentMessageId": "question-5"
}
]
[
{
"id": "question-ebb73fe2-15de-46dd-aab5-75416d8448eb",
"content": "123",
"isAnswer": false,
"parentMessageId": "57c989f9-3fa4-4dec-9ee5-c3568dd27418"
},
{
"id": "ebb73fe2-15de-46dd-aab5-75416d8448eb",
"content": "237.",
"isAnswer": true,
"parentMessageId": "question-ebb73fe2-15de-46dd-aab5-75416d8448eb"
},
{
"id": "question-3553d508-3850-462e-8594-078539f940f9",
"content": "123",
"isAnswer": false,
"parentMessageId": "57c989f9-3fa4-4dec-9ee5-c3568dd27418"
},
{
"id": "3553d508-3850-462e-8594-078539f940f9",
"content": "My number is 256.",
"isAnswer": true,
"parentMessageId": "question-3553d508-3850-462e-8594-078539f940f9"
},
{
"id": "question-507f9df9-1f06-4a57-bb38-f00228c42c22",
"content": "123",
"isAnswer": false,
"parentMessageId": "57c989f9-3fa4-4dec-9ee5-c3568dd27418"
},
{
"id": "507f9df9-1f06-4a57-bb38-f00228c42c22",
"content": "My number is 259.",
"isAnswer": true,
"parentMessageId": "question-507f9df9-1f06-4a57-bb38-f00228c42c22"
},
{
"id": "question-9e51a13b-7780-4565-98dc-f2d8c3b1758f",
"content": "1024",
"isAnswer": false,
"parentMessageId": "507f9df9-1f06-4a57-bb38-f00228c42c22"
},
{
"id": "9e51a13b-7780-4565-98dc-f2d8c3b1758f",
"content": "My number is 2048.",
"isAnswer": true,
"parentMessageId": "question-9e51a13b-7780-4565-98dc-f2d8c3b1758f"
},
{
"id": "question-93bac05d-1470-4ac9-b090-fe21cd7c3d55",
"content": "3306",
"isAnswer": false,
"parentMessageId": "9e51a13b-7780-4565-98dc-f2d8c3b1758f"
},
{
"id": "93bac05d-1470-4ac9-b090-fe21cd7c3d55",
"content": "My number is 4782.",
"isAnswer": true,
"parentMessageId": "question-93bac05d-1470-4ac9-b090-fe21cd7c3d55"
},
{
"id": "question-a956de3d-ef95-4d90-84fe-f7a26ef28cd7",
"content": "-5",
"isAnswer": false,
"parentMessageId": "93bac05d-1470-4ac9-b090-fe21cd7c3d55"
},
{
"id": "a956de3d-ef95-4d90-84fe-f7a26ef28cd7",
"content": "My number is 22.",
"isAnswer": true,
"parentMessageId": "question-a956de3d-ef95-4d90-84fe-f7a26ef28cd7"
},
{
"id": "question-3cded945-855a-4a24-aab7-43c7dd54664c",
"content": "3.11",
"isAnswer": false,
"parentMessageId": "a956de3d-ef95-4d90-84fe-f7a26ef28cd7"
},
{
"id": "3cded945-855a-4a24-aab7-43c7dd54664c",
"content": "My number is 7.89.",
"isAnswer": true,
"parentMessageId": "question-3cded945-855a-4a24-aab7-43c7dd54664c"
},
{
"id": "question-46a49bb9-0881-459e-8c6a-24d20ae48d2f",
"content": "78",
"isAnswer": false,
"parentMessageId": "3cded945-855a-4a24-aab7-43c7dd54664c"
},
{
"id": "46a49bb9-0881-459e-8c6a-24d20ae48d2f",
"content": "My number is 145.",
"isAnswer": true,
"parentMessageId": "question-46a49bb9-0881-459e-8c6a-24d20ae48d2f"
},
{
"id": "question-5c56a2b3-f057-42a0-9b2c-52a35713cd8c",
"content": "π",
"isAnswer": false,
"parentMessageId": "46a49bb9-0881-459e-8c6a-24d20ae48d2f"
},
{
"id": "5c56a2b3-f057-42a0-9b2c-52a35713cd8c",
"content": "My number is 2π (approximately 6.28).",
"isAnswer": true,
"parentMessageId": "question-5c56a2b3-f057-42a0-9b2c-52a35713cd8c"
},
{
"id": "question-9eac3bcc-8d3b-4e56-a12b-44c34cebc719",
"content": "e",
"isAnswer": false,
"parentMessageId": "5c56a2b3-f057-42a0-9b2c-52a35713cd8c"
},
{
"id": "9eac3bcc-8d3b-4e56-a12b-44c34cebc719",
"content": "My number is 3e (approximately 8.15).",
"isAnswer": true,
"parentMessageId": "question-9eac3bcc-8d3b-4e56-a12b-44c34cebc719"
}
]
import { get } from 'lodash-es'
import { buildChatItemTree, getThreadMessages } from '../utils'
import type { ChatItemInTree } from '../types'
import branchedTestMessages from './branchedTestMessages.json'
import legacyTestMessages from './legacyTestMessages.json'
import mixedTestMessages from './mixedTestMessages.json'
import multiRootNodesMessages from './multiRootNodesMessages.json'
import multiRootNodesWithLegacyTestMessages from './multiRootNodesWithLegacyTestMessages.json'
import realWorldMessages from './realWorldMessages.json'
import partialMessages from './partialMessages.json'
function visitNode(tree: ChatItemInTree | ChatItemInTree[], path: string): ChatItemInTree {
return get(tree, path)
}
describe('build chat item tree and get thread messages', () => {
const tree1 = buildChatItemTree(branchedTestMessages as ChatItemInTree[])
it('should build chat item tree1', () => {
const a1 = visitNode(tree1, '0.children.0')
expect(a1.id).toBe('1')
expect(a1.children).toHaveLength(2)
const a2 = visitNode(a1, 'children.0.children.0')
expect(a2.id).toBe('2')
expect(a2.siblingIndex).toBe(0)
const a3 = visitNode(a2, 'children.0.children.0')
expect(a3.id).toBe('3')
const a4 = visitNode(a1, 'children.1.children.0')
expect(a4.id).toBe('4')
expect(a4.siblingIndex).toBe(1)
})
it('should get thread messages from tree1, using the last message as the target', () => {
const threadChatItems1_1 = getThreadMessages(tree1)
expect(threadChatItems1_1).toHaveLength(4)
const q1 = visitNode(threadChatItems1_1, '0')
const a1 = visitNode(threadChatItems1_1, '1')
const q4 = visitNode(threadChatItems1_1, '2')
const a4 = visitNode(threadChatItems1_1, '3')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q4.id).toBe('question-4')
expect(a4.id).toBe('4')
expect(a4.siblingCount).toBe(2)
expect(a4.siblingIndex).toBe(1)
})
it('should get thread messages from tree1, using the message with id 3 as the target', () => {
const threadChatItems1_2 = getThreadMessages(tree1, '3')
expect(threadChatItems1_2).toHaveLength(6)
const q1 = visitNode(threadChatItems1_2, '0')
const a1 = visitNode(threadChatItems1_2, '1')
const q2 = visitNode(threadChatItems1_2, '2')
const a2 = visitNode(threadChatItems1_2, '3')
const q3 = visitNode(threadChatItems1_2, '4')
const a3 = visitNode(threadChatItems1_2, '5')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q2.id).toBe('question-2')
expect(a2.id).toBe('2')
expect(q3.id).toBe('question-3')
expect(a3.id).toBe('3')
expect(a2.siblingCount).toBe(2)
expect(a2.siblingIndex).toBe(0)
})
const tree2 = buildChatItemTree(legacyTestMessages as ChatItemInTree[])
it('should work with legacy chat items', () => {
expect(tree2).toHaveLength(1)
const q1 = visitNode(tree2, '0')
const a1 = visitNode(q1, 'children.0')
const q2 = visitNode(a1, 'children.0')
const a2 = visitNode(q2, 'children.0')
const q3 = visitNode(a2, 'children.0')
const a3 = visitNode(q3, 'children.0')
const q4 = visitNode(a3, 'children.0')
const a4 = visitNode(q4, 'children.0')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q2.id).toBe('question-2')
expect(a2.id).toBe('2')
expect(q3.id).toBe('question-3')
expect(a3.id).toBe('3')
expect(q4.id).toBe('question-4')
expect(a4.id).toBe('4')
})
it('should get thread messages from tree2, using the last message as the target', () => {
const threadMessages2 = getThreadMessages(tree2)
expect(threadMessages2).toHaveLength(8)
const q1 = visitNode(threadMessages2, '0')
const a1 = visitNode(threadMessages2, '1')
const q2 = visitNode(threadMessages2, '2')
const a2 = visitNode(threadMessages2, '3')
const q3 = visitNode(threadMessages2, '4')
const a3 = visitNode(threadMessages2, '5')
const q4 = visitNode(threadMessages2, '6')
const a4 = visitNode(threadMessages2, '7')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q2.id).toBe('question-2')
expect(a2.id).toBe('2')
expect(q3.id).toBe('question-3')
expect(a3.id).toBe('3')
expect(q4.id).toBe('question-4')
expect(a4.id).toBe('4')
expect(a1.siblingCount).toBe(1)
expect(a1.siblingIndex).toBe(0)
expect(a2.siblingCount).toBe(1)
expect(a2.siblingIndex).toBe(0)
expect(a3.siblingCount).toBe(1)
expect(a3.siblingIndex).toBe(0)
expect(a4.siblingCount).toBe(1)
expect(a4.siblingIndex).toBe(0)
})
const tree3 = buildChatItemTree(mixedTestMessages as ChatItemInTree[])
it('should build mixed chat items tree', () => {
expect(tree3).toHaveLength(1)
const a1 = visitNode(tree3, '0.children.0')
expect(a1.id).toBe('1')
expect(a1.children).toHaveLength(2)
const a2 = visitNode(a1, 'children.0.children.0')
expect(a2.id).toBe('2')
expect(a2.siblingIndex).toBe(0)
const a3 = visitNode(a2, 'children.0.children.0')
expect(a3.id).toBe('3')
const a4 = visitNode(a1, 'children.1.children.0')
expect(a4.id).toBe('4')
expect(a4.siblingIndex).toBe(1)
})
it('should get thread messages from tree3, using the last message as the target', () => {
const threadMessages3_1 = getThreadMessages(tree3)
expect(threadMessages3_1).toHaveLength(4)
const q1 = visitNode(threadMessages3_1, '0')
const a1 = visitNode(threadMessages3_1, '1')
const q4 = visitNode(threadMessages3_1, '2')
const a4 = visitNode(threadMessages3_1, '3')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q4.id).toBe('question-4')
expect(a4.id).toBe('4')
expect(a4.siblingCount).toBe(2)
expect(a4.siblingIndex).toBe(1)
})
it('should get thread messages from tree3, using the message with id 3 as the target', () => {
const threadMessages3_2 = getThreadMessages(tree3, '3')
expect(threadMessages3_2).toHaveLength(6)
const q1 = visitNode(threadMessages3_2, '0')
const a1 = visitNode(threadMessages3_2, '1')
const q2 = visitNode(threadMessages3_2, '2')
const a2 = visitNode(threadMessages3_2, '3')
const q3 = visitNode(threadMessages3_2, '4')
const a3 = visitNode(threadMessages3_2, '5')
expect(q1.id).toBe('question-1')
expect(a1.id).toBe('1')
expect(q2.id).toBe('question-2')
expect(a2.id).toBe('2')
expect(q3.id).toBe('question-3')
expect(a3.id).toBe('3')
expect(a2.siblingCount).toBe(2)
expect(a2.siblingIndex).toBe(0)
})
const tree4 = buildChatItemTree(multiRootNodesMessages as ChatItemInTree[])
it('should build multi root nodes chat items tree', () => {
expect(tree4).toHaveLength(2)
const a5 = visitNode(tree4, '1.children.0')
expect(a5.id).toBe('5')
expect(a5.siblingIndex).toBe(1)
})
it('should get thread messages from tree4, using the last message as the target', () => {
const threadMessages4 = getThreadMessages(tree4)
expect(threadMessages4).toHaveLength(2)
const a1 = visitNode(threadMessages4, '0.children.0')
expect(a1.id).toBe('5')
})
it('should get thread messages from tree4, using the message with id 2 as the target', () => {
const threadMessages4_1 = getThreadMessages(tree4, '2')
expect(threadMessages4_1).toHaveLength(6)
const a1 = visitNode(threadMessages4_1, '1')
expect(a1.id).toBe('1')
const a2 = visitNode(threadMessages4_1, '3')
expect(a2.id).toBe('2')
const a3 = visitNode(threadMessages4_1, '5')
expect(a3.id).toBe('3')
})
const tree5 = buildChatItemTree(multiRootNodesWithLegacyTestMessages as ChatItemInTree[])
it('should work with multi root nodes chat items with legacy chat items', () => {
expect(tree5).toHaveLength(2)
const q5 = visitNode(tree5, '1')
expect(q5.id).toBe('question-5')
expect(q5.parentMessageId).toBe(null)
const a5 = visitNode(q5, 'children.0')
expect(a5.id).toBe('5')
expect(a5.children).toHaveLength(0)
})
it('should get thread messages from tree5, using the last message as the target', () => {
const threadMessages5 = getThreadMessages(tree5)
expect(threadMessages5).toHaveLength(2)
const q5 = visitNode(threadMessages5, '0')
const a5 = visitNode(threadMessages5, '1')
expect(q5.id).toBe('question-5')
expect(a5.id).toBe('5')
expect(a5.siblingCount).toBe(2)
expect(a5.siblingIndex).toBe(1)
})
const tree6 = buildChatItemTree(realWorldMessages as ChatItemInTree[])
it('should work with real world messages', () => {
expect(tree6).toMatchSnapshot()
})
it ('should get thread messages from tree6, using the last message as target', () => {
const threadMessages6_1 = getThreadMessages(tree6)
expect(threadMessages6_1).toMatchSnapshot()
})
it ('should get thread messages from tree6, using specified message as target', () => {
const threadMessages6_2 = getThreadMessages(tree6, 'ff4c2b43-48a5-47ad-9dc5-08b34ddba61b')
expect(threadMessages6_2).toMatchSnapshot()
})
const partialMessages1 = (realWorldMessages as ChatItemInTree[]).slice(-10)
const tree7 = buildChatItemTree(partialMessages1)
it('should work with partial messages 1', () => {
expect(tree7).toMatchSnapshot()
})
const partialMessages2 = partialMessages as ChatItemInTree[]
const tree8 = buildChatItemTree(partialMessages2)
it('should work with partial messages 2', () => {
expect(tree8).toMatchSnapshot()
})
})
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-28 17:41:15
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
*/
import { useEffect, FC, useCallback, useRef, useState } from 'react'
import Chat from '../chat'
import { useChat, useUrlParams } from './hooks'
import { InputMessageType } from '../types'
import {
ChatContextProvider,
ChatConfigProvider,
ChatListProvider,
ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context'
import React from 'react'
import { useStore } from '@/app/components/app/store'
enum MessageListenerType {
RESET_CHAT = 'reset_chat',
}
type MessageListenerProps = {
payload: {
tags?: string[]
message?: string
}
type: MessageListenerType
}
const SEND_MESSAGE_KEY = 'sendMessage' // 使用 Symbol 避免命名冲突
const NEXT_SCENE_KEY = 'nextScene' // 下一场景全局方法键名
// 扩展 globalThis 类型
interface IGlobalThis {
[SEND_MESSAGE_KEY]?: (data: MessageListenerProps) => void
[NEXT_SCENE_KEY]?: () => void
}
type Props = {
presuppositionQuestion?: string
inputs?: Record<string, any>
// isShowPracticeButton: boolean
}
const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) => {
const setScenarioSummaryIndex = useStore(state => state.setScenarioSummaryIndex)
const setCustomerOriginal = useStore(state => state.setCustomerOriginal)
const setScenarioSummary = useStore(state => state.setScenarioSummary)
const setScenarioType = useStore(state => state.setScenarioType)
const setReviewPassed = useStore(state => state.setReviewPassed)
const [isAutoSend, setAutoSend] = useState<boolean>(true)
const [autoSendQuestion, setAutoSendQuestion] = useState<string | undefined>(presuppositionQuestion)
const {
config,
chatList,
handleStop,
sendMessage,
doRegenerate,
// appInfoError,
isResponding,
handleRestart,
handleFeedback,
// appInfoLoading,
handleNewConversation,
isManuallyStopped,
taskId,
} = useChat(inputs, useStore())
useEffect(() => {
if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) {
const timer = setTimeout(() => {
sendMessage(autoSendQuestion, InputMessageType.BY_AUTO)
setAutoSend(false)
}, 0)
return () => clearTimeout(timer)
}
}, [autoSendQuestion, config.initial_message, isAutoSend])
const handleGlobalMessage = useCallback((data: MessageListenerProps) => {
try {
switch (data?.type) {
case MessageListenerType.RESET_CHAT:
handleNewConversation(undefined, false) // 重新开启一次会话
const message = data?.payload?.message
setAutoSendQuestion(message) //可能没有预设消息,但是也要更新 重置对话的时候也要保持没有预设消息
message && setAutoSend(true) // 有预设消息才自动发送
break
}
} catch (error) {
console.error('send failed:', error)
}
}, [])
const handleNextScene = useCallback((data: any) => {
let sceneData = data
try {
setScenarioType(sceneData.type)
setScenarioSummary(sceneData.scenario_summary)
setCustomerOriginal(sceneData.customer_original)
setScenarioSummaryIndex(sceneData.scenario_summary_index)
setReviewPassed(false)
} catch (error) {
console.error('nextScene failed:', error)
}
}, [])
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: handleGlobalMessage,
writable: false,
configurable: true,
enumerable: false,
})
Object.defineProperty(globalThis, NEXT_SCENE_KEY, {
value: handleNextScene,
writable: false,
configurable: true,
enumerable: false,
})
return () => {
if (SEND_MESSAGE_KEY in globalThis) {
delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY]
}
if (NEXT_SCENE_KEY in globalThis) {
delete (globalThis as IGlobalThis)[NEXT_SCENE_KEY]
}
}
}, [handleGlobalMessage, handleNextScene])
const onRestart = useCallback(() => {
setAutoSend(true)
handleRestart()
}, [])
if (config.initial_message === undefined) return null
return (
<div className="h-full overflow-hidden">
<ChatConfigProvider config={config}>
<ChatContextProvider
onSend={sendMessage}
onRegenerate={doRegenerate}
onRestart={onRestart}
onFeedback={handleFeedback}
onStopResponding={handleStop}>
<ChatRespondingProvider isResponding={isResponding} taskId={taskId}>
<ChatListProvider chatList={chatList} isManuallyStopped={isManuallyStopped}>
<Chat />
</ChatListProvider>
</ChatRespondingProvider>
</ChatContextProvider>
</ChatConfigProvider>
</div>
)
})
export default ChatWrapper
// app/components/base/chat/chat/chat-config-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatConfig } from '../../types'
import { useMemo } from 'react'
const ChatConfigContext = createContext<ChatConfig>({} as ChatConfig)
type Props = {
children: React.ReactNode
config: ChatConfig
}
export const ChatConfigProvider = ({ children, config }: Props) => {
const value = useMemo(() => {
return {
appId: config.appId,
initial_message: config.initial_message,
suggested_questions: config.suggested_questions,
file_upload: config.file_upload,
supportFeedback: config.supportFeedback,
supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text,
}
}, []) as ChatConfig
return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider>
}
export const useChatConfigContext = () => useContext(ChatConfigContext)
'use client'
import { useCallback, useMemo } from 'react'
import { createContext, useContext } from 'use-context-selector'
import { noop } from 'lodash-es'
import type { ChatItem, Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types'
import { FileEntity } from '@/app/components/base/file-uploader/types'
export type OnSendMessage = (
message: string,
type?: InputMessageType,
files?: FileEntity[],
parentMessageId?: string,
) => void
export type ChatContextValue = {
onSend: OnSendMessage
onRegenerate?: OnRegenerate
onRestart: () => void
onFeedback?: (messageId: string, feedback: Feedback) => void
onStopResponding?: () => void
}
const ChatContext = createContext<ChatContextValue>({
onRestart: noop,
onSend: noop,
onFeedback: noop,
onStopResponding: noop,
})
type ChatContextProviderProps = {
children: React.ReactNode
} & ChatContextValue
export const ChatContextProvider = ({
children,
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}: ChatContextProviderProps) => {
const value = useMemo(
() => ({
onSend,
onRegenerate,
onRestart,
onFeedback,
onStopResponding,
}),
[onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
)
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
}
export const useChatContext = () => useContext(ChatContext)
export default ChatContext
// app/components/base/chat/chat/chat-runtime-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types'
import { useMemo } from 'react'
type ChatListContext = {
chatList: ChatItem[]
isManuallyStopped?: boolean // 添加手动停止标记
}
const ChatListContext = createContext<ChatListContext>({
chatList: [],
isManuallyStopped: false,
})
export const useChatListContext = () => useContext(ChatListContext)
type Props = {
children: React.ReactNode
} & ChatListContext
export const ChatListProvider = ({ children, chatList, isManuallyStopped }: Props) => {
const value = { chatList, isManuallyStopped }
return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider>
}
\ No newline at end of file \ No newline at end of file
// app/components/base/chat/chat/chat-runtime-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import { useEffect, useMemo } from 'react'
import { usePostMessage } from '../hooks'
type RespondingContext = {
isResponding?: boolean
taskId?: string
}
const ChatRespondingContext = createContext<RespondingContext>({
isResponding: false,
taskId: '',
})
export const useChatRespondingContext = () => useContext(ChatRespondingContext)
type Props = {
children: React.ReactNode
} & RespondingContext
const postMessage = usePostMessage()
export const ChatRespondingProvider = ({ children, isResponding, taskId }: Props) => {
const __isResponding = useMemo(() => isResponding, [isResponding])
const __taskId = useMemo(() => taskId, [taskId])
const value = useMemo(() => ({ isResponding: __isResponding, taskId: __taskId }), [__isResponding, __taskId])
useEffect(() => postMessage(value), [__isResponding, __taskId])
return <ChatRespondingContext.Provider value={value}>{children}</ChatRespondingContext.Provider>
}
"use client";
import type { RefObject } from "react";
import { createContext, useContext } from "use-context-selector";
import type { Callback, ChatConfig, ChatItemInTree, Feedback } from "../types";
import type { ThemeBuilder } from "../embedded-chatbot/theme/theme-context";
import type {
AppData,
AppMeta,
ConversationItem,
} from "@/models/share";
import { noop } from "lodash-es";
export type ChatWithHistoryContextValue = {
appInfoError?: any;
appInfoLoading?: boolean;
appMeta?: AppMeta;
appData?: AppData;
appParams?: ChatConfig;
appChatListDataLoading?: boolean;
currentConversationId: string;
currentConversationItem?: ConversationItem;
appPrevChatTree: ChatItemInTree[];
newConversationInputs: Record<string, any>;
newConversationInputsRef: RefObject<Record<string, any>>;
handleNewConversation: (v?: Record<string, any>,skipClear?:boolean) => void;
handleNewConversationCompleted?: (newConversationId: string) => void;
chatShouldReloadKey?: string;
isMobile?: boolean;
isInstalledApp: boolean;
appId?: string;
handleFeedback: (messageId: string, feedback: Feedback) => void;
currentChatInstanceRef: RefObject<{ handleStop: () => void }>;
themeBuilder?: ThemeBuilder;
clearChatList?: boolean;
setClearChatList?: (state: boolean) => void;
isResponding?: boolean;
setIsResponding: (state: boolean) => void;
currentConversationInputs?: Record<string, any> | null;
isShowPracticeButton: boolean;
};
export const ChatWithHistoryContext =
createContext<ChatWithHistoryContextValue>({
currentConversationId: "",
appPrevChatTree: [],
newConversationInputs: {},
newConversationInputsRef: { current: {} },
handleNewConversation: noop,
handleNewConversationCompleted: noop,
chatShouldReloadKey: "",
isMobile: false,
isInstalledApp: false,
handleFeedback: noop,
currentChatInstanceRef: { current: { handleStop: noop } },
clearChatList: false,
setClearChatList: noop,
isResponding: false,
setIsResponding: noop,
currentConversationInputs: {},
isShowPracticeButton: false,
});
export const useChatWithHistoryContext = () =>
useContext(ChatWithHistoryContext);
export { ChatConfigProvider, useChatConfigContext } from './chat-config-context'
export { ChatContextProvider, useChatContext } from './chat-context'
export { ChatListProvider, useChatListContext } from './chat-list-context'
export { ChatRespondingProvider, useChatRespondingContext } from './chat-responding-context'
// import { useCallback, useState } from 'react'
// import { useTranslation } from 'react-i18next'
// import {
// RiMenuLine,
// } from '@remixicon/react'
// import { useChatWithHistoryContext } from './context'
// import Operation from './header/operation'
// import Sidebar from './sidebar'
// import MobileOperationDropdown from './header/mobile-operation-dropdown'
// import AppIcon from '@/app/components/base/app-icon'
// import ActionButton from '@/app/components/base/action-button'
// import { Message3Fill } from '@/app/components/base/icons/src/public/other'
// import InputsFormContent from '@/app/components/base/chat/chat-with-history/inputs-form/content'
// import Confirm from '@/app/components/base/confirm'
// import RenameModal from '@/app/components/base/chat/chat-with-history/sidebar/rename-modal'
// import type { ConversationItem } from '@/models/share'
// const HeaderInMobile = () => {
// const {
// appData,
// currentConversationId,
// currentConversationItem,
// pinnedConversationList,
// handleNewConversation,
// handlePinConversation,
// handleUnpinConversation,
// handleDeleteConversation,
// handleRenameConversation,
// conversationRenaming,
// } = useChatWithHistoryContext()
// const { t } = useTranslation()
// const isPin = pinnedConversationList.some(item => item.id === currentConversationId)
// const [showConfirm, setShowConfirm] = useState<ConversationItem | null>(null)
// const [showRename, setShowRename] = useState<ConversationItem | null>(null)
// const handleOperate = useCallback((type: string) => {
// if (type === 'pin')
// handlePinConversation(currentConversationId)
// if (type === 'unpin')
// handleUnpinConversation(currentConversationId)
// if (type === 'delete')
// setShowConfirm(currentConversationItem as any)
// if (type === 'rename')
// setShowRename(currentConversationItem as any)
// }, [currentConversationId, currentConversationItem, handlePinConversation, handleUnpinConversation])
// const handleCancelConfirm = useCallback(() => {
// setShowConfirm(null)
// }, [])
// const handleDelete = useCallback(() => {
// if (showConfirm)
// handleDeleteConversation(showConfirm.id, { onSuccess: handleCancelConfirm })
// }, [showConfirm, handleDeleteConversation, handleCancelConfirm])
// const handleCancelRename = useCallback(() => {
// setShowRename(null)
// }, [])
// const handleRename = useCallback((newName: string) => {
// if (showRename)
// handleRenameConversation(showRename.id, newName, { onSuccess: handleCancelRename })
// }, [showRename, handleRenameConversation, handleCancelRename])
// const [showSidebar, setShowSidebar] = useState(false)
// const [showChatSettings, setShowChatSettings] = useState(false)
// return (
// <>
// <div className='flex shrink-0 items-center gap-1 bg-mask-top2bottom-gray-50-to-transparent px-2 py-3'>
// <ActionButton size='l' className='shrink-0' onClick={() => setShowSidebar(true)}>
// <RiMenuLine className='h-[18px] w-[18px]' />
// </ActionButton>
// <div className='flex grow items-center justify-center'>
// {!currentConversationId && (
// <>
// <AppIcon
// className='mr-2'
// size='tiny'
// icon={appData?.site.icon}
// iconType={appData?.site.icon_type}
// imageUrl={appData?.site.icon_url}
// background={appData?.site.icon_background}
// />
// <div className='system-md-semibold truncate text-text-secondary'>
// {appData?.site.title}
// </div>
// </>
// )}
// {currentConversationId && (
// <Operation
// title={currentConversationItem?.name || ''}
// isPinned={!!isPin}
// togglePin={() => handleOperate(isPin ? 'unpin' : 'pin')}
// isShowDelete
// isShowRenameConversation
// onRenameConversation={() => handleOperate('rename')}
// onDelete={() => handleOperate('delete')}
// />
// )}
// </div>
// <MobileOperationDropdown
// handleResetChat={handleNewConversation}
// handleViewChatSettings={() => setShowChatSettings(true)}
// />
// </div>
// {showSidebar && (
// <div className='fixed inset-0 z-50 flex bg-background-overlay p-1'
// onClick={() => setShowSidebar(false)}
// >
// <div className='flex h-full w-[calc(100vw_-_40px)] rounded-xl bg-components-panel-bg shadow-lg backdrop-blur-sm' onClick={e => e.stopPropagation()}>
// <Sidebar />
// </div>
// </div>
// )}
// {showChatSettings && (
// <div className='fixed inset-0 z-50 flex justify-end bg-background-overlay p-1'
// onClick={() => setShowChatSettings(false)}
// >
// <div className='flex h-full w-[calc(100vw_-_40px)] flex-col rounded-xl bg-components-panel-bg shadow-lg backdrop-blur-sm' onClick={e => e.stopPropagation()}>
// <div className='flex items-center gap-3 rounded-t-2xl border-b border-divider-subtle px-4 py-3'>
// <Message3Fill className='h-6 w-6 shrink-0' />
// <div className='system-xl-semibold grow text-text-secondary'>{t('share.chat.chatSettingsTitle')}</div>
// </div>
// <div className='p-4'>
// <InputsFormContent />
// </div>
// </div>
// </div>
// )}
// {!!showConfirm && (
// <Confirm
// title={t('share.chat.deleteConversation.title')}
// content={t('share.chat.deleteConversation.content') || ''}
// isShow
// onCancel={handleCancelConfirm}
// onConfirm={handleDelete}
// />
// )}
// {showRename && (
// <RenameModal
// isShow
// onClose={handleCancelRename}
// saveLoading={conversationRenaming}
// name={showRename?.name || ''}
// onSave={handleRename}
// />
// )}
// </>
// )
// }
// export default HeaderInMobile
/*
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: yangming@didihu.com.cn yangming@didihu.com.cn
* @LastEditTime: 2025-05-02 16:11:41
* @FilePath: \glsk-ai-assistant\app\components\base\chat\chat-with-history\header\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { AVATAR_AI_URL } from "@/app/components/base/chat/constants";
type Props = {
avatar: string;
title: string;
};
const Header = ({ avatar, title }: Props) => {
return (
<div className="flex items-center justify-between h-12 px-[2vw]">
<div className=" flex items-center">
<img
src={AVATAR_AI_URL}
className="rounded-full size-8"
alt="answer icon"
/>
<span className="ml-2 font-bold">{title}</span>
</div>
<img src={avatar} className="rounded-full size-8" alt="answer icon" />
</div>
);
};
export default Header;
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiMoreFill,
} from '@remixicon/react'
import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '@/app/components/base/portal-to-follow-elem'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
type Props = {
handleResetChat: () => void
handleViewChatSettings: () => void
}
const MobileOperationDropdown = ({
handleResetChat,
handleViewChatSettings,
}: Props) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
offset={{
mainAxis: 4,
crossAxis: -4,
}}
>
<PortalToFollowElemTrigger
onClick={() => setOpen(v => !v)}
>
<ActionButton size='l' state={open ? ActionButtonState.Hover : ActionButtonState.Default}>
<RiMoreFill className='h-[18px] w-[18px]' />
</ActionButton>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className="z-40">
<div
className={'min-w-[160px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-sm'}
>
<div className='system-md-regular flex cursor-pointer items-center space-x-1 rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover' onClick={handleResetChat}>
<span className='grow'>{t('share.chat.resetChat')}</span>
</div>
<div className='system-md-regular flex cursor-pointer items-center space-x-1 rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover' onClick={handleViewChatSettings}>
<span className='grow'>{t('share.chat.viewChatSettings')}</span>
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default MobileOperationDropdown
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import type { Placement } from '@floating-ui/react'
import {
RiArrowDownSLine,
} from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '@/app/components/base/portal-to-follow-elem'
import cn from '@/utils/classnames'
type Props = {
title: string
isPinned: boolean
isShowRenameConversation?: boolean
onRenameConversation?: () => void
isShowDelete: boolean
togglePin: () => void
onDelete: () => void
placement?: Placement
}
const Operation: FC<Props> = ({
title,
isPinned,
togglePin,
isShowRenameConversation,
onRenameConversation,
isShowDelete,
onDelete,
placement = 'bottom-start',
}) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement={placement}
offset={4}
>
<PortalToFollowElemTrigger
onClick={() => setOpen(v => !v)}
>
<div className={cn('flex cursor-pointer items-center rounded-lg p-1.5 pl-2 text-text-secondary hover:bg-state-base-hover', open && 'bg-state-base-hover')}>
<div className='system-md-semibold'>{title}</div>
<RiArrowDownSLine className='h-4 w-4 ' />
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className="z-50">
<div
className={'min-w-[120px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-sm'}
>
<div className={cn('system-md-regular flex cursor-pointer items-center space-x-1 rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover')} onClick={togglePin}>
<span className='grow'>{isPinned ? t('explore.sidebar.action.unpin') : t('explore.sidebar.action.pin')}</span>
</div>
{isShowRenameConversation && (
<div className={cn('system-md-regular flex cursor-pointer items-center space-x-1 rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover')} onClick={onRenameConversation}>
<span className='grow'>{t('explore.sidebar.action.rename')}</span>
</div>
)}
{isShowDelete && (
<div className={cn('system-md-regular group flex cursor-pointer items-center space-x-1 rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-destructive-hover hover:text-text-destructive')} onClick={onDelete} >
<span className='grow'>{t('explore.sidebar.action.delete')}</span>
</div>
)}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(Operation)
export { useChatWithHistory } from './useChatWithHistory'
export { useUrlParams } from './useUrlParams'
export { useChat } from './useChat'
export { default as useSyncState } from './useSyncState'
export { usePostMessage } from './usePostMessage'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import useSWR from 'swr'
import type { ChatConfig, ChatItem, Feedback } from '../../types'
import { fetchAppInfo, fetchAppParams, updateFeedback } from '@/service/share'
import type { InstalledApp } from '@/models/app'
import { useToastContext } from '@/app/components/base/toast'
import { useAppFavicon } from '@/hooks/use-app-favicon'
import { noop } from 'lodash-es'
export const useChatWithHistory = (installedAppInfo?: InstalledApp, inputs: Record<string, any> = {}) => {
const isInstalledApp = false
const {
data: appInfo,
isLoading: appInfoLoading,
error: appInfoError,
} = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo, { revalidateOnFocus: false })
const appId = useMemo(() => appInfo?.app_id, [appInfo])
const [currentConversationId, setConversationId] = useState('')
const swrKey = useMemo(() => {
if (!appId) {
return null
} else return ['appParams', isInstalledApp, appId]
}, [isInstalledApp, appId])
const { data: appParams } = useSWR(
swrKey,
() => {
return fetchAppParams(isInstalledApp, appId)
},
{ revalidateOnFocus: false },
)
const [clearChatList, setClearChatList] = useState(false)
const appPrevChatTree = useMemo(() => [], [])
const { t } = useTranslation()
const newConversationInputsRef = useRef<Record<string, any>>({})
const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>(inputs)
const { notify } = useToastContext()
const currentChatInstanceRef = useRef<{ handleStop: () => void }>({
handleStop: noop,
})
const handleNewConversation = useCallback(
(inputs?: Record<string, any>,isSkipClear:boolean=false) => {
currentChatInstanceRef.current.handleStop()
setConversationId('')
if (inputs) {
newConversationInputsRef.current = inputs
setNewConversationInputs(inputs)
}
if(!isSkipClear){
setClearChatList(true)
}
},
[setClearChatList],
)
const handleNewConversationCompleted = useCallback(
(newConversationId: string) => {
setConversationId(newConversationId)
},
[setConversationId],
)
const handleFeedback = useCallback(
async (messageId: string, feedback: Feedback) => {
await updateFeedback(
{
url: `/messages/${messageId}/feedbacks`,
body: { rating: feedback.rating },
},
isInstalledApp,
appId,
)
notify({ type: 'success', message: t('common.api.success') })
},
[appId, t, notify],
)
return {
isInstalledApp,
appInfoLoading,
appInfoError,
appId,
currentConversationId,
appParams: appParams || ({} as ChatConfig),
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
handleNewConversationCompleted,
handleFeedback,
currentChatInstanceRef,
clearChatList,
setClearChatList,
// isResponding,
// setIsResponding,
}
}
declare const uni:
| {
postMessage: (options: { data: IPostMessage }) => void
[key: string]: any
}
| undefined
const uniPostMessage = (() => {
if (typeof uni !== 'undefined' && uni?.postMessage) {
return uni.postMessage.bind(uni)
}
return () => {}
})()
export interface IPostMessage {
isResponding?: boolean
isRecording?: boolean
messageType?: string
sceneIndex?: number
}
export const usePostMessage = () => {
const postMessage = (message: IPostMessage) => {
uniPostMessage({
data: {
...message,
},
})
}
return postMessage
}
import React from 'react';
type Getter<T> = () => T;
type Setter<T> = (pre: T) => T;
export default function useSyncState<T>(defaultValue: T | Getter<T>) {
const [, forceUpdate] = React.useState(0);
const stateRef = React.useRef<T>(
typeof defaultValue === 'function' ? (defaultValue as Getter<T>)() : defaultValue,
);
const setState = React.useCallback((action: React.SetStateAction<T>) => {
stateRef.current =
typeof action === 'function' ? (action as Setter<T>)(stateRef.current) : action;
forceUpdate((prev) => prev + 1);
}, []);
const getState: Getter<T> = React.useCallback(() => stateRef.current, []);
return [stateRef.current, setState, getState] as const;
}
// hooks/useUrlParams.ts
// import { AVATAR_USER_URL, AVATAR_AI_URL, MAIN_TITLE } from '@/app/components/base/chat/constants'
import { PracticeStatus } from '../../types'
import { useSearchParams } from 'next/navigation'
import { useEffect, useRef } from 'react'
import { useStore } from '@/app/components/app/store'
/**
* 自定义 Hook,用于获取 URL 查询参数
* 保证只在组件首次挂载时执行一次
*/
export type Inputs = {
domain?: string
no_header?: string // 是否显示头部
avatar?: string // 头像
business_type?: string // 业务类型
brand?: string // 品牌
one_id?: string // 唯一标识
queryType?: string //问题类型
position?: string // 岗位
platformType?: string // 平台类型
presuppositionProblem?: string // 平台类型
practice_status?: PracticeStatus // 练习状态
type?: string // 场景类型
customer_original?: string // 自定义开场白
customer_name?: string // 客户名称
scenario_summary?: string // 场景摘要
scenario_summary_index?: number // 场景摘要索引
scenario_summary_length?: number // 场景摘要长度
}
type ParamsExtenal = {
inputs: Record<string, any>
presuppositionProblem?: string
customer_original?: string
customer_name?: string
scenario_summary?: string // 场景摘要
scenario_summary_index?: number // 场景摘要索引
scenario_summary_length?: number // 场景摘要长度
}
export const useUrlParams = (): ParamsExtenal => {
const searchParams = useSearchParams()
const setScenarioSummaryIndex = useStore(state => state.setScenarioSummaryIndex)
const setScenarioSummaryLength = useStore(state => state.setScenarioSummaryLength)
const setCustomerOriginal = useStore(state => state.setCustomerOriginal)
const setScenarioSummary = useStore(state => state.setScenarioSummary)
const setScenarioType = useStore(state => state.setScenarioType)
const allParams: Inputs = Object.fromEntries(searchParams.entries())
const { practice_status, presuppositionProblem, domain, avatar, no_header,
customer_original, customer_name, scenario_summary, scenario_summary_index, scenario_summary_length, type, ...inputs } = allParams
// 将场景摘要索引、长度、自定义开场白、场景摘要和场景类型存储到全局状态
useEffect(() => {
if (scenario_summary_index !== undefined) {
setScenarioSummaryIndex(Number(scenario_summary_index))
}
if (scenario_summary_length !== undefined) {
setScenarioSummaryLength(Number(scenario_summary_length))
}
if (customer_original !== undefined) {
setCustomerOriginal(customer_original)
}
if (scenario_summary !== undefined) {
setScenarioSummary(scenario_summary)
}
if (type !== undefined) {
setScenarioType(type)
}
// setTimeout(() => {
// setScenarioType('scenario_building')
// setScenarioSummary('客户询问延保的价值。客户类型:Type B 理性数据型。考核目标:能否通过场景塑造和价格锚点激发客户对自费维修风险的焦虑感。')
// setCustomerOriginal('这个延保到底有什么用?你说说看。')
// setScenarioSummaryIndex(2)
// console.log('场景2已设置')
// }, 10e3)
// setTimeout(() => {
// setScenarioType('compliance_closing')
// setScenarioSummary('客户表示"再考虑考虑"准备离开。客户类型:Type C 犹豫拖延型。考核目标:能否进行合规有效的挽留,并完成加微信留资。')
// setCustomerOriginal('我再考虑考虑吧,今天先不买了。')
// setScenarioSummaryIndex(3)
// console.log('场景3已设置')
// }, 20e3)
}, [scenario_summary_index, scenario_summary_length, customer_original, scenario_summary, type])
// const isShowPracticeButton =
// practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
// 将 customer_original 添加到 inputs 对象中,使用类型断言确保类型安全
// const inputsWithCustomerOriginal = { ..., customer_original, scenario_summary }
return {
inputs: inputs,
presuppositionProblem,
customer_original,
customer_name,
scenario_summary,
scenario_summary_index,
scenario_summary_length,
// isShowPracticeButton,
}
}
\ No newline at end of file \ No newline at end of file
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-04-16 18:17:38
* @LastEditors: limin
* @LastEditTime: 2025-07-26 14:48:20
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\index.tsx
*/
import type { FC } from 'react'
import { memo, useEffect, useState } from 'react'
import ChatWrapper from './chat-wrapper'
import Loading from '@/app/components/base/loading'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { checkOrSetAccessToken } from '@/app/components/share/utils'
import AppUnavailable from '@/app/components/base/app-unavailable'
import cn from '@/utils/classnames'
import React from 'react'
import { useUrlParams } from './hooks'
type ChatWithHistoryProps = {
className?: string
}
const ChatWithHistory: FC<ChatWithHistoryProps> = React.memo(() => {
const isMobile = useBreakpoints() === MediaType.mobile
const { presuppositionProblem, inputs } = useUrlParams()
return (
<div className={cn('flex h-full', isMobile && 'flex-col')}>
<div className={cn('relative grow', isMobile && 'h-[calc(100%_-_56px)] p-0')}>
<div className={cn('flex h-full flex-col overflow-hidden border-components-panel-border-subtle ')}>
<ChatWrapper
// presuppositionQuestion={presuppositionProblem}
// isShowPracticeButton={isShowPracticeButton}
inputs={inputs}
/>
</div>
</div>
</div>
)
// }
})
export type ChatWithHistoryWrapProps = {
installedAppInfo?: any //InstalledApp
className?: string
}
type LoadingType = 'loading' | 'success' | 'error'
const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
const [status, setStatus] = useState<LoadingType>('loading')
const [isLoaded, setIsLoaded] = useState(false)
useEffect(() => {
checkOrSetAccessToken()
.then(() => setStatus('success'))
.catch(() => setStatus('error'))
}, [])
useEffect(() => {
if (status === 'success' && !isLoaded) {
setIsLoaded(true)
}
}, [status, isLoaded])
return (
<>
{status === 'loading' && <Loading type="app" />}
{status === 'error' && <AppUnavailable />}
{isLoaded && <ChatWithHistory className={className} />}
</>
)
}
export default memo(ChatWithHistoryWrapWithCheckToken)
import React, { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useChatWithHistoryContext } from '../context'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import { PortalSelect } from '@/app/components/base/select'
import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
import { InputVarType } from '@/app/components/workflow/types'
type Props = {
showTip?: boolean
}
const InputsFormContent = ({ showTip }: Props) => {
const { t } = useTranslation()
const {
appParams,
inputsForms,
currentConversationId,
currentConversationInputs,
setCurrentConversationInputs,
newConversationInputs,
newConversationInputsRef,
handleNewConversationInputsChange,
} = useChatWithHistoryContext()
const inputsFormValue = currentConversationId ? currentConversationInputs : newConversationInputs
const handleFormChange = useCallback((variable: string, value: any) => {
setCurrentConversationInputs({
...currentConversationInputs,
[variable]: value,
})
handleNewConversationInputsChange({
...newConversationInputsRef.current,
[variable]: value,
})
}, [newConversationInputsRef, handleNewConversationInputsChange, currentConversationInputs, setCurrentConversationInputs])
return (
<div className='space-y-4'>
{inputsForms.map(form => (
<div key={form.variable} className='space-y-1'>
<div className='flex h-6 items-center gap-1'>
<div className='system-md-semibold text-text-secondary'>{form.label}</div>
{!form.required && (
<div className='system-xs-regular text-text-tertiary'>{t('appDebug.variableTable.optional')}</div>
)}
</div>
{form.type === InputVarType.textInput && (
<Input
value={inputsFormValue?.[form.variable] || ''}
onChange={e => handleFormChange(form.variable, e.target.value)}
placeholder={form.label}
/>
)}
{form.type === InputVarType.number && (
<Input
type='number'
value={inputsFormValue?.[form.variable] || ''}
onChange={e => handleFormChange(form.variable, e.target.value)}
placeholder={form.label}
/>
)}
{form.type === InputVarType.paragraph && (
<Textarea
value={inputsFormValue?.[form.variable] || ''}
onChange={e => handleFormChange(form.variable, e.target.value)}
placeholder={form.label}
/>
)}
{form.type === InputVarType.select && (
<PortalSelect
popupClassName='w-[200px]'
value={inputsFormValue?.[form.variable]}
items={form.options.map((option: string) => ({ value: option, name: option }))}
onSelect={item => handleFormChange(form.variable, item.value as string)}
placeholder={form.label}
/>
)}
{form.type === InputVarType.singleFile && (
<FileUploaderInAttachmentWrapper
value={inputsFormValue?.[form.variable] ? [inputsFormValue?.[form.variable]] : []}
onChange={files => handleFormChange(form.variable, files[0])}
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
allowed_file_upload_methods: form.allowed_file_upload_methods,
number_limits: 1,
fileUploadConfig: (appParams as any).system_parameters,
}}
/>
)}
{form.type === InputVarType.multiFiles && (
<FileUploaderInAttachmentWrapper
value={inputsFormValue?.[form.variable] || []}
onChange={files => handleFormChange(form.variable, files)}
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
allowed_file_upload_methods: form.allowed_file_upload_methods,
number_limits: form.max_length,
fileUploadConfig: (appParams as any).system_parameters,
}}
/>
)}
</div>
))}
{showTip && (
<div className='system-xs-regular text-text-tertiary'>{t('share.chat.chatFormTip')}</div>
)}
</div>
)
}
export default InputsFormContent
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!